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