firewire.c revision 188704
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 188704 2009-02-17 04:08:08Z 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		printf("send phy_config root_node=%d gap_count=%d\n",
1261						root_node, gap_count);
1262	fw_asyreq(fc, -1, xfer);
1263}
1264
1265#if 0
1266/*
1267 * Dump self ID.
1268 */
1269static void
1270fw_print_sid(uint32_t sid)
1271{
1272	union fw_self_id *s;
1273	s = (union fw_self_id *) &sid;
1274	printf("node:%d link:%d gap:%d spd:%d del:%d con:%d pwr:%d"
1275		" p0:%d p1:%d p2:%d i:%d m:%d\n",
1276		s->p0.phy_id, s->p0.link_active, s->p0.gap_count,
1277		s->p0.phy_speed, s->p0.phy_delay, s->p0.contender,
1278		s->p0.power_class, s->p0.port0, s->p0.port1,
1279		s->p0.port2, s->p0.initiated_reset, s->p0.more_packets);
1280}
1281#endif
1282
1283/*
1284 * To receive self ID.
1285 */
1286void fw_sidrcv(struct firewire_comm* fc, uint32_t *sid, u_int len)
1287{
1288	uint32_t *p;
1289	union fw_self_id *self_id;
1290	u_int i, j, node, c_port = 0, i_branch = 0;
1291
1292	fc->sid_cnt = len /(sizeof(uint32_t) * 2);
1293	fc->max_node = fc->nodeid & 0x3f;
1294	CSRARC(fc, NODE_IDS) = ((uint32_t)fc->nodeid) << 16;
1295	fc->status = FWBUSCYMELECT;
1296	fc->topology_map->crc_len = 2;
1297	fc->topology_map->generation ++;
1298	fc->topology_map->self_id_count = 0;
1299	fc->topology_map->node_count = 0;
1300	fc->speed_map->generation ++;
1301	fc->speed_map->crc_len = 1 + (64*64 + 3) / 4;
1302	self_id = &fc->topology_map->self_id[0];
1303	for(i = 0; i < fc->sid_cnt; i ++){
1304		if (sid[1] != ~sid[0]) {
1305			printf("fw_sidrcv: invalid self-id packet\n");
1306			sid += 2;
1307			continue;
1308		}
1309		*self_id = *((union fw_self_id *)sid);
1310		fc->topology_map->crc_len++;
1311		if(self_id->p0.sequel == 0){
1312			fc->topology_map->node_count ++;
1313			c_port = 0;
1314#if 0
1315			fw_print_sid(sid[0]);
1316#endif
1317			node = self_id->p0.phy_id;
1318			if(fc->max_node < node){
1319				fc->max_node = self_id->p0.phy_id;
1320			}
1321			/* XXX I'm not sure this is the right speed_map */
1322			fc->speed_map->speed[node][node]
1323					= self_id->p0.phy_speed;
1324			for (j = 0; j < node; j ++) {
1325				fc->speed_map->speed[j][node]
1326					= fc->speed_map->speed[node][j]
1327					= min(fc->speed_map->speed[j][j],
1328							self_id->p0.phy_speed);
1329			}
1330			if ((fc->irm == -1 || self_id->p0.phy_id > fc->irm) &&
1331			  (self_id->p0.link_active && self_id->p0.contender)) {
1332				fc->irm = self_id->p0.phy_id;
1333			}
1334			if(self_id->p0.port0 >= 0x2){
1335				c_port++;
1336			}
1337			if(self_id->p0.port1 >= 0x2){
1338				c_port++;
1339			}
1340			if(self_id->p0.port2 >= 0x2){
1341				c_port++;
1342			}
1343		}
1344		if(c_port > 2){
1345			i_branch += (c_port - 2);
1346		}
1347		sid += 2;
1348		self_id++;
1349		fc->topology_map->self_id_count ++;
1350	}
1351	device_printf(fc->bdev, "%d nodes", fc->max_node + 1);
1352	/* CRC */
1353	fc->topology_map->crc = fw_crc16(
1354			(uint32_t *)&fc->topology_map->generation,
1355			fc->topology_map->crc_len * 4);
1356	fc->speed_map->crc = fw_crc16(
1357			(uint32_t *)&fc->speed_map->generation,
1358			fc->speed_map->crc_len * 4);
1359	/* byteswap and copy to CSR */
1360	p = (uint32_t *)fc->topology_map;
1361	for (i = 0; i <= fc->topology_map->crc_len; i++)
1362		CSRARC(fc, TOPO_MAP + i * 4) = htonl(*p++);
1363	p = (uint32_t *)fc->speed_map;
1364	CSRARC(fc, SPED_MAP) = htonl(*p++);
1365	CSRARC(fc, SPED_MAP + 4) = htonl(*p++);
1366	/* don't byte-swap uint8_t array */
1367	bcopy(p, &CSRARC(fc, SPED_MAP + 8), (fc->speed_map->crc_len - 1)*4);
1368
1369	fc->max_hop = fc->max_node - i_branch;
1370	printf(", maxhop <= %d", fc->max_hop);
1371
1372	if(fc->irm == -1 ){
1373		printf(", Not found IRM capable node");
1374	}else{
1375		printf(", cable IRM = %d", fc->irm);
1376		if (fc->irm == fc->nodeid)
1377			printf(" (me)");
1378	}
1379	printf("\n");
1380
1381	if (try_bmr && (fc->irm != -1) && (CSRARC(fc, BUS_MGR_ID) == 0x3f)) {
1382		if (fc->irm == fc->nodeid) {
1383			fc->status = FWBUSMGRDONE;
1384			CSRARC(fc, BUS_MGR_ID) = fc->set_bmr(fc, fc->irm);
1385			fw_bmr(fc);
1386		} else {
1387			fc->status = FWBUSMGRELECT;
1388			callout_reset(&fc->bmr_callout, hz/8,
1389				(void *)fw_try_bmr, (void *)fc);
1390		}
1391	} else
1392		fc->status = FWBUSMGRDONE;
1393
1394	callout_reset(&fc->busprobe_callout, hz/4,
1395			(void *)fw_bus_probe, (void *)fc);
1396}
1397
1398/*
1399 * To probe devices on the IEEE1394 bus.
1400 */
1401static void
1402fw_bus_probe(struct firewire_comm *fc)
1403{
1404	int s;
1405	struct fw_device *fwdev;
1406
1407	s = splfw();
1408	fc->status = FWBUSEXPLORE;
1409
1410	/* Invalidate all devices, just after bus reset. */
1411	STAILQ_FOREACH(fwdev, &fc->devices, link)
1412		if (fwdev->status != FWDEVINVAL) {
1413			fwdev->status = FWDEVINVAL;
1414			fwdev->rcnt = 0;
1415		}
1416	splx(s);
1417
1418	wakeup((void *)fc);
1419}
1420
1421static int
1422fw_explore_read_quads(struct fw_device *fwdev, int offset,
1423    uint32_t *quad, int n)
1424{
1425	struct fw_xfer *xfer;
1426	uint32_t tmp;
1427	int i, error;
1428
1429	for (i = 0; i < n; i ++, offset += sizeof(uint32_t)) {
1430		xfer = fwmem_read_quad(fwdev, NULL, -1,
1431		    0xffff, 0xf0000000 | offset, (void *)&tmp,
1432		    fw_xferwake);
1433		if (xfer == NULL)
1434			return (-1);
1435		fw_xferwait(xfer);
1436
1437		if (xfer->resp == 0)
1438			quad[i] = ntohl(tmp);
1439
1440		error = xfer->resp;
1441		fw_xfer_free(xfer);
1442		if (error)
1443			return (error);
1444	}
1445	return (0);
1446}
1447
1448
1449static int
1450fw_explore_csrblock(struct fw_device *fwdev, int offset, int recur)
1451{
1452	int err, i, off;
1453	struct csrdirectory *dir;
1454	struct csrreg *reg;
1455
1456	dir = (struct csrdirectory *)&fwdev->csrrom[offset/sizeof(uint32_t)];
1457	err = fw_explore_read_quads(fwdev, CSRROMOFF + offset,
1458	    (uint32_t *)dir, 1);
1459	if (err)
1460		return (-1);
1461
1462	offset += sizeof(uint32_t);
1463	reg = (struct csrreg *)&fwdev->csrrom[offset/sizeof(uint32_t)];
1464	err = fw_explore_read_quads(fwdev, CSRROMOFF + offset,
1465	    (uint32_t *)reg, dir->crc_len);
1466	if (err)
1467		return (-1);
1468
1469	/* XXX check CRC */
1470
1471	off = CSRROMOFF + offset + sizeof(uint32_t) * (dir->crc_len - 1);
1472	if (fwdev->rommax < off)
1473		fwdev->rommax = off;
1474
1475	if (recur == 0)
1476		return (0);
1477
1478	for (i = 0; i < dir->crc_len; i ++, offset += sizeof(uint32_t)) {
1479		if ((reg[i].key & CSRTYPE_MASK) == CSRTYPE_D)
1480			recur = 1;
1481		else if ((reg[i].key & CSRTYPE_MASK) == CSRTYPE_L)
1482			recur = 0;
1483		else
1484			continue;
1485
1486		off = offset + reg[i].val * sizeof(uint32_t);
1487		if (off > CROMSIZE) {
1488			printf("%s: invalid offset %d\n", __FUNCTION__, off);
1489			return(-1);
1490		}
1491		err = fw_explore_csrblock(fwdev, off, recur);
1492		if (err)
1493			return (-1);
1494	}
1495	return (0);
1496}
1497
1498static int
1499fw_explore_node(struct fw_device *dfwdev)
1500{
1501	struct firewire_comm *fc;
1502	struct fw_device *fwdev, *pfwdev, *tfwdev;
1503	uint32_t *csr;
1504	struct csrhdr *hdr;
1505	struct bus_info *binfo;
1506	int err, node;
1507	uint32_t speed_test = 0;
1508
1509	fc = dfwdev->fc;
1510	csr = dfwdev->csrrom;
1511	node = dfwdev->dst;
1512
1513	/* First quad */
1514	err = fw_explore_read_quads(dfwdev, CSRROMOFF, &csr[0], 1);
1515	if (err) {
1516		device_printf(fc->bdev, "%s: node%d: explore_read_quads failure\n",
1517		    __func__, node);
1518		dfwdev->status = FWDEVINVAL;
1519		return (-1);
1520	}
1521	hdr = (struct csrhdr *)&csr[0];
1522	if (hdr->info_len != 4) {
1523		if (firewire_debug)
1524			printf("node%d: wrong bus info len(%d)\n",
1525			    node, hdr->info_len);
1526		return (-1);
1527	}
1528
1529	/* bus info */
1530	err = fw_explore_read_quads(dfwdev, CSRROMOFF + 0x04, &csr[1], 4);
1531	if (err)
1532		return (-1);
1533	binfo = (struct bus_info *)&csr[1];
1534	if (binfo->bus_name != CSR_BUS_NAME_IEEE1394) {
1535		if (firewire_debug)
1536			printf("node%d: invalid bus name 0x%08x\n",
1537			    node, binfo->bus_name);
1538		return (-1);
1539	}
1540
1541	if (firewire_debug)
1542		device_printf(fc->bdev, "%s: node(%d) BUS INFO BLOCK:\n"
1543					"irmc(%d) cmc(%d) isc(%d) bmc(%d) pmc(%d) "
1544					"cyc_clk_acc(%d) max_rec(%d) max_rom(%d) "
1545					"generation(%d) link_spd(%d)\n",
1546					__func__, node,
1547					binfo->irmc, binfo->cmc, binfo->isc,
1548					binfo->bmc, binfo->pmc, binfo->cyc_clk_acc,
1549					binfo->max_rec, binfo->max_rom,
1550					binfo->generation, binfo->link_spd);
1551
1552	STAILQ_FOREACH(fwdev, &fc->devices, link)
1553		if (FW_EUI64_EQUAL(fwdev->eui, binfo->eui64))
1554			break;
1555	if (fwdev == NULL) {
1556		/* new device */
1557		fwdev = malloc(sizeof(struct fw_device), M_FW,
1558						M_NOWAIT | M_ZERO);
1559		if (fwdev == NULL) {
1560			if (firewire_debug)
1561				printf("node%d: no memory\n", node);
1562			return (-1);
1563		}
1564		fwdev->fc = fc;
1565		fwdev->eui = binfo->eui64;
1566		/*
1567		 * Pre-1394a-2000 didn't have link_spd in
1568		 * the Bus Info block, so try and use the
1569		 * speed map value.
1570		 * 1394a-2000 compliant devices only use
1571		 * the Bus Info Block link spd value, so
1572		 * ignore the speed map alltogether. SWB
1573		 */
1574		if ( binfo->link_spd == FWSPD_S100 /* 0 */) {
1575			device_printf(fc->bdev, "%s"
1576				"Pre 1394a-2000 detected\n",
1577				__func__);
1578			fwdev->speed = fc->speed_map->speed[fc->nodeid][node];
1579		} else
1580			fwdev->speed = binfo->link_spd;
1581		/*
1582		 * Test this speed with a read to the CSRROM.
1583		 * If it fails, slow down the speed and retry.
1584		 */
1585		while (fwdev->speed > 0) {
1586			err = fw_explore_read_quads(fwdev, CSRROMOFF,
1587            				&speed_test, 1);
1588			if (err)
1589				fwdev->speed--;
1590			else
1591				break;
1592
1593		}
1594		if (fwdev->speed != binfo->link_spd)
1595			device_printf(fc->bdev, "%s: fwdev->speed(%s)"
1596						" set lower than binfo->link_spd(%s)\n",
1597						__func__,
1598						linkspeed[fwdev->speed],
1599						linkspeed[binfo->link_spd]);
1600		/* inesrt into sorted fwdev list */
1601		pfwdev = NULL;
1602		STAILQ_FOREACH(tfwdev, &fc->devices, link) {
1603			if (tfwdev->eui.hi > fwdev->eui.hi ||
1604				(tfwdev->eui.hi == fwdev->eui.hi &&
1605				tfwdev->eui.lo > fwdev->eui.lo))
1606				break;
1607			pfwdev = tfwdev;
1608		}
1609		if (pfwdev == NULL)
1610			STAILQ_INSERT_HEAD(&fc->devices, fwdev, link);
1611		else
1612			STAILQ_INSERT_AFTER(&fc->devices, pfwdev, fwdev, link);
1613
1614		device_printf(fc->bdev, "New %s device ID:%08x%08x\n",
1615		    linkspeed[fwdev->speed],
1616		    fwdev->eui.hi, fwdev->eui.lo);
1617	}
1618	fwdev->dst = node;
1619	fwdev->status = FWDEVINIT;
1620
1621	/* unchanged ? */
1622	if (bcmp(&csr[0], &fwdev->csrrom[0], sizeof(uint32_t) * 5) == 0) {
1623		if (firewire_debug)
1624			device_printf(fc->dev, "node%d: crom unchanged\n", node);
1625		return (0);
1626	}
1627
1628	bzero(&fwdev->csrrom[0], CROMSIZE);
1629
1630	/* copy first quad and bus info block */
1631	bcopy(&csr[0], &fwdev->csrrom[0], sizeof(uint32_t) * 5);
1632	fwdev->rommax = CSRROMOFF + sizeof(uint32_t) * 4;
1633
1634	err = fw_explore_csrblock(fwdev, 0x14, 1); /* root directory */
1635
1636	if (err) {
1637		fwdev->status = FWDEVINVAL;
1638		fwdev->csrrom[0] = 0;
1639	}
1640	return (err);
1641
1642}
1643
1644/*
1645 * Find the self_id packet for a node, ignoring sequels.
1646 */
1647static union fw_self_id *
1648fw_find_self_id(struct firewire_comm *fc, int node)
1649{
1650	uint32_t i;
1651	union fw_self_id *s;
1652
1653	for (i = 0; i < fc->topology_map->self_id_count; i++) {
1654		s = &fc->topology_map->self_id[i];
1655		if (s->p0.sequel)
1656			continue;
1657		if (s->p0.phy_id == node)
1658			return s;
1659	}
1660	return 0;
1661}
1662
1663static void
1664fw_explore(struct firewire_comm *fc)
1665{
1666	int node, err, s, i, todo, todo2, trys;
1667	char nodes[63];
1668	struct fw_device dfwdev;
1669	union fw_self_id *fwsid;
1670
1671	todo = 0;
1672	/* setup dummy fwdev */
1673	dfwdev.fc = fc;
1674	dfwdev.speed = 0;
1675	dfwdev.maxrec = 8; /* 512 */
1676	dfwdev.status = FWDEVINIT;
1677
1678	for (node = 0; node <= fc->max_node; node ++) {
1679		/* We don't probe myself and linkdown nodes */
1680		if (node == fc->nodeid)
1681			continue;
1682		fwsid = fw_find_self_id(fc, node);
1683		if (!fwsid || !fwsid->p0.link_active) {
1684			if (firewire_debug)
1685				printf("node%d: link down\n", node);
1686			continue;
1687		}
1688		nodes[todo++] = node;
1689	}
1690
1691	s = splfw();
1692	for (trys = 0; todo > 0 && trys < 3; trys ++) {
1693		todo2 = 0;
1694		for (i = 0; i < todo; i ++) {
1695			dfwdev.dst = nodes[i];
1696			err = fw_explore_node(&dfwdev);
1697			if (err)
1698				nodes[todo2++] = nodes[i];
1699			if (firewire_debug)
1700				printf("%s: node %d, err = %d\n",
1701					__FUNCTION__, node, err);
1702		}
1703		todo = todo2;
1704	}
1705	splx(s);
1706}
1707
1708
1709static void
1710fw_bus_probe_thread(void *arg)
1711{
1712	struct firewire_comm *fc;
1713
1714	fc = (struct firewire_comm *)arg;
1715
1716	mtx_lock(&fc->wait_lock);
1717	while (fc->status != FWBUSDETACH) {
1718		if (fc->status == FWBUSEXPLORE) {
1719			mtx_unlock(&fc->wait_lock);
1720			fw_explore(fc);
1721			fc->status = FWBUSEXPDONE;
1722			if (firewire_debug)
1723				printf("bus_explore done\n");
1724			fw_attach_dev(fc);
1725			mtx_lock(&fc->wait_lock);
1726		}
1727		msleep((void *)fc, &fc->wait_lock, PWAIT|PCATCH, "-", 0);
1728	}
1729	mtx_unlock(&fc->wait_lock);
1730	kproc_exit(0);
1731}
1732
1733/*
1734 * To attach sub-devices layer onto IEEE1394 bus.
1735 */
1736static void
1737fw_attach_dev(struct firewire_comm *fc)
1738{
1739	struct fw_device *fwdev, *next;
1740	int i, err;
1741	device_t *devlistp;
1742	int devcnt;
1743	struct firewire_dev_comm *fdc;
1744
1745	for (fwdev = STAILQ_FIRST(&fc->devices); fwdev != NULL; fwdev = next) {
1746		next = STAILQ_NEXT(fwdev, link);
1747		if (fwdev->status == FWDEVINIT) {
1748			fwdev->status = FWDEVATTACHED;
1749		} else if (fwdev->status == FWDEVINVAL) {
1750			fwdev->rcnt ++;
1751			if (fwdev->rcnt > hold_count) {
1752				/*
1753				 * Remove devices which have not been seen
1754				 * for a while.
1755				 */
1756				STAILQ_REMOVE(&fc->devices, fwdev, fw_device,
1757				    link);
1758				free(fwdev, M_FW);
1759			}
1760		}
1761	}
1762
1763	err = device_get_children(fc->bdev, &devlistp, &devcnt);
1764	if( err != 0 )
1765		return;
1766	for( i = 0 ; i < devcnt ; i++){
1767		if (device_get_state(devlistp[i]) >= DS_ATTACHED)  {
1768			fdc = device_get_softc(devlistp[i]);
1769			if (fdc->post_explore != NULL)
1770				fdc->post_explore(fdc);
1771		}
1772	}
1773	free(devlistp, M_TEMP);
1774
1775	return;
1776}
1777
1778/*
1779 * To allocate unique transaction label.
1780 */
1781static int
1782fw_get_tlabel(struct firewire_comm *fc, struct fw_xfer *xfer)
1783{
1784	u_int dst, new_tlabel;
1785	struct fw_xfer *txfer;
1786	int s;
1787
1788	dst = xfer->send.hdr.mode.hdr.dst & 0x3f;
1789	s = splfw();
1790	mtx_lock(&fc->tlabel_lock);
1791	new_tlabel = (fc->last_tlabel[dst] + 1) & 0x3f;
1792	STAILQ_FOREACH(txfer, &fc->tlabels[new_tlabel], tlabel)
1793		if ((txfer->send.hdr.mode.hdr.dst & 0x3f) == dst)
1794				break;
1795	if(txfer == NULL) {
1796		fc->last_tlabel[dst] = new_tlabel;
1797		STAILQ_INSERT_TAIL(&fc->tlabels[new_tlabel], xfer, tlabel);
1798		mtx_unlock(&fc->tlabel_lock);
1799		splx(s);
1800		xfer->tl = new_tlabel;
1801		xfer->send.hdr.mode.hdr.tlrt = new_tlabel << 2;
1802		if (firewire_debug > 1)
1803			printf("fw_get_tlabel: dst=%d tl=%d\n", dst, new_tlabel);
1804		return (new_tlabel);
1805	}
1806	mtx_unlock(&fc->tlabel_lock);
1807	splx(s);
1808
1809	if (firewire_debug > 1)
1810		printf("fw_get_tlabel: no free tlabel\n");
1811	return (-1);
1812}
1813
1814static void
1815fw_rcv_copy(struct fw_rcv_buf *rb)
1816{
1817	struct fw_pkt *pkt;
1818	u_char *p;
1819	struct tcode_info *tinfo;
1820	u_int res, i, len, plen;
1821
1822	rb->xfer->recv.spd = rb->spd;
1823
1824	pkt = (struct fw_pkt *)rb->vec->iov_base;
1825	tinfo = &rb->fc->tcode[pkt->mode.hdr.tcode];
1826
1827	/* Copy header */
1828	p = (u_char *)&rb->xfer->recv.hdr;
1829	bcopy(rb->vec->iov_base, p, tinfo->hdr_len);
1830	rb->vec->iov_base = (u_char *)rb->vec->iov_base + tinfo->hdr_len;
1831	rb->vec->iov_len -= tinfo->hdr_len;
1832
1833	/* Copy payload */
1834	p = (u_char *)rb->xfer->recv.payload;
1835	res = rb->xfer->recv.pay_len;
1836
1837	/* special handling for RRESQ */
1838	if (pkt->mode.hdr.tcode == FWTCODE_RRESQ &&
1839	    p != NULL && res >= sizeof(uint32_t)) {
1840		*(uint32_t *)p = pkt->mode.rresq.data;
1841		rb->xfer->recv.pay_len = sizeof(uint32_t);
1842		return;
1843	}
1844
1845	if ((tinfo->flag & FWTI_BLOCK_ASY) == 0)
1846		return;
1847
1848	plen = pkt->mode.rresb.len;
1849
1850	for (i = 0; i < rb->nvec; i++, rb->vec++) {
1851		len = MIN(rb->vec->iov_len, plen);
1852		if (res < len) {
1853			printf("rcv buffer(%d) is %d bytes short.\n",
1854			    rb->xfer->recv.pay_len, len - res);
1855			len = res;
1856		}
1857		bcopy(rb->vec->iov_base, p, len);
1858		p += len;
1859		res -= len;
1860		plen -= len;
1861		if (res == 0 || plen == 0)
1862			break;
1863	}
1864	rb->xfer->recv.pay_len -= res;
1865
1866}
1867
1868/*
1869 * Generic packet receiving process.
1870 */
1871void
1872fw_rcv(struct fw_rcv_buf *rb)
1873{
1874	struct fw_pkt *fp, *resfp;
1875	struct fw_bind *bind;
1876	int tcode;
1877	int i, len, oldstate;
1878#if 0
1879	{
1880		uint32_t *qld;
1881		int i;
1882		qld = (uint32_t *)buf;
1883		printf("spd %d len:%d\n", spd, len);
1884		for( i = 0 ; i <= len && i < 32; i+= 4){
1885			printf("0x%08x ", ntohl(qld[i/4]));
1886			if((i % 16) == 15) printf("\n");
1887		}
1888		if((i % 16) != 15) printf("\n");
1889	}
1890#endif
1891	fp = (struct fw_pkt *)rb->vec[0].iov_base;
1892	tcode = fp->mode.common.tcode;
1893	switch (tcode) {
1894	case FWTCODE_WRES:
1895	case FWTCODE_RRESQ:
1896	case FWTCODE_RRESB:
1897	case FWTCODE_LRES:
1898		rb->xfer = fw_tl2xfer(rb->fc, fp->mode.hdr.src,
1899				fp->mode.hdr.tlrt >> 2, fp->mode.hdr.tcode);
1900		if(rb->xfer == NULL) {
1901			printf("fw_rcv: unknown response "
1902			    "%s(%x) src=0x%x tl=0x%x rt=%d data=0x%x\n",
1903			    tcode_str[tcode], tcode,
1904			    fp->mode.hdr.src,
1905			    fp->mode.hdr.tlrt >> 2,
1906			    fp->mode.hdr.tlrt & 3,
1907			    fp->mode.rresq.data);
1908#if 0
1909			printf("try ad-hoc work around!!\n");
1910			rb->xfer = fw_tl2xfer(rb->fc, fp->mode.hdr.src,
1911					(fp->mode.hdr.tlrt >> 2)^3);
1912			if (rb->xfer == NULL) {
1913				printf("no use...\n");
1914				return;
1915			}
1916#else
1917			return;
1918#endif
1919		}
1920		fw_rcv_copy(rb);
1921		if (rb->xfer->recv.hdr.mode.wres.rtcode != RESP_CMP)
1922			rb->xfer->resp = EIO;
1923		else
1924			rb->xfer->resp = 0;
1925		/* make sure the packet is drained in AT queue */
1926		oldstate = rb->xfer->flag;
1927		rb->xfer->flag = FWXF_RCVD;
1928		switch (oldstate) {
1929		case FWXF_SENT:
1930			fw_xfer_done(rb->xfer);
1931			break;
1932		case FWXF_START:
1933#if 0
1934			if (firewire_debug)
1935				printf("not sent yet tl=%x\n", rb->xfer->tl);
1936#endif
1937			break;
1938		default:
1939			printf("unexpected flag 0x%02x\n", rb->xfer->flag);
1940		}
1941		return;
1942	case FWTCODE_WREQQ:
1943	case FWTCODE_WREQB:
1944	case FWTCODE_RREQQ:
1945	case FWTCODE_RREQB:
1946	case FWTCODE_LREQ:
1947		bind = fw_bindlookup(rb->fc, fp->mode.rreqq.dest_hi,
1948			fp->mode.rreqq.dest_lo);
1949		if(bind == NULL){
1950			printf("Unknown service addr 0x%04x:0x%08x %s(%x)"
1951#if defined(__DragonFly__) || __FreeBSD_version < 500000
1952			    " src=0x%x data=%lx\n",
1953#else
1954			    " src=0x%x data=%x\n",
1955#endif
1956			    fp->mode.wreqq.dest_hi, fp->mode.wreqq.dest_lo,
1957			    tcode_str[tcode], tcode,
1958			    fp->mode.hdr.src, ntohl(fp->mode.wreqq.data));
1959			if (rb->fc->status == FWBUSINIT) {
1960				printf("fw_rcv: cannot respond(bus reset)!\n");
1961				return;
1962			}
1963			rb->xfer = fw_xfer_alloc(M_FWXFER);
1964			if(rb->xfer == NULL){
1965				return;
1966			}
1967			rb->xfer->send.spd = rb->spd;
1968			rb->xfer->send.pay_len = 0;
1969			resfp = &rb->xfer->send.hdr;
1970			switch (tcode) {
1971			case FWTCODE_WREQQ:
1972			case FWTCODE_WREQB:
1973				resfp->mode.hdr.tcode = FWTCODE_WRES;
1974				break;
1975			case FWTCODE_RREQQ:
1976				resfp->mode.hdr.tcode = FWTCODE_RRESQ;
1977				break;
1978			case FWTCODE_RREQB:
1979				resfp->mode.hdr.tcode = FWTCODE_RRESB;
1980				break;
1981			case FWTCODE_LREQ:
1982				resfp->mode.hdr.tcode = FWTCODE_LRES;
1983				break;
1984			}
1985			resfp->mode.hdr.dst = fp->mode.hdr.src;
1986			resfp->mode.hdr.tlrt = fp->mode.hdr.tlrt;
1987			resfp->mode.hdr.pri = fp->mode.hdr.pri;
1988			resfp->mode.rresb.rtcode = RESP_ADDRESS_ERROR;
1989			resfp->mode.rresb.extcode = 0;
1990			resfp->mode.rresb.len = 0;
1991/*
1992			rb->xfer->hand = fw_xferwake;
1993*/
1994			rb->xfer->hand = fw_xfer_free;
1995			if(fw_asyreq(rb->fc, -1, rb->xfer)){
1996				fw_xfer_free(rb->xfer);
1997				return;
1998			}
1999			return;
2000		}
2001		len = 0;
2002		for (i = 0; i < rb->nvec; i ++)
2003			len += rb->vec[i].iov_len;
2004		rb->xfer = STAILQ_FIRST(&bind->xferlist);
2005		if (rb->xfer == NULL) {
2006#if 1
2007			printf("Discard a packet for this bind.\n");
2008#endif
2009			return;
2010		}
2011		STAILQ_REMOVE_HEAD(&bind->xferlist, link);
2012		fw_rcv_copy(rb);
2013		rb->xfer->hand(rb->xfer);
2014		return;
2015#if 0 /* shouldn't happen ?? or for GASP */
2016	case FWTCODE_STREAM:
2017	{
2018		struct fw_xferq *xferq;
2019
2020		xferq = rb->fc->ir[sub];
2021#if 0
2022		printf("stream rcv dma %d len %d off %d spd %d\n",
2023			sub, len, off, spd);
2024#endif
2025		if(xferq->queued >= xferq->maxq) {
2026			printf("receive queue is full\n");
2027			return;
2028		}
2029		/* XXX get xfer from xfer queue, we don't need copy for
2030			per packet mode */
2031		rb->xfer = fw_xfer_alloc_buf(M_FWXFER, 0, /* XXX */
2032						vec[0].iov_len);
2033		if (rb->xfer == NULL)
2034			return;
2035		fw_rcv_copy(rb)
2036		s = splfw();
2037		xferq->queued++;
2038		STAILQ_INSERT_TAIL(&xferq->q, rb->xfer, link);
2039		splx(s);
2040		sc = device_get_softc(rb->fc->bdev);
2041#if defined(__DragonFly__) || __FreeBSD_version < 500000
2042		if (&xferq->rsel.si_pid != 0)
2043#else
2044		if (SEL_WAITING(&xferq->rsel))
2045#endif
2046			selwakeuppri(&xferq->rsel, FWPRI);
2047		if (xferq->flag & FWXFERQ_WAKEUP) {
2048			xferq->flag &= ~FWXFERQ_WAKEUP;
2049			wakeup((caddr_t)xferq);
2050		}
2051		if (xferq->flag & FWXFERQ_HANDLER) {
2052			xferq->hand(xferq);
2053		}
2054		return;
2055		break;
2056	}
2057#endif
2058	default:
2059		printf("fw_rcv: unknow tcode %d\n", tcode);
2060		break;
2061	}
2062}
2063
2064/*
2065 * Post process for Bus Manager election process.
2066 */
2067static void
2068fw_try_bmr_callback(struct fw_xfer *xfer)
2069{
2070	struct firewire_comm *fc;
2071	int bmr;
2072
2073	if (xfer == NULL)
2074		return;
2075	fc = xfer->fc;
2076	if (xfer->resp != 0)
2077		goto error;
2078	if (xfer->recv.payload == NULL)
2079		goto error;
2080	if (xfer->recv.hdr.mode.lres.rtcode != FWRCODE_COMPLETE)
2081		goto error;
2082
2083	bmr = ntohl(xfer->recv.payload[0]);
2084	if (bmr == 0x3f)
2085		bmr = fc->nodeid;
2086
2087	CSRARC(fc, BUS_MGR_ID) = fc->set_bmr(fc, bmr & 0x3f);
2088	fw_xfer_free_buf(xfer);
2089	fw_bmr(fc);
2090	return;
2091
2092error:
2093	device_printf(fc->bdev, "bus manager election failed\n");
2094	fw_xfer_free_buf(xfer);
2095}
2096
2097
2098/*
2099 * To candidate Bus Manager election process.
2100 */
2101static void
2102fw_try_bmr(void *arg)
2103{
2104	struct fw_xfer *xfer;
2105	struct firewire_comm *fc = (struct firewire_comm *)arg;
2106	struct fw_pkt *fp;
2107	int err = 0;
2108
2109	xfer = fw_xfer_alloc_buf(M_FWXFER, 8, 4);
2110	if(xfer == NULL){
2111		return;
2112	}
2113	xfer->send.spd = 0;
2114	fc->status = FWBUSMGRELECT;
2115
2116	fp = &xfer->send.hdr;
2117	fp->mode.lreq.dest_hi = 0xffff;
2118	fp->mode.lreq.tlrt = 0;
2119	fp->mode.lreq.tcode = FWTCODE_LREQ;
2120	fp->mode.lreq.pri = 0;
2121	fp->mode.lreq.src = 0;
2122	fp->mode.lreq.len = 8;
2123	fp->mode.lreq.extcode = EXTCODE_CMP_SWAP;
2124	fp->mode.lreq.dst = FWLOCALBUS | fc->irm;
2125	fp->mode.lreq.dest_lo = 0xf0000000 | BUS_MGR_ID;
2126	xfer->send.payload[0] = htonl(0x3f);
2127	xfer->send.payload[1] = htonl(fc->nodeid);
2128	xfer->hand = fw_try_bmr_callback;
2129
2130	err = fw_asyreq(fc, -1, xfer);
2131	if(err){
2132		fw_xfer_free_buf(xfer);
2133		return;
2134	}
2135	return;
2136}
2137
2138#ifdef FW_VMACCESS
2139/*
2140 * Software implementation for physical memory block access.
2141 * XXX:Too slow, usef for debug purpose only.
2142 */
2143static void
2144fw_vmaccess(struct fw_xfer *xfer){
2145	struct fw_pkt *rfp, *sfp = NULL;
2146	uint32_t *ld = (uint32_t *)xfer->recv.buf;
2147
2148	printf("vmaccess spd:%2x len:%03x data:%08x %08x %08x %08x\n",
2149			xfer->spd, xfer->recv.len, ntohl(ld[0]), ntohl(ld[1]), ntohl(ld[2]), ntohl(ld[3]));
2150	printf("vmaccess          data:%08x %08x %08x %08x\n", ntohl(ld[4]), ntohl(ld[5]), ntohl(ld[6]), ntohl(ld[7]));
2151	if(xfer->resp != 0){
2152		fw_xfer_free( xfer);
2153		return;
2154	}
2155	if(xfer->recv.buf == NULL){
2156		fw_xfer_free( xfer);
2157		return;
2158	}
2159	rfp = (struct fw_pkt *)xfer->recv.buf;
2160	switch(rfp->mode.hdr.tcode){
2161		/* XXX need fix for 64bit arch */
2162		case FWTCODE_WREQB:
2163			xfer->send.buf = malloc(12, M_FW, M_NOWAIT);
2164			xfer->send.len = 12;
2165			sfp = (struct fw_pkt *)xfer->send.buf;
2166			bcopy(rfp->mode.wreqb.payload,
2167				(caddr_t)ntohl(rfp->mode.wreqb.dest_lo), ntohs(rfp->mode.wreqb.len));
2168			sfp->mode.wres.tcode = FWTCODE_WRES;
2169			sfp->mode.wres.rtcode = 0;
2170			break;
2171		case FWTCODE_WREQQ:
2172			xfer->send.buf = malloc(12, M_FW, M_NOWAIT);
2173			xfer->send.len = 12;
2174			sfp->mode.wres.tcode = FWTCODE_WRES;
2175			*((uint32_t *)(ntohl(rfp->mode.wreqb.dest_lo))) = rfp->mode.wreqq.data;
2176			sfp->mode.wres.rtcode = 0;
2177			break;
2178		case FWTCODE_RREQB:
2179			xfer->send.buf = malloc(16 + rfp->mode.rreqb.len, M_FW, M_NOWAIT);
2180			xfer->send.len = 16 + ntohs(rfp->mode.rreqb.len);
2181			sfp = (struct fw_pkt *)xfer->send.buf;
2182			bcopy((caddr_t)ntohl(rfp->mode.rreqb.dest_lo),
2183				sfp->mode.rresb.payload, (uint16_t)ntohs(rfp->mode.rreqb.len));
2184			sfp->mode.rresb.tcode = FWTCODE_RRESB;
2185			sfp->mode.rresb.len = rfp->mode.rreqb.len;
2186			sfp->mode.rresb.rtcode = 0;
2187			sfp->mode.rresb.extcode = 0;
2188			break;
2189		case FWTCODE_RREQQ:
2190			xfer->send.buf = malloc(16, M_FW, M_NOWAIT);
2191			xfer->send.len = 16;
2192			sfp = (struct fw_pkt *)xfer->send.buf;
2193			sfp->mode.rresq.data = *(uint32_t *)(ntohl(rfp->mode.rreqq.dest_lo));
2194			sfp->mode.wres.tcode = FWTCODE_RRESQ;
2195			sfp->mode.rresb.rtcode = 0;
2196			break;
2197		default:
2198			fw_xfer_free( xfer);
2199			return;
2200	}
2201	sfp->mode.hdr.dst = rfp->mode.hdr.src;
2202	xfer->dst = ntohs(rfp->mode.hdr.src);
2203	xfer->hand = fw_xfer_free;
2204
2205	sfp->mode.hdr.tlrt = rfp->mode.hdr.tlrt;
2206	sfp->mode.hdr.pri = 0;
2207
2208	fw_asyreq(xfer->fc, -1, xfer);
2209/**/
2210	return;
2211}
2212#endif
2213
2214/*
2215 * CRC16 check-sum for IEEE1394 register blocks.
2216 */
2217uint16_t
2218fw_crc16(uint32_t *ptr, uint32_t len){
2219	uint32_t i, sum, crc = 0;
2220	int shift;
2221	len = (len + 3) & ~3;
2222	for(i = 0 ; i < len ; i+= 4){
2223		for( shift = 28 ; shift >= 0 ; shift -= 4){
2224			sum = ((crc >> 12) ^ (ptr[i/4] >> shift)) & 0xf;
2225			crc = (crc << 4) ^ ( sum << 12 ) ^ ( sum << 5) ^ sum;
2226		}
2227		crc &= 0xffff;
2228	}
2229	return((uint16_t) crc);
2230}
2231
2232static int
2233fw_bmr(struct firewire_comm *fc)
2234{
2235	struct fw_device fwdev;
2236	union fw_self_id *self_id;
2237	int cmstr;
2238	uint32_t quad;
2239
2240	/* Check to see if the current root node is cycle master capable */
2241	self_id = fw_find_self_id(fc, fc->max_node);
2242	if (fc->max_node > 0) {
2243		/* XXX check cmc bit of businfo block rather than contender */
2244		if (self_id->p0.link_active && self_id->p0.contender)
2245			cmstr = fc->max_node;
2246		else {
2247			device_printf(fc->bdev,
2248				"root node is not cycle master capable\n");
2249			/* XXX shall we be the cycle master? */
2250			cmstr = fc->nodeid;
2251			/* XXX need bus reset */
2252		}
2253	} else
2254		cmstr = -1;
2255
2256	device_printf(fc->bdev, "bus manager %d ", CSRARC(fc, BUS_MGR_ID));
2257	if(CSRARC(fc, BUS_MGR_ID) != fc->nodeid) {
2258		/* We are not the bus manager */
2259		printf("\n");
2260		return(0);
2261	}
2262	printf("(me)\n");
2263
2264	/* Optimize gapcount */
2265	if(fc->max_hop <= MAX_GAPHOP )
2266		fw_phy_config(fc, cmstr, gap_cnt[fc->max_hop]);
2267	/* If we are the cycle master, nothing to do */
2268	if (cmstr == fc->nodeid || cmstr == -1)
2269		return 0;
2270	/* Bus probe has not finished, make dummy fwdev for cmstr */
2271	bzero(&fwdev, sizeof(fwdev));
2272	fwdev.fc = fc;
2273	fwdev.dst = cmstr;
2274	fwdev.speed = 0;
2275	fwdev.maxrec = 8; /* 512 */
2276	fwdev.status = FWDEVINIT;
2277	/* Set cmstr bit on the cycle master */
2278	quad = htonl(1 << 8);
2279	fwmem_write_quad(&fwdev, NULL, 0/*spd*/,
2280		0xffff, 0xf0000000 | STATE_SET, &quad, fw_asy_callback_free);
2281
2282	return 0;
2283}
2284
2285int
2286fw_open_isodma(struct firewire_comm *fc, int tx)
2287{
2288	struct fw_xferq **xferqa;
2289	struct fw_xferq *xferq;
2290	int i;
2291
2292	if (tx)
2293		xferqa = &fc->it[0];
2294	else
2295		xferqa = &fc->ir[0];
2296
2297	FW_GLOCK(fc);
2298	for (i = 0; i < fc->nisodma; i ++) {
2299		xferq = xferqa[i];
2300		if ((xferq->flag & FWXFERQ_OPEN) == 0) {
2301			xferq->flag |= FWXFERQ_OPEN;
2302			break;
2303		}
2304	}
2305	if (i == fc->nisodma) {
2306		printf("no free dma channel (tx=%d)\n", tx);
2307		i = -1;
2308	}
2309	FW_GUNLOCK(fc);
2310	return (i);
2311}
2312
2313static int
2314fw_modevent(module_t mode, int type, void *data)
2315{
2316	int err = 0;
2317#if defined(__FreeBSD__) && __FreeBSD_version >= 500000
2318	static eventhandler_tag fwdev_ehtag = NULL;
2319#endif
2320
2321	switch (type) {
2322	case MOD_LOAD:
2323#if defined(__FreeBSD__) && __FreeBSD_version >= 500000
2324		fwdev_ehtag = EVENTHANDLER_REGISTER(dev_clone,
2325						fwdev_clone, 0, 1000);
2326#endif
2327		break;
2328	case MOD_UNLOAD:
2329#if defined(__FreeBSD__) && __FreeBSD_version >= 500000
2330		if (fwdev_ehtag != NULL)
2331			EVENTHANDLER_DEREGISTER(dev_clone, fwdev_ehtag);
2332#endif
2333		break;
2334	case MOD_SHUTDOWN:
2335		break;
2336	default:
2337		return (EOPNOTSUPP);
2338	}
2339	return (err);
2340}
2341
2342
2343#ifdef __DragonFly__
2344DECLARE_DUMMY_MODULE(firewire);
2345#endif
2346DRIVER_MODULE(firewire,fwohci,firewire_driver,firewire_devclass,fw_modevent,0);
2347MODULE_VERSION(firewire, 1);
2348