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