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