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