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