Merge from vendor branch TCPDUMP:
[dragonfly.git] / sys / dev / netif / kue / if_kue.c
1 /*
2  * Copyright (c) 1997, 1998, 1999, 2000
3  *      Bill Paul <wpaul@ee.columbia.edu>.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by Bill Paul.
16  * 4. Neither the name of the author nor the names of any co-contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY Bill Paul AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL Bill Paul OR THE VOICES IN HIS HEAD
24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
30  * THE POSSIBILITY OF SUCH DAMAGE.
31  *
32  * $FreeBSD: src/sys/dev/usb/if_kue.c,v 1.17.2.9 2003/04/13 02:39:25 murray Exp $
33  * $DragonFly: src/sys/dev/netif/kue/if_kue.c,v 1.25 2007/07/01 21:24:02 hasso Exp $
34  */
35
36 /*
37  * Kawasaki LSI KL5KUSB101B USB to ethernet adapter driver.
38  *
39  * Written by Bill Paul <wpaul@ee.columbia.edu>
40  * Electrical Engineering Department
41  * Columbia University, New York City
42  */
43
44 /*
45  * The KLSI USB to ethernet adapter chip contains an USB serial interface,
46  * ethernet MAC and embedded microcontroller (called the QT Engine).
47  * The chip must have firmware loaded into it before it will operate.
48  * Packets are passed between the chip and host via bulk transfers.
49  * There is an interrupt endpoint mentioned in the software spec, however
50  * it's currently unused. This device is 10Mbps half-duplex only, hence
51  * there is no media selection logic. The MAC supports a 128 entry
52  * multicast filter, though the exact size of the filter can depend
53  * on the firmware. Curiously, while the software spec describes various
54  * ethernet statistics counters, my sample adapter and firmware combination
55  * claims not to support any statistics counters at all.
56  *
57  * Note that once we load the firmware in the device, we have to be
58  * careful not to load it again: if you restart your computer but
59  * leave the adapter attached to the USB controller, it may remain
60  * powered on and retain its firmware. In this case, we don't need
61  * to load the firmware a second time.
62  *
63  * Special thanks to Rob Furr for providing an ADS Technologies
64  * adapter for development and testing. No monkeys were harmed during
65  * the development of this driver.
66  */
67
68 #include <sys/param.h>
69 #include <sys/systm.h>
70 #include <sys/sockio.h>
71 #include <sys/mbuf.h>
72 #include <sys/malloc.h>
73 #include <sys/kernel.h>
74 #include <sys/socket.h>
75 #include <sys/bus.h>
76
77 #include <net/if.h>
78 #include <net/ifq_var.h>
79 #include <net/if_arp.h>
80 #include <net/ethernet.h>
81 #include <net/if_dl.h>
82 #include <net/if_media.h>
83 #include <net/bpf.h>
84
85 #include <machine/clock.h>
86
87 #include <bus/usb/usb.h>
88 #include <bus/usb/usbdi.h>
89 #include <bus/usb/usbdi_util.h>
90 #include <bus/usb/usbdivar.h>
91 #include <bus/usb/usbdevs.h>
92 #include <bus/usb/usb_ethersubr.h>
93
94 #include "if_kuereg.h"
95 #include <bus/usb/kue_fw.h>
96
97 MODULE_DEPEND(kue, usb, 1, 1, 1);
98
99 /*
100  * Various supported device vendors/products.
101  */
102 static struct kue_type kue_devs[] = {
103         { USB_VENDOR_AOX, USB_PRODUCT_AOX_USB101 },
104         { USB_VENDOR_KLSI, USB_PRODUCT_AOX_USB101 },
105         { USB_VENDOR_ADS, USB_PRODUCT_ADS_UBS10BT },
106         { USB_VENDOR_ATEN, USB_PRODUCT_ATEN_UC10T },
107         { USB_VENDOR_NETGEAR, USB_PRODUCT_NETGEAR_EA101 },
108         { USB_VENDOR_PERACOM, USB_PRODUCT_PERACOM_ENET },
109         { USB_VENDOR_PERACOM, USB_PRODUCT_PERACOM_ENET2 },
110         { USB_VENDOR_ENTREGA, USB_PRODUCT_ENTREGA_E45 },
111         { USB_VENDOR_3COM, USB_PRODUCT_3COM_3C19250 },
112         { USB_VENDOR_COREGA, USB_PRODUCT_COREGA_ETHER_USB_T },
113         { USB_VENDOR_DLINK, USB_PRODUCT_DLINK_DSB650C },
114         { USB_VENDOR_SMC, USB_PRODUCT_SMC_2102USB },
115         { USB_VENDOR_LINKSYS, USB_PRODUCT_LINKSYS_USB10T },
116         { USB_VENDOR_KLSI, USB_PRODUCT_KLSI_DUH3E10BT },
117         { USB_VENDOR_KLSI, USB_PRODUCT_KLSI_DUH3E10BTN },
118         { USB_VENDOR_PERACOM, USB_PRODUCT_PERACOM_ENET3 },
119         { USB_VENDOR_IODATA, USB_PRODUCT_IODATA_USBETT },
120         { USB_VENDOR_ABOCOM, USB_PRODUCT_ABOCOM_URE450 },
121         { 0, 0 }
122 };
123
124 static int kue_match(device_t);
125 static int kue_attach(device_t);
126 static int kue_detach(device_t);
127 static void kue_shutdown(device_t);
128 static int kue_tx_list_init(struct kue_softc *);
129 static int kue_rx_list_init(struct kue_softc *);
130 static int kue_newbuf(struct kue_softc *, struct kue_chain *, struct mbuf *);
131 static int kue_encap(struct kue_softc *, struct mbuf *, int);
132 static void kue_rxeof(usbd_xfer_handle, usbd_private_handle, usbd_status);
133 static void kue_txeof(usbd_xfer_handle, usbd_private_handle, usbd_status);
134 static void kue_start(struct ifnet *);
135 static void kue_rxstart(struct ifnet *);
136 static int kue_ioctl(struct ifnet *, u_long, caddr_t, struct ucred *);
137 static void kue_init(void *);
138 static void kue_stop(struct kue_softc *);
139 static void kue_watchdog(struct ifnet *);
140
141 static void kue_setmulti(struct kue_softc *);
142 static void kue_reset(struct kue_softc *);
143
144 static usbd_status kue_do_request(usbd_device_handle,
145                                   usb_device_request_t *, void *);
146 static usbd_status kue_ctl(struct kue_softc *, int, u_int8_t,
147                            u_int16_t, char *, int);
148 static usbd_status kue_setword(struct kue_softc *, u_int8_t, u_int16_t);
149 static int kue_load_fw(struct kue_softc *);
150
151 static device_method_t kue_methods[] = {
152         /* Device interface */
153         DEVMETHOD(device_probe,         kue_match),
154         DEVMETHOD(device_attach,        kue_attach),
155         DEVMETHOD(device_detach,        kue_detach),
156         DEVMETHOD(device_shutdown,      kue_shutdown),
157
158         { 0, 0 }
159 };
160
161 static driver_t kue_driver = {
162         "kue",
163         kue_methods,
164         sizeof(struct kue_softc)
165 };
166
167 static devclass_t kue_devclass;
168
169 DECLARE_DUMMY_MODULE(if_kue);
170 DRIVER_MODULE(kue, uhub, kue_driver, kue_devclass, usbd_driver_load, 0);
171
172 /*
173  * We have a custom do_request function which is almost like the
174  * regular do_request function, except it has a much longer timeout.
175  * Why? Because we need to make requests over the control endpoint
176  * to download the firmware to the device, which can take longer
177  * than the default timeout.
178  */
179 static usbd_status
180 kue_do_request(usbd_device_handle dev, usb_device_request_t *req, void *data)
181 {
182         usbd_xfer_handle        xfer;
183         usbd_status             err;
184
185         xfer = usbd_alloc_xfer(dev);
186         usbd_setup_default_xfer(xfer, dev, 0, 500000, req,
187             data, UGETW(req->wLength), USBD_SHORT_XFER_OK, 0);
188         err = usbd_sync_transfer(xfer);
189         usbd_free_xfer(xfer);
190         return(err);
191 }
192
193 static usbd_status
194 kue_setword(struct kue_softc *sc, u_int8_t breq, u_int16_t word)
195 {
196         usbd_device_handle      dev;
197         usb_device_request_t    req;
198         usbd_status             err;
199
200         if (sc->kue_dying)
201                 return(USBD_NORMAL_COMPLETION);
202
203         dev = sc->kue_udev;
204
205         KUE_LOCK(sc);
206
207         req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
208
209         req.bRequest = breq;
210         USETW(req.wValue, word);
211         USETW(req.wIndex, 0);
212         USETW(req.wLength, 0);
213
214         err = kue_do_request(dev, &req, NULL);
215
216         KUE_UNLOCK(sc);
217
218         return(err);
219 }
220
221 static usbd_status
222 kue_ctl(struct kue_softc *sc, int rw, u_int8_t breq, u_int16_t val,
223         char *data, int len)
224 {
225         usbd_device_handle      dev;
226         usb_device_request_t    req;
227         usbd_status             err;
228
229         dev = sc->kue_udev;
230
231         if (sc->kue_dying)
232                 return(USBD_NORMAL_COMPLETION);
233
234         KUE_LOCK(sc);
235
236         if (rw == KUE_CTL_WRITE)
237                 req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
238         else
239                 req.bmRequestType = UT_READ_VENDOR_DEVICE;
240
241         req.bRequest = breq;
242         USETW(req.wValue, val);
243         USETW(req.wIndex, 0);
244         USETW(req.wLength, len);
245
246         err = kue_do_request(dev, &req, data);
247
248         KUE_UNLOCK(sc);
249
250         return(err);
251 }
252
253 static int
254 kue_load_fw(struct kue_softc *sc)
255 {
256         usbd_status             err;
257         usb_device_descriptor_t *dd;
258         int                     hwrev;
259
260         dd = &sc->kue_udev->ddesc;
261         hwrev = UGETW(dd->bcdDevice);
262
263         /*
264          * First, check if we even need to load the firmware.
265          * If the device was still attached when the system was
266          * rebooted, it may already have firmware loaded in it.
267          * If this is the case, we don't need to do it again.
268          * And in fact, if we try to load it again, we'll hang,
269          * so we have to avoid this condition if we don't want
270          * to look stupid.
271          *
272          * We can test this quickly by checking the bcdRevision
273          * code. The NIC will return a different revision code if
274          * it's probed while the firmware is still loaded and
275          * running.
276          */
277         if (hwrev == 0x0202)
278                 return(0);
279
280         /* Load code segment */
281         err = kue_ctl(sc, KUE_CTL_WRITE, KUE_CMD_SEND_SCAN,
282             0, kue_code_seg, sizeof(kue_code_seg));
283         if (err) {
284                 kprintf("kue%d: failed to load code segment: %s\n",
285                     sc->kue_unit, usbd_errstr(err));
286                         return(ENXIO);
287         }
288
289         /* Load fixup segment */
290         err = kue_ctl(sc, KUE_CTL_WRITE, KUE_CMD_SEND_SCAN,
291             0, kue_fix_seg, sizeof(kue_fix_seg));
292         if (err) {
293                 kprintf("kue%d: failed to load fixup segment: %s\n",
294                     sc->kue_unit, usbd_errstr(err));
295                         return(ENXIO);
296         }
297
298         /* Send trigger command. */
299         err = kue_ctl(sc, KUE_CTL_WRITE, KUE_CMD_SEND_SCAN,
300             0, kue_trig_seg, sizeof(kue_trig_seg));
301         if (err) {
302                 kprintf("kue%d: failed to load trigger segment: %s\n",
303                     sc->kue_unit, usbd_errstr(err));
304                         return(ENXIO);
305         }
306
307         return(0);
308 }
309
310 static void
311 kue_setmulti(struct kue_softc *sc)
312 {
313         struct ifnet            *ifp;
314         struct ifmultiaddr      *ifma;
315         int                     i = 0;
316
317         ifp = &sc->arpcom.ac_if;
318
319         if (ifp->if_flags & IFF_ALLMULTI || ifp->if_flags & IFF_PROMISC) {
320                 sc->kue_rxfilt |= KUE_RXFILT_ALLMULTI;
321                 sc->kue_rxfilt &= ~KUE_RXFILT_MULTICAST;
322                 kue_setword(sc, KUE_CMD_SET_PKT_FILTER, sc->kue_rxfilt);
323                 return;
324         }
325
326         sc->kue_rxfilt &= ~KUE_RXFILT_ALLMULTI;
327
328 #if defined(__FreeBSD__) && __FreeBSD_version >= 500000
329         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link)
330 #else
331         LIST_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link)
332 #endif
333         {
334                 if (ifma->ifma_addr->sa_family != AF_LINK)
335                         continue;
336                 /*
337                  * If there are too many addresses for the
338                  * internal filter, switch over to allmulti mode.
339                  */
340                 if (i == KUE_MCFILTCNT(sc))
341                         break;
342                 bcopy(LLADDR((struct sockaddr_dl *)ifma->ifma_addr),
343                     KUE_MCFILT(sc, i), ETHER_ADDR_LEN);
344                 i++;
345         }
346
347         if (i == KUE_MCFILTCNT(sc))
348                 sc->kue_rxfilt |= KUE_RXFILT_ALLMULTI;
349         else {
350                 sc->kue_rxfilt |= KUE_RXFILT_MULTICAST;
351                 kue_ctl(sc, KUE_CTL_WRITE, KUE_CMD_SET_MCAST_FILTERS,
352                     i, sc->kue_mcfilters, i * ETHER_ADDR_LEN);
353         }
354
355         kue_setword(sc, KUE_CMD_SET_PKT_FILTER, sc->kue_rxfilt);
356
357         return;
358 }
359
360 /*
361  * Issue a SET_CONFIGURATION command to reset the MAC. This should be
362  * done after the firmware is loaded into the adapter in order to
363  * bring it into proper operation.
364  */
365 static void
366 kue_reset(struct kue_softc *sc)
367 {
368         if (usbd_set_config_no(sc->kue_udev, KUE_CONFIG_NO, 0) ||
369             usbd_device2interface_handle(sc->kue_udev, KUE_IFACE_IDX,
370             &sc->kue_iface)) {
371                 kprintf("kue%d: getting interface handle failed\n",
372                     sc->kue_unit);
373         }
374
375         /* Wait a little while for the chip to get its brains in order. */
376         DELAY(1000);
377         return;
378 }
379
380 /*
381  * Probe for a KLSI chip.
382  */
383 static int
384 kue_match(device_t self)
385 {
386         struct usb_attach_arg *uaa = device_get_ivars(self);
387         struct kue_type                 *t;
388
389         if (!uaa->iface)
390                 return(UMATCH_NONE);
391
392         t = kue_devs;
393         while(t->kue_vid) {
394                 if (uaa->vendor == t->kue_vid &&
395                     uaa->product == t->kue_did) {
396                         return(UMATCH_VENDOR_PRODUCT);
397                 }
398                 t++;
399         }
400
401         return(UMATCH_NONE);
402 }
403
404 /*
405  * Attach the interface. Allocate softc structures, do
406  * setup and ethernet/BPF attach.
407  */
408 static int
409 kue_attach(device_t self)
410 {
411         struct kue_softc *sc = device_get_softc(self);
412         struct usb_attach_arg *uaa = device_get_ivars(self);
413         char                    devinfo[1024];
414         struct ifnet            *ifp;
415         usbd_status             err;
416         usb_interface_descriptor_t      *id;
417         usb_endpoint_descriptor_t       *ed;
418         int                     i;
419
420         sc->kue_iface = uaa->iface;
421         sc->kue_udev = uaa->device;
422         sc->kue_unit = device_get_unit(self);
423
424         id = usbd_get_interface_descriptor(uaa->iface);
425
426         usbd_devinfo(uaa->device, 0, devinfo);
427         device_set_desc_copy(self, devinfo);
428         kprintf("%s: %s\n", device_get_nameunit(self), devinfo);
429
430         /* Find endpoints. */
431         for (i = 0; i < id->bNumEndpoints; i++) {
432                 ed = usbd_interface2endpoint_descriptor(uaa->iface, i);
433                 if (!ed) {
434                         kprintf("kue%d: couldn't get ep %d\n",
435                             sc->kue_unit, i);
436                         return ENXIO;
437                 }
438                 if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN &&
439                     UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK) {
440                         sc->kue_ed[KUE_ENDPT_RX] = ed->bEndpointAddress;
441                 } else if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_OUT &&
442                            UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK) {
443                         sc->kue_ed[KUE_ENDPT_TX] = ed->bEndpointAddress;
444                 } else if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN &&
445                            UE_GET_XFERTYPE(ed->bmAttributes) == UE_INTERRUPT) {
446                         sc->kue_ed[KUE_ENDPT_INTR] = ed->bEndpointAddress;
447                 }
448         }
449
450 #if defined(__FreeBSD__) && __FreeBSD_version >= 500000
451         mtx_init(&sc->kue_mtx, device_get_nameunit(self), MTX_NETWORK_LOCK,
452             MTX_DEF | MTX_RECURSE);
453 #endif
454         KUE_LOCK(sc);
455
456         /* Load the firmware into the NIC. */
457         if (kue_load_fw(sc)) {
458                 KUE_UNLOCK(sc);
459 #if defined(__FreeBSD__) && __FreeBSD_version >= 500000
460                 mtx_destroy(&sc->kue_mtx);
461 #endif
462                 return ENXIO;
463         }
464
465         /* Reset the adapter. */
466         kue_reset(sc);
467
468         /* Read ethernet descriptor */
469         err = kue_ctl(sc, KUE_CTL_READ, KUE_CMD_GET_ETHER_DESCRIPTOR,
470             0, (char *)&sc->kue_desc, sizeof(sc->kue_desc));
471
472         sc->kue_mcfilters = kmalloc(KUE_MCFILTCNT(sc) * ETHER_ADDR_LEN,
473             M_USBDEV, M_WAITOK);
474
475         ifp = &sc->arpcom.ac_if;
476         ifp->if_softc = sc;
477         if_initname(ifp, "kue", sc->kue_unit);
478         ifp->if_mtu = ETHERMTU;
479         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
480         ifp->if_ioctl = kue_ioctl;
481         ifp->if_start = kue_start;
482         ifp->if_watchdog = kue_watchdog;
483         ifp->if_init = kue_init;
484         ifp->if_baudrate = 10000000;
485         ifq_set_maxlen(&ifp->if_snd, IFQ_MAXLEN);
486         ifq_set_ready(&ifp->if_snd);
487
488         /*
489          * Call MI attach routine.
490          */
491         ether_ifattach(ifp, sc->kue_desc.kue_macaddr, NULL);
492         usb_register_netisr();
493         sc->kue_dying = 0;
494
495         KUE_UNLOCK(sc);
496
497         return 0;
498 }
499
500 static int
501 kue_detach(device_t dev)
502 {
503         struct kue_softc        *sc;
504         struct ifnet            *ifp;
505
506         sc = device_get_softc(dev);
507         KUE_LOCK(sc);
508         ifp = &sc->arpcom.ac_if;
509
510         sc->kue_dying = 1;
511
512         if (ifp != NULL)
513                 ether_ifdetach(ifp);
514
515         if (sc->kue_ep[KUE_ENDPT_TX] != NULL)
516                 usbd_abort_pipe(sc->kue_ep[KUE_ENDPT_TX]);
517         if (sc->kue_ep[KUE_ENDPT_RX] != NULL)
518                 usbd_abort_pipe(sc->kue_ep[KUE_ENDPT_RX]);
519         if (sc->kue_ep[KUE_ENDPT_INTR] != NULL)
520                 usbd_abort_pipe(sc->kue_ep[KUE_ENDPT_INTR]);
521
522         if (sc->kue_mcfilters != NULL)
523                 kfree(sc->kue_mcfilters, M_USBDEV);
524
525         KUE_UNLOCK(sc);
526 #if defined(__FreeBSD__) && __FreeBSD_version >= 500000
527         mtx_destroy(&sc->kue_mtx);
528 #endif
529
530         return(0);
531 }
532
533 /*
534  * Initialize an RX descriptor and attach an MBUF cluster.
535  */
536 static int
537 kue_newbuf(struct kue_softc *sc, struct kue_chain *c, struct mbuf *m)
538 {
539         struct mbuf             *m_new = NULL;
540
541         if (m == NULL) {
542                 MGETHDR(m_new, MB_DONTWAIT, MT_DATA);
543                 if (m_new == NULL) {
544                         kprintf("kue%d: no memory for rx list "
545                             "-- packet dropped!\n", sc->kue_unit);
546                         return(ENOBUFS);
547                 }
548
549                 MCLGET(m_new, MB_DONTWAIT);
550                 if (!(m_new->m_flags & M_EXT)) {
551                         kprintf("kue%d: no memory for rx list "
552                             "-- packet dropped!\n", sc->kue_unit);
553                         m_freem(m_new);
554                         return(ENOBUFS);
555                 }
556                 m_new->m_len = m_new->m_pkthdr.len = MCLBYTES;
557         } else {
558                 m_new = m;
559                 m_new->m_len = m_new->m_pkthdr.len = MCLBYTES;
560                 m_new->m_data = m_new->m_ext.ext_buf;
561         }
562
563         c->kue_mbuf = m_new;
564
565         return(0);
566 }
567
568 static int
569 kue_rx_list_init(struct kue_softc *sc)
570 {
571         struct kue_cdata        *cd;
572         struct kue_chain        *c;
573         int                     i;
574
575         cd = &sc->kue_cdata;
576         for (i = 0; i < KUE_RX_LIST_CNT; i++) {
577                 c = &cd->kue_rx_chain[i];
578                 c->kue_sc = sc;
579                 c->kue_idx = i;
580                 if (kue_newbuf(sc, c, NULL) == ENOBUFS)
581                         return(ENOBUFS);
582                 if (c->kue_xfer == NULL) {
583                         c->kue_xfer = usbd_alloc_xfer(sc->kue_udev);
584                         if (c->kue_xfer == NULL)
585                                 return(ENOBUFS);
586                 }
587         }
588
589         return(0);
590 }
591
592 static int
593 kue_tx_list_init(struct kue_softc *sc)
594 {
595         struct kue_cdata        *cd;
596         struct kue_chain        *c;
597         int                     i;
598
599         cd = &sc->kue_cdata;
600         for (i = 0; i < KUE_TX_LIST_CNT; i++) {
601                 c = &cd->kue_tx_chain[i];
602                 c->kue_sc = sc;
603                 c->kue_idx = i;
604                 c->kue_mbuf = NULL;
605                 if (c->kue_xfer == NULL) {
606                         c->kue_xfer = usbd_alloc_xfer(sc->kue_udev);
607                         if (c->kue_xfer == NULL)
608                                 return(ENOBUFS);
609                 }
610                 c->kue_buf = kmalloc(KUE_BUFSZ, M_USBDEV, M_WAITOK);
611                 if (c->kue_buf == NULL)
612                         return(ENOBUFS);
613         }
614
615         return(0);
616 }
617
618 static void
619 kue_rxstart(struct ifnet *ifp)
620 {
621         struct kue_softc        *sc;
622         struct kue_chain        *c;
623
624         sc = ifp->if_softc;
625         KUE_LOCK(sc);
626         c = &sc->kue_cdata.kue_rx_chain[sc->kue_cdata.kue_rx_prod];
627
628         if (kue_newbuf(sc, c, NULL) == ENOBUFS) {
629                 ifp->if_ierrors++;
630                 return;
631         }
632
633         /* Setup new transfer. */
634         usbd_setup_xfer(c->kue_xfer, sc->kue_ep[KUE_ENDPT_RX],
635             c, mtod(c->kue_mbuf, char *), KUE_BUFSZ, USBD_SHORT_XFER_OK,
636             USBD_NO_TIMEOUT, kue_rxeof);
637         usbd_transfer(c->kue_xfer);
638
639         KUE_UNLOCK(sc);
640
641         return;
642 }
643
644 /*
645  * A frame has been uploaded: pass the resulting mbuf chain up to
646  * the higher level protocols.
647  */
648 static void
649 kue_rxeof(usbd_xfer_handle xfer, usbd_private_handle priv, usbd_status status)
650 {
651         struct kue_softc        *sc;
652         struct kue_chain        *c;
653         struct mbuf             *m;
654         struct ifnet            *ifp;
655         int                     total_len = 0;
656         u_int16_t               len;
657
658         c = priv;
659         sc = c->kue_sc;
660         KUE_LOCK(sc);
661         ifp = &sc->arpcom.ac_if;
662
663         if (!(ifp->if_flags & IFF_RUNNING)) {
664                 KUE_UNLOCK(sc);
665                 return;
666         }
667
668         if (status != USBD_NORMAL_COMPLETION) {
669                 if (status == USBD_NOT_STARTED || status == USBD_CANCELLED) {
670                         KUE_UNLOCK(sc);
671                         return;
672                 }
673                 if (usbd_ratecheck(&sc->kue_rx_notice))
674                         kprintf("kue%d: usb error on rx: %s\n", sc->kue_unit,
675                             usbd_errstr(status));
676                 if (status == USBD_STALLED)
677                         usbd_clear_endpoint_stall(sc->kue_ep[KUE_ENDPT_RX]);
678                 goto done;
679         }
680
681         usbd_get_xfer_status(xfer, NULL, NULL, &total_len, NULL);
682         m = c->kue_mbuf;
683         if (total_len <= 1)
684                 goto done;
685
686         len = *mtod(m, u_int16_t *);
687         m_adj(m, sizeof(u_int16_t));
688
689         /* No errors; receive the packet. */
690         total_len = len;
691
692         if (len < sizeof(struct ether_header)) {
693                 ifp->if_ierrors++;
694                 goto done;
695         }
696
697         ifp->if_ipackets++;
698         m->m_pkthdr.rcvif = ifp;
699         m->m_pkthdr.len = m->m_len = total_len;
700
701         /* Put the packet on the special USB input queue. */
702         usb_ether_input(m);
703         kue_rxstart(ifp);
704
705         KUE_UNLOCK(sc);
706
707         return;
708 done:
709
710         /* Setup new transfer. */
711         usbd_setup_xfer(c->kue_xfer, sc->kue_ep[KUE_ENDPT_RX],
712             c, mtod(c->kue_mbuf, char *), KUE_BUFSZ, USBD_SHORT_XFER_OK,
713             USBD_NO_TIMEOUT, kue_rxeof);
714         usbd_transfer(c->kue_xfer);
715         KUE_UNLOCK(sc);
716
717         return;
718 }
719
720 /*
721  * A frame was downloaded to the chip. It's safe for us to clean up
722  * the list buffers.
723  */
724
725 static void
726 kue_txeof(usbd_xfer_handle xfer, usbd_private_handle priv, usbd_status status)
727 {
728         struct kue_softc        *sc;
729         struct kue_chain        *c;
730         struct ifnet            *ifp;
731         usbd_status             err;
732
733         c = priv;
734         sc = c->kue_sc;
735         KUE_LOCK(sc);
736
737         ifp = &sc->arpcom.ac_if;
738         ifp->if_timer = 0;
739         ifp->if_flags &= ~IFF_OACTIVE;
740
741         if (status != USBD_NORMAL_COMPLETION) {
742                 if (status == USBD_NOT_STARTED || status == USBD_CANCELLED) {
743                         KUE_UNLOCK(sc);
744                         return;
745                 }
746                 kprintf("kue%d: usb error on tx: %s\n", sc->kue_unit,
747                     usbd_errstr(status));
748                 if (status == USBD_STALLED)
749                         usbd_clear_endpoint_stall(sc->kue_ep[KUE_ENDPT_TX]);
750                 KUE_UNLOCK(sc);
751                 return;
752         }
753
754         usbd_get_xfer_status(c->kue_xfer, NULL, NULL, NULL, &err);
755
756         if (c->kue_mbuf != NULL) {
757                 m_freem(c->kue_mbuf);
758                 c->kue_mbuf = NULL;
759         }
760
761         if (err)
762                 ifp->if_oerrors++;
763         else
764                 ifp->if_opackets++;
765
766         if (!ifq_is_empty(&ifp->if_snd))
767                 (*ifp->if_start)(ifp);
768
769         KUE_UNLOCK(sc);
770
771         return;
772 }
773
774 static int
775 kue_encap(struct kue_softc *sc, struct mbuf *m, int idx)
776 {
777         int                     total_len;
778         struct kue_chain        *c;
779         usbd_status             err;
780
781         c = &sc->kue_cdata.kue_tx_chain[idx];
782
783         /*
784          * Copy the mbuf data into a contiguous buffer, leaving two
785          * bytes at the beginning to hold the frame length.
786          */
787         m_copydata(m, 0, m->m_pkthdr.len, c->kue_buf + 2);
788         c->kue_mbuf = m;
789
790         total_len = m->m_pkthdr.len + 2;
791         total_len += 64 - (total_len % 64);
792
793         /* Frame length is specified in the first 2 bytes of the buffer. */
794         c->kue_buf[0] = (u_int8_t)m->m_pkthdr.len;
795         c->kue_buf[1] = (u_int8_t)(m->m_pkthdr.len >> 8);
796
797         usbd_setup_xfer(c->kue_xfer, sc->kue_ep[KUE_ENDPT_TX],
798             c, c->kue_buf, total_len, 0, 10000, kue_txeof);
799
800         /* Transmit */
801         err = usbd_transfer(c->kue_xfer);
802         if (err != USBD_IN_PROGRESS) {
803                 kue_stop(sc);
804                 return(EIO);
805         }
806
807         sc->kue_cdata.kue_tx_cnt++;
808
809         return(0);
810 }
811
812 static void
813 kue_start(struct ifnet *ifp)
814 {
815         struct kue_softc        *sc;
816         struct mbuf             *m_head = NULL;
817
818         sc = ifp->if_softc;
819         KUE_LOCK(sc);
820
821         if (ifp->if_flags & IFF_OACTIVE) {
822                 KUE_UNLOCK(sc);
823                 return;
824         }
825
826         m_head = ifq_poll(&ifp->if_snd);
827         if (m_head == NULL) {
828                 KUE_UNLOCK(sc);
829                 return;
830         }
831
832         if (kue_encap(sc, m_head, 0)) {
833                 ifp->if_flags |= IFF_OACTIVE;
834                 KUE_UNLOCK(sc);
835                 return;
836         }
837         ifq_dequeue(&ifp->if_snd, m_head);
838
839         /*
840          * If there's a BPF listener, bounce a copy of this frame
841          * to him.
842          */
843         BPF_MTAP(ifp, m_head);
844
845         ifp->if_flags |= IFF_OACTIVE;
846
847         /*
848          * Set a timeout in case the chip goes out to lunch.
849          */
850         ifp->if_timer = 5;
851         KUE_UNLOCK(sc);
852
853         return;
854 }
855
856 static void
857 kue_init(void *xsc)
858 {
859         struct kue_softc        *sc = xsc;
860         struct ifnet            *ifp = &sc->arpcom.ac_if;
861         struct kue_chain        *c;
862         usbd_status             err;
863         int                     i;
864
865         KUE_LOCK(sc);
866
867         if (ifp->if_flags & IFF_RUNNING) {
868                 KUE_UNLOCK(sc);
869                 return;
870         }
871
872         /* Set MAC address */
873         kue_ctl(sc, KUE_CTL_WRITE, KUE_CMD_SET_MAC,
874             0, sc->arpcom.ac_enaddr, ETHER_ADDR_LEN);
875
876         sc->kue_rxfilt = KUE_RXFILT_UNICAST|KUE_RXFILT_BROADCAST;
877
878          /* If we want promiscuous mode, set the allframes bit. */
879         if (ifp->if_flags & IFF_PROMISC)
880                 sc->kue_rxfilt |= KUE_RXFILT_PROMISC;
881
882         kue_setword(sc, KUE_CMD_SET_PKT_FILTER, sc->kue_rxfilt);
883
884         /* I'm not sure how to tune these. */
885 #ifdef notdef
886         /*
887          * Leave this one alone for now; setting it
888          * wrong causes lockups on some machines/controllers.
889          */
890         kue_setword(sc, KUE_CMD_SET_SOFS, 1);
891 #endif
892         kue_setword(sc, KUE_CMD_SET_URB_SIZE, 64);
893
894         /* Init TX ring. */
895         if (kue_tx_list_init(sc) == ENOBUFS) {
896                 kprintf("kue%d: tx list init failed\n", sc->kue_unit);
897                 KUE_UNLOCK(sc);
898                 return;
899         }
900
901         /* Init RX ring. */
902         if (kue_rx_list_init(sc) == ENOBUFS) {
903                 kprintf("kue%d: rx list init failed\n", sc->kue_unit);
904                 KUE_UNLOCK(sc);
905                 return;
906         }
907
908         /* Load the multicast filter. */
909         kue_setmulti(sc);
910
911         /* Open RX and TX pipes. */
912         err = usbd_open_pipe(sc->kue_iface, sc->kue_ed[KUE_ENDPT_RX],
913             USBD_EXCLUSIVE_USE, &sc->kue_ep[KUE_ENDPT_RX]);
914         if (err) {
915                 kprintf("kue%d: open rx pipe failed: %s\n",
916                     sc->kue_unit, usbd_errstr(err));
917                 KUE_UNLOCK(sc);
918                 return;
919         }
920
921         err = usbd_open_pipe(sc->kue_iface, sc->kue_ed[KUE_ENDPT_TX],
922             USBD_EXCLUSIVE_USE, &sc->kue_ep[KUE_ENDPT_TX]);
923         if (err) {
924                 kprintf("kue%d: open tx pipe failed: %s\n",
925                     sc->kue_unit, usbd_errstr(err));
926                 KUE_UNLOCK(sc);
927                 return;
928         }
929
930         /* Start up the receive pipe. */
931         for (i = 0; i < KUE_RX_LIST_CNT; i++) {
932                 c = &sc->kue_cdata.kue_rx_chain[i];
933                 usbd_setup_xfer(c->kue_xfer, sc->kue_ep[KUE_ENDPT_RX],
934                     c, mtod(c->kue_mbuf, char *), KUE_BUFSZ,
935                 USBD_SHORT_XFER_OK, USBD_NO_TIMEOUT, kue_rxeof);
936                 usbd_transfer(c->kue_xfer);
937         }
938
939         ifp->if_flags |= IFF_RUNNING;
940         ifp->if_flags &= ~IFF_OACTIVE;
941
942         KUE_UNLOCK(sc);
943
944         return;
945 }
946
947 static int
948 kue_ioctl(struct ifnet *ifp, u_long command, caddr_t data, struct ucred *cr)
949 {
950         struct kue_softc        *sc = ifp->if_softc;
951         int                     error = 0;
952
953         KUE_LOCK(sc);
954
955         switch(command) {
956         case SIOCSIFFLAGS:
957                 if (ifp->if_flags & IFF_UP) {
958                         if (ifp->if_flags & IFF_RUNNING &&
959                             ifp->if_flags & IFF_PROMISC &&
960                             !(sc->kue_if_flags & IFF_PROMISC)) {
961                                 sc->kue_rxfilt |= KUE_RXFILT_PROMISC;
962                                 kue_setword(sc, KUE_CMD_SET_PKT_FILTER,
963                                     sc->kue_rxfilt);
964                         } else if (ifp->if_flags & IFF_RUNNING &&
965                             !(ifp->if_flags & IFF_PROMISC) &&
966                             sc->kue_if_flags & IFF_PROMISC) {
967                                 sc->kue_rxfilt &= ~KUE_RXFILT_PROMISC;
968                                 kue_setword(sc, KUE_CMD_SET_PKT_FILTER,
969                                     sc->kue_rxfilt);
970                         } else if (!(ifp->if_flags & IFF_RUNNING))
971                                 kue_init(sc);
972                 } else {
973                         if (ifp->if_flags & IFF_RUNNING)
974                                 kue_stop(sc);
975                 }
976                 sc->kue_if_flags = ifp->if_flags;
977                 error = 0;
978                 break;
979         case SIOCADDMULTI:
980         case SIOCDELMULTI:
981                 kue_setmulti(sc);
982                 error = 0;
983                 break;
984         default:
985                 error = ether_ioctl(ifp, command, data);
986                 break;
987         }
988
989         KUE_UNLOCK(sc);
990
991         return(error);
992 }
993
994 static void
995 kue_watchdog(struct ifnet *ifp)
996 {
997         struct kue_softc        *sc;
998         struct kue_chain        *c;
999         usbd_status             stat;
1000
1001         sc = ifp->if_softc;
1002         KUE_LOCK(sc);
1003         ifp->if_oerrors++;
1004         kprintf("kue%d: watchdog timeout\n", sc->kue_unit);
1005
1006         c = &sc->kue_cdata.kue_tx_chain[0];
1007         usbd_get_xfer_status(c->kue_xfer, NULL, NULL, NULL, &stat);
1008         kue_txeof(c->kue_xfer, c, stat);
1009
1010         if (ifq_is_empty(&ifp->if_snd))
1011                 kue_start(ifp);
1012         KUE_UNLOCK(sc);
1013
1014         return;
1015 }
1016
1017 /*
1018  * Stop the adapter and free any mbufs allocated to the
1019  * RX and TX lists.
1020  */
1021 static void
1022 kue_stop(struct kue_softc *sc)
1023 {
1024         usbd_status             err;
1025         struct ifnet            *ifp;
1026         int                     i;
1027
1028         KUE_LOCK(sc);
1029         ifp = &sc->arpcom.ac_if;
1030         ifp->if_timer = 0;
1031
1032         /* Stop transfers. */
1033         if (sc->kue_ep[KUE_ENDPT_RX] != NULL) {
1034                 err = usbd_abort_pipe(sc->kue_ep[KUE_ENDPT_RX]);
1035                 if (err) {
1036                         kprintf("kue%d: abort rx pipe failed: %s\n",
1037                         sc->kue_unit, usbd_errstr(err));
1038                 }
1039                 err = usbd_close_pipe(sc->kue_ep[KUE_ENDPT_RX]);
1040                 if (err) {
1041                         kprintf("kue%d: close rx pipe failed: %s\n",
1042                         sc->kue_unit, usbd_errstr(err));
1043                 }
1044                 sc->kue_ep[KUE_ENDPT_RX] = NULL;
1045         }
1046
1047         if (sc->kue_ep[KUE_ENDPT_TX] != NULL) {
1048                 err = usbd_abort_pipe(sc->kue_ep[KUE_ENDPT_TX]);
1049                 if (err) {
1050                         kprintf("kue%d: abort tx pipe failed: %s\n",
1051                         sc->kue_unit, usbd_errstr(err));
1052                 }
1053                 err = usbd_close_pipe(sc->kue_ep[KUE_ENDPT_TX]);
1054                 if (err) {
1055                         kprintf("kue%d: close tx pipe failed: %s\n",
1056                             sc->kue_unit, usbd_errstr(err));
1057                 }
1058                 sc->kue_ep[KUE_ENDPT_TX] = NULL;
1059         }
1060
1061         if (sc->kue_ep[KUE_ENDPT_INTR] != NULL) {
1062                 err = usbd_abort_pipe(sc->kue_ep[KUE_ENDPT_INTR]);
1063                 if (err) {
1064                         kprintf("kue%d: abort intr pipe failed: %s\n",
1065                         sc->kue_unit, usbd_errstr(err));
1066                 }
1067                 err = usbd_close_pipe(sc->kue_ep[KUE_ENDPT_INTR]);
1068                 if (err) {
1069                         kprintf("kue%d: close intr pipe failed: %s\n",
1070                             sc->kue_unit, usbd_errstr(err));
1071                 }
1072                 sc->kue_ep[KUE_ENDPT_INTR] = NULL;
1073         }
1074
1075         /* Free RX resources. */
1076         for (i = 0; i < KUE_RX_LIST_CNT; i++) {
1077                 if (sc->kue_cdata.kue_rx_chain[i].kue_buf != NULL) {
1078                         kfree(sc->kue_cdata.kue_rx_chain[i].kue_buf, M_USBDEV);
1079                         sc->kue_cdata.kue_rx_chain[i].kue_buf = NULL;
1080                 }
1081                 if (sc->kue_cdata.kue_rx_chain[i].kue_mbuf != NULL) {
1082                         m_freem(sc->kue_cdata.kue_rx_chain[i].kue_mbuf);
1083                         sc->kue_cdata.kue_rx_chain[i].kue_mbuf = NULL;
1084                 }
1085                 if (sc->kue_cdata.kue_rx_chain[i].kue_xfer != NULL) {
1086                         usbd_free_xfer(sc->kue_cdata.kue_rx_chain[i].kue_xfer);
1087                         sc->kue_cdata.kue_rx_chain[i].kue_xfer = NULL;
1088                 }
1089         }
1090
1091         /* Free TX resources. */
1092         for (i = 0; i < KUE_TX_LIST_CNT; i++) {
1093                 if (sc->kue_cdata.kue_tx_chain[i].kue_buf != NULL) {
1094                         kfree(sc->kue_cdata.kue_tx_chain[i].kue_buf, M_USBDEV);
1095                         sc->kue_cdata.kue_tx_chain[i].kue_buf = NULL;
1096                 }
1097                 if (sc->kue_cdata.kue_tx_chain[i].kue_mbuf != NULL) {
1098                         m_freem(sc->kue_cdata.kue_tx_chain[i].kue_mbuf);
1099                         sc->kue_cdata.kue_tx_chain[i].kue_mbuf = NULL;
1100                 }
1101                 if (sc->kue_cdata.kue_tx_chain[i].kue_xfer != NULL) {
1102                         usbd_free_xfer(sc->kue_cdata.kue_tx_chain[i].kue_xfer);
1103                         sc->kue_cdata.kue_tx_chain[i].kue_xfer = NULL;
1104                 }
1105         }
1106
1107         ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
1108         KUE_UNLOCK(sc);
1109
1110         return;
1111 }
1112
1113 /*
1114  * Stop all chip I/O so that the kernel's probe routines don't
1115  * get confused by errant DMAs when rebooting.
1116  */
1117 static void
1118 kue_shutdown(device_t dev)
1119 {
1120         struct kue_softc        *sc;
1121
1122         sc = device_get_softc(dev);
1123
1124         kue_stop(sc);
1125
1126         return;
1127 }