firewire.c revision 117716
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 117716 2003-07-18 05:28:30Z 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 state=%d\n",
337				xfer->dst, i, xfer->state);
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 = 1;
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	STAILQ_INIT(&src->chunk_list);
626
627	bzero(root, sizeof(struct crom_chunk));
628	crom_add_chunk(src, NULL, root, 0);
629	crom_add_entry(root, CSRKEY_NCAP, 0x0083c0); /* XXX */
630	/* private company_id */
631	crom_add_entry(root, CSRKEY_VENDOR, CSRVAL_VENDOR_PRIVATE);
632	crom_add_simple_text(src, root, &buf->vendor, "FreeBSD Project");
633	crom_add_entry(root, CSRKEY_HW, __FreeBSD_version);
634	crom_add_simple_text(src, root, &buf->hw, hostname);
635}
636
637/*
638 * Called after bus reset.
639 */
640void
641fw_busreset(struct firewire_comm *fc)
642{
643	struct firewire_dev_comm *fdc;
644	struct crom_src *src;
645	device_t *devlistp;
646	void *newrom;
647	int i, devcnt;
648
649	switch(fc->status){
650	case FWBUSMGRELECT:
651		callout_stop(&fc->bmr_callout);
652		break;
653	default:
654		break;
655	}
656	fc->status = FWBUSRESET;
657	fw_reset_csr(fc);
658	fw_reset_crom(fc);
659
660	if (device_get_children(fc->bdev, &devlistp, &devcnt) == 0) {
661		for( i = 0 ; i < devcnt ; i++)
662			if (device_get_state(devlistp[i]) >= DS_ATTACHED)  {
663				fdc = device_get_softc(devlistp[i]);
664				if (fdc->post_busreset != NULL)
665					fdc->post_busreset(fdc);
666			}
667		free(devlistp, M_TEMP);
668	}
669
670	newrom = malloc(CROMSIZE, M_FW, M_NOWAIT | M_ZERO);
671	src = &fc->crom_src_buf->src;
672	crom_load(src, (u_int32_t *)newrom, CROMSIZE);
673	if (bcmp(newrom, fc->config_rom, CROMSIZE) != 0) {
674		/* bump generation and reload */
675		src->businfo.generation ++;
676		/* generation must be between 0x2 and 0xF */
677		if (src->businfo.generation < 2)
678			src->businfo.generation ++;
679		crom_load(src, (u_int32_t *)newrom, CROMSIZE);
680		bcopy(newrom, (void *)fc->config_rom, CROMSIZE);
681	}
682	free(newrom, M_FW);
683}
684
685/* Call once after reboot */
686void fw_init(struct firewire_comm *fc)
687{
688	int i;
689	struct csrdir *csrd;
690#ifdef FW_VMACCESS
691	struct fw_xfer *xfer;
692	struct fw_bind *fwb;
693#endif
694
695	fc->max_asyretry = FW_MAXASYRTY;
696
697	fc->arq->queued = 0;
698	fc->ars->queued = 0;
699	fc->atq->queued = 0;
700	fc->ats->queued = 0;
701
702	fc->arq->buf = NULL;
703	fc->ars->buf = NULL;
704	fc->atq->buf = NULL;
705	fc->ats->buf = NULL;
706
707	fc->arq->flag = 0;
708	fc->ars->flag = 0;
709	fc->atq->flag = 0;
710	fc->ats->flag = 0;
711
712	STAILQ_INIT(&fc->atq->q);
713	STAILQ_INIT(&fc->ats->q);
714
715	for( i = 0 ; i < fc->nisodma ; i ++ ){
716		fc->it[i]->queued = 0;
717		fc->ir[i]->queued = 0;
718
719		fc->it[i]->start = NULL;
720		fc->ir[i]->start = NULL;
721
722		fc->it[i]->buf = NULL;
723		fc->ir[i]->buf = NULL;
724
725		fc->it[i]->flag = FWXFERQ_STREAM;
726		fc->ir[i]->flag = FWXFERQ_STREAM;
727
728		STAILQ_INIT(&fc->it[i]->q);
729		STAILQ_INIT(&fc->ir[i]->q);
730
731		STAILQ_INIT(&fc->it[i]->binds);
732		STAILQ_INIT(&fc->ir[i]->binds);
733	}
734
735	fc->arq->maxq = FWMAXQUEUE;
736	fc->ars->maxq = FWMAXQUEUE;
737	fc->atq->maxq = FWMAXQUEUE;
738	fc->ats->maxq = FWMAXQUEUE;
739
740	for( i = 0 ; i < fc->nisodma ; i++){
741		fc->ir[i]->maxq = FWMAXQUEUE;
742		fc->it[i]->maxq = FWMAXQUEUE;
743	}
744/* Initialize csr registers */
745	fc->topology_map = (struct fw_topology_map *)malloc(
746				sizeof(struct fw_topology_map),
747				M_FW, M_NOWAIT | M_ZERO);
748	fc->speed_map = (struct fw_speed_map *)malloc(
749				sizeof(struct fw_speed_map),
750				M_FW, M_NOWAIT | M_ZERO);
751	CSRARC(fc, TOPO_MAP) = 0x3f1 << 16;
752	CSRARC(fc, TOPO_MAP + 4) = 1;
753	CSRARC(fc, SPED_MAP) = 0x3f1 << 16;
754	CSRARC(fc, SPED_MAP + 4) = 1;
755
756	STAILQ_INIT(&fc->devices);
757	STAILQ_INIT(&fc->pending);
758
759/* Initialize csr ROM work space */
760	SLIST_INIT(&fc->ongocsr);
761	SLIST_INIT(&fc->csrfree);
762	for( i = 0 ; i < FWMAXCSRDIR ; i++){
763		csrd = (struct csrdir *) malloc(sizeof(struct csrdir), M_FW,M_NOWAIT);
764		if(csrd == NULL) break;
765		SLIST_INSERT_HEAD(&fc->csrfree, csrd, link);
766	}
767
768/* Initialize Async handlers */
769	STAILQ_INIT(&fc->binds);
770	for( i = 0 ; i < 0x40 ; i++){
771		STAILQ_INIT(&fc->tlabels[i]);
772	}
773
774/* DV depend CSRs see blue book */
775#if 0
776	CSRARC(fc, oMPR) = 0x3fff0001; /* # output channel = 1 */
777	CSRARC(fc, oPCR) = 0x8000007a;
778	for(i = 4 ; i < 0x7c/4 ; i+=4){
779		CSRARC(fc, i + oPCR) = 0x8000007a;
780	}
781
782	CSRARC(fc, iMPR) = 0x00ff0001; /* # input channel = 1 */
783	CSRARC(fc, iPCR) = 0x803f0000;
784	for(i = 4 ; i < 0x7c/4 ; i+=4){
785		CSRARC(fc, i + iPCR) = 0x0;
786	}
787#endif
788
789	fc->crom_src_buf = NULL;
790
791#ifdef FW_VMACCESS
792	xfer = fw_xfer_alloc();
793	if(xfer == NULL) return;
794
795	fwb = (struct fw_bind *)malloc(sizeof (struct fw_bind), M_FW, M_NOWAIT);
796	if(fwb == NULL){
797		fw_xfer_free(xfer);
798	}
799	xfer->act.hand = fw_vmaccess;
800	xfer->fc = fc;
801	xfer->sc = NULL;
802
803	fwb->start_hi = 0x2;
804	fwb->start_lo = 0;
805	fwb->addrlen = 0xffffffff;
806	fwb->xfer = xfer;
807	fw_bindadd(fc, fwb);
808#endif
809}
810
811/*
812 * To lookup binded process from IEEE1394 address.
813 */
814struct fw_bind *
815fw_bindlookup(struct firewire_comm *fc, u_int32_t dest_hi, u_int32_t dest_lo)
816{
817	struct fw_bind *tfw;
818	for(tfw = STAILQ_FIRST(&fc->binds) ; tfw != NULL ;
819		tfw = STAILQ_NEXT(tfw, fclist)){
820		if (tfw->act_type != FWACT_NULL &&
821			tfw->start_hi == dest_hi &&
822			tfw->start_lo <= dest_lo &&
823			(tfw->start_lo + tfw->addrlen) > dest_lo){
824			return(tfw);
825		}
826	}
827	return(NULL);
828}
829
830/*
831 * To bind IEEE1394 address block to process.
832 */
833int
834fw_bindadd(struct firewire_comm *fc, struct fw_bind *fwb)
835{
836	struct fw_bind *tfw, *tfw2 = NULL;
837	int err = 0;
838	tfw = STAILQ_FIRST(&fc->binds);
839	if(tfw == NULL){
840		STAILQ_INSERT_HEAD(&fc->binds, fwb, fclist);
841		goto out;
842	}
843	if((tfw->start_hi > fwb->start_hi) ||
844		(tfw->start_hi == fwb->start_hi &&
845		(tfw->start_lo > (fwb->start_lo + fwb->addrlen)))){
846		STAILQ_INSERT_HEAD(&fc->binds, fwb, fclist);
847		goto out;
848	}
849	for(; tfw != NULL; tfw = STAILQ_NEXT(tfw, fclist)){
850		if((tfw->start_hi < fwb->start_hi) ||
851		   (tfw->start_hi == fwb->start_hi &&
852		    (tfw->start_lo + tfw->addrlen) < fwb->start_lo)){
853		   tfw2 = STAILQ_NEXT(tfw, fclist);
854			if(tfw2 == NULL)
855				break;
856			if((tfw2->start_hi > fwb->start_hi) ||
857			   (tfw2->start_hi == fwb->start_hi &&
858			    tfw2->start_lo > (fwb->start_lo + fwb->addrlen))){
859				break;
860			}else{
861				err = EBUSY;
862				goto out;
863			}
864		}
865	}
866	if(tfw != NULL){
867		STAILQ_INSERT_AFTER(&fc->binds, tfw, fwb, fclist);
868	}else{
869		STAILQ_INSERT_TAIL(&fc->binds, fwb, fclist);
870	}
871out:
872	if (!err && fwb->act_type == FWACT_CH)
873		STAILQ_INSERT_HEAD(&fc->ir[fwb->sub]->binds, fwb, chlist);
874	return err;
875}
876
877/*
878 * To free IEEE1394 address block.
879 */
880int
881fw_bindremove(struct firewire_comm *fc, struct fw_bind *fwb)
882{
883	int s;
884	struct fw_xfer *xfer, *next;
885
886	s = splfw();
887	/* shall we check the existance? */
888	STAILQ_REMOVE(&fc->binds, fwb, fw_bind, fclist);
889	/* shall we do this? */
890	for (xfer = STAILQ_FIRST(&fwb->xferlist); xfer != NULL; xfer = next) {
891		next = STAILQ_NEXT(xfer, link);
892		fw_xfer_free(xfer);
893	}
894	STAILQ_INIT(&fwb->xferlist);
895
896	splx(s);
897	return 0;
898}
899
900/*
901 * To free transaction label.
902 */
903static void
904fw_tl_free(struct firewire_comm *fc, struct fw_xfer *xfer)
905{
906	struct tlabel *tl;
907	int s = splfw();
908
909	for( tl = STAILQ_FIRST(&fc->tlabels[xfer->tl]); tl != NULL;
910		tl = STAILQ_NEXT(tl, link)){
911		if(tl->xfer == xfer){
912			STAILQ_REMOVE(&fc->tlabels[xfer->tl], tl, tlabel, link);
913			free(tl, M_FW);
914			splx(s);
915			return;
916		}
917	}
918	splx(s);
919	return;
920}
921
922/*
923 * To obtain XFER structure by transaction label.
924 */
925static struct fw_xfer *
926fw_tl2xfer(struct firewire_comm *fc, int node, int tlabel)
927{
928	struct fw_xfer *xfer;
929	struct tlabel *tl;
930	int s = splfw();
931
932	for( tl = STAILQ_FIRST(&fc->tlabels[tlabel]); tl != NULL;
933		tl = STAILQ_NEXT(tl, link)){
934		if(tl->xfer->dst == node){
935			xfer = tl->xfer;
936			splx(s);
937			if (firewire_debug > 2)
938				printf("fw_tl2xfer: found tl=%d\n", tlabel);
939			return(xfer);
940		}
941	}
942	if (firewire_debug > 1)
943		printf("fw_tl2xfer: not found tl=%d\n", tlabel);
944	splx(s);
945	return(NULL);
946}
947
948/*
949 * To allocate IEEE1394 XFER structure.
950 */
951struct fw_xfer *
952fw_xfer_alloc(struct malloc_type *type)
953{
954	struct fw_xfer *xfer;
955
956	xfer = malloc(sizeof(struct fw_xfer), type, M_NOWAIT | M_ZERO);
957	if (xfer == NULL)
958		return xfer;
959
960	microtime(&xfer->tv);
961	xfer->malloc = type;
962
963	return xfer;
964}
965
966struct fw_xfer *
967fw_xfer_alloc_buf(struct malloc_type *type, int send_len, int recv_len)
968{
969	struct fw_xfer *xfer;
970
971	xfer = fw_xfer_alloc(type);
972	xfer->send.len = send_len;
973	xfer->recv.len = recv_len;
974	if (xfer == NULL)
975		return(NULL);
976	if (send_len) {
977		xfer->send.buf = malloc(send_len, type, M_NOWAIT | M_ZERO);
978		if (xfer->send.buf == NULL) {
979			fw_xfer_free(xfer);
980			return(NULL);
981		}
982	}
983	if (recv_len) {
984		xfer->recv.buf = malloc(recv_len, type, M_NOWAIT);
985		if (xfer->recv.buf == NULL) {
986			if (xfer->send.buf != NULL)
987				free(xfer->send.buf, type);
988			fw_xfer_free(xfer);
989			return(NULL);
990		}
991	}
992	return(xfer);
993}
994
995/*
996 * IEEE1394 XFER post process.
997 */
998void
999fw_xfer_done(struct fw_xfer *xfer)
1000{
1001	if (xfer->act.hand == NULL) {
1002		printf("act.hand == NULL\n");
1003		return;
1004	}
1005
1006	if (xfer->fc->status != FWBUSRESET)
1007		xfer->act.hand(xfer);
1008	else {
1009		printf("fw_xfer_done: pending\n");
1010		if (xfer->fc != NULL)
1011			STAILQ_INSERT_TAIL(&xfer->fc->pending, xfer, link);
1012		else
1013			panic("fw_xfer_done: why xfer->fc is NULL?");
1014	}
1015}
1016
1017void
1018fw_xfer_unload(struct fw_xfer* xfer)
1019{
1020	int s;
1021
1022	if(xfer == NULL ) return;
1023	if(xfer->state == FWXF_INQ){
1024		printf("fw_xfer_free FWXF_INQ\n");
1025		s = splfw();
1026		STAILQ_REMOVE(&xfer->q->q, xfer, fw_xfer, link);
1027		xfer->q->queued --;
1028		splx(s);
1029	}
1030	if (xfer->fc != NULL) {
1031#if 1
1032		if(xfer->state == FWXF_START)
1033			/*
1034			 * This could happen if:
1035			 *  1. We call fwohci_arcv() before fwohci_txd().
1036			 *  2. firewire_watch() is called.
1037			 */
1038			printf("fw_xfer_free FWXF_START\n");
1039#endif
1040		fw_tl_free(xfer->fc, xfer);
1041	}
1042	xfer->state = FWXF_INIT;
1043	xfer->resp = 0;
1044	xfer->retry = 0;
1045}
1046/*
1047 * To free IEEE1394 XFER structure.
1048 */
1049void
1050fw_xfer_free( struct fw_xfer* xfer)
1051{
1052	if(xfer == NULL ) return;
1053	fw_xfer_unload(xfer);
1054	if(xfer->send.buf != NULL){
1055		free(xfer->send.buf, xfer->malloc);
1056	}
1057	if(xfer->recv.buf != NULL){
1058		free(xfer->recv.buf, xfer->malloc);
1059	}
1060	free(xfer, xfer->malloc);
1061}
1062
1063static void
1064fw_asy_callback_free(struct fw_xfer *xfer)
1065{
1066#if 0
1067	printf("asyreq done state=%d resp=%d\n",
1068				xfer->state, xfer->resp);
1069#endif
1070	fw_xfer_free(xfer);
1071}
1072
1073/*
1074 * To configure PHY.
1075 */
1076static void
1077fw_phy_config(struct firewire_comm *fc, int root_node, int gap_count)
1078{
1079	struct fw_xfer *xfer;
1080	struct fw_pkt *fp;
1081
1082	fc->status = FWBUSPHYCONF;
1083
1084	xfer = fw_xfer_alloc_buf(M_FWXFER, 12, 0);
1085	if (xfer == NULL)
1086		return;
1087	xfer->fc = fc;
1088	xfer->retry_req = fw_asybusy;
1089	xfer->act.hand = fw_asy_callback_free;
1090
1091	fp = (struct fw_pkt *)xfer->send.buf;
1092	fp->mode.ld[1] = 0;
1093	if (root_node >= 0)
1094		fp->mode.ld[1] |= (root_node & 0x3f) << 24 | 1 << 23;
1095	if (gap_count >= 0)
1096		fp->mode.ld[1] |= 1 << 22 | (gap_count & 0x3f) << 16;
1097	fp->mode.ld[2] = ~fp->mode.ld[1];
1098/* XXX Dangerous, how to pass PHY packet to device driver */
1099	fp->mode.common.tcode |= FWTCODE_PHY;
1100
1101	if (firewire_debug)
1102		printf("send phy_config root_node=%d gap_count=%d\n",
1103						root_node, gap_count);
1104	fw_asyreq(fc, -1, xfer);
1105}
1106
1107#if 0
1108/*
1109 * Dump self ID.
1110 */
1111static void
1112fw_print_sid(u_int32_t sid)
1113{
1114	union fw_self_id *s;
1115	s = (union fw_self_id *) &sid;
1116	printf("node:%d link:%d gap:%d spd:%d del:%d con:%d pwr:%d"
1117		" p0:%d p1:%d p2:%d i:%d m:%d\n",
1118		s->p0.phy_id, s->p0.link_active, s->p0.gap_count,
1119		s->p0.phy_speed, s->p0.phy_delay, s->p0.contender,
1120		s->p0.power_class, s->p0.port0, s->p0.port1,
1121		s->p0.port2, s->p0.initiated_reset, s->p0.more_packets);
1122}
1123#endif
1124
1125/*
1126 * To receive self ID.
1127 */
1128void fw_sidrcv(struct firewire_comm* fc, u_int32_t *sid, u_int len)
1129{
1130	u_int32_t *p;
1131	union fw_self_id *self_id;
1132	u_int i, j, node, c_port = 0, i_branch = 0;
1133
1134	fc->sid_cnt = len /(sizeof(u_int32_t) * 2);
1135	fc->status = FWBUSINIT;
1136	fc->max_node = fc->nodeid & 0x3f;
1137	CSRARC(fc, NODE_IDS) = ((u_int32_t)fc->nodeid) << 16;
1138	fc->status = FWBUSCYMELECT;
1139	fc->topology_map->crc_len = 2;
1140	fc->topology_map->generation ++;
1141	fc->topology_map->self_id_count = 0;
1142	fc->topology_map->node_count = 0;
1143	fc->speed_map->generation ++;
1144	fc->speed_map->crc_len = 1 + (64*64 + 3) / 4;
1145	self_id = &fc->topology_map->self_id[0];
1146	for(i = 0; i < fc->sid_cnt; i ++){
1147		if (sid[1] != ~sid[0]) {
1148			printf("fw_sidrcv: invalid self-id packet\n");
1149			sid += 2;
1150			continue;
1151		}
1152		*self_id = *((union fw_self_id *)sid);
1153		fc->topology_map->crc_len++;
1154		if(self_id->p0.sequel == 0){
1155			fc->topology_map->node_count ++;
1156			c_port = 0;
1157#if 0
1158			fw_print_sid(sid[0]);
1159#endif
1160			node = self_id->p0.phy_id;
1161			if(fc->max_node < node){
1162				fc->max_node = self_id->p0.phy_id;
1163			}
1164			/* XXX I'm not sure this is the right speed_map */
1165			fc->speed_map->speed[node][node]
1166					= self_id->p0.phy_speed;
1167			for (j = 0; j < node; j ++) {
1168				fc->speed_map->speed[j][node]
1169					= fc->speed_map->speed[node][j]
1170					= min(fc->speed_map->speed[j][j],
1171							self_id->p0.phy_speed);
1172			}
1173			if ((fc->irm == -1 || self_id->p0.phy_id > fc->irm) &&
1174			  (self_id->p0.link_active && self_id->p0.contender)) {
1175				fc->irm = self_id->p0.phy_id;
1176			}
1177			if(self_id->p0.port0 >= 0x2){
1178				c_port++;
1179			}
1180			if(self_id->p0.port1 >= 0x2){
1181				c_port++;
1182			}
1183			if(self_id->p0.port2 >= 0x2){
1184				c_port++;
1185			}
1186		}
1187		if(c_port > 2){
1188			i_branch += (c_port - 2);
1189		}
1190		sid += 2;
1191		self_id++;
1192		fc->topology_map->self_id_count ++;
1193	}
1194	device_printf(fc->bdev, "%d nodes", fc->max_node + 1);
1195	/* CRC */
1196	fc->topology_map->crc = fw_crc16(
1197			(u_int32_t *)&fc->topology_map->generation,
1198			fc->topology_map->crc_len * 4);
1199	fc->speed_map->crc = fw_crc16(
1200			(u_int32_t *)&fc->speed_map->generation,
1201			fc->speed_map->crc_len * 4);
1202	/* byteswap and copy to CSR */
1203	p = (u_int32_t *)fc->topology_map;
1204	for (i = 0; i <= fc->topology_map->crc_len; i++)
1205		CSRARC(fc, TOPO_MAP + i * 4) = htonl(*p++);
1206	p = (u_int32_t *)fc->speed_map;
1207	CSRARC(fc, SPED_MAP) = htonl(*p++);
1208	CSRARC(fc, SPED_MAP + 4) = htonl(*p++);
1209	/* don't byte-swap u_int8_t array */
1210	bcopy(p, &CSRARC(fc, SPED_MAP + 8), (fc->speed_map->crc_len - 1)*4);
1211
1212	fc->max_hop = fc->max_node - i_branch;
1213	printf(", maxhop <= %d", fc->max_hop);
1214
1215	if(fc->irm == -1 ){
1216		printf(", Not found IRM capable node");
1217	}else{
1218		printf(", cable IRM = %d", fc->irm);
1219		if (fc->irm == fc->nodeid)
1220			printf(" (me)");
1221	}
1222	printf("\n");
1223
1224	if (try_bmr && (fc->irm != -1) && (CSRARC(fc, BUS_MGR_ID) == 0x3f)) {
1225		if (fc->irm == fc->nodeid) {
1226			fc->status = FWBUSMGRDONE;
1227			CSRARC(fc, BUS_MGR_ID) = fc->set_bmr(fc, fc->irm);
1228			fw_bmr(fc);
1229		} else {
1230			fc->status = FWBUSMGRELECT;
1231			callout_reset(&fc->bmr_callout, hz/8,
1232				(void *)fw_try_bmr, (void *)fc);
1233		}
1234	} else
1235		fc->status = FWBUSMGRDONE;
1236
1237	callout_reset(&fc->busprobe_callout, hz/4,
1238			(void *)fw_bus_probe, (void *)fc);
1239}
1240
1241/*
1242 * To probe devices on the IEEE1394 bus.
1243 */
1244static void
1245fw_bus_probe(struct firewire_comm *fc)
1246{
1247	int s;
1248	struct fw_device *fwdev, *next;
1249
1250	s = splfw();
1251	fc->status = FWBUSEXPLORE;
1252	fc->retry_count = 0;
1253
1254/*
1255 * Invalidate all devices, just after bus reset. Devices
1256 * to be removed has not been seen longer time.
1257 */
1258	for (fwdev = STAILQ_FIRST(&fc->devices); fwdev != NULL; fwdev = next) {
1259		next = STAILQ_NEXT(fwdev, link);
1260		if (fwdev->status != FWDEVINVAL) {
1261			fwdev->status = FWDEVINVAL;
1262			fwdev->rcnt = 0;
1263		} else if(fwdev->rcnt < FW_MAXDEVRCNT) {
1264			fwdev->rcnt ++;
1265		} else {
1266			STAILQ_REMOVE(&fc->devices, fwdev, fw_device, link);
1267			free(fwdev, M_FW);
1268		}
1269	}
1270	fc->ongonode = 0;
1271	fc->ongoaddr = CSRROMOFF;
1272	fc->ongodev = NULL;
1273	fc->ongoeui.hi = 0xffffffff; fc->ongoeui.lo = 0xffffffff;
1274	fw_bus_explore(fc);
1275	splx(s);
1276}
1277
1278/*
1279 * To collect device informations on the IEEE1394 bus.
1280 */
1281static void
1282fw_bus_explore(struct firewire_comm *fc )
1283{
1284	int err = 0;
1285	struct fw_device *fwdev, *pfwdev, *tfwdev;
1286	u_int32_t addr;
1287	struct fw_xfer *xfer;
1288	struct fw_pkt *fp;
1289
1290	if(fc->status != FWBUSEXPLORE)
1291		return;
1292
1293loop:
1294	if(fc->ongonode == fc->nodeid) fc->ongonode++;
1295
1296	if(fc->ongonode > fc->max_node) goto done;
1297	if(fc->ongonode >= 0x3f) goto done;
1298
1299	/* check link */
1300	/* XXX we need to check phy_id first */
1301	if (!fc->topology_map->self_id[fc->ongonode].p0.link_active) {
1302		if (firewire_debug)
1303			printf("node%d: link down\n", fc->ongonode);
1304		fc->ongonode++;
1305		goto loop;
1306	}
1307
1308	if(fc->ongoaddr <= CSRROMOFF &&
1309		fc->ongoeui.hi == 0xffffffff &&
1310		fc->ongoeui.lo == 0xffffffff ){
1311		fc->ongoaddr = CSRROMOFF;
1312		addr = 0xf0000000 | fc->ongoaddr;
1313	}else if(fc->ongoeui.hi == 0xffffffff ){
1314		fc->ongoaddr = CSRROMOFF + 0xc;
1315		addr = 0xf0000000 | fc->ongoaddr;
1316	}else if(fc->ongoeui.lo == 0xffffffff ){
1317		fc->ongoaddr = CSRROMOFF + 0x10;
1318		addr = 0xf0000000 | fc->ongoaddr;
1319	}else if(fc->ongodev == NULL){
1320		STAILQ_FOREACH(fwdev, &fc->devices, link)
1321			if (FW_EUI64_EQUAL(fwdev->eui, fc->ongoeui))
1322				break;
1323		if(fwdev != NULL){
1324			fwdev->dst = fc->ongonode;
1325			fwdev->status = FWDEVINIT;
1326			fc->ongodev = fwdev;
1327			fc->ongoaddr = CSRROMOFF;
1328			addr = 0xf0000000 | fc->ongoaddr;
1329			goto dorequest;
1330		}
1331		fwdev = malloc(sizeof(struct fw_device), M_FW,
1332							M_NOWAIT | M_ZERO);
1333		if(fwdev == NULL)
1334			return;
1335		fwdev->fc = fc;
1336		fwdev->rommax = 0;
1337		fwdev->dst = fc->ongonode;
1338		fwdev->eui.hi = fc->ongoeui.hi; fwdev->eui.lo = fc->ongoeui.lo;
1339		fwdev->status = FWDEVINIT;
1340		fwdev->speed = fc->speed_map->speed[fc->nodeid][fc->ongonode];
1341
1342		pfwdev = NULL;
1343		STAILQ_FOREACH(tfwdev, &fc->devices, link) {
1344			if (tfwdev->eui.hi > fwdev->eui.hi ||
1345					(tfwdev->eui.hi == fwdev->eui.hi &&
1346					tfwdev->eui.lo > fwdev->eui.lo))
1347				break;
1348			pfwdev = tfwdev;
1349		}
1350		if (pfwdev == NULL)
1351			STAILQ_INSERT_HEAD(&fc->devices, fwdev, link);
1352		else
1353			STAILQ_INSERT_AFTER(&fc->devices, pfwdev, fwdev, link);
1354
1355		device_printf(fc->bdev, "New %s device ID:%08x%08x\n",
1356			linkspeed[fwdev->speed],
1357			fc->ongoeui.hi, fc->ongoeui.lo);
1358
1359		fc->ongodev = fwdev;
1360		fc->ongoaddr = CSRROMOFF;
1361		addr = 0xf0000000 | fc->ongoaddr;
1362	}else{
1363		addr = 0xf0000000 | fc->ongoaddr;
1364	}
1365dorequest:
1366#if 0
1367	xfer = asyreqq(fc, FWSPD_S100, 0, 0,
1368		((FWLOCALBUS | fc->ongonode) << 16) | 0xffff , addr,
1369		fw_bus_explore_callback);
1370	if(xfer == NULL) goto done;
1371#else
1372	xfer = fw_xfer_alloc_buf(M_FWXFER, 16, 16);
1373	if(xfer == NULL){
1374		goto done;
1375	}
1376	xfer->spd = 0;
1377	fp = (struct fw_pkt *)xfer->send.buf;
1378	fp->mode.rreqq.dest_hi = 0xffff;
1379	fp->mode.rreqq.tlrt = 0;
1380	fp->mode.rreqq.tcode = FWTCODE_RREQQ;
1381	fp->mode.rreqq.pri = 0;
1382	fp->mode.rreqq.src = 0;
1383	xfer->dst = FWLOCALBUS | fc->ongonode;
1384	fp->mode.rreqq.dst = xfer->dst;
1385	fp->mode.rreqq.dest_lo = addr;
1386	xfer->act.hand = fw_bus_explore_callback;
1387
1388	if (firewire_debug)
1389		printf("node%d: explore addr=0x%x\n",
1390				fc->ongonode, fc->ongoaddr);
1391	err = fw_asyreq(fc, -1, xfer);
1392	if(err){
1393		fw_xfer_free( xfer);
1394		return;
1395	}
1396#endif
1397	return;
1398done:
1399	/* fw_attach_devs */
1400	fc->status = FWBUSEXPDONE;
1401	if (firewire_debug)
1402		printf("bus_explore done\n");
1403	fw_attach_dev(fc);
1404	return;
1405
1406}
1407
1408/* Portable Async. request read quad */
1409struct fw_xfer *
1410asyreqq(struct firewire_comm *fc, u_int8_t spd, u_int8_t tl, u_int8_t rt,
1411	u_int32_t addr_hi, u_int32_t addr_lo,
1412	void (*hand) __P((struct fw_xfer*)))
1413{
1414	struct fw_xfer *xfer;
1415	struct fw_pkt *fp;
1416	int err;
1417
1418	xfer = fw_xfer_alloc_buf(M_FWXFER, 16, 16);
1419	if (xfer == NULL)
1420		return NULL;
1421
1422	xfer->spd = spd; /* XXX:min(spd, fc->spd) */
1423	fp = (struct fw_pkt *)xfer->send.buf;
1424	fp->mode.rreqq.dest_hi = addr_hi & 0xffff;
1425	if(tl & FWP_TL_VALID){
1426		fp->mode.rreqq.tlrt = (tl & 0x3f) << 2;
1427	}else{
1428		fp->mode.rreqq.tlrt = 0;
1429	}
1430	fp->mode.rreqq.tlrt |= rt & 0x3;
1431	fp->mode.rreqq.tcode = FWTCODE_RREQQ;
1432	fp->mode.rreqq.pri = 0;
1433	fp->mode.rreqq.src = 0;
1434	xfer->dst = addr_hi >> 16;
1435	fp->mode.rreqq.dst = xfer->dst;
1436	fp->mode.rreqq.dest_lo = addr_lo;
1437	xfer->act.hand = hand;
1438
1439	err = fw_asyreq(fc, -1, xfer);
1440	if(err){
1441		fw_xfer_free( xfer);
1442		return NULL;
1443	}
1444	return xfer;
1445}
1446
1447/*
1448 * Callback for the IEEE1394 bus information collection.
1449 */
1450static void
1451fw_bus_explore_callback(struct fw_xfer *xfer)
1452{
1453	struct firewire_comm *fc;
1454	struct fw_pkt *sfp,*rfp;
1455	struct csrhdr *chdr;
1456	struct csrdir *csrd;
1457	struct csrreg *csrreg;
1458	u_int32_t offset;
1459
1460
1461	if(xfer == NULL) {
1462		printf("xfer == NULL\n");
1463		return;
1464	}
1465	fc = xfer->fc;
1466
1467	if (firewire_debug)
1468		printf("node%d: callback addr=0x%x\n",
1469			fc->ongonode, fc->ongoaddr);
1470
1471	if(xfer->resp != 0){
1472		printf("node%d: resp=%d addr=0x%x\n",
1473			fc->ongonode, xfer->resp, fc->ongoaddr);
1474		goto errnode;
1475	}
1476
1477	if(xfer->send.buf == NULL){
1478		printf("node%d: send.buf=NULL addr=0x%x\n",
1479			fc->ongonode, fc->ongoaddr);
1480		goto errnode;
1481	}
1482	sfp = (struct fw_pkt *)xfer->send.buf;
1483
1484	if(xfer->recv.buf == NULL){
1485		printf("node%d: recv.buf=NULL addr=0x%x\n",
1486			fc->ongonode, fc->ongoaddr);
1487		goto errnode;
1488	}
1489	rfp = (struct fw_pkt *)xfer->recv.buf;
1490#if 0
1491	{
1492		u_int32_t *qld;
1493		int i;
1494		qld = (u_int32_t *)xfer->recv.buf;
1495		printf("len:%d\n", xfer->recv.len);
1496		for( i = 0 ; i <= xfer->recv.len && i < 32; i+= 4){
1497			printf("0x%08x ", rfp->mode.ld[i/4]);
1498			if((i % 16) == 15) printf("\n");
1499		}
1500		if((i % 16) != 15) printf("\n");
1501	}
1502#endif
1503	if(fc->ongodev == NULL){
1504		if(sfp->mode.rreqq.dest_lo == (0xf0000000 | CSRROMOFF)){
1505			rfp->mode.rresq.data = ntohl(rfp->mode.rresq.data);
1506			chdr = (struct csrhdr *)(&rfp->mode.rresq.data);
1507/* If CSR is minimal confinguration, more investgation is not needed. */
1508			if(chdr->info_len == 1){
1509				if (firewire_debug)
1510					printf("node%d: minimal config\n",
1511								fc->ongonode);
1512				goto nextnode;
1513			}else{
1514				fc->ongoaddr = CSRROMOFF + 0xc;
1515			}
1516		}else if(sfp->mode.rreqq.dest_lo == (0xf0000000 |(CSRROMOFF + 0xc))){
1517			fc->ongoeui.hi = ntohl(rfp->mode.rresq.data);
1518			fc->ongoaddr = CSRROMOFF + 0x10;
1519		}else if(sfp->mode.rreqq.dest_lo == (0xf0000000 |(CSRROMOFF + 0x10))){
1520			fc->ongoeui.lo = ntohl(rfp->mode.rresq.data);
1521			if (fc->ongoeui.hi == 0 && fc->ongoeui.lo == 0) {
1522				if (firewire_debug)
1523					printf("node%d: eui64 is zero.\n",
1524							fc->ongonode);
1525				goto nextnode;
1526			}
1527			fc->ongoaddr = CSRROMOFF;
1528		}
1529	}else{
1530		if (fc->ongoaddr == CSRROMOFF &&
1531		    fc->ongodev->csrrom[0] == ntohl(rfp->mode.rresq.data)) {
1532			fc->ongodev->status = FWDEVATTACHED;
1533			goto nextnode;
1534		}
1535		fc->ongodev->csrrom[(fc->ongoaddr - CSRROMOFF)/4] = ntohl(rfp->mode.rresq.data);
1536		if(fc->ongoaddr > fc->ongodev->rommax){
1537			fc->ongodev->rommax = fc->ongoaddr;
1538		}
1539		csrd = SLIST_FIRST(&fc->ongocsr);
1540		if((csrd = SLIST_FIRST(&fc->ongocsr)) == NULL){
1541			chdr = (struct csrhdr *)(fc->ongodev->csrrom);
1542			offset = CSRROMOFF;
1543		}else{
1544			chdr = (struct csrhdr *)&fc->ongodev->csrrom[(csrd->off - CSRROMOFF)/4];
1545			offset = csrd->off;
1546		}
1547		if(fc->ongoaddr > (CSRROMOFF + 0x14) && fc->ongoaddr != offset){
1548			csrreg = (struct csrreg *)&fc->ongodev->csrrom[(fc->ongoaddr - CSRROMOFF)/4];
1549			if( csrreg->key == 0x81 || csrreg->key == 0xd1){
1550				csrd = SLIST_FIRST(&fc->csrfree);
1551				if(csrd == NULL){
1552					goto nextnode;
1553				}else{
1554					csrd->ongoaddr = fc->ongoaddr;
1555					fc->ongoaddr += csrreg->val * 4;
1556					csrd->off = fc->ongoaddr;
1557					SLIST_REMOVE_HEAD(&fc->csrfree, link);
1558					SLIST_INSERT_HEAD(&fc->ongocsr, csrd, link);
1559					goto nextaddr;
1560				}
1561			}
1562		}
1563		fc->ongoaddr += 4;
1564		if(((fc->ongoaddr - offset)/4 > chdr->crc_len) &&
1565				(fc->ongodev->rommax < 0x414)){
1566			if(fc->ongodev->rommax <= 0x414){
1567				csrd = SLIST_FIRST(&fc->csrfree);
1568				if(csrd == NULL) goto nextnode;
1569				csrd->off = fc->ongoaddr;
1570				csrd->ongoaddr = fc->ongoaddr;
1571				SLIST_REMOVE_HEAD(&fc->csrfree, link);
1572				SLIST_INSERT_HEAD(&fc->ongocsr, csrd, link);
1573			}
1574			goto nextaddr;
1575		}
1576
1577		while(((fc->ongoaddr - offset)/4 > chdr->crc_len)){
1578			if(csrd == NULL){
1579				goto nextnode;
1580			};
1581			fc->ongoaddr = csrd->ongoaddr + 4;
1582			SLIST_REMOVE_HEAD(&fc->ongocsr, link);
1583			SLIST_INSERT_HEAD(&fc->csrfree, csrd, link);
1584			csrd = SLIST_FIRST(&fc->ongocsr);
1585			if((csrd = SLIST_FIRST(&fc->ongocsr)) == NULL){
1586				chdr = (struct csrhdr *)(fc->ongodev->csrrom);
1587				offset = CSRROMOFF;
1588			}else{
1589				chdr = (struct csrhdr *)&(fc->ongodev->csrrom[(csrd->off - CSRROMOFF)/4]);
1590				offset = csrd->off;
1591			}
1592		}
1593		if((fc->ongoaddr - CSRROMOFF) > CSRROMSIZE){
1594			goto nextnode;
1595		}
1596	}
1597nextaddr:
1598	fw_xfer_free( xfer);
1599	fw_bus_explore(fc);
1600	return;
1601errnode:
1602	fc->retry_count++;
1603	if (fc->ongodev != NULL)
1604		fc->ongodev->status = FWDEVINVAL;
1605nextnode:
1606	fw_xfer_free( xfer);
1607	fc->ongonode++;
1608/* housekeeping work space */
1609	fc->ongoaddr = CSRROMOFF;
1610	fc->ongodev = NULL;
1611	fc->ongoeui.hi = 0xffffffff; fc->ongoeui.lo = 0xffffffff;
1612	while((csrd = SLIST_FIRST(&fc->ongocsr)) != NULL){
1613		SLIST_REMOVE_HEAD(&fc->ongocsr, link);
1614		SLIST_INSERT_HEAD(&fc->csrfree, csrd, link);
1615	}
1616	fw_bus_explore(fc);
1617	return;
1618}
1619
1620/*
1621 * To attach sub-devices layer onto IEEE1394 bus.
1622 */
1623static void
1624fw_attach_dev(struct firewire_comm *fc)
1625{
1626	struct fw_device *fwdev;
1627	struct fw_xfer *xfer;
1628	int i, err;
1629	device_t *devlistp;
1630	int devcnt;
1631	struct firewire_dev_comm *fdc;
1632
1633	STAILQ_FOREACH(fwdev, &fc->devices, link)
1634		if (fwdev->status == FWDEVINIT)
1635			fwdev->status = FWDEVATTACHED;
1636
1637	err = device_get_children(fc->bdev, &devlistp, &devcnt);
1638	if( err != 0 )
1639		return;
1640	for( i = 0 ; i < devcnt ; i++){
1641		if (device_get_state(devlistp[i]) >= DS_ATTACHED)  {
1642			fdc = device_get_softc(devlistp[i]);
1643			if (fdc->post_explore != NULL)
1644				fdc->post_explore(fdc);
1645		}
1646	}
1647	free(devlistp, M_TEMP);
1648
1649	/* call pending handlers */
1650	i = 0;
1651	while ((xfer = STAILQ_FIRST(&fc->pending))) {
1652		STAILQ_REMOVE_HEAD(&fc->pending, link);
1653		i++;
1654		if (xfer->act.hand)
1655			xfer->act.hand(xfer);
1656	}
1657	if (i > 0)
1658		printf("fw_attach_dev: %d pending handlers called\n", i);
1659	if (fc->retry_count > 0) {
1660		printf("probe failed for %d node\n", fc->retry_count);
1661#if 0
1662		callout_reset(&fc->retry_probe_callout, hz*2,
1663					(void *)fc->ibr, (void *)fc);
1664#endif
1665	}
1666	return;
1667}
1668
1669/*
1670 * To allocate uniq transaction label.
1671 */
1672static int
1673fw_get_tlabel(struct firewire_comm *fc, struct fw_xfer *xfer)
1674{
1675	u_int i;
1676	struct tlabel *tl, *tmptl;
1677	int s;
1678	static u_int32_t label = 0;
1679
1680	s = splfw();
1681	for( i = 0 ; i < 0x40 ; i ++){
1682		label = (label + 1) & 0x3f;
1683		for(tmptl = STAILQ_FIRST(&fc->tlabels[label]);
1684			tmptl != NULL; tmptl = STAILQ_NEXT(tmptl, link)){
1685			if(tmptl->xfer->dst == xfer->dst) break;
1686		}
1687		if(tmptl == NULL) {
1688			tl = malloc(sizeof(struct tlabel),M_FW,M_NOWAIT);
1689			if (tl == NULL) {
1690				splx(s);
1691				return (-1);
1692			}
1693			tl->xfer = xfer;
1694			STAILQ_INSERT_TAIL(&fc->tlabels[label], tl, link);
1695			splx(s);
1696			if (firewire_debug > 1)
1697				printf("fw_get_tlabel: dst=%d tl=%d\n",
1698						xfer->dst, label);
1699			return(label);
1700		}
1701	}
1702	splx(s);
1703
1704	printf("fw_get_tlabel: no free tlabel\n");
1705	return(-1);
1706}
1707
1708static void
1709fw_rcv_copy(struct fw_xfer *xfer, struct iovec *vec, int nvec)
1710{
1711	char *p;
1712	int res, i, len;
1713
1714	p = xfer->recv.buf;
1715	res = xfer->recv.len;
1716	for (i = 0; i < nvec; i++, vec++) {
1717		len = vec->iov_len;
1718		if (res < len) {
1719			printf("rcv buffer(%d) is %d bytes short.\n",
1720						xfer->recv.len, len - res);
1721			len = res;
1722		}
1723		bcopy(vec->iov_base, p, len);
1724		p += len;
1725		res -= len;
1726		if (res <= 0)
1727			break;
1728	}
1729	xfer->recv.len -= res;
1730}
1731
1732/*
1733 * Generic packet receving process.
1734 */
1735void
1736fw_rcv(struct firewire_comm *fc, struct iovec *vec, int nvec, u_int sub, u_int spd)
1737{
1738	struct fw_pkt *fp, *resfp;
1739	struct fw_xfer *xfer;
1740	struct fw_bind *bind;
1741	struct firewire_softc *sc;
1742	int tcode, s;
1743	int i, len, oldstate;
1744#if 0
1745	{
1746		u_int32_t *qld;
1747		int i;
1748		qld = (u_int32_t *)buf;
1749		printf("spd %d len:%d\n", spd, len);
1750		for( i = 0 ; i <= len && i < 32; i+= 4){
1751			printf("0x%08x ", ntohl(qld[i/4]));
1752			if((i % 16) == 15) printf("\n");
1753		}
1754		if((i % 16) != 15) printf("\n");
1755	}
1756#endif
1757	fp = (struct fw_pkt *)vec[0].iov_base;
1758	tcode = fp->mode.common.tcode;
1759#if 0 /* XXX this check is not valid for RRESQ and WREQQ */
1760	if (vec[0].iov_len < fc->tcode[tcode].hdr_len) {
1761#if __FreeBSD_version >= 500000
1762		printf("fw_rcv: iov_len(%zu) is less than"
1763#else
1764		printf("fw_rcv: iov_len(%u) is less than"
1765#endif
1766			" hdr_len(%d:tcode=%d)\n", vec[0].iov_len,
1767			fc->tcode[tcode].hdr_len, tcode);
1768	}
1769#endif
1770	switch (tcode) {
1771	case FWTCODE_WRES:
1772	case FWTCODE_RRESQ:
1773	case FWTCODE_RRESB:
1774	case FWTCODE_LRES:
1775		xfer = fw_tl2xfer(fc, fp->mode.hdr.src,
1776					fp->mode.hdr.tlrt >> 2);
1777		if(xfer == NULL) {
1778			printf("fw_rcv: unknown response "
1779					"tcode=%d src=0x%x tl=0x%x rt=%d data=0x%x\n",
1780					tcode,
1781					fp->mode.hdr.src,
1782					fp->mode.hdr.tlrt >> 2,
1783					fp->mode.hdr.tlrt & 3,
1784					fp->mode.rresq.data);
1785#if 1
1786			printf("try ad-hoc work around!!\n");
1787			xfer = fw_tl2xfer(fc, fp->mode.hdr.src,
1788					(fp->mode.hdr.tlrt >> 2)^3);
1789			if (xfer == NULL) {
1790				printf("no use...\n");
1791				goto err;
1792			}
1793#else
1794			goto err;
1795#endif
1796		}
1797		fw_rcv_copy(xfer, vec, nvec);
1798		xfer->resp = 0;
1799		/* make sure the packet is drained in AT queue */
1800		oldstate = xfer->state;
1801		xfer->state = FWXF_RCVD;
1802		switch (oldstate) {
1803		case FWXF_SENT:
1804			fw_xfer_done(xfer);
1805			break;
1806		case FWXF_START:
1807			if (firewire_debug)
1808				printf("not sent yet tl=%x\n", xfer->tl);
1809			break;
1810		default:
1811			printf("unexpected state %d\n", xfer->state);
1812		}
1813		return;
1814	case FWTCODE_WREQQ:
1815	case FWTCODE_WREQB:
1816	case FWTCODE_RREQQ:
1817	case FWTCODE_RREQB:
1818	case FWTCODE_LREQ:
1819		bind = fw_bindlookup(fc, fp->mode.rreqq.dest_hi,
1820			fp->mode.rreqq.dest_lo);
1821		if(bind == NULL){
1822#if __FreeBSD_version >= 500000
1823			printf("Unknown service addr 0x%08x:0x%08x tcode=%x src=0x%x data=%x\n",
1824#else
1825			printf("Unknown service addr 0x%08x:0x%08x tcode=%x src=0x%x data=%lx\n",
1826#endif
1827				fp->mode.wreqq.dest_hi,
1828				fp->mode.wreqq.dest_lo,
1829				tcode,
1830				fp->mode.hdr.src,
1831				ntohl(fp->mode.wreqq.data));
1832			if (fc->status == FWBUSRESET) {
1833				printf("fw_rcv: cannot respond(bus reset)!\n");
1834				goto err;
1835			}
1836			xfer = fw_xfer_alloc_buf(M_FWXFER, 16, 0);
1837			if(xfer == NULL){
1838				return;
1839			}
1840			xfer->spd = spd;
1841			resfp = (struct fw_pkt *)xfer->send.buf;
1842			switch (tcode) {
1843			case FWTCODE_WREQQ:
1844			case FWTCODE_WREQB:
1845				resfp->mode.hdr.tcode = FWTCODE_WRES;
1846				xfer->send.len = 12;
1847				break;
1848			case FWTCODE_RREQQ:
1849				resfp->mode.hdr.tcode = FWTCODE_RRESQ;
1850				xfer->send.len = 16;
1851				break;
1852			case FWTCODE_RREQB:
1853				resfp->mode.hdr.tcode = FWTCODE_RRESB;
1854				xfer->send.len = 16;
1855				break;
1856			case FWTCODE_LREQ:
1857				resfp->mode.hdr.tcode = FWTCODE_LRES;
1858				xfer->send.len = 16;
1859				break;
1860			}
1861			resfp->mode.hdr.dst = fp->mode.hdr.src;
1862			resfp->mode.hdr.tlrt = fp->mode.hdr.tlrt;
1863			resfp->mode.hdr.pri = fp->mode.hdr.pri;
1864			resfp->mode.rresb.rtcode = 7;
1865			resfp->mode.rresb.extcode = 0;
1866			resfp->mode.rresb.len = 0;
1867/*
1868			xfer->act.hand = fw_asy_callback;
1869*/
1870			xfer->act.hand = fw_xfer_free;
1871			if(fw_asyreq(fc, -1, xfer)){
1872				fw_xfer_free( xfer);
1873				return;
1874			}
1875			goto err;
1876		}
1877		len = 0;
1878		for (i = 0; i < nvec; i ++)
1879			len += vec[i].iov_len;
1880		switch(bind->act_type){
1881		case FWACT_XFER:
1882			/* splfw()?? */
1883			xfer = STAILQ_FIRST(&bind->xferlist);
1884			if (xfer == NULL) {
1885				printf("Discard a packet for this bind.\n");
1886				goto err;
1887			}
1888			STAILQ_REMOVE_HEAD(&bind->xferlist, link);
1889			fw_rcv_copy(xfer, vec, nvec);
1890			xfer->spd = spd;
1891			if (fc->status != FWBUSRESET)
1892				xfer->act.hand(xfer);
1893			else
1894				STAILQ_INSERT_TAIL(&fc->pending, xfer, link);
1895			return;
1896			break;
1897		case FWACT_CH:
1898			if(fc->ir[bind->sub]->queued >=
1899				fc->ir[bind->sub]->maxq){
1900				device_printf(fc->bdev,
1901					"Discard a packet %x %d\n",
1902					bind->sub,
1903					fc->ir[bind->sub]->queued);
1904				goto err;
1905			}
1906			xfer = STAILQ_FIRST(&bind->xferlist);
1907			if (xfer == NULL) {
1908				printf("Discard packet for this bind\n");
1909				goto err;
1910			}
1911			STAILQ_REMOVE_HEAD(&bind->xferlist, link);
1912			fw_rcv_copy(xfer, vec, nvec);
1913			xfer->spd = spd;
1914			s = splfw();
1915			fc->ir[bind->sub]->queued++;
1916			STAILQ_INSERT_TAIL(&fc->ir[bind->sub]->q, xfer, link);
1917			splx(s);
1918
1919			wakeup((caddr_t)fc->ir[bind->sub]);
1920
1921			return;
1922			break;
1923		default:
1924			goto err;
1925			break;
1926		}
1927		break;
1928	case FWTCODE_STREAM:
1929	{
1930		struct fw_xferq *xferq;
1931
1932		xferq = fc->ir[sub];
1933#if 0
1934		printf("stream rcv dma %d len %d off %d spd %d\n",
1935			sub, len, off, spd);
1936#endif
1937		if(xferq->queued >= xferq->maxq) {
1938			printf("receive queue is full\n");
1939			goto err;
1940		}
1941		/* XXX get xfer from xfer queue, we don't need copy for
1942			per packet mode */
1943		xfer = fw_xfer_alloc_buf(M_FWXFER, 0, /* XXX */
1944						vec[0].iov_len);
1945		if(xfer == NULL) goto err;
1946		fw_rcv_copy(xfer, vec, nvec);
1947		xfer->spd = spd;
1948		s = splfw();
1949		xferq->queued++;
1950		STAILQ_INSERT_TAIL(&xferq->q, xfer, link);
1951		splx(s);
1952		sc = device_get_softc(fc->bdev);
1953#if __FreeBSD_version >= 500000
1954		if (SEL_WAITING(&xferq->rsel))
1955#else
1956		if (&xferq->rsel.si_pid != 0)
1957#endif
1958			selwakeup(&xferq->rsel);
1959		if (xferq->flag & FWXFERQ_WAKEUP) {
1960			xferq->flag &= ~FWXFERQ_WAKEUP;
1961			wakeup((caddr_t)xferq);
1962		}
1963		if (xferq->flag & FWXFERQ_HANDLER) {
1964			xferq->hand(xferq);
1965		}
1966		return;
1967		break;
1968	}
1969	default:
1970		printf("fw_rcv: unknow tcode %d\n", tcode);
1971		break;
1972	}
1973err:
1974	return;
1975}
1976
1977/*
1978 * Post process for Bus Manager election process.
1979 */
1980static void
1981fw_try_bmr_callback(struct fw_xfer *xfer)
1982{
1983	struct fw_pkt *rfp;
1984	struct firewire_comm *fc;
1985	int bmr;
1986
1987	if (xfer == NULL)
1988		return;
1989	fc = xfer->fc;
1990	if (xfer->resp != 0)
1991		goto error;
1992	if (xfer->send.buf == NULL)
1993		goto error;
1994	if (xfer->recv.buf == NULL)
1995		goto error;
1996	rfp = (struct fw_pkt *)xfer->recv.buf;
1997	if (rfp->mode.lres.rtcode != FWRCODE_COMPLETE)
1998		goto error;
1999
2000	bmr = ntohl(rfp->mode.lres.payload[0]);
2001	if (bmr == 0x3f)
2002		bmr = fc->nodeid;
2003
2004	CSRARC(fc, BUS_MGR_ID) = fc->set_bmr(fc, bmr & 0x3f);
2005	fw_xfer_free(xfer);
2006	fw_bmr(fc);
2007	return;
2008
2009error:
2010	device_printf(fc->bdev, "bus manager election failed\n");
2011	fw_xfer_free(xfer);
2012}
2013
2014
2015/*
2016 * To candidate Bus Manager election process.
2017 */
2018static void
2019fw_try_bmr(void *arg)
2020{
2021	struct fw_xfer *xfer;
2022	struct firewire_comm *fc = (struct firewire_comm *)arg;
2023	struct fw_pkt *fp;
2024	int err = 0;
2025
2026	xfer = fw_xfer_alloc_buf(M_FWXFER, 24, 20);
2027	if(xfer == NULL){
2028		return;
2029	}
2030	xfer->spd = 0;
2031	fc->status = FWBUSMGRELECT;
2032
2033	fp = (struct fw_pkt *)xfer->send.buf;
2034	fp->mode.lreq.dest_hi = 0xffff;
2035	fp->mode.lreq.tlrt = 0;
2036	fp->mode.lreq.tcode = FWTCODE_LREQ;
2037	fp->mode.lreq.pri = 0;
2038	fp->mode.lreq.src = 0;
2039	fp->mode.lreq.len = 8;
2040	fp->mode.lreq.extcode = FW_LREQ_CMPSWAP;
2041	xfer->dst = FWLOCALBUS | fc->irm;
2042	fp->mode.lreq.dst = xfer->dst;
2043	fp->mode.lreq.dest_lo = 0xf0000000 | BUS_MGR_ID;
2044	fp->mode.lreq.payload[0] = htonl(0x3f);
2045	fp->mode.lreq.payload[1] = htonl(fc->nodeid);
2046	xfer->act.hand = fw_try_bmr_callback;
2047
2048	err = fw_asyreq(fc, -1, xfer);
2049	if(err){
2050		fw_xfer_free( xfer);
2051		return;
2052	}
2053	return;
2054}
2055
2056#ifdef FW_VMACCESS
2057/*
2058 * Software implementation for physical memory block access.
2059 * XXX:Too slow, usef for debug purpose only.
2060 */
2061static void
2062fw_vmaccess(struct fw_xfer *xfer){
2063	struct fw_pkt *rfp, *sfp = NULL;
2064	u_int32_t *ld = (u_int32_t *)xfer->recv.buf;
2065
2066	printf("vmaccess spd:%2x len:%03x data:%08x %08x %08x %08x\n",
2067			xfer->spd, xfer->recv.len, ntohl(ld[0]), ntohl(ld[1]), ntohl(ld[2]), ntohl(ld[3]));
2068	printf("vmaccess          data:%08x %08x %08x %08x\n", ntohl(ld[4]), ntohl(ld[5]), ntohl(ld[6]), ntohl(ld[7]));
2069	if(xfer->resp != 0){
2070		fw_xfer_free( xfer);
2071		return;
2072	}
2073	if(xfer->recv.buf == NULL){
2074		fw_xfer_free( xfer);
2075		return;
2076	}
2077	rfp = (struct fw_pkt *)xfer->recv.buf;
2078	switch(rfp->mode.hdr.tcode){
2079		/* XXX need fix for 64bit arch */
2080		case FWTCODE_WREQB:
2081			xfer->send.buf = malloc(12, M_FW, M_NOWAIT);
2082			xfer->send.len = 12;
2083			sfp = (struct fw_pkt *)xfer->send.buf;
2084			bcopy(rfp->mode.wreqb.payload,
2085				(caddr_t)ntohl(rfp->mode.wreqb.dest_lo), ntohs(rfp->mode.wreqb.len));
2086			sfp->mode.wres.tcode = FWTCODE_WRES;
2087			sfp->mode.wres.rtcode = 0;
2088			break;
2089		case FWTCODE_WREQQ:
2090			xfer->send.buf = malloc(12, M_FW, M_NOWAIT);
2091			xfer->send.len = 12;
2092			sfp->mode.wres.tcode = FWTCODE_WRES;
2093			*((u_int32_t *)(ntohl(rfp->mode.wreqb.dest_lo))) = rfp->mode.wreqq.data;
2094			sfp->mode.wres.rtcode = 0;
2095			break;
2096		case FWTCODE_RREQB:
2097			xfer->send.buf = malloc(16 + rfp->mode.rreqb.len, M_FW, M_NOWAIT);
2098			xfer->send.len = 16 + ntohs(rfp->mode.rreqb.len);
2099			sfp = (struct fw_pkt *)xfer->send.buf;
2100			bcopy((caddr_t)ntohl(rfp->mode.rreqb.dest_lo),
2101				sfp->mode.rresb.payload, (u_int16_t)ntohs(rfp->mode.rreqb.len));
2102			sfp->mode.rresb.tcode = FWTCODE_RRESB;
2103			sfp->mode.rresb.len = rfp->mode.rreqb.len;
2104			sfp->mode.rresb.rtcode = 0;
2105			sfp->mode.rresb.extcode = 0;
2106			break;
2107		case FWTCODE_RREQQ:
2108			xfer->send.buf = malloc(16, M_FW, M_NOWAIT);
2109			xfer->send.len = 16;
2110			sfp = (struct fw_pkt *)xfer->send.buf;
2111			sfp->mode.rresq.data = *(u_int32_t *)(ntohl(rfp->mode.rreqq.dest_lo));
2112			sfp->mode.wres.tcode = FWTCODE_RRESQ;
2113			sfp->mode.rresb.rtcode = 0;
2114			break;
2115		default:
2116			fw_xfer_free( xfer);
2117			return;
2118	}
2119	sfp->mode.hdr.dst = rfp->mode.hdr.src;
2120	xfer->dst = ntohs(rfp->mode.hdr.src);
2121	xfer->act.hand = fw_xfer_free;
2122	xfer->retry_req = fw_asybusy;
2123
2124	sfp->mode.hdr.tlrt = rfp->mode.hdr.tlrt;
2125	sfp->mode.hdr.pri = 0;
2126
2127	fw_asyreq(xfer->fc, -1, xfer);
2128/**/
2129	return;
2130}
2131#endif
2132
2133/*
2134 * CRC16 check-sum for IEEE1394 register blocks.
2135 */
2136u_int16_t
2137fw_crc16(u_int32_t *ptr, u_int32_t len){
2138	u_int32_t i, sum, crc = 0;
2139	int shift;
2140	len = (len + 3) & ~3;
2141	for(i = 0 ; i < len ; i+= 4){
2142		for( shift = 28 ; shift >= 0 ; shift -= 4){
2143			sum = ((crc >> 12) ^ (ptr[i/4] >> shift)) & 0xf;
2144			crc = (crc << 4) ^ ( sum << 12 ) ^ ( sum << 5) ^ sum;
2145		}
2146		crc &= 0xffff;
2147	}
2148	return((u_int16_t) crc);
2149}
2150
2151static int
2152fw_bmr(struct firewire_comm *fc)
2153{
2154	struct fw_device fwdev;
2155	union fw_self_id *self_id;
2156	int cmstr;
2157
2158	/* Check to see if the current root node is cycle master capable */
2159	self_id = &fc->topology_map->self_id[fc->max_node];
2160	if (fc->max_node > 0) {
2161		/* XXX check cmc bit of businfo block rather than contender */
2162		if (self_id->p0.link_active && self_id->p0.contender)
2163			cmstr = fc->max_node;
2164		else {
2165			device_printf(fc->bdev,
2166				"root node is not cycle master capable\n");
2167			/* XXX shall we be the cycle master? */
2168			cmstr = fc->nodeid;
2169			/* XXX need bus reset */
2170		}
2171	} else
2172		cmstr = -1;
2173
2174	device_printf(fc->bdev, "bus manager %d ", CSRARC(fc, BUS_MGR_ID));
2175	if(CSRARC(fc, BUS_MGR_ID) != fc->nodeid) {
2176		/* We are not the bus manager */
2177		printf("\n");
2178		return(0);
2179	}
2180	printf("(me)\n");
2181
2182	/* Optimize gapcount */
2183	if(fc->max_hop <= MAX_GAPHOP )
2184		fw_phy_config(fc, cmstr, gap_cnt[fc->max_hop]);
2185	/* If we are the cycle master, nothing to do */
2186	if (cmstr == fc->nodeid || cmstr == -1)
2187		return 0;
2188	/* Bus probe has not finished, make dummy fwdev for cmstr */
2189	bzero(&fwdev, sizeof(fwdev));
2190	fwdev.fc = fc;
2191	fwdev.dst = cmstr;
2192	fwdev.speed = 0;
2193	fwdev.maxrec = 8; /* 512 */
2194	fwdev.status = FWDEVINIT;
2195	/* Set cmstr bit on the cycle master */
2196	fwmem_write_quad(&fwdev, NULL, 0/*spd*/,
2197		0xffff, 0xf0000000 | STATE_SET, htonl(1 << 8),
2198		fw_asy_callback_free);
2199
2200	return 0;
2201}
2202
2203DRIVER_MODULE(firewire,fwohci,firewire_driver,firewire_devclass,0,0);
2204MODULE_VERSION(firewire, 1);
2205