xref: /freebsd/sys/dev/usb/net/if_muge.c (revision 85732ac8)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (C) 2012 Ben Gray <bgray@freebsd.org>.
5  * Copyright (C) 2018 The FreeBSD Foundation.
6  *
7  * This software was developed by Arshan Khanifar <arshankhanifar@gmail.com>
8  * under sponsorship from the FreeBSD Foundation.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  * $FreeBSD$
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 /*
38  * USB-To-Ethernet adapter driver for Microchip's LAN78XX and related families.
39  *
40  * USB 3.1 to 10/100/1000 Mbps Ethernet
41  * LAN7800 http://www.microchip.com/wwwproducts/en/LAN7800
42  *
43  * USB 2.0 to 10/100/1000 Mbps Ethernet
44  * LAN7850 http://www.microchip.com/wwwproducts/en/LAN7850
45  *
46  * USB 2 to 10/100/1000 Mbps Ethernet with built-in USB hub
47  * LAN7515 (no datasheet available, but probes and functions as LAN7800)
48  *
49  * This driver is based on the if_smsc driver, with lan78xx-specific
50  * functionality modelled on Microchip's Linux lan78xx driver.
51  *
52  * UNIMPLEMENTED FEATURES
53  * ------------------
54  * A number of features supported by the lan78xx are not yet implemented in
55  * this driver:
56  *
57  * - RX/TX checksum offloading: Nothing has been implemented yet for
58  *   TX checksumming. RX checksumming works with ICMP messages, but is broken
59  *   for TCP/UDP packets.
60  * - Direct address translation filtering: Implemented but untested.
61  * - VLAN tag removal.
62  * - Support for USB interrupt endpoints.
63  * - Latency Tolerance Messaging (LTM) support.
64  * - TCP LSO support.
65  *
66  */
67 
68 #include <sys/param.h>
69 #include <sys/bus.h>
70 #include <sys/callout.h>
71 #include <sys/condvar.h>
72 #include <sys/kernel.h>
73 #include <sys/lock.h>
74 #include <sys/malloc.h>
75 #include <sys/module.h>
76 #include <sys/mutex.h>
77 #include <sys/priv.h>
78 #include <sys/queue.h>
79 #include <sys/random.h>
80 #include <sys/socket.h>
81 #include <sys/stddef.h>
82 #include <sys/stdint.h>
83 #include <sys/sx.h>
84 #include <sys/sysctl.h>
85 #include <sys/systm.h>
86 #include <sys/unistd.h>
87 
88 #include <net/if.h>
89 #include <net/if_var.h>
90 
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 #endif
101 
102 #include <dev/usb/usb.h>
103 #include <dev/usb/usbdi.h>
104 #include <dev/usb/usbdi_util.h>
105 #include "usbdevs.h"
106 
107 #define USB_DEBUG_VAR lan78xx_debug
108 #include <dev/usb/usb_debug.h>
109 #include <dev/usb/usb_process.h>
110 
111 #include <dev/usb/net/usb_ethernet.h>
112 
113 #include <dev/usb/net/if_mugereg.h>
114 
115 #ifdef USB_DEBUG
116 static int muge_debug = 0;
117 
118 SYSCTL_NODE(_hw_usb, OID_AUTO, muge, CTLFLAG_RW, 0,
119     "Microchip LAN78xx USB-GigE");
120 SYSCTL_INT(_hw_usb_muge, OID_AUTO, debug, CTLFLAG_RWTUN, &muge_debug, 0,
121     "Debug level");
122 #endif
123 
124 #define MUGE_DEFAULT_RX_CSUM_ENABLE (false)
125 #define MUGE_DEFAULT_TX_CSUM_ENABLE (false)
126 #define MUGE_DEFAULT_TSO_CSUM_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_ZERO(addr) \
154 	(!(addr[0] | addr[1] | addr[2] | addr[3] | addr[4] | addr[5]))
155 
156 #define ETHER_IS_VALID(addr) \
157 	(!ETHER_IS_MULTICAST(addr) && !ETHER_IS_ZERO(addr))
158 
159 /* USB endpoints. */
160 
161 enum {
162 	MUGE_BULK_DT_RD,
163 	MUGE_BULK_DT_WR,
164 #if 0 /* Ignore interrupt endpoints for now as we poll on MII status. */
165 	MUGE_INTR_DT_WR,
166 	MUGE_INTR_DT_RD,
167 #endif
168 	MUGE_N_TRANSFER,
169 };
170 
171 struct muge_softc {
172 	struct usb_ether	sc_ue;
173 	struct mtx		sc_mtx;
174 	struct usb_xfer		*sc_xfer[MUGE_N_TRANSFER];
175 	int			sc_phyno;
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(struct ifnet *);
217 static void muge_ifmedia_sts(struct ifnet *, struct ifmediareq *);
218 
219 static int lan78xx_chip_init(struct muge_softc *sc);
220 static int muge_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data);
221 
222 static const struct usb_config muge_config[MUGE_N_TRANSFER] = {
223 
224 	[MUGE_BULK_DT_WR] = {
225 		.type = UE_BULK,
226 		.endpoint = UE_ADDR_ANY,
227 		.direction = UE_DIR_OUT,
228 		.frames = 16,
229 		.bufsize = 16 * (MCLBYTES + 16),
230 		.flags = {.pipe_bof = 1,.force_short_xfer = 1,},
231 		.callback = muge_bulk_write_callback,
232 		.timeout = 10000,	/* 10 seconds */
233 	},
234 
235 	[MUGE_BULK_DT_RD] = {
236 		.type = UE_BULK,
237 		.endpoint = UE_ADDR_ANY,
238 		.direction = UE_DIR_IN,
239 		.bufsize = 20480,	/* bytes */
240 		.flags = {.pipe_bof = 1,.short_xfer_ok = 1,},
241 		.callback = muge_bulk_read_callback,
242 		.timeout = 0,	/* no timeout */
243 	},
244 	/*
245 	 * The chip supports interrupt endpoints, however they aren't
246 	 * needed as we poll on the MII status.
247 	 */
248 };
249 
250 static const struct usb_ether_methods muge_ue_methods = {
251 	.ue_attach_post = muge_attach_post,
252 	.ue_attach_post_sub = muge_attach_post_sub,
253 	.ue_start = muge_start,
254 	.ue_ioctl = muge_ioctl,
255 	.ue_init = muge_init,
256 	.ue_stop = muge_stop,
257 	.ue_tick = muge_tick,
258 	.ue_setmulti = muge_setmulti,
259 	.ue_setpromisc = muge_setpromisc,
260 	.ue_mii_upd = muge_ifmedia_upd,
261 	.ue_mii_sts = muge_ifmedia_sts,
262 };
263 
264 /**
265  *	lan78xx_read_reg - Read a 32-bit register on the device
266  *	@sc: driver soft context
267  *	@off: offset of the register
268  *	@data: pointer a value that will be populated with the register value
269  *
270  *	LOCKING:
271  *	The device lock must be held before calling this function.
272  *
273  *	RETURNS:
274  *	0 on success, a USB_ERR_?? error code on failure.
275  */
276 static int
277 lan78xx_read_reg(struct muge_softc *sc, uint32_t off, uint32_t *data)
278 {
279 	struct usb_device_request req;
280 	uint32_t buf;
281 	usb_error_t err;
282 
283 	MUGE_LOCK_ASSERT(sc, MA_OWNED);
284 
285 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
286 	req.bRequest = UVR_READ_REG;
287 	USETW(req.wValue, 0);
288 	USETW(req.wIndex, off);
289 	USETW(req.wLength, 4);
290 
291 	err = uether_do_request(&sc->sc_ue, &req, &buf, 1000);
292 	if (err != 0)
293 		muge_warn_printf(sc, "Failed to read register 0x%0x\n", off);
294 	*data = le32toh(buf);
295 	return (err);
296 }
297 
298 /**
299  *	lan78xx_write_reg - Write a 32-bit register on the device
300  *	@sc: driver soft context
301  *	@off: offset of the register
302  *	@data: the 32-bit value to write into the register
303  *
304  *	LOCKING:
305  *	The device lock must be held before calling this function.
306  *
307  *	RETURNS:
308  *	0 on success, a USB_ERR_?? error code on failure.
309  */
310 static int
311 lan78xx_write_reg(struct muge_softc *sc, uint32_t off, uint32_t data)
312 {
313 	struct usb_device_request req;
314 	uint32_t buf;
315 	usb_error_t err;
316 
317 	MUGE_LOCK_ASSERT(sc, MA_OWNED);
318 
319 	buf = htole32(data);
320 
321 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
322 	req.bRequest = UVR_WRITE_REG;
323 	USETW(req.wValue, 0);
324 	USETW(req.wIndex, off);
325 	USETW(req.wLength, 4);
326 
327 	err = uether_do_request(&sc->sc_ue, &req, &buf, 1000);
328 	if (err != 0)
329 		muge_warn_printf(sc, "Failed to write register 0x%0x\n", off);
330 	return (err);
331 }
332 
333 /**
334  *	lan78xx_wait_for_bits - Poll on a register value until bits are cleared
335  *	@sc: soft context
336  *	@reg: offset of the register
337  *	@bits: if the bits are clear the function returns
338  *
339  *	LOCKING:
340  *	The device lock must be held before calling this function.
341  *
342  *	RETURNS:
343  *	0 on success, or a USB_ERR_?? error code on failure.
344  */
345 static int
346 lan78xx_wait_for_bits(struct muge_softc *sc, uint32_t reg, uint32_t bits)
347 {
348 	usb_ticks_t start_ticks;
349 	const usb_ticks_t max_ticks = USB_MS_TO_TICKS(1000);
350 	uint32_t val;
351 	int err;
352 
353 	MUGE_LOCK_ASSERT(sc, MA_OWNED);
354 
355 	start_ticks = (usb_ticks_t)ticks;
356 	do {
357 		if ((err = lan78xx_read_reg(sc, reg, &val)) != 0)
358 			return (err);
359 		if (!(val & bits))
360 			return (0);
361 		uether_pause(&sc->sc_ue, hz / 100);
362 	} while (((usb_ticks_t)(ticks - start_ticks)) < max_ticks);
363 
364 	return (USB_ERR_TIMEOUT);
365 }
366 
367 /**
368  *	lan78xx_eeprom_read_raw - Read the attached EEPROM
369  *	@sc: soft context
370  *	@off: the eeprom address offset
371  *	@buf: stores the bytes
372  *	@buflen: the number of bytes to read
373  *
374  *	Simply reads bytes from an attached eeprom.
375  *
376  *	LOCKING:
377  *	The function takes and releases the device lock if not already held.
378  *
379  *	RETURNS:
380  *	0 on success, or a USB_ERR_?? error code on failure.
381  */
382 static int
383 lan78xx_eeprom_read_raw(struct muge_softc *sc, uint16_t off, uint8_t *buf,
384     uint16_t buflen)
385 {
386 	usb_ticks_t start_ticks;
387 	const usb_ticks_t max_ticks = USB_MS_TO_TICKS(1000);
388 	int err, locked;
389 	uint32_t val, saved;
390 	uint16_t i;
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 locked, err;
483 	uint32_t val;
484 	uint16_t i;
485 	locked = mtx_owned(&sc->sc_mtx);
486 	if (!locked)
487 		MUGE_LOCK(sc);
488 
489 	err = lan78xx_read_reg(sc, OTP_PWR_DN, &val);
490 
491 	/* Checking if bit is set. */
492 	if (val & OTP_PWR_DN_PWRDN_N) {
493 		/* Clear it, then wait for it to be cleared. */
494 		lan78xx_write_reg(sc, OTP_PWR_DN, 0);
495 		err = lan78xx_wait_for_bits(sc, OTP_PWR_DN, OTP_PWR_DN_PWRDN_N);
496 		if (err != 0) {
497 			muge_warn_printf(sc, "OTP off? failed to read data\n");
498 			goto done;
499 		}
500 	}
501 	/* Start reading the bytes, one at a time. */
502 	for (i = 0; i < buflen; i++) {
503 		err = lan78xx_write_reg(sc, OTP_ADDR1,
504 		    ((off + i) >> 8) & OTP_ADDR1_15_11);
505 		err = lan78xx_write_reg(sc, OTP_ADDR2,
506 		    ((off + i) & OTP_ADDR2_10_3));
507 		err = lan78xx_write_reg(sc, OTP_FUNC_CMD, OTP_FUNC_CMD_READ_);
508 		err = lan78xx_write_reg(sc, OTP_CMD_GO, OTP_CMD_GO_GO_);
509 
510 		err = lan78xx_wait_for_bits(sc, OTP_STATUS, OTP_STATUS_BUSY_);
511 		if (err != 0) {
512 			muge_warn_printf(sc, "OTP busy failed to read data\n");
513 			goto done;
514 		}
515 
516 		if ((err = lan78xx_read_reg(sc, OTP_RD_DATA, &val)) != 0)
517 			goto done;
518 
519 		buf[i] = (uint8_t)(val & 0xff);
520 	}
521 
522 done:
523 	if (!locked)
524 		MUGE_UNLOCK(sc);
525 	return (err);
526 }
527 
528 /**
529  *	lan78xx_otp_read
530  *	@sc: soft context
531  *	@off: the otp address offset
532  *	@buf: stores the bytes
533  *	@buflen: the number of bytes to read
534  *
535  *	Simply reads bytes from the otp.
536  *
537  *	LOCKING:
538  *	The function takes and releases device lock if it is not already held.
539  *
540  *	RETURNS:
541  *	0 on success, or a USB_ERR_?? error code on failure.
542  */
543 static int
544 lan78xx_otp_read(struct muge_softc *sc, uint16_t off, uint8_t *buf,
545     uint16_t buflen)
546 {
547 	uint8_t sig;
548 	int err;
549 
550 	err = lan78xx_otp_read_raw(sc, OTP_INDICATOR_OFFSET, &sig, 1);
551 	if (err == 0) {
552 		if (sig == OTP_INDICATOR_1) {
553 		} else if (sig == OTP_INDICATOR_2) {
554 			off += 0x100; /* XXX */
555 		} else {
556 			err = -EINVAL;
557 		}
558 		if (!err)
559 			err = lan78xx_otp_read_raw(sc, off, buf, buflen);
560 	}
561 	return (err);
562 }
563 
564 /**
565  *	lan78xx_setmacaddress - Set the mac address in the device
566  *	@sc: driver soft context
567  *	@addr: pointer to array contain at least 6 bytes of the mac
568  *
569  *	LOCKING:
570  *	Should be called with the MUGE lock held.
571  *
572  *	RETURNS:
573  *	Returns 0 on success or a negative error code.
574  */
575 static int
576 lan78xx_setmacaddress(struct muge_softc *sc, const uint8_t *addr)
577 {
578 	int err;
579 	uint32_t val;
580 
581 	muge_dbg_printf(sc,
582 	    "setting mac address to %02x:%02x:%02x:%02x:%02x:%02x\n",
583 	    addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
584 
585 	MUGE_LOCK_ASSERT(sc, MA_OWNED);
586 
587 	val = (addr[3] << 24) | (addr[2] << 16) | (addr[1] << 8) | addr[0];
588 	if ((err = lan78xx_write_reg(sc, ETH_RX_ADDRL, val)) != 0)
589 		goto done;
590 
591 	val = (addr[5] << 8) | addr[4];
592 	err = lan78xx_write_reg(sc, ETH_RX_ADDRH, val);
593 
594 done:
595 	return (err);
596 }
597 
598 /**
599  *	lan78xx_set_rx_max_frame_length
600  *	@sc: driver soft context
601  *	@size: pointer to array contain at least 6 bytes of the mac
602  *
603  *	Sets the maximum frame length to be received. Frames bigger than
604  *	this size are aborted.
605  *
606  *	RETURNS:
607  *	Returns 0 on success or a negative error code.
608  */
609 static int
610 lan78xx_set_rx_max_frame_length(struct muge_softc *sc, int size)
611 {
612 	int err = 0;
613 	uint32_t buf;
614 	bool rxenabled;
615 
616 	/* First we have to disable rx before changing the length. */
617 	err = 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 		err = 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 	err = 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 		err = 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 	int locked;
659 	uint32_t addr, val;
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 	int locked;
712 	uint32_t addr;
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 	struct ifnet *ifp;
759 	int locked;
760 	int err;
761 	uint32_t flow = 0;
762 	uint32_t fct_flow = 0;
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 	    (ifp->if_drv_flags & 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;
893 	usb_ticks_t start_ticks;
894 	const usb_ticks_t max_ticks = USB_MS_TO_TICKS(1000);
895 
896 	MUGE_LOCK_ASSERT(sc, MA_OWNED);
897 
898 	/* Reset phy and wait for reset to complete. */
899 	lan78xx_miibus_writereg(sc->sc_ue.ue_dev, sc->sc_phyno, MII_BMCR,
900 	    BMCR_RESET);
901 
902 	start_ticks = ticks;
903 	do {
904 		uether_pause(&sc->sc_ue, hz / 100);
905 		bmcr = lan78xx_miibus_readreg(sc->sc_ue.ue_dev, sc->sc_phyno,
906 		    MII_BMCR);
907 	} while ((bmcr & BMCR_RESET) && ((ticks - start_ticks) < max_ticks));
908 
909 	if (((usb_ticks_t)(ticks - start_ticks)) >= max_ticks) {
910 		muge_err_printf(sc, "PHY reset timed-out\n");
911 		return (EIO);
912 	}
913 
914 	/* Setup phy to interrupt upon link down or autoneg completion. */
915 	lan78xx_miibus_readreg(sc->sc_ue.ue_dev, sc->sc_phyno,
916 	    MUGE_PHY_INTR_STAT);
917 	lan78xx_miibus_writereg(sc->sc_ue.ue_dev, sc->sc_phyno,
918 	    MUGE_PHY_INTR_MASK,
919 	    (MUGE_PHY_INTR_ANEG_COMP | MUGE_PHY_INTR_LINK_CHANGE));
920 
921 	/* Enable Auto-MDIX for crossover and polarity detection. */
922 	lan78xx_set_mdix_auto(sc);
923 
924 	/* Enable all modes. */
925 	lan78xx_miibus_writereg(sc->sc_ue.ue_dev, sc->sc_phyno, MII_ANAR,
926 	    ANAR_10 | ANAR_10_FD | ANAR_TX | ANAR_TX_FD |
927 	    ANAR_CSMA | ANAR_FC | ANAR_PAUSE_ASYM);
928 
929 	/* Restart auto-negotation. */
930 	bmcr |= BMCR_STARTNEG;
931 	bmcr |= BMCR_AUTOEN;
932 	lan78xx_miibus_writereg(sc->sc_ue.ue_dev, sc->sc_phyno, MII_BMCR, bmcr);
933 	bmcr = lan78xx_miibus_readreg(sc->sc_ue.ue_dev, sc->sc_phyno, MII_BMCR);
934 	return (0);
935 }
936 
937 /**
938  *	lan78xx_chip_init - Initialises the chip after power on
939  *	@sc: driver soft context
940  *
941  *	This initialisation sequence is modelled on the procedure in the Linux
942  *	driver.
943  *
944  *	RETURNS:
945  *	Returns 0 on success or an error code on failure.
946  */
947 static int
948 lan78xx_chip_init(struct muge_softc *sc)
949 {
950 	int err;
951 	uint32_t buf;
952 	uint32_t burst_cap;
953 
954 	MUGE_LOCK_ASSERT(sc, MA_OWNED);
955 
956 	/* Enter H/W config mode. */
957 	lan78xx_write_reg(sc, ETH_HW_CFG, ETH_HW_CFG_LRST_);
958 
959 	if ((err = lan78xx_wait_for_bits(sc, ETH_HW_CFG, ETH_HW_CFG_LRST_)) !=
960 	    0) {
961 		muge_warn_printf(sc,
962 		    "timed-out waiting for lite reset to complete\n");
963 		goto init_failed;
964 	}
965 
966 	/* Set the mac address. */
967 	if ((err = lan78xx_setmacaddress(sc, sc->sc_ue.ue_eaddr)) != 0) {
968 		muge_warn_printf(sc, "failed to set the MAC address\n");
969 		goto init_failed;
970 	}
971 
972 	/* Read and display the revision register. */
973 	if ((err = lan78xx_read_reg(sc, ETH_ID_REV, &buf)) < 0) {
974 		muge_warn_printf(sc, "failed to read ETH_ID_REV (err = %d)\n",
975 		    err);
976 		goto init_failed;
977 	}
978 	sc->chipid = (buf & ETH_ID_REV_CHIP_ID_MASK_) >> 16;
979 	sc->chiprev = buf & ETH_ID_REV_CHIP_REV_MASK_;
980 	switch (sc->chipid) {
981 	case ETH_ID_REV_CHIP_ID_7800_:
982 	case ETH_ID_REV_CHIP_ID_7850_:
983 		break;
984 	default:
985 		muge_warn_printf(sc, "Chip ID 0x%04x not yet supported\n",
986 		    sc->chipid);
987 		goto init_failed;
988 	}
989 	device_printf(sc->sc_ue.ue_dev, "Chip ID 0x%04x rev %04x\n", sc->chipid,
990 	    sc->chiprev);
991 
992 	/* Respond to BULK-IN tokens with a NAK when RX FIFO is empty. */
993 	if ((err = lan78xx_read_reg(sc, ETH_USB_CFG0, &buf)) != 0) {
994 		muge_warn_printf(sc, "failed to read ETH_USB_CFG0 (err=%d)\n", err);
995 		goto init_failed;
996 	}
997 	buf |= ETH_USB_CFG_BIR_;
998 	lan78xx_write_reg(sc, ETH_USB_CFG0, buf);
999 
1000 	/*
1001 	 * XXX LTM support will go here.
1002 	 */
1003 
1004 	/* Configuring the burst cap. */
1005 	switch (usbd_get_speed(sc->sc_ue.ue_udev)) {
1006 	case USB_SPEED_SUPER:
1007 		burst_cap = MUGE_DEFAULT_BURST_CAP_SIZE/MUGE_SS_USB_PKT_SIZE;
1008 		break;
1009 	case USB_SPEED_HIGH:
1010 		burst_cap = MUGE_DEFAULT_BURST_CAP_SIZE/MUGE_HS_USB_PKT_SIZE;
1011 		break;
1012 	default:
1013 		burst_cap = MUGE_DEFAULT_BURST_CAP_SIZE/MUGE_FS_USB_PKT_SIZE;
1014 	}
1015 
1016 	lan78xx_write_reg(sc, ETH_BURST_CAP, burst_cap);
1017 
1018 	/* Set the default bulk in delay (same value from Linux driver). */
1019 	lan78xx_write_reg(sc, ETH_BULK_IN_DLY, MUGE_DEFAULT_BULK_IN_DELAY);
1020 
1021 	/* Multiple ethernet frames per USB packets. */
1022 	err = lan78xx_read_reg(sc, ETH_HW_CFG, &buf);
1023 	buf |= ETH_HW_CFG_MEF_;
1024 	err = lan78xx_write_reg(sc, ETH_HW_CFG, buf);
1025 
1026 	/* Enable burst cap. */
1027 	if ((err = lan78xx_read_reg(sc, ETH_USB_CFG0, &buf)) < 0) {
1028 		muge_warn_printf(sc, "failed to read ETH_USB_CFG0 (err=%d)\n",
1029 		    err);
1030 		goto init_failed;
1031 	}
1032 	buf |= ETH_USB_CFG_BCE_;
1033 	err = lan78xx_write_reg(sc, ETH_USB_CFG0, buf);
1034 
1035 	/*
1036 	 * Set FCL's RX and TX FIFO sizes: according to data sheet this is
1037 	 * already the default value. But we initialize it to the same value
1038 	 * anyways, as that's what the Linux driver does.
1039 	 *
1040 	 */
1041 	buf = (MUGE_MAX_RX_FIFO_SIZE - 512) / 512;
1042 	err = lan78xx_write_reg(sc, ETH_FCT_RX_FIFO_END, buf);
1043 
1044 	buf = (MUGE_MAX_TX_FIFO_SIZE - 512) / 512;
1045 	err = lan78xx_write_reg(sc, ETH_FCT_TX_FIFO_END, buf);
1046 
1047 	/* Enabling interrupts. (Not using them for now) */
1048 	err = lan78xx_write_reg(sc, ETH_INT_STS, ETH_INT_STS_CLEAR_ALL_);
1049 
1050 	/*
1051 	 * Initializing flow control registers to 0.  These registers are
1052 	 * properly set is handled in link-reset function in the Linux driver.
1053 	 */
1054 	err = lan78xx_write_reg(sc, ETH_FLOW, 0);
1055 	err = lan78xx_write_reg(sc, ETH_FCT_FLOW, 0);
1056 
1057 	/*
1058 	 * Settings for the RFE, we enable broadcast and destination address
1059 	 * perfect filtering.
1060 	 */
1061 	err = lan78xx_read_reg(sc, ETH_RFE_CTL, &buf);
1062 	buf |= ETH_RFE_CTL_BCAST_EN_ | ETH_RFE_CTL_DA_PERFECT_;
1063 	err = lan78xx_write_reg(sc, ETH_RFE_CTL, buf);
1064 
1065 	/*
1066 	 * At this point the Linux driver writes multicast tables, and enables
1067 	 * checksum engines. But in FreeBSD that gets done in muge_init,
1068 	 * which gets called when the interface is brought up.
1069 	 */
1070 
1071 	/* Reset the PHY. */
1072 	lan78xx_write_reg(sc, ETH_PMT_CTL, ETH_PMT_CTL_PHY_RST_);
1073 	if ((err = lan78xx_wait_for_bits(sc, ETH_PMT_CTL,
1074 	    ETH_PMT_CTL_PHY_RST_)) != 0) {
1075 		muge_warn_printf(sc,
1076 		    "timed-out waiting for phy reset to complete\n");
1077 		goto init_failed;
1078 	}
1079 
1080 	err = lan78xx_read_reg(sc, ETH_MAC_CR, &buf);
1081 	if (sc->chipid == ETH_ID_REV_CHIP_ID_7800_ &&
1082 	    !lan78xx_eeprom_present(sc)) {
1083 		/* Set automatic duplex and speed on LAN7800 without EEPROM. */
1084 		buf |= ETH_MAC_CR_AUTO_DUPLEX_ | ETH_MAC_CR_AUTO_SPEED_;
1085 	}
1086 	err = lan78xx_write_reg(sc, ETH_MAC_CR, buf);
1087 
1088 	/*
1089 	 * Enable PHY interrupts (Not really getting used for now)
1090 	 * ETH_INT_EP_CTL: interrupt endpoint control register
1091 	 * phy events cause interrupts to be issued
1092 	 */
1093 	err = lan78xx_read_reg(sc, ETH_INT_EP_CTL, &buf);
1094 	buf |= ETH_INT_ENP_PHY_INT;
1095 	err = lan78xx_write_reg(sc, ETH_INT_EP_CTL, buf);
1096 
1097 	/*
1098 	 * Enables mac's transmitter.  It will transmit frames from the buffer
1099 	 * onto the cable.
1100 	 */
1101 	err = lan78xx_read_reg(sc, ETH_MAC_TX, &buf);
1102 	buf |= ETH_MAC_TX_TXEN_;
1103 	err = lan78xx_write_reg(sc, ETH_MAC_TX, buf);
1104 
1105 	/* FIFO is capable of transmitting frames to MAC. */
1106 	err = lan78xx_read_reg(sc, ETH_FCT_TX_CTL, &buf);
1107 	buf |= ETH_FCT_TX_CTL_EN_;
1108 	err = lan78xx_write_reg(sc, ETH_FCT_TX_CTL, buf);
1109 
1110 	/*
1111 	 * Set max frame length.  In linux this is dev->mtu (which by default
1112 	 * is 1500) + VLAN_ETH_HLEN = 1518.
1113 	 */
1114 	err = lan78xx_set_rx_max_frame_length(sc, ETHER_MAX_LEN);
1115 
1116 	/* Initialise the PHY. */
1117 	if ((err = lan78xx_phy_init(sc)) != 0)
1118 		goto init_failed;
1119 
1120 	/* Enable MAC RX. */
1121 	err = lan78xx_read_reg(sc, ETH_MAC_RX, &buf);
1122 	buf |= ETH_MAC_RX_EN_;
1123 	err = lan78xx_write_reg(sc, ETH_MAC_RX, buf);
1124 
1125 	/* Enable FIFO controller RX. */
1126 	err = lan78xx_read_reg(sc, ETH_FCT_RX_CTL, &buf);
1127 	buf |= ETH_FCT_TX_CTL_EN_;
1128 	err = lan78xx_write_reg(sc, ETH_FCT_RX_CTL, buf);
1129 
1130 	sc->sc_flags |= MUGE_FLAG_INIT_DONE;
1131 	return (0);
1132 
1133 init_failed:
1134 	muge_err_printf(sc, "lan78xx_chip_init failed (err=%d)\n", err);
1135 	return (err);
1136 }
1137 
1138 static void
1139 muge_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error)
1140 {
1141 	struct muge_softc *sc = usbd_xfer_softc(xfer);
1142 	struct usb_ether *ue = &sc->sc_ue;
1143 	struct ifnet *ifp = uether_getifp(ue);
1144 	struct mbuf *m;
1145 	struct usb_page_cache *pc;
1146 	uint16_t pktlen;
1147 	uint32_t rx_cmd_a, rx_cmd_b;
1148 	uint16_t rx_cmd_c;
1149 	int off;
1150 	int actlen;
1151 
1152 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
1153 	muge_dbg_printf(sc, "rx : actlen %d\n", actlen);
1154 
1155 	switch (USB_GET_STATE(xfer)) {
1156 	case USB_ST_TRANSFERRED:
1157 
1158 		/*
1159 		 * There is always a zero length frame after bringing the
1160 		 * interface up.
1161 		 */
1162 		if (actlen < (sizeof(rx_cmd_a) + ETHER_CRC_LEN))
1163 			goto tr_setup;
1164 
1165 		/*
1166 		 * There may be multiple packets in the USB frame.  Each will
1167 		 * have a header and each needs to have its own mbuf allocated
1168 		 * and populated for it.
1169 		 */
1170 		pc = usbd_xfer_get_frame(xfer, 0);
1171 		off = 0;
1172 
1173 		while (off < actlen) {
1174 
1175 			/* The frame header is aligned on a 4 byte boundary. */
1176 			off = ((off + 0x3) & ~0x3);
1177 
1178 			/* Extract RX CMD A. */
1179 			if (off + sizeof(rx_cmd_a) > actlen)
1180 				goto tr_setup;
1181 			usbd_copy_out(pc, off, &rx_cmd_a, sizeof(rx_cmd_a));
1182 			off += (sizeof(rx_cmd_a));
1183 			rx_cmd_a = le32toh(rx_cmd_a);
1184 
1185 
1186 			/* Extract RX CMD B. */
1187 			if (off + sizeof(rx_cmd_b) > actlen)
1188 				goto tr_setup;
1189 			usbd_copy_out(pc, off, &rx_cmd_b, sizeof(rx_cmd_b));
1190 			off += (sizeof(rx_cmd_b));
1191 			rx_cmd_b = le32toh(rx_cmd_b);
1192 
1193 
1194 			/* Extract RX CMD C. */
1195 			if (off + sizeof(rx_cmd_c) > actlen)
1196 				goto tr_setup;
1197 			usbd_copy_out(pc, off, &rx_cmd_c, sizeof(rx_cmd_c));
1198 			off += (sizeof(rx_cmd_c));
1199 			rx_cmd_c = le16toh(rx_cmd_c);
1200 
1201 			if (off > actlen)
1202 				goto tr_setup;
1203 
1204 			pktlen = (rx_cmd_a & RX_CMD_A_LEN_MASK_);
1205 
1206 			muge_dbg_printf(sc,
1207 			    "rx_cmd_a 0x%08x rx_cmd_b 0x%08x rx_cmd_c 0x%04x "
1208 			    " pktlen %d actlen %d off %d\n",
1209 			    rx_cmd_a, rx_cmd_b, rx_cmd_c, pktlen, actlen, off);
1210 
1211 			if (rx_cmd_a & RX_CMD_A_RED_) {
1212 				muge_dbg_printf(sc,
1213 				     "rx error (hdr 0x%08x)\n", rx_cmd_a);
1214 				if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
1215 			} else {
1216 				/* Ethernet frame too big or too small? */
1217 				if ((pktlen < ETHER_HDR_LEN) ||
1218 				    (pktlen > (actlen - off)))
1219 					goto tr_setup;
1220 
1221 				/* Create a new mbuf to store the packet. */
1222 				m = uether_newbuf();
1223 				if (m == NULL) {
1224 					muge_warn_printf(sc,
1225 					    "failed to create new mbuf\n");
1226 					if_inc_counter(ifp, IFCOUNTER_IQDROPS,
1227 					    1);
1228 					goto tr_setup;
1229 				}
1230 
1231 				usbd_copy_out(pc, off, mtod(m, uint8_t *),
1232 				    pktlen);
1233 
1234 				/*
1235 				 * Check if RX checksums are computed, and
1236 				 * offload them
1237 				 */
1238 				if ((ifp->if_capabilities & IFCAP_RXCSUM) &&
1239 				    !(rx_cmd_a & RX_CMD_A_ICSM_)) {
1240 					struct ether_header *eh;
1241 					eh = mtod(m, struct ether_header *);
1242 					/*
1243 					 * Remove the extra 2 bytes of the csum
1244 					 *
1245 					 * The checksum appears to be
1246 					 * simplistically calculated over the
1247 					 * protocol headers up to the end of the
1248 					 * eth frame.  Which means if the eth
1249 					 * frame is padded the csum calculation
1250 					 * is incorrectly performed over the
1251 					 * padding bytes as well.  Therefore to
1252 					 * be safe we ignore the H/W csum on
1253 					 * frames less than or equal to
1254 					 * 64 bytes.
1255 					 *
1256 					 * Protocols checksummed:
1257 					 * TCP, UDP, ICMP, IGMP, IP
1258 					 */
1259 					if (pktlen > ETHER_MIN_LEN) {
1260 						m->m_pkthdr.csum_flags |=
1261 						    CSUM_DATA_VALID;
1262 
1263 						/*
1264 						 * Copy the checksum from the
1265 						 * last 2 bytes of the transfer
1266 						 * and put in the csum_data
1267 						 * field.
1268 						 */
1269 						usbd_copy_out(pc,
1270 						    (off + pktlen),
1271 						    &m->m_pkthdr.csum_data, 2);
1272 
1273 						/*
1274 						 * The data is copied in network
1275 						 * order, but the csum algorithm
1276 						 * in the kernel expects it to
1277 						 * be in host network order.
1278 						 */
1279 						m->m_pkthdr.csum_data =
1280 						   ntohs(m->m_pkthdr.csum_data);
1281 
1282 						muge_dbg_printf(sc,
1283 						    "RX checksum offloaded (0x%04x)\n",
1284 						    m->m_pkthdr.csum_data);
1285 					}
1286 				}
1287 
1288 				/* Enqueue the mbuf on the receive queue. */
1289 				if (pktlen < (4 + ETHER_HDR_LEN)) {
1290 					m_freem(m);
1291 					goto tr_setup;
1292 				}
1293 				/* Remove 4 trailing bytes */
1294 				uether_rxmbuf(ue, m, pktlen - 4);
1295 			}
1296 
1297 			/*
1298 			 * Update the offset to move to the next potential
1299 			 * packet.
1300 			 */
1301 			off += pktlen;
1302 		}
1303 
1304 		/* FALLTHROUGH */
1305 	case USB_ST_SETUP:
1306 tr_setup:
1307 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
1308 		usbd_transfer_submit(xfer);
1309 		uether_rxflush(ue);
1310 		return;
1311 
1312 	default:
1313 		if (error != USB_ERR_CANCELLED) {
1314 			muge_warn_printf(sc, "bulk read error, %s\n",
1315 			    usbd_errstr(error));
1316 			usbd_xfer_set_stall(xfer);
1317 			goto tr_setup;
1318 		}
1319 		return;
1320 	}
1321 }
1322 
1323 /**
1324  *	muge_bulk_write_callback - Write callback used to send ethernet frame(s)
1325  *	@xfer: the USB transfer
1326  *	@error: error code if the transfers is in an errored state
1327  *
1328  *	The main write function that pulls ethernet frames off the queue and
1329  *	sends them out.
1330  *
1331  */
1332 static void
1333 muge_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error)
1334 {
1335 	struct muge_softc *sc = usbd_xfer_softc(xfer);
1336 	struct ifnet *ifp = uether_getifp(&sc->sc_ue);
1337 	struct usb_page_cache *pc;
1338 	struct mbuf *m;
1339 	int nframes;
1340 	uint32_t frm_len = 0, tx_cmd_a = 0, tx_cmd_b = 0;
1341 
1342 	switch (USB_GET_STATE(xfer)) {
1343 	case USB_ST_TRANSFERRED:
1344 		muge_dbg_printf(sc,
1345 		    "USB TRANSFER status: USB_ST_TRANSFERRED\n");
1346 		ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1347 		/* FALLTHROUGH */
1348 	case USB_ST_SETUP:
1349 		muge_dbg_printf(sc, "USB TRANSFER status: USB_ST_SETUP\n");
1350 tr_setup:
1351 		if ((sc->sc_flags & MUGE_FLAG_LINK) == 0 ||
1352 			(ifp->if_drv_flags & IFF_DRV_OACTIVE) != 0) {
1353 			muge_dbg_printf(sc,
1354 			    "sc->sc_flags & MUGE_FLAG_LINK: %d\n",
1355 			    (sc->sc_flags & MUGE_FLAG_LINK));
1356 			muge_dbg_printf(sc,
1357 			    "ifp->if_drv_flags & IFF_DRV_OACTIVE: %d\n",
1358 			    (ifp->if_drv_flags & IFF_DRV_OACTIVE));
1359 			muge_dbg_printf(sc,
1360 			    "USB TRANSFER not sending: no link or controller is busy \n");
1361 			/*
1362 			 * Don't send anything if there is no link or
1363 			 * controller is busy.
1364 			 */
1365 			return;
1366 		}
1367 		for (nframes = 0; nframes < 16 &&
1368 		    !IFQ_DRV_IS_EMPTY(&ifp->if_snd); nframes++) {
1369 			IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
1370 			if (m == NULL)
1371 				break;
1372 			usbd_xfer_set_frame_offset(xfer, nframes * MCLBYTES,
1373 				nframes);
1374 			frm_len = 0;
1375 			pc = usbd_xfer_get_frame(xfer, nframes);
1376 
1377 			/*
1378 			 * Each frame is prefixed with two 32-bit values
1379 			 * describing the length of the packet and buffer.
1380 			 */
1381 			tx_cmd_a = (m->m_pkthdr.len & TX_CMD_A_LEN_MASK_) |
1382 			     TX_CMD_A_FCS_;
1383 			tx_cmd_a = htole32(tx_cmd_a);
1384 			usbd_copy_in(pc, 0, &tx_cmd_a, sizeof(tx_cmd_a));
1385 
1386 			tx_cmd_b = 0;
1387 
1388 			/* TCP LSO Support will probably be implemented here. */
1389 			tx_cmd_b = htole32(tx_cmd_b);
1390 			usbd_copy_in(pc, 4, &tx_cmd_b, sizeof(tx_cmd_b));
1391 
1392 			frm_len += 8;
1393 
1394 			/* Next copy in the actual packet */
1395 			usbd_m_copy_in(pc, frm_len, m, 0, m->m_pkthdr.len);
1396 			frm_len += m->m_pkthdr.len;
1397 
1398 			if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
1399 
1400 			/*
1401 			 * If there's a BPF listener, bounce a copy of this
1402 			 * frame to it.
1403 			 */
1404 			BPF_MTAP(ifp, m);
1405 			m_freem(m);
1406 
1407 			/* Set frame length. */
1408 			usbd_xfer_set_frame_len(xfer, nframes, frm_len);
1409 		}
1410 
1411 		muge_dbg_printf(sc, "USB TRANSFER nframes: %d\n", nframes);
1412 		if (nframes != 0) {
1413 			muge_dbg_printf(sc, "USB TRANSFER submit attempt\n");
1414 			usbd_xfer_set_frames(xfer, nframes);
1415 			usbd_transfer_submit(xfer);
1416 			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1417 		}
1418 		return;
1419 
1420 	default:
1421 		if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
1422 		ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1423 
1424 		if (error != USB_ERR_CANCELLED) {
1425 			muge_err_printf(sc,
1426 			    "usb error on tx: %s\n", usbd_errstr(error));
1427 			usbd_xfer_set_stall(xfer);
1428 			goto tr_setup;
1429 		}
1430 		return;
1431 	}
1432 }
1433 
1434 #ifdef FDT
1435 /**
1436  *	muge_fdt_find_eth_node - find descendant node with required compatibility
1437  *	@start: start node
1438  *	@compatible: compatible string used to identify the node
1439  *
1440  *	Loop through all descendant nodes and return first match with required
1441  *	compatibility.
1442  *
1443  *	RETURNS:
1444  *	Returns node's phandle on success -1 otherwise
1445  */
1446 static phandle_t
1447 muge_fdt_find_eth_node(phandle_t start, const char *compatible)
1448 {
1449 	phandle_t child, node;
1450 
1451 	/* Traverse through entire tree to find usb ethernet nodes. */
1452 	for (node = OF_child(start); node != 0; node = OF_peer(node)) {
1453 		if (ofw_bus_node_is_compatible(node, compatible))
1454 			return (node);
1455 		child = muge_fdt_find_eth_node(node, compatible);
1456 		if (child != -1)
1457 			return (child);
1458 	}
1459 
1460 	return (-1);
1461 }
1462 
1463 /**
1464  *	muge_fdt_read_mac_property - read MAC address from node
1465  *	@node: USB device node
1466  *	@mac: memory to store MAC address to
1467  *
1468  *	Check for common properties that might contain MAC address
1469  *	passed by boot loader.
1470  *
1471  *	RETURNS:
1472  *	Returns 0 on success, error code otherwise
1473  */
1474 static int
1475 muge_fdt_read_mac_property(phandle_t node, unsigned char *mac)
1476 {
1477 	int len;
1478 
1479 	/* Check if there is property */
1480 	if ((len = OF_getproplen(node, "local-mac-address")) > 0) {
1481 		if (len != ETHER_ADDR_LEN)
1482 			return (EINVAL);
1483 
1484 		OF_getprop(node, "local-mac-address", mac,
1485 		    ETHER_ADDR_LEN);
1486 		return (0);
1487 	}
1488 
1489 	if ((len = OF_getproplen(node, "mac-address")) > 0) {
1490 		if (len != ETHER_ADDR_LEN)
1491 			return (EINVAL);
1492 
1493 		OF_getprop(node, "mac-address", mac,
1494 		    ETHER_ADDR_LEN);
1495 		return (0);
1496 	}
1497 
1498 	return (ENXIO);
1499 }
1500 
1501 /**
1502  *	muge_fdt_find_mac - read MAC address from node
1503  *	@compatible: compatible string for DTB node in the form "usb[N]NNN,[M]MMM"
1504  *	    where NNN is vendor id and MMM is product id
1505  *	@mac: memory to store MAC address to
1506  *
1507  *	Tries to find matching node in DTS and obtain MAC address info from it
1508  *
1509  *	RETURNS:
1510  *	Returns 0 on success, error code otherwise
1511  */
1512 static int
1513 muge_fdt_find_mac(const char *compatible, unsigned char *mac)
1514 {
1515 	phandle_t node, root;
1516 
1517 	root = OF_finddevice("/");
1518 	node = muge_fdt_find_eth_node(root, compatible);
1519 	if (node != -1) {
1520 		if (muge_fdt_read_mac_property(node, mac) == 0)
1521 			return (0);
1522 	}
1523 
1524 	return (ENXIO);
1525 }
1526 #endif
1527 
1528 /**
1529  *	muge_set_mac_addr - Initiailizes NIC MAC address
1530  *	@ue: the USB ethernet device
1531  *
1532  *	Tries to obtain MAC address from number of sources: registers,
1533  *	EEPROM, DTB blob. If all sources fail - generates random MAC.
1534  */
1535 static void
1536 muge_set_mac_addr(struct usb_ether *ue)
1537 {
1538 	struct muge_softc *sc = uether_getsc(ue);
1539 	uint32_t mac_h, mac_l;
1540 #ifdef FDT
1541 	char compatible[16];
1542 	struct usb_attach_arg *uaa = device_get_ivars(ue->ue_dev);
1543 #endif
1544 
1545 	memset(sc->sc_ue.ue_eaddr, 0xff, ETHER_ADDR_LEN);
1546 
1547 	uint32_t val;
1548 	lan78xx_read_reg(sc, 0, &val);
1549 
1550 	/* Read current MAC address from RX_ADDRx registers. */
1551 	if ((lan78xx_read_reg(sc, ETH_RX_ADDRL, &mac_l) == 0) &&
1552 	    (lan78xx_read_reg(sc, ETH_RX_ADDRH, &mac_h) == 0)) {
1553 		sc->sc_ue.ue_eaddr[5] = (uint8_t)((mac_h >> 8) & 0xff);
1554 		sc->sc_ue.ue_eaddr[4] = (uint8_t)((mac_h) & 0xff);
1555 		sc->sc_ue.ue_eaddr[3] = (uint8_t)((mac_l >> 24) & 0xff);
1556 		sc->sc_ue.ue_eaddr[2] = (uint8_t)((mac_l >> 16) & 0xff);
1557 		sc->sc_ue.ue_eaddr[1] = (uint8_t)((mac_l >> 8) & 0xff);
1558 		sc->sc_ue.ue_eaddr[0] = (uint8_t)((mac_l) & 0xff);
1559 	}
1560 
1561 	/* If RX_ADDRx did not provide a valid MAC address, try EEPROM. */
1562 	if (ETHER_IS_VALID(sc->sc_ue.ue_eaddr)) {
1563 		muge_dbg_printf(sc, "MAC assigned from registers\n");
1564 		return;
1565 	}
1566 
1567 	if ((lan78xx_eeprom_present(sc) &&
1568 	    lan78xx_eeprom_read_raw(sc, ETH_E2P_MAC_OFFSET,
1569 	    sc->sc_ue.ue_eaddr, ETHER_ADDR_LEN) == 0) ||
1570 	    (lan78xx_otp_read(sc, OTP_MAC_OFFSET,
1571 	    sc->sc_ue.ue_eaddr, ETHER_ADDR_LEN) == 0)) {
1572 		if (ETHER_IS_VALID(sc->sc_ue.ue_eaddr)) {
1573 			muge_dbg_printf(sc, "MAC read from EEPROM\n");
1574 			return;
1575 		}
1576 	}
1577 
1578 #ifdef FDT
1579 	snprintf(compatible, sizeof(compatible), "usb%x,%x",
1580 	    uaa->info.idVendor, uaa->info.idProduct);
1581 	if (muge_fdt_find_mac(compatible, sc->sc_ue.ue_eaddr) == 0) {
1582 		muge_dbg_printf(sc, "MAC assigned from FDT blob\n");
1583 		return;
1584 	}
1585 #endif
1586 
1587 	muge_dbg_printf(sc, "MAC assigned randomly\n");
1588 	arc4rand(sc->sc_ue.ue_eaddr, ETHER_ADDR_LEN, 0);
1589 	sc->sc_ue.ue_eaddr[0] &= ~0x01;	/* unicast */
1590 	sc->sc_ue.ue_eaddr[0] |= 0x02;	/* locally administered */
1591 }
1592 
1593 /**
1594  *	muge_attach_post - Called after the driver attached to the USB interface
1595  *	@ue: the USB ethernet device
1596  *
1597  *	This is where the chip is intialised for the first time.  This is
1598  *	different from the muge_init() function in that that one is designed to
1599  *	setup the H/W to match the UE settings and can be called after a reset.
1600  *
1601  */
1602 static void
1603 muge_attach_post(struct usb_ether *ue)
1604 {
1605 	struct muge_softc *sc = uether_getsc(ue);
1606 
1607 	muge_dbg_printf(sc, "Calling muge_attach_post.\n");
1608 
1609 	/* Setup some of the basics */
1610 	sc->sc_phyno = 1;
1611 
1612 	muge_set_mac_addr(ue);
1613 
1614 	/* Initialise the chip for the first time */
1615 	lan78xx_chip_init(sc);
1616 }
1617 
1618 /**
1619  *	muge_attach_post_sub - Called after attach to the USB interface
1620  *	@ue: the USB ethernet device
1621  *
1622  *	Most of this is boilerplate code and copied from the base USB ethernet
1623  *	driver.  It has been overriden so that we can indicate to the system
1624  *	that the chip supports H/W checksumming.
1625  *
1626  *	RETURNS:
1627  *	Returns 0 on success or a negative error code.
1628  */
1629 static int
1630 muge_attach_post_sub(struct usb_ether *ue)
1631 {
1632 	struct muge_softc *sc;
1633 	struct ifnet *ifp;
1634 	int error;
1635 
1636 	sc = uether_getsc(ue);
1637 	muge_dbg_printf(sc, "Calling muge_attach_post_sub.\n");
1638 	ifp = ue->ue_ifp;
1639 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
1640 	ifp->if_start = uether_start;
1641 	ifp->if_ioctl = muge_ioctl;
1642 	ifp->if_init = uether_init;
1643 	IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
1644 	ifp->if_snd.ifq_drv_maxlen = ifqmaxlen;
1645 	IFQ_SET_READY(&ifp->if_snd);
1646 
1647 	/*
1648 	 * The chip supports TCP/UDP checksum offloading on TX and RX paths,
1649 	 * however currently only RX checksum is supported in the driver
1650 	 * (see top of file).
1651 	 */
1652 	ifp->if_hwassist = 0;
1653 	if (MUGE_DEFAULT_RX_CSUM_ENABLE)
1654 		ifp->if_capabilities |= IFCAP_RXCSUM;
1655 
1656 	if (MUGE_DEFAULT_TX_CSUM_ENABLE)
1657 		ifp->if_capabilities |= IFCAP_TXCSUM;
1658 
1659 	/*
1660 	 * In the Linux driver they also enable scatter/gather (NETIF_F_SG)
1661 	 * here, that's something related to socket buffers used in Linux.
1662 	 * FreeBSD doesn't have that as an interface feature.
1663 	 */
1664 	if (MUGE_DEFAULT_TSO_CSUM_ENABLE)
1665 		ifp->if_capabilities |= IFCAP_TSO4 | IFCAP_TSO6;
1666 
1667 #if 0
1668 	/* TX checksuming is disabled since not yet implemented. */
1669 	ifp->if_capabilities |= IFCAP_TXCSUM;
1670 	ifp->if_capenable |= IFCAP_TXCSUM;
1671 	ifp->if_hwassist = CSUM_TCP | CSUM_UDP;
1672 #endif
1673 
1674 	ifp->if_capenable = ifp->if_capabilities;
1675 
1676 	mtx_lock(&Giant);
1677 	error = mii_attach(ue->ue_dev, &ue->ue_miibus, ifp,
1678 		uether_ifmedia_upd, ue->ue_methods->ue_mii_sts,
1679 		BMSR_DEFCAPMASK, sc->sc_phyno, MII_OFFSET_ANY, 0);
1680 	mtx_unlock(&Giant);
1681 
1682 	return (0);
1683 }
1684 
1685 /**
1686  *	muge_start - Starts communication with the LAN78xx chip
1687  *	@ue: USB ether interface
1688  */
1689 static void
1690 muge_start(struct usb_ether *ue)
1691 {
1692 	struct muge_softc *sc = uether_getsc(ue);
1693 
1694 	/*
1695 	 * Start the USB transfers, if not already started.
1696 	 */
1697 	usbd_transfer_start(sc->sc_xfer[MUGE_BULK_DT_RD]);
1698 	usbd_transfer_start(sc->sc_xfer[MUGE_BULK_DT_WR]);
1699 }
1700 
1701 /**
1702  *	muge_ioctl - ioctl function for the device
1703  *	@ifp: interface pointer
1704  *	@cmd: the ioctl command
1705  *	@data: data passed in the ioctl call, typically a pointer to struct
1706  *	ifreq.
1707  *
1708  *	The ioctl routine is overridden to detect change requests for the H/W
1709  *	checksum capabilities.
1710  *
1711  *	RETURNS:
1712  *	0 on success and an error code on failure.
1713  */
1714 static int
1715 muge_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1716 {
1717 	struct usb_ether *ue = ifp->if_softc;
1718 	struct muge_softc *sc;
1719 	struct ifreq *ifr;
1720 	int rc;
1721 	int mask;
1722 	int reinit;
1723 
1724 	if (cmd == SIOCSIFCAP) {
1725 		sc = uether_getsc(ue);
1726 		ifr = (struct ifreq *)data;
1727 
1728 		MUGE_LOCK(sc);
1729 
1730 		rc = 0;
1731 		reinit = 0;
1732 
1733 		mask = ifr->ifr_reqcap ^ ifp->if_capenable;
1734 
1735 		/* Modify the RX CSUM enable bits. */
1736 		if ((mask & IFCAP_RXCSUM) != 0 &&
1737 			(ifp->if_capabilities & IFCAP_RXCSUM) != 0) {
1738 			ifp->if_capenable ^= IFCAP_RXCSUM;
1739 
1740 			if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1741 				ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1742 				reinit = 1;
1743 			}
1744 		}
1745 
1746 		MUGE_UNLOCK(sc);
1747 		if (reinit)
1748 			uether_init(ue);
1749 
1750 	} else {
1751 		rc = uether_ioctl(ifp, cmd, data);
1752 	}
1753 
1754 	return (rc);
1755 }
1756 
1757 /**
1758  *	muge_reset - Reset the SMSC chip
1759  *	@sc: device soft context
1760  *
1761  *	LOCKING:
1762  *	Should be called with the SMSC lock held.
1763  */
1764 static void
1765 muge_reset(struct muge_softc *sc)
1766 {
1767 	struct usb_config_descriptor *cd;
1768 	usb_error_t err;
1769 
1770 	cd = usbd_get_config_descriptor(sc->sc_ue.ue_udev);
1771 
1772 	err = usbd_req_set_config(sc->sc_ue.ue_udev, &sc->sc_mtx,
1773 	    cd->bConfigurationValue);
1774 	if (err)
1775 		muge_warn_printf(sc, "reset failed (ignored)\n");
1776 
1777 	/* Wait a little while for the chip to get its brains in order. */
1778 	uether_pause(&sc->sc_ue, hz / 100);
1779 
1780 	/* Reinitialize controller to achieve full reset. */
1781 	lan78xx_chip_init(sc);
1782 }
1783 
1784 /**
1785  * muge_set_addr_filter
1786  *
1787  *	@sc: device soft context
1788  *	@index: index of the entry to the perfect address table
1789  *	@addr: address to be written
1790  *
1791  */
1792 static void
1793 muge_set_addr_filter(struct muge_softc *sc, int index,
1794     uint8_t addr[ETHER_ADDR_LEN])
1795 {
1796 	uint32_t tmp;
1797 
1798 	if ((sc) && (index > 0) && (index < MUGE_NUM_PFILTER_ADDRS_)) {
1799 		tmp = addr[3];
1800 		tmp |= addr[2] | (tmp << 8);
1801 		tmp |= addr[1] | (tmp << 8);
1802 		tmp |= addr[0] | (tmp << 8);
1803 		sc->sc_pfilter_table[index][1] = tmp;
1804 		tmp = addr[5];
1805 		tmp |= addr[4] | (tmp << 8);
1806 		tmp |= ETH_MAF_HI_VALID_ | ETH_MAF_HI_TYPE_DST_;
1807 		sc->sc_pfilter_table[index][0] = tmp;
1808 	}
1809 }
1810 
1811 /**
1812  *	lan78xx_dataport_write - write to the selected RAM
1813  *	@sc: The device soft context.
1814  *	@ram_select: Select which RAM to access.
1815  *	@addr: Starting address to write to.
1816  *	@buf: word-sized buffer to write to RAM, starting at @addr.
1817  *	@length: length of @buf
1818  *
1819  *
1820  *	RETURNS:
1821  *	0 if write successful.
1822  */
1823 static int
1824 lan78xx_dataport_write(struct muge_softc *sc, uint32_t ram_select,
1825     uint32_t addr, uint32_t length, uint32_t *buf)
1826 {
1827 	uint32_t dp_sel;
1828 	int i, ret;
1829 
1830 	MUGE_LOCK_ASSERT(sc, MA_OWNED);
1831 	ret = lan78xx_wait_for_bits(sc, ETH_DP_SEL, ETH_DP_SEL_DPRDY_);
1832 	if (ret < 0)
1833 		goto done;
1834 
1835 	ret = lan78xx_read_reg(sc, ETH_DP_SEL, &dp_sel);
1836 
1837 	dp_sel &= ~ETH_DP_SEL_RSEL_MASK_;
1838 	dp_sel |= ram_select;
1839 
1840 	ret = lan78xx_write_reg(sc, ETH_DP_SEL, dp_sel);
1841 
1842 	for (i = 0; i < length; i++) {
1843 		ret = lan78xx_write_reg(sc, ETH_DP_ADDR, addr + i);
1844 		ret = lan78xx_write_reg(sc, ETH_DP_DATA, buf[i]);
1845 		ret = lan78xx_write_reg(sc, ETH_DP_CMD, ETH_DP_CMD_WRITE_);
1846 		ret = lan78xx_wait_for_bits(sc, ETH_DP_SEL, ETH_DP_SEL_DPRDY_);
1847 		if (ret != 0)
1848 			goto done;
1849 	}
1850 
1851 done:
1852 	return (ret);
1853 }
1854 
1855 /**
1856  * muge_multicast_write
1857  * @sc: device's soft context
1858  *
1859  * Writes perfect addres filters and hash address filters to their
1860  * corresponding registers and RAMs.
1861  *
1862  */
1863 static void
1864 muge_multicast_write(struct muge_softc *sc)
1865 {
1866 	int i, ret;
1867 	lan78xx_dataport_write(sc, ETH_DP_SEL_RSEL_VLAN_DA_,
1868 	    ETH_DP_SEL_VHF_VLAN_LEN, ETH_DP_SEL_VHF_HASH_LEN,
1869 	    sc->sc_mchash_table);
1870 
1871 	for (i = 1; i < MUGE_NUM_PFILTER_ADDRS_; i++) {
1872 		ret = lan78xx_write_reg(sc, PFILTER_HI(i), 0);
1873 		ret = lan78xx_write_reg(sc, PFILTER_LO(i),
1874 		    sc->sc_pfilter_table[i][1]);
1875 		ret = lan78xx_write_reg(sc, PFILTER_HI(i),
1876 		    sc->sc_pfilter_table[i][0]);
1877 	}
1878 }
1879 
1880 /**
1881  *	muge_hash - Calculate the hash of a mac address
1882  *	@addr: The mac address to calculate the hash on
1883  *
1884  *	This function is used when configuring a range of multicast mac
1885  *	addresses to filter on.  The hash of the mac address is put in the
1886  *	device's mac hash table.
1887  *
1888  *	RETURNS:
1889  *	Returns a value from 0-63 value which is the hash of the mac address.
1890  */
1891 static inline uint32_t
1892 muge_hash(uint8_t addr[ETHER_ADDR_LEN])
1893 {
1894 	return (ether_crc32_be(addr, ETHER_ADDR_LEN) >> 23) & 0x1ff;
1895 }
1896 
1897 /**
1898  *	muge_setmulti - Setup multicast
1899  *	@ue: usb ethernet device context
1900  *
1901  *	Tells the device to either accept frames with a multicast mac address,
1902  *	a select group of m'cast mac addresses or just the devices mac address.
1903  *
1904  *	LOCKING:
1905  *	Should be called with the MUGE lock held.
1906  */
1907 static void
1908 muge_setmulti(struct usb_ether *ue)
1909 {
1910 	struct muge_softc *sc = uether_getsc(ue);
1911 	struct ifnet *ifp = uether_getifp(ue);
1912 	uint8_t i, *addr;
1913 	struct ifmultiaddr *ifma;
1914 
1915 	MUGE_LOCK_ASSERT(sc, MA_OWNED);
1916 
1917 	sc->sc_rfe_ctl &= ~(ETH_RFE_CTL_UCAST_EN_ | ETH_RFE_CTL_MCAST_EN_ |
1918 		ETH_RFE_CTL_DA_PERFECT_ | ETH_RFE_CTL_MCAST_HASH_);
1919 
1920 	/* Initialize hash filter table. */
1921 	for (i = 0; i < ETH_DP_SEL_VHF_HASH_LEN; i++)
1922 		sc->sc_mchash_table[i] = 0;
1923 
1924 	/* Initialize perfect filter table. */
1925 	for (i = 1; i < MUGE_NUM_PFILTER_ADDRS_; i++) {
1926 		sc->sc_pfilter_table[i][0] =
1927 		sc->sc_pfilter_table[i][1] = 0;
1928 	}
1929 
1930 	sc->sc_rfe_ctl |= ETH_RFE_CTL_BCAST_EN_;
1931 
1932 	if (ifp->if_flags & IFF_PROMISC) {
1933 		muge_dbg_printf(sc, "promiscuous mode enabled\n");
1934 		sc->sc_rfe_ctl |= ETH_RFE_CTL_MCAST_EN_ | ETH_RFE_CTL_UCAST_EN_;
1935 	} else if (ifp->if_flags & IFF_ALLMULTI){
1936 		muge_dbg_printf(sc, "receive all multicast enabled\n");
1937 		sc->sc_rfe_ctl |= ETH_RFE_CTL_MCAST_EN_;
1938 	} else {
1939 		/* Lock the mac address list before hashing each of them. */
1940 		if_maddr_rlock(ifp);
1941 		if (!CK_STAILQ_EMPTY(&ifp->if_multiaddrs)) {
1942 			i = 1;
1943 			CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs,
1944 			    ifma_link) {
1945 				/* First fill up the perfect address table. */
1946 				addr = LLADDR((struct sockaddr_dl *)
1947 				    ifma->ifma_addr);
1948 				if (i < 33 /* XXX */) {
1949 					muge_set_addr_filter(sc, i, addr);
1950 				} else {
1951 					uint32_t bitnum = muge_hash(addr);
1952 					sc->sc_mchash_table[bitnum / 32] |=
1953 					    (1 << (bitnum % 32));
1954 					sc->sc_rfe_ctl |=
1955 					    ETH_RFE_CTL_MCAST_HASH_;
1956 				}
1957 				i++;
1958 			}
1959 		}
1960 		if_maddr_runlock(ifp);
1961 		muge_multicast_write(sc);
1962 	}
1963 	lan78xx_write_reg(sc, ETH_RFE_CTL, sc->sc_rfe_ctl);
1964 }
1965 
1966 /**
1967  *	muge_setpromisc - Enables/disables promiscuous mode
1968  *	@ue: usb ethernet device context
1969  *
1970  *	LOCKING:
1971  *	Should be called with the MUGE lock held.
1972  */
1973 static void
1974 muge_setpromisc(struct usb_ether *ue)
1975 {
1976 	struct muge_softc *sc = uether_getsc(ue);
1977 	struct ifnet *ifp = uether_getifp(ue);
1978 
1979 	muge_dbg_printf(sc, "promiscuous mode %sabled\n",
1980 	    (ifp->if_flags & IFF_PROMISC) ? "en" : "dis");
1981 
1982 	MUGE_LOCK_ASSERT(sc, MA_OWNED);
1983 
1984 	if (ifp->if_flags & IFF_PROMISC)
1985 		sc->sc_rfe_ctl |= ETH_RFE_CTL_MCAST_EN_ | ETH_RFE_CTL_UCAST_EN_;
1986 	else
1987 		sc->sc_rfe_ctl &= ~(ETH_RFE_CTL_MCAST_EN_);
1988 
1989 	lan78xx_write_reg(sc, ETH_RFE_CTL, sc->sc_rfe_ctl);
1990 }
1991 
1992 /**
1993  *	muge_sethwcsum - Enable or disable H/W UDP and TCP checksumming
1994  *	@sc: driver soft context
1995  *
1996  *	LOCKING:
1997  *	Should be called with the MUGE lock held.
1998  *
1999  *	RETURNS:
2000  *	Returns 0 on success or a negative error code.
2001  */
2002 static int muge_sethwcsum(struct muge_softc *sc)
2003 {
2004 	struct ifnet *ifp = uether_getifp(&sc->sc_ue);
2005 	int err;
2006 
2007 	if (!ifp)
2008 		return (-EIO);
2009 
2010 	MUGE_LOCK_ASSERT(sc, MA_OWNED);
2011 
2012 	if (ifp->if_capabilities & IFCAP_RXCSUM) {
2013 		sc->sc_rfe_ctl |= ETH_RFE_CTL_IGMP_COE_ | ETH_RFE_CTL_ICMP_COE_;
2014 		sc->sc_rfe_ctl |= ETH_RFE_CTL_TCPUDP_COE_ | ETH_RFE_CTL_IP_COE_;
2015 	} else {
2016 		sc->sc_rfe_ctl &=
2017 		    ~(ETH_RFE_CTL_IGMP_COE_ | ETH_RFE_CTL_ICMP_COE_);
2018 		sc->sc_rfe_ctl &=
2019 		     ~(ETH_RFE_CTL_TCPUDP_COE_ | ETH_RFE_CTL_IP_COE_);
2020 	}
2021 
2022 	sc->sc_rfe_ctl &= ~ETH_RFE_CTL_VLAN_FILTER_;
2023 
2024 	err = lan78xx_write_reg(sc, ETH_RFE_CTL, sc->sc_rfe_ctl);
2025 
2026 	if (err != 0) {
2027 		muge_warn_printf(sc, "failed to write ETH_RFE_CTL (err=%d)\n",
2028 		    err);
2029 		return (err);
2030 	}
2031 
2032 	return (0);
2033 }
2034 
2035 /**
2036  *	muge_ifmedia_upd - Set media options
2037  *	@ifp: interface pointer
2038  *
2039  *	Basically boilerplate code that simply calls the mii functions to set
2040  *	the media options.
2041  *
2042  *	LOCKING:
2043  *	The device lock must be held before this function is called.
2044  *
2045  *	RETURNS:
2046  *	Returns 0 on success or a negative error code.
2047  */
2048 static int
2049 muge_ifmedia_upd(struct ifnet *ifp)
2050 {
2051 	struct muge_softc *sc = ifp->if_softc;
2052 	muge_dbg_printf(sc, "Calling muge_ifmedia_upd.\n");
2053 	struct mii_data *mii = uether_getmii(&sc->sc_ue);
2054 	struct mii_softc *miisc;
2055 	int err;
2056 
2057 	MUGE_LOCK_ASSERT(sc, MA_OWNED);
2058 
2059 	LIST_FOREACH(miisc, &mii->mii_phys, mii_list)
2060 		PHY_RESET(miisc);
2061 	err = mii_mediachg(mii);
2062 	return (err);
2063 }
2064 
2065 /**
2066  *	muge_init - Initialises the LAN95xx chip
2067  *	@ue: USB ether interface
2068  *
2069  *	Called when the interface is brought up (i.e. ifconfig ue0 up), this
2070  *	initialise the interface and the rx/tx pipes.
2071  *
2072  *	LOCKING:
2073  *	Should be called with the MUGE lock held.
2074  */
2075 static void
2076 muge_init(struct usb_ether *ue)
2077 {
2078 	struct muge_softc *sc = uether_getsc(ue);
2079 	muge_dbg_printf(sc, "Calling muge_init.\n");
2080 	struct ifnet *ifp = uether_getifp(ue);
2081 	MUGE_LOCK_ASSERT(sc, MA_OWNED);
2082 
2083 	if (lan78xx_setmacaddress(sc, IF_LLADDR(ifp)))
2084 		muge_dbg_printf(sc, "setting MAC address failed\n");
2085 
2086 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) != 0)
2087 		return;
2088 
2089 	/* Cancel pending I/O. */
2090 	muge_stop(ue);
2091 
2092 	/* Reset the ethernet interface. */
2093 	muge_reset(sc);
2094 
2095 	/* Load the multicast filter. */
2096 	muge_setmulti(ue);
2097 
2098 	/* TCP/UDP checksum offload engines. */
2099 	muge_sethwcsum(sc);
2100 
2101 	usbd_xfer_set_stall(sc->sc_xfer[MUGE_BULK_DT_WR]);
2102 
2103 	/* Indicate we are up and running. */
2104 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
2105 
2106 	/* Switch to selected media. */
2107 	muge_ifmedia_upd(ifp);
2108 	muge_start(ue);
2109 }
2110 
2111 /**
2112  *	muge_stop - Stops communication with the LAN78xx chip
2113  *	@ue: USB ether interface
2114  */
2115 static void
2116 muge_stop(struct usb_ether *ue)
2117 {
2118 	struct muge_softc *sc = uether_getsc(ue);
2119 	struct ifnet *ifp = uether_getifp(ue);
2120 
2121 	MUGE_LOCK_ASSERT(sc, MA_OWNED);
2122 
2123 	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
2124 	sc->sc_flags &= ~MUGE_FLAG_LINK;
2125 
2126 	/*
2127 	 * Stop all the transfers, if not already stopped.
2128 	 */
2129 	usbd_transfer_stop(sc->sc_xfer[MUGE_BULK_DT_WR]);
2130 	usbd_transfer_stop(sc->sc_xfer[MUGE_BULK_DT_RD]);
2131 }
2132 
2133 /**
2134  *	muge_tick - Called periodically to monitor the state of the LAN95xx chip
2135  *	@ue: USB ether interface
2136  *
2137  *	Simply calls the mii status functions to check the state of the link.
2138  *
2139  *	LOCKING:
2140  *	Should be called with the MUGE lock held.
2141  */
2142 static void
2143 muge_tick(struct usb_ether *ue)
2144 {
2145 
2146 	struct muge_softc *sc = uether_getsc(ue);
2147 	struct mii_data *mii = uether_getmii(&sc->sc_ue);
2148 
2149 	MUGE_LOCK_ASSERT(sc, MA_OWNED);
2150 
2151 	mii_tick(mii);
2152 	if ((sc->sc_flags & MUGE_FLAG_LINK) == 0) {
2153 		lan78xx_miibus_statchg(ue->ue_dev);
2154 		if ((sc->sc_flags & MUGE_FLAG_LINK) != 0)
2155 			muge_start(ue);
2156 	}
2157 }
2158 
2159 /**
2160  *	muge_ifmedia_sts - Report current media status
2161  *	@ifp: inet interface pointer
2162  *	@ifmr: interface media request
2163  *
2164  *	Call the mii functions to get the media status.
2165  *
2166  *	LOCKING:
2167  *	Internally takes and releases the device lock.
2168  */
2169 static void
2170 muge_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
2171 {
2172 	struct muge_softc *sc = ifp->if_softc;
2173 	struct mii_data *mii = uether_getmii(&sc->sc_ue);
2174 
2175 	MUGE_LOCK(sc);
2176 	mii_pollstat(mii);
2177 	ifmr->ifm_active = mii->mii_media_active;
2178 	ifmr->ifm_status = mii->mii_media_status;
2179 	MUGE_UNLOCK(sc);
2180 }
2181 
2182 /**
2183  *	muge_probe - Probe the interface.
2184  *	@dev: muge device handle
2185  *
2186  *	Checks if the device is a match for this driver.
2187  *
2188  *	RETURNS:
2189  *	Returns 0 on success or an error code on failure.
2190  */
2191 static int
2192 muge_probe(device_t dev)
2193 {
2194 	struct usb_attach_arg *uaa = device_get_ivars(dev);
2195 
2196 	if (uaa->usb_mode != USB_MODE_HOST)
2197 		return (ENXIO);
2198 	if (uaa->info.bConfigIndex != MUGE_CONFIG_INDEX)
2199 		return (ENXIO);
2200 	if (uaa->info.bIfaceIndex != MUGE_IFACE_IDX)
2201 		return (ENXIO);
2202 	return (usbd_lookup_id_by_uaa(lan78xx_devs, sizeof(lan78xx_devs), uaa));
2203 }
2204 
2205 /**
2206  *	muge_attach - Attach the interface.
2207  *	@dev: muge device handle
2208  *
2209  *	Allocate softc structures, do ifmedia setup and ethernet/BPF attach.
2210  *
2211  *	RETURNS:
2212  *	Returns 0 on success or a negative error code.
2213  */
2214 static int
2215 muge_attach(device_t dev)
2216 {
2217 	struct usb_attach_arg *uaa = device_get_ivars(dev);
2218 	struct muge_softc *sc = device_get_softc(dev);
2219 	struct usb_ether *ue = &sc->sc_ue;
2220 	uint8_t iface_index;
2221 	int err;
2222 
2223 	sc->sc_flags = USB_GET_DRIVER_INFO(uaa);
2224 
2225 	device_set_usb_desc(dev);
2226 
2227 	mtx_init(&sc->sc_mtx, device_get_nameunit(dev), NULL, MTX_DEF);
2228 
2229 	/* Setup the endpoints for the Microchip LAN78xx device. */
2230 	iface_index = MUGE_IFACE_IDX;
2231 	err = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer,
2232 	    muge_config, MUGE_N_TRANSFER, sc, &sc->sc_mtx);
2233 	if (err) {
2234 		device_printf(dev, "error: allocating USB transfers failed\n");
2235 		goto err;
2236 	}
2237 
2238 	ue->ue_sc = sc;
2239 	ue->ue_dev = dev;
2240 	ue->ue_udev = uaa->device;
2241 	ue->ue_mtx = &sc->sc_mtx;
2242 	ue->ue_methods = &muge_ue_methods;
2243 
2244 	err = uether_ifattach(ue);
2245 	if (err) {
2246 		device_printf(dev, "error: could not attach interface\n");
2247 		goto err_usbd;
2248 	}
2249 
2250 	/* Wait for lan78xx_chip_init from post-attach callback to complete. */
2251 	uether_ifattach_wait(ue);
2252 	if (!(sc->sc_flags & MUGE_FLAG_INIT_DONE))
2253 		goto err_attached;
2254 
2255 	return (0);
2256 
2257 err_attached:
2258 	uether_ifdetach(ue);
2259 err_usbd:
2260 	usbd_transfer_unsetup(sc->sc_xfer, MUGE_N_TRANSFER);
2261 err:
2262 	mtx_destroy(&sc->sc_mtx);
2263 	return (ENXIO);
2264 }
2265 
2266 /**
2267  *	muge_detach - Detach the interface.
2268  *	@dev: muge device handle
2269  *
2270  *	RETURNS:
2271  *	Returns 0.
2272  */
2273 static int
2274 muge_detach(device_t dev)
2275 {
2276 
2277 	struct muge_softc *sc = device_get_softc(dev);
2278 	struct usb_ether *ue = &sc->sc_ue;
2279 
2280 	usbd_transfer_unsetup(sc->sc_xfer, MUGE_N_TRANSFER);
2281 	uether_ifdetach(ue);
2282 	mtx_destroy(&sc->sc_mtx);
2283 
2284 	return (0);
2285 }
2286 
2287 static device_method_t muge_methods[] = {
2288 	/* Device interface */
2289 	DEVMETHOD(device_probe, muge_probe),
2290 	DEVMETHOD(device_attach, muge_attach),
2291 	DEVMETHOD(device_detach, muge_detach),
2292 
2293 	/* Bus interface */
2294 	DEVMETHOD(bus_print_child, bus_generic_print_child),
2295 	DEVMETHOD(bus_driver_added, bus_generic_driver_added),
2296 
2297 	/* MII interface */
2298 	DEVMETHOD(miibus_readreg, lan78xx_miibus_readreg),
2299 	DEVMETHOD(miibus_writereg, lan78xx_miibus_writereg),
2300 	DEVMETHOD(miibus_statchg, lan78xx_miibus_statchg),
2301 
2302 	DEVMETHOD_END
2303 };
2304 
2305 static driver_t muge_driver = {
2306 	.name = "muge",
2307 	.methods = muge_methods,
2308 	.size = sizeof(struct muge_softc),
2309 };
2310 
2311 static devclass_t muge_devclass;
2312 
2313 DRIVER_MODULE(muge, uhub, muge_driver, muge_devclass, NULL, 0);
2314 DRIVER_MODULE(miibus, muge, miibus_driver, miibus_devclass, 0, 0);
2315 MODULE_DEPEND(muge, uether, 1, 1, 1);
2316 MODULE_DEPEND(muge, usb, 1, 1, 1);
2317 MODULE_DEPEND(muge, ether, 1, 1, 1);
2318 MODULE_DEPEND(muge, miibus, 1, 1, 1);
2319 MODULE_VERSION(muge, 1);
2320 USB_PNP_HOST_INFO(lan78xx_devs);
2321