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