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