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