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