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