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