xref: /dragonfly/sys/bus/firewire/firewire.c (revision f02303f9)
1 /*
2  * Copyright (c) 2003 Hidetoshi Shimokawa
3  * Copyright (c) 1998-2002 Katsushi Kobayashi and Hidetoshi Shimokawa
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. All advertising materials mentioning features or use of this software
15  *    must display the acknowledgement as bellow:
16  *
17  *    This product includes software developed by K. Kobayashi and H. Shimokawa
18  *
19  * 4. The name of the author may not be used to endorse or promote products
20  *    derived from this software without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
23  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
24  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
25  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
26  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
27  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
28  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
30  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGE.
33  *
34  * $FreeBSD: src/sys/dev/firewire/firewire.c,v 1.68 2004/01/08 14:58:09 simokawa Exp $
35  * $DragonFly: src/sys/bus/firewire/firewire.c,v 1.18 2006/12/22 23:12:16 swildner Exp $
36  *
37  */
38 
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/types.h>
42 
43 #include <sys/kernel.h>
44 #include <sys/malloc.h>
45 #include <sys/conf.h>
46 #include <sys/bus.h>		/* used by smbus and newbus */
47 #include <sys/sysctl.h>
48 #include <sys/thread2.h>
49 
50 #if defined(__DragonFly__) || __FreeBSD_version < 500000
51 #include <machine/clock.h>	/* for DELAY() */
52 #endif
53 
54 #ifdef __DragonFly__
55 #include "firewire.h"
56 #include "firewirereg.h"
57 #include "fwmem.h"
58 #include "iec13213.h"
59 #include "iec68113.h"
60 #else
61 #include <dev/firewire/firewire.h>
62 #include <dev/firewire/firewirereg.h>
63 #include <dev/firewire/fwmem.h>
64 #include <dev/firewire/iec13213.h>
65 #include <dev/firewire/iec68113.h>
66 #endif
67 
68 struct crom_src_buf {
69 	struct crom_src	src;
70 	struct crom_chunk root;
71 	struct crom_chunk vendor;
72 	struct crom_chunk hw;
73 };
74 
75 int firewire_debug=0, try_bmr=1, hold_count=3;
76 SYSCTL_INT(_debug, OID_AUTO, firewire_debug, CTLFLAG_RW, &firewire_debug, 0,
77 	"FireWire driver debug flag");
78 SYSCTL_NODE(_hw, OID_AUTO, firewire, CTLFLAG_RD, 0, "FireWire Subsystem");
79 SYSCTL_INT(_hw_firewire, OID_AUTO, try_bmr, CTLFLAG_RW, &try_bmr, 0,
80 	"Try to be a bus manager");
81 SYSCTL_INT(_hw_firewire, OID_AUTO, hold_count, CTLFLAG_RW, &hold_count, 0,
82 	"Number of count of bus resets for removing lost device information");
83 
84 MALLOC_DEFINE(M_FW, "firewire", "FireWire");
85 MALLOC_DEFINE(M_FWXFER, "fw_xfer", "XFER/FireWire");
86 
87 #define FW_MAXASYRTY 4
88 
89 devclass_t firewire_devclass;
90 
91 static int firewire_probe	(device_t);
92 static int firewire_attach      (device_t);
93 static int firewire_detach      (device_t);
94 static int firewire_resume      (device_t);
95 #if 0
96 static int firewire_shutdown    (device_t);
97 #endif
98 static device_t firewire_add_child (device_t, device_t, int, const char *, int);
99 static void fw_try_bmr (void *);
100 static void fw_try_bmr_callback (struct fw_xfer *);
101 static void fw_asystart (struct fw_xfer *);
102 static int fw_get_tlabel (struct firewire_comm *, struct fw_xfer *);
103 static void fw_bus_probe (struct firewire_comm *);
104 static void fw_bus_explore (struct firewire_comm *);
105 static void fw_bus_explore_callback (struct fw_xfer *);
106 static void fw_attach_dev (struct firewire_comm *);
107 #ifdef FW_VMACCESS
108 static void fw_vmaccess (struct fw_xfer *);
109 #endif
110 struct fw_xfer *asyreqq (struct firewire_comm *, u_int8_t, u_int8_t, u_int8_t,
111 	u_int32_t, u_int32_t, void (*)(struct fw_xfer *));
112 static int fw_bmr (struct firewire_comm *);
113 
114 /*
115  * note: bus_generic_identify() will automatically install a "firewire"
116  * device under any attached fwohci device.
117  */
118 static device_method_t firewire_methods[] = {
119 	/* Device interface */
120 	DEVMETHOD(device_identify,	bus_generic_identify),
121 	DEVMETHOD(device_probe,		firewire_probe),
122 	DEVMETHOD(device_attach,	firewire_attach),
123 	DEVMETHOD(device_detach,	firewire_detach),
124 	DEVMETHOD(device_suspend,	bus_generic_suspend),
125 	DEVMETHOD(device_resume,	firewire_resume),
126 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
127 
128 	/* Bus interface */
129 	DEVMETHOD(bus_add_child,	firewire_add_child),
130 	DEVMETHOD(bus_print_child,	bus_generic_print_child),
131 
132 	{ 0, 0 }
133 };
134 char *linkspeed[] = {
135 	"S100", "S200", "S400", "S800",
136 	"S1600", "S3200", "undef", "undef"
137 };
138 
139 static char *tcode_str[] = {
140 	"WREQQ", "WREQB", "WRES",   "undef",
141 	"RREQQ", "RREQB", "RRESQ",  "RRESB",
142 	"CYCS",  "LREQ",  "STREAM", "LRES",
143 	"undef", "undef", "PHY",    "undef"
144 };
145 
146 /* IEEE-1394a Table C-2 Gap count as a function of hops*/
147 #define MAX_GAPHOP 15
148 u_int gap_cnt[] = { 5,  5,  7,  8, 10, 13, 16, 18,
149 		   21, 24, 26, 29, 32, 35, 37, 40};
150 
151 static driver_t firewire_driver = {
152 	"firewire",
153 	firewire_methods,
154 	sizeof(struct firewire_softc),
155 };
156 
157 /*
158  * Lookup fwdev by node id.
159  */
160 struct fw_device *
161 fw_noderesolve_nodeid(struct firewire_comm *fc, int dst)
162 {
163 	struct fw_device *fwdev;
164 
165 	crit_enter();
166 	STAILQ_FOREACH(fwdev, &fc->devices, link)
167 		if (fwdev->dst == dst && fwdev->status != FWDEVINVAL)
168 			break;
169 	crit_exit();
170 
171 	return fwdev;
172 }
173 
174 /*
175  * Lookup fwdev by EUI64.
176  */
177 struct fw_device *
178 fw_noderesolve_eui64(struct firewire_comm *fc, struct fw_eui64 *eui)
179 {
180 	struct fw_device *fwdev;
181 
182 	crit_enter();
183 	STAILQ_FOREACH(fwdev, &fc->devices, link)
184 		if (FW_EUI64_EQUAL(fwdev->eui, *eui))
185 			break;
186 	crit_exit();
187 
188 	if(fwdev == NULL) return NULL;
189 	if(fwdev->status == FWDEVINVAL) return NULL;
190 	return fwdev;
191 }
192 
193 /*
194  * Async. request procedure for userland application.
195  */
196 int
197 fw_asyreq(struct firewire_comm *fc, int sub, struct fw_xfer *xfer)
198 {
199 	int err = 0;
200 	struct fw_xferq *xferq;
201 	int tl = 0, len;
202 	struct fw_pkt *fp;
203 	int tcode;
204 	struct tcode_info *info;
205 
206 	if(xfer == NULL) return EINVAL;
207 	if(xfer->act.hand == NULL){
208 		kprintf("act.hand == NULL\n");
209 		return EINVAL;
210 	}
211 	fp = &xfer->send.hdr;
212 
213 	tcode = fp->mode.common.tcode & 0xf;
214 	info = &fc->tcode[tcode];
215 	if (info->flag == 0) {
216 		kprintf("invalid tcode=%x\n", tcode);
217 		return EINVAL;
218 	}
219 	if (info->flag & FWTI_REQ)
220 		xferq = fc->atq;
221 	else
222 		xferq = fc->ats;
223 	len = info->hdr_len;
224 	if (xfer->send.pay_len > MAXREC(fc->maxrec)) {
225 		kprintf("send.pay_len > maxrec\n");
226 		return EINVAL;
227 	}
228 	if (info->flag & FWTI_BLOCK_STR)
229 		len = fp->mode.stream.len;
230 	else if (info->flag & FWTI_BLOCK_ASY)
231 		len = fp->mode.rresb.len;
232 	else
233 		len = 0;
234 	if (len != xfer->send.pay_len){
235 		kprintf("len(%d) != send.pay_len(%d) %s(%x)\n",
236 		    len, xfer->send.pay_len, tcode_str[tcode], tcode);
237 		return EINVAL;
238 	}
239 
240 	if(xferq->start == NULL){
241 		kprintf("xferq->start == NULL\n");
242 		return EINVAL;
243 	}
244 	if(!(xferq->queued < xferq->maxq)){
245 		device_printf(fc->bdev, "Discard a packet (queued=%d)\n",
246 			xferq->queued);
247 		return EINVAL;
248 	}
249 
250 	microtime(&xfer->tv);
251 	if (info->flag & FWTI_TLABEL) {
252 		if((tl = fw_get_tlabel(fc, xfer)) == -1 )
253 			return EIO;
254 		fp->mode.hdr.tlrt = tl << 2;
255 	}
256 
257 	xfer->tl = tl;
258 	xfer->resp = 0;
259 	xfer->fc = fc;
260 	xfer->q = xferq;
261 	xfer->retry_req = fw_asybusy;
262 
263 	fw_asystart(xfer);
264 	return err;
265 }
266 /*
267  * Wakeup blocked process.
268  */
269 void
270 fw_asy_callback(struct fw_xfer *xfer){
271 	wakeup(xfer);
272 	return;
273 }
274 /*
275  * Postpone to later retry.
276  */
277 void
278 fw_asybusy(struct fw_xfer *xfer)
279 {
280 	kprintf("fw_asybusy\n");
281 /*
282 	xfer->ch =  timeout((timeout_t *)fw_asystart, (void *)xfer, 20000);
283 */
284 #if 0
285 	DELAY(20000);
286 #endif
287 	fw_asystart(xfer);
288 	return;
289 }
290 
291 /*
292  * Async. request with given xfer structure.
293  */
294 static void
295 fw_asystart(struct fw_xfer *xfer)
296 {
297 	struct firewire_comm *fc = xfer->fc;
298 
299 	if(xfer->retry++ >= fc->max_asyretry){
300 		device_printf(fc->bdev, "max_asyretry exceeded\n");
301 		xfer->resp = EBUSY;
302 		xfer->state = FWXF_BUSY;
303 		xfer->act.hand(xfer);
304 		return;
305 	}
306 #if 0 /* XXX allow bus explore packets only after bus rest */
307 	if (fc->status < FWBUSEXPLORE) {
308 		xfer->resp = EAGAIN;
309 		xfer->state = FWXF_BUSY;
310 		if (xfer->act.hand != NULL)
311 			xfer->act.hand(xfer);
312 		return;
313 	}
314 #endif
315 	crit_enter();
316 	xfer->state = FWXF_INQ;
317 	STAILQ_INSERT_TAIL(&xfer->q->q, xfer, link);
318 	xfer->q->queued ++;
319 	crit_exit();
320 	/* XXX just queue for mbuf */
321 	if (xfer->mbuf == NULL)
322 		xfer->q->start(fc);
323 	return;
324 }
325 
326 static int
327 firewire_probe(device_t dev)
328 {
329 	device_set_desc(dev, "IEEE1394(FireWire) bus");
330 	return (0);
331 }
332 
333 static void
334 firewire_xfer_timeout(struct firewire_comm *fc)
335 {
336 	struct fw_xfer *xfer;
337 	struct tlabel *tl;
338 	struct timeval tv;
339 	struct timeval split_timeout;
340 	int i;
341 
342 	split_timeout.tv_sec = 0;
343 	split_timeout.tv_usec = 200 * 1000;	 /* 200 msec */
344 
345 	microtime(&tv);
346 	timevalsub(&tv, &split_timeout);
347 
348 	crit_enter();
349 	for (i = 0; i < 0x40; i ++) {
350 		while ((tl = STAILQ_FIRST(&fc->tlabels[i])) != NULL) {
351 			xfer = tl->xfer;
352 			if (timevalcmp(&xfer->tv, &tv, >))
353 				/* the rests are newer than this */
354 				break;
355 			if (xfer->state == FWXF_START)
356 				/* not sent yet */
357 				break;
358 			device_printf(fc->bdev,
359 				"split transaction timeout dst=0x%x tl=0x%x state=%d\n",
360 				xfer->send.hdr.mode.hdr.dst, i, xfer->state);
361 			xfer->resp = ETIMEDOUT;
362 			STAILQ_REMOVE_HEAD(&fc->tlabels[i], link);
363 			fw_xfer_done(xfer);
364 		}
365 	}
366 	crit_exit();
367 }
368 
369 #define WATCHDOC_HZ 10
370 static void
371 firewire_watchdog(void *arg)
372 {
373 	struct firewire_comm *fc;
374 	static int watchdoc_clock = 0;
375 
376 	fc = (struct firewire_comm *)arg;
377 
378 	/*
379 	 * At boot stage, the device interrupt is disabled and
380 	 * We encounter a timeout easily. To avoid this,
381 	 * ignore clock interrupt for a while.
382 	 */
383 	if (watchdoc_clock > WATCHDOC_HZ * 15) {
384 		firewire_xfer_timeout(fc);
385 		fc->timeout(fc);
386 	} else
387 		watchdoc_clock ++;
388 
389 	callout_reset(&fc->timeout_callout, hz / WATCHDOC_HZ,
390 			(void *)firewire_watchdog, (void *)fc);
391 }
392 
393 /*
394  * The attach routine.
395  */
396 static int
397 firewire_attach(device_t dev)
398 {
399 	int unit;
400 	struct firewire_softc *sc = device_get_softc(dev);
401 	device_t pa = device_get_parent(dev);
402 	struct firewire_comm *fc;
403 
404 	fc = (struct firewire_comm *)device_get_softc(pa);
405 	sc->fc = fc;
406 	fc->status = FWBUSNOTREADY;
407 
408 	unit = device_get_unit(dev);
409 	if( fc->nisodma > FWMAXNDMA) fc->nisodma = FWMAXNDMA;
410 
411 	fwdev_makedev(sc);
412 
413 	CALLOUT_INIT(&sc->fc->timeout_callout);
414 	CALLOUT_INIT(&sc->fc->bmr_callout);
415 	CALLOUT_INIT(&sc->fc->retry_probe_callout);
416 	CALLOUT_INIT(&sc->fc->busprobe_callout);
417 
418 	callout_reset(&sc->fc->timeout_callout, hz,
419 			(void *)firewire_watchdog, (void *)sc->fc);
420 
421 	/* Locate our children */
422 	bus_generic_probe(dev);
423 
424 	/* launch attachement of the added children */
425 	bus_generic_attach(dev);
426 
427 	/* bus_reset */
428 	fw_busreset(fc);
429 	fc->ibr(fc);
430 
431 	return 0;
432 }
433 
434 /*
435  * Attach it as child.
436  */
437 static device_t
438 firewire_add_child(device_t bus, device_t parent, int order, const char *name, int unit)
439 {
440         device_t child;
441 	struct firewire_softc *sc;
442 
443 	sc = (struct firewire_softc *)device_get_softc(parent);
444 	child = device_add_child(parent, name, unit);
445 	if (child) {
446 		device_set_ivars(child, sc->fc);
447 		device_probe_and_attach(child);
448 	}
449 
450 	return child;
451 }
452 
453 static int
454 firewire_resume(device_t dev)
455 {
456 	struct firewire_softc *sc;
457 
458 	sc = (struct firewire_softc *)device_get_softc(dev);
459 	sc->fc->status = FWBUSNOTREADY;
460 
461 	bus_generic_resume(dev);
462 
463 	return(0);
464 }
465 
466 /*
467  * Dettach it.
468  */
469 static int
470 firewire_detach(device_t dev)
471 {
472 	struct firewire_softc *sc;
473 	struct csrdir *csrd, *next;
474 	struct fw_device *fwdev, *fwdev_next;
475 	int err;
476 
477 	sc = (struct firewire_softc *)device_get_softc(dev);
478 	if ((err = fwdev_destroydev(sc)) != 0)
479 		return err;
480 
481 	if ((err = bus_generic_detach(dev)) != 0)
482 		return err;
483 
484 	callout_stop(&sc->fc->timeout_callout);
485 	callout_stop(&sc->fc->bmr_callout);
486 	callout_stop(&sc->fc->retry_probe_callout);
487 	callout_stop(&sc->fc->busprobe_callout);
488 
489 	/* XXX xfree_free and untimeout on all xfers */
490 	for (fwdev = STAILQ_FIRST(&sc->fc->devices); fwdev != NULL;
491 							fwdev = fwdev_next) {
492 		fwdev_next = STAILQ_NEXT(fwdev, link);
493 		kfree(fwdev, M_FW);
494 	}
495 	for (csrd = SLIST_FIRST(&sc->fc->csrfree); csrd != NULL; csrd = next) {
496 		next = SLIST_NEXT(csrd, link);
497 		kfree(csrd, M_FW);
498 	}
499 	kfree(sc->fc->topology_map, M_FW);
500 	kfree(sc->fc->speed_map, M_FW);
501 	kfree(sc->fc->crom_src_buf, M_FW);
502 	return(0);
503 }
504 #if 0
505 static int
506 firewire_shutdown( device_t dev )
507 {
508 	return 0;
509 }
510 #endif
511 
512 
513 static void
514 fw_xferq_drain(struct fw_xferq *xferq)
515 {
516 	struct fw_xfer *xfer;
517 
518 	while ((xfer = STAILQ_FIRST(&xferq->q)) != NULL) {
519 		STAILQ_REMOVE_HEAD(&xferq->q, link);
520 		xferq->queued --;
521 		xfer->resp = EAGAIN;
522 		fw_xfer_done(xfer);
523 	}
524 }
525 
526 void
527 fw_drain_txq(struct firewire_comm *fc)
528 {
529 	int i;
530 
531 	fw_xferq_drain(fc->atq);
532 	fw_xferq_drain(fc->ats);
533 	for(i = 0; i < fc->nisodma; i++)
534 		fw_xferq_drain(fc->it[i]);
535 }
536 
537 static void
538 fw_reset_csr(struct firewire_comm *fc)
539 {
540 	int i;
541 
542 	CSRARC(fc, STATE_CLEAR)
543 			= 1 << 23 | 0 << 17 | 1 << 16 | 1 << 15 | 1 << 14 ;
544 	CSRARC(fc, STATE_SET) = CSRARC(fc, STATE_CLEAR);
545 	CSRARC(fc, NODE_IDS) = 0x3f;
546 
547 	CSRARC(fc, TOPO_MAP + 8) = 0;
548 	fc->irm = -1;
549 
550 	fc->max_node = -1;
551 
552 	for(i = 2; i < 0x100/4 - 2 ; i++){
553 		CSRARC(fc, SPED_MAP + i * 4) = 0;
554 	}
555 	CSRARC(fc, STATE_CLEAR) = 1 << 23 | 0 << 17 | 1 << 16 | 1 << 15 | 1 << 14 ;
556 	CSRARC(fc, STATE_SET) = CSRARC(fc, STATE_CLEAR);
557 	CSRARC(fc, RESET_START) = 0;
558 	CSRARC(fc, SPLIT_TIMEOUT_HI) = 0;
559 	CSRARC(fc, SPLIT_TIMEOUT_LO) = 800 << 19;
560 	CSRARC(fc, CYCLE_TIME) = 0x0;
561 	CSRARC(fc, BUS_TIME) = 0x0;
562 	CSRARC(fc, BUS_MGR_ID) = 0x3f;
563 	CSRARC(fc, BANDWIDTH_AV) = 4915;
564 	CSRARC(fc, CHANNELS_AV_HI) = 0xffffffff;
565 	CSRARC(fc, CHANNELS_AV_LO) = 0xffffffff;
566 	CSRARC(fc, IP_CHANNELS) = (1 << 31);
567 
568 	CSRARC(fc, CONF_ROM) = 0x04 << 24;
569 	CSRARC(fc, CONF_ROM + 4) = 0x31333934; /* means strings 1394 */
570 	CSRARC(fc, CONF_ROM + 8) = 1 << 31 | 1 << 30 | 1 << 29 |
571 				1 << 28 | 0xff << 16 | 0x09 << 8;
572 	CSRARC(fc, CONF_ROM + 0xc) = 0;
573 
574 /* DV depend CSRs see blue book */
575 	CSRARC(fc, oPCR) &= ~DV_BROADCAST_ON;
576 	CSRARC(fc, iPCR) &= ~DV_BROADCAST_ON;
577 
578 	CSRARC(fc, STATE_CLEAR) &= ~(1 << 23 | 1 << 15 | 1 << 14 );
579 	CSRARC(fc, STATE_SET) = CSRARC(fc, STATE_CLEAR);
580 }
581 
582 static void
583 fw_init_crom(struct firewire_comm *fc)
584 {
585 	struct crom_src *src;
586 
587 	fc->crom_src_buf = (struct crom_src_buf *)
588 		kmalloc(sizeof(struct crom_src_buf), M_FW, M_WAITOK | M_ZERO);
589 	if (fc->crom_src_buf == NULL)
590 		return;
591 
592 	src = &fc->crom_src_buf->src;
593 	bzero(src, sizeof(struct crom_src));
594 
595 	/* BUS info sample */
596 	src->hdr.info_len = 4;
597 
598 	src->businfo.bus_name = CSR_BUS_NAME_IEEE1394;
599 
600 	src->businfo.irmc = 1;
601 	src->businfo.cmc = 1;
602 	src->businfo.isc = 1;
603 	src->businfo.bmc = 1;
604 	src->businfo.pmc = 0;
605 	src->businfo.cyc_clk_acc = 100;
606 	src->businfo.max_rec = fc->maxrec;
607 	src->businfo.max_rom = MAXROM_4;
608 	src->businfo.generation = 1;
609 	src->businfo.link_spd = fc->speed;
610 
611 	src->businfo.eui64.hi = fc->eui.hi;
612 	src->businfo.eui64.lo = fc->eui.lo;
613 
614 	STAILQ_INIT(&src->chunk_list);
615 
616 	fc->crom_src = src;
617 	fc->crom_root = &fc->crom_src_buf->root;
618 }
619 
620 static void
621 fw_reset_crom(struct firewire_comm *fc)
622 {
623 	struct crom_src_buf *buf;
624 	struct crom_src *src;
625 	struct crom_chunk *root;
626 
627 	if (fc->crom_src_buf == NULL)
628 		fw_init_crom(fc);
629 
630 	buf =  fc->crom_src_buf;
631 	src = fc->crom_src;
632 	root = fc->crom_root;
633 
634 	STAILQ_INIT(&src->chunk_list);
635 
636 	bzero(root, sizeof(struct crom_chunk));
637 	crom_add_chunk(src, NULL, root, 0);
638 	crom_add_entry(root, CSRKEY_NCAP, 0x0083c0); /* XXX */
639 	/* private company_id */
640 	crom_add_entry(root, CSRKEY_VENDOR, CSRVAL_VENDOR_PRIVATE);
641 #ifdef __DragonFly__
642 	crom_add_simple_text(src, root, &buf->vendor, "DragonFly Project");
643 	crom_add_entry(root, CSRKEY_HW, __DragonFly_cc_version);
644 #else
645 	crom_add_simple_text(src, root, &buf->vendor, "FreeBSD Project");
646 	crom_add_entry(root, CSRKEY_HW, __FreeBSD_version);
647 #endif
648 	crom_add_simple_text(src, root, &buf->hw, hostname);
649 }
650 
651 /*
652  * Called after bus reset.
653  */
654 void
655 fw_busreset(struct firewire_comm *fc)
656 {
657 	struct firewire_dev_comm *fdc;
658 	struct crom_src *src;
659 	device_t *devlistp;
660 	void *newrom;
661 	int i, devcnt;
662 
663 	switch(fc->status){
664 	case FWBUSMGRELECT:
665 		callout_stop(&fc->bmr_callout);
666 		break;
667 	default:
668 		break;
669 	}
670 	fc->status = FWBUSRESET;
671 	fw_reset_csr(fc);
672 	fw_reset_crom(fc);
673 
674 	if (device_get_children(fc->bdev, &devlistp, &devcnt) == 0) {
675 		for( i = 0 ; i < devcnt ; i++)
676 			if (device_get_state(devlistp[i]) >= DS_ATTACHED)  {
677 				fdc = device_get_softc(devlistp[i]);
678 				if (fdc->post_busreset != NULL)
679 					fdc->post_busreset(fdc);
680 			}
681 		kfree(devlistp, M_TEMP);
682 	}
683 
684 	newrom = kmalloc(CROMSIZE, M_FW, M_WAITOK | M_ZERO);
685 	src = &fc->crom_src_buf->src;
686 	crom_load(src, (u_int32_t *)newrom, CROMSIZE);
687 	if (bcmp(newrom, fc->config_rom, CROMSIZE) != 0) {
688 		/* bump generation and reload */
689 		src->businfo.generation ++;
690 		/* generation must be between 0x2 and 0xF */
691 		if (src->businfo.generation < 2)
692 			src->businfo.generation ++;
693 		crom_load(src, (u_int32_t *)newrom, CROMSIZE);
694 		bcopy(newrom, (void *)fc->config_rom, CROMSIZE);
695 	}
696 	kfree(newrom, M_FW);
697 }
698 
699 /* Call once after reboot */
700 void
701 fw_init(struct firewire_comm *fc)
702 {
703 	int i;
704 	struct csrdir *csrd;
705 #ifdef FW_VMACCESS
706 	struct fw_xfer *xfer;
707 	struct fw_bind *fwb;
708 #endif
709 
710 	fc->max_asyretry = FW_MAXASYRTY;
711 
712 	fc->arq->queued = 0;
713 	fc->ars->queued = 0;
714 	fc->atq->queued = 0;
715 	fc->ats->queued = 0;
716 
717 	fc->arq->buf = NULL;
718 	fc->ars->buf = NULL;
719 	fc->atq->buf = NULL;
720 	fc->ats->buf = NULL;
721 
722 	fc->arq->flag = 0;
723 	fc->ars->flag = 0;
724 	fc->atq->flag = 0;
725 	fc->ats->flag = 0;
726 
727 	STAILQ_INIT(&fc->atq->q);
728 	STAILQ_INIT(&fc->ats->q);
729 
730 	for( i = 0 ; i < fc->nisodma ; i ++ ){
731 		fc->it[i]->queued = 0;
732 		fc->ir[i]->queued = 0;
733 
734 		fc->it[i]->start = NULL;
735 		fc->ir[i]->start = NULL;
736 
737 		fc->it[i]->buf = NULL;
738 		fc->ir[i]->buf = NULL;
739 
740 		fc->it[i]->flag = FWXFERQ_STREAM;
741 		fc->ir[i]->flag = FWXFERQ_STREAM;
742 
743 		STAILQ_INIT(&fc->it[i]->q);
744 		STAILQ_INIT(&fc->ir[i]->q);
745 
746 		STAILQ_INIT(&fc->it[i]->binds);
747 		STAILQ_INIT(&fc->ir[i]->binds);
748 	}
749 
750 	fc->arq->maxq = FWMAXQUEUE;
751 	fc->ars->maxq = FWMAXQUEUE;
752 	fc->atq->maxq = FWMAXQUEUE;
753 	fc->ats->maxq = FWMAXQUEUE;
754 
755 	for( i = 0 ; i < fc->nisodma ; i++){
756 		fc->ir[i]->maxq = FWMAXQUEUE;
757 		fc->it[i]->maxq = FWMAXQUEUE;
758 	}
759 /* Initialize csr registers */
760 	fc->topology_map = kmalloc(sizeof(struct fw_topology_map),
761 				    M_FW, M_WAITOK | M_ZERO);
762 	fc->speed_map = kmalloc(sizeof(struct fw_speed_map),
763 				    M_FW, M_WAITOK | M_ZERO);
764 	CSRARC(fc, TOPO_MAP) = 0x3f1 << 16;
765 	CSRARC(fc, TOPO_MAP + 4) = 1;
766 	CSRARC(fc, SPED_MAP) = 0x3f1 << 16;
767 	CSRARC(fc, SPED_MAP + 4) = 1;
768 
769 	STAILQ_INIT(&fc->devices);
770 
771 /* Initialize csr ROM work space */
772 	SLIST_INIT(&fc->ongocsr);
773 	SLIST_INIT(&fc->csrfree);
774 	for( i = 0 ; i < FWMAXCSRDIR ; i++){
775 		csrd = kmalloc(sizeof(struct csrdir), M_FW, M_WAITOK);
776 		if(csrd == NULL) break;
777 		SLIST_INSERT_HEAD(&fc->csrfree, csrd, link);
778 	}
779 
780 /* Initialize Async handlers */
781 	STAILQ_INIT(&fc->binds);
782 	for( i = 0 ; i < 0x40 ; i++){
783 		STAILQ_INIT(&fc->tlabels[i]);
784 	}
785 
786 /* DV depend CSRs see blue book */
787 #if 0
788 	CSRARC(fc, oMPR) = 0x3fff0001; /* # output channel = 1 */
789 	CSRARC(fc, oPCR) = 0x8000007a;
790 	for(i = 4 ; i < 0x7c/4 ; i+=4){
791 		CSRARC(fc, i + oPCR) = 0x8000007a;
792 	}
793 
794 	CSRARC(fc, iMPR) = 0x00ff0001; /* # input channel = 1 */
795 	CSRARC(fc, iPCR) = 0x803f0000;
796 	for(i = 4 ; i < 0x7c/4 ; i+=4){
797 		CSRARC(fc, i + iPCR) = 0x0;
798 	}
799 #endif
800 
801 	fc->crom_src_buf = NULL;
802 
803 #ifdef FW_VMACCESS
804 	xfer = fw_xfer_alloc();
805 	if(xfer == NULL) return;
806 
807 	fwb = kmalloc(sizeof (struct fw_bind), M_FW, M_WAITOK);
808 	xfer->act.hand = fw_vmaccess;
809 	xfer->fc = fc;
810 	xfer->sc = NULL;
811 
812 	fwb->start_hi = 0x2;
813 	fwb->start_lo = 0;
814 	fwb->addrlen = 0xffffffff;
815 	fwb->xfer = xfer;
816 	fw_bindadd(fc, fwb);
817 #endif
818 }
819 
820 #define BIND_CMP(addr, fwb) (((addr) < (fwb)->start)?-1:\
821     ((fwb)->end < (addr))?1:0)
822 
823 /*
824  * To lookup binded process from IEEE1394 address.
825  */
826 struct fw_bind *
827 fw_bindlookup(struct firewire_comm *fc, u_int16_t dest_hi, u_int32_t dest_lo)
828 {
829 	u_int64_t addr;
830 	struct fw_bind *tfw;
831 
832 	addr = ((u_int64_t)dest_hi << 32) | dest_lo;
833 	STAILQ_FOREACH(tfw, &fc->binds, fclist)
834 		if (tfw->act_type != FWACT_NULL && BIND_CMP(addr, tfw) == 0)
835 			return(tfw);
836 	return(NULL);
837 }
838 
839 /*
840  * To bind IEEE1394 address block to process.
841  */
842 int
843 fw_bindadd(struct firewire_comm *fc, struct fw_bind *fwb)
844 {
845 	struct fw_bind *tfw, *prev = NULL;
846 
847 	if (fwb->start > fwb->end) {
848 		kprintf("%s: invalid range\n", __func__);
849 		return EINVAL;
850 	}
851 
852 	STAILQ_FOREACH(tfw, &fc->binds, fclist) {
853 		if (fwb->end < tfw->start)
854 			break;
855 		prev = tfw;
856 	}
857 	if (prev == NULL) {
858 		STAILQ_INSERT_HEAD(&fc->binds, fwb, fclist);
859 		goto out;
860 	}
861 	if (prev->end < fwb->start) {
862 		STAILQ_INSERT_AFTER(&fc->binds, prev, fwb, fclist);
863 		goto out;
864 	}
865 
866 	kprintf("%s: bind failed\n", __func__);
867 	return (EBUSY);
868 
869 out:
870 	if (fwb->act_type == FWACT_CH)
871 		STAILQ_INSERT_HEAD(&fc->ir[fwb->sub]->binds, fwb, chlist);
872 	return (0);
873 }
874 
875 /*
876  * To free IEEE1394 address block.
877  */
878 int
879 fw_bindremove(struct firewire_comm *fc, struct fw_bind *fwb)
880 {
881 #if 0
882 	struct fw_xfer *xfer, *next;
883 #endif
884 	struct fw_bind *tfw;
885 
886 	crit_enter();
887 	STAILQ_FOREACH(tfw, &fc->binds, fclist)
888 		if (tfw == fwb) {
889 			STAILQ_REMOVE(&fc->binds, fwb, fw_bind, fclist);
890 			goto found;
891 		}
892 
893 	kprintf("%s: no such bind\n", __func__);
894 	crit_exit();
895 	return (1);
896 found:
897 #if 0
898 	/* shall we do this? */
899 	for (xfer = STAILQ_FIRST(&fwb->xferlist); xfer != NULL; xfer = next) {
900 		next = STAILQ_NEXT(xfer, link);
901 		fw_xfer_free(xfer);
902 	}
903 	STAILQ_INIT(&fwb->xferlist);
904 #endif
905 
906 	crit_exit();
907 	return 0;
908 }
909 
910 /*
911  * To free transaction label.
912  */
913 static void
914 fw_tl_free(struct firewire_comm *fc, struct fw_xfer *xfer)
915 {
916 	struct tlabel *tl;
917 
918 	crit_enter();
919 	for( tl = STAILQ_FIRST(&fc->tlabels[xfer->tl]); tl != NULL;
920 		tl = STAILQ_NEXT(tl, link)){
921 		if(tl->xfer == xfer){
922 			STAILQ_REMOVE(&fc->tlabels[xfer->tl], tl, tlabel, link);
923 			kfree(tl, M_FW);
924 			break;
925 		}
926 	}
927 	crit_exit();
928 }
929 
930 /*
931  * To obtain XFER structure by transaction label.
932  */
933 static struct fw_xfer *
934 fw_tl2xfer(struct firewire_comm *fc, int node, int tlabel)
935 {
936 	struct fw_xfer *xfer;
937 	struct tlabel *tl;
938 
939 	crit_enter();
940 
941 	for( tl = STAILQ_FIRST(&fc->tlabels[tlabel]); tl != NULL;
942 		tl = STAILQ_NEXT(tl, link)){
943 		if(tl->xfer->send.hdr.mode.hdr.dst == node){
944 			xfer = tl->xfer;
945 			crit_exit();
946 			if (firewire_debug > 2)
947 				kprintf("fw_tl2xfer: found tl=%d\n", tlabel);
948 			return(xfer);
949 		}
950 	}
951 	if (firewire_debug > 1)
952 		kprintf("fw_tl2xfer: not found tl=%d\n", tlabel);
953 	crit_exit();
954 	return(NULL);
955 }
956 
957 /*
958  * To allocate IEEE1394 XFER structure.
959  */
960 struct fw_xfer *
961 fw_xfer_alloc(struct malloc_type *type)
962 {
963 	struct fw_xfer *xfer;
964 
965 	xfer = kmalloc(sizeof(struct fw_xfer), type, M_INTWAIT | M_ZERO);
966 	xfer->malloc = type;
967 
968 	return xfer;
969 }
970 
971 struct fw_xfer *
972 fw_xfer_alloc_buf(struct malloc_type *type, int send_len, int recv_len)
973 {
974 	struct fw_xfer *xfer;
975 
976 	xfer = fw_xfer_alloc(type);
977 	xfer->send.pay_len = send_len;
978 	xfer->recv.pay_len = recv_len;
979 	if (xfer == NULL)
980 		return(NULL);
981 	if (send_len > 0) {
982 		xfer->send.payload = kmalloc(send_len, type, M_INTWAIT | M_ZERO);
983 		if (xfer->send.payload == NULL) {
984 			fw_xfer_free(xfer);
985 			return(NULL);
986 		}
987 	}
988 	if (recv_len > 0) {
989 		xfer->recv.payload = kmalloc(recv_len, type, M_INTWAIT);
990 		if (xfer->recv.payload == NULL) {
991 			if (xfer->send.payload != NULL)
992 				kfree(xfer->send.payload, type);
993 			fw_xfer_free(xfer);
994 			return(NULL);
995 		}
996 	}
997 	return(xfer);
998 }
999 
1000 /*
1001  * IEEE1394 XFER post process.
1002  */
1003 void
1004 fw_xfer_done(struct fw_xfer *xfer)
1005 {
1006 	if (xfer->act.hand == NULL) {
1007 		kprintf("act.hand == NULL\n");
1008 		return;
1009 	}
1010 
1011 	if (xfer->fc == NULL)
1012 		panic("fw_xfer_done: why xfer->fc is NULL?");
1013 
1014 	xfer->act.hand(xfer);
1015 }
1016 
1017 void
1018 fw_xfer_unload(struct fw_xfer* xfer)
1019 {
1020 	if(xfer == NULL ) return;
1021 	if(xfer->state == FWXF_INQ){
1022 		kprintf("fw_xfer_free FWXF_INQ\n");
1023 		crit_enter();
1024 		STAILQ_REMOVE(&xfer->q->q, xfer, fw_xfer, link);
1025 		xfer->q->queued --;
1026 		crit_exit();
1027 	}
1028 	if (xfer->fc != NULL) {
1029 #if 1
1030 		if(xfer->state == FWXF_START)
1031 			/*
1032 			 * This could happen if:
1033 			 *  1. We call fwohci_arcv() before fwohci_txd().
1034 			 *  2. firewire_watch() is called.
1035 			 */
1036 			kprintf("fw_xfer_free FWXF_START\n");
1037 #endif
1038 		fw_tl_free(xfer->fc, xfer);
1039 	}
1040 	xfer->state = FWXF_INIT;
1041 	xfer->resp = 0;
1042 	xfer->retry = 0;
1043 }
1044 /*
1045  * To free IEEE1394 XFER structure.
1046  */
1047 void
1048 fw_xfer_free_buf( struct fw_xfer* xfer)
1049 {
1050 	if (xfer == NULL) {
1051 		kprintf("%s: xfer == NULL\n", __func__);
1052 		return;
1053 	}
1054 	fw_xfer_unload(xfer);
1055 	if(xfer->send.payload != NULL){
1056 		kfree(xfer->send.payload, xfer->malloc);
1057 	}
1058 	if(xfer->recv.payload != NULL){
1059 		kfree(xfer->recv.payload, xfer->malloc);
1060 	}
1061 	kfree(xfer, xfer->malloc);
1062 }
1063 
1064 void
1065 fw_xfer_free( struct fw_xfer* xfer)
1066 {
1067 	if (xfer == NULL) {
1068 		kprintf("%s: xfer == NULL\n", __func__);
1069 		return;
1070 	}
1071 	fw_xfer_unload(xfer);
1072 	kfree(xfer, xfer->malloc);
1073 }
1074 
1075 void
1076 fw_asy_callback_free(struct fw_xfer *xfer)
1077 {
1078 #if 0
1079 	kprintf("asyreq done state=%d resp=%d\n",
1080 				xfer->state, xfer->resp);
1081 #endif
1082 	fw_xfer_free(xfer);
1083 }
1084 
1085 /*
1086  * To configure PHY.
1087  */
1088 static void
1089 fw_phy_config(struct firewire_comm *fc, int root_node, int gap_count)
1090 {
1091 	struct fw_xfer *xfer;
1092 	struct fw_pkt *fp;
1093 
1094 	fc->status = FWBUSPHYCONF;
1095 
1096 	xfer = fw_xfer_alloc(M_FWXFER);
1097 	if (xfer == NULL)
1098 		return;
1099 	xfer->fc = fc;
1100 	xfer->retry_req = fw_asybusy;
1101 	xfer->act.hand = fw_asy_callback_free;
1102 
1103 	fp = &xfer->send.hdr;
1104 	fp->mode.ld[1] = 0;
1105 	if (root_node >= 0)
1106 		fp->mode.ld[1] |= (root_node & 0x3f) << 24 | 1 << 23;
1107 	if (gap_count >= 0)
1108 		fp->mode.ld[1] |= 1 << 22 | (gap_count & 0x3f) << 16;
1109 	fp->mode.ld[2] = ~fp->mode.ld[1];
1110 /* XXX Dangerous, how to pass PHY packet to device driver */
1111 	fp->mode.common.tcode |= FWTCODE_PHY;
1112 
1113 	if (firewire_debug)
1114 		kprintf("send phy_config root_node=%d gap_count=%d\n",
1115 						root_node, gap_count);
1116 	fw_asyreq(fc, -1, xfer);
1117 }
1118 
1119 #if 0
1120 /*
1121  * Dump self ID.
1122  */
1123 static void
1124 fw_print_sid(u_int32_t sid)
1125 {
1126 	union fw_self_id *s;
1127 	s = (union fw_self_id *) &sid;
1128 	kprintf("node:%d link:%d gap:%d spd:%d del:%d con:%d pwr:%d"
1129 		" p0:%d p1:%d p2:%d i:%d m:%d\n",
1130 		s->p0.phy_id, s->p0.link_active, s->p0.gap_count,
1131 		s->p0.phy_speed, s->p0.phy_delay, s->p0.contender,
1132 		s->p0.power_class, s->p0.port0, s->p0.port1,
1133 		s->p0.port2, s->p0.initiated_reset, s->p0.more_packets);
1134 }
1135 #endif
1136 
1137 /*
1138  * To receive self ID.
1139  */
1140 void
1141 fw_sidrcv(struct firewire_comm* fc, u_int32_t *sid, u_int len)
1142 {
1143 	u_int32_t *p;
1144 	union fw_self_id *self_id;
1145 	u_int i, j, node, c_port = 0, i_branch = 0;
1146 
1147 	fc->sid_cnt = len /(sizeof(u_int32_t) * 2);
1148 	fc->status = FWBUSINIT;
1149 	fc->max_node = fc->nodeid & 0x3f;
1150 	CSRARC(fc, NODE_IDS) = ((u_int32_t)fc->nodeid) << 16;
1151 	fc->status = FWBUSCYMELECT;
1152 	fc->topology_map->crc_len = 2;
1153 	fc->topology_map->generation ++;
1154 	fc->topology_map->self_id_count = 0;
1155 	fc->topology_map->node_count = 0;
1156 	fc->speed_map->generation ++;
1157 	fc->speed_map->crc_len = 1 + (64*64 + 3) / 4;
1158 	self_id = &fc->topology_map->self_id[0];
1159 	for(i = 0; i < fc->sid_cnt; i ++){
1160 		if (sid[1] != ~sid[0]) {
1161 			kprintf("fw_sidrcv: invalid self-id packet\n");
1162 			sid += 2;
1163 			continue;
1164 		}
1165 		*self_id = *((union fw_self_id *)sid);
1166 		fc->topology_map->crc_len++;
1167 		if(self_id->p0.sequel == 0){
1168 			fc->topology_map->node_count ++;
1169 			c_port = 0;
1170 #if 0
1171 			fw_print_sid(sid[0]);
1172 #endif
1173 			node = self_id->p0.phy_id;
1174 			if(fc->max_node < node){
1175 				fc->max_node = self_id->p0.phy_id;
1176 			}
1177 			/* XXX I'm not sure this is the right speed_map */
1178 			fc->speed_map->speed[node][node]
1179 					= self_id->p0.phy_speed;
1180 			for (j = 0; j < node; j ++) {
1181 				fc->speed_map->speed[j][node]
1182 					= fc->speed_map->speed[node][j]
1183 					= min(fc->speed_map->speed[j][j],
1184 							self_id->p0.phy_speed);
1185 			}
1186 			if ((fc->irm == -1 || self_id->p0.phy_id > fc->irm) &&
1187 			  (self_id->p0.link_active && self_id->p0.contender)) {
1188 				fc->irm = self_id->p0.phy_id;
1189 			}
1190 			if(self_id->p0.port0 >= 0x2){
1191 				c_port++;
1192 			}
1193 			if(self_id->p0.port1 >= 0x2){
1194 				c_port++;
1195 			}
1196 			if(self_id->p0.port2 >= 0x2){
1197 				c_port++;
1198 			}
1199 		}
1200 		if(c_port > 2){
1201 			i_branch += (c_port - 2);
1202 		}
1203 		sid += 2;
1204 		self_id++;
1205 		fc->topology_map->self_id_count ++;
1206 	}
1207 	device_printf(fc->bdev, "%d nodes", fc->max_node + 1);
1208 	/* CRC */
1209 	fc->topology_map->crc = fw_crc16(
1210 			(u_int32_t *)&fc->topology_map->generation,
1211 			fc->topology_map->crc_len * 4);
1212 	fc->speed_map->crc = fw_crc16(
1213 			(u_int32_t *)&fc->speed_map->generation,
1214 			fc->speed_map->crc_len * 4);
1215 	/* byteswap and copy to CSR */
1216 	p = (u_int32_t *)fc->topology_map;
1217 	for (i = 0; i <= fc->topology_map->crc_len; i++)
1218 		CSRARC(fc, TOPO_MAP + i * 4) = htonl(*p++);
1219 	p = (u_int32_t *)fc->speed_map;
1220 	CSRARC(fc, SPED_MAP) = htonl(*p++);
1221 	CSRARC(fc, SPED_MAP + 4) = htonl(*p++);
1222 	/* don't byte-swap u_int8_t array */
1223 	bcopy(p, &CSRARC(fc, SPED_MAP + 8), (fc->speed_map->crc_len - 1)*4);
1224 
1225 	fc->max_hop = fc->max_node - i_branch;
1226 	kprintf(", maxhop <= %d", fc->max_hop);
1227 
1228 	if(fc->irm == -1 ){
1229 		kprintf(", Not found IRM capable node");
1230 	}else{
1231 		kprintf(", cable IRM = %d", fc->irm);
1232 		if (fc->irm == fc->nodeid)
1233 			kprintf(" (me)");
1234 	}
1235 	kprintf("\n");
1236 
1237 	if (try_bmr && (fc->irm != -1) && (CSRARC(fc, BUS_MGR_ID) == 0x3f)) {
1238 		if (fc->irm == fc->nodeid) {
1239 			fc->status = FWBUSMGRDONE;
1240 			CSRARC(fc, BUS_MGR_ID) = fc->set_bmr(fc, fc->irm);
1241 			fw_bmr(fc);
1242 		} else {
1243 			fc->status = FWBUSMGRELECT;
1244 			callout_reset(&fc->bmr_callout, hz/8,
1245 				(void *)fw_try_bmr, (void *)fc);
1246 		}
1247 	} else
1248 		fc->status = FWBUSMGRDONE;
1249 
1250 	callout_reset(&fc->busprobe_callout, hz/4,
1251 			(void *)fw_bus_probe, (void *)fc);
1252 }
1253 
1254 /*
1255  * To probe devices on the IEEE1394 bus.
1256  */
1257 static void
1258 fw_bus_probe(struct firewire_comm *fc)
1259 {
1260 	struct fw_device *fwdev;
1261 
1262 	crit_enter();
1263 	fc->status = FWBUSEXPLORE;
1264 	fc->retry_count = 0;
1265 
1266 	/* Invalidate all devices, just after bus reset. */
1267 	STAILQ_FOREACH(fwdev, &fc->devices, link)
1268 		if (fwdev->status != FWDEVINVAL) {
1269 			fwdev->status = FWDEVINVAL;
1270 			fwdev->rcnt = 0;
1271 		}
1272 
1273 	fc->ongonode = 0;
1274 	fc->ongoaddr = CSRROMOFF;
1275 	fc->ongodev = NULL;
1276 	fc->ongoeui.hi = 0xffffffff; fc->ongoeui.lo = 0xffffffff;
1277 	fw_bus_explore(fc);
1278 	crit_exit();
1279 }
1280 
1281 /*
1282  * To collect device informations on the IEEE1394 bus.
1283  */
1284 static void
1285 fw_bus_explore(struct firewire_comm *fc )
1286 {
1287 	int err = 0;
1288 	struct fw_device *fwdev, *pfwdev, *tfwdev;
1289 	u_int32_t addr;
1290 	struct fw_xfer *xfer;
1291 	struct fw_pkt *fp;
1292 
1293 	if(fc->status != FWBUSEXPLORE)
1294 		return;
1295 
1296 loop:
1297 	if(fc->ongonode == fc->nodeid) fc->ongonode++;
1298 
1299 	if(fc->ongonode > fc->max_node) goto done;
1300 	if(fc->ongonode >= 0x3f) goto done;
1301 
1302 	/* check link */
1303 	/* XXX we need to check phy_id first */
1304 	if (!fc->topology_map->self_id[fc->ongonode].p0.link_active) {
1305 		if (firewire_debug)
1306 			kprintf("node%d: link down\n", fc->ongonode);
1307 		fc->ongonode++;
1308 		goto loop;
1309 	}
1310 
1311 	if(fc->ongoaddr <= CSRROMOFF &&
1312 		fc->ongoeui.hi == 0xffffffff &&
1313 		fc->ongoeui.lo == 0xffffffff ){
1314 		fc->ongoaddr = CSRROMOFF;
1315 		addr = 0xf0000000 | fc->ongoaddr;
1316 	}else if(fc->ongoeui.hi == 0xffffffff ){
1317 		fc->ongoaddr = CSRROMOFF + 0xc;
1318 		addr = 0xf0000000 | fc->ongoaddr;
1319 	}else if(fc->ongoeui.lo == 0xffffffff ){
1320 		fc->ongoaddr = CSRROMOFF + 0x10;
1321 		addr = 0xf0000000 | fc->ongoaddr;
1322 	}else if(fc->ongodev == NULL){
1323 		STAILQ_FOREACH(fwdev, &fc->devices, link)
1324 			if (FW_EUI64_EQUAL(fwdev->eui, fc->ongoeui))
1325 				break;
1326 		if(fwdev != NULL){
1327 			fwdev->dst = fc->ongonode;
1328 			fwdev->status = FWDEVINIT;
1329 			fc->ongodev = fwdev;
1330 			fc->ongoaddr = CSRROMOFF;
1331 			addr = 0xf0000000 | fc->ongoaddr;
1332 			goto dorequest;
1333 		}
1334 		fwdev = kmalloc(sizeof(struct fw_device), M_FW,
1335 				M_WAITOK | M_ZERO);
1336 		fwdev->fc = fc;
1337 		fwdev->rommax = 0;
1338 		fwdev->dst = fc->ongonode;
1339 		fwdev->eui.hi = fc->ongoeui.hi; fwdev->eui.lo = fc->ongoeui.lo;
1340 		fwdev->status = FWDEVINIT;
1341 		fwdev->speed = fc->speed_map->speed[fc->nodeid][fc->ongonode];
1342 
1343 		pfwdev = NULL;
1344 		STAILQ_FOREACH(tfwdev, &fc->devices, link) {
1345 			if (tfwdev->eui.hi > fwdev->eui.hi ||
1346 					(tfwdev->eui.hi == fwdev->eui.hi &&
1347 					tfwdev->eui.lo > fwdev->eui.lo))
1348 				break;
1349 			pfwdev = tfwdev;
1350 		}
1351 		if (pfwdev == NULL)
1352 			STAILQ_INSERT_HEAD(&fc->devices, fwdev, link);
1353 		else
1354 			STAILQ_INSERT_AFTER(&fc->devices, pfwdev, fwdev, link);
1355 
1356 		device_printf(fc->bdev, "New %s device ID:%08x%08x\n",
1357 			linkspeed[fwdev->speed],
1358 			fc->ongoeui.hi, fc->ongoeui.lo);
1359 
1360 		fc->ongodev = fwdev;
1361 		fc->ongoaddr = CSRROMOFF;
1362 		addr = 0xf0000000 | fc->ongoaddr;
1363 	}else{
1364 		addr = 0xf0000000 | fc->ongoaddr;
1365 	}
1366 dorequest:
1367 #if 0
1368 	xfer = asyreqq(fc, FWSPD_S100, 0, 0,
1369 		((FWLOCALBUS | fc->ongonode) << 16) | 0xffff , addr,
1370 		fw_bus_explore_callback);
1371 	if(xfer == NULL) goto done;
1372 #else
1373 	xfer = fw_xfer_alloc(M_FWXFER);
1374 	if(xfer == NULL){
1375 		goto done;
1376 	}
1377 	xfer->send.spd = 0;
1378 	fp = &xfer->send.hdr;
1379 	fp->mode.rreqq.dest_hi = 0xffff;
1380 	fp->mode.rreqq.tlrt = 0;
1381 	fp->mode.rreqq.tcode = FWTCODE_RREQQ;
1382 	fp->mode.rreqq.pri = 0;
1383 	fp->mode.rreqq.src = 0;
1384 	fp->mode.rreqq.dst = FWLOCALBUS | fc->ongonode;
1385 	fp->mode.rreqq.dest_lo = addr;
1386 	xfer->act.hand = fw_bus_explore_callback;
1387 
1388 	if (firewire_debug)
1389 		kprintf("node%d: explore addr=0x%x\n",
1390 				fc->ongonode, fc->ongoaddr);
1391 	err = fw_asyreq(fc, -1, xfer);
1392 	if(err){
1393 		fw_xfer_free( xfer);
1394 		return;
1395 	}
1396 #endif
1397 	return;
1398 done:
1399 	/* fw_attach_devs */
1400 	fc->status = FWBUSEXPDONE;
1401 	if (firewire_debug)
1402 		kprintf("bus_explore done\n");
1403 	fw_attach_dev(fc);
1404 	return;
1405 
1406 }
1407 
1408 /* Portable Async. request read quad */
1409 struct fw_xfer *
1410 asyreqq(struct firewire_comm *fc, u_int8_t spd, u_int8_t tl, u_int8_t rt,
1411 	u_int32_t addr_hi, u_int32_t addr_lo,
1412 	void (*hand) (struct fw_xfer*))
1413 {
1414 	struct fw_xfer *xfer;
1415 	struct fw_pkt *fp;
1416 	int err;
1417 
1418 	xfer = fw_xfer_alloc(M_FWXFER);
1419 	if (xfer == NULL)
1420 		return NULL;
1421 
1422 	xfer->send.spd = spd; /* XXX:min(spd, fc->spd) */
1423 	fp = &xfer->send.hdr;
1424 	fp->mode.rreqq.dest_hi = addr_hi & 0xffff;
1425 	if(tl & FWP_TL_VALID){
1426 		fp->mode.rreqq.tlrt = (tl & 0x3f) << 2;
1427 	}else{
1428 		fp->mode.rreqq.tlrt = 0;
1429 	}
1430 	fp->mode.rreqq.tlrt |= rt & 0x3;
1431 	fp->mode.rreqq.tcode = FWTCODE_RREQQ;
1432 	fp->mode.rreqq.pri = 0;
1433 	fp->mode.rreqq.src = 0;
1434 	fp->mode.rreqq.dst = addr_hi >> 16;
1435 	fp->mode.rreqq.dest_lo = addr_lo;
1436 	xfer->act.hand = hand;
1437 
1438 	err = fw_asyreq(fc, -1, xfer);
1439 	if(err){
1440 		fw_xfer_free( xfer);
1441 		return NULL;
1442 	}
1443 	return xfer;
1444 }
1445 
1446 /*
1447  * Callback for the IEEE1394 bus information collection.
1448  */
1449 static void
1450 fw_bus_explore_callback(struct fw_xfer *xfer)
1451 {
1452 	struct firewire_comm *fc;
1453 	struct fw_pkt *sfp,*rfp;
1454 	struct csrhdr *chdr;
1455 	struct csrdir *csrd;
1456 	struct csrreg *csrreg;
1457 	u_int32_t offset;
1458 
1459 
1460 	if(xfer == NULL) {
1461 		kprintf("xfer == NULL\n");
1462 		return;
1463 	}
1464 	fc = xfer->fc;
1465 
1466 	if (firewire_debug)
1467 		kprintf("node%d: callback addr=0x%x\n",
1468 			fc->ongonode, fc->ongoaddr);
1469 
1470 	if(xfer->resp != 0){
1471 		kprintf("node%d: resp=%d addr=0x%x\n",
1472 			fc->ongonode, xfer->resp, fc->ongoaddr);
1473 		goto errnode;
1474 	}
1475 
1476 	sfp = &xfer->send.hdr;
1477 	rfp = &xfer->recv.hdr;
1478 #if 0
1479 	{
1480 		u_int32_t *qld;
1481 		int i;
1482 		qld = (u_int32_t *)xfer->recv.buf;
1483 		kprintf("len:%d\n", xfer->recv.len);
1484 		for( i = 0 ; i <= xfer->recv.len && i < 32; i+= 4){
1485 			kprintf("0x%08x ", rfp->mode.ld[i/4]);
1486 			if((i % 16) == 15) kprintf("\n");
1487 		}
1488 		if((i % 16) != 15) kprintf("\n");
1489 	}
1490 #endif
1491 	if(fc->ongodev == NULL){
1492 		if(sfp->mode.rreqq.dest_lo == (0xf0000000 | CSRROMOFF)){
1493 			rfp->mode.rresq.data = ntohl(rfp->mode.rresq.data);
1494 			chdr = (struct csrhdr *)(&rfp->mode.rresq.data);
1495 /* If CSR is minimal confinguration, more investgation is not needed. */
1496 			if(chdr->info_len == 1){
1497 				if (firewire_debug)
1498 					kprintf("node%d: minimal config\n",
1499 								fc->ongonode);
1500 				goto nextnode;
1501 			}else{
1502 				fc->ongoaddr = CSRROMOFF + 0xc;
1503 			}
1504 		}else if(sfp->mode.rreqq.dest_lo == (0xf0000000 |(CSRROMOFF + 0xc))){
1505 			fc->ongoeui.hi = ntohl(rfp->mode.rresq.data);
1506 			fc->ongoaddr = CSRROMOFF + 0x10;
1507 		}else if(sfp->mode.rreqq.dest_lo == (0xf0000000 |(CSRROMOFF + 0x10))){
1508 			fc->ongoeui.lo = ntohl(rfp->mode.rresq.data);
1509 			if (fc->ongoeui.hi == 0 && fc->ongoeui.lo == 0) {
1510 				if (firewire_debug)
1511 					kprintf("node%d: eui64 is zero.\n",
1512 							fc->ongonode);
1513 				goto nextnode;
1514 			}
1515 			fc->ongoaddr = CSRROMOFF;
1516 		}
1517 	}else{
1518 		if (fc->ongoaddr == CSRROMOFF &&
1519 		    fc->ongodev->csrrom[0] == ntohl(rfp->mode.rresq.data)) {
1520 			fc->ongodev->status = FWDEVATTACHED;
1521 			goto nextnode;
1522 		}
1523 		fc->ongodev->csrrom[(fc->ongoaddr - CSRROMOFF)/4] = ntohl(rfp->mode.rresq.data);
1524 		if(fc->ongoaddr > fc->ongodev->rommax){
1525 			fc->ongodev->rommax = fc->ongoaddr;
1526 		}
1527 		csrd = SLIST_FIRST(&fc->ongocsr);
1528 		if((csrd = SLIST_FIRST(&fc->ongocsr)) == NULL){
1529 			chdr = (struct csrhdr *)(fc->ongodev->csrrom);
1530 			offset = CSRROMOFF;
1531 		}else{
1532 			chdr = (struct csrhdr *)&fc->ongodev->csrrom[(csrd->off - CSRROMOFF)/4];
1533 			offset = csrd->off;
1534 		}
1535 		if(fc->ongoaddr > (CSRROMOFF + 0x14) && fc->ongoaddr != offset){
1536 			csrreg = (struct csrreg *)&fc->ongodev->csrrom[(fc->ongoaddr - CSRROMOFF)/4];
1537 			if( csrreg->key == 0x81 || csrreg->key == 0xd1){
1538 				csrd = SLIST_FIRST(&fc->csrfree);
1539 				if(csrd == NULL){
1540 					goto nextnode;
1541 				}else{
1542 					csrd->ongoaddr = fc->ongoaddr;
1543 					fc->ongoaddr += csrreg->val * 4;
1544 					csrd->off = fc->ongoaddr;
1545 					SLIST_REMOVE_HEAD(&fc->csrfree, link);
1546 					SLIST_INSERT_HEAD(&fc->ongocsr, csrd, link);
1547 					goto nextaddr;
1548 				}
1549 			}
1550 		}
1551 		fc->ongoaddr += 4;
1552 		if(((fc->ongoaddr - offset)/4 > chdr->crc_len) &&
1553 				(fc->ongodev->rommax < 0x414)){
1554 			if(fc->ongodev->rommax <= 0x414){
1555 				csrd = SLIST_FIRST(&fc->csrfree);
1556 				if(csrd == NULL) goto nextnode;
1557 				csrd->off = fc->ongoaddr;
1558 				csrd->ongoaddr = fc->ongoaddr;
1559 				SLIST_REMOVE_HEAD(&fc->csrfree, link);
1560 				SLIST_INSERT_HEAD(&fc->ongocsr, csrd, link);
1561 			}
1562 			goto nextaddr;
1563 		}
1564 
1565 		while(((fc->ongoaddr - offset)/4 > chdr->crc_len)){
1566 			if(csrd == NULL){
1567 				goto nextnode;
1568 			};
1569 			fc->ongoaddr = csrd->ongoaddr + 4;
1570 			SLIST_REMOVE_HEAD(&fc->ongocsr, link);
1571 			SLIST_INSERT_HEAD(&fc->csrfree, csrd, link);
1572 			csrd = SLIST_FIRST(&fc->ongocsr);
1573 			if((csrd = SLIST_FIRST(&fc->ongocsr)) == NULL){
1574 				chdr = (struct csrhdr *)(fc->ongodev->csrrom);
1575 				offset = CSRROMOFF;
1576 			}else{
1577 				chdr = (struct csrhdr *)&(fc->ongodev->csrrom[(csrd->off - CSRROMOFF)/4]);
1578 				offset = csrd->off;
1579 			}
1580 		}
1581 		if((fc->ongoaddr - CSRROMOFF) > CSRROMSIZE){
1582 			goto nextnode;
1583 		}
1584 	}
1585 nextaddr:
1586 	fw_xfer_free( xfer);
1587 	fw_bus_explore(fc);
1588 	return;
1589 errnode:
1590 	fc->retry_count++;
1591 	if (fc->ongodev != NULL)
1592 		fc->ongodev->status = FWDEVINVAL;
1593 nextnode:
1594 	fw_xfer_free( xfer);
1595 	fc->ongonode++;
1596 /* housekeeping work space */
1597 	fc->ongoaddr = CSRROMOFF;
1598 	fc->ongodev = NULL;
1599 	fc->ongoeui.hi = 0xffffffff; fc->ongoeui.lo = 0xffffffff;
1600 	while((csrd = SLIST_FIRST(&fc->ongocsr)) != NULL){
1601 		SLIST_REMOVE_HEAD(&fc->ongocsr, link);
1602 		SLIST_INSERT_HEAD(&fc->csrfree, csrd, link);
1603 	}
1604 	fw_bus_explore(fc);
1605 	return;
1606 }
1607 
1608 /*
1609  * To attach sub-devices layer onto IEEE1394 bus.
1610  */
1611 static void
1612 fw_attach_dev(struct firewire_comm *fc)
1613 {
1614 	struct fw_device *fwdev, *next;
1615 	int i, err;
1616 	device_t *devlistp;
1617 	int devcnt;
1618 	struct firewire_dev_comm *fdc;
1619 
1620 	for (fwdev = STAILQ_FIRST(&fc->devices); fwdev != NULL; fwdev = next) {
1621 		next = STAILQ_NEXT(fwdev, link);
1622 		if (fwdev->status == FWDEVINIT) {
1623 			fwdev->status = FWDEVATTACHED;
1624 		} else if (fwdev->status == FWDEVINVAL) {
1625 			fwdev->rcnt ++;
1626 			if (fwdev->rcnt > hold_count) {
1627 				/*
1628 				 * Remove devices which have not been seen
1629 				 * for a while.
1630 				 */
1631 				STAILQ_REMOVE(&fc->devices, fwdev, fw_device,
1632 				    link);
1633 				kfree(fwdev, M_FW);
1634 			}
1635 		}
1636 	}
1637 
1638 	err = device_get_children(fc->bdev, &devlistp, &devcnt);
1639 	if( err != 0 )
1640 		return;
1641 	for( i = 0 ; i < devcnt ; i++){
1642 		if (device_get_state(devlistp[i]) >= DS_ATTACHED)  {
1643 			fdc = device_get_softc(devlistp[i]);
1644 			if (fdc->post_explore != NULL)
1645 				fdc->post_explore(fdc);
1646 		}
1647 	}
1648 	kfree(devlistp, M_TEMP);
1649 
1650 	if (fc->retry_count > 0) {
1651 		kprintf("probe failed for %d node\n", fc->retry_count);
1652 #if 0
1653 		callout_reset(&fc->retry_probe_callout, hz*2,
1654 					(void *)fc->ibr, (void *)fc);
1655 #endif
1656 	}
1657 	return;
1658 }
1659 
1660 /*
1661  * To allocate uniq transaction label.
1662  */
1663 static int
1664 fw_get_tlabel(struct firewire_comm *fc, struct fw_xfer *xfer)
1665 {
1666 	u_int i;
1667 	struct tlabel *tl, *tmptl;
1668 	static u_int32_t label = 0;
1669 
1670 	crit_enter();
1671 	for( i = 0 ; i < 0x40 ; i ++){
1672 		label = (label + 1) & 0x3f;
1673 		for(tmptl = STAILQ_FIRST(&fc->tlabels[label]);
1674 			tmptl != NULL; tmptl = STAILQ_NEXT(tmptl, link)){
1675 			if (tmptl->xfer->send.hdr.mode.hdr.dst ==
1676 			    xfer->send.hdr.mode.hdr.dst)
1677 				break;
1678 		}
1679 		if(tmptl == NULL) {
1680 			tl = kmalloc(sizeof(struct tlabel), M_FW, M_WAITOK);
1681 			tl->xfer = xfer;
1682 			STAILQ_INSERT_TAIL(&fc->tlabels[label], tl, link);
1683 			crit_exit();
1684 			if (firewire_debug > 1)
1685 				kprintf("fw_get_tlabel: dst=%d tl=%d\n",
1686 				    xfer->send.hdr.mode.hdr.dst, label);
1687 			return(label);
1688 		}
1689 	}
1690 	crit_exit();
1691 
1692 	kprintf("fw_get_tlabel: no free tlabel\n");
1693 	return(-1);
1694 }
1695 
1696 static void
1697 fw_rcv_copy(struct fw_rcv_buf *rb)
1698 {
1699 	struct fw_pkt *pkt;
1700 	u_char *p;
1701 	struct tcode_info *tinfo;
1702 	u_int res, i, len, plen;
1703 
1704 	rb->xfer->recv.spd -= rb->spd;
1705 
1706 	pkt = (struct fw_pkt *)rb->vec->iov_base;
1707 	tinfo = &rb->fc->tcode[pkt->mode.hdr.tcode];
1708 
1709 	/* Copy header */
1710 	p = (u_char *)&rb->xfer->recv.hdr;
1711 	bcopy(rb->vec->iov_base, p, tinfo->hdr_len);
1712 	rb->vec->iov_base = (uint8_t *)rb->vec->iov_base + tinfo->hdr_len;
1713 	rb->vec->iov_len -= tinfo->hdr_len;
1714 
1715 	/* Copy payload */
1716 	p = (u_char *)rb->xfer->recv.payload;
1717 	res = rb->xfer->recv.pay_len;
1718 
1719 	/* special handling for RRESQ */
1720 	if (pkt->mode.hdr.tcode == FWTCODE_RRESQ &&
1721 	    p != NULL && res >= sizeof(u_int32_t)) {
1722 		*(u_int32_t *)p = pkt->mode.rresq.data;
1723 		rb->xfer->recv.pay_len = sizeof(u_int32_t);
1724 		return;
1725 	}
1726 
1727 	if ((tinfo->flag & FWTI_BLOCK_ASY) == 0)
1728 		return;
1729 
1730 	plen = pkt->mode.rresb.len;
1731 
1732 	for (i = 0; i < rb->nvec; i++, rb->vec++) {
1733 		len = MIN(rb->vec->iov_len, plen);
1734 		if (res < len) {
1735 			kprintf("rcv buffer(%d) is %d bytes short.\n",
1736 			    rb->xfer->recv.pay_len, len - res);
1737 			len = res;
1738 		}
1739 		bcopy(rb->vec->iov_base, p, len);
1740 		p += len;
1741 		res -= len;
1742 		plen -= len;
1743 		if (res == 0 || plen == 0)
1744 			break;
1745 	}
1746 	rb->xfer->recv.pay_len -= res;
1747 
1748 }
1749 
1750 /*
1751  * Generic packet receving process.
1752  */
1753 void
1754 fw_rcv(struct fw_rcv_buf *rb)
1755 {
1756 	struct fw_pkt *fp, *resfp;
1757 	struct fw_bind *bind;
1758 	int tcode;
1759 	int i, len, oldstate;
1760 #if 0
1761 	{
1762 		u_int32_t *qld;
1763 		int i;
1764 		qld = (u_int32_t *)buf;
1765 		kprintf("spd %d len:%d\n", spd, len);
1766 		for( i = 0 ; i <= len && i < 32; i+= 4){
1767 			kprintf("0x%08x ", ntohl(qld[i/4]));
1768 			if((i % 16) == 15) kprintf("\n");
1769 		}
1770 		if((i % 16) != 15) kprintf("\n");
1771 	}
1772 #endif
1773 	fp = (struct fw_pkt *)rb->vec[0].iov_base;
1774 	tcode = fp->mode.common.tcode;
1775 	switch (tcode) {
1776 	case FWTCODE_WRES:
1777 	case FWTCODE_RRESQ:
1778 	case FWTCODE_RRESB:
1779 	case FWTCODE_LRES:
1780 		rb->xfer = fw_tl2xfer(rb->fc, fp->mode.hdr.src,
1781 					fp->mode.hdr.tlrt >> 2);
1782 		if(rb->xfer == NULL) {
1783 			kprintf("fw_rcv: unknown response "
1784 			    "%s(%x) src=0x%x tl=0x%x rt=%d data=0x%x\n",
1785 			    tcode_str[tcode], tcode,
1786 			    fp->mode.hdr.src,
1787 			    fp->mode.hdr.tlrt >> 2,
1788 			    fp->mode.hdr.tlrt & 3,
1789 			    fp->mode.rresq.data);
1790 #if 1
1791 			kprintf("try ad-hoc work around!!\n");
1792 			rb->xfer = fw_tl2xfer(rb->fc, fp->mode.hdr.src,
1793 					(fp->mode.hdr.tlrt >> 2)^3);
1794 			if (rb->xfer == NULL) {
1795 				kprintf("no use...\n");
1796 				goto err;
1797 			}
1798 #else
1799 			goto err;
1800 #endif
1801 		}
1802 		fw_rcv_copy(rb);
1803 		if (rb->xfer->recv.hdr.mode.wres.rtcode != RESP_CMP)
1804 			rb->xfer->resp = EIO;
1805 		else
1806 			rb->xfer->resp = 0;
1807 		/* make sure the packet is drained in AT queue */
1808 		oldstate = rb->xfer->state;
1809 		rb->xfer->state = FWXF_RCVD;
1810 		switch (oldstate) {
1811 		case FWXF_SENT:
1812 			fw_xfer_done(rb->xfer);
1813 			break;
1814 		case FWXF_START:
1815 #if 0
1816 			if (firewire_debug)
1817 				kprintf("not sent yet tl=%x\n", rb->xfer->tl);
1818 #endif
1819 			break;
1820 		default:
1821 			kprintf("unexpected state %d\n", rb->xfer->state);
1822 		}
1823 		return;
1824 	case FWTCODE_WREQQ:
1825 	case FWTCODE_WREQB:
1826 	case FWTCODE_RREQQ:
1827 	case FWTCODE_RREQB:
1828 	case FWTCODE_LREQ:
1829 		bind = fw_bindlookup(rb->fc, fp->mode.rreqq.dest_hi,
1830 			fp->mode.rreqq.dest_lo);
1831 		if(bind == NULL){
1832 			kprintf("Unknown service addr 0x%04x:0x%08x %s(%x)"
1833 			    " src=0x%x data=%x\n",
1834 			    fp->mode.wreqq.dest_hi, fp->mode.wreqq.dest_lo,
1835 			    tcode_str[tcode], tcode,
1836 			    fp->mode.hdr.src, ntohl(fp->mode.wreqq.data));
1837 			if (rb->fc->status == FWBUSRESET) {
1838 				kprintf("fw_rcv: cannot respond(bus reset)!\n");
1839 				goto err;
1840 			}
1841 			rb->xfer = fw_xfer_alloc(M_FWXFER);
1842 			if(rb->xfer == NULL){
1843 				return;
1844 			}
1845 			rb->xfer->send.spd = rb->spd;
1846 			rb->xfer->send.pay_len = 0;
1847 			resfp = &rb->xfer->send.hdr;
1848 			switch (tcode) {
1849 			case FWTCODE_WREQQ:
1850 			case FWTCODE_WREQB:
1851 				resfp->mode.hdr.tcode = FWTCODE_WRES;
1852 				break;
1853 			case FWTCODE_RREQQ:
1854 				resfp->mode.hdr.tcode = FWTCODE_RRESQ;
1855 				break;
1856 			case FWTCODE_RREQB:
1857 				resfp->mode.hdr.tcode = FWTCODE_RRESB;
1858 				break;
1859 			case FWTCODE_LREQ:
1860 				resfp->mode.hdr.tcode = FWTCODE_LRES;
1861 				break;
1862 			}
1863 			resfp->mode.hdr.dst = fp->mode.hdr.src;
1864 			resfp->mode.hdr.tlrt = fp->mode.hdr.tlrt;
1865 			resfp->mode.hdr.pri = fp->mode.hdr.pri;
1866 			resfp->mode.rresb.rtcode = RESP_ADDRESS_ERROR;
1867 			resfp->mode.rresb.extcode = 0;
1868 			resfp->mode.rresb.len = 0;
1869 /*
1870 			rb->xfer->act.hand = fw_asy_callback;
1871 */
1872 			rb->xfer->act.hand = fw_xfer_free;
1873 			if(fw_asyreq(rb->fc, -1, rb->xfer)){
1874 				fw_xfer_free(rb->xfer);
1875 				return;
1876 			}
1877 			goto err;
1878 		}
1879 		len = 0;
1880 		for (i = 0; i < rb->nvec; i ++)
1881 			len += rb->vec[i].iov_len;
1882 		switch(bind->act_type){
1883 		case FWACT_XFER:
1884 			crit_enter();
1885 			rb->xfer = STAILQ_FIRST(&bind->xferlist);
1886 			if (rb->xfer == NULL) {
1887 				kprintf("Discard a packet for this bind.\n");
1888 				crit_exit();
1889 				goto err;
1890 			}
1891 			STAILQ_REMOVE_HEAD(&bind->xferlist, link);
1892 			crit_exit();
1893 			fw_rcv_copy(rb);
1894 			rb->xfer->act.hand(rb->xfer);
1895 			return;
1896 			break;
1897 		case FWACT_CH:
1898 			if(rb->fc->ir[bind->sub]->queued >=
1899 				rb->fc->ir[bind->sub]->maxq){
1900 				device_printf(rb->fc->bdev,
1901 					"Discard a packet %x %d\n",
1902 					bind->sub,
1903 					rb->fc->ir[bind->sub]->queued);
1904 				goto err;
1905 			}
1906 			crit_enter();
1907 			rb->xfer = STAILQ_FIRST(&bind->xferlist);
1908 			if (rb->xfer == NULL) {
1909 				kprintf("Discard packet for this bind\n");
1910 				goto err;
1911 			}
1912 			STAILQ_REMOVE_HEAD(&bind->xferlist, link);
1913 			crit_exit();
1914 			fw_rcv_copy(rb);
1915 			crit_enter();
1916 			rb->fc->ir[bind->sub]->queued++;
1917 			STAILQ_INSERT_TAIL(&rb->fc->ir[bind->sub]->q,
1918 			    rb->xfer, link);
1919 			crit_exit();
1920 
1921 			wakeup((caddr_t)rb->fc->ir[bind->sub]);
1922 
1923 			return;
1924 			break;
1925 		default:
1926 			goto err;
1927 			break;
1928 		}
1929 		break;
1930 #if 0 /* shouldn't happen ?? or for GASP */
1931 	case FWTCODE_STREAM:
1932 	{
1933 		struct fw_xferq *xferq;
1934 
1935 		xferq = rb->fc->ir[sub];
1936 #if 0
1937 		kprintf("stream rcv dma %d len %d off %d spd %d\n",
1938 			sub, len, off, spd);
1939 #endif
1940 		if(xferq->queued >= xferq->maxq) {
1941 			kprintf("receive queue is full\n");
1942 			goto err;
1943 		}
1944 		/* XXX get xfer from xfer queue, we don't need copy for
1945 			per packet mode */
1946 		rb->xfer = fw_xfer_alloc_buf(M_FWXFER, 0, /* XXX */
1947 						vec[0].iov_len);
1948 		if (rb->xfer == NULL) goto err;
1949 		fw_rcv_copy(rb)
1950 		crit_enter();
1951 		xferq->queued++;
1952 		STAILQ_INSERT_TAIL(&xferq->q, rb->xfer, link);
1953 		crit_exit();
1954 		sc = device_get_softc(rb->fc->bdev);
1955 #if defined(__DragonFly__) || __FreeBSD_version < 500000
1956 		if (&xferq->rsel.si_pid != 0)
1957 #else
1958 		if (SEL_WAITING(&xferq->rsel))
1959 #endif
1960 			selwakeuppri(&xferq->rsel, FWPRI);
1961 		if (xferq->flag & FWXFERQ_WAKEUP) {
1962 			xferq->flag &= ~FWXFERQ_WAKEUP;
1963 			wakeup((caddr_t)xferq);
1964 		}
1965 		if (xferq->flag & FWXFERQ_HANDLER) {
1966 			xferq->hand(xferq);
1967 		}
1968 		return;
1969 		break;
1970 	}
1971 #endif
1972 	default:
1973 		kprintf("fw_rcv: unknow tcode %d\n", tcode);
1974 		break;
1975 	}
1976 err:
1977 	return;
1978 }
1979 
1980 /*
1981  * Post process for Bus Manager election process.
1982  */
1983 static void
1984 fw_try_bmr_callback(struct fw_xfer *xfer)
1985 {
1986 	struct firewire_comm *fc;
1987 	int bmr;
1988 
1989 	if (xfer == NULL)
1990 		return;
1991 	fc = xfer->fc;
1992 	if (xfer->resp != 0)
1993 		goto error;
1994 	if (xfer->recv.payload == NULL)
1995 		goto error;
1996 	if (xfer->recv.hdr.mode.lres.rtcode != FWRCODE_COMPLETE)
1997 		goto error;
1998 
1999 	bmr = ntohl(xfer->recv.payload[0]);
2000 	if (bmr == 0x3f)
2001 		bmr = fc->nodeid;
2002 
2003 	CSRARC(fc, BUS_MGR_ID) = fc->set_bmr(fc, bmr & 0x3f);
2004 	fw_xfer_free_buf(xfer);
2005 	fw_bmr(fc);
2006 	return;
2007 
2008 error:
2009 	device_printf(fc->bdev, "bus manager election failed\n");
2010 	fw_xfer_free_buf(xfer);
2011 }
2012 
2013 
2014 /*
2015  * To candidate Bus Manager election process.
2016  */
2017 static void
2018 fw_try_bmr(void *arg)
2019 {
2020 	struct fw_xfer *xfer;
2021 	struct firewire_comm *fc = (struct firewire_comm *)arg;
2022 	struct fw_pkt *fp;
2023 	int err = 0;
2024 
2025 	xfer = fw_xfer_alloc_buf(M_FWXFER, 8, 4);
2026 	if(xfer == NULL){
2027 		return;
2028 	}
2029 	xfer->send.spd = 0;
2030 	fc->status = FWBUSMGRELECT;
2031 
2032 	fp = &xfer->send.hdr;
2033 	fp->mode.lreq.dest_hi = 0xffff;
2034 	fp->mode.lreq.tlrt = 0;
2035 	fp->mode.lreq.tcode = FWTCODE_LREQ;
2036 	fp->mode.lreq.pri = 0;
2037 	fp->mode.lreq.src = 0;
2038 	fp->mode.lreq.len = 8;
2039 	fp->mode.lreq.extcode = EXTCODE_CMP_SWAP;
2040 	fp->mode.lreq.dst = FWLOCALBUS | fc->irm;
2041 	fp->mode.lreq.dest_lo = 0xf0000000 | BUS_MGR_ID;
2042 	xfer->send.payload[0] = htonl(0x3f);
2043 	xfer->send.payload[1] = htonl(fc->nodeid);
2044 	xfer->act.hand = fw_try_bmr_callback;
2045 
2046 	err = fw_asyreq(fc, -1, xfer);
2047 	if(err){
2048 		fw_xfer_free_buf(xfer);
2049 		return;
2050 	}
2051 	return;
2052 }
2053 
2054 #ifdef FW_VMACCESS
2055 /*
2056  * Software implementation for physical memory block access.
2057  * XXX:Too slow, usef for debug purpose only.
2058  */
2059 static void
2060 fw_vmaccess(struct fw_xfer *xfer){
2061 	struct fw_pkt *rfp, *sfp = NULL;
2062 	u_int32_t *ld = (u_int32_t *)xfer->recv.buf;
2063 
2064 	kprintf("vmaccess spd:%2x len:%03x data:%08x %08x %08x %08x\n",
2065 			xfer->spd, xfer->recv.len, ntohl(ld[0]), ntohl(ld[1]), ntohl(ld[2]), ntohl(ld[3]));
2066 	kprintf("vmaccess          data:%08x %08x %08x %08x\n", ntohl(ld[4]), ntohl(ld[5]), ntohl(ld[6]), ntohl(ld[7]));
2067 	if(xfer->resp != 0){
2068 		fw_xfer_free( xfer);
2069 		return;
2070 	}
2071 	if(xfer->recv.buf == NULL){
2072 		fw_xfer_free( xfer);
2073 		return;
2074 	}
2075 	rfp = (struct fw_pkt *)xfer->recv.buf;
2076 	switch(rfp->mode.hdr.tcode){
2077 		/* XXX need fix for 64bit arch */
2078 		case FWTCODE_WREQB:
2079 			xfer->send.buf = kmalloc(12, M_FW, M_WAITOK);
2080 			xfer->send.len = 12;
2081 			sfp = (struct fw_pkt *)xfer->send.buf;
2082 			bcopy(rfp->mode.wreqb.payload,
2083 				(caddr_t)ntohl(rfp->mode.wreqb.dest_lo), ntohs(rfp->mode.wreqb.len));
2084 			sfp->mode.wres.tcode = FWTCODE_WRES;
2085 			sfp->mode.wres.rtcode = 0;
2086 			break;
2087 		case FWTCODE_WREQQ:
2088 			xfer->send.buf = kmalloc(12, M_FW, M_WAITOK);
2089 			xfer->send.len = 12;
2090 			sfp->mode.wres.tcode = FWTCODE_WRES;
2091 			*((u_int32_t *)(ntohl(rfp->mode.wreqb.dest_lo))) = rfp->mode.wreqq.data;
2092 			sfp->mode.wres.rtcode = 0;
2093 			break;
2094 		case FWTCODE_RREQB:
2095 			xfer->send.buf = kmalloc(16 + rfp->mode.rreqb.len, M_FW, M_WAITOK);
2096 			xfer->send.len = 16 + ntohs(rfp->mode.rreqb.len);
2097 			sfp = (struct fw_pkt *)xfer->send.buf;
2098 			bcopy((caddr_t)ntohl(rfp->mode.rreqb.dest_lo),
2099 				sfp->mode.rresb.payload, (u_int16_t)ntohs(rfp->mode.rreqb.len));
2100 			sfp->mode.rresb.tcode = FWTCODE_RRESB;
2101 			sfp->mode.rresb.len = rfp->mode.rreqb.len;
2102 			sfp->mode.rresb.rtcode = 0;
2103 			sfp->mode.rresb.extcode = 0;
2104 			break;
2105 		case FWTCODE_RREQQ:
2106 			xfer->send.buf = kmalloc(16, M_FW, M_WAITOK);
2107 			xfer->send.len = 16;
2108 			sfp = (struct fw_pkt *)xfer->send.buf;
2109 			sfp->mode.rresq.data = *(u_int32_t *)(ntohl(rfp->mode.rreqq.dest_lo));
2110 			sfp->mode.wres.tcode = FWTCODE_RRESQ;
2111 			sfp->mode.rresb.rtcode = 0;
2112 			break;
2113 		default:
2114 			fw_xfer_free( xfer);
2115 			return;
2116 	}
2117 	sfp->mode.hdr.dst = rfp->mode.hdr.src;
2118 	xfer->dst = ntohs(rfp->mode.hdr.src);
2119 	xfer->act.hand = fw_xfer_free;
2120 	xfer->retry_req = fw_asybusy;
2121 
2122 	sfp->mode.hdr.tlrt = rfp->mode.hdr.tlrt;
2123 	sfp->mode.hdr.pri = 0;
2124 
2125 	fw_asyreq(xfer->fc, -1, xfer);
2126 /**/
2127 	return;
2128 }
2129 #endif
2130 
2131 /*
2132  * CRC16 check-sum for IEEE1394 register blocks.
2133  */
2134 u_int16_t
2135 fw_crc16(u_int32_t *ptr, u_int32_t len){
2136 	u_int32_t i, sum, crc = 0;
2137 	int shift;
2138 	len = (len + 3) & ~3;
2139 	for(i = 0 ; i < len ; i+= 4){
2140 		for( shift = 28 ; shift >= 0 ; shift -= 4){
2141 			sum = ((crc >> 12) ^ (ptr[i/4] >> shift)) & 0xf;
2142 			crc = (crc << 4) ^ ( sum << 12 ) ^ ( sum << 5) ^ sum;
2143 		}
2144 		crc &= 0xffff;
2145 	}
2146 	return((u_int16_t) crc);
2147 }
2148 
2149 static int
2150 fw_bmr(struct firewire_comm *fc)
2151 {
2152 	struct fw_device fwdev;
2153 	union fw_self_id *self_id;
2154 	int cmstr;
2155 	u_int32_t quad;
2156 
2157 	/* Check to see if the current root node is cycle master capable */
2158 	self_id = &fc->topology_map->self_id[fc->max_node];
2159 	if (fc->max_node > 0) {
2160 		/* XXX check cmc bit of businfo block rather than contender */
2161 		if (self_id->p0.link_active && self_id->p0.contender)
2162 			cmstr = fc->max_node;
2163 		else {
2164 			device_printf(fc->bdev,
2165 				"root node is not cycle master capable\n");
2166 			/* XXX shall we be the cycle master? */
2167 			cmstr = fc->nodeid;
2168 			/* XXX need bus reset */
2169 		}
2170 	} else
2171 		cmstr = -1;
2172 
2173 	device_printf(fc->bdev, "bus manager %d ", CSRARC(fc, BUS_MGR_ID));
2174 	if(CSRARC(fc, BUS_MGR_ID) != fc->nodeid) {
2175 		/* We are not the bus manager */
2176 		kprintf("\n");
2177 		return(0);
2178 	}
2179 	kprintf("(me)\n");
2180 
2181 	/* Optimize gapcount */
2182 	if(fc->max_hop <= MAX_GAPHOP )
2183 		fw_phy_config(fc, cmstr, gap_cnt[fc->max_hop]);
2184 	/* If we are the cycle master, nothing to do */
2185 	if (cmstr == fc->nodeid || cmstr == -1)
2186 		return 0;
2187 	/* Bus probe has not finished, make dummy fwdev for cmstr */
2188 	bzero(&fwdev, sizeof(fwdev));
2189 	fwdev.fc = fc;
2190 	fwdev.dst = cmstr;
2191 	fwdev.speed = 0;
2192 	fwdev.maxrec = 8; /* 512 */
2193 	fwdev.status = FWDEVINIT;
2194 	/* Set cmstr bit on the cycle master */
2195 	quad = htonl(1 << 8);
2196 	fwmem_write_quad(&fwdev, NULL, 0/*spd*/,
2197 		0xffff, 0xf0000000 | STATE_SET, &quad, fw_asy_callback_free);
2198 
2199 	return 0;
2200 }
2201 
2202 static int
2203 fw_modevent(module_t mode, int type, void *data)
2204 {
2205 	int err = 0;
2206 #if defined(__FreeBSD__) && __FreeBSD_version >= 500000
2207 	static eventhandler_tag fwdev_ehtag = NULL;
2208 #endif
2209 
2210 	switch (type) {
2211 	case MOD_LOAD:
2212 #if defined(__FreeBSD__) && __FreeBSD_version >= 500000
2213 		fwdev_ehtag = EVENTHANDLER_REGISTER(dev_clone,
2214 						fwdev_clone, 0, 1000);
2215 #endif
2216 		break;
2217 	case MOD_UNLOAD:
2218 #if defined(__FreeBSD__) && __FreeBSD_version >= 500000
2219 		if (fwdev_ehtag != NULL)
2220 			EVENTHANDLER_DEREGISTER(dev_clone, fwdev_ehtag);
2221 #endif
2222 		break;
2223 	case MOD_SHUTDOWN:
2224 		break;
2225 	}
2226 	return (err);
2227 }
2228 
2229 /*
2230  * This causes the firewire identify to be called for any attached fwohci
2231  * device in the system.
2232  */
2233 DECLARE_DUMMY_MODULE(firewire);
2234 DRIVER_MODULE(firewire,fwohci,firewire_driver,firewire_devclass,fw_modevent,0);
2235 MODULE_VERSION(firewire, 1);
2236