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