firewire.c revision 172836
1139749Simp/*-
2117632Sharti * Copyright (c) 2003 Hidetoshi Shimokawa
3117632Sharti * Copyright (c) 1998-2002 Katsushi Kobayashi and Hidetoshi Shimokawa
4117632Sharti * All rights reserved.
5117632Sharti *
6117632Sharti * Redistribution and use in source and binary forms, with or without
7117632Sharti * modification, are permitted provided that the following conditions
8117632Sharti * are met:
9117632Sharti * 1. Redistributions of source code must retain the above copyright
10117632Sharti *    notice, this list of conditions and the following disclaimer.
11117632Sharti * 2. Redistributions in binary form must reproduce the above copyright
12117632Sharti *    notice, this list of conditions and the following disclaimer in the
13117632Sharti *    documentation and/or other materials provided with the distribution.
14117632Sharti * 3. All advertising materials mentioning features or use of this software
15117632Sharti *    must display the acknowledgement as bellow:
16117632Sharti *
17117632Sharti *    This product includes software developed by K. Kobayashi and H. Shimokawa
18117632Sharti *
19117632Sharti * 4. The name of the author may not be used to endorse or promote products
20117632Sharti *    derived from this software without specific prior written permission.
21117632Sharti *
22117632Sharti * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
23117632Sharti * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
24117632Sharti * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
25117632Sharti * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
26117632Sharti * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
27117632Sharti * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
28117632Sharti * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29117632Sharti * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
30117632Sharti * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31117632Sharti * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32117632Sharti * POSSIBILITY OF SUCH DAMAGE.
33117632Sharti *
34117632Sharti * $FreeBSD: head/sys/dev/firewire/firewire.c 172836 2007-10-20 23:23:23Z julian $
35117632Sharti *
36117632Sharti */
37117632Sharti
38117632Sharti#include <sys/param.h>
39119418Sobrien#include <sys/systm.h>
40117632Sharti#include <sys/types.h>
41117632Sharti
42117632Sharti#include <sys/kernel.h>
43117632Sharti#include <sys/module.h>
44117632Sharti#include <sys/malloc.h>
45117632Sharti#include <sys/conf.h>
46117632Sharti#include <sys/sysctl.h>
47117632Sharti#include <sys/kthread.h>
48117632Sharti
49117632Sharti#include <sys/kdb.h>
50117632Sharti
51117632Sharti#if defined(__DragonFly__) || __FreeBSD_version < 500000
52117632Sharti#include <machine/clock.h>	/* for DELAY() */
53117632Sharti#endif
54117632Sharti
55117632Sharti#include <sys/bus.h>		/* used by smbus and newbus */
56117632Sharti#include <machine/bus.h>
57117632Sharti
58117632Sharti#ifdef __DragonFly__
59117632Sharti#include "firewire.h"
60117632Sharti#include "firewirereg.h"
61117632Sharti#include "fwmem.h"
62117632Sharti#include "iec13213.h"
63117632Sharti#include "iec68113.h"
64117632Sharti#else
65117632Sharti#include <dev/firewire/firewire.h>
66117632Sharti#include <dev/firewire/firewirereg.h>
67117632Sharti#include <dev/firewire/fwmem.h>
68117632Sharti#include <dev/firewire/iec13213.h>
69117632Sharti#include <dev/firewire/iec68113.h>
70117632Sharti#endif
71117632Sharti
72117632Shartistruct crom_src_buf {
73117632Sharti	struct crom_src	src;
74117632Sharti	struct crom_chunk root;
75117632Sharti	struct crom_chunk vendor;
76117632Sharti	struct crom_chunk hw;
77117632Sharti};
78117632Sharti
79117632Shartiint firewire_debug=0, try_bmr=1, hold_count=3;
80117632ShartiSYSCTL_INT(_debug, OID_AUTO, firewire_debug, CTLFLAG_RW, &firewire_debug, 0,
81117632Sharti	"FireWire driver debug flag");
82117632ShartiSYSCTL_NODE(_hw, OID_AUTO, firewire, CTLFLAG_RD, 0, "FireWire Subsystem");
83117632ShartiSYSCTL_INT(_hw_firewire, OID_AUTO, try_bmr, CTLFLAG_RW, &try_bmr, 0,
84117632Sharti	"Try to be a bus manager");
85117632ShartiSYSCTL_INT(_hw_firewire, OID_AUTO, hold_count, CTLFLAG_RW, &hold_count, 0,
86117632Sharti	"Number of count of bus resets for removing lost device information");
87117632Sharti
88117632ShartiMALLOC_DEFINE(M_FW, "firewire", "FireWire");
89117632ShartiMALLOC_DEFINE(M_FWXFER, "fw_xfer", "XFER/FireWire");
90117632Sharti
91117632Sharti#define FW_MAXASYRTY 4
92117632Sharti
93117632Shartidevclass_t firewire_devclass;
94117632Sharti
95117632Shartistatic void firewire_identify	(driver_t *, device_t);
96117632Shartistatic int firewire_probe	(device_t);
97117632Shartistatic int firewire_attach      (device_t);
98117632Shartistatic int firewire_detach      (device_t);
99117632Shartistatic int firewire_resume      (device_t);
100117632Shartistatic void firewire_xfer_timeout(void *, int);
101117632Sharti#if 0
102117632Shartistatic int firewire_shutdown    (device_t);
103117632Sharti#endif
104117632Shartistatic device_t firewire_add_child   (device_t, int, const char *, int);
105117632Shartistatic void fw_try_bmr (void *);
106117632Shartistatic void fw_try_bmr_callback (struct fw_xfer *);
107117632Shartistatic void fw_asystart (struct fw_xfer *);
108117632Shartistatic int fw_get_tlabel (struct firewire_comm *, struct fw_xfer *);
109117632Shartistatic void fw_bus_probe (struct firewire_comm *);
110117632Shartistatic void fw_attach_dev (struct firewire_comm *);
111117632Shartistatic void fw_bus_probe_thread(void *);
112117632Sharti#ifdef FW_VMACCESS
113117632Shartistatic void fw_vmaccess (struct fw_xfer *);
114117632Sharti#endif
115117632Shartistatic int fw_bmr (struct firewire_comm *);
116117632Shartistatic void fw_dump_hdr(struct fw_pkt *, char *);
117117632Sharti
118117632Shartistatic device_method_t firewire_methods[] = {
119117632Sharti	/* Device interface */
120117632Sharti	DEVMETHOD(device_identify,	firewire_identify),
121117632Sharti	DEVMETHOD(device_probe,		firewire_probe),
122147256Sbrooks	DEVMETHOD(device_attach,	firewire_attach),
123117632Sharti	DEVMETHOD(device_detach,	firewire_detach),
124117632Sharti	DEVMETHOD(device_suspend,	bus_generic_suspend),
125117632Sharti	DEVMETHOD(device_resume,	firewire_resume),
126117632Sharti	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
127117632Sharti
128147256Sbrooks	/* Bus interface */
129117632Sharti	DEVMETHOD(bus_add_child,	firewire_add_child),
130117632Sharti	DEVMETHOD(bus_print_child,	bus_generic_print_child),
131117632Sharti
132117632Sharti	{ 0, 0 }
133117632Sharti};
134117632Shartichar *linkspeed[] = {
135117632Sharti	"S100", "S200", "S400", "S800",
136117632Sharti	"S1600", "S3200", "undef", "undef"
137117632Sharti};
138117632Sharti
139117632Shartistatic char *tcode_str[] = {
140117632Sharti	"WREQQ", "WREQB", "WRES",   "undef",
141117632Sharti	"RREQQ", "RREQB", "RRESQ",  "RRESB",
142117632Sharti	"CYCS",  "LREQ",  "STREAM", "LRES",
143117632Sharti	"undef", "undef", "PHY",    "undef"
144117632Sharti};
145117632Sharti
146117632Sharti/* IEEE-1394a Table C-2 Gap count as a function of hops*/
147117632Sharti#define MAX_GAPHOP 15
148117632Shartiu_int gap_cnt[] = { 5,  5,  7,  8, 10, 13, 16, 18,
149117632Sharti		   21, 24, 26, 29, 32, 35, 37, 40};
150117632Sharti
151117632Shartistatic driver_t firewire_driver = {
152147256Sbrooks	"firewire",
153117632Sharti	firewire_methods,
154117632Sharti	sizeof(struct firewire_softc),
155117632Sharti};
156117632Sharti
157117632Sharti/*
158117632Sharti * Lookup fwdev by node id.
159117632Sharti */
160117632Shartistruct fw_device *
161117632Shartifw_noderesolve_nodeid(struct firewire_comm *fc, int dst)
162117632Sharti{
163117632Sharti	struct fw_device *fwdev;
164147256Sbrooks	int s;
165117632Sharti
166117632Sharti	s = splfw();
167117632Sharti	STAILQ_FOREACH(fwdev, &fc->devices, link)
168117632Sharti		if (fwdev->dst == dst && fwdev->status != FWDEVINVAL)
169117632Sharti			break;
170117632Sharti	splx(s);
171117632Sharti
172117632Sharti	return fwdev;
173117632Sharti}
174117632Sharti
175117632Sharti/*
176117632Sharti * Lookup fwdev by EUI64.
177117632Sharti */
178117632Shartistruct fw_device *
179117632Shartifw_noderesolve_eui64(struct firewire_comm *fc, struct fw_eui64 *eui)
180117632Sharti{
181117632Sharti	struct fw_device *fwdev;
182117632Sharti	int s;
183117632Sharti
184117632Sharti	s = splfw();
185117632Sharti	FW_GLOCK(fc);
186117632Sharti	STAILQ_FOREACH(fwdev, &fc->devices, link)
187117632Sharti		if (FW_EUI64_EQUAL(fwdev->eui, *eui))
188117632Sharti			break;
189117632Sharti	FW_GUNLOCK(fc);
190117632Sharti	splx(s);
191117632Sharti
192117632Sharti	if(fwdev == NULL) return NULL;
193117632Sharti	if(fwdev->status == FWDEVINVAL) return NULL;
194117632Sharti	return fwdev;
195117632Sharti}
196117632Sharti
197117632Sharti/*
198117632Sharti * Async. request procedure for userland application.
199117632Sharti */
200117632Shartiint
201117632Shartifw_asyreq(struct firewire_comm *fc, int sub, struct fw_xfer *xfer)
202117632Sharti{
203117632Sharti	int err = 0;
204117632Sharti	struct fw_xferq *xferq;
205117632Sharti	int len;
206117632Sharti	struct fw_pkt *fp;
207117632Sharti	int tcode;
208117632Sharti	struct tcode_info *info;
209117632Sharti
210117632Sharti	if(xfer == NULL) return EINVAL;
211117632Sharti	if(xfer->hand == NULL){
212117632Sharti		printf("hand == NULL\n");
213117632Sharti		return EINVAL;
214117632Sharti	}
215117632Sharti	fp = &xfer->send.hdr;
216117632Sharti
217117632Sharti	tcode = fp->mode.common.tcode & 0xf;
218117632Sharti	info = &fc->tcode[tcode];
219117632Sharti	if (info->flag == 0) {
220117632Sharti		printf("invalid tcode=%x\n", tcode);
221117632Sharti		return EINVAL;
222117632Sharti	}
223117632Sharti
224117632Sharti	/* XXX allow bus explore packets only after bus rest */
225117632Sharti	if ((fc->status < FWBUSEXPLORE) &&
226117632Sharti	    ((tcode != FWTCODE_RREQQ) || (fp->mode.rreqq.dest_hi != 0xffff) ||
227117632Sharti	    (fp->mode.rreqq.dest_lo  < 0xf0000000) ||
228117632Sharti	    (fp->mode.rreqq.dest_lo >= 0xf0001000))) {
229117632Sharti		xfer->resp = EAGAIN;
230117632Sharti		xfer->flag = FWXF_BUSY;
231117632Sharti		return (EAGAIN);
232117632Sharti	}
233117632Sharti
234117632Sharti	if (info->flag & FWTI_REQ)
235117632Sharti		xferq = fc->atq;
236117632Sharti	else
237117632Sharti		xferq = fc->ats;
238117632Sharti	len = info->hdr_len;
239117632Sharti	if (xfer->send.pay_len > MAXREC(fc->maxrec)) {
240117632Sharti		printf("send.pay_len > maxrec\n");
241117632Sharti		return EINVAL;
242117632Sharti	}
243117632Sharti	if (info->flag & FWTI_BLOCK_STR)
244117632Sharti		len = fp->mode.stream.len;
245117632Sharti	else if (info->flag & FWTI_BLOCK_ASY)
246117632Sharti		len = fp->mode.rresb.len;
247117632Sharti	else
248117632Sharti		len = 0;
249117632Sharti	if (len != xfer->send.pay_len){
250117632Sharti		printf("len(%d) != send.pay_len(%d) %s(%x)\n",
251117632Sharti		    len, xfer->send.pay_len, tcode_str[tcode], tcode);
252117632Sharti		return EINVAL;
253117632Sharti	}
254117632Sharti
255117632Sharti	if(xferq->start == NULL){
256117632Sharti		printf("xferq->start == NULL\n");
257117632Sharti		return EINVAL;
258117632Sharti	}
259117632Sharti	if(!(xferq->queued < xferq->maxq)){
260117632Sharti		device_printf(fc->bdev, "Discard a packet (queued=%d)\n",
261117632Sharti			xferq->queued);
262117632Sharti		return EAGAIN;
263117632Sharti	}
264117632Sharti
265117632Sharti	xfer->tl = -1;
266117632Sharti	if (info->flag & FWTI_TLABEL) {
267117632Sharti		if (fw_get_tlabel(fc, xfer) < 0)
268117632Sharti			return EAGAIN;
269117632Sharti	}
270117632Sharti
271117632Sharti	xfer->resp = 0;
272117632Sharti	xfer->fc = fc;
273117632Sharti	xfer->q = xferq;
274117632Sharti
275117632Sharti	fw_asystart(xfer);
276117632Sharti	return err;
277117632Sharti}
278117632Sharti/*
279117632Sharti * Wakeup blocked process.
280117632Sharti */
281117632Shartivoid
282117632Shartifw_xferwake(struct fw_xfer *xfer)
283117632Sharti{
284117632Sharti	struct mtx *lock = &xfer->fc->wait_lock;
285147721Sharti
286117632Sharti	mtx_lock(lock);
287117632Sharti	xfer->flag |= FWXF_WAKE;
288117632Sharti	mtx_unlock(lock);
289117632Sharti
290117632Sharti	wakeup(xfer);
291117632Sharti	return;
292148887Srwatson}
293117632Sharti
294117632Shartiint
295117632Shartifw_xferwait(struct fw_xfer *xfer)
296117632Sharti{
297117632Sharti	struct mtx *lock = &xfer->fc->wait_lock;
298117632Sharti	int err = 0;
299117632Sharti
300117632Sharti	mtx_lock(lock);
301117632Sharti	if ((xfer->flag & FWXF_WAKE) == 0)
302117632Sharti		err = msleep((void *)xfer, lock, PWAIT|PCATCH, "fw_xferwait", 0);
303117632Sharti	mtx_unlock(lock);
304117632Sharti
305117632Sharti	return (err);
306147256Sbrooks}
307117632Sharti
308117632Sharti/*
309117632Sharti * Async. request with given xfer structure.
310117632Sharti */
311117632Shartistatic void
312117632Shartifw_asystart(struct fw_xfer *xfer)
313117632Sharti{
314117632Sharti	struct firewire_comm *fc = xfer->fc;
315117632Sharti	int s;
316117632Sharti	s = splfw();
317117632Sharti	/* Protect from interrupt/timeout */
318147256Sbrooks	FW_GLOCK(fc);
319117632Sharti	xfer->flag = FWXF_INQ;
320117632Sharti	STAILQ_INSERT_TAIL(&xfer->q->q, xfer, link);
321117632Sharti#if 0
322117632Sharti	xfer->q->queued ++;
323117632Sharti#endif
324117632Sharti	FW_GUNLOCK(fc);
325147256Sbrooks	splx(s);
326117632Sharti	/* XXX just queue for mbuf */
327117632Sharti	if (xfer->mbuf == NULL)
328117632Sharti		xfer->q->start(fc);
329117632Sharti	return;
330117632Sharti}
331117632Sharti
332147256Sbrooksstatic void
333117632Shartifirewire_identify(driver_t *driver, device_t parent)
334117632Sharti{
335117632Sharti	BUS_ADD_CHILD(parent, 0, "firewire", -1);
336117632Sharti}
337117632Sharti
338117632Shartistatic int
339117632Shartifirewire_probe(device_t dev)
340117632Sharti{
341117632Sharti	device_set_desc(dev, "IEEE1394(FireWire) bus");
342147256Sbrooks	return (0);
343117632Sharti}
344117632Sharti
345117632Shartistatic void
346117632Shartifirewire_xfer_timeout(void *arg, int pending)
347117632Sharti{
348117632Sharti	struct firewire_comm *fc = (struct firewire_comm *)arg;
349117632Sharti	struct fw_xfer *xfer, *txfer;
350117632Sharti	struct timeval tv;
351147256Sbrooks	struct timeval split_timeout;
352117632Sharti	STAILQ_HEAD(, fw_xfer) xfer_timeout;
353117632Sharti	int i, s;
354117632Sharti
355117632Sharti	split_timeout.tv_sec = 0;
356117632Sharti	split_timeout.tv_usec = 200 * 1000;	 /* 200 msec */
357117632Sharti
358117632Sharti	microtime(&tv);
359147256Sbrooks	timevalsub(&tv, &split_timeout);
360117632Sharti	STAILQ_INIT(&xfer_timeout);
361117632Sharti
362117632Sharti	s = splfw();
363117632Sharti	mtx_lock(&fc->tlabel_lock);
364117632Sharti	for (i = 0; i < 0x40; i ++) {
365117632Sharti		while ((xfer = STAILQ_FIRST(&fc->tlabels[i])) != NULL) {
366117632Sharti			if ((xfer->flag & FWXF_SENT) == 0)
367147256Sbrooks				/* not sent yet */
368117632Sharti				break;
369117632Sharti			if (timevalcmp(&xfer->tv, &tv, >))
370117632Sharti				/* the rests are newer than this */
371117632Sharti				break;
372117632Sharti			device_printf(fc->bdev,
373117632Sharti				"split transaction timeout: "
374117632Sharti				"tl=0x%x flag=0x%02x\n", i, xfer->flag);
375117632Sharti			fw_dump_hdr(&xfer->send.hdr, "send");
376254804Sandre			xfer->resp = ETIMEDOUT;
377117632Sharti			STAILQ_REMOVE_HEAD(&fc->tlabels[i], tlabel);
378117632Sharti			STAILQ_INSERT_TAIL(&xfer_timeout, xfer, tlabel);
379117632Sharti		}
380147256Sbrooks	}
381117632Sharti	mtx_unlock(&fc->tlabel_lock);
382117632Sharti	splx(s);
383117632Sharti	fc->timeout(fc);
384117632Sharti
385117632Sharti	STAILQ_FOREACH_SAFE(xfer, &xfer_timeout, tlabel, txfer)
386117632Sharti		xfer->hand(xfer);
387117632Sharti}
388117632Sharti
389118539Sharti#define WATCHDOG_HZ 10
390117632Shartistatic void
391117632Shartifirewire_watchdog(void *arg)
392117632Sharti{
393117632Sharti	struct firewire_comm *fc;
394117632Sharti	static int watchdog_clock = 0;
395117632Sharti
396117632Sharti	fc = (struct firewire_comm *)arg;
397117632Sharti
398117632Sharti	/*
399117632Sharti	 * At boot stage, the device interrupt is disabled and
400117632Sharti	 * We encounter a timeout easily. To avoid this,
401117632Sharti	 * ignore clock interrupt for a while.
402117632Sharti	 */
403117632Sharti	if (watchdog_clock > WATCHDOG_HZ * 15)
404117632Sharti		taskqueue_enqueue(fc->taskqueue, &fc->task_timeout);
405117632Sharti	else
406117632Sharti		watchdog_clock ++;
407117632Sharti
408117632Sharti	callout_reset(&fc->timeout_callout, hz / WATCHDOG_HZ,
409117632Sharti			(void *)firewire_watchdog, (void *)fc);
410117632Sharti}
411117632Sharti
412117632Sharti/*
413117632Sharti * The attach routine.
414117632Sharti */
415117632Shartistatic int
416117632Shartifirewire_attach(device_t dev)
417117632Sharti{
418147256Sbrooks	int unit;
419117632Sharti	struct firewire_softc *sc = device_get_softc(dev);
420117632Sharti	device_t pa = device_get_parent(dev);
421117632Sharti	struct firewire_comm *fc;
422117632Sharti
423117632Sharti	fc = (struct firewire_comm *)device_get_softc(pa);
424117632Sharti	sc->fc = fc;
425117872Sharti	fc->status = FWBUSNOTREADY;
426117632Sharti
427117632Sharti	unit = device_get_unit(dev);
428117632Sharti	if( fc->nisodma > FWMAXNDMA) fc->nisodma = FWMAXNDMA;
429117632Sharti
430117632Sharti	fwdev_makedev(sc);
431117632Sharti
432117632Sharti	mtx_init(&fc->wait_lock, "fwwait", NULL, MTX_DEF);
433117632Sharti	mtx_init(&fc->tlabel_lock, "fwtlabel", NULL, MTX_DEF);
434117632Sharti	CALLOUT_INIT(&fc->timeout_callout);
435117632Sharti	CALLOUT_INIT(&fc->bmr_callout);
436117632Sharti	CALLOUT_INIT(&fc->busprobe_callout);
437117632Sharti	TASK_INIT(&fc->task_timeout, 0, firewire_xfer_timeout, (void *)fc);
438117632Sharti
439117632Sharti	callout_reset(&sc->fc->timeout_callout, hz,
440117632Sharti			(void *)firewire_watchdog, (void *)sc->fc);
441243857Sglebius
442117632Sharti	/* create thread */
443117632Sharti	kproc_create(fw_bus_probe_thread, (void *)fc, &fc->probe_thread,
444147256Sbrooks		0, 0, "fw%d_probe", unit);
445117632Sharti
446117632Sharti	/* Locate our children */
447117632Sharti	bus_generic_probe(dev);
448117632Sharti
449117632Sharti	/* launch attachement of the added children */
450117632Sharti	bus_generic_attach(dev);
451117632Sharti
452117632Sharti	/* bus_reset */
453117632Sharti	fw_busreset(fc, FWBUSNOTREADY);
454117632Sharti	fc->ibr(fc);
455117632Sharti
456117632Sharti	return 0;
457117632Sharti}
458117632Sharti
459117632Sharti/*
460117632Sharti * Attach it as child.
461117632Sharti */
462117632Shartistatic device_t
463117632Shartifirewire_add_child(device_t dev, int order, const char *name, int unit)
464117632Sharti{
465117632Sharti        device_t child;
466117632Sharti	struct firewire_softc *sc;
467117632Sharti
468117632Sharti	sc = (struct firewire_softc *)device_get_softc(dev);
469117632Sharti	child = device_add_child(dev, name, unit);
470117632Sharti	if (child) {
471117632Sharti		device_set_ivars(child, sc->fc);
472117632Sharti		device_probe_and_attach(child);
473117632Sharti	}
474117632Sharti
475117632Sharti	return child;
476254804Sandre}
477117632Sharti
478117632Shartistatic int
479117632Shartifirewire_resume(device_t dev)
480117632Sharti{
481117632Sharti	struct firewire_softc *sc;
482117632Sharti
483117632Sharti	sc = (struct firewire_softc *)device_get_softc(dev);
484117632Sharti	sc->fc->status = FWBUSNOTREADY;
485117632Sharti
486117632Sharti	bus_generic_resume(dev);
487117632Sharti
488117632Sharti	return(0);
489117632Sharti}
490117632Sharti
491117632Sharti/*
492117632Sharti * Dettach it.
493117632Sharti */
494117632Shartistatic int
495117632Shartifirewire_detach(device_t dev)
496117632Sharti{
497117632Sharti	struct firewire_softc *sc;
498117632Sharti	struct firewire_comm *fc;
499117632Sharti	struct fw_device *fwdev, *fwdev_next;
500117632Sharti	int err;
501117632Sharti
502254804Sandre	sc = (struct firewire_softc *)device_get_softc(dev);
503117632Sharti	fc = sc->fc;
504117632Sharti	mtx_lock(&fc->wait_lock);
505117632Sharti	fc->status = FWBUSDETACH;
506117632Sharti	wakeup(fc);
507117632Sharti	if (msleep(fc->probe_thread, &fc->wait_lock, PWAIT, "fwthr", hz * 60))
508117632Sharti		printf("firewire probe thread didn't die\n");
509117632Sharti	mtx_unlock(&fc->wait_lock);
510117632Sharti
511117632Sharti	if ((err = fwdev_destroydev(sc)) != 0)
512117632Sharti		return err;
513117632Sharti
514117632Sharti	if ((err = bus_generic_detach(dev)) != 0)
515117632Sharti		return err;
516117632Sharti
517117632Sharti	callout_stop(&fc->timeout_callout);
518117632Sharti	callout_stop(&fc->bmr_callout);
519117632Sharti	callout_stop(&fc->busprobe_callout);
520117632Sharti
521117632Sharti	/* XXX xfree_free and untimeout on all xfers */
522117632Sharti	for (fwdev = STAILQ_FIRST(&fc->devices); fwdev != NULL;
523117632Sharti							fwdev = fwdev_next) {
524117632Sharti		fwdev_next = STAILQ_NEXT(fwdev, link);
525117632Sharti		free(fwdev, M_FW);
526117632Sharti	}
527117632Sharti	free(fc->topology_map, M_FW);
528117632Sharti	free(fc->speed_map, M_FW);
529117632Sharti	free(fc->crom_src_buf, M_FW);
530117632Sharti
531117632Sharti	mtx_destroy(&fc->tlabel_lock);
532117632Sharti	mtx_destroy(&fc->wait_lock);
533117632Sharti	return(0);
534117632Sharti}
535243857Sglebius#if 0
536147256Sbrooksstatic int
537117632Shartifirewire_shutdown( device_t dev )
538117632Sharti{
539117632Sharti	return 0;
540117632Sharti}
541117632Sharti#endif
542117632Sharti
543117632Sharti
544147256Sbrooksstatic void
545117632Shartifw_xferq_drain(struct fw_xferq *xferq)
546117632Sharti{
547117632Sharti	struct fw_xfer *xfer;
548117632Sharti
549117632Sharti	while ((xfer = STAILQ_FIRST(&xferq->q)) != NULL) {
550147256Sbrooks		STAILQ_REMOVE_HEAD(&xferq->q, link);
551117632Sharti#if 0
552117632Sharti		xferq->queued --;
553117632Sharti#endif
554117632Sharti		xfer->resp = EAGAIN;
555117632Sharti		xfer->flag = FWXF_SENTERR;
556117632Sharti		fw_xfer_done(xfer);
557117632Sharti	}
558117632Sharti}
559117632Sharti
560117632Shartivoid
561117632Shartifw_drain_txq(struct firewire_comm *fc)
562117632Sharti{
563117632Sharti	struct fw_xfer *xfer, *txfer;
564117632Sharti	STAILQ_HEAD(, fw_xfer) xfer_drain;
565117632Sharti	int i;
566117632Sharti
567117632Sharti	STAILQ_INIT(&xfer_drain);
568117632Sharti
569117632Sharti	FW_GLOCK(fc);
570117632Sharti	fw_xferq_drain(fc->atq);
571117632Sharti	fw_xferq_drain(fc->ats);
572117632Sharti	for(i = 0; i < fc->nisodma; i++)
573117632Sharti		fw_xferq_drain(fc->it[i]);
574117632Sharti	FW_GUNLOCK(fc);
575117632Sharti
576117632Sharti	mtx_lock(&fc->tlabel_lock);
577117632Sharti	for (i = 0; i < 0x40; i ++)
578117632Sharti		while ((xfer = STAILQ_FIRST(&fc->tlabels[i])) != NULL) {
579117632Sharti			if (firewire_debug)
580117632Sharti				printf("tl=%d flag=%d\n", i, xfer->flag);
581117632Sharti			xfer->resp = EAGAIN;
582117632Sharti			STAILQ_REMOVE_HEAD(&fc->tlabels[i], tlabel);
583117632Sharti			STAILQ_INSERT_TAIL(&xfer_drain, xfer, tlabel);
584117632Sharti		}
585117632Sharti	mtx_unlock(&fc->tlabel_lock);
586117632Sharti
587117632Sharti	STAILQ_FOREACH_SAFE(xfer, &xfer_drain, tlabel, txfer)
588117632Sharti		xfer->hand(xfer);
589117632Sharti}
590117632Sharti
591117632Shartistatic void
592117632Shartifw_reset_csr(struct firewire_comm *fc)
593117632Sharti{
594117632Sharti	int i;
595117632Sharti
596117632Sharti	CSRARC(fc, STATE_CLEAR)
597117632Sharti			= 1 << 23 | 0 << 17 | 1 << 16 | 1 << 15 | 1 << 14 ;
598117632Sharti	CSRARC(fc, STATE_SET) = CSRARC(fc, STATE_CLEAR);
599117632Sharti	CSRARC(fc, NODE_IDS) = 0x3f;
600117632Sharti
601117632Sharti	CSRARC(fc, TOPO_MAP + 8) = 0;
602117632Sharti	fc->irm = -1;
603117632Sharti
604117632Sharti	fc->max_node = -1;
605117632Sharti
606117632Sharti	for(i = 2; i < 0x100/4 - 2 ; i++){
607117632Sharti		CSRARC(fc, SPED_MAP + i * 4) = 0;
608117632Sharti	}
609117632Sharti	CSRARC(fc, STATE_CLEAR) = 1 << 23 | 0 << 17 | 1 << 16 | 1 << 15 | 1 << 14 ;
610117632Sharti	CSRARC(fc, STATE_SET) = CSRARC(fc, STATE_CLEAR);
611117632Sharti	CSRARC(fc, RESET_START) = 0;
612117632Sharti	CSRARC(fc, SPLIT_TIMEOUT_HI) = 0;
613117632Sharti	CSRARC(fc, SPLIT_TIMEOUT_LO) = 800 << 19;
614117632Sharti	CSRARC(fc, CYCLE_TIME) = 0x0;
615117632Sharti	CSRARC(fc, BUS_TIME) = 0x0;
616117632Sharti	CSRARC(fc, BUS_MGR_ID) = 0x3f;
617117632Sharti	CSRARC(fc, BANDWIDTH_AV) = 4915;
618117632Sharti	CSRARC(fc, CHANNELS_AV_HI) = 0xffffffff;
619117632Sharti	CSRARC(fc, CHANNELS_AV_LO) = 0xffffffff;
620117632Sharti	CSRARC(fc, IP_CHANNELS) = (1 << 31);
621117632Sharti
622117632Sharti	CSRARC(fc, CONF_ROM) = 0x04 << 24;
623117632Sharti	CSRARC(fc, CONF_ROM + 4) = 0x31333934; /* means strings 1394 */
624117632Sharti	CSRARC(fc, CONF_ROM + 8) = 1 << 31 | 1 << 30 | 1 << 29 |
625117632Sharti				1 << 28 | 0xff << 16 | 0x09 << 8;
626117632Sharti	CSRARC(fc, CONF_ROM + 0xc) = 0;
627117632Sharti
628117632Sharti/* DV depend CSRs see blue book */
629117632Sharti	CSRARC(fc, oPCR) &= ~DV_BROADCAST_ON;
630117632Sharti	CSRARC(fc, iPCR) &= ~DV_BROADCAST_ON;
631117632Sharti
632117632Sharti	CSRARC(fc, STATE_CLEAR) &= ~(1 << 23 | 1 << 15 | 1 << 14 );
633117632Sharti	CSRARC(fc, STATE_SET) = CSRARC(fc, STATE_CLEAR);
634117632Sharti}
635117632Sharti
636117632Shartistatic void
637117632Shartifw_init_crom(struct firewire_comm *fc)
638117632Sharti{
639117632Sharti	struct crom_src *src;
640117632Sharti
641117632Sharti	fc->crom_src_buf = (struct crom_src_buf *)
642117632Sharti		malloc(sizeof(struct crom_src_buf), M_FW, M_WAITOK | M_ZERO);
643117632Sharti	if (fc->crom_src_buf == NULL)
644117632Sharti		return;
645117632Sharti
646117632Sharti	src = &fc->crom_src_buf->src;
647117632Sharti	bzero(src, sizeof(struct crom_src));
648117632Sharti
649117632Sharti	/* BUS info sample */
650117632Sharti	src->hdr.info_len = 4;
651117632Sharti
652117632Sharti	src->businfo.bus_name = CSR_BUS_NAME_IEEE1394;
653117632Sharti
654117632Sharti	src->businfo.irmc = 1;
655117632Sharti	src->businfo.cmc = 1;
656117632Sharti	src->businfo.isc = 1;
657117632Sharti	src->businfo.bmc = 1;
658117632Sharti	src->businfo.pmc = 0;
659117632Sharti	src->businfo.cyc_clk_acc = 100;
660117632Sharti	src->businfo.max_rec = fc->maxrec;
661117632Sharti	src->businfo.max_rom = MAXROM_4;
662117632Sharti	src->businfo.generation = 1;
663117632Sharti	src->businfo.link_spd = fc->speed;
664117632Sharti
665117632Sharti	src->businfo.eui64.hi = fc->eui.hi;
666117632Sharti	src->businfo.eui64.lo = fc->eui.lo;
667117632Sharti
668117632Sharti	STAILQ_INIT(&src->chunk_list);
669117632Sharti
670117632Sharti	fc->crom_src = src;
671117632Sharti	fc->crom_root = &fc->crom_src_buf->root;
672117632Sharti}
673117632Sharti
674117632Shartistatic void
675117632Shartifw_reset_crom(struct firewire_comm *fc)
676117632Sharti{
677117632Sharti	struct crom_src_buf *buf;
678117632Sharti	struct crom_src *src;
679117632Sharti	struct crom_chunk *root;
680117632Sharti
681117632Sharti	if (fc->crom_src_buf == NULL)
682117632Sharti		fw_init_crom(fc);
683117632Sharti
684117632Sharti	buf =  fc->crom_src_buf;
685117632Sharti	src = fc->crom_src;
686117632Sharti	root = fc->crom_root;
687117632Sharti
688117632Sharti	STAILQ_INIT(&src->chunk_list);
689117632Sharti
690117632Sharti	bzero(root, sizeof(struct crom_chunk));
691117632Sharti	crom_add_chunk(src, NULL, root, 0);
692117632Sharti	crom_add_entry(root, CSRKEY_NCAP, 0x0083c0); /* XXX */
693254804Sandre	/* private company_id */
694117632Sharti	crom_add_entry(root, CSRKEY_VENDOR, CSRVAL_VENDOR_PRIVATE);
695117632Sharti#ifdef __DragonFly__
696117632Sharti	crom_add_simple_text(src, root, &buf->vendor, "DragonFly Project");
697117632Sharti	crom_add_entry(root, CSRKEY_HW, __DragonFly_cc_version);
698117632Sharti#else
699117632Sharti	crom_add_simple_text(src, root, &buf->vendor, "FreeBSD Project");
700117632Sharti	crom_add_entry(root, CSRKEY_HW, __FreeBSD_version);
701117632Sharti#endif
702117632Sharti	crom_add_simple_text(src, root, &buf->hw, hostname);
703117632Sharti}
704117632Sharti
705117632Sharti/*
706117632Sharti * Called after bus reset.
707117632Sharti */
708117632Shartivoid
709117632Shartifw_busreset(struct firewire_comm *fc, uint32_t new_status)
710117632Sharti{
711117632Sharti	struct firewire_dev_comm *fdc;
712117632Sharti	struct crom_src *src;
713117632Sharti	device_t *devlistp;
714117632Sharti	void *newrom;
715117632Sharti	int i, devcnt;
716118539Sharti
717117632Sharti	switch(fc->status){
718117632Sharti	case FWBUSMGRELECT:
719117632Sharti		callout_stop(&fc->bmr_callout);
720117632Sharti		break;
721117632Sharti	default:
722117632Sharti		break;
723117632Sharti	}
724117632Sharti	fc->status = new_status;
725117632Sharti	fw_reset_csr(fc);
726117632Sharti	fw_reset_crom(fc);
727117632Sharti
728117632Sharti	if (device_get_children(fc->bdev, &devlistp, &devcnt) == 0) {
729117632Sharti		for( i = 0 ; i < devcnt ; i++)
730117632Sharti			if (device_get_state(devlistp[i]) >= DS_ATTACHED)  {
731117632Sharti				fdc = device_get_softc(devlistp[i]);
732117632Sharti				if (fdc->post_busreset != NULL)
733117632Sharti					fdc->post_busreset(fdc);
734117632Sharti			}
735117632Sharti		free(devlistp, M_TEMP);
736117632Sharti	}
737117632Sharti
738117632Sharti	newrom = malloc(CROMSIZE, M_FW, M_NOWAIT | M_ZERO);
739117632Sharti	src = &fc->crom_src_buf->src;
740117632Sharti	crom_load(src, (uint32_t *)newrom, CROMSIZE);
741117632Sharti	if (bcmp(newrom, fc->config_rom, CROMSIZE) != 0) {
742117632Sharti		/* bump generation and reload */
743117632Sharti		src->businfo.generation ++;
744147256Sbrooks		/* generation must be between 0x2 and 0xF */
745117632Sharti		if (src->businfo.generation < 2)
746117632Sharti			src->businfo.generation ++;
747117632Sharti		crom_load(src, (uint32_t *)newrom, CROMSIZE);
748117632Sharti		bcopy(newrom, (void *)fc->config_rom, CROMSIZE);
749147256Sbrooks	}
750118158Sharti	free(newrom, M_FW);
751117632Sharti}
752117632Sharti
753117632Sharti/* Call once after reboot */
754117632Shartivoid fw_init(struct firewire_comm *fc)
755117632Sharti{
756117632Sharti	int i;
757117632Sharti#ifdef FW_VMACCESS
758117632Sharti	struct fw_xfer *xfer;
759117632Sharti	struct fw_bind *fwb;
760117632Sharti#endif
761117632Sharti
762117632Sharti	fc->arq->queued = 0;
763117632Sharti	fc->ars->queued = 0;
764117632Sharti	fc->atq->queued = 0;
765117632Sharti	fc->ats->queued = 0;
766117632Sharti
767117632Sharti	fc->arq->buf = NULL;
768117632Sharti	fc->ars->buf = NULL;
769117632Sharti	fc->atq->buf = NULL;
770117632Sharti	fc->ats->buf = NULL;
771117632Sharti
772117632Sharti	fc->arq->flag = 0;
773117632Sharti	fc->ars->flag = 0;
774117632Sharti	fc->atq->flag = 0;
775117632Sharti	fc->ats->flag = 0;
776117632Sharti
777117632Sharti	STAILQ_INIT(&fc->atq->q);
778117632Sharti	STAILQ_INIT(&fc->ats->q);
779117632Sharti
780117632Sharti	for( i = 0 ; i < fc->nisodma ; i ++ ){
781117632Sharti		fc->it[i]->queued = 0;
782117632Sharti		fc->ir[i]->queued = 0;
783117632Sharti
784117632Sharti		fc->it[i]->start = NULL;
785117632Sharti		fc->ir[i]->start = NULL;
786117632Sharti
787117632Sharti		fc->it[i]->buf = NULL;
788117632Sharti		fc->ir[i]->buf = NULL;
789117632Sharti
790117632Sharti		fc->it[i]->flag = FWXFERQ_STREAM;
791117632Sharti		fc->ir[i]->flag = FWXFERQ_STREAM;
792117632Sharti
793117632Sharti		STAILQ_INIT(&fc->it[i]->q);
794117632Sharti		STAILQ_INIT(&fc->ir[i]->q);
795117632Sharti	}
796117632Sharti
797117632Sharti	fc->arq->maxq = FWMAXQUEUE;
798117632Sharti	fc->ars->maxq = FWMAXQUEUE;
799117632Sharti	fc->atq->maxq = FWMAXQUEUE;
800117632Sharti	fc->ats->maxq = FWMAXQUEUE;
801117632Sharti
802117632Sharti	for( i = 0 ; i < fc->nisodma ; i++){
803117632Sharti		fc->ir[i]->maxq = FWMAXQUEUE;
804117632Sharti		fc->it[i]->maxq = FWMAXQUEUE;
805117632Sharti	}
806117632Sharti/* Initialize csr registers */
807117632Sharti	fc->topology_map = (struct fw_topology_map *)malloc(
808117632Sharti				sizeof(struct fw_topology_map),
809117632Sharti				M_FW, M_NOWAIT | M_ZERO);
810117632Sharti	fc->speed_map = (struct fw_speed_map *)malloc(
811117632Sharti				sizeof(struct fw_speed_map),
812117632Sharti				M_FW, M_NOWAIT | M_ZERO);
813117632Sharti	CSRARC(fc, TOPO_MAP) = 0x3f1 << 16;
814117632Sharti	CSRARC(fc, TOPO_MAP + 4) = 1;
815117632Sharti	CSRARC(fc, SPED_MAP) = 0x3f1 << 16;
816117632Sharti	CSRARC(fc, SPED_MAP + 4) = 1;
817117632Sharti
818117632Sharti	STAILQ_INIT(&fc->devices);
819117632Sharti
820117632Sharti/* Initialize Async handlers */
821117632Sharti	STAILQ_INIT(&fc->binds);
822117632Sharti	for( i = 0 ; i < 0x40 ; i++){
823117632Sharti		STAILQ_INIT(&fc->tlabels[i]);
824117632Sharti	}
825117632Sharti
826117632Sharti/* DV depend CSRs see blue book */
827117632Sharti#if 0
828117632Sharti	CSRARC(fc, oMPR) = 0x3fff0001; /* # output channel = 1 */
829117632Sharti	CSRARC(fc, oPCR) = 0x8000007a;
830117632Sharti	for(i = 4 ; i < 0x7c/4 ; i+=4){
831117632Sharti		CSRARC(fc, i + oPCR) = 0x8000007a;
832117632Sharti	}
833117632Sharti
834117632Sharti	CSRARC(fc, iMPR) = 0x00ff0001; /* # input channel = 1 */
835117632Sharti	CSRARC(fc, iPCR) = 0x803f0000;
836117632Sharti	for(i = 4 ; i < 0x7c/4 ; i+=4){
837117632Sharti		CSRARC(fc, i + iPCR) = 0x0;
838117632Sharti	}
839117632Sharti#endif
840117632Sharti
841117632Sharti	fc->crom_src_buf = NULL;
842117632Sharti
843117632Sharti#ifdef FW_VMACCESS
844117632Sharti	xfer = fw_xfer_alloc();
845117632Sharti	if(xfer == NULL) return;
846117632Sharti
847117632Sharti	fwb = (struct fw_bind *)malloc(sizeof (struct fw_bind), M_FW, M_NOWAIT);
848117632Sharti	if(fwb == NULL){
849117632Sharti		fw_xfer_free(xfer);
850117632Sharti		return;
851117632Sharti	}
852117632Sharti	xfer->hand = fw_vmaccess;
853117632Sharti	xfer->fc = fc;
854117632Sharti	xfer->sc = NULL;
855117632Sharti
856117632Sharti	fwb->start_hi = 0x2;
857117632Sharti	fwb->start_lo = 0;
858117632Sharti	fwb->addrlen = 0xffffffff;
859117632Sharti	fwb->xfer = xfer;
860117632Sharti	fw_bindadd(fc, fwb);
861117632Sharti#endif
862117632Sharti}
863117632Sharti
864117632Sharti#define BIND_CMP(addr, fwb) (((addr) < (fwb)->start)?-1:\
865117632Sharti    ((fwb)->end < (addr))?1:0)
866117632Sharti
867117632Sharti/*
868117632Sharti * To lookup bound process from IEEE1394 address.
869117632Sharti */
870117632Shartistruct fw_bind *
871117632Shartifw_bindlookup(struct firewire_comm *fc, uint16_t dest_hi, uint32_t dest_lo)
872117632Sharti{
873117632Sharti	u_int64_t addr;
874117632Sharti	struct fw_bind *tfw, *r = NULL;
875117632Sharti
876117632Sharti	addr = ((u_int64_t)dest_hi << 32) | dest_lo;
877117632Sharti	FW_GLOCK(fc);
878117632Sharti	STAILQ_FOREACH(tfw, &fc->binds, fclist)
879117632Sharti		if (BIND_CMP(addr, tfw) == 0) {
880117632Sharti			r = tfw;
881117632Sharti			break;
882117632Sharti		}
883117632Sharti	FW_GUNLOCK(fc);
884117632Sharti	return(r);
885117632Sharti}
886117632Sharti
887117632Sharti/*
888117632Sharti * To bind IEEE1394 address block to process.
889117632Sharti */
890117632Shartiint
891117632Shartifw_bindadd(struct firewire_comm *fc, struct fw_bind *fwb)
892117632Sharti{
893117632Sharti	struct fw_bind *tfw, *prev = NULL;
894117632Sharti	int r = 0;
895117632Sharti
896117632Sharti	if (fwb->start > fwb->end) {
897117632Sharti		printf("%s: invalid range\n", __func__);
898117632Sharti		return EINVAL;
899117632Sharti	}
900117632Sharti
901117632Sharti	FW_GLOCK(fc);
902117632Sharti	STAILQ_FOREACH(tfw, &fc->binds, fclist) {
903117632Sharti		if (fwb->end < tfw->start)
904117632Sharti			break;
905117632Sharti		prev = tfw;
906117632Sharti	}
907117632Sharti	if (prev == NULL)
908117632Sharti		STAILQ_INSERT_HEAD(&fc->binds, fwb, fclist);
909117632Sharti	else if (prev->end < fwb->start)
910117632Sharti		STAILQ_INSERT_AFTER(&fc->binds, prev, fwb, fclist);
911117632Sharti	else {
912117632Sharti		printf("%s: bind failed\n", __func__);
913117632Sharti		r = EBUSY;
914117632Sharti	}
915117632Sharti	FW_GUNLOCK(fc);
916117632Sharti	return (r);
917117632Sharti}
918117632Sharti
919117632Sharti/*
920117632Sharti * To free IEEE1394 address block.
921117632Sharti */
922117632Shartiint
923117632Shartifw_bindremove(struct firewire_comm *fc, struct fw_bind *fwb)
924117632Sharti{
925117632Sharti#if 0
926117632Sharti	struct fw_xfer *xfer, *next;
927117632Sharti#endif
928117632Sharti	struct fw_bind *tfw;
929117632Sharti	int s;
930117632Sharti
931117632Sharti	s = splfw();
932117632Sharti	FW_GLOCK(fc);
933117632Sharti	STAILQ_FOREACH(tfw, &fc->binds, fclist)
934117632Sharti		if (tfw == fwb) {
935117632Sharti			STAILQ_REMOVE(&fc->binds, fwb, fw_bind, fclist);
936117632Sharti			goto found;
937117632Sharti		}
938117632Sharti
939117632Sharti	printf("%s: no such binding\n", __func__);
940117632Sharti	FW_GUNLOCK(fc);
941117632Sharti	splx(s);
942117632Sharti	return (1);
943117632Shartifound:
944117632Sharti#if 0
945117632Sharti	/* shall we do this? */
946117632Sharti	for (xfer = STAILQ_FIRST(&fwb->xferlist); xfer != NULL; xfer = next) {
947117632Sharti		next = STAILQ_NEXT(xfer, link);
948117632Sharti		fw_xfer_free(xfer);
949117632Sharti	}
950117632Sharti	STAILQ_INIT(&fwb->xferlist);
951117632Sharti#endif
952117632Sharti	FW_GUNLOCK(fc);
953117632Sharti
954117632Sharti	splx(s);
955117632Sharti	return 0;
956117632Sharti}
957117632Sharti
958117632Shartiint
959117632Shartifw_xferlist_add(struct fw_xferlist *q, struct malloc_type *type,
960117632Sharti    int slen, int rlen, int n,
961117632Sharti    struct firewire_comm *fc, void *sc, void (*hand)(struct fw_xfer *))
962117632Sharti{
963117632Sharti	int i, s;
964117632Sharti	struct fw_xfer *xfer;
965117632Sharti
966117632Sharti	for (i = 0; i < n; i++) {
967117632Sharti		xfer = fw_xfer_alloc_buf(type, slen, rlen);
968117632Sharti		if (xfer == NULL)
969117632Sharti			return (n);
970117632Sharti		xfer->fc = fc;
971117632Sharti		xfer->sc = sc;
972117632Sharti		xfer->hand = hand;
973117632Sharti		s = splfw();
974117632Sharti		STAILQ_INSERT_TAIL(q, xfer, link);
975117632Sharti		splx(s);
976117632Sharti	}
977117632Sharti	return (n);
978117632Sharti}
979117632Sharti
980117632Shartivoid
981117632Shartifw_xferlist_remove(struct fw_xferlist *q)
982117632Sharti{
983117632Sharti	struct fw_xfer *xfer, *next;
984117632Sharti
985117632Sharti	for (xfer = STAILQ_FIRST(q); xfer != NULL; xfer = next) {
986117632Sharti                next = STAILQ_NEXT(xfer, link);
987117632Sharti                fw_xfer_free_buf(xfer);
988117632Sharti        }
989117632Sharti        STAILQ_INIT(q);
990117632Sharti}
991117632Sharti/*
992117632Sharti * dump packet header
993117632Sharti */
994117632Shartistatic void
995117632Shartifw_dump_hdr(struct fw_pkt *fp, char *prefix)
996117632Sharti{
997117632Sharti	printf("%s: dst=0x%02x tl=0x%02x rt=%d tcode=0x%x pri=0x%x "
998117632Sharti	    "src=0x%03x\n", prefix,
999117632Sharti	    fp->mode.hdr.dst & 0x3f,
1000117632Sharti	    fp->mode.hdr.tlrt >> 2, fp->mode.hdr.tlrt & 3,
1001117632Sharti	    fp->mode.hdr.tcode, fp->mode.hdr.pri,
1002117632Sharti	    fp->mode.hdr.src);
1003117632Sharti}
1004117632Sharti
1005117632Sharti/*
1006117632Sharti * To free transaction label.
1007117632Sharti */
1008117632Shartistatic void
1009117632Shartifw_tl_free(struct firewire_comm *fc, struct fw_xfer *xfer)
1010117632Sharti{
1011117632Sharti	struct fw_xfer *txfer;
1012117632Sharti	int s;
1013117632Sharti
1014117632Sharti	if (xfer->tl < 0)
1015117632Sharti		return;
1016117632Sharti
1017117632Sharti	s = splfw();
1018117632Sharti	mtx_lock(&fc->tlabel_lock);
1019117632Sharti#if 1	/* make sure the label is allocated */
1020117632Sharti	STAILQ_FOREACH(txfer, &fc->tlabels[xfer->tl], tlabel)
1021117632Sharti		if(txfer == xfer)
1022117632Sharti			break;
1023117632Sharti	if (txfer == NULL) {
1024117632Sharti		printf("%s: the xfer is not in the queue "
1025117632Sharti		    "(tlabel=%d, flag=0x%x)\n",
1026117632Sharti		    __FUNCTION__, xfer->tl, xfer->flag);
1027117632Sharti		fw_dump_hdr(&xfer->send.hdr, "send");
1028117632Sharti		fw_dump_hdr(&xfer->recv.hdr, "recv");
1029117632Sharti		kdb_backtrace();
1030117632Sharti		mtx_unlock(&fc->tlabel_lock);
1031117632Sharti		splx(s);
1032117632Sharti		return;
1033117632Sharti	}
1034117632Sharti#endif
1035117632Sharti
1036117632Sharti	STAILQ_REMOVE(&fc->tlabels[xfer->tl], xfer, fw_xfer, tlabel);
1037117632Sharti	mtx_unlock(&fc->tlabel_lock);
1038117632Sharti	splx(s);
1039117632Sharti	return;
1040117632Sharti}
1041117632Sharti
1042117632Sharti/*
1043117632Sharti * To obtain XFER structure by transaction label.
1044117632Sharti */
1045117632Shartistatic struct fw_xfer *
1046117632Shartifw_tl2xfer(struct firewire_comm *fc, int node, int tlabel, int tcode)
1047117632Sharti{
1048117632Sharti	struct fw_xfer *xfer;
1049117632Sharti	int s = splfw();
1050117632Sharti	int req;
1051117632Sharti
1052117632Sharti	mtx_lock(&fc->tlabel_lock);
1053117632Sharti	STAILQ_FOREACH(xfer, &fc->tlabels[tlabel], tlabel)
1054117632Sharti		if(xfer->send.hdr.mode.hdr.dst == node) {
1055117632Sharti			mtx_unlock(&fc->tlabel_lock);
1056117632Sharti			splx(s);
1057117632Sharti			KASSERT(xfer->tl == tlabel,
1058117632Sharti				("xfer->tl 0x%x != 0x%x", xfer->tl, tlabel));
1059117632Sharti			/* extra sanity check */
1060117632Sharti			req = xfer->send.hdr.mode.hdr.tcode;
1061117632Sharti			if (xfer->fc->tcode[req].valid_res != tcode) {
1062117632Sharti				printf("%s: invalid response tcode "
1063117632Sharti				    "(0x%x for 0x%x)\n", __FUNCTION__,
1064117632Sharti				    tcode, req);
1065117632Sharti				return(NULL);
1066117632Sharti			}
1067117632Sharti
1068117632Sharti			if (firewire_debug > 2)
1069117632Sharti				printf("fw_tl2xfer: found tl=%d\n", tlabel);
1070117632Sharti			return(xfer);
1071117632Sharti		}
1072117632Sharti	mtx_unlock(&fc->tlabel_lock);
1073117632Sharti	if (firewire_debug > 1)
1074117632Sharti		printf("fw_tl2xfer: not found tl=%d\n", tlabel);
1075117632Sharti	splx(s);
1076117632Sharti	return(NULL);
1077117632Sharti}
1078117632Sharti
1079117632Sharti/*
1080117632Sharti * To allocate IEEE1394 XFER structure.
1081117632Sharti */
1082117632Shartistruct fw_xfer *
1083117632Shartifw_xfer_alloc(struct malloc_type *type)
1084117632Sharti{
1085117632Sharti	struct fw_xfer *xfer;
1086117632Sharti
1087117632Sharti	xfer = malloc(sizeof(struct fw_xfer), type, M_NOWAIT | M_ZERO);
1088117632Sharti	if (xfer == NULL)
1089117632Sharti		return xfer;
1090117632Sharti
1091117632Sharti	xfer->malloc = type;
1092117632Sharti
1093117632Sharti	return xfer;
1094117632Sharti}
1095117632Sharti
1096117632Shartistruct fw_xfer *
1097117632Shartifw_xfer_alloc_buf(struct malloc_type *type, int send_len, int recv_len)
1098117632Sharti{
1099117632Sharti	struct fw_xfer *xfer;
1100117632Sharti
1101117632Sharti	xfer = fw_xfer_alloc(type);
1102117632Sharti	if (xfer == NULL)
1103117632Sharti		return(NULL);
1104117632Sharti	xfer->send.pay_len = send_len;
1105117632Sharti	xfer->recv.pay_len = recv_len;
1106117632Sharti	if (send_len > 0) {
1107117632Sharti		xfer->send.payload = malloc(send_len, type, M_NOWAIT | M_ZERO);
1108117632Sharti		if (xfer->send.payload == NULL) {
1109117632Sharti			fw_xfer_free(xfer);
1110117632Sharti			return(NULL);
1111117632Sharti		}
1112117632Sharti	}
1113117632Sharti	if (recv_len > 0) {
1114117632Sharti		xfer->recv.payload = malloc(recv_len, type, M_NOWAIT);
1115117632Sharti		if (xfer->recv.payload == NULL) {
1116117632Sharti			if (xfer->send.payload != NULL)
1117117632Sharti				free(xfer->send.payload, type);
1118117632Sharti			fw_xfer_free(xfer);
1119117632Sharti			return(NULL);
1120117632Sharti		}
1121117632Sharti	}
1122117632Sharti	return(xfer);
1123117632Sharti}
1124117632Sharti
1125117632Sharti/*
1126117632Sharti * IEEE1394 XFER post process.
1127117632Sharti */
1128117632Shartivoid
1129147256Sbrooksfw_xfer_done(struct fw_xfer *xfer)
1130117632Sharti{
1131117632Sharti	if (xfer->hand == NULL) {
1132117632Sharti		printf("hand == NULL\n");
1133117632Sharti		return;
1134117632Sharti	}
1135117632Sharti
1136117632Sharti	if (xfer->fc == NULL)
1137117632Sharti		panic("fw_xfer_done: why xfer->fc is NULL?");
1138117632Sharti
1139117632Sharti	fw_tl_free(xfer->fc, xfer);
1140117632Sharti	xfer->hand(xfer);
1141117632Sharti}
1142117632Sharti
1143117632Shartivoid
1144117632Shartifw_xfer_unload(struct fw_xfer* xfer)
1145117632Sharti{
1146117632Sharti	int s;
1147117632Sharti
1148117632Sharti	if(xfer == NULL ) return;
1149117632Sharti	if(xfer->flag & FWXF_INQ){
1150117632Sharti		printf("fw_xfer_free FWXF_INQ\n");
1151117632Sharti		s = splfw();
1152117632Sharti		FW_GLOCK(xfer->fc);
1153117632Sharti		STAILQ_REMOVE(&xfer->q->q, xfer, fw_xfer, link);
1154117632Sharti#if 0
1155117632Sharti		xfer->q->queued --;
1156117632Sharti#endif
1157117632Sharti		FW_GUNLOCK(xfer->fc);
1158117632Sharti		splx(s);
1159117632Sharti	}
1160117632Sharti	if (xfer->fc != NULL) {
1161117632Sharti#if 1
1162117632Sharti		if(xfer->flag & FWXF_START)
1163117632Sharti			/*
1164117632Sharti			 * This could happen if:
1165117632Sharti			 *  1. We call fwohci_arcv() before fwohci_txd().
1166117632Sharti			 *  2. firewire_watch() is called.
1167117632Sharti			 */
1168117632Sharti			printf("fw_xfer_free FWXF_START\n");
1169117632Sharti#endif
1170117632Sharti	}
1171117632Sharti	xfer->flag = FWXF_INIT;
1172117632Sharti	xfer->resp = 0;
1173117632Sharti}
1174117632Sharti/*
1175117632Sharti * To free IEEE1394 XFER structure.
1176117632Sharti */
1177117632Shartivoid
1178117632Shartifw_xfer_free_buf( struct fw_xfer* xfer)
1179117632Sharti{
1180117632Sharti	if (xfer == NULL) {
1181117632Sharti		printf("%s: xfer == NULL\n", __func__);
1182117632Sharti		return;
1183117632Sharti	}
1184117632Sharti	fw_xfer_unload(xfer);
1185117632Sharti	if(xfer->send.payload != NULL){
1186117632Sharti		free(xfer->send.payload, xfer->malloc);
1187117632Sharti	}
1188117632Sharti	if(xfer->recv.payload != NULL){
1189117632Sharti		free(xfer->recv.payload, xfer->malloc);
1190117632Sharti	}
1191117632Sharti	free(xfer, xfer->malloc);
1192117632Sharti}
1193117632Sharti
1194117632Shartivoid
1195117632Shartifw_xfer_free( struct fw_xfer* xfer)
1196117632Sharti{
1197117632Sharti	if (xfer == NULL) {
1198117632Sharti		printf("%s: xfer == NULL\n", __func__);
1199117632Sharti		return;
1200117632Sharti	}
1201117632Sharti	fw_xfer_unload(xfer);
1202117632Sharti	free(xfer, xfer->malloc);
1203117632Sharti}
1204117632Sharti
1205117632Shartivoid
1206117632Shartifw_asy_callback_free(struct fw_xfer *xfer)
1207117632Sharti{
1208117632Sharti#if 0
1209117632Sharti	printf("asyreq done flag=0x%02x resp=%d\n",
1210117632Sharti				xfer->flag, xfer->resp);
1211117632Sharti#endif
1212117632Sharti	fw_xfer_free(xfer);
1213117632Sharti}
1214117632Sharti
1215117632Sharti/*
1216117632Sharti * To configure PHY.
1217117632Sharti */
1218117632Shartistatic void
1219117632Shartifw_phy_config(struct firewire_comm *fc, int root_node, int gap_count)
1220117632Sharti{
1221117632Sharti	struct fw_xfer *xfer;
1222117632Sharti	struct fw_pkt *fp;
1223117632Sharti
1224117632Sharti	fc->status = FWBUSPHYCONF;
1225117632Sharti
1226117632Sharti	xfer = fw_xfer_alloc(M_FWXFER);
1227117632Sharti	if (xfer == NULL)
1228117632Sharti		return;
1229117632Sharti	xfer->fc = fc;
1230117632Sharti	xfer->hand = fw_asy_callback_free;
1231117632Sharti
1232117632Sharti	fp = &xfer->send.hdr;
1233117632Sharti	fp->mode.ld[1] = 0;
1234117632Sharti	if (root_node >= 0)
1235117632Sharti		fp->mode.ld[1] |= (root_node & 0x3f) << 24 | 1 << 23;
1236117632Sharti	if (gap_count >= 0)
1237117632Sharti		fp->mode.ld[1] |= 1 << 22 | (gap_count & 0x3f) << 16;
1238117632Sharti	fp->mode.ld[2] = ~fp->mode.ld[1];
1239117632Sharti/* XXX Dangerous, how to pass PHY packet to device driver */
1240117632Sharti	fp->mode.common.tcode |= FWTCODE_PHY;
1241117632Sharti
1242117632Sharti	if (firewire_debug)
1243117632Sharti		printf("send phy_config root_node=%d gap_count=%d\n",
1244117632Sharti						root_node, gap_count);
1245117632Sharti	fw_asyreq(fc, -1, xfer);
1246117632Sharti}
1247117632Sharti
1248117632Sharti#if 0
1249117632Sharti/*
1250117632Sharti * Dump self ID.
1251117632Sharti */
1252117632Shartistatic void
1253117632Shartifw_print_sid(uint32_t sid)
1254117632Sharti{
1255117632Sharti	union fw_self_id *s;
1256117632Sharti	s = (union fw_self_id *) &sid;
1257117632Sharti	printf("node:%d link:%d gap:%d spd:%d del:%d con:%d pwr:%d"
1258117632Sharti		" p0:%d p1:%d p2:%d i:%d m:%d\n",
1259117632Sharti		s->p0.phy_id, s->p0.link_active, s->p0.gap_count,
1260117632Sharti		s->p0.phy_speed, s->p0.phy_delay, s->p0.contender,
1261117632Sharti		s->p0.power_class, s->p0.port0, s->p0.port1,
1262117632Sharti		s->p0.port2, s->p0.initiated_reset, s->p0.more_packets);
1263117632Sharti}
1264117632Sharti#endif
1265117632Sharti
1266117632Sharti/*
1267117632Sharti * To receive self ID.
1268117632Sharti */
1269117632Shartivoid fw_sidrcv(struct firewire_comm* fc, uint32_t *sid, u_int len)
1270117632Sharti{
1271117632Sharti	uint32_t *p;
1272117632Sharti	union fw_self_id *self_id;
1273117632Sharti	u_int i, j, node, c_port = 0, i_branch = 0;
1274117632Sharti
1275117632Sharti	fc->sid_cnt = len /(sizeof(uint32_t) * 2);
1276117632Sharti	fc->max_node = fc->nodeid & 0x3f;
1277	CSRARC(fc, NODE_IDS) = ((uint32_t)fc->nodeid) << 16;
1278	fc->status = FWBUSCYMELECT;
1279	fc->topology_map->crc_len = 2;
1280	fc->topology_map->generation ++;
1281	fc->topology_map->self_id_count = 0;
1282	fc->topology_map->node_count = 0;
1283	fc->speed_map->generation ++;
1284	fc->speed_map->crc_len = 1 + (64*64 + 3) / 4;
1285	self_id = &fc->topology_map->self_id[0];
1286	for(i = 0; i < fc->sid_cnt; i ++){
1287		if (sid[1] != ~sid[0]) {
1288			printf("fw_sidrcv: invalid self-id packet\n");
1289			sid += 2;
1290			continue;
1291		}
1292		*self_id = *((union fw_self_id *)sid);
1293		fc->topology_map->crc_len++;
1294		if(self_id->p0.sequel == 0){
1295			fc->topology_map->node_count ++;
1296			c_port = 0;
1297#if 0
1298			fw_print_sid(sid[0]);
1299#endif
1300			node = self_id->p0.phy_id;
1301			if(fc->max_node < node){
1302				fc->max_node = self_id->p0.phy_id;
1303			}
1304			/* XXX I'm not sure this is the right speed_map */
1305			fc->speed_map->speed[node][node]
1306					= self_id->p0.phy_speed;
1307			for (j = 0; j < node; j ++) {
1308				fc->speed_map->speed[j][node]
1309					= fc->speed_map->speed[node][j]
1310					= min(fc->speed_map->speed[j][j],
1311							self_id->p0.phy_speed);
1312			}
1313			if ((fc->irm == -1 || self_id->p0.phy_id > fc->irm) &&
1314			  (self_id->p0.link_active && self_id->p0.contender)) {
1315				fc->irm = self_id->p0.phy_id;
1316			}
1317			if(self_id->p0.port0 >= 0x2){
1318				c_port++;
1319			}
1320			if(self_id->p0.port1 >= 0x2){
1321				c_port++;
1322			}
1323			if(self_id->p0.port2 >= 0x2){
1324				c_port++;
1325			}
1326		}
1327		if(c_port > 2){
1328			i_branch += (c_port - 2);
1329		}
1330		sid += 2;
1331		self_id++;
1332		fc->topology_map->self_id_count ++;
1333	}
1334	device_printf(fc->bdev, "%d nodes", fc->max_node + 1);
1335	/* CRC */
1336	fc->topology_map->crc = fw_crc16(
1337			(uint32_t *)&fc->topology_map->generation,
1338			fc->topology_map->crc_len * 4);
1339	fc->speed_map->crc = fw_crc16(
1340			(uint32_t *)&fc->speed_map->generation,
1341			fc->speed_map->crc_len * 4);
1342	/* byteswap and copy to CSR */
1343	p = (uint32_t *)fc->topology_map;
1344	for (i = 0; i <= fc->topology_map->crc_len; i++)
1345		CSRARC(fc, TOPO_MAP + i * 4) = htonl(*p++);
1346	p = (uint32_t *)fc->speed_map;
1347	CSRARC(fc, SPED_MAP) = htonl(*p++);
1348	CSRARC(fc, SPED_MAP + 4) = htonl(*p++);
1349	/* don't byte-swap uint8_t array */
1350	bcopy(p, &CSRARC(fc, SPED_MAP + 8), (fc->speed_map->crc_len - 1)*4);
1351
1352	fc->max_hop = fc->max_node - i_branch;
1353	printf(", maxhop <= %d", fc->max_hop);
1354
1355	if(fc->irm == -1 ){
1356		printf(", Not found IRM capable node");
1357	}else{
1358		printf(", cable IRM = %d", fc->irm);
1359		if (fc->irm == fc->nodeid)
1360			printf(" (me)");
1361	}
1362	printf("\n");
1363
1364	if (try_bmr && (fc->irm != -1) && (CSRARC(fc, BUS_MGR_ID) == 0x3f)) {
1365		if (fc->irm == fc->nodeid) {
1366			fc->status = FWBUSMGRDONE;
1367			CSRARC(fc, BUS_MGR_ID) = fc->set_bmr(fc, fc->irm);
1368			fw_bmr(fc);
1369		} else {
1370			fc->status = FWBUSMGRELECT;
1371			callout_reset(&fc->bmr_callout, hz/8,
1372				(void *)fw_try_bmr, (void *)fc);
1373		}
1374	} else
1375		fc->status = FWBUSMGRDONE;
1376
1377	callout_reset(&fc->busprobe_callout, hz/4,
1378			(void *)fw_bus_probe, (void *)fc);
1379}
1380
1381/*
1382 * To probe devices on the IEEE1394 bus.
1383 */
1384static void
1385fw_bus_probe(struct firewire_comm *fc)
1386{
1387	int s;
1388	struct fw_device *fwdev;
1389
1390	s = splfw();
1391	fc->status = FWBUSEXPLORE;
1392
1393	/* Invalidate all devices, just after bus reset. */
1394	STAILQ_FOREACH(fwdev, &fc->devices, link)
1395		if (fwdev->status != FWDEVINVAL) {
1396			fwdev->status = FWDEVINVAL;
1397			fwdev->rcnt = 0;
1398		}
1399	splx(s);
1400
1401	wakeup((void *)fc);
1402}
1403
1404static int
1405fw_explore_read_quads(struct fw_device *fwdev, int offset,
1406    uint32_t *quad, int n)
1407{
1408	struct fw_xfer *xfer;
1409	uint32_t tmp;
1410	int i, error;
1411
1412	for (i = 0; i < n; i ++, offset += sizeof(uint32_t)) {
1413		xfer = fwmem_read_quad(fwdev, NULL, -1,
1414		    0xffff, 0xf0000000 | offset, (void *)&tmp,
1415		    fw_xferwake);
1416		if (xfer == NULL)
1417			return (-1);
1418		fw_xferwait(xfer);
1419
1420		if (xfer->resp == 0)
1421			quad[i] = ntohl(tmp);
1422
1423		error = xfer->resp;
1424		fw_xfer_free(xfer);
1425		if (error)
1426			return (error);
1427	}
1428	return (0);
1429}
1430
1431
1432static int
1433fw_explore_csrblock(struct fw_device *fwdev, int offset, int recur)
1434{
1435	int err, i, off;
1436	struct csrdirectory *dir;
1437	struct csrreg *reg;
1438
1439	dir = (struct csrdirectory *)&fwdev->csrrom[offset/sizeof(uint32_t)];
1440	err = fw_explore_read_quads(fwdev, CSRROMOFF + offset,
1441	    (uint32_t *)dir, 1);
1442	if (err)
1443		return (-1);
1444
1445	offset += sizeof(uint32_t);
1446	reg = (struct csrreg *)&fwdev->csrrom[offset/sizeof(uint32_t)];
1447	err = fw_explore_read_quads(fwdev, CSRROMOFF + offset,
1448	    (uint32_t *)reg, dir->crc_len);
1449	if (err)
1450		return (-1);
1451
1452	/* XXX check CRC */
1453
1454	off = CSRROMOFF + offset + sizeof(uint32_t) * (dir->crc_len - 1);
1455	if (fwdev->rommax < off)
1456		fwdev->rommax = off;
1457
1458	if (recur == 0)
1459		return (0);
1460
1461	for (i = 0; i < dir->crc_len; i ++, offset += sizeof(uint32_t)) {
1462		if ((reg[i].key & CSRTYPE_MASK) == CSRTYPE_D)
1463			recur = 1;
1464		else if ((reg[i].key & CSRTYPE_MASK) == CSRTYPE_L)
1465			recur = 0;
1466		else
1467			continue;
1468
1469		off = offset + reg[i].val * sizeof(uint32_t);
1470		if (off > CROMSIZE) {
1471			printf("%s: invalid offset %d\n", __FUNCTION__, off);
1472			return(-1);
1473		}
1474		err = fw_explore_csrblock(fwdev, off, recur);
1475		if (err)
1476			return (-1);
1477	}
1478	return (0);
1479}
1480
1481static int
1482fw_explore_node(struct fw_device *dfwdev)
1483{
1484	struct firewire_comm *fc;
1485	struct fw_device *fwdev, *pfwdev, *tfwdev;
1486	uint32_t *csr;
1487	struct csrhdr *hdr;
1488	struct bus_info *binfo;
1489	int err, node, spd;
1490
1491	fc = dfwdev->fc;
1492	csr = dfwdev->csrrom;
1493	node = dfwdev->dst;
1494
1495	/* First quad */
1496	err = fw_explore_read_quads(dfwdev, CSRROMOFF, &csr[0], 1);
1497	if (err)
1498		return (-1);
1499	hdr = (struct csrhdr *)&csr[0];
1500	if (hdr->info_len != 4) {
1501		if (firewire_debug)
1502			printf("node%d: wrong bus info len(%d)\n",
1503			    node, hdr->info_len);
1504		return (-1);
1505	}
1506
1507	/* bus info */
1508	err = fw_explore_read_quads(dfwdev, CSRROMOFF + 0x04, &csr[1], 4);
1509	if (err)
1510		return (-1);
1511	binfo = (struct bus_info *)&csr[1];
1512	if (binfo->bus_name != CSR_BUS_NAME_IEEE1394) {
1513		if (firewire_debug)
1514			printf("node%d: invalid bus name 0x%08x\n",
1515			    node, binfo->bus_name);
1516		return (-1);
1517	}
1518	spd = fc->speed_map->speed[fc->nodeid][node];
1519	STAILQ_FOREACH(fwdev, &fc->devices, link)
1520		if (FW_EUI64_EQUAL(fwdev->eui, binfo->eui64))
1521			break;
1522	if (fwdev == NULL) {
1523		/* new device */
1524		fwdev = malloc(sizeof(struct fw_device), M_FW,
1525						M_NOWAIT | M_ZERO);
1526		if (fwdev == NULL) {
1527			if (firewire_debug)
1528				printf("node%d: no memory\n", node);
1529			return (-1);
1530		}
1531		fwdev->fc = fc;
1532		fwdev->eui = binfo->eui64;
1533		/* inesrt into sorted fwdev list */
1534		pfwdev = NULL;
1535		STAILQ_FOREACH(tfwdev, &fc->devices, link) {
1536			if (tfwdev->eui.hi > fwdev->eui.hi ||
1537				(tfwdev->eui.hi == fwdev->eui.hi &&
1538				tfwdev->eui.lo > fwdev->eui.lo))
1539				break;
1540			pfwdev = tfwdev;
1541		}
1542		if (pfwdev == NULL)
1543			STAILQ_INSERT_HEAD(&fc->devices, fwdev, link);
1544		else
1545			STAILQ_INSERT_AFTER(&fc->devices, pfwdev, fwdev, link);
1546
1547		device_printf(fc->bdev, "New %s device ID:%08x%08x\n",
1548		    linkspeed[spd],
1549		    fwdev->eui.hi, fwdev->eui.lo);
1550	}
1551	fwdev->dst = node;
1552	fwdev->status = FWDEVINIT;
1553	fwdev->speed = spd;
1554
1555	/* unchanged ? */
1556	if (bcmp(&csr[0], &fwdev->csrrom[0], sizeof(uint32_t) * 5) == 0) {
1557		if (firewire_debug)
1558			printf("node%d: crom unchanged\n", node);
1559		return (0);
1560	}
1561
1562	bzero(&fwdev->csrrom[0], CROMSIZE);
1563
1564	/* copy first quad and bus info block */
1565	bcopy(&csr[0], &fwdev->csrrom[0], sizeof(uint32_t) * 5);
1566	fwdev->rommax = CSRROMOFF + sizeof(uint32_t) * 4;
1567
1568	err = fw_explore_csrblock(fwdev, 0x14, 1); /* root directory */
1569
1570	if (err) {
1571		fwdev->status = FWDEVINVAL;
1572		fwdev->csrrom[0] = 0;
1573	}
1574	return (err);
1575
1576}
1577
1578/*
1579 * Find the self_id packet for a node, ignoring sequels.
1580 */
1581static union fw_self_id *
1582fw_find_self_id(struct firewire_comm *fc, int node)
1583{
1584	uint32_t i;
1585	union fw_self_id *s;
1586
1587	for (i = 0; i < fc->topology_map->self_id_count; i++) {
1588		s = &fc->topology_map->self_id[i];
1589		if (s->p0.sequel)
1590			continue;
1591		if (s->p0.phy_id == node)
1592			return s;
1593	}
1594	return 0;
1595}
1596
1597static void
1598fw_explore(struct firewire_comm *fc)
1599{
1600	int node, err, s, i, todo, todo2, trys;
1601	char nodes[63];
1602	struct fw_device dfwdev;
1603	union fw_self_id *fwsid;
1604
1605	todo = 0;
1606	/* setup dummy fwdev */
1607	dfwdev.fc = fc;
1608	dfwdev.speed = 0;
1609	dfwdev.maxrec = 8; /* 512 */
1610	dfwdev.status = FWDEVINIT;
1611
1612	for (node = 0; node <= fc->max_node; node ++) {
1613		/* We don't probe myself and linkdown nodes */
1614		if (node == fc->nodeid)
1615			continue;
1616		fwsid = fw_find_self_id(fc, node);
1617		if (!fwsid || !fwsid->p0.link_active) {
1618			if (firewire_debug)
1619				printf("node%d: link down\n", node);
1620			continue;
1621		}
1622		nodes[todo++] = node;
1623	}
1624
1625	s = splfw();
1626	for (trys = 0; todo > 0 && trys < 3; trys ++) {
1627		todo2 = 0;
1628		for (i = 0; i < todo; i ++) {
1629			dfwdev.dst = nodes[i];
1630			err = fw_explore_node(&dfwdev);
1631			if (err)
1632				nodes[todo2++] = nodes[i];
1633			if (firewire_debug)
1634				printf("%s: node %d, err = %d\n",
1635					__FUNCTION__, node, err);
1636		}
1637		todo = todo2;
1638	}
1639	splx(s);
1640}
1641
1642
1643static void
1644fw_bus_probe_thread(void *arg)
1645{
1646	struct firewire_comm *fc;
1647
1648	fc = (struct firewire_comm *)arg;
1649
1650	mtx_lock(&fc->wait_lock);
1651	while (fc->status != FWBUSDETACH) {
1652		if (fc->status == FWBUSEXPLORE) {
1653			mtx_unlock(&fc->wait_lock);
1654			fw_explore(fc);
1655			fc->status = FWBUSEXPDONE;
1656			if (firewire_debug)
1657				printf("bus_explore done\n");
1658			fw_attach_dev(fc);
1659			mtx_lock(&fc->wait_lock);
1660		}
1661		msleep((void *)fc, &fc->wait_lock, PWAIT|PCATCH, "-", 0);
1662	}
1663	mtx_unlock(&fc->wait_lock);
1664	kproc_exit(0);
1665}
1666
1667/*
1668 * To attach sub-devices layer onto IEEE1394 bus.
1669 */
1670static void
1671fw_attach_dev(struct firewire_comm *fc)
1672{
1673	struct fw_device *fwdev, *next;
1674	int i, err;
1675	device_t *devlistp;
1676	int devcnt;
1677	struct firewire_dev_comm *fdc;
1678
1679	for (fwdev = STAILQ_FIRST(&fc->devices); fwdev != NULL; fwdev = next) {
1680		next = STAILQ_NEXT(fwdev, link);
1681		if (fwdev->status == FWDEVINIT) {
1682			fwdev->status = FWDEVATTACHED;
1683		} else if (fwdev->status == FWDEVINVAL) {
1684			fwdev->rcnt ++;
1685			if (fwdev->rcnt > hold_count) {
1686				/*
1687				 * Remove devices which have not been seen
1688				 * for a while.
1689				 */
1690				STAILQ_REMOVE(&fc->devices, fwdev, fw_device,
1691				    link);
1692				free(fwdev, M_FW);
1693			}
1694		}
1695	}
1696
1697	err = device_get_children(fc->bdev, &devlistp, &devcnt);
1698	if( err != 0 )
1699		return;
1700	for( i = 0 ; i < devcnt ; i++){
1701		if (device_get_state(devlistp[i]) >= DS_ATTACHED)  {
1702			fdc = device_get_softc(devlistp[i]);
1703			if (fdc->post_explore != NULL)
1704				fdc->post_explore(fdc);
1705		}
1706	}
1707	free(devlistp, M_TEMP);
1708
1709	return;
1710}
1711
1712/*
1713 * To allocate unique transaction label.
1714 */
1715static int
1716fw_get_tlabel(struct firewire_comm *fc, struct fw_xfer *xfer)
1717{
1718	u_int dst, new_tlabel;
1719	struct fw_xfer *txfer;
1720	int s;
1721
1722	dst = xfer->send.hdr.mode.hdr.dst & 0x3f;
1723	s = splfw();
1724	mtx_lock(&fc->tlabel_lock);
1725	new_tlabel = (fc->last_tlabel[dst] + 1) & 0x3f;
1726	STAILQ_FOREACH(txfer, &fc->tlabels[new_tlabel], tlabel)
1727		if ((txfer->send.hdr.mode.hdr.dst & 0x3f) == dst)
1728				break;
1729	if(txfer == NULL) {
1730		fc->last_tlabel[dst] = new_tlabel;
1731		STAILQ_INSERT_TAIL(&fc->tlabels[new_tlabel], xfer, tlabel);
1732		mtx_unlock(&fc->tlabel_lock);
1733		splx(s);
1734		xfer->tl = new_tlabel;
1735		xfer->send.hdr.mode.hdr.tlrt = new_tlabel << 2;
1736		if (firewire_debug > 1)
1737			printf("fw_get_tlabel: dst=%d tl=%d\n", dst, new_tlabel);
1738		return (new_tlabel);
1739	}
1740	mtx_unlock(&fc->tlabel_lock);
1741	splx(s);
1742
1743	if (firewire_debug > 1)
1744		printf("fw_get_tlabel: no free tlabel\n");
1745	return (-1);
1746}
1747
1748static void
1749fw_rcv_copy(struct fw_rcv_buf *rb)
1750{
1751	struct fw_pkt *pkt;
1752	u_char *p;
1753	struct tcode_info *tinfo;
1754	u_int res, i, len, plen;
1755
1756	rb->xfer->recv.spd = rb->spd;
1757
1758	pkt = (struct fw_pkt *)rb->vec->iov_base;
1759	tinfo = &rb->fc->tcode[pkt->mode.hdr.tcode];
1760
1761	/* Copy header */
1762	p = (u_char *)&rb->xfer->recv.hdr;
1763	bcopy(rb->vec->iov_base, p, tinfo->hdr_len);
1764	rb->vec->iov_base = (u_char *)rb->vec->iov_base + tinfo->hdr_len;
1765	rb->vec->iov_len -= tinfo->hdr_len;
1766
1767	/* Copy payload */
1768	p = (u_char *)rb->xfer->recv.payload;
1769	res = rb->xfer->recv.pay_len;
1770
1771	/* special handling for RRESQ */
1772	if (pkt->mode.hdr.tcode == FWTCODE_RRESQ &&
1773	    p != NULL && res >= sizeof(uint32_t)) {
1774		*(uint32_t *)p = pkt->mode.rresq.data;
1775		rb->xfer->recv.pay_len = sizeof(uint32_t);
1776		return;
1777	}
1778
1779	if ((tinfo->flag & FWTI_BLOCK_ASY) == 0)
1780		return;
1781
1782	plen = pkt->mode.rresb.len;
1783
1784	for (i = 0; i < rb->nvec; i++, rb->vec++) {
1785		len = MIN(rb->vec->iov_len, plen);
1786		if (res < len) {
1787			printf("rcv buffer(%d) is %d bytes short.\n",
1788			    rb->xfer->recv.pay_len, len - res);
1789			len = res;
1790		}
1791		bcopy(rb->vec->iov_base, p, len);
1792		p += len;
1793		res -= len;
1794		plen -= len;
1795		if (res == 0 || plen == 0)
1796			break;
1797	}
1798	rb->xfer->recv.pay_len -= res;
1799
1800}
1801
1802/*
1803 * Generic packet receiving process.
1804 */
1805void
1806fw_rcv(struct fw_rcv_buf *rb)
1807{
1808	struct fw_pkt *fp, *resfp;
1809	struct fw_bind *bind;
1810	int tcode;
1811	int i, len, oldstate;
1812#if 0
1813	{
1814		uint32_t *qld;
1815		int i;
1816		qld = (uint32_t *)buf;
1817		printf("spd %d len:%d\n", spd, len);
1818		for( i = 0 ; i <= len && i < 32; i+= 4){
1819			printf("0x%08x ", ntohl(qld[i/4]));
1820			if((i % 16) == 15) printf("\n");
1821		}
1822		if((i % 16) != 15) printf("\n");
1823	}
1824#endif
1825	fp = (struct fw_pkt *)rb->vec[0].iov_base;
1826	tcode = fp->mode.common.tcode;
1827	switch (tcode) {
1828	case FWTCODE_WRES:
1829	case FWTCODE_RRESQ:
1830	case FWTCODE_RRESB:
1831	case FWTCODE_LRES:
1832		rb->xfer = fw_tl2xfer(rb->fc, fp->mode.hdr.src,
1833				fp->mode.hdr.tlrt >> 2, fp->mode.hdr.tcode);
1834		if(rb->xfer == NULL) {
1835			printf("fw_rcv: unknown response "
1836			    "%s(%x) src=0x%x tl=0x%x rt=%d data=0x%x\n",
1837			    tcode_str[tcode], tcode,
1838			    fp->mode.hdr.src,
1839			    fp->mode.hdr.tlrt >> 2,
1840			    fp->mode.hdr.tlrt & 3,
1841			    fp->mode.rresq.data);
1842#if 0
1843			printf("try ad-hoc work around!!\n");
1844			rb->xfer = fw_tl2xfer(rb->fc, fp->mode.hdr.src,
1845					(fp->mode.hdr.tlrt >> 2)^3);
1846			if (rb->xfer == NULL) {
1847				printf("no use...\n");
1848				return;
1849			}
1850#else
1851			return;
1852#endif
1853		}
1854		fw_rcv_copy(rb);
1855		if (rb->xfer->recv.hdr.mode.wres.rtcode != RESP_CMP)
1856			rb->xfer->resp = EIO;
1857		else
1858			rb->xfer->resp = 0;
1859		/* make sure the packet is drained in AT queue */
1860		oldstate = rb->xfer->flag;
1861		rb->xfer->flag = FWXF_RCVD;
1862		switch (oldstate) {
1863		case FWXF_SENT:
1864			fw_xfer_done(rb->xfer);
1865			break;
1866		case FWXF_START:
1867#if 0
1868			if (firewire_debug)
1869				printf("not sent yet tl=%x\n", rb->xfer->tl);
1870#endif
1871			break;
1872		default:
1873			printf("unexpected flag 0x%02x\n", rb->xfer->flag);
1874		}
1875		return;
1876	case FWTCODE_WREQQ:
1877	case FWTCODE_WREQB:
1878	case FWTCODE_RREQQ:
1879	case FWTCODE_RREQB:
1880	case FWTCODE_LREQ:
1881		bind = fw_bindlookup(rb->fc, fp->mode.rreqq.dest_hi,
1882			fp->mode.rreqq.dest_lo);
1883		if(bind == NULL){
1884			printf("Unknown service addr 0x%04x:0x%08x %s(%x)"
1885#if defined(__DragonFly__) || __FreeBSD_version < 500000
1886			    " src=0x%x data=%lx\n",
1887#else
1888			    " src=0x%x data=%x\n",
1889#endif
1890			    fp->mode.wreqq.dest_hi, fp->mode.wreqq.dest_lo,
1891			    tcode_str[tcode], tcode,
1892			    fp->mode.hdr.src, ntohl(fp->mode.wreqq.data));
1893			if (rb->fc->status == FWBUSINIT) {
1894				printf("fw_rcv: cannot respond(bus reset)!\n");
1895				return;
1896			}
1897			rb->xfer = fw_xfer_alloc(M_FWXFER);
1898			if(rb->xfer == NULL){
1899				return;
1900			}
1901			rb->xfer->send.spd = rb->spd;
1902			rb->xfer->send.pay_len = 0;
1903			resfp = &rb->xfer->send.hdr;
1904			switch (tcode) {
1905			case FWTCODE_WREQQ:
1906			case FWTCODE_WREQB:
1907				resfp->mode.hdr.tcode = FWTCODE_WRES;
1908				break;
1909			case FWTCODE_RREQQ:
1910				resfp->mode.hdr.tcode = FWTCODE_RRESQ;
1911				break;
1912			case FWTCODE_RREQB:
1913				resfp->mode.hdr.tcode = FWTCODE_RRESB;
1914				break;
1915			case FWTCODE_LREQ:
1916				resfp->mode.hdr.tcode = FWTCODE_LRES;
1917				break;
1918			}
1919			resfp->mode.hdr.dst = fp->mode.hdr.src;
1920			resfp->mode.hdr.tlrt = fp->mode.hdr.tlrt;
1921			resfp->mode.hdr.pri = fp->mode.hdr.pri;
1922			resfp->mode.rresb.rtcode = RESP_ADDRESS_ERROR;
1923			resfp->mode.rresb.extcode = 0;
1924			resfp->mode.rresb.len = 0;
1925/*
1926			rb->xfer->hand = fw_xferwake;
1927*/
1928			rb->xfer->hand = fw_xfer_free;
1929			if(fw_asyreq(rb->fc, -1, rb->xfer)){
1930				fw_xfer_free(rb->xfer);
1931				return;
1932			}
1933			return;
1934		}
1935		len = 0;
1936		for (i = 0; i < rb->nvec; i ++)
1937			len += rb->vec[i].iov_len;
1938		rb->xfer = STAILQ_FIRST(&bind->xferlist);
1939		if (rb->xfer == NULL) {
1940#if 1
1941			printf("Discard a packet for this bind.\n");
1942#endif
1943			return;
1944		}
1945		STAILQ_REMOVE_HEAD(&bind->xferlist, link);
1946		fw_rcv_copy(rb);
1947		rb->xfer->hand(rb->xfer);
1948		return;
1949#if 0 /* shouldn't happen ?? or for GASP */
1950	case FWTCODE_STREAM:
1951	{
1952		struct fw_xferq *xferq;
1953
1954		xferq = rb->fc->ir[sub];
1955#if 0
1956		printf("stream rcv dma %d len %d off %d spd %d\n",
1957			sub, len, off, spd);
1958#endif
1959		if(xferq->queued >= xferq->maxq) {
1960			printf("receive queue is full\n");
1961			return;
1962		}
1963		/* XXX get xfer from xfer queue, we don't need copy for
1964			per packet mode */
1965		rb->xfer = fw_xfer_alloc_buf(M_FWXFER, 0, /* XXX */
1966						vec[0].iov_len);
1967		if (rb->xfer == NULL)
1968			return;
1969		fw_rcv_copy(rb)
1970		s = splfw();
1971		xferq->queued++;
1972		STAILQ_INSERT_TAIL(&xferq->q, rb->xfer, link);
1973		splx(s);
1974		sc = device_get_softc(rb->fc->bdev);
1975#if defined(__DragonFly__) || __FreeBSD_version < 500000
1976		if (&xferq->rsel.si_pid != 0)
1977#else
1978		if (SEL_WAITING(&xferq->rsel))
1979#endif
1980			selwakeuppri(&xferq->rsel, FWPRI);
1981		if (xferq->flag & FWXFERQ_WAKEUP) {
1982			xferq->flag &= ~FWXFERQ_WAKEUP;
1983			wakeup((caddr_t)xferq);
1984		}
1985		if (xferq->flag & FWXFERQ_HANDLER) {
1986			xferq->hand(xferq);
1987		}
1988		return;
1989		break;
1990	}
1991#endif
1992	default:
1993		printf("fw_rcv: unknow tcode %d\n", tcode);
1994		break;
1995	}
1996}
1997
1998/*
1999 * Post process for Bus Manager election process.
2000 */
2001static void
2002fw_try_bmr_callback(struct fw_xfer *xfer)
2003{
2004	struct firewire_comm *fc;
2005	int bmr;
2006
2007	if (xfer == NULL)
2008		return;
2009	fc = xfer->fc;
2010	if (xfer->resp != 0)
2011		goto error;
2012	if (xfer->recv.payload == NULL)
2013		goto error;
2014	if (xfer->recv.hdr.mode.lres.rtcode != FWRCODE_COMPLETE)
2015		goto error;
2016
2017	bmr = ntohl(xfer->recv.payload[0]);
2018	if (bmr == 0x3f)
2019		bmr = fc->nodeid;
2020
2021	CSRARC(fc, BUS_MGR_ID) = fc->set_bmr(fc, bmr & 0x3f);
2022	fw_xfer_free_buf(xfer);
2023	fw_bmr(fc);
2024	return;
2025
2026error:
2027	device_printf(fc->bdev, "bus manager election failed\n");
2028	fw_xfer_free_buf(xfer);
2029}
2030
2031
2032/*
2033 * To candidate Bus Manager election process.
2034 */
2035static void
2036fw_try_bmr(void *arg)
2037{
2038	struct fw_xfer *xfer;
2039	struct firewire_comm *fc = (struct firewire_comm *)arg;
2040	struct fw_pkt *fp;
2041	int err = 0;
2042
2043	xfer = fw_xfer_alloc_buf(M_FWXFER, 8, 4);
2044	if(xfer == NULL){
2045		return;
2046	}
2047	xfer->send.spd = 0;
2048	fc->status = FWBUSMGRELECT;
2049
2050	fp = &xfer->send.hdr;
2051	fp->mode.lreq.dest_hi = 0xffff;
2052	fp->mode.lreq.tlrt = 0;
2053	fp->mode.lreq.tcode = FWTCODE_LREQ;
2054	fp->mode.lreq.pri = 0;
2055	fp->mode.lreq.src = 0;
2056	fp->mode.lreq.len = 8;
2057	fp->mode.lreq.extcode = EXTCODE_CMP_SWAP;
2058	fp->mode.lreq.dst = FWLOCALBUS | fc->irm;
2059	fp->mode.lreq.dest_lo = 0xf0000000 | BUS_MGR_ID;
2060	xfer->send.payload[0] = htonl(0x3f);
2061	xfer->send.payload[1] = htonl(fc->nodeid);
2062	xfer->hand = fw_try_bmr_callback;
2063
2064	err = fw_asyreq(fc, -1, xfer);
2065	if(err){
2066		fw_xfer_free_buf(xfer);
2067		return;
2068	}
2069	return;
2070}
2071
2072#ifdef FW_VMACCESS
2073/*
2074 * Software implementation for physical memory block access.
2075 * XXX:Too slow, usef for debug purpose only.
2076 */
2077static void
2078fw_vmaccess(struct fw_xfer *xfer){
2079	struct fw_pkt *rfp, *sfp = NULL;
2080	uint32_t *ld = (uint32_t *)xfer->recv.buf;
2081
2082	printf("vmaccess spd:%2x len:%03x data:%08x %08x %08x %08x\n",
2083			xfer->spd, xfer->recv.len, ntohl(ld[0]), ntohl(ld[1]), ntohl(ld[2]), ntohl(ld[3]));
2084	printf("vmaccess          data:%08x %08x %08x %08x\n", ntohl(ld[4]), ntohl(ld[5]), ntohl(ld[6]), ntohl(ld[7]));
2085	if(xfer->resp != 0){
2086		fw_xfer_free( xfer);
2087		return;
2088	}
2089	if(xfer->recv.buf == NULL){
2090		fw_xfer_free( xfer);
2091		return;
2092	}
2093	rfp = (struct fw_pkt *)xfer->recv.buf;
2094	switch(rfp->mode.hdr.tcode){
2095		/* XXX need fix for 64bit arch */
2096		case FWTCODE_WREQB:
2097			xfer->send.buf = malloc(12, M_FW, M_NOWAIT);
2098			xfer->send.len = 12;
2099			sfp = (struct fw_pkt *)xfer->send.buf;
2100			bcopy(rfp->mode.wreqb.payload,
2101				(caddr_t)ntohl(rfp->mode.wreqb.dest_lo), ntohs(rfp->mode.wreqb.len));
2102			sfp->mode.wres.tcode = FWTCODE_WRES;
2103			sfp->mode.wres.rtcode = 0;
2104			break;
2105		case FWTCODE_WREQQ:
2106			xfer->send.buf = malloc(12, M_FW, M_NOWAIT);
2107			xfer->send.len = 12;
2108			sfp->mode.wres.tcode = FWTCODE_WRES;
2109			*((uint32_t *)(ntohl(rfp->mode.wreqb.dest_lo))) = rfp->mode.wreqq.data;
2110			sfp->mode.wres.rtcode = 0;
2111			break;
2112		case FWTCODE_RREQB:
2113			xfer->send.buf = malloc(16 + rfp->mode.rreqb.len, M_FW, M_NOWAIT);
2114			xfer->send.len = 16 + ntohs(rfp->mode.rreqb.len);
2115			sfp = (struct fw_pkt *)xfer->send.buf;
2116			bcopy((caddr_t)ntohl(rfp->mode.rreqb.dest_lo),
2117				sfp->mode.rresb.payload, (uint16_t)ntohs(rfp->mode.rreqb.len));
2118			sfp->mode.rresb.tcode = FWTCODE_RRESB;
2119			sfp->mode.rresb.len = rfp->mode.rreqb.len;
2120			sfp->mode.rresb.rtcode = 0;
2121			sfp->mode.rresb.extcode = 0;
2122			break;
2123		case FWTCODE_RREQQ:
2124			xfer->send.buf = malloc(16, M_FW, M_NOWAIT);
2125			xfer->send.len = 16;
2126			sfp = (struct fw_pkt *)xfer->send.buf;
2127			sfp->mode.rresq.data = *(uint32_t *)(ntohl(rfp->mode.rreqq.dest_lo));
2128			sfp->mode.wres.tcode = FWTCODE_RRESQ;
2129			sfp->mode.rresb.rtcode = 0;
2130			break;
2131		default:
2132			fw_xfer_free( xfer);
2133			return;
2134	}
2135	sfp->mode.hdr.dst = rfp->mode.hdr.src;
2136	xfer->dst = ntohs(rfp->mode.hdr.src);
2137	xfer->hand = fw_xfer_free;
2138
2139	sfp->mode.hdr.tlrt = rfp->mode.hdr.tlrt;
2140	sfp->mode.hdr.pri = 0;
2141
2142	fw_asyreq(xfer->fc, -1, xfer);
2143/**/
2144	return;
2145}
2146#endif
2147
2148/*
2149 * CRC16 check-sum for IEEE1394 register blocks.
2150 */
2151uint16_t
2152fw_crc16(uint32_t *ptr, uint32_t len){
2153	uint32_t i, sum, crc = 0;
2154	int shift;
2155	len = (len + 3) & ~3;
2156	for(i = 0 ; i < len ; i+= 4){
2157		for( shift = 28 ; shift >= 0 ; shift -= 4){
2158			sum = ((crc >> 12) ^ (ptr[i/4] >> shift)) & 0xf;
2159			crc = (crc << 4) ^ ( sum << 12 ) ^ ( sum << 5) ^ sum;
2160		}
2161		crc &= 0xffff;
2162	}
2163	return((uint16_t) crc);
2164}
2165
2166static int
2167fw_bmr(struct firewire_comm *fc)
2168{
2169	struct fw_device fwdev;
2170	union fw_self_id *self_id;
2171	int cmstr;
2172	uint32_t quad;
2173
2174	/* Check to see if the current root node is cycle master capable */
2175	self_id = fw_find_self_id(fc, fc->max_node);
2176	if (fc->max_node > 0) {
2177		/* XXX check cmc bit of businfo block rather than contender */
2178		if (self_id->p0.link_active && self_id->p0.contender)
2179			cmstr = fc->max_node;
2180		else {
2181			device_printf(fc->bdev,
2182				"root node is not cycle master capable\n");
2183			/* XXX shall we be the cycle master? */
2184			cmstr = fc->nodeid;
2185			/* XXX need bus reset */
2186		}
2187	} else
2188		cmstr = -1;
2189
2190	device_printf(fc->bdev, "bus manager %d ", CSRARC(fc, BUS_MGR_ID));
2191	if(CSRARC(fc, BUS_MGR_ID) != fc->nodeid) {
2192		/* We are not the bus manager */
2193		printf("\n");
2194		return(0);
2195	}
2196	printf("(me)\n");
2197
2198	/* Optimize gapcount */
2199	if(fc->max_hop <= MAX_GAPHOP )
2200		fw_phy_config(fc, cmstr, gap_cnt[fc->max_hop]);
2201	/* If we are the cycle master, nothing to do */
2202	if (cmstr == fc->nodeid || cmstr == -1)
2203		return 0;
2204	/* Bus probe has not finished, make dummy fwdev for cmstr */
2205	bzero(&fwdev, sizeof(fwdev));
2206	fwdev.fc = fc;
2207	fwdev.dst = cmstr;
2208	fwdev.speed = 0;
2209	fwdev.maxrec = 8; /* 512 */
2210	fwdev.status = FWDEVINIT;
2211	/* Set cmstr bit on the cycle master */
2212	quad = htonl(1 << 8);
2213	fwmem_write_quad(&fwdev, NULL, 0/*spd*/,
2214		0xffff, 0xf0000000 | STATE_SET, &quad, fw_asy_callback_free);
2215
2216	return 0;
2217}
2218
2219int
2220fw_open_isodma(struct firewire_comm *fc, int tx)
2221{
2222	struct fw_xferq **xferqa;
2223	struct fw_xferq *xferq;
2224	int i;
2225
2226	if (tx)
2227		xferqa = &fc->it[0];
2228	else
2229		xferqa = &fc->ir[0];
2230
2231	FW_GLOCK(fc);
2232	for (i = 0; i < fc->nisodma; i ++) {
2233		xferq = xferqa[i];
2234		if ((xferq->flag & FWXFERQ_OPEN) == 0) {
2235			xferq->flag |= FWXFERQ_OPEN;
2236			break;
2237		}
2238	}
2239	if (i == fc->nisodma) {
2240		printf("no free dma channel (tx=%d)\n", tx);
2241		i = -1;
2242	}
2243	FW_GUNLOCK(fc);
2244	return (i);
2245}
2246
2247static int
2248fw_modevent(module_t mode, int type, void *data)
2249{
2250	int err = 0;
2251#if defined(__FreeBSD__) && __FreeBSD_version >= 500000
2252	static eventhandler_tag fwdev_ehtag = NULL;
2253#endif
2254
2255	switch (type) {
2256	case MOD_LOAD:
2257#if defined(__FreeBSD__) && __FreeBSD_version >= 500000
2258		fwdev_ehtag = EVENTHANDLER_REGISTER(dev_clone,
2259						fwdev_clone, 0, 1000);
2260#endif
2261		break;
2262	case MOD_UNLOAD:
2263#if defined(__FreeBSD__) && __FreeBSD_version >= 500000
2264		if (fwdev_ehtag != NULL)
2265			EVENTHANDLER_DEREGISTER(dev_clone, fwdev_ehtag);
2266#endif
2267		break;
2268	case MOD_SHUTDOWN:
2269		break;
2270	default:
2271		return (EOPNOTSUPP);
2272	}
2273	return (err);
2274}
2275
2276
2277#ifdef __DragonFly__
2278DECLARE_DUMMY_MODULE(firewire);
2279#endif
2280DRIVER_MODULE(firewire,fwohci,firewire_driver,firewire_devclass,fw_modevent,0);
2281MODULE_VERSION(firewire, 1);
2282