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