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