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