]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/usb/net/if_muge.c
Add driver for Microchip LAN78xx USB3-GigE controller
[FreeBSD/FreeBSD.git] / sys / dev / usb / net / if_muge.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (C) 2012 Ben Gray <bgray@freebsd.org>.
5  * Copyright (C) 2018 The FreeBSD Foundation.
6  *
7  * This software was developed by Arshan Khanifar <arshankhanifar@gmail.com>
8  * under sponsorship from the FreeBSD Foundation.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  * $FreeBSD$
32  */
33
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36
37 /*
38  * USB-To-Ethernet adapter driver for Microchip's LAN78XX and related families.
39  *
40  * USB 3.1 to 10/100/1000 Mbps Ethernet
41  * LAN7800 http://www.microchip.com/wwwproducts/en/LAN7800
42  *
43  * USB 2 to 10/100/1000 Mbps Ethernet with built-in USB hub
44  * LAN7515 (no datasheet available, but probes and functions as LAN7800)
45  *
46  * This driver is based on the if_smsc driver, with lan78xx-specific
47  * functionality modelled on Microchip's Linux lan78xx driver.
48  *
49  * UNIMPLEMENTED FEATURES
50  * ------------------
51  * A number of features supported by the lan78xx are not yet implemented in
52  * this driver:
53  *
54  * 1. RX/TX checksum offloading: Nothing has been implemented yet for
55  *    TX checksumming. RX checksumming works with ICMP messages, but is broken
56  *    for TCP/UDP packets.
57  * 2. Direct address translation filtering: Implemented but untested.
58  * 3. VLAN tag removal.
59  * 4. Reading MAC address from the device tree: Specific to the RPi 3B+.
60  *    Currently, the driver assigns a random MAC address itself.
61  * 5. Support for USB interrupt endpoints.
62  * 6. Latency Tolerance Messaging (LTM) support.
63  * 7. TCP LSO support.
64  *
65  */
66
67 #include <sys/param.h>
68 #include <sys/bus.h>
69 #include <sys/callout.h>
70 #include <sys/condvar.h>
71 #include <sys/kernel.h>
72 #include <sys/lock.h>
73 #include <sys/malloc.h>
74 #include <sys/module.h>
75 #include <sys/mutex.h>
76 #include <sys/priv.h>
77 #include <sys/queue.h>
78 #include <sys/random.h>
79 #include <sys/socket.h>
80 #include <sys/stddef.h>
81 #include <sys/stdint.h>
82 #include <sys/sx.h>
83 #include <sys/sysctl.h>
84 #include <sys/systm.h>
85 #include <sys/unistd.h>
86
87 #include <net/if.h>
88 #include <net/if_var.h>
89
90 #include <netinet/in.h>
91 #include <netinet/ip.h>
92
93 #include "opt_platform.h"
94
95 #include <dev/usb/usb.h>
96 #include <dev/usb/usbdi.h>
97 #include <dev/usb/usbdi_util.h>
98 #include "usbdevs.h"
99
100 #define USB_DEBUG_VAR lan78xx_debug
101 #include <dev/usb/usb_debug.h>
102 #include <dev/usb/usb_process.h>
103
104 #include <dev/usb/net/usb_ethernet.h>
105
106 #include <dev/usb/net/if_mugereg.h>
107
108 #ifdef USB_DEBUG
109 static int muge_debug = 0;
110
111 SYSCTL_NODE(_hw_usb, OID_AUTO, muge, CTLFLAG_RW, 0,
112     "Microchip LAN78xx USB-GigE");
113 SYSCTL_INT(_hw_usb_muge, OID_AUTO, debug, CTLFLAG_RWTUN, &muge_debug, 0,
114     "Debug level");
115 #endif
116
117 #define MUGE_DEFAULT_RX_CSUM_ENABLE (false)
118 #define MUGE_DEFAULT_TX_CSUM_ENABLE (false)
119 #define MUGE_DEFAULT_TSO_CSUM_ENABLE (false)
120
121 /* Supported Vendor and Product IDs. */
122 static const struct usb_device_id lan78xx_devs[] = {
123 #define MUGE_DEV(p,i) { USB_VPI(USB_VENDOR_SMC2, USB_PRODUCT_SMC2_##p, i) }
124         MUGE_DEV(LAN7800_ETH, 0),
125 #undef MUGE_DEV
126 };
127
128 #ifdef USB_DEBUG
129 #define lan78xx_dbg_printf(sc, fmt, args...) \
130 do { \
131         if (muge_debug > 0) \
132                 device_printf((sc)->sc_ue.ue_dev, "debug: " fmt, ##args); \
133 } while(0)
134 #else
135 #define muge_dbg_printf(sc, fmt, args...) do { } while (0)
136 #endif
137
138 #define muge_warn_printf(sc, fmt, args...) \
139         device_printf((sc)->sc_ue.ue_dev, "warning: " fmt, ##args)
140
141 #define muge_err_printf(sc, fmt, args...) \
142         device_printf((sc)->sc_ue.ue_dev, "error: " fmt, ##args)
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 /* USB endpoints. */
151
152 enum {
153         MUGE_BULK_DT_RD,
154         MUGE_BULK_DT_WR,
155         /*
156          * the device does support interrupt endpoints,
157          * but they're not needed as we poll on MII status.
158          * MUGE_INTR_DT_WR,
159          * MUGE_INTR_DT_RD,
160          */
161         MUGE_N_TRANSFER,
162 };
163
164 struct muge_softc {
165         struct usb_ether        sc_ue;
166         struct mtx              sc_mtx;
167         struct usb_xfer  *sc_xfer[MUGE_N_TRANSFER];
168         int                     sc_phyno;
169
170         /* Settings for the mac control (MAC_CSR) register. */
171         uint32_t                sc_rfe_ctl;
172         uint32_t                sc_mdix_ctl;
173         uint32_t                sc_rev_id;
174         uint32_t                sc_mchash_table[DP_SEL_VHF_HASH_LEN];
175         uint32_t                sc_pfilter_table[MUGE_NUM_PFILTER_ADDRS_][2];
176
177         uint32_t                sc_flags;
178 #define MUGE_FLAG_LINK  0x0001
179 };
180
181 #define MUGE_IFACE_IDX          0
182
183 #define MUGE_LOCK(_sc)                  mtx_lock(&(_sc)->sc_mtx)
184 #define MUGE_UNLOCK(_sc)                mtx_unlock(&(_sc)->sc_mtx)
185 #define MUGE_LOCK_ASSERT(_sc, t)        mtx_assert(&(_sc)->sc_mtx, t)
186
187
188 static device_probe_t muge_probe;
189 static device_attach_t muge_attach;
190 static device_detach_t muge_detach;
191
192 static usb_callback_t muge_bulk_read_callback;
193 static usb_callback_t muge_bulk_write_callback;
194
195 static miibus_readreg_t lan78xx_miibus_readreg;
196 static miibus_writereg_t lan78xx_miibus_writereg;
197 static miibus_statchg_t lan78xx_miibus_statchg;
198
199 static int muge_attach_post_sub(struct usb_ether *ue);
200 static uether_fn_t muge_attach_post;
201 static uether_fn_t muge_init;
202 static uether_fn_t muge_stop;
203 static uether_fn_t muge_start;
204 static uether_fn_t muge_tick;
205 static uether_fn_t muge_setmulti;
206 static uether_fn_t muge_setpromisc;
207
208 static int muge_ifmedia_upd(struct ifnet *);
209 static void muge_ifmedia_sts(struct ifnet *, struct ifmediareq *);
210
211 static int lan78xx_chip_init(struct muge_softc *sc);
212 static int muge_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data);
213
214 static const struct usb_config muge_config[MUGE_N_TRANSFER] = {
215
216         [MUGE_BULK_DT_WR] = {
217                 .type = UE_BULK,
218                 .endpoint = UE_ADDR_ANY,
219                 .direction = UE_DIR_OUT,
220                 .frames = 16,
221                 .bufsize = 16 * (MCLBYTES + 16),
222                 .flags = {.pipe_bof = 1,.force_short_xfer = 1,},
223                 .callback = muge_bulk_write_callback,
224                 .timeout = 10000,       /* 10 seconds */
225         },
226
227         [MUGE_BULK_DT_RD] = {
228                 .type = UE_BULK,
229                 .endpoint = UE_ADDR_ANY,
230                 .direction = UE_DIR_IN,
231                 .bufsize = 20480,       /* bytes */
232                 .flags = {.pipe_bof = 1,.short_xfer_ok = 1,},
233                 .callback = muge_bulk_read_callback,
234                 .timeout = 0,   /* no timeout */
235         },
236         /*
237          * The chip supports interrupt endpoints, however they aren't
238          * needed as we poll on the MII status.
239          */
240 };
241
242 static const struct usb_ether_methods muge_ue_methods = {
243         .ue_attach_post = muge_attach_post,
244         .ue_attach_post_sub = muge_attach_post_sub,
245         .ue_start = muge_start,
246         .ue_ioctl = muge_ioctl,
247         .ue_init = muge_init,
248         .ue_stop = muge_stop,
249         .ue_tick = muge_tick,
250         .ue_setmulti = muge_setmulti,
251         .ue_setpromisc = muge_setpromisc,
252         .ue_mii_upd = muge_ifmedia_upd,
253         .ue_mii_sts = muge_ifmedia_sts,
254 };
255
256 /**
257  *      lan78xx_read_reg - Read a 32-bit register on the device
258  *      @sc: driver soft context
259  *      @off: offset of the register
260  *      @data: pointer a value that will be populated with the register value
261  *
262  *      LOCKING:
263  *      The device lock must be held before calling this function.
264  *
265  *      RETURNS:
266  *      0 on success, a USB_ERR_?? error code on failure.
267  */
268 static int
269 lan78xx_read_reg(struct muge_softc *sc, uint32_t off, uint32_t *data)
270 {
271         struct usb_device_request req;
272         uint32_t buf;
273         usb_error_t err;
274
275         MUGE_LOCK_ASSERT(sc, MA_OWNED);
276
277         req.bmRequestType = UT_READ_VENDOR_DEVICE;
278         req.bRequest = UVR_READ_REG;
279         USETW(req.wValue, 0);
280         USETW(req.wIndex, off);
281         USETW(req.wLength, 4);
282
283         err = uether_do_request(&sc->sc_ue, &req, &buf, 1000);
284         if (err != 0)
285                 muge_warn_printf(sc, "Failed to read register 0x%0x\n", off);
286         *data = le32toh(buf);
287         return (err);
288 }
289
290 /**
291  *      lan78xx_write_reg - Write a 32-bit register on the device
292  *      @sc: driver soft context
293  *      @off: offset of the register
294  *      @data: the 32-bit value to write into the register
295  *
296  *      LOCKING:
297  *      The device lock must be held before calling this function.
298  *
299  *      RETURNS:
300  *      0 on success, a USB_ERR_?? error code on failure.
301  */
302 static int
303 lan78xx_write_reg(struct muge_softc *sc, uint32_t off, uint32_t data)
304 {
305         struct usb_device_request req;
306         uint32_t buf;
307         usb_error_t err;
308
309         MUGE_LOCK_ASSERT(sc, MA_OWNED);
310
311         buf = htole32(data);
312
313         req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
314         req.bRequest = UVR_WRITE_REG;
315         USETW(req.wValue, 0);
316         USETW(req.wIndex, off);
317         USETW(req.wLength, 4);
318
319         err = uether_do_request(&sc->sc_ue, &req, &buf, 1000);
320         if (err != 0)
321                 muge_warn_printf(sc, "Failed to write register 0x%0x\n", off);
322         return (err);
323 }
324
325 /**
326  *      lan78xx_wait_for_bits - Poll on a register value until bits are cleared
327  *      @sc: soft context
328  *      @reg: offset of the register
329  *      @bits: if the bits are clear the function returns
330  *
331  *      LOCKING:
332  *      The device lock must be held before calling this function.
333  *
334  *      RETURNS:
335  *      0 on success, or a USB_ERR_?? error code on failure.
336  */
337 static int
338 lan78xx_wait_for_bits(struct muge_softc *sc, uint32_t reg, uint32_t bits)
339 {
340         usb_ticks_t start_ticks;
341         const usb_ticks_t max_ticks = USB_MS_TO_TICKS(1000);
342         uint32_t val;
343         int err;
344
345         MUGE_LOCK_ASSERT(sc, MA_OWNED);
346
347         start_ticks = (usb_ticks_t)ticks;
348         do {
349                 if ((err = lan78xx_read_reg(sc, reg, &val)) != 0)
350                         return (err);
351                 if (!(val & bits))
352                         return (0);
353                 uether_pause(&sc->sc_ue, hz / 100);
354         } while (((usb_ticks_t)(ticks - start_ticks)) < max_ticks);
355
356         return (USB_ERR_TIMEOUT);
357 }
358
359 /**
360  *      lan78xx_eeprom_read_raw - Read the attached EEPROM
361  *      @sc: soft context
362  *      @off: the eeprom address offset
363  *      @buf: stores the bytes
364  *      @buflen: the number of bytes to read
365  *
366  *      Simply reads bytes from an attached eeprom.
367  *
368  *      LOCKING:
369  *      The function takes and releases the device lock if not already held.
370  *
371  *      RETURNS:
372  *      0 on success, or a USB_ERR_?? error code on failure.
373  */
374 static int
375 lan78xx_eeprom_read_raw(struct muge_softc *sc, uint16_t off, uint8_t *buf,
376     uint16_t buflen)
377 {
378         usb_ticks_t start_ticks;
379         const usb_ticks_t max_ticks = USB_MS_TO_TICKS(1000);
380         int err, locked;
381         uint32_t val, saved;
382         uint16_t i;
383
384         locked = mtx_owned(&sc->sc_mtx); /* XXX */
385         if (!locked)
386                 MUGE_LOCK(sc);
387
388         err = lan78xx_read_reg(sc, HW_CFG, &val);
389         saved = val;
390
391         val &= ~(HW_CFG_LEDO_EN_ | HW_CFG_LED1_EN_);
392         err = lan78xx_write_reg(sc, HW_CFG, val);
393
394         err = lan78xx_wait_for_bits(sc, E2P_CMD, E2P_CMD_BUSY_);
395         if (err != 0) {
396                 muge_warn_printf(sc, "eeprom busy, failed to read data\n");
397                 goto done;
398         }
399
400         /* Start reading the bytes, one at a time. */
401         for (i = 0; i < buflen; i++) {
402                 val = E2P_CMD_BUSY_ | E2P_CMD_READ_;
403                 val |= (E2P_CMD_ADDR_MASK_ & (off + i));
404                 if ((err = lan78xx_write_reg(sc, E2P_CMD, val)) != 0)
405                         goto done;
406
407                 start_ticks = (usb_ticks_t)ticks;
408                 do {
409                         if ((err = lan78xx_read_reg(sc, E2P_CMD, &val)) != 0)
410                                 goto done;
411                         if (!(val & E2P_CMD_BUSY_) || (val & E2P_CMD_TIMEOUT_))
412                                 break;
413
414                         uether_pause(&sc->sc_ue, hz / 100);
415                 } while (((usb_ticks_t)(ticks - start_ticks)) < max_ticks);
416
417                 if (val & (E2P_CMD_BUSY_ | E2P_CMD_TIMEOUT_)) {
418                         muge_warn_printf(sc, "eeprom command failed\n");
419                         err = USB_ERR_IOERROR;
420                         break;
421                 }
422
423                 if ((err = lan78xx_read_reg(sc, E2P_DATA, &val)) != 0)
424                         goto done;
425
426                 buf[i] = (val & 0xff);
427         }
428
429 done:
430         if (!locked)
431                 MUGE_UNLOCK(sc);
432         lan78xx_write_reg(sc, HW_CFG, saved);
433         return (err);
434 }
435
436 /**
437  *      lan78xx_eeprom_read - Read EEPROM and confirm it is programmed
438  *      @sc: soft context
439  *      @off: the eeprom address offset
440  *      @buf: stores the bytes
441  *      @buflen: the number of bytes to read
442  *
443  *      RETURNS:
444  *      0 on success, or a USB_ERR_?? error code on failure.
445  */
446 static int
447 lan78xx_eeprom_read(struct muge_softc *sc, uint16_t off, uint8_t *buf,
448     uint16_t buflen)
449 {
450         uint8_t sig;
451         int ret;
452
453         ret = lan78xx_eeprom_read_raw(sc, E2P_INDICATOR_OFFSET, &sig, 1);
454         if ((ret == 0) && (sig == E2P_INDICATOR)) {
455                 ret = lan78xx_eeprom_read_raw(sc, off, buf, buflen);
456                 muge_dbg_printf(sc, "EEPROM present\n");
457         } else {
458                 ret = -EINVAL;
459                 muge_dbg_printf(sc, "EEPROM not present\n");
460         }
461         return ret;
462 }
463
464 /**
465  *      lan78xx_otp_read_raw
466  *      @sc: soft context
467  *      @off: the otp address offset
468  *      @buf: stores the bytes
469  *      @buflen: the number of bytes to read
470  *
471  *      Simply reads bytes from the OTP.
472  *
473  *      LOCKING:
474  *      The function takes and releases the device lock if not already held.
475  *
476  *      RETURNS:
477  *      0 on success, or a USB_ERR_?? error code on failure.
478  *
479  */
480 static int
481 lan78xx_otp_read_raw(struct muge_softc *sc, uint16_t off, uint8_t *buf,
482     uint16_t buflen)
483 {
484         int locked, err;
485         uint32_t val;
486         uint16_t i;
487         locked = mtx_owned(&sc->sc_mtx);
488         if (!locked)
489                 MUGE_LOCK(sc);
490
491         err = lan78xx_read_reg(sc, OTP_PWR_DN, &val);
492
493         /* checking if bit is set */
494         if (val & OTP_PWR_DN_PWRDN_N) {
495                 /* clearing it, then waiting for it to be cleared */
496                 lan78xx_write_reg(sc, OTP_PWR_DN, 0);
497                 err = lan78xx_wait_for_bits(sc, OTP_PWR_DN, OTP_PWR_DN_PWRDN_N);
498                 if (err != 0) {
499                         muge_warn_printf(sc, "OTP off? failed to read data\n");
500                         goto done;
501                 }
502         }
503         /* start reading the bytes, one at a time */
504         for (i = 0; i < buflen; i++) {
505                 err = lan78xx_write_reg(sc, OTP_ADDR1,
506                     ((off + i) >> 8) & OTP_ADDR1_15_11);
507                 err = lan78xx_write_reg(sc, OTP_ADDR2,
508                     ((off + i) & OTP_ADDR2_10_3));
509                 err = lan78xx_write_reg(sc, OTP_FUNC_CMD, OTP_FUNC_CMD_READ_);
510                 err = lan78xx_write_reg(sc, OTP_CMD_GO, OTP_CMD_GO_GO_);
511
512                 err = lan78xx_wait_for_bits(sc, OTP_STATUS, OTP_STATUS_BUSY_);
513                 if (err != 0) {
514                         muge_warn_printf(sc, "OTP busy failed to read data\n");
515                         goto done;
516                 }
517
518                 if ((err = lan78xx_read_reg(sc, OTP_RD_DATA, &val)) != 0)
519                         goto done;
520
521                 buf[i] = (uint8_t)(val & 0xff);
522         }
523
524 done:
525         if (!locked)
526                 MUGE_UNLOCK(sc);
527         return (err);
528 }
529
530 /**
531  *      lan78xx_otp_read
532  *      @sc: soft context
533  *      @off: the otp address offset
534  *      @buf: stores the bytes
535  *      @buflen: the number of bytes to read
536  *
537  *      Simply reads bytes from the otp.
538  *
539  *      LOCKING:
540  *      The function takes and releases device lock if it is not already held.
541  *
542  *      RETURNS:
543  *      0 on success, or a USB_ERR_?? error code on failure.
544  */
545 static int
546 lan78xx_otp_read(struct muge_softc *sc, uint16_t off, uint8_t *buf,
547     uint16_t buflen)
548 {
549         uint8_t sig;
550         int err;
551
552         err = lan78xx_otp_read_raw(sc, OTP_INDICATOR_OFFSET, &sig, 1);
553         if (err == 0) {
554                 if (sig == OTP_INDICATOR_1) {
555                 } else if (sig == OTP_INDICATOR_2) {
556                         off += 0x100;
557                 } else {
558                         err = -EINVAL;
559                 }
560                 if(!err)
561                         err = lan78xx_otp_read_raw(sc, off, buf, buflen);
562         }
563         return err;
564 }
565
566 /**
567  *      lan78xx_setmacaddress - Set the mac address in the device
568  *      @sc: driver soft context
569  *      @addr: pointer to array contain at least 6 bytes of the mac
570  *
571  *      LOCKING:
572  *      Should be called with the MUGE lock held.
573  *
574  *      RETURNS:
575  *      Returns 0 on success or a negative error code.
576  */
577 static int
578 lan78xx_setmacaddress(struct muge_softc *sc, const uint8_t *addr)
579 {
580         int err;
581         uint32_t val;
582
583         muge_dbg_printf(sc,
584             "setting mac address to %02x:%02x:%02x:%02x:%02x:%02x\n",
585             addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
586
587         MUGE_LOCK_ASSERT(sc, MA_OWNED);
588
589         val = (addr[3] << 24) | (addr[2] << 16) | (addr[1] << 8) | addr[0];
590         if ((err = lan78xx_write_reg(sc, RX_ADDRL, val)) != 0)
591                 goto done;
592
593         val = (addr[5] << 8) | addr[4];
594         err = lan78xx_write_reg(sc, RX_ADDRH, val);
595
596 done:
597         return (err);
598 }
599
600 /**
601  *      lan78xx_set_rx_max_frame_length
602  *      @sc: driver soft context
603  *      @size: pointer to array contain at least 6 bytes of the mac
604  *
605  *      Sets the maximum frame length to be received. Frames bigger than
606  *      this size are aborted.
607  *
608  *      RETURNS:
609  *      Returns 0 on success or a negative error code.
610  */
611 static int
612 lan78xx_set_rx_max_frame_length(struct muge_softc *sc, int size)
613 {
614         int err = 0;
615         uint32_t buf;
616         bool rxenabled;
617
618         /* first we have to disable rx before changing the length */
619
620         err = lan78xx_read_reg(sc, MAC_RX, &buf);
621         rxenabled = ((buf & MAC_RX_EN_) != 0);
622
623         if (rxenabled) {
624                 buf &= ~MAC_RX_EN_;
625                 err = lan78xx_write_reg(sc, MAC_RX, buf);
626         }
627
628         /* setting max frame length */
629
630         buf &= ~MAC_RX_MAX_FR_SIZE_MASK_;
631         buf |= (((size + 4) << MAC_RX_MAX_FR_SIZE_SHIFT_) &
632             MAC_RX_MAX_FR_SIZE_MASK_);
633         err = lan78xx_write_reg(sc, MAC_RX, buf);
634
635         /* If it were enabled before, we enable it back. */
636
637         if (rxenabled) {
638                 buf |= MAC_RX_EN_;
639                 err = lan78xx_write_reg(sc, MAC_RX, buf);
640         }
641
642         return 0;
643 }
644
645 /**
646  *      lan78xx_miibus_readreg - Read a MII/MDIO register
647  *      @dev: usb ether device
648  *      @phy: the number of phy reading from
649  *      @reg: the register address
650  *
651  *      LOCKING:
652  *      Takes and releases the device mutex lock if not already held.
653  *
654  *      RETURNS:
655  *      Returns the 16-bits read from the MII register, if this function fails
656  *      0 is returned.
657  */
658 static int
659 lan78xx_miibus_readreg(device_t dev, int phy, int reg) {
660
661         struct muge_softc *sc = device_get_softc(dev);
662         int locked;
663         uint32_t addr, val;
664
665         val = 0;
666         locked = mtx_owned(&sc->sc_mtx);
667         if (!locked)
668                 MUGE_LOCK(sc);
669
670         if (lan78xx_wait_for_bits(sc, MII_ACCESS, MII_BUSY_) != 0) {
671                 muge_warn_printf(sc, "MII is busy\n");
672                 goto done;
673         }
674
675         addr = (phy << 11) | (reg << 6) | MII_READ_ | MII_BUSY_;
676         lan78xx_write_reg(sc, MII_ACCESS, addr);
677
678         if (lan78xx_wait_for_bits(sc, MII_ACCESS, MII_BUSY_) != 0) {
679                 muge_warn_printf(sc, "MII read timeout\n");
680                 goto done;
681         }
682
683         lan78xx_read_reg(sc, MII_DATA, &val);
684         val = le32toh(val);
685
686 done:
687         if (!locked)
688                 MUGE_UNLOCK(sc);
689
690         return (val & 0xFFFF);
691 }
692
693 /**
694  *      lan78xx_miibus_writereg - Writes a MII/MDIO register
695  *      @dev: usb ether device
696  *      @phy: the number of phy writing to
697  *      @reg: the register address
698  *      @val: the value to write
699  *
700  *      Attempts to write a PHY register through the usb controller registers.
701  *
702  *      LOCKING:
703  *      Takes and releases the device mutex lock if not already held.
704  *
705  *      RETURNS:
706  *      Always returns 0 regardless of success or failure.
707  */
708 static int
709 lan78xx_miibus_writereg(device_t dev, int phy, int reg, int val)
710 {
711         struct muge_softc *sc = device_get_softc(dev);
712         int locked;
713         uint32_t addr;
714
715         if (sc->sc_phyno != phy)
716                 return (0);
717
718         locked = mtx_owned(&sc->sc_mtx);
719         if (!locked)
720                 MUGE_LOCK(sc);
721
722         if (lan78xx_wait_for_bits(sc, MII_ACCESS, MII_BUSY_) != 0) {
723                 muge_warn_printf(sc, "MII is busy\n");
724                 goto done;
725         }
726
727         val = htole32(val);
728         lan78xx_write_reg(sc, MII_DATA, val);
729
730         addr = (phy << 11) | (reg << 6) | MII_WRITE_ | MII_BUSY_;
731         lan78xx_write_reg(sc, MII_ACCESS, addr);
732
733         if (lan78xx_wait_for_bits(sc, MII_ACCESS, MII_BUSY_) != 0)
734                 muge_warn_printf(sc, "MII write timeout\n");
735
736 done:
737         if (!locked)
738                 MUGE_UNLOCK(sc);
739         return (0);
740 }
741
742 /*
743  *      lan78xx_miibus_statchg - Called to detect phy status change
744  *      @dev: usb ether device
745  *
746  *      This function is called periodically by the system to poll for status
747  *      changes of the link.
748  *
749  *      LOCKING:
750  *      Takes and releases the device mutex lock if not already held.
751  */
752 static void
753 lan78xx_miibus_statchg(device_t dev)
754 {
755         struct muge_softc *sc = device_get_softc(dev);
756         struct mii_data *mii = uether_getmii(&sc->sc_ue);
757         struct ifnet *ifp;
758         int locked;
759         int err;
760         uint32_t flow = 0;
761         uint32_t fct_flow = 0;
762
763         locked = mtx_owned(&sc->sc_mtx);
764         if (!locked)
765                 MUGE_LOCK(sc);
766
767         ifp = uether_getifp(&sc->sc_ue);
768         if (mii == NULL || ifp == NULL ||
769             (ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
770                 goto done;
771
772         /* Use the MII status to determine link status */
773         sc->sc_flags &= ~MUGE_FLAG_LINK;
774         if ((mii->mii_media_status & (IFM_ACTIVE | IFM_AVALID)) ==
775             (IFM_ACTIVE | IFM_AVALID)) {
776                 muge_dbg_printf(sc, "media is active\n");
777                 switch (IFM_SUBTYPE(mii->mii_media_active)) {
778                 case IFM_10_T:
779                 case IFM_100_TX:
780                         sc->sc_flags |= MUGE_FLAG_LINK;
781                         muge_dbg_printf(sc, "10/100 ethernet\n");
782                         break;
783                 case IFM_1000_T:
784                         sc->sc_flags |= MUGE_FLAG_LINK;
785                         muge_dbg_printf(sc, "Gigabit ethernet\n");
786                         break;
787                 default:
788                         break;
789                 }
790         }
791         /* Lost link, do nothing. */
792         if ((sc->sc_flags & MUGE_FLAG_LINK) == 0) {
793                 muge_dbg_printf(sc, "link flag not set\n");
794                 goto done;
795         }
796
797         err = lan78xx_read_reg(sc, FCT_FLOW, &fct_flow);
798         if (err) {
799                 muge_warn_printf(sc,
800                    "failed to read initial flow control thresholds, error %d\n",
801                     err);
802                 goto done;
803         }
804
805         /* Enable/disable full duplex operation and TX/RX pause */
806         if ((IFM_OPTIONS(mii->mii_media_active) & IFM_FDX) != 0) {
807                 muge_dbg_printf(sc, "full duplex operation\n");
808
809                 /* enable transmit MAC flow control function */
810                 if ((IFM_OPTIONS(mii->mii_media_active) & IFM_ETH_TXPAUSE) != 0)
811                         flow |= FLOW_CR_TX_FCEN_ | 0xFFFF;
812
813                 if ((IFM_OPTIONS(mii->mii_media_active) & IFM_ETH_RXPAUSE) != 0)
814                         flow |= FLOW_CR_RX_FCEN_;
815         }
816
817         switch(usbd_get_speed(sc->sc_ue.ue_udev)) {
818         case USB_SPEED_SUPER:
819                 fct_flow = 0x817; /* XXX */
820                 break;
821         case USB_SPEED_HIGH:
822                 fct_flow = 0x211; /* XXX */
823                 break;
824         default:
825                 break;
826         }
827
828         err += lan78xx_write_reg(sc, FLOW, flow);
829         err += lan78xx_write_reg(sc, FCT_FLOW, fct_flow);
830         if (err)
831                 muge_warn_printf(sc, "media change failed, error %d\n", err);
832
833 done:
834         if (!locked)
835                 MUGE_UNLOCK(sc);
836 }
837
838 /*
839  *      lan78xx_set_mdix_auto - Configure the device to enable automatic
840  *      crossover and polarity detection.  LAN7800 provides HP Auto-MDIX
841  *      functionality for seamless crossover and polarity detection.
842  *
843  *      @sc: driver soft context
844  *
845  *      LOCKING:
846  *      Takes and releases the device mutex lock if not already held.
847  */
848 static void
849 lan78xx_set_mdix_auto(struct muge_softc *sc)
850 {
851         uint32_t buf, err;
852
853         err = lan78xx_miibus_writereg(sc->sc_ue.ue_dev, sc->sc_phyno,
854             MUGE_EXT_PAGE_ACCESS, MUGE_EXT_PAGE_SPACE_1);
855
856         buf = lan78xx_miibus_readreg(sc->sc_ue.ue_dev, sc->sc_phyno,
857             MUGE_EXT_MODE_CTRL);
858         buf &= ~MUGE_EXT_MODE_CTRL_MDIX_MASK_;
859         buf |= MUGE_EXT_MODE_CTRL_AUTO_MDIX_;
860
861         lan78xx_miibus_readreg(sc->sc_ue.ue_dev, sc->sc_phyno, MII_BMCR);
862         err += lan78xx_miibus_writereg(sc->sc_ue.ue_dev, sc->sc_phyno,
863             MUGE_EXT_MODE_CTRL, buf);
864
865         err += lan78xx_miibus_writereg(sc->sc_ue.ue_dev, sc->sc_phyno,
866             MUGE_EXT_PAGE_ACCESS, MUGE_EXT_PAGE_SPACE_0);
867
868         if (err != 0)
869                 muge_warn_printf(sc, "error setting PHY's MDIX status\n");
870
871         sc->sc_mdix_ctl = buf;
872 }
873
874 /**
875  *      lan78xx_phy_init - Initialises the in-built MUGE phy
876  *      @sc: driver soft context
877  *
878  *      Resets the PHY part of the chip and then initialises it to default
879  *      values.  The 'link down' and 'auto-negotiation complete' interrupts
880  *      from the PHY are also enabled, however we don't monitor the interrupt
881  *      endpoints for the moment.
882  *
883  *      RETURNS:
884  *      Returns 0 on success or EIO if failed to reset the PHY.
885  */
886 static int
887 lan78xx_phy_init(struct muge_softc *sc)
888 {
889         muge_dbg_printf(sc, "Initializing PHY.\n");
890         uint16_t bmcr;
891         usb_ticks_t start_ticks;
892         const usb_ticks_t max_ticks = USB_MS_TO_TICKS(1000);
893
894         MUGE_LOCK_ASSERT(sc, MA_OWNED);
895
896         /* Reset phy and wait for reset to complete */
897         lan78xx_miibus_writereg(sc->sc_ue.ue_dev, sc->sc_phyno, MII_BMCR,
898             BMCR_RESET);
899
900         start_ticks = ticks;
901         do {
902                 uether_pause(&sc->sc_ue, hz / 100);
903                 bmcr = lan78xx_miibus_readreg(sc->sc_ue.ue_dev, sc->sc_phyno,
904                     MII_BMCR);
905         } while ((bmcr & BMCR_RESET) && ((ticks - start_ticks) < max_ticks));
906
907         if (((usb_ticks_t)(ticks - start_ticks)) >= max_ticks) {
908                 muge_err_printf(sc, "PHY reset timed-out\n");
909                 return (EIO);
910         }
911
912         /* Setup phy to interrupt upon link down or autoneg completion. */
913         lan78xx_miibus_readreg(sc->sc_ue.ue_dev, sc->sc_phyno,
914             MUGE_PHY_INTR_STAT);
915         lan78xx_miibus_writereg(sc->sc_ue.ue_dev, sc->sc_phyno,
916             MUGE_PHY_INTR_MASK,
917             (MUGE_PHY_INTR_ANEG_COMP | MUGE_PHY_INTR_LINK_CHANGE));
918
919         /* Enable Auto-MDIX for crossover and polarity detection. */
920         lan78xx_set_mdix_auto(sc);
921
922         /* Enable all modes. */
923         lan78xx_miibus_writereg(sc->sc_ue.ue_dev, sc->sc_phyno, MII_ANAR,
924             ANAR_10 | ANAR_10_FD | ANAR_TX | ANAR_TX_FD |
925             ANAR_CSMA | ANAR_FC | ANAR_PAUSE_ASYM);
926
927         /* Restart auto-negotation */
928         bmcr |= BMCR_STARTNEG;
929         bmcr |= BMCR_AUTOEN;
930         lan78xx_miibus_writereg(sc->sc_ue.ue_dev, sc->sc_phyno, MII_BMCR, bmcr);
931         bmcr = lan78xx_miibus_readreg(sc->sc_ue.ue_dev, sc->sc_phyno, MII_BMCR);
932         return (0);
933 }
934
935 /**
936  *      lan78xx_chip_init - Initialises the chip after power on
937  *      @sc: driver soft context
938  *
939  *      This initialisation sequence is modelled on the procedure in the Linux
940  *      driver.
941  *
942  *      RETURNS:
943  *      Returns 0 on success or an error code on failure.
944  */
945 static int
946 lan78xx_chip_init(struct muge_softc *sc)
947 {
948         int err;
949         int locked;
950         uint32_t buf;
951         uint32_t burst_cap;
952
953         locked = mtx_owned(&sc->sc_mtx);
954         if (!locked)
955                 MUGE_LOCK(sc);
956
957         /* Enter H/W config mode */
958         lan78xx_write_reg(sc, HW_CFG, HW_CFG_LRST_);
959
960         if ((err = lan78xx_wait_for_bits(sc, HW_CFG, HW_CFG_LRST_)) != 0) {
961                 muge_warn_printf(sc,
962                     "timed-out waiting for lite reset to complete\n");
963                 goto init_failed;
964         }
965
966         /* Set the mac address */
967         if ((err = lan78xx_setmacaddress(sc, sc->sc_ue.ue_eaddr)) != 0) {
968                 muge_warn_printf(sc, "failed to set the MAC address\n");
969                 goto init_failed;
970         }
971
972         /* Read and display the revision register */
973         if ((err = lan78xx_read_reg(sc, ID_REV, &sc->sc_rev_id)) < 0) {
974                 muge_warn_printf(sc, "failed to read ID_REV (err = %d)\n", err);
975                 goto init_failed;
976         }
977
978         device_printf(sc->sc_ue.ue_dev, "chip 0x%04lx, rev. %04lx\n",
979                 (sc->sc_rev_id & ID_REV_CHIP_ID_MASK_) >> 16,
980                 (sc->sc_rev_id & ID_REV_CHIP_REV_MASK_));
981
982         /* Respond to BULK-IN tokens with a NAK when RX FIFO is empty. */
983         if ((err = lan78xx_read_reg(sc, USB_CFG0, &buf)) != 0) {
984                 muge_warn_printf(sc, "failed to read USB_CFG0: %d\n", err);
985                 goto init_failed;
986         }
987         buf |= USB_CFG_BIR_;
988         lan78xx_write_reg(sc, USB_CFG0, buf);
989
990         /*
991          * LTM support will go here.
992          */
993
994         /* Configuring the burst cap. */
995         switch (usbd_get_speed(sc->sc_ue.ue_udev)) {
996         case USB_SPEED_SUPER:
997                 burst_cap = MUGE_DEFAULT_BURST_CAP_SIZE/MUGE_SS_USB_PKT_SIZE;
998                 break;
999         case USB_SPEED_HIGH:
1000                 burst_cap = MUGE_DEFAULT_BURST_CAP_SIZE/MUGE_HS_USB_PKT_SIZE;
1001                 break;
1002         default:
1003                 burst_cap = MUGE_DEFAULT_BURST_CAP_SIZE/MUGE_FS_USB_PKT_SIZE;
1004         }
1005
1006         lan78xx_write_reg(sc, BURST_CAP, burst_cap);
1007
1008         /* Set the default bulk in delay (same value from Linux driver) */
1009         lan78xx_write_reg(sc, BULK_IN_DLY, MUGE_DEFAULT_BULK_IN_DELAY);
1010
1011         /* Multiple ethernet frames per USB packets */
1012         err = lan78xx_read_reg(sc, HW_CFG, &buf);
1013         buf |= HW_CFG_MEF_;
1014         err = lan78xx_write_reg(sc, HW_CFG, buf);
1015
1016         /* Enable burst cap. */
1017         if ((err = lan78xx_read_reg(sc, USB_CFG0, &buf)) < 0) {
1018                 muge_warn_printf(sc, "failed to read USB_CFG0: (err = %d)\n",
1019                     err);
1020                 goto init_failed;
1021         }
1022         buf |= USB_CFG_BCE_;
1023         err = lan78xx_write_reg(sc, USB_CFG0, buf);
1024
1025         /*
1026          * Set FCL's RX and TX FIFO sizes: according to data sheet this is
1027          * already the default value. But we initialize it to the same value
1028          * anyways, as that's what the Linux driver does.
1029          *
1030          */
1031
1032         buf = (MUGE_MAX_RX_FIFO_SIZE - 512) / 512;
1033         err = lan78xx_write_reg(sc, FCT_RX_FIFO_END, buf);
1034
1035         buf = (MUGE_MAX_TX_FIFO_SIZE - 512) / 512;
1036         err = lan78xx_write_reg(sc, FCT_TX_FIFO_END, buf);
1037
1038         /* Enabling interrupts. (Not using them for now) */
1039         err = lan78xx_write_reg(sc, INT_STS, INT_STS_CLEAR_ALL_);
1040
1041         /*
1042          * Initializing flow control registers to 0.  These registers are
1043          * properly set is handled in link-reset function in the Linux driver.
1044          */
1045         err = lan78xx_write_reg(sc, FLOW, 0);
1046         err = lan78xx_write_reg(sc, FCT_FLOW, 0);
1047
1048         /*
1049          * Settings for the RFE, we enable broadcast and destination address
1050          * perfect filtering.
1051          */
1052         err = lan78xx_read_reg(sc, RFE_CTL, &buf);
1053         buf |= RFE_CTL_BCAST_EN_ | RFE_CTL_DA_PERFECT_;
1054         err = lan78xx_write_reg(sc, RFE_CTL, buf);
1055
1056         /*
1057          * At this point the Linux driver writes multicast tables, and enables
1058          * checksum engines. But in FreeBSD that gets done in muge_init,
1059          * which gets called when the interface is brought up.
1060          */
1061
1062         /* Reset the PHY. */
1063         lan78xx_write_reg(sc, PMT_CTL, PMT_CTL_PHY_RST_);
1064         if ((err = lan78xx_wait_for_bits(sc, PMT_CTL, PMT_CTL_PHY_RST_)) != 0) {
1065                 muge_warn_printf(sc,
1066                     "timed-out waiting for phy reset to complete\n");
1067                 goto init_failed;
1068         }
1069
1070         /* Enable automatic duplex detection and automatic speed detection. */
1071         err = lan78xx_read_reg(sc, MAC_CR, &buf);
1072         buf |= MAC_CR_AUTO_DUPLEX_ | MAC_CR_AUTO_SPEED_;
1073         err = lan78xx_write_reg(sc, MAC_CR, buf);
1074
1075         /*
1076          * Enable PHY interrupts (Not really getting used for now)
1077          * INT_EP_CTL: interrupt endpoint control register
1078          * phy events cause interrupts to be issued
1079          */
1080         err = lan78xx_read_reg(sc, INT_EP_CTL, &buf);
1081         buf |= INT_ENP_PHY_INT;
1082         err = lan78xx_write_reg(sc, INT_EP_CTL, buf);
1083
1084         /*
1085          * Enables mac's transmitter.  It will transmit frames from the buffer
1086          * onto the cable.
1087          */
1088         err = lan78xx_read_reg(sc, MAC_TX, &buf);
1089         buf |= MAC_TX_TXEN_;
1090         err = lan78xx_write_reg(sc, MAC_TX, buf);
1091
1092         /*
1093          * FIFO is capable of transmitting frames to MAC.
1094          */
1095         err = lan78xx_read_reg(sc, FCT_TX_CTL, &buf);
1096         buf |= FCT_TX_CTL_EN_;
1097         err = lan78xx_write_reg(sc, FCT_TX_CTL, buf);
1098
1099         /*
1100          * Set max frame length.  In linux this is dev->mtu (which by default
1101          * is 1500) + VLAN_ETH_HLEN = 1518
1102          */
1103         err = lan78xx_set_rx_max_frame_length(sc, ETHER_MAX_LEN);
1104
1105         /*
1106          * Initialise the PHY
1107          */
1108         if ((err = lan78xx_phy_init(sc)) != 0)
1109                 goto init_failed;
1110
1111         /*
1112          * enable MAC RX
1113          */
1114         err = lan78xx_read_reg(sc, MAC_RX, &buf);
1115         buf |= MAC_RX_EN_;
1116         err = lan78xx_write_reg(sc, MAC_RX, buf);
1117
1118         /*
1119          * enable FIFO controller RX
1120          */
1121         err = lan78xx_read_reg(sc, FCT_RX_CTL, &buf);
1122         buf |= FCT_TX_CTL_EN_;
1123         err = lan78xx_write_reg(sc, FCT_RX_CTL, buf);
1124
1125         return 0;
1126
1127 init_failed:
1128         if (!locked)
1129                 MUGE_UNLOCK(sc);
1130
1131         muge_err_printf(sc, "lan78xx_chip_init failed (err=%d)\n", err);
1132         return (err);
1133 }
1134
1135 static void
1136 muge_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error)
1137 {
1138         struct muge_softc *sc = usbd_xfer_softc(xfer);
1139         struct usb_ether *ue = &sc->sc_ue;
1140         struct ifnet *ifp = uether_getifp(ue);
1141         struct mbuf *m;
1142         struct usb_page_cache *pc;
1143         uint16_t pktlen;
1144         uint32_t rx_cmd_a, rx_cmd_b;
1145         uint16_t rx_cmd_c;
1146         int off;
1147         int actlen;
1148
1149         usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
1150         muge_dbg_printf(sc, "rx : actlen %d\n", actlen);
1151
1152         switch (USB_GET_STATE(xfer)) {
1153         case USB_ST_TRANSFERRED:
1154
1155                 /*
1156                  * There is always a zero length frame after bringing the
1157                  * interface up.
1158                  */
1159                 if (actlen < (sizeof(rx_cmd_a) + ETHER_CRC_LEN))
1160                         goto tr_setup;
1161
1162                 /*
1163                  * There may be multiple packets in the USB frame.  Each will
1164                  * have a header and each needs to have its own mbuf allocated
1165                  * and populated for it.
1166                  */
1167                 pc = usbd_xfer_get_frame(xfer, 0);
1168                 off = 0;
1169
1170                 while (off < actlen) {
1171
1172                         /* The frame header is aligned on a 4 byte boundary. */
1173                         off = ((off + 0x3) & ~0x3);
1174
1175                         /* Extract RX CMD A. */
1176                         if (off + sizeof(rx_cmd_a) > actlen)
1177                                 goto tr_setup;
1178                         usbd_copy_out(pc, off, &rx_cmd_a, sizeof(rx_cmd_a));
1179                         off += (sizeof(rx_cmd_a));
1180                         rx_cmd_a = le32toh(rx_cmd_a);
1181
1182
1183                         /* Extract RX CMD B. */
1184                         if (off + sizeof(rx_cmd_b) > actlen)
1185                                 goto tr_setup;
1186                         usbd_copy_out(pc, off, &rx_cmd_b, sizeof(rx_cmd_b));
1187                         off += (sizeof(rx_cmd_b));
1188                         rx_cmd_b = le32toh(rx_cmd_b);
1189
1190
1191                         /* Extract RX CMD C. */
1192                         if (off + sizeof(rx_cmd_c) > actlen)
1193                                 goto tr_setup;
1194                         usbd_copy_out(pc, off, &rx_cmd_c, sizeof(rx_cmd_c));
1195                         off += (sizeof(rx_cmd_c));
1196                         rx_cmd_c = le32toh(rx_cmd_c);
1197
1198                         if (off > actlen)
1199                                 goto tr_setup;
1200
1201                         pktlen = (rx_cmd_a & RX_CMD_A_LEN_MASK_);
1202
1203                         muge_dbg_printf(sc,
1204                             "rx_cmd_a 0x%08x rx_cmd_b 0x%08x rx_cmd_c 0x%04x "
1205                             " pktlen %d actlen %d off %d\n",
1206                             rx_cmd_a, rx_cmd_b, rx_cmd_c, pktlen, actlen, off);
1207
1208                         if (rx_cmd_a & RX_CMD_A_RED_) {
1209                                 muge_dbg_printf(sc,
1210                                      "rx error (hdr 0x%08x)\n", rx_cmd_a);
1211                                 if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
1212                         } else {
1213                                 /* Ethernet frame too big or too small? */
1214                                 if ((pktlen < ETHER_HDR_LEN) ||
1215                                     (pktlen > (actlen - off)))
1216                                         goto tr_setup;
1217
1218                                 /* Create a new mbuf to store the packet in */
1219                                 m = uether_newbuf();
1220                                 if (m == NULL) {
1221                                         muge_warn_printf(sc,
1222                                             "failed to create new mbuf\n");
1223                                         if_inc_counter(ifp, IFCOUNTER_IQDROPS,
1224                                             1);
1225                                         goto tr_setup;
1226                                 }
1227
1228                                 usbd_copy_out(pc, off, mtod(m, uint8_t *),
1229                                     pktlen);
1230
1231                                 /*
1232                                  * Check if RX checksums are computed, and
1233                                  * offload them
1234                                  */
1235                                 if ((ifp->if_capabilities & IFCAP_RXCSUM) &&
1236                                     !(rx_cmd_a & RX_CMD_A_ICSM_)) {
1237                                         struct ether_header *eh;
1238                                         eh = mtod(m, struct ether_header *);
1239                                         /*
1240                                          * Remove the extra 2 bytes of the csum
1241                                          *
1242                                          * The checksum appears to be
1243                                          * simplistically calculated over the
1244                                          * protocol headers up to the end of the
1245                                          * eth frame.  Which means if the eth
1246                                          * frame is padded the csum calculation
1247                                          * is incorrectly performed over the
1248                                          * padding bytes as well.  Therefore to
1249                                          * be safe we ignore the H/W csum on
1250                                          * frames less than or equal to
1251                                          * 64 bytes.
1252                                          *
1253                                          * Protocols checksummed:
1254                                          * TCP, UDP, ICMP, IGMP, IP
1255                                          */
1256                                         if (pktlen > ETHER_MIN_LEN) {
1257                                                 m->m_pkthdr.csum_flags |=
1258                                                     CSUM_DATA_VALID;
1259
1260                                                 /*
1261                                                  * Copy the checksum from the
1262                                                  * last 2 bytes of the transfer
1263                                                  * and put in the csum_data
1264                                                  * field.
1265                                                  */
1266                                                 usbd_copy_out(pc,
1267                                                     (off + pktlen),
1268                                                     &m->m_pkthdr.csum_data, 2);
1269
1270                                                 /*
1271                                                  * The data is copied in network
1272                                                  * order, but the csum algorithm
1273                                                  * in the kernel expects it to
1274                                                  * be in host network order.
1275                                                  */
1276                                                 m->m_pkthdr.csum_data =
1277                                                    ntohs(m->m_pkthdr.csum_data);
1278
1279                                                 muge_dbg_printf(sc,
1280                                                     "RX checksum offloaded (0x%04x)\n",
1281                                                     m->m_pkthdr.csum_data);
1282                                         }
1283                                 }
1284
1285                                 /* Enqueue the mbuf on the receive queue. */
1286                                 if (pktlen < (4 + ETHER_HDR_LEN)) {
1287                                         m_freem(m);
1288                                         goto tr_setup;
1289                                 }
1290                                 /* Remove 4 trailing bytes */
1291                                 uether_rxmbuf(ue, m, pktlen - 4);
1292                         }
1293
1294                         /*
1295                          * Update the offset to move to the next potential
1296                          * packet.
1297                          */
1298                         off += pktlen;
1299                 }
1300
1301                 /* FALLTHROUGH */
1302         case USB_ST_SETUP:
1303 tr_setup:
1304                 usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
1305                 usbd_transfer_submit(xfer);
1306                 uether_rxflush(ue);
1307                 return;
1308
1309         default:
1310                 if (error != USB_ERR_CANCELLED) {
1311                         muge_warn_printf(sc, "bulk read error, %s\n",
1312                             usbd_errstr(error));
1313                         usbd_xfer_set_stall(xfer);
1314                         goto tr_setup;
1315                 }
1316                 return;
1317         }
1318 }
1319
1320 /**
1321  *      muge_bulk_write_callback - Write callback used to send ethernet frame(s)
1322  *      @xfer: the USB transfer
1323  *      @error: error code if the transfers is in an errored state
1324  *
1325  *      The main write function that pulls ethernet frames off the queue and
1326  *      sends them out.
1327  *
1328  */
1329
1330 static void
1331 muge_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error)
1332 {
1333         struct muge_softc *sc = usbd_xfer_softc(xfer);
1334         struct ifnet *ifp = uether_getifp(&sc->sc_ue);
1335         struct usb_page_cache *pc;
1336         struct mbuf *m;
1337         int nframes;
1338         uint32_t frm_len = 0, tx_cmd_a = 0, tx_cmd_b = 0;
1339
1340         switch (USB_GET_STATE(xfer)) {
1341         case USB_ST_TRANSFERRED:
1342                 muge_dbg_printf(sc,
1343                     "USB TRANSFER status: USB_ST_TRANSFERRED\n");
1344                 ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1345                 /* FALLTHROUGH */
1346         case USB_ST_SETUP:
1347                 muge_dbg_printf(sc, "USB TRANSFER status: USB_ST_SETUP\n");
1348 tr_setup:
1349                 if ((sc->sc_flags & MUGE_FLAG_LINK) == 0 ||
1350                         (ifp->if_drv_flags & IFF_DRV_OACTIVE) != 0) {
1351                         muge_dbg_printf(sc,
1352                             "sc->sc_flags & MUGE_FLAG_LINK: %d\n",
1353                             (sc->sc_flags & MUGE_FLAG_LINK));
1354                         muge_dbg_printf(sc,
1355                             "ifp->if_drv_flags & IFF_DRV_OACTIVE: %d\n",
1356                             (ifp->if_drv_flags & IFF_DRV_OACTIVE));
1357                         muge_dbg_printf(sc,
1358                             "USB TRANSFER not sending: no link or controller is busy \n");
1359                         /*
1360                          * Don't send anything if there is no link or
1361                          * controller is busy.
1362                          */
1363                         return;
1364                 }
1365                 for (nframes = 0; nframes < 16 &&
1366                     !IFQ_DRV_IS_EMPTY(&ifp->if_snd); nframes++) {
1367                         IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
1368                         if (m == NULL)
1369                                 break;
1370                         usbd_xfer_set_frame_offset(xfer, nframes * MCLBYTES,
1371                                 nframes);
1372                         frm_len = 0;
1373                         pc = usbd_xfer_get_frame(xfer, nframes);
1374
1375                         /*
1376                          * Each frame is prefixed with two 32-bit values
1377                          * describing the length of the packet and buffer.
1378                          */
1379                         tx_cmd_a = (m->m_pkthdr.len & TX_CMD_A_LEN_MASK_) |
1380                              TX_CMD_A_FCS_;
1381                         tx_cmd_a = htole32(tx_cmd_a);
1382                         usbd_copy_in(pc, 0, &tx_cmd_a, sizeof(tx_cmd_a));
1383
1384                         tx_cmd_b = 0;
1385
1386                         /* TCP LSO Support will probably be implemented here. */
1387                         tx_cmd_b = htole32(tx_cmd_b);
1388                         usbd_copy_in(pc, 4, &tx_cmd_b, sizeof(tx_cmd_b));
1389
1390                         frm_len += 8;
1391
1392                         /* Next copy in the actual packet */
1393                         usbd_m_copy_in(pc, frm_len, m, 0, m->m_pkthdr.len);
1394                         frm_len += m->m_pkthdr.len;
1395
1396                         if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
1397
1398                         /*
1399                          * If there's a BPF listener, bounce a copy of this
1400                          * frame to it.
1401                          */
1402                         BPF_MTAP(ifp, m);
1403                         m_freem(m);
1404
1405                         /* Set frame length. */
1406                         usbd_xfer_set_frame_len(xfer, nframes, frm_len);
1407                 }
1408
1409                 muge_dbg_printf(sc, "USB TRANSFER nframes: %d\n", nframes);
1410                 if (nframes != 0) {
1411                         muge_dbg_printf(sc, "USB TRANSFER submit attempt\n");
1412                         usbd_xfer_set_frames(xfer, nframes);
1413                         usbd_transfer_submit(xfer);
1414                         ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1415                 }
1416                 return;
1417
1418         default:
1419                 if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
1420                 ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1421
1422                 if (error != USB_ERR_CANCELLED) {
1423                         muge_err_printf(sc,
1424                             "usb error on tx: %s\n", usbd_errstr(error));
1425                         usbd_xfer_set_stall(xfer);
1426                         goto tr_setup;
1427                 }
1428                 return;
1429         }
1430 }
1431
1432 /**
1433  *      muge_attach_post - Called after the driver attached to the USB interface
1434  *      @ue: the USB ethernet device
1435  *
1436  *      This is where the chip is intialised for the first time.  This is
1437  *      different from the muge_init() function in that that one is designed to
1438  *      setup the H/W to match the UE settings and can be called after a reset.
1439  *
1440  */
1441 static void
1442 muge_attach_post(struct usb_ether *ue)
1443 {
1444         struct muge_softc *sc = uether_getsc(ue);
1445         uint32_t mac_h, mac_l;
1446         muge_dbg_printf(sc, "Calling muge_attach_post.\n");
1447
1448         /* Setup some of the basics */
1449         sc->sc_phyno = 1;
1450
1451         /*
1452          * Attempt to get the mac address, if an EEPROM is not attached this
1453          * will just return FF:FF:FF:FF:FF:FF, so in such cases we invent a MAC
1454          * address based on urandom.
1455          */
1456         memset(sc->sc_ue.ue_eaddr, 0xff, ETHER_ADDR_LEN);
1457
1458         uint32_t val;
1459         lan78xx_read_reg(sc, 0, &val);
1460
1461         /* Check if there is already a MAC address in the register */
1462         if ((lan78xx_read_reg(sc, RX_ADDRL, &mac_l) == 0) &&
1463                 (lan78xx_read_reg(sc, RX_ADDRH, &mac_h) == 0)) {
1464                 sc->sc_ue.ue_eaddr[5] = (uint8_t)((mac_h >> 8) & 0xff);
1465                 sc->sc_ue.ue_eaddr[4] = (uint8_t)((mac_h) & 0xff);
1466                 sc->sc_ue.ue_eaddr[3] = (uint8_t)((mac_l >> 24) & 0xff);
1467                 sc->sc_ue.ue_eaddr[2] = (uint8_t)((mac_l >> 16) & 0xff);
1468                 sc->sc_ue.ue_eaddr[1] = (uint8_t)((mac_l >> 8) & 0xff);
1469                 sc->sc_ue.ue_eaddr[0] = (uint8_t)((mac_l) & 0xff);
1470         }
1471
1472         /*
1473          * MAC address is not set so try to read from EEPROM, if that fails
1474          * generate a random MAC address.
1475          */
1476         if (!ETHER_IS_VALID(sc->sc_ue.ue_eaddr)) {
1477                 if ((lan78xx_eeprom_read(sc, E2P_MAC_OFFSET,
1478                     sc->sc_ue.ue_eaddr, ETHER_ADDR_LEN) == 0) ||
1479                     (lan78xx_otp_read(sc, OTP_MAC_OFFSET,
1480                     sc->sc_ue.ue_eaddr, ETHER_ADDR_LEN) == 0)) {
1481                         if(ETHER_IS_VALID(sc->sc_ue.ue_eaddr)) {
1482                                 muge_dbg_printf(sc, "MAC read from EEPROM\n");
1483                         } else {
1484                                 muge_dbg_printf(sc, "MAC assigned randomly\n");
1485                                 read_random(sc->sc_ue.ue_eaddr, ETHER_ADDR_LEN);
1486                                 sc->sc_ue.ue_eaddr[0] &= ~0x01; /* unicast */
1487                                 sc->sc_ue.ue_eaddr[0] |= 0x02;/* locally administered */
1488                         }
1489                 } else {
1490                         muge_dbg_printf(sc, "MAC assigned randomly\n");
1491                         arc4rand(sc->sc_ue.ue_eaddr, ETHER_ADDR_LEN, 0);
1492                         sc->sc_ue.ue_eaddr[0] &= ~0x01; /* unicast */
1493                         sc->sc_ue.ue_eaddr[0] |= 0x02;  /* locally administered */
1494                 }
1495         } else {
1496                 muge_dbg_printf(sc, "MAC assigned from registers\n");
1497         }
1498
1499         /* Initialise the chip for the first time */
1500         lan78xx_chip_init(sc);
1501 }
1502
1503 /**
1504  *      muge_attach_post_sub - Called after attach to the USB interface
1505  *      @ue: the USB ethernet device
1506  *
1507  *      Most of this is boilerplate code and copied from the base USB ethernet
1508  *      driver.  It has been overriden so that we can indicate to the system
1509  *      that the chip supports H/W checksumming.
1510  *
1511  *      RETURNS:
1512  *      Returns 0 on success or a negative error code.
1513  */
1514 static int
1515 muge_attach_post_sub(struct usb_ether *ue)
1516 {
1517         struct muge_softc *sc;
1518         struct ifnet *ifp;
1519         int error;
1520
1521         sc = uether_getsc(ue);
1522         muge_dbg_printf(sc, "Calling muge_attach_post_sub.\n");
1523         ifp = ue->ue_ifp;
1524         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
1525         ifp->if_start = uether_start;
1526         ifp->if_ioctl = muge_ioctl;
1527         ifp->if_init = uether_init;
1528         IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
1529         ifp->if_snd.ifq_drv_maxlen = ifqmaxlen;
1530         IFQ_SET_READY(&ifp->if_snd);
1531
1532         /*
1533          * The chip supports TCP/UDP checksum offloading on TX and RX paths,
1534          * however currently only RX checksum is supported in the driver
1535          * (see top of file).
1536          */
1537         ifp->if_hwassist = 0;
1538         if (MUGE_DEFAULT_RX_CSUM_ENABLE)
1539                 ifp->if_capabilities |= IFCAP_RXCSUM;
1540
1541         if (MUGE_DEFAULT_TX_CSUM_ENABLE)
1542                 ifp->if_capabilities |= IFCAP_TXCSUM;
1543
1544         /*
1545          * In the Linux driver they also enable scatter/gather (NETIF_F_SG)
1546          * here, that's something related to socket buffers used in Linux.
1547          * FreeBSD doesn't have that as an interface feature.
1548          */
1549         if (MUGE_DEFAULT_TSO_CSUM_ENABLE)
1550                 ifp->if_capabilities |= IFCAP_TSO4 | IFCAP_TSO6;
1551
1552 #if 0
1553         /* TX checksuming is disabled since not yet implemented. */
1554         ifp->if_capabilities |= IFCAP_TXCSUM;
1555         ifp->if_capenable |= IFCAP_TXCSUM;
1556         ifp->if_hwassist = CSUM_TCP | CSUM_UDP;
1557 #endif
1558
1559         ifp->if_capenable = ifp->if_capabilities;
1560
1561         mtx_lock(&Giant);
1562         error = mii_attach(ue->ue_dev, &ue->ue_miibus, ifp,
1563                 uether_ifmedia_upd, ue->ue_methods->ue_mii_sts,
1564                 BMSR_DEFCAPMASK, sc->sc_phyno, MII_OFFSET_ANY, 0);
1565         mtx_unlock(&Giant);
1566
1567         return 0;
1568 }
1569
1570 /**
1571  *      muge_start - Starts communication with the LAN78xx chip
1572  *      @ue: USB ether interface
1573  */
1574 static void
1575 muge_start(struct usb_ether *ue)
1576 {
1577         struct muge_softc *sc = uether_getsc(ue);
1578
1579         /*
1580          * Start the USB transfers, if not already started.
1581          */
1582         usbd_transfer_start(sc->sc_xfer[MUGE_BULK_DT_RD]);
1583         usbd_transfer_start(sc->sc_xfer[MUGE_BULK_DT_WR]);
1584 }
1585
1586 /**
1587  *      muge_ioctl - ioctl function for the device
1588  *      @ifp: interface pointer
1589  *      @cmd: the ioctl command
1590  *      @data: data passed in the ioctl call, typically a pointer to struct
1591  *      ifreq.
1592  *
1593  *      The ioctl routine is overridden to detect change requests for the H/W
1594  *      checksum capabilities.
1595  *
1596  *      RETURNS:
1597  *      0 on success and an error code on failure.
1598  */
1599 static int
1600 muge_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1601 {
1602         struct usb_ether *ue = ifp->if_softc;
1603         struct muge_softc *sc;
1604         struct ifreq *ifr;
1605         int rc;
1606         int mask;
1607         int reinit;
1608
1609         if (cmd == SIOCSIFCAP) {
1610                 sc = uether_getsc(ue);
1611                 ifr = (struct ifreq *)data;
1612
1613                 MUGE_LOCK(sc);
1614
1615                 rc = 0;
1616                 reinit = 0;
1617
1618                 mask = ifr->ifr_reqcap ^ ifp->if_capenable;
1619
1620                 /* Modify the RX CSUM enable bits */
1621                 if ((mask & IFCAP_RXCSUM) != 0 &&
1622                         (ifp->if_capabilities & IFCAP_RXCSUM) != 0) {
1623                         ifp->if_capenable ^= IFCAP_RXCSUM;
1624
1625                         if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1626                                 ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1627                                 reinit = 1;
1628                         }
1629                 }
1630
1631                 MUGE_UNLOCK(sc);
1632                 if (reinit)
1633                         uether_init(ue);
1634
1635         } else {
1636                 rc = uether_ioctl(ifp, cmd, data);
1637         }
1638
1639         return (rc);
1640 }
1641
1642 /**
1643  *      muge_reset - Reset the SMSC chip
1644  *      @sc: device soft context
1645  *
1646  *      LOCKING:
1647  *      Should be called with the SMSC lock held.
1648  */
1649 static void
1650 muge_reset(struct muge_softc *sc)
1651 {
1652         struct usb_config_descriptor *cd;
1653         usb_error_t err;
1654
1655         cd = usbd_get_config_descriptor(sc->sc_ue.ue_udev);
1656
1657         err = usbd_req_set_config(sc->sc_ue.ue_udev, &sc->sc_mtx,
1658             cd->bConfigurationValue);
1659         if (err)
1660                 muge_warn_printf(sc, "reset failed (ignored)\n");
1661
1662         /* Wait a little while for the chip to get its brains in order. */
1663         uether_pause(&sc->sc_ue, hz / 100);
1664
1665         /* Reinitialize controller to achieve full reset. */
1666         lan78xx_chip_init(sc);
1667 }
1668
1669 /**
1670  * muge_set_addr_filter
1671  *
1672  *      @sc: device soft context
1673  *      @index: index of the entry to the perfect address table
1674  *      @addr: address to be written
1675  *
1676  */
1677 static void
1678 muge_set_addr_filter(struct muge_softc *sc, int index,
1679     uint8_t addr[ETHER_ADDR_LEN])
1680 {
1681         uint32_t tmp;
1682
1683         if ((sc) && (index > 0) && (index < MUGE_NUM_PFILTER_ADDRS_)) {
1684                 tmp = addr[3];
1685                 tmp |= addr[2] | (tmp << 8);
1686                 tmp |= addr[1] | (tmp << 8);
1687                 tmp |= addr[0] | (tmp << 8);
1688                 sc->sc_pfilter_table[index][1] = tmp;
1689                 tmp = addr[5];
1690                 tmp |= addr[4] | (tmp << 8);
1691                 tmp |= PFILTER_ADDR_VALID_ | PFILTER_ADDR_TYPE_DST_;
1692                 sc->sc_pfilter_table[index][0] = tmp;
1693         }
1694 }
1695
1696 /**
1697  *      lan78xx_dataport_write - write to the selected RAM
1698  *      @sc: The device soft context.
1699  *      @ram_select: Select which RAM to access.
1700  *      @addr: Starting address to write to.
1701  *      @buf: word-sized buffer to write to RAM, starting at @addr.
1702  *      @length: length of @buf
1703  *
1704  *
1705  *      RETURNS:
1706  *      0 if write successful.
1707  */
1708 static int
1709 lan78xx_dataport_write(struct muge_softc *sc, uint32_t ram_select,
1710     uint32_t addr, uint32_t length, uint32_t *buf)
1711 {
1712         uint32_t dp_sel;
1713         int i, ret;
1714
1715         MUGE_LOCK_ASSERT(sc, MA_OWNED);
1716         ret = lan78xx_wait_for_bits(sc, DP_SEL, DP_SEL_DPRDY_);
1717         if (ret < 0)
1718                 goto done;
1719
1720         ret = lan78xx_read_reg(sc, DP_SEL, &dp_sel);
1721
1722         dp_sel &= ~DP_SEL_RSEL_MASK_;
1723         dp_sel |= ram_select;
1724
1725         ret = lan78xx_write_reg(sc, DP_SEL, dp_sel);
1726
1727         for (i = 0; i < length; i++) {
1728                 ret = lan78xx_write_reg(sc, DP_ADDR, addr + i);
1729                 ret = lan78xx_write_reg(sc, DP_DATA, buf[i]);
1730                 ret = lan78xx_write_reg(sc, DP_CMD, DP_CMD_WRITE_);
1731                 ret = lan78xx_wait_for_bits(sc, DP_SEL, DP_SEL_DPRDY_);
1732                 if (ret != 0)
1733                         goto done;
1734         }
1735
1736 done:
1737         return ret;
1738 }
1739
1740 /**
1741  * muge_multicast_write
1742  * @sc: device's soft context
1743  *
1744  * Writes perfect addres filters and hash address filters to their
1745  * corresponding registers and RAMs.
1746  *
1747  */
1748 static void
1749 muge_multicast_write(struct muge_softc *sc)
1750 {
1751         int i, ret;
1752         lan78xx_dataport_write(sc, DP_SEL_RSEL_VLAN_DA_, DP_SEL_VHF_VLAN_LEN,
1753             DP_SEL_VHF_HASH_LEN, sc->sc_mchash_table);
1754
1755         for (i = 1; i < MUGE_NUM_PFILTER_ADDRS_; i++) {
1756                 ret = lan78xx_write_reg(sc, PFILTER_HI(i), 0);
1757                 ret = lan78xx_write_reg(sc, PFILTER_LO(i),
1758                     sc->sc_pfilter_table[i][1]);
1759                 ret = lan78xx_write_reg(sc, PFILTER_HI(i),
1760                     sc->sc_pfilter_table[i][0]);
1761         }
1762 }
1763
1764 /**
1765  *      muge_hash - Calculate the hash of a mac address
1766  *      @addr: The mac address to calculate the hash on
1767  *
1768  *      This function is used when configuring a range of multicast mac
1769  *      addresses to filter on.  The hash of the mac address is put in the
1770  *      device's mac hash table.
1771  *
1772  *      RETURNS:
1773  *      Returns a value from 0-63 value which is the hash of the mac address.
1774  */
1775 static inline uint32_t
1776 muge_hash(uint8_t addr[ETHER_ADDR_LEN])
1777 {
1778         return (ether_crc32_be(addr, ETHER_ADDR_LEN) >> 26) & 0x3f;
1779 }
1780
1781 /**
1782  *      muge_setmulti - Setup multicast
1783  *      @ue: usb ethernet device context
1784  *
1785  *      Tells the device to either accept frames with a multicast mac address,
1786  *      a select group of m'cast mac addresses or just the devices mac address.
1787  *
1788  *      LOCKING:
1789  *      Should be called with the MUGE lock held.
1790  */
1791 static void
1792 muge_setmulti(struct usb_ether *ue)
1793 {
1794         struct muge_softc *sc = uether_getsc(ue);
1795         struct ifnet *ifp = uether_getifp(ue);
1796         uint8_t i, *addr;
1797         struct ifmultiaddr *ifma;
1798
1799         MUGE_LOCK_ASSERT(sc, MA_OWNED);
1800
1801         sc->sc_rfe_ctl &= ~(RFE_CTL_UCAST_EN_ | RFE_CTL_MCAST_EN_ |
1802                 RFE_CTL_DA_PERFECT_ | RFE_CTL_MCAST_HASH_);
1803
1804         /* Initializing hash filter table */
1805         for (i = 0; i < DP_SEL_VHF_HASH_LEN; i++)
1806                 sc->sc_mchash_table[i] = 0;
1807
1808         /* Initializing perfect filter table */
1809         for (i = 1; i < MUGE_NUM_PFILTER_ADDRS_; i++) {
1810                 sc->sc_pfilter_table[i][0] =
1811                 sc->sc_pfilter_table[i][1] = 0;
1812         }
1813
1814         sc->sc_rfe_ctl |= RFE_CTL_BCAST_EN_;
1815
1816         if (ifp->if_flags & IFF_PROMISC) {
1817                 muge_dbg_printf(sc, "promiscuous mode enabled\n");
1818                 sc->sc_rfe_ctl |= RFE_CTL_MCAST_EN_ | RFE_CTL_UCAST_EN_;
1819         } else if (ifp->if_flags & IFF_ALLMULTI){
1820                 muge_dbg_printf(sc, "receive all multicast enabled\n");
1821                 sc->sc_rfe_ctl |= RFE_CTL_MCAST_EN_;
1822         } else {
1823                 /*
1824                  * Take the lock of the mac address list before hashing each of
1825                  * them.
1826                  */
1827                 if_maddr_rlock(ifp);
1828                 if (!TAILQ_EMPTY(&ifp->if_multiaddrs)) {
1829                         i = 1;
1830
1831                         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
1832                                 /*
1833                                  * First we fill up the perfect address table.
1834                                  */
1835                                 addr = LLADDR((struct sockaddr_dl *)
1836                                     ifma->ifma_addr);
1837                                 if (i < 33 /* XXX */) {
1838                                         muge_set_addr_filter(sc, i, addr);
1839                                 } else {
1840                                         uint32_t bitnum = muge_hash(addr);
1841                                         sc->sc_mchash_table[bitnum / 32] |=
1842                                             (1 << (bitnum % 32));
1843                                         sc->sc_rfe_ctl |= RFE_CTL_MCAST_HASH_;
1844                                 }
1845                                 i++;
1846                         }
1847                 }
1848                 if_maddr_runlock(ifp);
1849                 muge_multicast_write(sc);
1850         }
1851         lan78xx_write_reg(sc, RFE_CTL, sc->sc_rfe_ctl);
1852 }
1853
1854 /**
1855  *      muge_setpromisc - Enables/disables promiscuous mode
1856  *      @ue: usb ethernet device context
1857  *
1858  *      LOCKING:
1859  *      Should be called with the MUGE lock held.
1860  */
1861 static void
1862 muge_setpromisc(struct usb_ether *ue)
1863 {
1864         struct muge_softc *sc = uether_getsc(ue);
1865         struct ifnet *ifp = uether_getifp(ue);
1866
1867         muge_dbg_printf(sc, "promiscuous mode %sabled\n",
1868             (ifp->if_flags & IFF_PROMISC) ? "en" : "dis");
1869
1870         MUGE_LOCK_ASSERT(sc, MA_OWNED);
1871
1872         if (ifp->if_flags & IFF_PROMISC)
1873                 sc->sc_rfe_ctl |= RFE_CTL_MCAST_EN_ | RFE_CTL_UCAST_EN_;
1874         else
1875                 sc->sc_rfe_ctl &= ~(RFE_CTL_MCAST_EN_);
1876
1877         lan78xx_write_reg(sc, RFE_CTL, sc->sc_rfe_ctl);
1878 }
1879
1880 /**
1881  *      muge_sethwcsum - Enable or disable H/W UDP and TCP checksumming
1882  *      @sc: driver soft context
1883  *
1884  *      LOCKING:
1885  *      Should be called with the MUGE lock held.
1886  *
1887  *      RETURNS:
1888  *      Returns 0 on success or a negative error code.
1889  */
1890 static int muge_sethwcsum(struct muge_softc *sc)
1891 {
1892         struct ifnet *ifp = uether_getifp(&sc->sc_ue);
1893         int err;
1894
1895         if (!ifp)
1896                 return (-EIO);
1897
1898         MUGE_LOCK_ASSERT(sc, MA_OWNED);
1899
1900         if (ifp->if_capabilities & IFCAP_RXCSUM) {
1901                 sc->sc_rfe_ctl |= RFE_CTL_IGMP_COE_ | RFE_CTL_ICMP_COE_;
1902                 sc->sc_rfe_ctl |= RFE_CTL_TCPUDP_COE_ | RFE_CTL_IP_COE_;
1903         } else {
1904                 sc->sc_rfe_ctl &= ~(RFE_CTL_IGMP_COE_ | RFE_CTL_ICMP_COE_);
1905                 sc->sc_rfe_ctl &= ~(RFE_CTL_TCPUDP_COE_ | RFE_CTL_IP_COE_);
1906         }
1907
1908         sc->sc_rfe_ctl &= ~RFE_CTL_VLAN_FILTER_;
1909
1910         err = lan78xx_write_reg(sc, RFE_CTL, sc->sc_rfe_ctl);
1911
1912         if (err != 0) {
1913                 muge_warn_printf(sc, "failed to write RFE_CTL (err=%d)\n", err);
1914                 return (err);
1915         }
1916
1917         return (0);
1918 }
1919
1920 /**
1921  *      muge_ifmedia_upd - Set media options
1922  *      @ifp: interface pointer
1923  *
1924  *      Basically boilerplate code that simply calls the mii functions to set
1925  *      the media options.
1926  *
1927  *      LOCKING:
1928  *      The device lock must be held before this function is called.
1929  *
1930  *      RETURNS:
1931  *      Returns 0 on success or a negative error code.
1932  */
1933 static int
1934 muge_ifmedia_upd(struct ifnet *ifp)
1935 {
1936         struct muge_softc *sc = ifp->if_softc;
1937         muge_dbg_printf(sc, "Calling muge_ifmedia_upd.\n");
1938         struct mii_data *mii = uether_getmii(&sc->sc_ue);
1939         struct mii_softc *miisc;
1940         int err;
1941
1942         MUGE_LOCK_ASSERT(sc, MA_OWNED);
1943
1944         LIST_FOREACH(miisc, &mii->mii_phys, mii_list)
1945                 PHY_RESET(miisc);
1946         err = mii_mediachg(mii);
1947         return (err);
1948 }
1949
1950 /**
1951  *      muge_init - Initialises the LAN95xx chip
1952  *      @ue: USB ether interface
1953  *
1954  *      Called when the interface is brought up (i.e. ifconfig ue0 up), this
1955  *      initialise the interface and the rx/tx pipes.
1956  *
1957  *      LOCKING:
1958  *      Should be called with the MUGE lock held.
1959  */
1960 static void
1961 muge_init(struct usb_ether *ue)
1962 {
1963         struct muge_softc *sc = uether_getsc(ue);
1964         muge_dbg_printf(sc, "Calling muge_init.\n");
1965         struct ifnet *ifp = uether_getifp(ue);
1966         MUGE_LOCK_ASSERT(sc, MA_OWNED);
1967
1968         if (lan78xx_setmacaddress(sc, IF_LLADDR(ifp)))
1969                 muge_dbg_printf(sc, "setting MAC address failed\n");
1970
1971         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) != 0)
1972                 return;
1973
1974         /* Cancel pending I/O */
1975         muge_stop(ue);
1976
1977         /* Reset the ethernet interface. */
1978         muge_reset(sc);
1979
1980         /* Load the multicast filter. */
1981         muge_setmulti(ue);
1982
1983         /* TCP/UDP checksum offload engines. */
1984         muge_sethwcsum(sc);
1985
1986         usbd_xfer_set_stall(sc->sc_xfer[MUGE_BULK_DT_WR]);
1987
1988         /* Indicate we are up and running. */
1989         ifp->if_drv_flags |= IFF_DRV_RUNNING;
1990
1991         /* Switch to selected media. */
1992         muge_ifmedia_upd(ifp);
1993         muge_start(ue);
1994 }
1995
1996 /**
1997  *      muge_stop - Stops communication with the LAN78xx chip
1998  *      @ue: USB ether interface
1999  *
2000  *
2001  *
2002  */
2003 static void
2004 muge_stop(struct usb_ether *ue)
2005 {
2006         struct muge_softc *sc = uether_getsc(ue);
2007         struct ifnet *ifp = uether_getifp(ue);
2008
2009         MUGE_LOCK_ASSERT(sc, MA_OWNED);
2010
2011         ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
2012         sc->sc_flags &= ~MUGE_FLAG_LINK;
2013
2014         /*
2015          * stop all the transfers, if not already stopped:
2016          */
2017         usbd_transfer_stop(sc->sc_xfer[MUGE_BULK_DT_WR]);
2018         usbd_transfer_stop(sc->sc_xfer[MUGE_BULK_DT_RD]);
2019 }
2020
2021 /**
2022  *      muge_tick - Called periodically to monitor the state of the LAN95xx chip
2023  *      @ue: USB ether interface
2024  *
2025  *      Simply calls the mii status functions to check the state of the link.
2026  *
2027  *      LOCKING:
2028  *      Should be called with the MUGE lock held.
2029  */
2030 static void
2031 muge_tick(struct usb_ether *ue)
2032 {
2033
2034         struct muge_softc *sc = uether_getsc(ue);
2035         struct mii_data *mii = uether_getmii(&sc->sc_ue);
2036
2037         MUGE_LOCK_ASSERT(sc, MA_OWNED);
2038
2039         mii_tick(mii);
2040         if ((sc->sc_flags & MUGE_FLAG_LINK) == 0) {
2041                 lan78xx_miibus_statchg(ue->ue_dev);
2042                 if ((sc->sc_flags & MUGE_FLAG_LINK) != 0)
2043                         muge_start(ue);
2044         }
2045 }
2046
2047 /**
2048  *      muge_ifmedia_sts - Report current media status
2049  *      @ifp: inet interface pointer
2050  *      @ifmr: interface media request
2051  *
2052  *      Basically boilerplate code that simply calls the mii functions to get the
2053  *      media status.
2054  *
2055  *      LOCKING:
2056  *      Internally takes and releases the device lock.
2057  */
2058 static void
2059 muge_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
2060 {
2061         struct muge_softc *sc = ifp->if_softc;
2062         struct mii_data *mii = uether_getmii(&sc->sc_ue);
2063
2064         MUGE_LOCK(sc);
2065         mii_pollstat(mii);
2066         ifmr->ifm_active = mii->mii_media_active;
2067         ifmr->ifm_status = mii->mii_media_status;
2068         MUGE_UNLOCK(sc);
2069 }
2070
2071 /**
2072  *      muge_probe - Probe the interface.
2073  *      @dev: muge device handle
2074  *
2075  *      Checks if the device is a match for this driver.
2076  *
2077  *      RETURNS:
2078  *      Returns 0 on success or an error code on failure.
2079  */
2080 static int
2081 muge_probe(device_t dev)
2082 {
2083         struct usb_attach_arg *uaa = device_get_ivars(dev);
2084
2085         if (uaa->usb_mode != USB_MODE_HOST)
2086                 return (ENXIO);
2087         if (uaa->info.bConfigIndex != MUGE_CONFIG_INDEX)
2088                 return (ENXIO);
2089         if (uaa->info.bIfaceIndex != MUGE_IFACE_IDX)
2090                 return (ENXIO);
2091         return (usbd_lookup_id_by_uaa(lan78xx_devs, sizeof(lan78xx_devs), uaa));
2092 }
2093
2094 /**
2095  *      muge_attach - Attach the interface.
2096  *      @dev: muge device handle
2097  *
2098  *      Allocate softc structures, do ifmedia setup and ethernet/BPF attach.
2099  *
2100  *      RETURNS:
2101  *      Returns 0 on success or a negative error code.
2102  */
2103 static int
2104 muge_attach(device_t dev)
2105 {
2106         struct usb_attach_arg *uaa = device_get_ivars(dev);
2107         struct muge_softc *sc = device_get_softc(dev);
2108         struct usb_ether *ue = &sc->sc_ue;
2109         uint8_t iface_index;
2110         int err;
2111
2112         sc->sc_flags = USB_GET_DRIVER_INFO(uaa);
2113
2114         device_set_usb_desc(dev);
2115
2116         mtx_init(&sc->sc_mtx, device_get_nameunit(dev), NULL, MTX_DEF);
2117
2118         /* Setup the endpoints for the Microchip LAN78xx device(s) */
2119         iface_index = MUGE_IFACE_IDX;
2120         err = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer,
2121             muge_config, MUGE_N_TRANSFER, sc, &sc->sc_mtx);
2122         if (err) {
2123                 device_printf(dev, "error: allocating USB transfers failed\n");
2124                 goto detach;
2125         }
2126
2127         ue->ue_sc = sc;
2128         ue->ue_dev = dev;
2129         ue->ue_udev = uaa->device;
2130         ue->ue_mtx = &sc->sc_mtx;
2131         ue->ue_methods = &muge_ue_methods;
2132
2133         err = uether_ifattach(ue);
2134         if (err) {
2135                 device_printf(dev, "error: could not attach interface\n");
2136                 goto detach;
2137         }
2138         return (0);
2139
2140 detach:
2141         muge_detach(dev);
2142         return (ENXIO);
2143 }
2144
2145 /**
2146  *      muge_detach - Detach the interface.
2147  *      @dev: muge device handle
2148  *
2149  *      RETURNS:
2150  *      Returns 0.
2151  */
2152 static int
2153 muge_detach(device_t dev)
2154 {
2155
2156         struct muge_softc *sc = device_get_softc(dev);
2157         struct usb_ether *ue = &sc->sc_ue;
2158
2159         usbd_transfer_unsetup(sc->sc_xfer, MUGE_N_TRANSFER);
2160         uether_ifdetach(ue);
2161         mtx_destroy(&sc->sc_mtx);
2162
2163         return (0);
2164 }
2165
2166 static device_method_t muge_methods[] = {
2167         /* Device interface */
2168         DEVMETHOD(device_probe, muge_probe),
2169         DEVMETHOD(device_attach, muge_attach),
2170         DEVMETHOD(device_detach, muge_detach),
2171
2172         /* Bus interface */
2173         DEVMETHOD(bus_print_child, bus_generic_print_child),
2174         DEVMETHOD(bus_driver_added, bus_generic_driver_added),
2175
2176         /* MII interface */
2177         DEVMETHOD(miibus_readreg, lan78xx_miibus_readreg),
2178         DEVMETHOD(miibus_writereg, lan78xx_miibus_writereg),
2179         DEVMETHOD(miibus_statchg, lan78xx_miibus_statchg),
2180
2181         DEVMETHOD_END
2182 };
2183
2184 static driver_t muge_driver = {
2185         .name = "muge",
2186         .methods = muge_methods,
2187         .size = sizeof(struct muge_softc),
2188 };
2189
2190 static devclass_t muge_devclass;
2191
2192 DRIVER_MODULE(muge, uhub, muge_driver, muge_devclass, NULL, 0);
2193 DRIVER_MODULE(miibus, muge, miibus_driver, miibus_devclass, 0, 0);
2194 MODULE_DEPEND(muge, uether, 1, 1, 1);
2195 MODULE_DEPEND(muge, usb, 1, 1, 1);
2196 MODULE_DEPEND(muge, ether, 1, 1, 1);
2197 MODULE_DEPEND(muge, miibus, 1, 1, 1);
2198 MODULE_VERSION(muge, 1);
2199 USB_PNP_HOST_INFO(lan78xx_devs);