]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/usb/net/if_smsc.c
Fix memory corruption in USB network device drivers.
[FreeBSD/FreeBSD.git] / sys / dev / usb / net / if_smsc.c
1 /*-
2  * Copyright (c) 2012
3  *      Ben Gray <bgray@freebsd.org>.
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  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29
30 /*
31  * SMSC LAN9xxx devices (http://www.smsc.com/)
32  * 
33  * The LAN9500 & LAN9500A devices are stand-alone USB to Ethernet chips that
34  * support USB 2.0 and 10/100 Mbps Ethernet.
35  *
36  * The LAN951x devices are an integrated USB hub and USB to Ethernet adapter.
37  * The driver only covers the Ethernet part, the standard USB hub driver
38  * supports the hub part.
39  *
40  * This driver is closely modelled on the Linux driver written and copyrighted
41  * by SMSC.
42  *
43  *
44  *
45  *
46  * H/W TCP & UDP Checksum Offloading
47  * ---------------------------------
48  * The chip supports both tx and rx offloading of UDP & TCP checksums, this
49  * feature can be dynamically enabled/disabled.  
50  *
51  * RX checksuming is performed across bytes after the IPv4 header to the end of
52  * the Ethernet frame, this means if the frame is padded with non-zero values
53  * the H/W checksum will be incorrect, however the rx code compensates for this.
54  *
55  * TX checksuming is more complicated, the device requires a special header to
56  * be prefixed onto the start of the frame which indicates the start and end
57  * positions of the UDP or TCP frame.  This requires the driver to manually
58  * go through the packet data and decode the headers prior to sending.
59  * On Linux they generally provide cues to the location of the csum and the
60  * area to calculate it over, on FreeBSD we seem to have to do it all ourselves,
61  * hence this is not as optimal and therefore h/w tX checksum is currently not
62  * implemented.
63  *
64  */
65 #include <sys/stdint.h>
66 #include <sys/stddef.h>
67 #include <sys/param.h>
68 #include <sys/queue.h>
69 #include <sys/types.h>
70 #include <sys/systm.h>
71 #include <sys/kernel.h>
72 #include <sys/bus.h>
73 #include <sys/module.h>
74 #include <sys/lock.h>
75 #include <sys/mutex.h>
76 #include <sys/condvar.h>
77 #include <sys/socket.h>
78 #include <sys/sysctl.h>
79 #include <sys/sx.h>
80 #include <sys/unistd.h>
81 #include <sys/callout.h>
82 #include <sys/malloc.h>
83 #include <sys/priv.h>
84 #include <sys/random.h>
85
86 #include <net/if.h>
87 #include <net/if_var.h>
88
89 #include <netinet/in.h>
90 #include <netinet/ip.h>
91
92 #include "opt_platform.h"
93
94 #ifdef FDT
95 #include <dev/fdt/fdt_common.h>
96 #include <dev/ofw/ofw_bus.h>
97 #include <dev/ofw/ofw_bus_subr.h>
98 #endif
99
100 #include <dev/usb/usb.h>
101 #include <dev/usb/usbdi.h>
102 #include <dev/usb/usbdi_util.h>
103 #include "usbdevs.h"
104
105 #define USB_DEBUG_VAR smsc_debug
106 #include <dev/usb/usb_debug.h>
107 #include <dev/usb/usb_process.h>
108
109 #include <dev/usb/net/usb_ethernet.h>
110
111 #include <dev/usb/net/if_smscreg.h>
112
113 #ifdef USB_DEBUG
114 static int smsc_debug = 0;
115
116 SYSCTL_NODE(_hw_usb, OID_AUTO, smsc, CTLFLAG_RW, 0, "USB smsc");
117 SYSCTL_INT(_hw_usb_smsc, OID_AUTO, debug, CTLFLAG_RWTUN, &smsc_debug, 0,
118     "Debug level");
119 #endif
120
121 /*
122  * Various supported device vendors/products.
123  */
124 static const struct usb_device_id smsc_devs[] = {
125 #define SMSC_DEV(p,i) { USB_VPI(USB_VENDOR_SMC2, USB_PRODUCT_SMC2_##p, i) }
126         SMSC_DEV(LAN89530_ETH, 0),
127         SMSC_DEV(LAN9500_ETH, 0),
128         SMSC_DEV(LAN9500_ETH_2, 0),
129         SMSC_DEV(LAN9500A_ETH, 0),
130         SMSC_DEV(LAN9500A_ETH_2, 0),
131         SMSC_DEV(LAN9505_ETH, 0),
132         SMSC_DEV(LAN9505A_ETH, 0),
133         SMSC_DEV(LAN9514_ETH, 0),
134         SMSC_DEV(LAN9514_ETH_2, 0),
135         SMSC_DEV(LAN9530_ETH, 0),
136         SMSC_DEV(LAN9730_ETH, 0),
137         SMSC_DEV(LAN9500_SAL10, 0),
138         SMSC_DEV(LAN9505_SAL10, 0),
139         SMSC_DEV(LAN9500A_SAL10, 0),
140         SMSC_DEV(LAN9505A_SAL10, 0),
141         SMSC_DEV(LAN9514_SAL10, 0),
142         SMSC_DEV(LAN9500A_HAL, 0),
143         SMSC_DEV(LAN9505A_HAL, 0),
144 #undef SMSC_DEV
145 };
146
147
148 #ifdef USB_DEBUG
149 #define smsc_dbg_printf(sc, fmt, args...) \
150         do { \
151                 if (smsc_debug > 0) \
152                         device_printf((sc)->sc_ue.ue_dev, "debug: " fmt, ##args); \
153         } while(0)
154 #else
155 #define smsc_dbg_printf(sc, fmt, args...) do { } while (0)
156 #endif
157
158 #define smsc_warn_printf(sc, fmt, args...) \
159         device_printf((sc)->sc_ue.ue_dev, "warning: " fmt, ##args)
160
161 #define smsc_err_printf(sc, fmt, args...) \
162         device_printf((sc)->sc_ue.ue_dev, "error: " fmt, ##args)
163         
164
165 #define ETHER_IS_ZERO(addr) \
166         (!(addr[0] | addr[1] | addr[2] | addr[3] | addr[4] | addr[5]))
167         
168 #define ETHER_IS_VALID(addr) \
169         (!ETHER_IS_MULTICAST(addr) && !ETHER_IS_ZERO(addr))
170         
171 static device_probe_t smsc_probe;
172 static device_attach_t smsc_attach;
173 static device_detach_t smsc_detach;
174
175 static usb_callback_t smsc_bulk_read_callback;
176 static usb_callback_t smsc_bulk_write_callback;
177
178 static miibus_readreg_t smsc_miibus_readreg;
179 static miibus_writereg_t smsc_miibus_writereg;
180 static miibus_statchg_t smsc_miibus_statchg;
181
182 #if __FreeBSD_version > 1000000
183 static int smsc_attach_post_sub(struct usb_ether *ue);
184 #endif
185 static uether_fn_t smsc_attach_post;
186 static uether_fn_t smsc_init;
187 static uether_fn_t smsc_stop;
188 static uether_fn_t smsc_start;
189 static uether_fn_t smsc_tick;
190 static uether_fn_t smsc_setmulti;
191 static uether_fn_t smsc_setpromisc;
192
193 static int      smsc_ifmedia_upd(struct ifnet *);
194 static void     smsc_ifmedia_sts(struct ifnet *, struct ifmediareq *);
195
196 static int smsc_chip_init(struct smsc_softc *sc);
197 static int smsc_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data);
198
199 static const struct usb_config smsc_config[SMSC_N_TRANSFER] = {
200
201         [SMSC_BULK_DT_WR] = {
202                 .type = UE_BULK,
203                 .endpoint = UE_ADDR_ANY,
204                 .direction = UE_DIR_OUT,
205                 .frames = 16,
206                 .bufsize = 16 * (MCLBYTES + 16),
207                 .flags = {.pipe_bof = 1,.force_short_xfer = 1,},
208                 .callback = smsc_bulk_write_callback,
209                 .timeout = 10000,       /* 10 seconds */
210         },
211
212         [SMSC_BULK_DT_RD] = {
213                 .type = UE_BULK,
214                 .endpoint = UE_ADDR_ANY,
215                 .direction = UE_DIR_IN,
216                 .bufsize = 20480,       /* bytes */
217                 .flags = {.pipe_bof = 1,.short_xfer_ok = 1,},
218                 .callback = smsc_bulk_read_callback,
219                 .timeout = 0,   /* no timeout */
220         },
221
222         /* The SMSC chip supports an interrupt endpoints, however they aren't
223          * needed as we poll on the MII status.
224          */
225 };
226
227 static const struct usb_ether_methods smsc_ue_methods = {
228         .ue_attach_post = smsc_attach_post,
229 #if __FreeBSD_version > 1000000
230         .ue_attach_post_sub = smsc_attach_post_sub,
231 #endif
232         .ue_start = smsc_start,
233         .ue_ioctl = smsc_ioctl,
234         .ue_init = smsc_init,
235         .ue_stop = smsc_stop,
236         .ue_tick = smsc_tick,
237         .ue_setmulti = smsc_setmulti,
238         .ue_setpromisc = smsc_setpromisc,
239         .ue_mii_upd = smsc_ifmedia_upd,
240         .ue_mii_sts = smsc_ifmedia_sts,
241 };
242
243 /**
244  *      smsc_read_reg - Reads a 32-bit register on the device
245  *      @sc: driver soft context
246  *      @off: offset of the register
247  *      @data: pointer a value that will be populated with the register value
248  *      
249  *      LOCKING:
250  *      The device lock must be held before calling this function.
251  *
252  *      RETURNS:
253  *      0 on success, a USB_ERR_?? error code on failure.
254  */
255 static int
256 smsc_read_reg(struct smsc_softc *sc, uint32_t off, uint32_t *data)
257 {
258         struct usb_device_request req;
259         uint32_t buf;
260         usb_error_t err;
261
262         SMSC_LOCK_ASSERT(sc, MA_OWNED);
263
264         req.bmRequestType = UT_READ_VENDOR_DEVICE;
265         req.bRequest = SMSC_UR_READ_REG;
266         USETW(req.wValue, 0);
267         USETW(req.wIndex, off);
268         USETW(req.wLength, 4);
269
270         err = uether_do_request(&sc->sc_ue, &req, &buf, 1000);
271         if (err != 0)
272                 smsc_warn_printf(sc, "Failed to read register 0x%0x\n", off);
273
274         *data = le32toh(buf);
275         
276         return (err);
277 }
278
279 /**
280  *      smsc_write_reg - Writes a 32-bit register on the device
281  *      @sc: driver soft context
282  *      @off: offset of the register
283  *      @data: the 32-bit value to write into the register
284  *      
285  *      LOCKING:
286  *      The device lock must be held before calling this function.
287  *
288  *      RETURNS:
289  *      0 on success, a USB_ERR_?? error code on failure.
290  */
291 static int
292 smsc_write_reg(struct smsc_softc *sc, uint32_t off, uint32_t data)
293 {
294         struct usb_device_request req;
295         uint32_t buf;
296         usb_error_t err;
297
298         SMSC_LOCK_ASSERT(sc, MA_OWNED);
299         
300         buf = htole32(data);
301
302         req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
303         req.bRequest = SMSC_UR_WRITE_REG;
304         USETW(req.wValue, 0);
305         USETW(req.wIndex, off);
306         USETW(req.wLength, 4);
307
308         err = uether_do_request(&sc->sc_ue, &req, &buf, 1000);
309         if (err != 0)
310                 smsc_warn_printf(sc, "Failed to write register 0x%0x\n", off);
311
312         return (err);
313 }
314
315 /**
316  *      smsc_wait_for_bits - Polls on a register value until bits are cleared
317  *      @sc: soft context
318  *      @reg: offset of the register
319  *      @bits: if the bits are clear the function returns
320  *
321  *      LOCKING:
322  *      The device lock must be held before calling this function.
323  *
324  *      RETURNS:
325  *      0 on success, or a USB_ERR_?? error code on failure.
326  */
327 static int
328 smsc_wait_for_bits(struct smsc_softc *sc, uint32_t reg, uint32_t bits)
329 {
330         usb_ticks_t start_ticks;
331         const usb_ticks_t max_ticks = USB_MS_TO_TICKS(1000);
332         uint32_t val;
333         int err;
334         
335         SMSC_LOCK_ASSERT(sc, MA_OWNED);
336
337         start_ticks = (usb_ticks_t)ticks;
338         do {
339                 if ((err = smsc_read_reg(sc, reg, &val)) != 0)
340                         return (err);
341                 if (!(val & bits))
342                         return (0);
343                 
344                 uether_pause(&sc->sc_ue, hz / 100);
345         } while (((usb_ticks_t)(ticks - start_ticks)) < max_ticks);
346
347         return (USB_ERR_TIMEOUT);
348 }
349
350 /**
351  *      smsc_eeprom_read - Reads the attached EEPROM
352  *      @sc: soft context
353  *      @off: the eeprom address offset
354  *      @buf: stores the bytes
355  *      @buflen: the number of bytes to read
356  *
357  *      Simply reads bytes from an attached eeprom.
358  *
359  *      LOCKING:
360  *      The function takes and releases the device lock if it is not already held.
361  *
362  *      RETURNS:
363  *      0 on success, or a USB_ERR_?? error code on failure.
364  */
365 static int
366 smsc_eeprom_read(struct smsc_softc *sc, uint16_t off, uint8_t *buf, uint16_t buflen)
367 {
368         usb_ticks_t start_ticks;
369         const usb_ticks_t max_ticks = USB_MS_TO_TICKS(1000);
370         int err;
371         int locked;
372         uint32_t val;
373         uint16_t i;
374
375         locked = mtx_owned(&sc->sc_mtx);
376         if (!locked)
377                 SMSC_LOCK(sc);
378
379         err = smsc_wait_for_bits(sc, SMSC_EEPROM_CMD, SMSC_EEPROM_CMD_BUSY);
380         if (err != 0) {
381                 smsc_warn_printf(sc, "eeprom busy, failed to read data\n");
382                 goto done;
383         }
384
385         /* start reading the bytes, one at a time */
386         for (i = 0; i < buflen; i++) {
387         
388                 val = SMSC_EEPROM_CMD_BUSY | (SMSC_EEPROM_CMD_ADDR_MASK & (off + i));
389                 if ((err = smsc_write_reg(sc, SMSC_EEPROM_CMD, val)) != 0)
390                         goto done;
391                 
392                 start_ticks = (usb_ticks_t)ticks;
393                 do {
394                         if ((err = smsc_read_reg(sc, SMSC_EEPROM_CMD, &val)) != 0)
395                                 goto done;
396                         if (!(val & SMSC_EEPROM_CMD_BUSY) || (val & SMSC_EEPROM_CMD_TIMEOUT))
397                                 break;
398
399                         uether_pause(&sc->sc_ue, hz / 100);
400                 } while (((usb_ticks_t)(ticks - start_ticks)) < max_ticks);
401
402                 if (val & (SMSC_EEPROM_CMD_BUSY | SMSC_EEPROM_CMD_TIMEOUT)) {
403                         smsc_warn_printf(sc, "eeprom command failed\n");
404                         err = USB_ERR_IOERROR;
405                         break;
406                 }
407                         
408                 if ((err = smsc_read_reg(sc, SMSC_EEPROM_DATA, &val)) != 0)
409                         goto done;
410
411                 buf[i] = (val & 0xff);
412         }
413         
414 done:
415         if (!locked)
416                 SMSC_UNLOCK(sc);
417
418         return (err);
419 }
420
421 /**
422  *      smsc_miibus_readreg - Reads a MII/MDIO register
423  *      @dev: usb ether device
424  *      @phy: the number of phy reading from
425  *      @reg: the register address
426  *
427  *      Attempts to read a phy register over the MII bus.
428  *
429  *      LOCKING:
430  *      Takes and releases the device mutex lock if not already held.
431  *
432  *      RETURNS:
433  *      Returns the 16-bits read from the MII register, if this function fails 0
434  *      is returned.
435  */
436 static int
437 smsc_miibus_readreg(device_t dev, int phy, int reg)
438 {
439         struct smsc_softc *sc = device_get_softc(dev);
440         int locked;
441         uint32_t addr;
442         uint32_t val = 0;
443
444         locked = mtx_owned(&sc->sc_mtx);
445         if (!locked)
446                 SMSC_LOCK(sc);
447
448         if (smsc_wait_for_bits(sc, SMSC_MII_ADDR, SMSC_MII_BUSY) != 0) {
449                 smsc_warn_printf(sc, "MII is busy\n");
450                 goto done;
451         }
452
453         addr = (phy << 11) | (reg << 6) | SMSC_MII_READ;
454         smsc_write_reg(sc, SMSC_MII_ADDR, addr);
455
456         if (smsc_wait_for_bits(sc, SMSC_MII_ADDR, SMSC_MII_BUSY) != 0)
457                 smsc_warn_printf(sc, "MII read timeout\n");
458
459         smsc_read_reg(sc, SMSC_MII_DATA, &val);
460         val = le32toh(val);
461         
462 done:
463         if (!locked)
464                 SMSC_UNLOCK(sc);
465
466         return (val & 0xFFFF);
467 }
468
469 /**
470  *      smsc_miibus_writereg - Writes a MII/MDIO register
471  *      @dev: usb ether device
472  *      @phy: the number of phy writing to
473  *      @reg: the register address
474  *      @val: the value to write
475  *
476  *      Attempts to write a phy register over the MII bus.
477  *
478  *      LOCKING:
479  *      Takes and releases the device mutex lock if not already held.
480  *
481  *      RETURNS:
482  *      Always returns 0 regardless of success or failure.
483  */
484 static int
485 smsc_miibus_writereg(device_t dev, int phy, int reg, int val)
486 {
487         struct smsc_softc *sc = device_get_softc(dev);
488         int locked;
489         uint32_t addr;
490
491         if (sc->sc_phyno != phy)
492                 return (0);
493
494         locked = mtx_owned(&sc->sc_mtx);
495         if (!locked)
496                 SMSC_LOCK(sc);
497
498         if (smsc_wait_for_bits(sc, SMSC_MII_ADDR, SMSC_MII_BUSY) != 0) {
499                 smsc_warn_printf(sc, "MII is busy\n");
500                 goto done;
501         }
502
503         val = htole32(val);
504         smsc_write_reg(sc, SMSC_MII_DATA, val);
505
506         addr = (phy << 11) | (reg << 6) | SMSC_MII_WRITE;
507         smsc_write_reg(sc, SMSC_MII_ADDR, addr);
508
509         if (smsc_wait_for_bits(sc, SMSC_MII_ADDR, SMSC_MII_BUSY) != 0)
510                 smsc_warn_printf(sc, "MII write timeout\n");
511
512 done:
513         if (!locked)
514                 SMSC_UNLOCK(sc);
515         return (0);
516 }
517
518
519
520 /**
521  *      smsc_miibus_statchg - Called to detect phy status change
522  *      @dev: usb ether device
523  *
524  *      This function is called periodically by the system to poll for status
525  *      changes of the link.
526  *
527  *      LOCKING:
528  *      Takes and releases the device mutex lock if not already held.
529  */
530 static void
531 smsc_miibus_statchg(device_t dev)
532 {
533         struct smsc_softc *sc = device_get_softc(dev);
534         struct mii_data *mii = uether_getmii(&sc->sc_ue);
535         struct ifnet *ifp;
536         int locked;
537         int err;
538         uint32_t flow;
539         uint32_t afc_cfg;
540
541         locked = mtx_owned(&sc->sc_mtx);
542         if (!locked)
543                 SMSC_LOCK(sc);
544
545         ifp = uether_getifp(&sc->sc_ue);
546         if (mii == NULL || ifp == NULL ||
547             (ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
548                 goto done;
549
550         /* Use the MII status to determine link status */
551         sc->sc_flags &= ~SMSC_FLAG_LINK;
552         if ((mii->mii_media_status & (IFM_ACTIVE | IFM_AVALID)) ==
553             (IFM_ACTIVE | IFM_AVALID)) {
554                 switch (IFM_SUBTYPE(mii->mii_media_active)) {
555                         case IFM_10_T:
556                         case IFM_100_TX:
557                                 sc->sc_flags |= SMSC_FLAG_LINK;
558                                 break;
559                         case IFM_1000_T:
560                                 /* Gigabit ethernet not supported by chipset */
561                                 break;
562                         default:
563                                 break;
564                 }
565         }
566
567         /* Lost link, do nothing. */
568         if ((sc->sc_flags & SMSC_FLAG_LINK) == 0) {
569                 smsc_dbg_printf(sc, "link flag not set\n");
570                 goto done;
571         }
572         
573         err = smsc_read_reg(sc, SMSC_AFC_CFG, &afc_cfg);
574         if (err) {
575                 smsc_warn_printf(sc, "failed to read initial AFC_CFG, error %d\n", err);
576                 goto done;
577         }
578         
579         /* Enable/disable full duplex operation and TX/RX pause */
580         if ((IFM_OPTIONS(mii->mii_media_active) & IFM_FDX) != 0) {
581                 smsc_dbg_printf(sc, "full duplex operation\n");
582                 sc->sc_mac_csr &= ~SMSC_MAC_CSR_RCVOWN;
583                 sc->sc_mac_csr |= SMSC_MAC_CSR_FDPX;
584
585                 if ((IFM_OPTIONS(mii->mii_media_active) & IFM_ETH_RXPAUSE) != 0)
586                         flow = 0xffff0002;
587                 else
588                         flow = 0;
589                         
590                 if ((IFM_OPTIONS(mii->mii_media_active) & IFM_ETH_TXPAUSE) != 0)
591                         afc_cfg |= 0xf;
592                 else
593                         afc_cfg &= ~0xf;
594                 
595         } else {
596                 smsc_dbg_printf(sc, "half duplex operation\n");
597                 sc->sc_mac_csr &= ~SMSC_MAC_CSR_FDPX;
598                 sc->sc_mac_csr |= SMSC_MAC_CSR_RCVOWN;
599                 
600                 flow = 0;
601                 afc_cfg |= 0xf;
602         }
603
604         err = smsc_write_reg(sc, SMSC_MAC_CSR, sc->sc_mac_csr);
605         err += smsc_write_reg(sc, SMSC_FLOW, flow);
606         err += smsc_write_reg(sc, SMSC_AFC_CFG, afc_cfg);
607         if (err)
608                 smsc_warn_printf(sc, "media change failed, error %d\n", err);
609         
610 done:
611         if (!locked)
612                 SMSC_UNLOCK(sc);
613 }
614
615 /**
616  *      smsc_ifmedia_upd - Set media options
617  *      @ifp: interface pointer
618  *
619  *      Basically boilerplate code that simply calls the mii functions to set the
620  *      media options.
621  *
622  *      LOCKING:
623  *      The device lock must be held before this function is called.
624  *
625  *      RETURNS:
626  *      Returns 0 on success or a negative error code.
627  */
628 static int
629 smsc_ifmedia_upd(struct ifnet *ifp)
630 {
631         struct smsc_softc *sc = ifp->if_softc;
632         struct mii_data *mii = uether_getmii(&sc->sc_ue);
633         struct mii_softc *miisc;
634         int err;
635
636         SMSC_LOCK_ASSERT(sc, MA_OWNED);
637
638         LIST_FOREACH(miisc, &mii->mii_phys, mii_list)
639                 PHY_RESET(miisc);
640         err = mii_mediachg(mii);
641         return (err);
642 }
643
644 /**
645  *      smsc_ifmedia_sts - Report current media status
646  *      @ifp: inet interface pointer
647  *      @ifmr: interface media request
648  *
649  *      Basically boilerplate code that simply calls the mii functions to get the
650  *      media status.
651  *
652  *      LOCKING:
653  *      Internally takes and releases the device lock.
654  */
655 static void
656 smsc_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
657 {
658         struct smsc_softc *sc = ifp->if_softc;
659         struct mii_data *mii = uether_getmii(&sc->sc_ue);
660
661         SMSC_LOCK(sc);
662         mii_pollstat(mii);
663         ifmr->ifm_active = mii->mii_media_active;
664         ifmr->ifm_status = mii->mii_media_status;
665         SMSC_UNLOCK(sc);
666 }
667
668 /**
669  *      smsc_hash - Calculate the hash of a mac address
670  *      @addr: The mac address to calculate the hash on
671  *
672  *      This function is used when configuring a range of m'cast mac addresses to
673  *      filter on.  The hash of the mac address is put in the device's mac hash
674  *      table.
675  *
676  *      RETURNS:
677  *      Returns a value from 0-63 value which is the hash of the mac address.
678  */
679 static inline uint32_t
680 smsc_hash(uint8_t addr[ETHER_ADDR_LEN])
681 {
682         return (ether_crc32_be(addr, ETHER_ADDR_LEN) >> 26) & 0x3f;
683 }
684
685 /**
686  *      smsc_setmulti - Setup multicast
687  *      @ue: usb ethernet device context
688  *
689  *      Tells the device to either accept frames with a multicast mac address, a
690  *      select group of m'cast mac addresses or just the devices mac address.
691  *
692  *      LOCKING:
693  *      Should be called with the SMSC lock held.
694  */
695 static void
696 smsc_setmulti(struct usb_ether *ue)
697 {
698         struct smsc_softc *sc = uether_getsc(ue);
699         struct ifnet *ifp = uether_getifp(ue);
700         struct ifmultiaddr *ifma;
701         uint32_t hashtbl[2] = { 0, 0 };
702         uint32_t hash;
703
704         SMSC_LOCK_ASSERT(sc, MA_OWNED);
705
706         if (ifp->if_flags & (IFF_ALLMULTI | IFF_PROMISC)) {
707                 smsc_dbg_printf(sc, "receive all multicast enabled\n");
708                 sc->sc_mac_csr |= SMSC_MAC_CSR_MCPAS;
709                 sc->sc_mac_csr &= ~SMSC_MAC_CSR_HPFILT;
710                 
711         } else {
712                 /* Take the lock of the mac address list before hashing each of them */
713                 if_maddr_rlock(ifp);
714
715                 if (!TAILQ_EMPTY(&ifp->if_multiaddrs)) {
716                         /* We are filtering on a set of address so calculate hashes of each
717                          * of the address and set the corresponding bits in the register.
718                          */
719                         sc->sc_mac_csr |= SMSC_MAC_CSR_HPFILT;
720                         sc->sc_mac_csr &= ~(SMSC_MAC_CSR_PRMS | SMSC_MAC_CSR_MCPAS);
721                 
722                         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
723                                 if (ifma->ifma_addr->sa_family != AF_LINK)
724                                         continue;
725
726                                 hash = smsc_hash(LLADDR((struct sockaddr_dl *)ifma->ifma_addr));
727                                 hashtbl[hash >> 5] |= 1 << (hash & 0x1F);
728                         }
729                 } else {
730                         /* Only receive packets with destination set to our mac address */
731                         sc->sc_mac_csr &= ~(SMSC_MAC_CSR_MCPAS | SMSC_MAC_CSR_HPFILT);
732                 }
733
734                 if_maddr_runlock(ifp);
735                 
736                 /* Debug */
737                 if (sc->sc_mac_csr & SMSC_MAC_CSR_HPFILT)
738                         smsc_dbg_printf(sc, "receive select group of macs\n");
739                 else
740                         smsc_dbg_printf(sc, "receive own packets only\n");
741         }
742
743         /* Write the hash table and mac control registers */
744         smsc_write_reg(sc, SMSC_HASHH, hashtbl[1]);
745         smsc_write_reg(sc, SMSC_HASHL, hashtbl[0]);
746         smsc_write_reg(sc, SMSC_MAC_CSR, sc->sc_mac_csr);
747 }
748
749
750 /**
751  *      smsc_setpromisc - Enables/disables promiscuous mode
752  *      @ue: usb ethernet device context
753  *
754  *      LOCKING:
755  *      Should be called with the SMSC lock held.
756  */
757 static void
758 smsc_setpromisc(struct usb_ether *ue)
759 {
760         struct smsc_softc *sc = uether_getsc(ue);
761         struct ifnet *ifp = uether_getifp(ue);
762
763         smsc_dbg_printf(sc, "promiscuous mode %sabled\n",
764                         (ifp->if_flags & IFF_PROMISC) ? "en" : "dis");
765
766         SMSC_LOCK_ASSERT(sc, MA_OWNED);
767
768         if (ifp->if_flags & IFF_PROMISC)
769                 sc->sc_mac_csr |= SMSC_MAC_CSR_PRMS;
770         else
771                 sc->sc_mac_csr &= ~SMSC_MAC_CSR_PRMS;
772
773         smsc_write_reg(sc, SMSC_MAC_CSR, sc->sc_mac_csr);
774 }
775
776
777 /**
778  *      smsc_sethwcsum - Enable or disable H/W UDP and TCP checksumming
779  *      @sc: driver soft context
780  *
781  *      LOCKING:
782  *      Should be called with the SMSC lock held.
783  *
784  *      RETURNS:
785  *      Returns 0 on success or a negative error code.
786  */
787 static int smsc_sethwcsum(struct smsc_softc *sc)
788 {
789         struct ifnet *ifp = uether_getifp(&sc->sc_ue);
790         uint32_t val;
791         int err;
792
793         if (!ifp)
794                 return (-EIO);
795
796         SMSC_LOCK_ASSERT(sc, MA_OWNED);
797
798         err = smsc_read_reg(sc, SMSC_COE_CTRL, &val);
799         if (err != 0) {
800                 smsc_warn_printf(sc, "failed to read SMSC_COE_CTRL (err=%d)\n", err);
801                 return (err);
802         }
803
804         /* Enable/disable the Rx checksum */
805         if ((ifp->if_capabilities & ifp->if_capenable) & IFCAP_RXCSUM)
806                 val |= SMSC_COE_CTRL_RX_EN;
807         else
808                 val &= ~SMSC_COE_CTRL_RX_EN;
809
810         /* Enable/disable the Tx checksum (currently not supported) */
811         if ((ifp->if_capabilities & ifp->if_capenable) & IFCAP_TXCSUM)
812                 val |= SMSC_COE_CTRL_TX_EN;
813         else
814                 val &= ~SMSC_COE_CTRL_TX_EN;
815
816         err = smsc_write_reg(sc, SMSC_COE_CTRL, val);
817         if (err != 0) {
818                 smsc_warn_printf(sc, "failed to write SMSC_COE_CTRL (err=%d)\n", err);
819                 return (err);
820         }
821
822         return (0);
823 }
824
825 /**
826  *      smsc_setmacaddress - Sets the mac address in the device
827  *      @sc: driver soft context
828  *      @addr: pointer to array contain at least 6 bytes of the mac
829  *
830  *      Writes the MAC address into the device, usually the MAC is programmed with
831  *      values from the EEPROM.
832  *
833  *      LOCKING:
834  *      Should be called with the SMSC lock held.
835  *
836  *      RETURNS:
837  *      Returns 0 on success or a negative error code.
838  */
839 static int
840 smsc_setmacaddress(struct smsc_softc *sc, const uint8_t *addr)
841 {
842         int err;
843         uint32_t val;
844
845         smsc_dbg_printf(sc, "setting mac address to %02x:%02x:%02x:%02x:%02x:%02x\n",
846                         addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
847
848         SMSC_LOCK_ASSERT(sc, MA_OWNED);
849
850         val = (addr[3] << 24) | (addr[2] << 16) | (addr[1] << 8) | addr[0];
851         if ((err = smsc_write_reg(sc, SMSC_MAC_ADDRL, val)) != 0)
852                 goto done;
853                 
854         val = (addr[5] << 8) | addr[4];
855         err = smsc_write_reg(sc, SMSC_MAC_ADDRH, val);
856         
857 done:
858         return (err);
859 }
860
861 /**
862  *      smsc_reset - Reset the SMSC chip
863  *      @sc: device soft context
864  *
865  *      LOCKING:
866  *      Should be called with the SMSC lock held.
867  */
868 static void
869 smsc_reset(struct smsc_softc *sc)
870 {
871         struct usb_config_descriptor *cd;
872         usb_error_t err;
873
874         cd = usbd_get_config_descriptor(sc->sc_ue.ue_udev);
875
876         err = usbd_req_set_config(sc->sc_ue.ue_udev, &sc->sc_mtx,
877                                   cd->bConfigurationValue);
878         if (err)
879                 smsc_warn_printf(sc, "reset failed (ignored)\n");
880
881         /* Wait a little while for the chip to get its brains in order. */
882         uether_pause(&sc->sc_ue, hz / 100);
883
884         /* Reinitialize controller to achieve full reset. */
885         smsc_chip_init(sc);
886 }
887
888
889 /**
890  *      smsc_init - Initialises the LAN95xx chip
891  *      @ue: USB ether interface
892  *
893  *      Called when the interface is brought up (i.e. ifconfig ue0 up), this
894  *      initialise the interface and the rx/tx pipes.
895  *
896  *      LOCKING:
897  *      Should be called with the SMSC lock held.
898  */
899 static void
900 smsc_init(struct usb_ether *ue)
901 {
902         struct smsc_softc *sc = uether_getsc(ue);
903         struct ifnet *ifp = uether_getifp(ue);
904
905         SMSC_LOCK_ASSERT(sc, MA_OWNED);
906
907         if (smsc_setmacaddress(sc, IF_LLADDR(ifp)))
908                 smsc_dbg_printf(sc, "setting MAC address failed\n");
909
910         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) != 0)
911                 return;
912
913         /* Cancel pending I/O */
914         smsc_stop(ue);
915
916 #if __FreeBSD_version <= 1000000
917         /* On earlier versions this was the first place we could tell the system
918          * that we supported h/w csuming, however this is only called after the
919          * the interface has been brought up - not ideal.  
920          */
921         if (!(ifp->if_capabilities & IFCAP_RXCSUM)) {
922                 ifp->if_capabilities |= IFCAP_RXCSUM;
923                 ifp->if_capenable |= IFCAP_RXCSUM;
924                 ifp->if_hwassist = 0;
925         }
926         
927         /* TX checksuming is disabled for now
928         ifp->if_capabilities |= IFCAP_TXCSUM;
929         ifp->if_capenable |= IFCAP_TXCSUM;
930         ifp->if_hwassist = CSUM_TCP | CSUM_UDP;
931         */
932 #endif
933
934         /* Reset the ethernet interface. */
935         smsc_reset(sc);
936
937         /* Load the multicast filter. */
938         smsc_setmulti(ue);
939
940         /* TCP/UDP checksum offload engines. */
941         smsc_sethwcsum(sc);
942
943         usbd_xfer_set_stall(sc->sc_xfer[SMSC_BULK_DT_WR]);
944
945         /* Indicate we are up and running. */
946         ifp->if_drv_flags |= IFF_DRV_RUNNING;
947
948         /* Switch to selected media. */
949         smsc_ifmedia_upd(ifp);
950         smsc_start(ue);
951 }
952
953 /**
954  *      smsc_bulk_read_callback - Read callback used to process the USB URB
955  *      @xfer: the USB transfer
956  *      @error: 
957  *
958  *      Reads the URB data which can contain one or more ethernet frames, the
959  *      frames are copyed into a mbuf and given to the system.
960  *
961  *      LOCKING:
962  *      No locking required, doesn't access internal driver settings.
963  */
964 static void
965 smsc_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error)
966 {
967         struct smsc_softc *sc = usbd_xfer_softc(xfer);
968         struct usb_ether *ue = &sc->sc_ue;
969         struct ifnet *ifp = uether_getifp(ue);
970         struct mbuf *m;
971         struct usb_page_cache *pc;
972         uint32_t rxhdr;
973         int pktlen;
974         int off;
975         int actlen;
976
977         usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
978         smsc_dbg_printf(sc, "rx : actlen %d\n", actlen);
979
980         switch (USB_GET_STATE(xfer)) {
981         case USB_ST_TRANSFERRED:
982         
983                 /* There is always a zero length frame after bringing the IF up */
984                 if (actlen < (sizeof(rxhdr) + ETHER_CRC_LEN))
985                         goto tr_setup;
986
987                 /* There maybe multiple packets in the USB frame, each will have a 
988                  * header and each needs to have it's own mbuf allocated and populated
989                  * for it.
990                  */
991                 pc = usbd_xfer_get_frame(xfer, 0);
992                 off = 0;
993                 
994                 while (off < actlen) {
995                 
996                         /* The frame header is always aligned on a 4 byte boundary */
997                         off = ((off + 0x3) & ~0x3);
998
999                         if ((off + sizeof(rxhdr)) > actlen)
1000                                 goto tr_setup;
1001
1002                         usbd_copy_out(pc, off, &rxhdr, sizeof(rxhdr));
1003                         off += (sizeof(rxhdr) + ETHER_ALIGN);
1004                         rxhdr = le32toh(rxhdr);
1005                 
1006                         pktlen = (uint16_t)SMSC_RX_STAT_FRM_LENGTH(rxhdr);
1007                         
1008                         smsc_dbg_printf(sc, "rx : rxhdr 0x%08x : pktlen %d : actlen %d : "
1009                                         "off %d\n", rxhdr, pktlen, actlen, off);
1010
1011                         
1012                         if (rxhdr & SMSC_RX_STAT_ERROR) {
1013                                 smsc_dbg_printf(sc, "rx error (hdr 0x%08x)\n", rxhdr);
1014                                 if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
1015                                 if (rxhdr & SMSC_RX_STAT_COLLISION)
1016                                         if_inc_counter(ifp, IFCOUNTER_COLLISIONS, 1);
1017                         } else {
1018
1019                                 /* Check if the ethernet frame is too big or too small */
1020                                 if ((pktlen < ETHER_HDR_LEN) || (pktlen > (actlen - off)))
1021                                         goto tr_setup;
1022                         
1023                                 /* Create a new mbuf to store the packet in */
1024                                 m = uether_newbuf();
1025                                 if (m == NULL) {
1026                                         smsc_warn_printf(sc, "failed to create new mbuf\n");
1027                                         if_inc_counter(ifp, IFCOUNTER_IQDROPS, 1);
1028                                         goto tr_setup;
1029                                 }
1030                                 if (pktlen > m->m_len) {
1031                                         smsc_dbg_printf(sc, "buffer too small %d vs %d bytes",
1032                                             pktlen, m->m_len);
1033                                         if_inc_counter(ifp, IFCOUNTER_IQDROPS, 1);
1034                                         m_freem(m);
1035                                         goto tr_setup;
1036                                 }
1037                                 usbd_copy_out(pc, off, mtod(m, uint8_t *), pktlen);
1038
1039                                 /* Check if RX TCP/UDP checksumming is being offloaded */
1040                                 if ((ifp->if_capenable & IFCAP_RXCSUM) != 0) {
1041
1042                                         struct ether_header *eh;
1043
1044                                         eh = mtod(m, struct ether_header *);
1045                                 
1046                                         /* Remove the extra 2 bytes of the csum */
1047                                         pktlen -= 2;
1048
1049                                         /* The checksum appears to be simplistically calculated
1050                                          * over the udp/tcp header and data up to the end of the
1051                                          * eth frame.  Which means if the eth frame is padded
1052                                          * the csum calculation is incorrectly performed over
1053                                          * the padding bytes as well. Therefore to be safe we
1054                                          * ignore the H/W csum on frames less than or equal to
1055                                          * 64 bytes.
1056                                          *
1057                                          * Ignore H/W csum for non-IPv4 packets.
1058                                          */
1059                                         if ((be16toh(eh->ether_type) == ETHERTYPE_IP) &&
1060                                             (pktlen > ETHER_MIN_LEN)) {
1061                                                 struct ip *ip;
1062
1063                                                 ip = (struct ip *)(eh + 1);
1064                                                 if ((ip->ip_v == IPVERSION) &&
1065                                                     ((ip->ip_p == IPPROTO_TCP) ||
1066                                                      (ip->ip_p == IPPROTO_UDP))) {
1067                                                         /* Indicate the UDP/TCP csum has been calculated */
1068                                                         m->m_pkthdr.csum_flags |= CSUM_DATA_VALID;
1069
1070                                                         /* Copy the TCP/UDP checksum from the last 2 bytes
1071                                                          * of the transfer and put in the csum_data field.
1072                                                          */
1073                                                         usbd_copy_out(pc, (off + pktlen),
1074                                                                       &m->m_pkthdr.csum_data, 2);
1075
1076                                                         /* The data is copied in network order, but the
1077                                                          * csum algorithm in the kernel expects it to be
1078                                                          * in host network order.
1079                                                          */
1080                                                         m->m_pkthdr.csum_data = ntohs(m->m_pkthdr.csum_data);
1081
1082                                                         smsc_dbg_printf(sc, "RX checksum offloaded (0x%04x)\n",
1083                                                                         m->m_pkthdr.csum_data);
1084                                                 }
1085                                         }
1086                                         
1087                                         /* Need to adjust the offset as well or we'll be off
1088                                          * by 2 because the csum is removed from the packet
1089                                          * length.
1090                                          */
1091                                         off += 2;
1092                                 }
1093                         
1094                                 /* Finally enqueue the mbuf on the receive queue */
1095                                 /* Remove 4 trailing bytes */
1096                                 if (pktlen < (4 + ETHER_HDR_LEN)) {
1097                                         m_freem(m);
1098                                         goto tr_setup;
1099                                 }
1100                                 uether_rxmbuf(ue, m, pktlen - 4);
1101                         }
1102
1103                         /* Update the offset to move to the next potential packet */
1104                         off += pktlen;
1105                 }
1106         
1107                 /* FALLTHROUGH */
1108                 
1109         case USB_ST_SETUP:
1110 tr_setup:
1111                 usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
1112                 usbd_transfer_submit(xfer);
1113                 uether_rxflush(ue);
1114                 return;
1115
1116         default:
1117                 if (error != USB_ERR_CANCELLED) {
1118                         smsc_warn_printf(sc, "bulk read error, %s\n", usbd_errstr(error));
1119                         usbd_xfer_set_stall(xfer);
1120                         goto tr_setup;
1121                 }
1122                 return;
1123         }
1124 }
1125
1126 /**
1127  *      smsc_bulk_write_callback - Write callback used to send ethernet frame(s)
1128  *      @xfer: the USB transfer
1129  *      @error: error code if the transfers is in an errored state
1130  *
1131  *      The main write function that pulls ethernet frames off the queue and sends
1132  *      them out.
1133  *
1134  *      LOCKING:
1135  *      
1136  */
1137 static void
1138 smsc_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error)
1139 {
1140         struct smsc_softc *sc = usbd_xfer_softc(xfer);
1141         struct ifnet *ifp = uether_getifp(&sc->sc_ue);
1142         struct usb_page_cache *pc;
1143         struct mbuf *m;
1144         uint32_t txhdr;
1145         uint32_t frm_len = 0;
1146         int nframes;
1147
1148         switch (USB_GET_STATE(xfer)) {
1149         case USB_ST_TRANSFERRED:
1150                 ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1151                 /* FALLTHROUGH */
1152
1153         case USB_ST_SETUP:
1154 tr_setup:
1155                 if ((sc->sc_flags & SMSC_FLAG_LINK) == 0 ||
1156                         (ifp->if_drv_flags & IFF_DRV_OACTIVE) != 0) {
1157                         /* Don't send anything if there is no link or controller is busy. */
1158                         return;
1159                 }
1160
1161                 for (nframes = 0; nframes < 16 &&
1162                     !IFQ_DRV_IS_EMPTY(&ifp->if_snd); nframes++) {
1163                         IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
1164                         if (m == NULL)
1165                                 break;
1166                         usbd_xfer_set_frame_offset(xfer, nframes * MCLBYTES,
1167                             nframes);
1168                         frm_len = 0;
1169                         pc = usbd_xfer_get_frame(xfer, nframes);
1170
1171                         /* Each frame is prefixed with two 32-bit values describing the
1172                          * length of the packet and buffer.
1173                          */
1174                         txhdr = SMSC_TX_CTRL_0_BUF_SIZE(m->m_pkthdr.len) | 
1175                                         SMSC_TX_CTRL_0_FIRST_SEG | SMSC_TX_CTRL_0_LAST_SEG;
1176                         txhdr = htole32(txhdr);
1177                         usbd_copy_in(pc, 0, &txhdr, sizeof(txhdr));
1178                         
1179                         txhdr = SMSC_TX_CTRL_1_PKT_LENGTH(m->m_pkthdr.len);
1180                         txhdr = htole32(txhdr);
1181                         usbd_copy_in(pc, 4, &txhdr, sizeof(txhdr));
1182                         
1183                         frm_len += 8;
1184
1185                         /* Next copy in the actual packet */
1186                         usbd_m_copy_in(pc, frm_len, m, 0, m->m_pkthdr.len);
1187                         frm_len += m->m_pkthdr.len;
1188
1189                         if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
1190
1191                         /* If there's a BPF listener, bounce a copy of this frame to him */
1192                         BPF_MTAP(ifp, m);
1193
1194                         m_freem(m);
1195
1196                         /* Set frame length. */
1197                         usbd_xfer_set_frame_len(xfer, nframes, frm_len);
1198                 }
1199                 if (nframes != 0) {
1200                         usbd_xfer_set_frames(xfer, nframes);
1201                         usbd_transfer_submit(xfer);
1202                         ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1203                 }
1204                 return;
1205
1206         default:
1207                 if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
1208                 ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1209                 
1210                 if (error != USB_ERR_CANCELLED) {
1211                         smsc_err_printf(sc, "usb error on tx: %s\n", usbd_errstr(error));
1212                         usbd_xfer_set_stall(xfer);
1213                         goto tr_setup;
1214                 }
1215                 return;
1216         }
1217 }
1218
1219 /**
1220  *      smsc_tick - Called periodically to monitor the state of the LAN95xx chip
1221  *      @ue: USB ether interface
1222  *
1223  *      Simply calls the mii status functions to check the state of the link.
1224  *
1225  *      LOCKING:
1226  *      Should be called with the SMSC lock held.
1227  */
1228 static void
1229 smsc_tick(struct usb_ether *ue)
1230 {
1231         struct smsc_softc *sc = uether_getsc(ue);
1232         struct mii_data *mii = uether_getmii(&sc->sc_ue);
1233
1234         SMSC_LOCK_ASSERT(sc, MA_OWNED);
1235
1236         mii_tick(mii);
1237         if ((sc->sc_flags & SMSC_FLAG_LINK) == 0) {
1238                 smsc_miibus_statchg(ue->ue_dev);
1239                 if ((sc->sc_flags & SMSC_FLAG_LINK) != 0)
1240                         smsc_start(ue);
1241         }
1242 }
1243
1244 /**
1245  *      smsc_start - Starts communication with the LAN95xx chip
1246  *      @ue: USB ether interface
1247  *
1248  *      
1249  *
1250  */
1251 static void
1252 smsc_start(struct usb_ether *ue)
1253 {
1254         struct smsc_softc *sc = uether_getsc(ue);
1255
1256         /*
1257          * start the USB transfers, if not already started:
1258          */
1259         usbd_transfer_start(sc->sc_xfer[SMSC_BULK_DT_RD]);
1260         usbd_transfer_start(sc->sc_xfer[SMSC_BULK_DT_WR]);
1261 }
1262
1263 /**
1264  *      smsc_stop - Stops communication with the LAN95xx chip
1265  *      @ue: USB ether interface
1266  *
1267  *      
1268  *
1269  */
1270 static void
1271 smsc_stop(struct usb_ether *ue)
1272 {
1273         struct smsc_softc *sc = uether_getsc(ue);
1274         struct ifnet *ifp = uether_getifp(ue);
1275
1276         SMSC_LOCK_ASSERT(sc, MA_OWNED);
1277
1278         ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
1279         sc->sc_flags &= ~SMSC_FLAG_LINK;
1280
1281         /*
1282          * stop all the transfers, if not already stopped:
1283          */
1284         usbd_transfer_stop(sc->sc_xfer[SMSC_BULK_DT_WR]);
1285         usbd_transfer_stop(sc->sc_xfer[SMSC_BULK_DT_RD]);
1286 }
1287
1288 /**
1289  *      smsc_phy_init - Initialises the in-built SMSC phy
1290  *      @sc: driver soft context
1291  *
1292  *      Resets the PHY part of the chip and then initialises it to default
1293  *      values.  The 'link down' and 'auto-negotiation complete' interrupts
1294  *      from the PHY are also enabled, however we don't monitor the interrupt
1295  *      endpoints for the moment.
1296  *
1297  *      RETURNS:
1298  *      Returns 0 on success or EIO if failed to reset the PHY.
1299  */
1300 static int
1301 smsc_phy_init(struct smsc_softc *sc)
1302 {
1303         int bmcr;
1304         usb_ticks_t start_ticks;
1305         const usb_ticks_t max_ticks = USB_MS_TO_TICKS(1000);
1306
1307         SMSC_LOCK_ASSERT(sc, MA_OWNED);
1308
1309         /* Reset phy and wait for reset to complete */
1310         smsc_miibus_writereg(sc->sc_ue.ue_dev, sc->sc_phyno, MII_BMCR, BMCR_RESET);
1311
1312         start_ticks = ticks;
1313         do {
1314                 uether_pause(&sc->sc_ue, hz / 100);
1315                 bmcr = smsc_miibus_readreg(sc->sc_ue.ue_dev, sc->sc_phyno, MII_BMCR);
1316         } while ((bmcr & MII_BMCR) && ((ticks - start_ticks) < max_ticks));
1317
1318         if (((usb_ticks_t)(ticks - start_ticks)) >= max_ticks) {
1319                 smsc_err_printf(sc, "PHY reset timed-out");
1320                 return (EIO);
1321         }
1322
1323         smsc_miibus_writereg(sc->sc_ue.ue_dev, sc->sc_phyno, MII_ANAR,
1324                              ANAR_10 | ANAR_10_FD | ANAR_TX | ANAR_TX_FD |  /* all modes */
1325                              ANAR_CSMA | 
1326                              ANAR_FC |
1327                              ANAR_PAUSE_ASYM);
1328
1329         /* Setup the phy to interrupt when the link goes down or autoneg completes */
1330         smsc_miibus_readreg(sc->sc_ue.ue_dev, sc->sc_phyno, SMSC_PHY_INTR_STAT);
1331         smsc_miibus_writereg(sc->sc_ue.ue_dev, sc->sc_phyno, SMSC_PHY_INTR_MASK,
1332                              (SMSC_PHY_INTR_ANEG_COMP | SMSC_PHY_INTR_LINK_DOWN));
1333         
1334         /* Restart auto-negotation */
1335         bmcr = smsc_miibus_readreg(sc->sc_ue.ue_dev, sc->sc_phyno, MII_BMCR);
1336         bmcr |= BMCR_STARTNEG;
1337         smsc_miibus_writereg(sc->sc_ue.ue_dev, sc->sc_phyno, MII_BMCR, bmcr);
1338         
1339         return (0);
1340 }
1341
1342
1343 /**
1344  *      smsc_chip_init - Initialises the chip after power on
1345  *      @sc: driver soft context
1346  *
1347  *      This initialisation sequence is modelled on the procedure in the Linux
1348  *      driver.
1349  *
1350  *      RETURNS:
1351  *      Returns 0 on success or an error code on failure.
1352  */
1353 static int
1354 smsc_chip_init(struct smsc_softc *sc)
1355 {
1356         int err;
1357         int locked;
1358         uint32_t reg_val;
1359         int burst_cap;
1360
1361         locked = mtx_owned(&sc->sc_mtx);
1362         if (!locked)
1363                 SMSC_LOCK(sc);
1364
1365         /* Enter H/W config mode */
1366         smsc_write_reg(sc, SMSC_HW_CFG, SMSC_HW_CFG_LRST);
1367
1368         if ((err = smsc_wait_for_bits(sc, SMSC_HW_CFG, SMSC_HW_CFG_LRST)) != 0) {
1369                 smsc_warn_printf(sc, "timed-out waiting for reset to complete\n");
1370                 goto init_failed;
1371         }
1372
1373         /* Reset the PHY */
1374         smsc_write_reg(sc, SMSC_PM_CTRL, SMSC_PM_CTRL_PHY_RST);
1375
1376         if ((err = smsc_wait_for_bits(sc, SMSC_PM_CTRL, SMSC_PM_CTRL_PHY_RST)) != 0) {
1377                 smsc_warn_printf(sc, "timed-out waiting for phy reset to complete\n");
1378                 goto init_failed;
1379         }
1380
1381         /* Set the mac address */
1382         if ((err = smsc_setmacaddress(sc, sc->sc_ue.ue_eaddr)) != 0) {
1383                 smsc_warn_printf(sc, "failed to set the MAC address\n");
1384                 goto init_failed;
1385         }
1386
1387         /* Don't know what the HW_CFG_BIR bit is, but following the reset sequence
1388          * as used in the Linux driver.
1389          */
1390         if ((err = smsc_read_reg(sc, SMSC_HW_CFG, &reg_val)) != 0) {
1391                 smsc_warn_printf(sc, "failed to read HW_CFG: %d\n", err);
1392                 goto init_failed;
1393         }
1394         reg_val |= SMSC_HW_CFG_BIR;
1395         smsc_write_reg(sc, SMSC_HW_CFG, reg_val);
1396
1397         /* There is a so called 'turbo mode' that the linux driver supports, it
1398          * seems to allow you to jam multiple frames per Rx transaction.  By default
1399          * this driver supports that and therefore allows multiple frames per URB.
1400          *
1401          * The xfer buffer size needs to reflect this as well, therefore based on
1402          * the calculations in the Linux driver the RX bufsize is set to 18944,
1403          *     bufsz = (16 * 1024 + 5 * 512)
1404          *
1405          * Burst capability is the number of URBs that can be in a burst of data/
1406          * ethernet frames.
1407          */
1408         if (usbd_get_speed(sc->sc_ue.ue_udev) == USB_SPEED_HIGH)
1409                 burst_cap = 37;
1410         else
1411                 burst_cap = 128;
1412
1413         smsc_write_reg(sc, SMSC_BURST_CAP, burst_cap);
1414
1415         /* Set the default bulk in delay (magic value from Linux driver) */
1416         smsc_write_reg(sc, SMSC_BULK_IN_DLY, 0x00002000);
1417
1418
1419
1420         /*
1421          * Initialise the RX interface
1422          */
1423         if ((err = smsc_read_reg(sc, SMSC_HW_CFG, &reg_val)) < 0) {
1424                 smsc_warn_printf(sc, "failed to read HW_CFG: (err = %d)\n", err);
1425                 goto init_failed;
1426         }
1427
1428         /* Adjust the packet offset in the buffer (designed to try and align IP
1429          * header on 4 byte boundary)
1430          */
1431         reg_val &= ~SMSC_HW_CFG_RXDOFF;
1432         reg_val |= (ETHER_ALIGN << 9) & SMSC_HW_CFG_RXDOFF;
1433         
1434         /* The following setings are used for 'turbo mode', a.k.a multiple frames
1435          * per Rx transaction (again info taken form Linux driver).
1436          */
1437         reg_val |= (SMSC_HW_CFG_MEF | SMSC_HW_CFG_BCE);
1438
1439         smsc_write_reg(sc, SMSC_HW_CFG, reg_val);
1440
1441         /* Clear the status register ? */
1442         smsc_write_reg(sc, SMSC_INTR_STATUS, 0xffffffff);
1443
1444         /* Read and display the revision register */
1445         if ((err = smsc_read_reg(sc, SMSC_ID_REV, &sc->sc_rev_id)) < 0) {
1446                 smsc_warn_printf(sc, "failed to read ID_REV (err = %d)\n", err);
1447                 goto init_failed;
1448         }
1449
1450         device_printf(sc->sc_ue.ue_dev, "chip 0x%04lx, rev. %04lx\n", 
1451             (sc->sc_rev_id & SMSC_ID_REV_CHIP_ID_MASK) >> 16, 
1452             (sc->sc_rev_id & SMSC_ID_REV_CHIP_REV_MASK));
1453
1454         /* GPIO/LED setup */
1455         reg_val = SMSC_LED_GPIO_CFG_SPD_LED | SMSC_LED_GPIO_CFG_LNK_LED | 
1456                   SMSC_LED_GPIO_CFG_FDX_LED;
1457         smsc_write_reg(sc, SMSC_LED_GPIO_CFG, reg_val);
1458
1459         /*
1460          * Initialise the TX interface
1461          */
1462         smsc_write_reg(sc, SMSC_FLOW, 0);
1463
1464         smsc_write_reg(sc, SMSC_AFC_CFG, AFC_CFG_DEFAULT);
1465
1466         /* Read the current MAC configuration */
1467         if ((err = smsc_read_reg(sc, SMSC_MAC_CSR, &sc->sc_mac_csr)) < 0) {
1468                 smsc_warn_printf(sc, "failed to read MAC_CSR (err=%d)\n", err);
1469                 goto init_failed;
1470         }
1471         
1472         /* Vlan */
1473         smsc_write_reg(sc, SMSC_VLAN1, (uint32_t)ETHERTYPE_VLAN);
1474
1475         /*
1476          * Initialise the PHY
1477          */
1478         if ((err = smsc_phy_init(sc)) != 0)
1479                 goto init_failed;
1480
1481
1482         /*
1483          * Start TX
1484          */
1485         sc->sc_mac_csr |= SMSC_MAC_CSR_TXEN;
1486         smsc_write_reg(sc, SMSC_MAC_CSR, sc->sc_mac_csr);
1487         smsc_write_reg(sc, SMSC_TX_CFG, SMSC_TX_CFG_ON);
1488
1489         /*
1490          * Start RX
1491          */
1492         sc->sc_mac_csr |= SMSC_MAC_CSR_RXEN;
1493         smsc_write_reg(sc, SMSC_MAC_CSR, sc->sc_mac_csr);
1494
1495         if (!locked)
1496                 SMSC_UNLOCK(sc);
1497
1498         return (0);
1499         
1500 init_failed:
1501         if (!locked)
1502                 SMSC_UNLOCK(sc);
1503
1504         smsc_err_printf(sc, "smsc_chip_init failed (err=%d)\n", err);
1505         return (err);
1506 }
1507
1508
1509 /**
1510  *      smsc_ioctl - ioctl function for the device
1511  *      @ifp: interface pointer
1512  *      @cmd: the ioctl command
1513  *      @data: data passed in the ioctl call, typically a pointer to struct ifreq.
1514  *      
1515  *      The ioctl routine is overridden to detect change requests for the H/W
1516  *      checksum capabilities.
1517  *
1518  *      RETURNS:
1519  *      0 on success and an error code on failure.
1520  */
1521 static int
1522 smsc_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1523 {
1524         struct usb_ether *ue = ifp->if_softc;
1525         struct smsc_softc *sc;
1526         struct ifreq *ifr;
1527         int rc;
1528         int mask;
1529         int reinit;
1530         
1531         if (cmd == SIOCSIFCAP) {
1532
1533                 sc = uether_getsc(ue);
1534                 ifr = (struct ifreq *)data;
1535
1536                 SMSC_LOCK(sc);
1537
1538                 rc = 0;
1539                 reinit = 0;
1540
1541                 mask = ifr->ifr_reqcap ^ ifp->if_capenable;
1542
1543                 /* Modify the RX CSUM enable bits */
1544                 if ((mask & IFCAP_RXCSUM) != 0 &&
1545                     (ifp->if_capabilities & IFCAP_RXCSUM) != 0) {
1546                         ifp->if_capenable ^= IFCAP_RXCSUM;
1547                         
1548                         if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1549                                 ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1550                                 reinit = 1;
1551                         }
1552                 }
1553                 
1554                 SMSC_UNLOCK(sc);
1555                 if (reinit)
1556 #if __FreeBSD_version > 1000000
1557                         uether_init(ue);
1558 #else
1559                         ifp->if_init(ue);
1560 #endif
1561
1562         } else {
1563                 rc = uether_ioctl(ifp, cmd, data);
1564         }
1565
1566         return (rc);
1567 }
1568
1569 #ifdef FDT
1570 /*
1571  * This is FreeBSD-specific compatibility strings for RPi/RPi2
1572  */
1573 static phandle_t
1574 smsc_fdt_find_eth_node(phandle_t start)
1575 {
1576         phandle_t child, node;
1577
1578         /* Traverse through entire tree to find usb ethernet nodes. */
1579         for (node = OF_child(start); node != 0; node = OF_peer(node)) {
1580                 if ((ofw_bus_node_is_compatible(node, "net,ethernet") &&
1581                     ofw_bus_node_is_compatible(node, "usb,device")) ||
1582                     ofw_bus_node_is_compatible(node, "usb424,ec00"))
1583                         return (node);
1584                 child = smsc_fdt_find_eth_node(node);
1585                 if (child != -1)
1586                         return (child);
1587         }
1588
1589         return (-1);
1590 }
1591
1592 /*
1593  * Check if node's path is <*>/usb/hub/ethernet
1594  */
1595 static int
1596 smsc_fdt_is_usb_eth(phandle_t node)
1597 {
1598         char name[16];
1599         int len;
1600
1601         memset(name, 0, sizeof(name));
1602         len = OF_getprop(node, "name", name, sizeof(name));
1603         if (len <= 0)
1604                 return (0);
1605
1606         if (strcmp(name, "ethernet"))
1607                 return (0);
1608
1609         node = OF_parent(node);
1610         if (node == -1)
1611                 return (0);
1612         len = OF_getprop(node, "name", name, sizeof(name));
1613         if (len <= 0)
1614                 return (0);
1615
1616         if (strcmp(name, "hub"))
1617                 return (0);
1618
1619         node = OF_parent(node);
1620         if (node == -1)
1621                 return (0);
1622         len = OF_getprop(node, "name", name, sizeof(name));
1623         if (len <= 0)
1624                 return (0);
1625
1626         if (strcmp(name, "usb"))
1627                 return (0);
1628
1629         return (1);
1630 }
1631
1632 static phandle_t
1633 smsc_fdt_find_eth_node_by_path(phandle_t start)
1634 {
1635         phandle_t child, node;
1636
1637         /* Traverse through entire tree to find usb ethernet nodes. */
1638         for (node = OF_child(start); node != 0; node = OF_peer(node)) {
1639                 if (smsc_fdt_is_usb_eth(node))
1640                         return (node);
1641                 child = smsc_fdt_find_eth_node_by_path(node);
1642                 if (child != -1)
1643                         return (child);
1644         }
1645
1646         return (-1);
1647 }
1648
1649 /*
1650  * Look through known names that can contain mac address
1651  * return 0 if valid MAC address has been found
1652  */
1653 static int
1654 smsc_fdt_read_mac_property(phandle_t node, unsigned char *mac)
1655 {
1656         int len;
1657
1658         /* Check if there is property */
1659         if ((len = OF_getproplen(node, "local-mac-address")) > 0) {
1660                 if (len != ETHER_ADDR_LEN)
1661                         return (EINVAL);
1662
1663                 OF_getprop(node, "local-mac-address", mac,
1664                     ETHER_ADDR_LEN);
1665                 return (0);
1666         }
1667
1668         if ((len = OF_getproplen(node, "mac-address")) > 0) {
1669                 if (len != ETHER_ADDR_LEN)
1670                         return (EINVAL);
1671
1672                 OF_getprop(node, "mac-address", mac,
1673                     ETHER_ADDR_LEN);
1674                 return (0);
1675         }
1676
1677         return (ENXIO);
1678 }
1679
1680 /**
1681  * Get MAC address from FDT blob.  Firmware or loader should fill
1682  * mac-address or local-mac-address property.  Returns 0 if MAC address
1683  * obtained, error code otherwise.
1684  */
1685 static int
1686 smsc_fdt_find_mac(unsigned char *mac)
1687 {
1688         phandle_t node, root;
1689
1690         root = OF_finddevice("/");
1691         node = smsc_fdt_find_eth_node(root);
1692         if (node != -1) {
1693                 if (smsc_fdt_read_mac_property(node, mac) == 0)
1694                         return (0);
1695         }
1696
1697         /*
1698          * If it's not FreeBSD FDT blob for RPi, try more
1699          *     generic .../usb/hub/ethernet
1700          */
1701         node = smsc_fdt_find_eth_node_by_path(root);
1702
1703         if (node != -1)
1704                 return smsc_fdt_read_mac_property(node, mac);
1705
1706         return (ENXIO);
1707 }
1708 #endif
1709
1710 /**
1711  *      smsc_attach_post - Called after the driver attached to the USB interface
1712  *      @ue: the USB ethernet device
1713  *
1714  *      This is where the chip is intialised for the first time.  This is different
1715  *      from the smsc_init() function in that that one is designed to setup the
1716  *      H/W to match the UE settings and can be called after a reset.
1717  *
1718  *
1719  */
1720 static void
1721 smsc_attach_post(struct usb_ether *ue)
1722 {
1723         struct smsc_softc *sc = uether_getsc(ue);
1724         uint32_t mac_h, mac_l;
1725         int err;
1726
1727         smsc_dbg_printf(sc, "smsc_attach_post\n");
1728
1729         /* Setup some of the basics */
1730         sc->sc_phyno = 1;
1731
1732
1733         /* Attempt to get the mac address, if an EEPROM is not attached this
1734          * will just return FF:FF:FF:FF:FF:FF, so in such cases we invent a MAC
1735          * address based on urandom.
1736          */
1737         memset(sc->sc_ue.ue_eaddr, 0xff, ETHER_ADDR_LEN);
1738         
1739         /* Check if there is already a MAC address in the register */
1740         if ((smsc_read_reg(sc, SMSC_MAC_ADDRL, &mac_l) == 0) &&
1741             (smsc_read_reg(sc, SMSC_MAC_ADDRH, &mac_h) == 0)) {
1742                 sc->sc_ue.ue_eaddr[5] = (uint8_t)((mac_h >> 8) & 0xff);
1743                 sc->sc_ue.ue_eaddr[4] = (uint8_t)((mac_h) & 0xff);
1744                 sc->sc_ue.ue_eaddr[3] = (uint8_t)((mac_l >> 24) & 0xff);
1745                 sc->sc_ue.ue_eaddr[2] = (uint8_t)((mac_l >> 16) & 0xff);
1746                 sc->sc_ue.ue_eaddr[1] = (uint8_t)((mac_l >> 8) & 0xff);
1747                 sc->sc_ue.ue_eaddr[0] = (uint8_t)((mac_l) & 0xff);
1748         }
1749         
1750         /* MAC address is not set so try to read from EEPROM, if that fails generate
1751          * a random MAC address.
1752          */
1753         if (!ETHER_IS_VALID(sc->sc_ue.ue_eaddr)) {
1754
1755                 err = smsc_eeprom_read(sc, 0x01, sc->sc_ue.ue_eaddr, ETHER_ADDR_LEN);
1756 #ifdef FDT
1757                 if ((err != 0) || (!ETHER_IS_VALID(sc->sc_ue.ue_eaddr)))
1758                         err = smsc_fdt_find_mac(sc->sc_ue.ue_eaddr);
1759 #endif
1760                 if ((err != 0) || (!ETHER_IS_VALID(sc->sc_ue.ue_eaddr))) {
1761                         read_random(sc->sc_ue.ue_eaddr, ETHER_ADDR_LEN);
1762                         sc->sc_ue.ue_eaddr[0] &= ~0x01;     /* unicast */
1763                         sc->sc_ue.ue_eaddr[0] |=  0x02;     /* locally administered */
1764                 }
1765         }
1766         
1767         /* Initialise the chip for the first time */
1768         smsc_chip_init(sc);
1769 }
1770
1771
1772 /**
1773  *      smsc_attach_post_sub - Called after the driver attached to the USB interface
1774  *      @ue: the USB ethernet device
1775  *
1776  *      Most of this is boilerplate code and copied from the base USB ethernet
1777  *      driver.  It has been overriden so that we can indicate to the system that
1778  *      the chip supports H/W checksumming.
1779  *
1780  *      RETURNS:
1781  *      Returns 0 on success or a negative error code.
1782  */
1783 #if __FreeBSD_version > 1000000
1784 static int
1785 smsc_attach_post_sub(struct usb_ether *ue)
1786 {
1787         struct smsc_softc *sc;
1788         struct ifnet *ifp;
1789         int error;
1790
1791         sc = uether_getsc(ue);
1792         ifp = ue->ue_ifp;
1793         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
1794         ifp->if_start = uether_start;
1795         ifp->if_ioctl = smsc_ioctl;
1796         ifp->if_init = uether_init;
1797         IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
1798         ifp->if_snd.ifq_drv_maxlen = ifqmaxlen;
1799         IFQ_SET_READY(&ifp->if_snd);
1800
1801         /* The chip supports TCP/UDP checksum offloading on TX and RX paths, however
1802          * currently only RX checksum is supported in the driver (see top of file).
1803          */
1804         ifp->if_capabilities |= IFCAP_RXCSUM | IFCAP_VLAN_MTU;
1805         ifp->if_hwassist = 0;
1806         
1807         /* TX checksuming is disabled (for now?)
1808         ifp->if_capabilities |= IFCAP_TXCSUM;
1809         ifp->if_capenable |= IFCAP_TXCSUM;
1810         ifp->if_hwassist = CSUM_TCP | CSUM_UDP;
1811         */
1812
1813         ifp->if_capenable = ifp->if_capabilities;
1814
1815         mtx_lock(&Giant);
1816         error = mii_attach(ue->ue_dev, &ue->ue_miibus, ifp,
1817             uether_ifmedia_upd, ue->ue_methods->ue_mii_sts,
1818             BMSR_DEFCAPMASK, sc->sc_phyno, MII_OFFSET_ANY, 0);
1819         mtx_unlock(&Giant);
1820
1821         return (error);
1822 }
1823 #endif /* __FreeBSD_version > 1000000 */
1824
1825
1826 /**
1827  *      smsc_probe - Probe the interface. 
1828  *      @dev: smsc device handle
1829  *
1830  *      Checks if the device is a match for this driver.
1831  *
1832  *      RETURNS:
1833  *      Returns 0 on success or an error code on failure.
1834  */
1835 static int
1836 smsc_probe(device_t dev)
1837 {
1838         struct usb_attach_arg *uaa = device_get_ivars(dev);
1839
1840         if (uaa->usb_mode != USB_MODE_HOST)
1841                 return (ENXIO);
1842         if (uaa->info.bConfigIndex != SMSC_CONFIG_INDEX)
1843                 return (ENXIO);
1844         if (uaa->info.bIfaceIndex != SMSC_IFACE_IDX)
1845                 return (ENXIO);
1846
1847         return (usbd_lookup_id_by_uaa(smsc_devs, sizeof(smsc_devs), uaa));
1848 }
1849
1850
1851 /**
1852  *      smsc_attach - Attach the interface. 
1853  *      @dev: smsc device handle
1854  *
1855  *      Allocate softc structures, do ifmedia setup and ethernet/BPF attach.
1856  *
1857  *      RETURNS:
1858  *      Returns 0 on success or a negative error code.
1859  */
1860 static int
1861 smsc_attach(device_t dev)
1862 {
1863         struct usb_attach_arg *uaa = device_get_ivars(dev);
1864         struct smsc_softc *sc = device_get_softc(dev);
1865         struct usb_ether *ue = &sc->sc_ue;
1866         uint8_t iface_index;
1867         int err;
1868
1869         sc->sc_flags = USB_GET_DRIVER_INFO(uaa);
1870
1871         device_set_usb_desc(dev);
1872
1873         mtx_init(&sc->sc_mtx, device_get_nameunit(dev), NULL, MTX_DEF);
1874
1875         /* Setup the endpoints for the SMSC LAN95xx device(s) */
1876         iface_index = SMSC_IFACE_IDX;
1877         err = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer,
1878                                   smsc_config, SMSC_N_TRANSFER, sc, &sc->sc_mtx);
1879         if (err) {
1880                 device_printf(dev, "error: allocating USB transfers failed\n");
1881                 goto detach;
1882         }
1883
1884         ue->ue_sc = sc;
1885         ue->ue_dev = dev;
1886         ue->ue_udev = uaa->device;
1887         ue->ue_mtx = &sc->sc_mtx;
1888         ue->ue_methods = &smsc_ue_methods;
1889
1890         err = uether_ifattach(ue);
1891         if (err) {
1892                 device_printf(dev, "error: could not attach interface\n");
1893                 goto detach;
1894         }
1895         return (0);                     /* success */
1896
1897 detach:
1898         smsc_detach(dev);
1899         return (ENXIO);         /* failure */
1900 }
1901
1902 /**
1903  *      smsc_detach - Detach the interface. 
1904  *      @dev: smsc device handle
1905  *
1906  *      RETURNS:
1907  *      Returns 0.
1908  */
1909 static int
1910 smsc_detach(device_t dev)
1911 {
1912         struct smsc_softc *sc = device_get_softc(dev);
1913         struct usb_ether *ue = &sc->sc_ue;
1914
1915         usbd_transfer_unsetup(sc->sc_xfer, SMSC_N_TRANSFER);
1916         uether_ifdetach(ue);
1917         mtx_destroy(&sc->sc_mtx);
1918
1919         return (0);
1920 }
1921
1922 static device_method_t smsc_methods[] = {
1923         /* Device interface */
1924         DEVMETHOD(device_probe, smsc_probe),
1925         DEVMETHOD(device_attach, smsc_attach),
1926         DEVMETHOD(device_detach, smsc_detach),
1927
1928         /* bus interface */
1929         DEVMETHOD(bus_print_child, bus_generic_print_child),
1930         DEVMETHOD(bus_driver_added, bus_generic_driver_added),
1931
1932         /* MII interface */
1933         DEVMETHOD(miibus_readreg, smsc_miibus_readreg),
1934         DEVMETHOD(miibus_writereg, smsc_miibus_writereg),
1935         DEVMETHOD(miibus_statchg, smsc_miibus_statchg),
1936
1937         DEVMETHOD_END
1938 };
1939
1940 static driver_t smsc_driver = {
1941         .name = "smsc",
1942         .methods = smsc_methods,
1943         .size = sizeof(struct smsc_softc),
1944 };
1945
1946 static devclass_t smsc_devclass;
1947
1948 DRIVER_MODULE(smsc, uhub, smsc_driver, smsc_devclass, NULL, 0);
1949 DRIVER_MODULE(miibus, smsc, miibus_driver, miibus_devclass, 0, 0);
1950 MODULE_DEPEND(smsc, uether, 1, 1, 1);
1951 MODULE_DEPEND(smsc, usb, 1, 1, 1);
1952 MODULE_DEPEND(smsc, ether, 1, 1, 1);
1953 MODULE_DEPEND(smsc, miibus, 1, 1, 1);
1954 MODULE_VERSION(smsc, 1);
1955 USB_PNP_HOST_INFO(smsc_devs);