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