xref: /freebsd/sys/dev/firewire/firewire.c (revision 37ce2656ecc485e9a38169c72d1a64a00f6beb6d)
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/kernel.h>
43 #include <sys/module.h>
44 #include <sys/malloc.h>
45 #include <sys/conf.h>
46 #include <sys/sysctl.h>
47 #include <sys/kthread.h>
48 #include <sys/vimage.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=3;
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 	src->businfo.generation = 0;
689 	src->businfo.link_spd = fc->speed;
690 
691 	src->businfo.eui64.hi = fc->eui.hi;
692 	src->businfo.eui64.lo = fc->eui.lo;
693 
694 	STAILQ_INIT(&src->chunk_list);
695 
696 	fc->crom_src = src;
697 	fc->crom_root = &fc->crom_src_buf->root;
698 }
699 
700 static void
701 fw_reset_crom(struct firewire_comm *fc)
702 {
703 	struct crom_src_buf *buf;
704 	struct crom_src *src;
705 	struct crom_chunk *root;
706 
707 	buf =  fc->crom_src_buf;
708 	src = fc->crom_src;
709 	root = fc->crom_root;
710 
711 	STAILQ_INIT(&src->chunk_list);
712 
713 	bzero(root, sizeof(struct crom_chunk));
714 	crom_add_chunk(src, NULL, root, 0);
715 	crom_add_entry(root, CSRKEY_NCAP, 0x0083c0); /* XXX */
716 	/* private company_id */
717 	crom_add_entry(root, CSRKEY_VENDOR, CSRVAL_VENDOR_PRIVATE);
718 #ifdef __DragonFly__
719 	crom_add_simple_text(src, root, &buf->vendor, "DragonFly Project");
720 	crom_add_entry(root, CSRKEY_HW, __DragonFly_cc_version);
721 #else
722 	crom_add_simple_text(src, root, &buf->vendor, "FreeBSD Project");
723 	crom_add_entry(root, CSRKEY_HW, __FreeBSD_version);
724 #endif
725 	crom_add_simple_text(src, root, &buf->hw, G_hostname);
726 }
727 
728 /*
729  * Called after bus reset.
730  */
731 void
732 fw_busreset(struct firewire_comm *fc, uint32_t new_status)
733 {
734 	struct firewire_dev_comm *fdc;
735 	struct crom_src *src;
736 	device_t *devlistp;
737 	int i, devcnt;
738 
739 	FW_GLOCK_ASSERT(fc);
740 	if (fc->status == FWBUSMGRELECT)
741 		callout_stop(&fc->bmr_callout);
742 
743 	fc->status = new_status;
744 	fw_reset_csr(fc);
745 
746 	if (fc->status == FWBUSNOTREADY)
747 		fw_init_crom(fc);
748 
749 	fw_reset_crom(fc);
750 
751 	if (device_get_children(fc->bdev, &devlistp, &devcnt) == 0) {
752 		for( i = 0 ; i < devcnt ; i++)
753 			if (device_get_state(devlistp[i]) >= DS_ATTACHED)  {
754 				fdc = device_get_softc(devlistp[i]);
755 				if (fdc->post_busreset != NULL)
756 					fdc->post_busreset(fdc);
757 			}
758 		free(devlistp, M_TEMP);
759 	}
760 
761 	src = &fc->crom_src_buf->src;
762 	/*
763 	 * If the old config rom needs to be overwritten,
764 	 * bump the businfo.generation indicator to
765 	 * indicate that we need to be reprobed
766 	 */
767 	if (bcmp(src, fc->config_rom, CROMSIZE) != 0) {
768 		/* generation is a 2 bit field */
769 		/* valid values are only from 0 - 3 */
770 		src->businfo.generation = 1;
771 		bcopy(src, (void *)fc->config_rom, CROMSIZE);
772 	} else
773 		src->businfo.generation = 0;
774 }
775 
776 /* Call once after reboot */
777 void fw_init(struct firewire_comm *fc)
778 {
779 	int i;
780 #ifdef FW_VMACCESS
781 	struct fw_xfer *xfer;
782 	struct fw_bind *fwb;
783 #endif
784 
785 	fc->arq->queued = 0;
786 	fc->ars->queued = 0;
787 	fc->atq->queued = 0;
788 	fc->ats->queued = 0;
789 
790 	fc->arq->buf = NULL;
791 	fc->ars->buf = NULL;
792 	fc->atq->buf = NULL;
793 	fc->ats->buf = NULL;
794 
795 	fc->arq->flag = 0;
796 	fc->ars->flag = 0;
797 	fc->atq->flag = 0;
798 	fc->ats->flag = 0;
799 
800 	STAILQ_INIT(&fc->atq->q);
801 	STAILQ_INIT(&fc->ats->q);
802 
803 	for( i = 0 ; i < fc->nisodma ; i ++ ){
804 		fc->it[i]->queued = 0;
805 		fc->ir[i]->queued = 0;
806 
807 		fc->it[i]->start = NULL;
808 		fc->ir[i]->start = NULL;
809 
810 		fc->it[i]->buf = NULL;
811 		fc->ir[i]->buf = NULL;
812 
813 		fc->it[i]->flag = FWXFERQ_STREAM;
814 		fc->ir[i]->flag = FWXFERQ_STREAM;
815 
816 		STAILQ_INIT(&fc->it[i]->q);
817 		STAILQ_INIT(&fc->ir[i]->q);
818 	}
819 
820 	fc->arq->maxq = FWMAXQUEUE;
821 	fc->ars->maxq = FWMAXQUEUE;
822 	fc->atq->maxq = FWMAXQUEUE;
823 	fc->ats->maxq = FWMAXQUEUE;
824 
825 	for( i = 0 ; i < fc->nisodma ; i++){
826 		fc->ir[i]->maxq = FWMAXQUEUE;
827 		fc->it[i]->maxq = FWMAXQUEUE;
828 	}
829 
830 	CSRARC(fc, TOPO_MAP) = 0x3f1 << 16;
831 	CSRARC(fc, TOPO_MAP + 4) = 1;
832 	CSRARC(fc, SPED_MAP) = 0x3f1 << 16;
833 	CSRARC(fc, SPED_MAP + 4) = 1;
834 
835 	STAILQ_INIT(&fc->devices);
836 
837 /* Initialize Async handlers */
838 	STAILQ_INIT(&fc->binds);
839 	for( i = 0 ; i < 0x40 ; i++){
840 		STAILQ_INIT(&fc->tlabels[i]);
841 	}
842 
843 /* DV depend CSRs see blue book */
844 #if 0
845 	CSRARC(fc, oMPR) = 0x3fff0001; /* # output channel = 1 */
846 	CSRARC(fc, oPCR) = 0x8000007a;
847 	for(i = 4 ; i < 0x7c/4 ; i+=4){
848 		CSRARC(fc, i + oPCR) = 0x8000007a;
849 	}
850 
851 	CSRARC(fc, iMPR) = 0x00ff0001; /* # input channel = 1 */
852 	CSRARC(fc, iPCR) = 0x803f0000;
853 	for(i = 4 ; i < 0x7c/4 ; i+=4){
854 		CSRARC(fc, i + iPCR) = 0x0;
855 	}
856 #endif
857 
858 	fc->crom_src_buf = NULL;
859 
860 #ifdef FW_VMACCESS
861 	xfer = fw_xfer_alloc();
862 	if(xfer == NULL) return;
863 
864 	fwb = (struct fw_bind *)malloc(sizeof (struct fw_bind), M_FW, M_NOWAIT);
865 	if(fwb == NULL){
866 		fw_xfer_free(xfer);
867 		return;
868 	}
869 	xfer->hand = fw_vmaccess;
870 	xfer->fc = fc;
871 	xfer->sc = NULL;
872 
873 	fwb->start_hi = 0x2;
874 	fwb->start_lo = 0;
875 	fwb->addrlen = 0xffffffff;
876 	fwb->xfer = xfer;
877 	fw_bindadd(fc, fwb);
878 #endif
879 }
880 
881 #define BIND_CMP(addr, fwb) (((addr) < (fwb)->start)?-1:\
882     ((fwb)->end < (addr))?1:0)
883 
884 /*
885  * To lookup bound process from IEEE1394 address.
886  */
887 struct fw_bind *
888 fw_bindlookup(struct firewire_comm *fc, uint16_t dest_hi, uint32_t dest_lo)
889 {
890 	u_int64_t addr;
891 	struct fw_bind *tfw, *r = NULL;
892 
893 	addr = ((u_int64_t)dest_hi << 32) | dest_lo;
894 	FW_GLOCK(fc);
895 	STAILQ_FOREACH(tfw, &fc->binds, fclist)
896 		if (BIND_CMP(addr, tfw) == 0) {
897 			r = tfw;
898 			break;
899 		}
900 	FW_GUNLOCK(fc);
901 	return(r);
902 }
903 
904 /*
905  * To bind IEEE1394 address block to process.
906  */
907 int
908 fw_bindadd(struct firewire_comm *fc, struct fw_bind *fwb)
909 {
910 	struct fw_bind *tfw, *prev = NULL;
911 	int r = 0;
912 
913 	if (fwb->start > fwb->end) {
914 		printf("%s: invalid range\n", __func__);
915 		return EINVAL;
916 	}
917 
918 	FW_GLOCK(fc);
919 	STAILQ_FOREACH(tfw, &fc->binds, fclist) {
920 		if (fwb->end < tfw->start)
921 			break;
922 		prev = tfw;
923 	}
924 	if (prev == NULL)
925 		STAILQ_INSERT_HEAD(&fc->binds, fwb, fclist);
926 	else if (prev->end < fwb->start)
927 		STAILQ_INSERT_AFTER(&fc->binds, prev, fwb, fclist);
928 	else {
929 		printf("%s: bind failed\n", __func__);
930 		r = EBUSY;
931 	}
932 	FW_GUNLOCK(fc);
933 	return (r);
934 }
935 
936 /*
937  * To free IEEE1394 address block.
938  */
939 int
940 fw_bindremove(struct firewire_comm *fc, struct fw_bind *fwb)
941 {
942 #if 0
943 	struct fw_xfer *xfer, *next;
944 #endif
945 	struct fw_bind *tfw;
946 	int s;
947 
948 	s = splfw();
949 	FW_GLOCK(fc);
950 	STAILQ_FOREACH(tfw, &fc->binds, fclist)
951 		if (tfw == fwb) {
952 			STAILQ_REMOVE(&fc->binds, fwb, fw_bind, fclist);
953 			goto found;
954 		}
955 
956 	printf("%s: no such binding\n", __func__);
957 	FW_GUNLOCK(fc);
958 	splx(s);
959 	return (1);
960 found:
961 #if 0
962 	/* shall we do this? */
963 	for (xfer = STAILQ_FIRST(&fwb->xferlist); xfer != NULL; xfer = next) {
964 		next = STAILQ_NEXT(xfer, link);
965 		fw_xfer_free(xfer);
966 	}
967 	STAILQ_INIT(&fwb->xferlist);
968 #endif
969 	FW_GUNLOCK(fc);
970 
971 	splx(s);
972 	return 0;
973 }
974 
975 int
976 fw_xferlist_add(struct fw_xferlist *q, struct malloc_type *type,
977     int slen, int rlen, int n,
978     struct firewire_comm *fc, void *sc, void (*hand)(struct fw_xfer *))
979 {
980 	int i, s;
981 	struct fw_xfer *xfer;
982 
983 	for (i = 0; i < n; i++) {
984 		xfer = fw_xfer_alloc_buf(type, slen, rlen);
985 		if (xfer == NULL)
986 			return (n);
987 		xfer->fc = fc;
988 		xfer->sc = sc;
989 		xfer->hand = hand;
990 		s = splfw();
991 		STAILQ_INSERT_TAIL(q, xfer, link);
992 		splx(s);
993 	}
994 	return (n);
995 }
996 
997 void
998 fw_xferlist_remove(struct fw_xferlist *q)
999 {
1000 	struct fw_xfer *xfer, *next;
1001 
1002 	for (xfer = STAILQ_FIRST(q); xfer != NULL; xfer = next) {
1003                 next = STAILQ_NEXT(xfer, link);
1004                 fw_xfer_free_buf(xfer);
1005         }
1006         STAILQ_INIT(q);
1007 }
1008 /*
1009  * dump packet header
1010  */
1011 static void
1012 fw_dump_hdr(struct fw_pkt *fp, char *prefix)
1013 {
1014 	printf("%s: dst=0x%02x tl=0x%02x rt=%d tcode=0x%x pri=0x%x "
1015 	    "src=0x%03x\n", prefix,
1016 	    fp->mode.hdr.dst & 0x3f,
1017 	    fp->mode.hdr.tlrt >> 2, fp->mode.hdr.tlrt & 3,
1018 	    fp->mode.hdr.tcode, fp->mode.hdr.pri,
1019 	    fp->mode.hdr.src);
1020 }
1021 
1022 /*
1023  * To free transaction label.
1024  */
1025 static void
1026 fw_tl_free(struct firewire_comm *fc, struct fw_xfer *xfer)
1027 {
1028 	struct fw_xfer *txfer;
1029 	int s;
1030 
1031 	if (xfer->tl < 0)
1032 		return;
1033 
1034 	s = splfw();
1035 	mtx_lock(&fc->tlabel_lock);
1036 #if 1	/* make sure the label is allocated */
1037 	STAILQ_FOREACH(txfer, &fc->tlabels[xfer->tl], tlabel)
1038 		if(txfer == xfer)
1039 			break;
1040 	if (txfer == NULL) {
1041 		printf("%s: the xfer is not in the queue "
1042 		    "(tlabel=%d, flag=0x%x)\n",
1043 		    __FUNCTION__, xfer->tl, xfer->flag);
1044 		fw_dump_hdr(&xfer->send.hdr, "send");
1045 		fw_dump_hdr(&xfer->recv.hdr, "recv");
1046 		kdb_backtrace();
1047 		mtx_unlock(&fc->tlabel_lock);
1048 		splx(s);
1049 		return;
1050 	}
1051 #endif
1052 
1053 	STAILQ_REMOVE(&fc->tlabels[xfer->tl], xfer, fw_xfer, tlabel);
1054 	mtx_unlock(&fc->tlabel_lock);
1055 	splx(s);
1056 	return;
1057 }
1058 
1059 /*
1060  * To obtain XFER structure by transaction label.
1061  */
1062 static struct fw_xfer *
1063 fw_tl2xfer(struct firewire_comm *fc, int node, int tlabel, int tcode)
1064 {
1065 	struct fw_xfer *xfer;
1066 	int s = splfw();
1067 	int req;
1068 
1069 	mtx_lock(&fc->tlabel_lock);
1070 	STAILQ_FOREACH(xfer, &fc->tlabels[tlabel], tlabel)
1071 		if(xfer->send.hdr.mode.hdr.dst == node) {
1072 			mtx_unlock(&fc->tlabel_lock);
1073 			splx(s);
1074 			KASSERT(xfer->tl == tlabel,
1075 				("xfer->tl 0x%x != 0x%x", xfer->tl, tlabel));
1076 			/* extra sanity check */
1077 			req = xfer->send.hdr.mode.hdr.tcode;
1078 			if (xfer->fc->tcode[req].valid_res != tcode) {
1079 				printf("%s: invalid response tcode "
1080 				    "(0x%x for 0x%x)\n", __FUNCTION__,
1081 				    tcode, req);
1082 				return(NULL);
1083 			}
1084 
1085 			if (firewire_debug > 2)
1086 				printf("fw_tl2xfer: found tl=%d\n", tlabel);
1087 			return(xfer);
1088 		}
1089 	mtx_unlock(&fc->tlabel_lock);
1090 	if (firewire_debug > 1)
1091 		printf("fw_tl2xfer: not found tl=%d\n", tlabel);
1092 	splx(s);
1093 	return(NULL);
1094 }
1095 
1096 /*
1097  * To allocate IEEE1394 XFER structure.
1098  */
1099 struct fw_xfer *
1100 fw_xfer_alloc(struct malloc_type *type)
1101 {
1102 	struct fw_xfer *xfer;
1103 
1104 	xfer = malloc(sizeof(struct fw_xfer), type, M_NOWAIT | M_ZERO);
1105 	if (xfer == NULL)
1106 		return xfer;
1107 
1108 	xfer->malloc = type;
1109 
1110 	return xfer;
1111 }
1112 
1113 struct fw_xfer *
1114 fw_xfer_alloc_buf(struct malloc_type *type, int send_len, int recv_len)
1115 {
1116 	struct fw_xfer *xfer;
1117 
1118 	xfer = fw_xfer_alloc(type);
1119 	if (xfer == NULL)
1120 		return(NULL);
1121 	xfer->send.pay_len = send_len;
1122 	xfer->recv.pay_len = recv_len;
1123 	if (send_len > 0) {
1124 		xfer->send.payload = malloc(send_len, type, M_NOWAIT | M_ZERO);
1125 		if (xfer->send.payload == NULL) {
1126 			fw_xfer_free(xfer);
1127 			return(NULL);
1128 		}
1129 	}
1130 	if (recv_len > 0) {
1131 		xfer->recv.payload = malloc(recv_len, type, M_NOWAIT);
1132 		if (xfer->recv.payload == NULL) {
1133 			if (xfer->send.payload != NULL)
1134 				free(xfer->send.payload, type);
1135 			fw_xfer_free(xfer);
1136 			return(NULL);
1137 		}
1138 	}
1139 	return(xfer);
1140 }
1141 
1142 /*
1143  * IEEE1394 XFER post process.
1144  */
1145 void
1146 fw_xfer_done(struct fw_xfer *xfer)
1147 {
1148 	if (xfer->hand == NULL) {
1149 		printf("hand == NULL\n");
1150 		return;
1151 	}
1152 
1153 	if (xfer->fc == NULL)
1154 		panic("fw_xfer_done: why xfer->fc is NULL?");
1155 
1156 	fw_tl_free(xfer->fc, xfer);
1157 	xfer->hand(xfer);
1158 }
1159 
1160 void
1161 fw_xfer_unload(struct fw_xfer* xfer)
1162 {
1163 	int s;
1164 
1165 	if(xfer == NULL ) return;
1166 	if(xfer->flag & FWXF_INQ){
1167 		printf("fw_xfer_free FWXF_INQ\n");
1168 		s = splfw();
1169 		FW_GLOCK(xfer->fc);
1170 		STAILQ_REMOVE(&xfer->q->q, xfer, fw_xfer, link);
1171 #if 0
1172 		xfer->q->queued --;
1173 #endif
1174 		FW_GUNLOCK(xfer->fc);
1175 		splx(s);
1176 	}
1177 	if (xfer->fc != NULL) {
1178 #if 1
1179 		if(xfer->flag & FWXF_START)
1180 			/*
1181 			 * This could happen if:
1182 			 *  1. We call fwohci_arcv() before fwohci_txd().
1183 			 *  2. firewire_watch() is called.
1184 			 */
1185 			printf("fw_xfer_free FWXF_START\n");
1186 #endif
1187 	}
1188 	xfer->flag = FWXF_INIT;
1189 	xfer->resp = 0;
1190 }
1191 /*
1192  * To free IEEE1394 XFER structure.
1193  */
1194 void
1195 fw_xfer_free_buf( struct fw_xfer* xfer)
1196 {
1197 	if (xfer == NULL) {
1198 		printf("%s: xfer == NULL\n", __func__);
1199 		return;
1200 	}
1201 	fw_xfer_unload(xfer);
1202 	if(xfer->send.payload != NULL){
1203 		free(xfer->send.payload, xfer->malloc);
1204 	}
1205 	if(xfer->recv.payload != NULL){
1206 		free(xfer->recv.payload, xfer->malloc);
1207 	}
1208 	free(xfer, xfer->malloc);
1209 }
1210 
1211 void
1212 fw_xfer_free( 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 	free(xfer, xfer->malloc);
1220 }
1221 
1222 void
1223 fw_asy_callback_free(struct fw_xfer *xfer)
1224 {
1225 #if 0
1226 	printf("asyreq done flag=0x%02x resp=%d\n",
1227 				xfer->flag, xfer->resp);
1228 #endif
1229 	fw_xfer_free(xfer);
1230 }
1231 
1232 /*
1233  * To configure PHY.
1234  */
1235 static void
1236 fw_phy_config(struct firewire_comm *fc, int root_node, int gap_count)
1237 {
1238 	struct fw_xfer *xfer;
1239 	struct fw_pkt *fp;
1240 
1241 	fc->status = FWBUSPHYCONF;
1242 
1243 	xfer = fw_xfer_alloc(M_FWXFER);
1244 	if (xfer == NULL)
1245 		return;
1246 	xfer->fc = fc;
1247 	xfer->hand = fw_asy_callback_free;
1248 
1249 	fp = &xfer->send.hdr;
1250 	fp->mode.ld[1] = 0;
1251 	if (root_node >= 0)
1252 		fp->mode.ld[1] |= (root_node & 0x3f) << 24 | 1 << 23;
1253 	if (gap_count >= 0)
1254 		fp->mode.ld[1] |= 1 << 22 | (gap_count & 0x3f) << 16;
1255 	fp->mode.ld[2] = ~fp->mode.ld[1];
1256 /* XXX Dangerous, how to pass PHY packet to device driver */
1257 	fp->mode.common.tcode |= FWTCODE_PHY;
1258 
1259 	if (firewire_debug)
1260 		printf("send phy_config root_node=%d gap_count=%d\n",
1261 						root_node, gap_count);
1262 	fw_asyreq(fc, -1, xfer);
1263 }
1264 
1265 #if 0
1266 /*
1267  * Dump self ID.
1268  */
1269 static void
1270 fw_print_sid(uint32_t sid)
1271 {
1272 	union fw_self_id *s;
1273 	s = (union fw_self_id *) &sid;
1274 	printf("node:%d link:%d gap:%d spd:%d del:%d con:%d pwr:%d"
1275 		" p0:%d p1:%d p2:%d i:%d m:%d\n",
1276 		s->p0.phy_id, s->p0.link_active, s->p0.gap_count,
1277 		s->p0.phy_speed, s->p0.phy_delay, s->p0.contender,
1278 		s->p0.power_class, s->p0.port0, s->p0.port1,
1279 		s->p0.port2, s->p0.initiated_reset, s->p0.more_packets);
1280 }
1281 #endif
1282 
1283 /*
1284  * To receive self ID.
1285  */
1286 void fw_sidrcv(struct firewire_comm* fc, uint32_t *sid, u_int len)
1287 {
1288 	uint32_t *p;
1289 	union fw_self_id *self_id;
1290 	u_int i, j, node, c_port = 0, i_branch = 0;
1291 
1292 	fc->sid_cnt = len /(sizeof(uint32_t) * 2);
1293 	fc->max_node = fc->nodeid & 0x3f;
1294 	CSRARC(fc, NODE_IDS) = ((uint32_t)fc->nodeid) << 16;
1295 	fc->status = FWBUSCYMELECT;
1296 	fc->topology_map->crc_len = 2;
1297 	fc->topology_map->generation ++;
1298 	fc->topology_map->self_id_count = 0;
1299 	fc->topology_map->node_count = 0;
1300 	fc->speed_map->generation ++;
1301 	fc->speed_map->crc_len = 1 + (64*64 + 3) / 4;
1302 	self_id = &fc->topology_map->self_id[0];
1303 	for(i = 0; i < fc->sid_cnt; i ++){
1304 		if (sid[1] != ~sid[0]) {
1305 			printf("fw_sidrcv: invalid self-id packet\n");
1306 			sid += 2;
1307 			continue;
1308 		}
1309 		*self_id = *((union fw_self_id *)sid);
1310 		fc->topology_map->crc_len++;
1311 		if(self_id->p0.sequel == 0){
1312 			fc->topology_map->node_count ++;
1313 			c_port = 0;
1314 #if 0
1315 			fw_print_sid(sid[0]);
1316 #endif
1317 			node = self_id->p0.phy_id;
1318 			if(fc->max_node < node){
1319 				fc->max_node = self_id->p0.phy_id;
1320 			}
1321 			/* XXX I'm not sure this is the right speed_map */
1322 			fc->speed_map->speed[node][node]
1323 					= self_id->p0.phy_speed;
1324 			for (j = 0; j < node; j ++) {
1325 				fc->speed_map->speed[j][node]
1326 					= fc->speed_map->speed[node][j]
1327 					= min(fc->speed_map->speed[j][j],
1328 							self_id->p0.phy_speed);
1329 			}
1330 			if ((fc->irm == -1 || self_id->p0.phy_id > fc->irm) &&
1331 			  (self_id->p0.link_active && self_id->p0.contender)) {
1332 				fc->irm = self_id->p0.phy_id;
1333 			}
1334 			if(self_id->p0.port0 >= 0x2){
1335 				c_port++;
1336 			}
1337 			if(self_id->p0.port1 >= 0x2){
1338 				c_port++;
1339 			}
1340 			if(self_id->p0.port2 >= 0x2){
1341 				c_port++;
1342 			}
1343 		}
1344 		if(c_port > 2){
1345 			i_branch += (c_port - 2);
1346 		}
1347 		sid += 2;
1348 		self_id++;
1349 		fc->topology_map->self_id_count ++;
1350 	}
1351 	device_printf(fc->bdev, "%d nodes", fc->max_node + 1);
1352 	/* CRC */
1353 	fc->topology_map->crc = fw_crc16(
1354 			(uint32_t *)&fc->topology_map->generation,
1355 			fc->topology_map->crc_len * 4);
1356 	fc->speed_map->crc = fw_crc16(
1357 			(uint32_t *)&fc->speed_map->generation,
1358 			fc->speed_map->crc_len * 4);
1359 	/* byteswap and copy to CSR */
1360 	p = (uint32_t *)fc->topology_map;
1361 	for (i = 0; i <= fc->topology_map->crc_len; i++)
1362 		CSRARC(fc, TOPO_MAP + i * 4) = htonl(*p++);
1363 	p = (uint32_t *)fc->speed_map;
1364 	CSRARC(fc, SPED_MAP) = htonl(*p++);
1365 	CSRARC(fc, SPED_MAP + 4) = htonl(*p++);
1366 	/* don't byte-swap uint8_t array */
1367 	bcopy(p, &CSRARC(fc, SPED_MAP + 8), (fc->speed_map->crc_len - 1)*4);
1368 
1369 	fc->max_hop = fc->max_node - i_branch;
1370 	printf(", maxhop <= %d", fc->max_hop);
1371 
1372 	if(fc->irm == -1 ){
1373 		printf(", Not found IRM capable node");
1374 	}else{
1375 		printf(", cable IRM = %d", fc->irm);
1376 		if (fc->irm == fc->nodeid)
1377 			printf(" (me)");
1378 	}
1379 	printf("\n");
1380 
1381 	if (try_bmr && (fc->irm != -1) && (CSRARC(fc, BUS_MGR_ID) == 0x3f)) {
1382 		if (fc->irm == fc->nodeid) {
1383 			fc->status = FWBUSMGRDONE;
1384 			CSRARC(fc, BUS_MGR_ID) = fc->set_bmr(fc, fc->irm);
1385 			fw_bmr(fc);
1386 		} else {
1387 			fc->status = FWBUSMGRELECT;
1388 			callout_reset(&fc->bmr_callout, hz/8,
1389 				(void *)fw_try_bmr, (void *)fc);
1390 		}
1391 	} else
1392 		fc->status = FWBUSMGRDONE;
1393 
1394 	callout_reset(&fc->busprobe_callout, hz/4,
1395 			(void *)fw_bus_probe, (void *)fc);
1396 }
1397 
1398 /*
1399  * To probe devices on the IEEE1394 bus.
1400  */
1401 static void
1402 fw_bus_probe(struct firewire_comm *fc)
1403 {
1404 	int s;
1405 	struct fw_device *fwdev;
1406 
1407 	s = splfw();
1408 	fc->status = FWBUSEXPLORE;
1409 
1410 	/* Invalidate all devices, just after bus reset. */
1411 	STAILQ_FOREACH(fwdev, &fc->devices, link)
1412 		if (fwdev->status != FWDEVINVAL) {
1413 			fwdev->status = FWDEVINVAL;
1414 			fwdev->rcnt = 0;
1415 		}
1416 	splx(s);
1417 
1418 	wakeup((void *)fc);
1419 }
1420 
1421 static int
1422 fw_explore_read_quads(struct fw_device *fwdev, int offset,
1423     uint32_t *quad, int n)
1424 {
1425 	struct fw_xfer *xfer;
1426 	uint32_t tmp;
1427 	int i, error;
1428 
1429 	for (i = 0; i < n; i ++, offset += sizeof(uint32_t)) {
1430 		xfer = fwmem_read_quad(fwdev, NULL, -1,
1431 		    0xffff, 0xf0000000 | offset, (void *)&tmp,
1432 		    fw_xferwake);
1433 		if (xfer == NULL)
1434 			return (-1);
1435 		fw_xferwait(xfer);
1436 
1437 		if (xfer->resp == 0)
1438 			quad[i] = ntohl(tmp);
1439 
1440 		error = xfer->resp;
1441 		fw_xfer_free(xfer);
1442 		if (error)
1443 			return (error);
1444 	}
1445 	return (0);
1446 }
1447 
1448 
1449 static int
1450 fw_explore_csrblock(struct fw_device *fwdev, int offset, int recur)
1451 {
1452 	int err, i, off;
1453 	struct csrdirectory *dir;
1454 	struct csrreg *reg;
1455 
1456 	dir = (struct csrdirectory *)&fwdev->csrrom[offset/sizeof(uint32_t)];
1457 	err = fw_explore_read_quads(fwdev, CSRROMOFF + offset,
1458 	    (uint32_t *)dir, 1);
1459 	if (err)
1460 		return (-1);
1461 
1462 	offset += sizeof(uint32_t);
1463 	reg = (struct csrreg *)&fwdev->csrrom[offset/sizeof(uint32_t)];
1464 	err = fw_explore_read_quads(fwdev, CSRROMOFF + offset,
1465 	    (uint32_t *)reg, dir->crc_len);
1466 	if (err)
1467 		return (-1);
1468 
1469 	/* XXX check CRC */
1470 
1471 	off = CSRROMOFF + offset + sizeof(uint32_t) * (dir->crc_len - 1);
1472 	if (fwdev->rommax < off)
1473 		fwdev->rommax = off;
1474 
1475 	if (recur == 0)
1476 		return (0);
1477 
1478 	for (i = 0; i < dir->crc_len; i ++, offset += sizeof(uint32_t)) {
1479 		if ((reg[i].key & CSRTYPE_MASK) == CSRTYPE_D)
1480 			recur = 1;
1481 		else if ((reg[i].key & CSRTYPE_MASK) == CSRTYPE_L)
1482 			recur = 0;
1483 		else
1484 			continue;
1485 
1486 		off = offset + reg[i].val * sizeof(uint32_t);
1487 		if (off > CROMSIZE) {
1488 			printf("%s: invalid offset %d\n", __FUNCTION__, off);
1489 			return(-1);
1490 		}
1491 		err = fw_explore_csrblock(fwdev, off, recur);
1492 		if (err)
1493 			return (-1);
1494 	}
1495 	return (0);
1496 }
1497 
1498 static int
1499 fw_explore_node(struct fw_device *dfwdev)
1500 {
1501 	struct firewire_comm *fc;
1502 	struct fw_device *fwdev, *pfwdev, *tfwdev;
1503 	uint32_t *csr;
1504 	struct csrhdr *hdr;
1505 	struct bus_info *binfo;
1506 	int err, node, spd;
1507 
1508 	fc = dfwdev->fc;
1509 	csr = dfwdev->csrrom;
1510 	node = dfwdev->dst;
1511 
1512 	/* First quad */
1513 	err = fw_explore_read_quads(dfwdev, CSRROMOFF, &csr[0], 1);
1514 	if (err)
1515 		return (-1);
1516 	hdr = (struct csrhdr *)&csr[0];
1517 	if (hdr->info_len != 4) {
1518 		if (firewire_debug)
1519 			printf("node%d: wrong bus info len(%d)\n",
1520 			    node, hdr->info_len);
1521 		return (-1);
1522 	}
1523 
1524 	/* bus info */
1525 	err = fw_explore_read_quads(dfwdev, CSRROMOFF + 0x04, &csr[1], 4);
1526 	if (err)
1527 		return (-1);
1528 	binfo = (struct bus_info *)&csr[1];
1529 	if (binfo->bus_name != CSR_BUS_NAME_IEEE1394) {
1530 		if (firewire_debug)
1531 			printf("node%d: invalid bus name 0x%08x\n",
1532 			    node, binfo->bus_name);
1533 		return (-1);
1534 	}
1535 	spd = fc->speed_map->speed[fc->nodeid][node];
1536 	STAILQ_FOREACH(fwdev, &fc->devices, link)
1537 		if (FW_EUI64_EQUAL(fwdev->eui, binfo->eui64))
1538 			break;
1539 	if (fwdev == NULL) {
1540 		/* new device */
1541 		fwdev = malloc(sizeof(struct fw_device), M_FW,
1542 						M_NOWAIT | M_ZERO);
1543 		if (fwdev == NULL) {
1544 			if (firewire_debug)
1545 				printf("node%d: no memory\n", node);
1546 			return (-1);
1547 		}
1548 		fwdev->fc = fc;
1549 		fwdev->eui = binfo->eui64;
1550 		/* inesrt into sorted fwdev list */
1551 		pfwdev = NULL;
1552 		STAILQ_FOREACH(tfwdev, &fc->devices, link) {
1553 			if (tfwdev->eui.hi > fwdev->eui.hi ||
1554 				(tfwdev->eui.hi == fwdev->eui.hi &&
1555 				tfwdev->eui.lo > fwdev->eui.lo))
1556 				break;
1557 			pfwdev = tfwdev;
1558 		}
1559 		if (pfwdev == NULL)
1560 			STAILQ_INSERT_HEAD(&fc->devices, fwdev, link);
1561 		else
1562 			STAILQ_INSERT_AFTER(&fc->devices, pfwdev, fwdev, link);
1563 
1564 		device_printf(fc->bdev, "New %s device ID:%08x%08x\n",
1565 		    linkspeed[spd],
1566 		    fwdev->eui.hi, fwdev->eui.lo);
1567 	}
1568 	fwdev->dst = node;
1569 	fwdev->status = FWDEVINIT;
1570 	fwdev->speed = spd;
1571 
1572 	/* unchanged ? */
1573 	if (bcmp(&csr[0], &fwdev->csrrom[0], sizeof(uint32_t) * 5) == 0) {
1574 		if (firewire_debug)
1575 			device_printf(fc->dev, "node%d: crom unchanged\n", node);
1576 		return (0);
1577 	}
1578 
1579 	bzero(&fwdev->csrrom[0], CROMSIZE);
1580 
1581 	/* copy first quad and bus info block */
1582 	bcopy(&csr[0], &fwdev->csrrom[0], sizeof(uint32_t) * 5);
1583 	fwdev->rommax = CSRROMOFF + sizeof(uint32_t) * 4;
1584 
1585 	err = fw_explore_csrblock(fwdev, 0x14, 1); /* root directory */
1586 
1587 	if (err) {
1588 		fwdev->status = FWDEVINVAL;
1589 		fwdev->csrrom[0] = 0;
1590 	}
1591 	return (err);
1592 
1593 }
1594 
1595 /*
1596  * Find the self_id packet for a node, ignoring sequels.
1597  */
1598 static union fw_self_id *
1599 fw_find_self_id(struct firewire_comm *fc, int node)
1600 {
1601 	uint32_t i;
1602 	union fw_self_id *s;
1603 
1604 	for (i = 0; i < fc->topology_map->self_id_count; i++) {
1605 		s = &fc->topology_map->self_id[i];
1606 		if (s->p0.sequel)
1607 			continue;
1608 		if (s->p0.phy_id == node)
1609 			return s;
1610 	}
1611 	return 0;
1612 }
1613 
1614 static void
1615 fw_explore(struct firewire_comm *fc)
1616 {
1617 	int node, err, s, i, todo, todo2, trys;
1618 	char nodes[63];
1619 	struct fw_device dfwdev;
1620 	union fw_self_id *fwsid;
1621 
1622 	todo = 0;
1623 	/* setup dummy fwdev */
1624 	dfwdev.fc = fc;
1625 	dfwdev.speed = 0;
1626 	dfwdev.maxrec = 8; /* 512 */
1627 	dfwdev.status = FWDEVINIT;
1628 
1629 	for (node = 0; node <= fc->max_node; node ++) {
1630 		/* We don't probe myself and linkdown nodes */
1631 		if (node == fc->nodeid)
1632 			continue;
1633 		fwsid = fw_find_self_id(fc, node);
1634 		if (!fwsid || !fwsid->p0.link_active) {
1635 			if (firewire_debug)
1636 				printf("node%d: link down\n", node);
1637 			continue;
1638 		}
1639 		nodes[todo++] = node;
1640 	}
1641 
1642 	s = splfw();
1643 	for (trys = 0; todo > 0 && trys < 3; trys ++) {
1644 		todo2 = 0;
1645 		for (i = 0; i < todo; i ++) {
1646 			dfwdev.dst = nodes[i];
1647 			err = fw_explore_node(&dfwdev);
1648 			if (err)
1649 				nodes[todo2++] = nodes[i];
1650 			if (firewire_debug)
1651 				printf("%s: node %d, err = %d\n",
1652 					__FUNCTION__, node, err);
1653 		}
1654 		todo = todo2;
1655 	}
1656 	splx(s);
1657 }
1658 
1659 
1660 static void
1661 fw_bus_probe_thread(void *arg)
1662 {
1663 	struct firewire_comm *fc;
1664 
1665 	fc = (struct firewire_comm *)arg;
1666 
1667 	mtx_lock(&fc->wait_lock);
1668 	while (fc->status != FWBUSDETACH) {
1669 		if (fc->status == FWBUSEXPLORE) {
1670 			mtx_unlock(&fc->wait_lock);
1671 			fw_explore(fc);
1672 			fc->status = FWBUSEXPDONE;
1673 			if (firewire_debug)
1674 				printf("bus_explore done\n");
1675 			fw_attach_dev(fc);
1676 			mtx_lock(&fc->wait_lock);
1677 		}
1678 		msleep((void *)fc, &fc->wait_lock, PWAIT|PCATCH, "-", 0);
1679 	}
1680 	mtx_unlock(&fc->wait_lock);
1681 	kproc_exit(0);
1682 }
1683 
1684 /*
1685  * To attach sub-devices layer onto IEEE1394 bus.
1686  */
1687 static void
1688 fw_attach_dev(struct firewire_comm *fc)
1689 {
1690 	struct fw_device *fwdev, *next;
1691 	int i, err;
1692 	device_t *devlistp;
1693 	int devcnt;
1694 	struct firewire_dev_comm *fdc;
1695 
1696 	for (fwdev = STAILQ_FIRST(&fc->devices); fwdev != NULL; fwdev = next) {
1697 		next = STAILQ_NEXT(fwdev, link);
1698 		if (fwdev->status == FWDEVINIT) {
1699 			fwdev->status = FWDEVATTACHED;
1700 		} else if (fwdev->status == FWDEVINVAL) {
1701 			fwdev->rcnt ++;
1702 			if (fwdev->rcnt > hold_count) {
1703 				/*
1704 				 * Remove devices which have not been seen
1705 				 * for a while.
1706 				 */
1707 				STAILQ_REMOVE(&fc->devices, fwdev, fw_device,
1708 				    link);
1709 				free(fwdev, M_FW);
1710 			}
1711 		}
1712 	}
1713 
1714 	err = device_get_children(fc->bdev, &devlistp, &devcnt);
1715 	if( err != 0 )
1716 		return;
1717 	for( i = 0 ; i < devcnt ; i++){
1718 		if (device_get_state(devlistp[i]) >= DS_ATTACHED)  {
1719 			fdc = device_get_softc(devlistp[i]);
1720 			if (fdc->post_explore != NULL)
1721 				fdc->post_explore(fdc);
1722 		}
1723 	}
1724 	free(devlistp, M_TEMP);
1725 
1726 	return;
1727 }
1728 
1729 /*
1730  * To allocate unique transaction label.
1731  */
1732 static int
1733 fw_get_tlabel(struct firewire_comm *fc, struct fw_xfer *xfer)
1734 {
1735 	u_int dst, new_tlabel;
1736 	struct fw_xfer *txfer;
1737 	int s;
1738 
1739 	dst = xfer->send.hdr.mode.hdr.dst & 0x3f;
1740 	s = splfw();
1741 	mtx_lock(&fc->tlabel_lock);
1742 	new_tlabel = (fc->last_tlabel[dst] + 1) & 0x3f;
1743 	STAILQ_FOREACH(txfer, &fc->tlabels[new_tlabel], tlabel)
1744 		if ((txfer->send.hdr.mode.hdr.dst & 0x3f) == dst)
1745 				break;
1746 	if(txfer == NULL) {
1747 		fc->last_tlabel[dst] = new_tlabel;
1748 		STAILQ_INSERT_TAIL(&fc->tlabels[new_tlabel], xfer, tlabel);
1749 		mtx_unlock(&fc->tlabel_lock);
1750 		splx(s);
1751 		xfer->tl = new_tlabel;
1752 		xfer->send.hdr.mode.hdr.tlrt = new_tlabel << 2;
1753 		if (firewire_debug > 1)
1754 			printf("fw_get_tlabel: dst=%d tl=%d\n", dst, new_tlabel);
1755 		return (new_tlabel);
1756 	}
1757 	mtx_unlock(&fc->tlabel_lock);
1758 	splx(s);
1759 
1760 	if (firewire_debug > 1)
1761 		printf("fw_get_tlabel: no free tlabel\n");
1762 	return (-1);
1763 }
1764 
1765 static void
1766 fw_rcv_copy(struct fw_rcv_buf *rb)
1767 {
1768 	struct fw_pkt *pkt;
1769 	u_char *p;
1770 	struct tcode_info *tinfo;
1771 	u_int res, i, len, plen;
1772 
1773 	rb->xfer->recv.spd = rb->spd;
1774 
1775 	pkt = (struct fw_pkt *)rb->vec->iov_base;
1776 	tinfo = &rb->fc->tcode[pkt->mode.hdr.tcode];
1777 
1778 	/* Copy header */
1779 	p = (u_char *)&rb->xfer->recv.hdr;
1780 	bcopy(rb->vec->iov_base, p, tinfo->hdr_len);
1781 	rb->vec->iov_base = (u_char *)rb->vec->iov_base + tinfo->hdr_len;
1782 	rb->vec->iov_len -= tinfo->hdr_len;
1783 
1784 	/* Copy payload */
1785 	p = (u_char *)rb->xfer->recv.payload;
1786 	res = rb->xfer->recv.pay_len;
1787 
1788 	/* special handling for RRESQ */
1789 	if (pkt->mode.hdr.tcode == FWTCODE_RRESQ &&
1790 	    p != NULL && res >= sizeof(uint32_t)) {
1791 		*(uint32_t *)p = pkt->mode.rresq.data;
1792 		rb->xfer->recv.pay_len = sizeof(uint32_t);
1793 		return;
1794 	}
1795 
1796 	if ((tinfo->flag & FWTI_BLOCK_ASY) == 0)
1797 		return;
1798 
1799 	plen = pkt->mode.rresb.len;
1800 
1801 	for (i = 0; i < rb->nvec; i++, rb->vec++) {
1802 		len = MIN(rb->vec->iov_len, plen);
1803 		if (res < len) {
1804 			printf("rcv buffer(%d) is %d bytes short.\n",
1805 			    rb->xfer->recv.pay_len, len - res);
1806 			len = res;
1807 		}
1808 		bcopy(rb->vec->iov_base, p, len);
1809 		p += len;
1810 		res -= len;
1811 		plen -= len;
1812 		if (res == 0 || plen == 0)
1813 			break;
1814 	}
1815 	rb->xfer->recv.pay_len -= res;
1816 
1817 }
1818 
1819 /*
1820  * Generic packet receiving process.
1821  */
1822 void
1823 fw_rcv(struct fw_rcv_buf *rb)
1824 {
1825 	struct fw_pkt *fp, *resfp;
1826 	struct fw_bind *bind;
1827 	int tcode;
1828 	int i, len, oldstate;
1829 #if 0
1830 	{
1831 		uint32_t *qld;
1832 		int i;
1833 		qld = (uint32_t *)buf;
1834 		printf("spd %d len:%d\n", spd, len);
1835 		for( i = 0 ; i <= len && i < 32; i+= 4){
1836 			printf("0x%08x ", ntohl(qld[i/4]));
1837 			if((i % 16) == 15) printf("\n");
1838 		}
1839 		if((i % 16) != 15) printf("\n");
1840 	}
1841 #endif
1842 	fp = (struct fw_pkt *)rb->vec[0].iov_base;
1843 	tcode = fp->mode.common.tcode;
1844 	switch (tcode) {
1845 	case FWTCODE_WRES:
1846 	case FWTCODE_RRESQ:
1847 	case FWTCODE_RRESB:
1848 	case FWTCODE_LRES:
1849 		rb->xfer = fw_tl2xfer(rb->fc, fp->mode.hdr.src,
1850 				fp->mode.hdr.tlrt >> 2, fp->mode.hdr.tcode);
1851 		if(rb->xfer == NULL) {
1852 			printf("fw_rcv: unknown response "
1853 			    "%s(%x) src=0x%x tl=0x%x rt=%d data=0x%x\n",
1854 			    tcode_str[tcode], tcode,
1855 			    fp->mode.hdr.src,
1856 			    fp->mode.hdr.tlrt >> 2,
1857 			    fp->mode.hdr.tlrt & 3,
1858 			    fp->mode.rresq.data);
1859 #if 0
1860 			printf("try ad-hoc work around!!\n");
1861 			rb->xfer = fw_tl2xfer(rb->fc, fp->mode.hdr.src,
1862 					(fp->mode.hdr.tlrt >> 2)^3);
1863 			if (rb->xfer == NULL) {
1864 				printf("no use...\n");
1865 				return;
1866 			}
1867 #else
1868 			return;
1869 #endif
1870 		}
1871 		fw_rcv_copy(rb);
1872 		if (rb->xfer->recv.hdr.mode.wres.rtcode != RESP_CMP)
1873 			rb->xfer->resp = EIO;
1874 		else
1875 			rb->xfer->resp = 0;
1876 		/* make sure the packet is drained in AT queue */
1877 		oldstate = rb->xfer->flag;
1878 		rb->xfer->flag = FWXF_RCVD;
1879 		switch (oldstate) {
1880 		case FWXF_SENT:
1881 			fw_xfer_done(rb->xfer);
1882 			break;
1883 		case FWXF_START:
1884 #if 0
1885 			if (firewire_debug)
1886 				printf("not sent yet tl=%x\n", rb->xfer->tl);
1887 #endif
1888 			break;
1889 		default:
1890 			printf("unexpected flag 0x%02x\n", rb->xfer->flag);
1891 		}
1892 		return;
1893 	case FWTCODE_WREQQ:
1894 	case FWTCODE_WREQB:
1895 	case FWTCODE_RREQQ:
1896 	case FWTCODE_RREQB:
1897 	case FWTCODE_LREQ:
1898 		bind = fw_bindlookup(rb->fc, fp->mode.rreqq.dest_hi,
1899 			fp->mode.rreqq.dest_lo);
1900 		if(bind == NULL){
1901 			printf("Unknown service addr 0x%04x:0x%08x %s(%x)"
1902 #if defined(__DragonFly__) || __FreeBSD_version < 500000
1903 			    " src=0x%x data=%lx\n",
1904 #else
1905 			    " src=0x%x data=%x\n",
1906 #endif
1907 			    fp->mode.wreqq.dest_hi, fp->mode.wreqq.dest_lo,
1908 			    tcode_str[tcode], tcode,
1909 			    fp->mode.hdr.src, ntohl(fp->mode.wreqq.data));
1910 			if (rb->fc->status == FWBUSINIT) {
1911 				printf("fw_rcv: cannot respond(bus reset)!\n");
1912 				return;
1913 			}
1914 			rb->xfer = fw_xfer_alloc(M_FWXFER);
1915 			if(rb->xfer == NULL){
1916 				return;
1917 			}
1918 			rb->xfer->send.spd = rb->spd;
1919 			rb->xfer->send.pay_len = 0;
1920 			resfp = &rb->xfer->send.hdr;
1921 			switch (tcode) {
1922 			case FWTCODE_WREQQ:
1923 			case FWTCODE_WREQB:
1924 				resfp->mode.hdr.tcode = FWTCODE_WRES;
1925 				break;
1926 			case FWTCODE_RREQQ:
1927 				resfp->mode.hdr.tcode = FWTCODE_RRESQ;
1928 				break;
1929 			case FWTCODE_RREQB:
1930 				resfp->mode.hdr.tcode = FWTCODE_RRESB;
1931 				break;
1932 			case FWTCODE_LREQ:
1933 				resfp->mode.hdr.tcode = FWTCODE_LRES;
1934 				break;
1935 			}
1936 			resfp->mode.hdr.dst = fp->mode.hdr.src;
1937 			resfp->mode.hdr.tlrt = fp->mode.hdr.tlrt;
1938 			resfp->mode.hdr.pri = fp->mode.hdr.pri;
1939 			resfp->mode.rresb.rtcode = RESP_ADDRESS_ERROR;
1940 			resfp->mode.rresb.extcode = 0;
1941 			resfp->mode.rresb.len = 0;
1942 /*
1943 			rb->xfer->hand = fw_xferwake;
1944 */
1945 			rb->xfer->hand = fw_xfer_free;
1946 			if(fw_asyreq(rb->fc, -1, rb->xfer)){
1947 				fw_xfer_free(rb->xfer);
1948 				return;
1949 			}
1950 			return;
1951 		}
1952 		len = 0;
1953 		for (i = 0; i < rb->nvec; i ++)
1954 			len += rb->vec[i].iov_len;
1955 		rb->xfer = STAILQ_FIRST(&bind->xferlist);
1956 		if (rb->xfer == NULL) {
1957 #if 1
1958 			printf("Discard a packet for this bind.\n");
1959 #endif
1960 			return;
1961 		}
1962 		STAILQ_REMOVE_HEAD(&bind->xferlist, link);
1963 		fw_rcv_copy(rb);
1964 		rb->xfer->hand(rb->xfer);
1965 		return;
1966 #if 0 /* shouldn't happen ?? or for GASP */
1967 	case FWTCODE_STREAM:
1968 	{
1969 		struct fw_xferq *xferq;
1970 
1971 		xferq = rb->fc->ir[sub];
1972 #if 0
1973 		printf("stream rcv dma %d len %d off %d spd %d\n",
1974 			sub, len, off, spd);
1975 #endif
1976 		if(xferq->queued >= xferq->maxq) {
1977 			printf("receive queue is full\n");
1978 			return;
1979 		}
1980 		/* XXX get xfer from xfer queue, we don't need copy for
1981 			per packet mode */
1982 		rb->xfer = fw_xfer_alloc_buf(M_FWXFER, 0, /* XXX */
1983 						vec[0].iov_len);
1984 		if (rb->xfer == NULL)
1985 			return;
1986 		fw_rcv_copy(rb)
1987 		s = splfw();
1988 		xferq->queued++;
1989 		STAILQ_INSERT_TAIL(&xferq->q, rb->xfer, link);
1990 		splx(s);
1991 		sc = device_get_softc(rb->fc->bdev);
1992 #if defined(__DragonFly__) || __FreeBSD_version < 500000
1993 		if (&xferq->rsel.si_pid != 0)
1994 #else
1995 		if (SEL_WAITING(&xferq->rsel))
1996 #endif
1997 			selwakeuppri(&xferq->rsel, FWPRI);
1998 		if (xferq->flag & FWXFERQ_WAKEUP) {
1999 			xferq->flag &= ~FWXFERQ_WAKEUP;
2000 			wakeup((caddr_t)xferq);
2001 		}
2002 		if (xferq->flag & FWXFERQ_HANDLER) {
2003 			xferq->hand(xferq);
2004 		}
2005 		return;
2006 		break;
2007 	}
2008 #endif
2009 	default:
2010 		printf("fw_rcv: unknow tcode %d\n", tcode);
2011 		break;
2012 	}
2013 }
2014 
2015 /*
2016  * Post process for Bus Manager election process.
2017  */
2018 static void
2019 fw_try_bmr_callback(struct fw_xfer *xfer)
2020 {
2021 	struct firewire_comm *fc;
2022 	int bmr;
2023 
2024 	if (xfer == NULL)
2025 		return;
2026 	fc = xfer->fc;
2027 	if (xfer->resp != 0)
2028 		goto error;
2029 	if (xfer->recv.payload == NULL)
2030 		goto error;
2031 	if (xfer->recv.hdr.mode.lres.rtcode != FWRCODE_COMPLETE)
2032 		goto error;
2033 
2034 	bmr = ntohl(xfer->recv.payload[0]);
2035 	if (bmr == 0x3f)
2036 		bmr = fc->nodeid;
2037 
2038 	CSRARC(fc, BUS_MGR_ID) = fc->set_bmr(fc, bmr & 0x3f);
2039 	fw_xfer_free_buf(xfer);
2040 	fw_bmr(fc);
2041 	return;
2042 
2043 error:
2044 	device_printf(fc->bdev, "bus manager election failed\n");
2045 	fw_xfer_free_buf(xfer);
2046 }
2047 
2048 
2049 /*
2050  * To candidate Bus Manager election process.
2051  */
2052 static void
2053 fw_try_bmr(void *arg)
2054 {
2055 	struct fw_xfer *xfer;
2056 	struct firewire_comm *fc = (struct firewire_comm *)arg;
2057 	struct fw_pkt *fp;
2058 	int err = 0;
2059 
2060 	xfer = fw_xfer_alloc_buf(M_FWXFER, 8, 4);
2061 	if(xfer == NULL){
2062 		return;
2063 	}
2064 	xfer->send.spd = 0;
2065 	fc->status = FWBUSMGRELECT;
2066 
2067 	fp = &xfer->send.hdr;
2068 	fp->mode.lreq.dest_hi = 0xffff;
2069 	fp->mode.lreq.tlrt = 0;
2070 	fp->mode.lreq.tcode = FWTCODE_LREQ;
2071 	fp->mode.lreq.pri = 0;
2072 	fp->mode.lreq.src = 0;
2073 	fp->mode.lreq.len = 8;
2074 	fp->mode.lreq.extcode = EXTCODE_CMP_SWAP;
2075 	fp->mode.lreq.dst = FWLOCALBUS | fc->irm;
2076 	fp->mode.lreq.dest_lo = 0xf0000000 | BUS_MGR_ID;
2077 	xfer->send.payload[0] = htonl(0x3f);
2078 	xfer->send.payload[1] = htonl(fc->nodeid);
2079 	xfer->hand = fw_try_bmr_callback;
2080 
2081 	err = fw_asyreq(fc, -1, xfer);
2082 	if(err){
2083 		fw_xfer_free_buf(xfer);
2084 		return;
2085 	}
2086 	return;
2087 }
2088 
2089 #ifdef FW_VMACCESS
2090 /*
2091  * Software implementation for physical memory block access.
2092  * XXX:Too slow, usef for debug purpose only.
2093  */
2094 static void
2095 fw_vmaccess(struct fw_xfer *xfer){
2096 	struct fw_pkt *rfp, *sfp = NULL;
2097 	uint32_t *ld = (uint32_t *)xfer->recv.buf;
2098 
2099 	printf("vmaccess spd:%2x len:%03x data:%08x %08x %08x %08x\n",
2100 			xfer->spd, xfer->recv.len, ntohl(ld[0]), ntohl(ld[1]), ntohl(ld[2]), ntohl(ld[3]));
2101 	printf("vmaccess          data:%08x %08x %08x %08x\n", ntohl(ld[4]), ntohl(ld[5]), ntohl(ld[6]), ntohl(ld[7]));
2102 	if(xfer->resp != 0){
2103 		fw_xfer_free( xfer);
2104 		return;
2105 	}
2106 	if(xfer->recv.buf == NULL){
2107 		fw_xfer_free( xfer);
2108 		return;
2109 	}
2110 	rfp = (struct fw_pkt *)xfer->recv.buf;
2111 	switch(rfp->mode.hdr.tcode){
2112 		/* XXX need fix for 64bit arch */
2113 		case FWTCODE_WREQB:
2114 			xfer->send.buf = malloc(12, M_FW, M_NOWAIT);
2115 			xfer->send.len = 12;
2116 			sfp = (struct fw_pkt *)xfer->send.buf;
2117 			bcopy(rfp->mode.wreqb.payload,
2118 				(caddr_t)ntohl(rfp->mode.wreqb.dest_lo), ntohs(rfp->mode.wreqb.len));
2119 			sfp->mode.wres.tcode = FWTCODE_WRES;
2120 			sfp->mode.wres.rtcode = 0;
2121 			break;
2122 		case FWTCODE_WREQQ:
2123 			xfer->send.buf = malloc(12, M_FW, M_NOWAIT);
2124 			xfer->send.len = 12;
2125 			sfp->mode.wres.tcode = FWTCODE_WRES;
2126 			*((uint32_t *)(ntohl(rfp->mode.wreqb.dest_lo))) = rfp->mode.wreqq.data;
2127 			sfp->mode.wres.rtcode = 0;
2128 			break;
2129 		case FWTCODE_RREQB:
2130 			xfer->send.buf = malloc(16 + rfp->mode.rreqb.len, M_FW, M_NOWAIT);
2131 			xfer->send.len = 16 + ntohs(rfp->mode.rreqb.len);
2132 			sfp = (struct fw_pkt *)xfer->send.buf;
2133 			bcopy((caddr_t)ntohl(rfp->mode.rreqb.dest_lo),
2134 				sfp->mode.rresb.payload, (uint16_t)ntohs(rfp->mode.rreqb.len));
2135 			sfp->mode.rresb.tcode = FWTCODE_RRESB;
2136 			sfp->mode.rresb.len = rfp->mode.rreqb.len;
2137 			sfp->mode.rresb.rtcode = 0;
2138 			sfp->mode.rresb.extcode = 0;
2139 			break;
2140 		case FWTCODE_RREQQ:
2141 			xfer->send.buf = malloc(16, M_FW, M_NOWAIT);
2142 			xfer->send.len = 16;
2143 			sfp = (struct fw_pkt *)xfer->send.buf;
2144 			sfp->mode.rresq.data = *(uint32_t *)(ntohl(rfp->mode.rreqq.dest_lo));
2145 			sfp->mode.wres.tcode = FWTCODE_RRESQ;
2146 			sfp->mode.rresb.rtcode = 0;
2147 			break;
2148 		default:
2149 			fw_xfer_free( xfer);
2150 			return;
2151 	}
2152 	sfp->mode.hdr.dst = rfp->mode.hdr.src;
2153 	xfer->dst = ntohs(rfp->mode.hdr.src);
2154 	xfer->hand = fw_xfer_free;
2155 
2156 	sfp->mode.hdr.tlrt = rfp->mode.hdr.tlrt;
2157 	sfp->mode.hdr.pri = 0;
2158 
2159 	fw_asyreq(xfer->fc, -1, xfer);
2160 /**/
2161 	return;
2162 }
2163 #endif
2164 
2165 /*
2166  * CRC16 check-sum for IEEE1394 register blocks.
2167  */
2168 uint16_t
2169 fw_crc16(uint32_t *ptr, uint32_t len){
2170 	uint32_t i, sum, crc = 0;
2171 	int shift;
2172 	len = (len + 3) & ~3;
2173 	for(i = 0 ; i < len ; i+= 4){
2174 		for( shift = 28 ; shift >= 0 ; shift -= 4){
2175 			sum = ((crc >> 12) ^ (ptr[i/4] >> shift)) & 0xf;
2176 			crc = (crc << 4) ^ ( sum << 12 ) ^ ( sum << 5) ^ sum;
2177 		}
2178 		crc &= 0xffff;
2179 	}
2180 	return((uint16_t) crc);
2181 }
2182 
2183 static int
2184 fw_bmr(struct firewire_comm *fc)
2185 {
2186 	struct fw_device fwdev;
2187 	union fw_self_id *self_id;
2188 	int cmstr;
2189 	uint32_t quad;
2190 
2191 	/* Check to see if the current root node is cycle master capable */
2192 	self_id = fw_find_self_id(fc, fc->max_node);
2193 	if (fc->max_node > 0) {
2194 		/* XXX check cmc bit of businfo block rather than contender */
2195 		if (self_id->p0.link_active && self_id->p0.contender)
2196 			cmstr = fc->max_node;
2197 		else {
2198 			device_printf(fc->bdev,
2199 				"root node is not cycle master capable\n");
2200 			/* XXX shall we be the cycle master? */
2201 			cmstr = fc->nodeid;
2202 			/* XXX need bus reset */
2203 		}
2204 	} else
2205 		cmstr = -1;
2206 
2207 	device_printf(fc->bdev, "bus manager %d ", CSRARC(fc, BUS_MGR_ID));
2208 	if(CSRARC(fc, BUS_MGR_ID) != fc->nodeid) {
2209 		/* We are not the bus manager */
2210 		printf("\n");
2211 		return(0);
2212 	}
2213 	printf("(me)\n");
2214 
2215 	/* Optimize gapcount */
2216 	if(fc->max_hop <= MAX_GAPHOP )
2217 		fw_phy_config(fc, cmstr, gap_cnt[fc->max_hop]);
2218 	/* If we are the cycle master, nothing to do */
2219 	if (cmstr == fc->nodeid || cmstr == -1)
2220 		return 0;
2221 	/* Bus probe has not finished, make dummy fwdev for cmstr */
2222 	bzero(&fwdev, sizeof(fwdev));
2223 	fwdev.fc = fc;
2224 	fwdev.dst = cmstr;
2225 	fwdev.speed = 0;
2226 	fwdev.maxrec = 8; /* 512 */
2227 	fwdev.status = FWDEVINIT;
2228 	/* Set cmstr bit on the cycle master */
2229 	quad = htonl(1 << 8);
2230 	fwmem_write_quad(&fwdev, NULL, 0/*spd*/,
2231 		0xffff, 0xf0000000 | STATE_SET, &quad, fw_asy_callback_free);
2232 
2233 	return 0;
2234 }
2235 
2236 int
2237 fw_open_isodma(struct firewire_comm *fc, int tx)
2238 {
2239 	struct fw_xferq **xferqa;
2240 	struct fw_xferq *xferq;
2241 	int i;
2242 
2243 	if (tx)
2244 		xferqa = &fc->it[0];
2245 	else
2246 		xferqa = &fc->ir[0];
2247 
2248 	FW_GLOCK(fc);
2249 	for (i = 0; i < fc->nisodma; i ++) {
2250 		xferq = xferqa[i];
2251 		if ((xferq->flag & FWXFERQ_OPEN) == 0) {
2252 			xferq->flag |= FWXFERQ_OPEN;
2253 			break;
2254 		}
2255 	}
2256 	if (i == fc->nisodma) {
2257 		printf("no free dma channel (tx=%d)\n", tx);
2258 		i = -1;
2259 	}
2260 	FW_GUNLOCK(fc);
2261 	return (i);
2262 }
2263 
2264 static int
2265 fw_modevent(module_t mode, int type, void *data)
2266 {
2267 	int err = 0;
2268 #if defined(__FreeBSD__) && __FreeBSD_version >= 500000
2269 	static eventhandler_tag fwdev_ehtag = NULL;
2270 #endif
2271 
2272 	switch (type) {
2273 	case MOD_LOAD:
2274 #if defined(__FreeBSD__) && __FreeBSD_version >= 500000
2275 		fwdev_ehtag = EVENTHANDLER_REGISTER(dev_clone,
2276 						fwdev_clone, 0, 1000);
2277 #endif
2278 		break;
2279 	case MOD_UNLOAD:
2280 #if defined(__FreeBSD__) && __FreeBSD_version >= 500000
2281 		if (fwdev_ehtag != NULL)
2282 			EVENTHANDLER_DEREGISTER(dev_clone, fwdev_ehtag);
2283 #endif
2284 		break;
2285 	case MOD_SHUTDOWN:
2286 		break;
2287 	default:
2288 		return (EOPNOTSUPP);
2289 	}
2290 	return (err);
2291 }
2292 
2293 
2294 #ifdef __DragonFly__
2295 DECLARE_DUMMY_MODULE(firewire);
2296 #endif
2297 DRIVER_MODULE(firewire,fwohci,firewire_driver,firewire_devclass,fw_modevent,0);
2298 MODULE_VERSION(firewire, 1);
2299