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