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