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