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