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