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