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