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