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