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