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