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