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