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