xref: /freebsd/sys/dev/usb/net/if_smsc.c (revision 6419bb52)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2012
5  *	Ben Gray <bgray@freebsd.org>.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 /*
33  * SMSC LAN9xxx devices (http://www.smsc.com/)
34  *
35  * The LAN9500 & LAN9500A devices are stand-alone USB to Ethernet chips that
36  * support USB 2.0 and 10/100 Mbps Ethernet.
37  *
38  * The LAN951x devices are an integrated USB hub and USB to Ethernet adapter.
39  * The driver only covers the Ethernet part, the standard USB hub driver
40  * supports the hub part.
41  *
42  * This driver is closely modelled on the Linux driver written and copyrighted
43  * by SMSC.
44  *
45  *
46  *
47  *
48  * H/W TCP & UDP Checksum Offloading
49  * ---------------------------------
50  * The chip supports both tx and rx offloading of UDP & TCP checksums, this
51  * feature can be dynamically enabled/disabled.
52  *
53  * RX checksuming is performed across bytes after the IPv4 header to the end of
54  * the Ethernet frame, this means if the frame is padded with non-zero values
55  * the H/W checksum will be incorrect, however the rx code compensates for this.
56  *
57  * TX checksuming is more complicated, the device requires a special header to
58  * be prefixed onto the start of the frame which indicates the start and end
59  * positions of the UDP or TCP frame.  This requires the driver to manually
60  * go through the packet data and decode the headers prior to sending.
61  * On Linux they generally provide cues to the location of the csum and the
62  * area to calculate it over, on FreeBSD we seem to have to do it all ourselves,
63  * hence this is not as optimal and therefore h/w tX checksum is currently not
64  * implemented.
65  *
66  */
67 #include <sys/stdint.h>
68 #include <sys/stddef.h>
69 #include <sys/param.h>
70 #include <sys/queue.h>
71 #include <sys/types.h>
72 #include <sys/systm.h>
73 #include <sys/kernel.h>
74 #include <sys/bus.h>
75 #include <sys/module.h>
76 #include <sys/lock.h>
77 #include <sys/mutex.h>
78 #include <sys/condvar.h>
79 #include <sys/socket.h>
80 #include <sys/sysctl.h>
81 #include <sys/sx.h>
82 #include <sys/unistd.h>
83 #include <sys/callout.h>
84 #include <sys/malloc.h>
85 #include <sys/priv.h>
86 #include <sys/random.h>
87 
88 #include <net/if.h>
89 #include <net/if_var.h>
90 #include <net/if_media.h>
91 
92 #include <dev/mii/mii.h>
93 #include <dev/mii/miivar.h>
94 
95 #include <netinet/in.h>
96 #include <netinet/ip.h>
97 
98 #include "opt_platform.h"
99 
100 #ifdef FDT
101 #include <dev/fdt/fdt_common.h>
102 #include <dev/ofw/ofw_bus.h>
103 #include <dev/ofw/ofw_bus_subr.h>
104 #include <dev/usb/usb_fdt_support.h>
105 #endif
106 
107 #include <dev/usb/usb.h>
108 #include <dev/usb/usbdi.h>
109 #include <dev/usb/usbdi_util.h>
110 #include "usbdevs.h"
111 
112 #define	USB_DEBUG_VAR smsc_debug
113 #include <dev/usb/usb_debug.h>
114 #include <dev/usb/usb_process.h>
115 
116 #include <dev/usb/net/usb_ethernet.h>
117 
118 #include <dev/usb/net/if_smscreg.h>
119 
120 #include "miibus_if.h"
121 
122 #ifdef USB_DEBUG
123 static int smsc_debug = 0;
124 
125 SYSCTL_NODE(_hw_usb, OID_AUTO, smsc, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
126     "USB smsc");
127 SYSCTL_INT(_hw_usb_smsc, OID_AUTO, debug, CTLFLAG_RWTUN, &smsc_debug, 0,
128     "Debug level");
129 #endif
130 
131 /*
132  * Various supported device vendors/products.
133  */
134 static const struct usb_device_id smsc_devs[] = {
135 #define	SMSC_DEV(p,i) { USB_VPI(USB_VENDOR_SMC2, USB_PRODUCT_SMC2_##p, i) }
136 	SMSC_DEV(LAN89530_ETH, 0),
137 	SMSC_DEV(LAN9500_ETH, 0),
138 	SMSC_DEV(LAN9500_ETH_2, 0),
139 	SMSC_DEV(LAN9500A_ETH, 0),
140 	SMSC_DEV(LAN9500A_ETH_2, 0),
141 	SMSC_DEV(LAN9505_ETH, 0),
142 	SMSC_DEV(LAN9505A_ETH, 0),
143 	SMSC_DEV(LAN9514_ETH, 0),
144 	SMSC_DEV(LAN9514_ETH_2, 0),
145 	SMSC_DEV(LAN9530_ETH, 0),
146 	SMSC_DEV(LAN9730_ETH, 0),
147 	SMSC_DEV(LAN9500_SAL10, 0),
148 	SMSC_DEV(LAN9505_SAL10, 0),
149 	SMSC_DEV(LAN9500A_SAL10, 0),
150 	SMSC_DEV(LAN9505A_SAL10, 0),
151 	SMSC_DEV(LAN9514_SAL10, 0),
152 	SMSC_DEV(LAN9500A_HAL, 0),
153 	SMSC_DEV(LAN9505A_HAL, 0),
154 #undef SMSC_DEV
155 };
156 
157 
158 #ifdef USB_DEBUG
159 #define smsc_dbg_printf(sc, fmt, args...) \
160 	do { \
161 		if (smsc_debug > 0) \
162 			device_printf((sc)->sc_ue.ue_dev, "debug: " fmt, ##args); \
163 	} while(0)
164 #else
165 #define smsc_dbg_printf(sc, fmt, args...) do { } while (0)
166 #endif
167 
168 #define smsc_warn_printf(sc, fmt, args...) \
169 	device_printf((sc)->sc_ue.ue_dev, "warning: " fmt, ##args)
170 
171 #define smsc_err_printf(sc, fmt, args...) \
172 	device_printf((sc)->sc_ue.ue_dev, "error: " fmt, ##args)
173 
174 
175 #define ETHER_IS_VALID(addr) \
176 	(!ETHER_IS_MULTICAST(addr) && !ETHER_IS_ZERO(addr))
177 
178 static device_probe_t smsc_probe;
179 static device_attach_t smsc_attach;
180 static device_detach_t smsc_detach;
181 
182 static usb_callback_t smsc_bulk_read_callback;
183 static usb_callback_t smsc_bulk_write_callback;
184 
185 static miibus_readreg_t smsc_miibus_readreg;
186 static miibus_writereg_t smsc_miibus_writereg;
187 static miibus_statchg_t smsc_miibus_statchg;
188 
189 static int smsc_attach_post_sub(struct usb_ether *ue);
190 static uether_fn_t smsc_attach_post;
191 static uether_fn_t smsc_init;
192 static uether_fn_t smsc_stop;
193 static uether_fn_t smsc_start;
194 static uether_fn_t smsc_tick;
195 static uether_fn_t smsc_setmulti;
196 static uether_fn_t smsc_setpromisc;
197 
198 static int	smsc_ifmedia_upd(struct ifnet *);
199 static void	smsc_ifmedia_sts(struct ifnet *, struct ifmediareq *);
200 
201 static int smsc_chip_init(struct smsc_softc *sc);
202 static int smsc_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data);
203 
204 static const struct usb_config smsc_config[SMSC_N_TRANSFER] = {
205 
206 	[SMSC_BULK_DT_WR] = {
207 		.type = UE_BULK,
208 		.endpoint = UE_ADDR_ANY,
209 		.direction = UE_DIR_OUT,
210 		.frames = 16,
211 		.bufsize = 16 * (MCLBYTES + 16),
212 		.flags = {.pipe_bof = 1,.force_short_xfer = 1,},
213 		.callback = smsc_bulk_write_callback,
214 		.timeout = 10000,	/* 10 seconds */
215 	},
216 
217 	[SMSC_BULK_DT_RD] = {
218 		.type = UE_BULK,
219 		.endpoint = UE_ADDR_ANY,
220 		.direction = UE_DIR_IN,
221 		.bufsize = 20480,	/* bytes */
222 		.flags = {.pipe_bof = 1,.short_xfer_ok = 1,},
223 		.callback = smsc_bulk_read_callback,
224 		.timeout = 0,	/* no timeout */
225 	},
226 
227 	/* The SMSC chip supports an interrupt endpoints, however they aren't
228 	 * needed as we poll on the MII status.
229 	 */
230 };
231 
232 static const struct usb_ether_methods smsc_ue_methods = {
233 	.ue_attach_post = smsc_attach_post,
234 	.ue_attach_post_sub = smsc_attach_post_sub,
235 	.ue_start = smsc_start,
236 	.ue_ioctl = smsc_ioctl,
237 	.ue_init = smsc_init,
238 	.ue_stop = smsc_stop,
239 	.ue_tick = smsc_tick,
240 	.ue_setmulti = smsc_setmulti,
241 	.ue_setpromisc = smsc_setpromisc,
242 	.ue_mii_upd = smsc_ifmedia_upd,
243 	.ue_mii_sts = smsc_ifmedia_sts,
244 };
245 
246 /**
247  *	smsc_read_reg - Reads a 32-bit register on the device
248  *	@sc: driver soft context
249  *	@off: offset of the register
250  *	@data: pointer a value that will be populated with the register value
251  *
252  *	LOCKING:
253  *	The device lock must be held before calling this function.
254  *
255  *	RETURNS:
256  *	0 on success, a USB_ERR_?? error code on failure.
257  */
258 static int
259 smsc_read_reg(struct smsc_softc *sc, uint32_t off, uint32_t *data)
260 {
261 	struct usb_device_request req;
262 	uint32_t buf;
263 	usb_error_t err;
264 
265 	SMSC_LOCK_ASSERT(sc, MA_OWNED);
266 
267 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
268 	req.bRequest = SMSC_UR_READ_REG;
269 	USETW(req.wValue, 0);
270 	USETW(req.wIndex, off);
271 	USETW(req.wLength, 4);
272 
273 	err = uether_do_request(&sc->sc_ue, &req, &buf, 1000);
274 	if (err != 0)
275 		smsc_warn_printf(sc, "Failed to read register 0x%0x\n", off);
276 
277 	*data = le32toh(buf);
278 
279 	return (err);
280 }
281 
282 /**
283  *	smsc_write_reg - Writes a 32-bit register on the device
284  *	@sc: driver soft context
285  *	@off: offset of the register
286  *	@data: the 32-bit value to write into the register
287  *
288  *	LOCKING:
289  *	The device lock must be held before calling this function.
290  *
291  *	RETURNS:
292  *	0 on success, a USB_ERR_?? error code on failure.
293  */
294 static int
295 smsc_write_reg(struct smsc_softc *sc, uint32_t off, uint32_t data)
296 {
297 	struct usb_device_request req;
298 	uint32_t buf;
299 	usb_error_t err;
300 
301 	SMSC_LOCK_ASSERT(sc, MA_OWNED);
302 
303 	buf = htole32(data);
304 
305 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
306 	req.bRequest = SMSC_UR_WRITE_REG;
307 	USETW(req.wValue, 0);
308 	USETW(req.wIndex, off);
309 	USETW(req.wLength, 4);
310 
311 	err = uether_do_request(&sc->sc_ue, &req, &buf, 1000);
312 	if (err != 0)
313 		smsc_warn_printf(sc, "Failed to write register 0x%0x\n", off);
314 
315 	return (err);
316 }
317 
318 /**
319  *	smsc_wait_for_bits - Polls on a register value until bits are cleared
320  *	@sc: soft context
321  *	@reg: offset of the register
322  *	@bits: if the bits are clear the function returns
323  *
324  *	LOCKING:
325  *	The device lock must be held before calling this function.
326  *
327  *	RETURNS:
328  *	0 on success, or a USB_ERR_?? error code on failure.
329  */
330 static int
331 smsc_wait_for_bits(struct smsc_softc *sc, uint32_t reg, uint32_t bits)
332 {
333 	usb_ticks_t start_ticks;
334 	const usb_ticks_t max_ticks = USB_MS_TO_TICKS(1000);
335 	uint32_t val;
336 	int err;
337 
338 	SMSC_LOCK_ASSERT(sc, MA_OWNED);
339 
340 	start_ticks = (usb_ticks_t)ticks;
341 	do {
342 		if ((err = smsc_read_reg(sc, reg, &val)) != 0)
343 			return (err);
344 		if (!(val & bits))
345 			return (0);
346 
347 		uether_pause(&sc->sc_ue, hz / 100);
348 	} while (((usb_ticks_t)(ticks - start_ticks)) < max_ticks);
349 
350 	return (USB_ERR_TIMEOUT);
351 }
352 
353 /**
354  *	smsc_eeprom_read - Reads the attached EEPROM
355  *	@sc: soft context
356  *	@off: the eeprom address offset
357  *	@buf: stores the bytes
358  *	@buflen: the number of bytes to read
359  *
360  *	Simply reads bytes from an attached eeprom.
361  *
362  *	LOCKING:
363  *	The function takes and releases the device lock if it is not already held.
364  *
365  *	RETURNS:
366  *	0 on success, or a USB_ERR_?? error code on failure.
367  */
368 static int
369 smsc_eeprom_read(struct smsc_softc *sc, uint16_t off, uint8_t *buf, uint16_t buflen)
370 {
371 	usb_ticks_t start_ticks;
372 	const usb_ticks_t max_ticks = USB_MS_TO_TICKS(1000);
373 	int err;
374 	int locked;
375 	uint32_t val;
376 	uint16_t i;
377 
378 	locked = mtx_owned(&sc->sc_mtx);
379 	if (!locked)
380 		SMSC_LOCK(sc);
381 
382 	err = smsc_wait_for_bits(sc, SMSC_EEPROM_CMD, SMSC_EEPROM_CMD_BUSY);
383 	if (err != 0) {
384 		smsc_warn_printf(sc, "eeprom busy, failed to read data\n");
385 		goto done;
386 	}
387 
388 	/* start reading the bytes, one at a time */
389 	for (i = 0; i < buflen; i++) {
390 
391 		val = SMSC_EEPROM_CMD_BUSY | (SMSC_EEPROM_CMD_ADDR_MASK & (off + i));
392 		if ((err = smsc_write_reg(sc, SMSC_EEPROM_CMD, val)) != 0)
393 			goto done;
394 
395 		start_ticks = (usb_ticks_t)ticks;
396 		do {
397 			if ((err = smsc_read_reg(sc, SMSC_EEPROM_CMD, &val)) != 0)
398 				goto done;
399 			if (!(val & SMSC_EEPROM_CMD_BUSY) || (val & SMSC_EEPROM_CMD_TIMEOUT))
400 				break;
401 
402 			uether_pause(&sc->sc_ue, hz / 100);
403 		} while (((usb_ticks_t)(ticks - start_ticks)) < max_ticks);
404 
405 		if (val & (SMSC_EEPROM_CMD_BUSY | SMSC_EEPROM_CMD_TIMEOUT)) {
406 			smsc_warn_printf(sc, "eeprom command failed\n");
407 			err = USB_ERR_IOERROR;
408 			break;
409 		}
410 
411 		if ((err = smsc_read_reg(sc, SMSC_EEPROM_DATA, &val)) != 0)
412 			goto done;
413 
414 		buf[i] = (val & 0xff);
415 	}
416 
417 done:
418 	if (!locked)
419 		SMSC_UNLOCK(sc);
420 
421 	return (err);
422 }
423 
424 /**
425  *	smsc_miibus_readreg - Reads a MII/MDIO register
426  *	@dev: usb ether device
427  *	@phy: the number of phy reading from
428  *	@reg: the register address
429  *
430  *	Attempts to read a phy register over the MII bus.
431  *
432  *	LOCKING:
433  *	Takes and releases the device mutex lock if not already held.
434  *
435  *	RETURNS:
436  *	Returns the 16-bits read from the MII register, if this function fails 0
437  *	is returned.
438  */
439 static int
440 smsc_miibus_readreg(device_t dev, int phy, int reg)
441 {
442 	struct smsc_softc *sc = device_get_softc(dev);
443 	int locked;
444 	uint32_t addr;
445 	uint32_t val = 0;
446 
447 	locked = mtx_owned(&sc->sc_mtx);
448 	if (!locked)
449 		SMSC_LOCK(sc);
450 
451 	if (smsc_wait_for_bits(sc, SMSC_MII_ADDR, SMSC_MII_BUSY) != 0) {
452 		smsc_warn_printf(sc, "MII is busy\n");
453 		goto done;
454 	}
455 
456 	addr = (phy << 11) | (reg << 6) | SMSC_MII_READ | SMSC_MII_BUSY;
457 	smsc_write_reg(sc, SMSC_MII_ADDR, addr);
458 
459 	if (smsc_wait_for_bits(sc, SMSC_MII_ADDR, SMSC_MII_BUSY) != 0)
460 		smsc_warn_printf(sc, "MII read timeout\n");
461 
462 	smsc_read_reg(sc, SMSC_MII_DATA, &val);
463 	val = le32toh(val);
464 
465 done:
466 	if (!locked)
467 		SMSC_UNLOCK(sc);
468 
469 	return (val & 0xFFFF);
470 }
471 
472 /**
473  *	smsc_miibus_writereg - Writes a MII/MDIO register
474  *	@dev: usb ether device
475  *	@phy: the number of phy writing to
476  *	@reg: the register address
477  *	@val: the value to write
478  *
479  *	Attempts to write a phy register over the MII bus.
480  *
481  *	LOCKING:
482  *	Takes and releases the device mutex lock if not already held.
483  *
484  *	RETURNS:
485  *	Always returns 0 regardless of success or failure.
486  */
487 static int
488 smsc_miibus_writereg(device_t dev, int phy, int reg, int val)
489 {
490 	struct smsc_softc *sc = device_get_softc(dev);
491 	int locked;
492 	uint32_t addr;
493 
494 	if (sc->sc_phyno != phy)
495 		return (0);
496 
497 	locked = mtx_owned(&sc->sc_mtx);
498 	if (!locked)
499 		SMSC_LOCK(sc);
500 
501 	if (smsc_wait_for_bits(sc, SMSC_MII_ADDR, SMSC_MII_BUSY) != 0) {
502 		smsc_warn_printf(sc, "MII is busy\n");
503 		goto done;
504 	}
505 
506 	val = htole32(val);
507 	smsc_write_reg(sc, SMSC_MII_DATA, val);
508 
509 	addr = (phy << 11) | (reg << 6) | SMSC_MII_WRITE | SMSC_MII_BUSY;
510 	smsc_write_reg(sc, SMSC_MII_ADDR, addr);
511 
512 	if (smsc_wait_for_bits(sc, SMSC_MII_ADDR, SMSC_MII_BUSY) != 0)
513 		smsc_warn_printf(sc, "MII write timeout\n");
514 
515 done:
516 	if (!locked)
517 		SMSC_UNLOCK(sc);
518 	return (0);
519 }
520 
521 
522 
523 /**
524  *	smsc_miibus_statchg - Called to detect phy status change
525  *	@dev: usb ether device
526  *
527  *	This function is called periodically by the system to poll for status
528  *	changes of the link.
529  *
530  *	LOCKING:
531  *	Takes and releases the device mutex lock if not already held.
532  */
533 static void
534 smsc_miibus_statchg(device_t dev)
535 {
536 	struct smsc_softc *sc = device_get_softc(dev);
537 	struct mii_data *mii = uether_getmii(&sc->sc_ue);
538 	struct ifnet *ifp;
539 	int locked;
540 	int err;
541 	uint32_t flow;
542 	uint32_t afc_cfg;
543 
544 	locked = mtx_owned(&sc->sc_mtx);
545 	if (!locked)
546 		SMSC_LOCK(sc);
547 
548 	ifp = uether_getifp(&sc->sc_ue);
549 	if (mii == NULL || ifp == NULL ||
550 	    (ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
551 		goto done;
552 
553 	/* Use the MII status to determine link status */
554 	sc->sc_flags &= ~SMSC_FLAG_LINK;
555 	if ((mii->mii_media_status & (IFM_ACTIVE | IFM_AVALID)) ==
556 	    (IFM_ACTIVE | IFM_AVALID)) {
557 		switch (IFM_SUBTYPE(mii->mii_media_active)) {
558 			case IFM_10_T:
559 			case IFM_100_TX:
560 				sc->sc_flags |= SMSC_FLAG_LINK;
561 				break;
562 			case IFM_1000_T:
563 				/* Gigabit ethernet not supported by chipset */
564 				break;
565 			default:
566 				break;
567 		}
568 	}
569 
570 	/* Lost link, do nothing. */
571 	if ((sc->sc_flags & SMSC_FLAG_LINK) == 0) {
572 		smsc_dbg_printf(sc, "link flag not set\n");
573 		goto done;
574 	}
575 
576 	err = smsc_read_reg(sc, SMSC_AFC_CFG, &afc_cfg);
577 	if (err) {
578 		smsc_warn_printf(sc, "failed to read initial AFC_CFG, error %d\n", err);
579 		goto done;
580 	}
581 
582 	/* Enable/disable full duplex operation and TX/RX pause */
583 	if ((IFM_OPTIONS(mii->mii_media_active) & IFM_FDX) != 0) {
584 		smsc_dbg_printf(sc, "full duplex operation\n");
585 		sc->sc_mac_csr &= ~SMSC_MAC_CSR_RCVOWN;
586 		sc->sc_mac_csr |= SMSC_MAC_CSR_FDPX;
587 
588 		if ((IFM_OPTIONS(mii->mii_media_active) & IFM_ETH_RXPAUSE) != 0)
589 			flow = 0xffff0002;
590 		else
591 			flow = 0;
592 
593 		if ((IFM_OPTIONS(mii->mii_media_active) & IFM_ETH_TXPAUSE) != 0)
594 			afc_cfg |= 0xf;
595 		else
596 			afc_cfg &= ~0xf;
597 
598 	} else {
599 		smsc_dbg_printf(sc, "half duplex operation\n");
600 		sc->sc_mac_csr &= ~SMSC_MAC_CSR_FDPX;
601 		sc->sc_mac_csr |= SMSC_MAC_CSR_RCVOWN;
602 
603 		flow = 0;
604 		afc_cfg |= 0xf;
605 	}
606 
607 	err = smsc_write_reg(sc, SMSC_MAC_CSR, sc->sc_mac_csr);
608 	err += smsc_write_reg(sc, SMSC_FLOW, flow);
609 	err += smsc_write_reg(sc, SMSC_AFC_CFG, afc_cfg);
610 	if (err)
611 		smsc_warn_printf(sc, "media change failed, error %d\n", err);
612 
613 done:
614 	if (!locked)
615 		SMSC_UNLOCK(sc);
616 }
617 
618 /**
619  *	smsc_ifmedia_upd - Set media options
620  *	@ifp: interface pointer
621  *
622  *	Basically boilerplate code that simply calls the mii functions to set the
623  *	media options.
624  *
625  *	LOCKING:
626  *	The device lock must be held before this function is called.
627  *
628  *	RETURNS:
629  *	Returns 0 on success or a negative error code.
630  */
631 static int
632 smsc_ifmedia_upd(struct ifnet *ifp)
633 {
634 	struct smsc_softc *sc = ifp->if_softc;
635 	struct mii_data *mii = uether_getmii(&sc->sc_ue);
636 	struct mii_softc *miisc;
637 	int err;
638 
639 	SMSC_LOCK_ASSERT(sc, MA_OWNED);
640 
641 	LIST_FOREACH(miisc, &mii->mii_phys, mii_list)
642 		PHY_RESET(miisc);
643 	err = mii_mediachg(mii);
644 	return (err);
645 }
646 
647 /**
648  *	smsc_ifmedia_sts - Report current media status
649  *	@ifp: inet interface pointer
650  *	@ifmr: interface media request
651  *
652  *	Basically boilerplate code that simply calls the mii functions to get the
653  *	media status.
654  *
655  *	LOCKING:
656  *	Internally takes and releases the device lock.
657  */
658 static void
659 smsc_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
660 {
661 	struct smsc_softc *sc = ifp->if_softc;
662 	struct mii_data *mii = uether_getmii(&sc->sc_ue);
663 
664 	SMSC_LOCK(sc);
665 	mii_pollstat(mii);
666 	ifmr->ifm_active = mii->mii_media_active;
667 	ifmr->ifm_status = mii->mii_media_status;
668 	SMSC_UNLOCK(sc);
669 }
670 
671 /**
672  *	smsc_hash - Calculate the hash of a mac address
673  *	@addr: The mac address to calculate the hash on
674  *
675  *	This function is used when configuring a range of m'cast mac addresses to
676  *	filter on.  The hash of the mac address is put in the device's mac hash
677  *	table.
678  *
679  *	RETURNS:
680  *	Returns a value from 0-63 value which is the hash of the mac address.
681  */
682 static inline uint32_t
683 smsc_hash(uint8_t addr[ETHER_ADDR_LEN])
684 {
685 	return (ether_crc32_be(addr, ETHER_ADDR_LEN) >> 26) & 0x3f;
686 }
687 
688 static u_int
689 smsc_hash_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
690 {
691 	uint32_t hash, *hashtbl = arg;
692 
693 	hash = smsc_hash(LLADDR(sdl));
694 	hashtbl[hash >> 5] |= 1 << (hash & 0x1F);
695 
696 	return (1);
697 }
698 
699 
700 /**
701  *	smsc_setmulti - Setup multicast
702  *	@ue: usb ethernet device context
703  *
704  *	Tells the device to either accept frames with a multicast mac address, a
705  *	select group of m'cast mac addresses or just the devices mac address.
706  *
707  *	LOCKING:
708  *	Should be called with the SMSC lock held.
709  */
710 static void
711 smsc_setmulti(struct usb_ether *ue)
712 {
713 	struct smsc_softc *sc = uether_getsc(ue);
714 	struct ifnet *ifp = uether_getifp(ue);
715 	uint32_t hashtbl[2] = { 0, 0 };
716 
717 	SMSC_LOCK_ASSERT(sc, MA_OWNED);
718 
719 	if (ifp->if_flags & (IFF_ALLMULTI | IFF_PROMISC)) {
720 		smsc_dbg_printf(sc, "receive all multicast enabled\n");
721 		sc->sc_mac_csr |= SMSC_MAC_CSR_MCPAS;
722 		sc->sc_mac_csr &= ~SMSC_MAC_CSR_HPFILT;
723 
724 	} else {
725 		if (if_foreach_llmaddr(ifp, smsc_hash_maddr, &hashtbl) > 0) {
726 			/* We are filtering on a set of address so calculate
727 			 * hashes of each of the address and set the
728 			 * corresponding bits in the register.
729 			 */
730 			sc->sc_mac_csr |= SMSC_MAC_CSR_HPFILT;
731 			sc->sc_mac_csr &= ~(SMSC_MAC_CSR_PRMS | SMSC_MAC_CSR_MCPAS);
732 		} else {
733 			/* Only receive packets with destination set to
734 			 * our mac address
735 			 */
736 			sc->sc_mac_csr &= ~(SMSC_MAC_CSR_MCPAS | SMSC_MAC_CSR_HPFILT);
737 		}
738 
739 		/* Debug */
740 		if (sc->sc_mac_csr & SMSC_MAC_CSR_HPFILT)
741 			smsc_dbg_printf(sc, "receive select group of macs\n");
742 		else
743 			smsc_dbg_printf(sc, "receive own packets only\n");
744 	}
745 
746 	/* Write the hash table and mac control registers */
747 	smsc_write_reg(sc, SMSC_HASHH, hashtbl[1]);
748 	smsc_write_reg(sc, SMSC_HASHL, hashtbl[0]);
749 	smsc_write_reg(sc, SMSC_MAC_CSR, sc->sc_mac_csr);
750 }
751 
752 
753 /**
754  *	smsc_setpromisc - Enables/disables promiscuous mode
755  *	@ue: usb ethernet device context
756  *
757  *	LOCKING:
758  *	Should be called with the SMSC lock held.
759  */
760 static void
761 smsc_setpromisc(struct usb_ether *ue)
762 {
763 	struct smsc_softc *sc = uether_getsc(ue);
764 	struct ifnet *ifp = uether_getifp(ue);
765 
766 	smsc_dbg_printf(sc, "promiscuous mode %sabled\n",
767 	                (ifp->if_flags & IFF_PROMISC) ? "en" : "dis");
768 
769 	SMSC_LOCK_ASSERT(sc, MA_OWNED);
770 
771 	if (ifp->if_flags & IFF_PROMISC)
772 		sc->sc_mac_csr |= SMSC_MAC_CSR_PRMS;
773 	else
774 		sc->sc_mac_csr &= ~SMSC_MAC_CSR_PRMS;
775 
776 	smsc_write_reg(sc, SMSC_MAC_CSR, sc->sc_mac_csr);
777 }
778 
779 
780 /**
781  *	smsc_sethwcsum - Enable or disable H/W UDP and TCP checksumming
782  *	@sc: driver soft context
783  *
784  *	LOCKING:
785  *	Should be called with the SMSC lock held.
786  *
787  *	RETURNS:
788  *	Returns 0 on success or a negative error code.
789  */
790 static int smsc_sethwcsum(struct smsc_softc *sc)
791 {
792 	struct ifnet *ifp = uether_getifp(&sc->sc_ue);
793 	uint32_t val;
794 	int err;
795 
796 	if (!ifp)
797 		return (-EIO);
798 
799 	SMSC_LOCK_ASSERT(sc, MA_OWNED);
800 
801 	err = smsc_read_reg(sc, SMSC_COE_CTRL, &val);
802 	if (err != 0) {
803 		smsc_warn_printf(sc, "failed to read SMSC_COE_CTRL (err=%d)\n", err);
804 		return (err);
805 	}
806 
807 	/* Enable/disable the Rx checksum */
808 	if ((ifp->if_capabilities & ifp->if_capenable) & IFCAP_RXCSUM)
809 		val |= SMSC_COE_CTRL_RX_EN;
810 	else
811 		val &= ~SMSC_COE_CTRL_RX_EN;
812 
813 	/* Enable/disable the Tx checksum (currently not supported) */
814 	if ((ifp->if_capabilities & ifp->if_capenable) & IFCAP_TXCSUM)
815 		val |= SMSC_COE_CTRL_TX_EN;
816 	else
817 		val &= ~SMSC_COE_CTRL_TX_EN;
818 
819 	err = smsc_write_reg(sc, SMSC_COE_CTRL, val);
820 	if (err != 0) {
821 		smsc_warn_printf(sc, "failed to write SMSC_COE_CTRL (err=%d)\n", err);
822 		return (err);
823 	}
824 
825 	return (0);
826 }
827 
828 /**
829  *	smsc_setmacaddress - Sets the mac address in the device
830  *	@sc: driver soft context
831  *	@addr: pointer to array contain at least 6 bytes of the mac
832  *
833  *	Writes the MAC address into the device, usually the MAC is programmed with
834  *	values from the EEPROM.
835  *
836  *	LOCKING:
837  *	Should be called with the SMSC lock held.
838  *
839  *	RETURNS:
840  *	Returns 0 on success or a negative error code.
841  */
842 static int
843 smsc_setmacaddress(struct smsc_softc *sc, const uint8_t *addr)
844 {
845 	int err;
846 	uint32_t val;
847 
848 	smsc_dbg_printf(sc, "setting mac address to %02x:%02x:%02x:%02x:%02x:%02x\n",
849 	                addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
850 
851 	SMSC_LOCK_ASSERT(sc, MA_OWNED);
852 
853 	val = (addr[3] << 24) | (addr[2] << 16) | (addr[1] << 8) | addr[0];
854 	if ((err = smsc_write_reg(sc, SMSC_MAC_ADDRL, val)) != 0)
855 		goto done;
856 
857 	val = (addr[5] << 8) | addr[4];
858 	err = smsc_write_reg(sc, SMSC_MAC_ADDRH, val);
859 
860 done:
861 	return (err);
862 }
863 
864 /**
865  *	smsc_reset - Reset the SMSC chip
866  *	@sc: device soft context
867  *
868  *	LOCKING:
869  *	Should be called with the SMSC lock held.
870  */
871 static void
872 smsc_reset(struct smsc_softc *sc)
873 {
874 	struct usb_config_descriptor *cd;
875 	usb_error_t err;
876 
877 	cd = usbd_get_config_descriptor(sc->sc_ue.ue_udev);
878 
879 	err = usbd_req_set_config(sc->sc_ue.ue_udev, &sc->sc_mtx,
880 	                          cd->bConfigurationValue);
881 	if (err)
882 		smsc_warn_printf(sc, "reset failed (ignored)\n");
883 
884 	/* Wait a little while for the chip to get its brains in order. */
885 	uether_pause(&sc->sc_ue, hz / 100);
886 
887 	/* Reinitialize controller to achieve full reset. */
888 	smsc_chip_init(sc);
889 }
890 
891 
892 /**
893  *	smsc_init - Initialises the LAN95xx chip
894  *	@ue: USB ether interface
895  *
896  *	Called when the interface is brought up (i.e. ifconfig ue0 up), this
897  *	initialise the interface and the rx/tx pipes.
898  *
899  *	LOCKING:
900  *	Should be called with the SMSC lock held.
901  */
902 static void
903 smsc_init(struct usb_ether *ue)
904 {
905 	struct smsc_softc *sc = uether_getsc(ue);
906 	struct ifnet *ifp = uether_getifp(ue);
907 
908 	SMSC_LOCK_ASSERT(sc, MA_OWNED);
909 
910 	if (smsc_setmacaddress(sc, IF_LLADDR(ifp)))
911 		smsc_dbg_printf(sc, "setting MAC address failed\n");
912 
913 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) != 0)
914 		return;
915 
916 	/* Cancel pending I/O */
917 	smsc_stop(ue);
918 
919 	/* Reset the ethernet interface. */
920 	smsc_reset(sc);
921 
922 	/* Load the multicast filter. */
923 	smsc_setmulti(ue);
924 
925 	/* TCP/UDP checksum offload engines. */
926 	smsc_sethwcsum(sc);
927 
928 	usbd_xfer_set_stall(sc->sc_xfer[SMSC_BULK_DT_WR]);
929 
930 	/* Indicate we are up and running. */
931 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
932 
933 	/* Switch to selected media. */
934 	smsc_ifmedia_upd(ifp);
935 	smsc_start(ue);
936 }
937 
938 /**
939  *	smsc_bulk_read_callback - Read callback used to process the USB URB
940  *	@xfer: the USB transfer
941  *	@error:
942  *
943  *	Reads the URB data which can contain one or more ethernet frames, the
944  *	frames are copyed into a mbuf and given to the system.
945  *
946  *	LOCKING:
947  *	No locking required, doesn't access internal driver settings.
948  */
949 static void
950 smsc_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error)
951 {
952 	struct smsc_softc *sc = usbd_xfer_softc(xfer);
953 	struct usb_ether *ue = &sc->sc_ue;
954 	struct ifnet *ifp = uether_getifp(ue);
955 	struct mbuf *m;
956 	struct usb_page_cache *pc;
957 	uint32_t rxhdr;
958 	int pktlen;
959 	int off;
960 	int actlen;
961 
962 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
963 	smsc_dbg_printf(sc, "rx : actlen %d\n", actlen);
964 
965 	switch (USB_GET_STATE(xfer)) {
966 	case USB_ST_TRANSFERRED:
967 
968 		/* There is always a zero length frame after bringing the IF up */
969 		if (actlen < (sizeof(rxhdr) + ETHER_CRC_LEN))
970 			goto tr_setup;
971 
972 		/* There maybe multiple packets in the USB frame, each will have a
973 		 * header and each needs to have it's own mbuf allocated and populated
974 		 * for it.
975 		 */
976 		pc = usbd_xfer_get_frame(xfer, 0);
977 		off = 0;
978 
979 		while (off < actlen) {
980 
981 			/* The frame header is always aligned on a 4 byte boundary */
982 			off = ((off + 0x3) & ~0x3);
983 
984 			if ((off + sizeof(rxhdr)) > actlen)
985 				goto tr_setup;
986 
987 			usbd_copy_out(pc, off, &rxhdr, sizeof(rxhdr));
988 			off += (sizeof(rxhdr) + ETHER_ALIGN);
989 			rxhdr = le32toh(rxhdr);
990 
991 			pktlen = (uint16_t)SMSC_RX_STAT_FRM_LENGTH(rxhdr);
992 
993 			smsc_dbg_printf(sc, "rx : rxhdr 0x%08x : pktlen %d : actlen %d : "
994 			                "off %d\n", rxhdr, pktlen, actlen, off);
995 
996 
997 			if (rxhdr & SMSC_RX_STAT_ERROR) {
998 				smsc_dbg_printf(sc, "rx error (hdr 0x%08x)\n", rxhdr);
999 				if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
1000 				if (rxhdr & SMSC_RX_STAT_COLLISION)
1001 					if_inc_counter(ifp, IFCOUNTER_COLLISIONS, 1);
1002 			} else {
1003 
1004 				/* Check if the ethernet frame is too big or too small */
1005 				if ((pktlen < ETHER_HDR_LEN) || (pktlen > (actlen - off)))
1006 					goto tr_setup;
1007 
1008 				/* Create a new mbuf to store the packet in */
1009 				m = uether_newbuf();
1010 				if (m == NULL) {
1011 					smsc_warn_printf(sc, "failed to create new mbuf\n");
1012 					if_inc_counter(ifp, IFCOUNTER_IQDROPS, 1);
1013 					goto tr_setup;
1014 				}
1015 				if (pktlen > m->m_len) {
1016 					smsc_dbg_printf(sc, "buffer too small %d vs %d bytes",
1017 					    pktlen, m->m_len);
1018 					if_inc_counter(ifp, IFCOUNTER_IQDROPS, 1);
1019 					m_freem(m);
1020 					goto tr_setup;
1021 				}
1022 				usbd_copy_out(pc, off, mtod(m, uint8_t *), pktlen);
1023 
1024 				/* Check if RX TCP/UDP checksumming is being offloaded */
1025 				if ((ifp->if_capenable & IFCAP_RXCSUM) != 0) {
1026 
1027 					struct ether_header *eh;
1028 
1029 					eh = mtod(m, struct ether_header *);
1030 
1031 					/* Remove the extra 2 bytes of the csum */
1032 					pktlen -= 2;
1033 
1034 					/* The checksum appears to be simplistically calculated
1035 					 * over the udp/tcp header and data up to the end of the
1036 					 * eth frame.  Which means if the eth frame is padded
1037 					 * the csum calculation is incorrectly performed over
1038 					 * the padding bytes as well. Therefore to be safe we
1039 					 * ignore the H/W csum on frames less than or equal to
1040 					 * 64 bytes.
1041 					 *
1042 					 * Ignore H/W csum for non-IPv4 packets.
1043 					 */
1044 					if ((be16toh(eh->ether_type) == ETHERTYPE_IP) &&
1045 					    (pktlen > ETHER_MIN_LEN)) {
1046 						struct ip *ip;
1047 
1048 						ip = (struct ip *)(eh + 1);
1049 						if ((ip->ip_v == IPVERSION) &&
1050 						    ((ip->ip_p == IPPROTO_TCP) ||
1051 						     (ip->ip_p == IPPROTO_UDP))) {
1052 							/* Indicate the UDP/TCP csum has been calculated */
1053 							m->m_pkthdr.csum_flags |= CSUM_DATA_VALID;
1054 
1055 							/* Copy the TCP/UDP checksum from the last 2 bytes
1056 							 * of the transfer and put in the csum_data field.
1057 							 */
1058 							usbd_copy_out(pc, (off + pktlen),
1059 							              &m->m_pkthdr.csum_data, 2);
1060 
1061 							/* The data is copied in network order, but the
1062 							 * csum algorithm in the kernel expects it to be
1063 							 * in host network order.
1064 							 */
1065 							m->m_pkthdr.csum_data = ntohs(m->m_pkthdr.csum_data);
1066 
1067 							smsc_dbg_printf(sc, "RX checksum offloaded (0x%04x)\n",
1068 							                m->m_pkthdr.csum_data);
1069 						}
1070 					}
1071 
1072 					/* Need to adjust the offset as well or we'll be off
1073 					 * by 2 because the csum is removed from the packet
1074 					 * length.
1075 					 */
1076 					off += 2;
1077 				}
1078 
1079 				/* Finally enqueue the mbuf on the receive queue */
1080 				/* Remove 4 trailing bytes */
1081 				if (pktlen < (4 + ETHER_HDR_LEN)) {
1082 					m_freem(m);
1083 					goto tr_setup;
1084 				}
1085 				uether_rxmbuf(ue, m, pktlen - 4);
1086 			}
1087 
1088 			/* Update the offset to move to the next potential packet */
1089 			off += pktlen;
1090 		}
1091 
1092 		/* FALLTHROUGH */
1093 
1094 	case USB_ST_SETUP:
1095 tr_setup:
1096 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
1097 		usbd_transfer_submit(xfer);
1098 		uether_rxflush(ue);
1099 		return;
1100 
1101 	default:
1102 		if (error != USB_ERR_CANCELLED) {
1103 			smsc_warn_printf(sc, "bulk read error, %s\n", usbd_errstr(error));
1104 			usbd_xfer_set_stall(xfer);
1105 			goto tr_setup;
1106 		}
1107 		return;
1108 	}
1109 }
1110 
1111 /**
1112  *	smsc_bulk_write_callback - Write callback used to send ethernet frame(s)
1113  *	@xfer: the USB transfer
1114  *	@error: error code if the transfers is in an errored state
1115  *
1116  *	The main write function that pulls ethernet frames off the queue and sends
1117  *	them out.
1118  *
1119  *	LOCKING:
1120  *
1121  */
1122 static void
1123 smsc_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error)
1124 {
1125 	struct smsc_softc *sc = usbd_xfer_softc(xfer);
1126 	struct ifnet *ifp = uether_getifp(&sc->sc_ue);
1127 	struct usb_page_cache *pc;
1128 	struct mbuf *m;
1129 	uint32_t txhdr;
1130 	uint32_t frm_len = 0;
1131 	int nframes;
1132 
1133 	switch (USB_GET_STATE(xfer)) {
1134 	case USB_ST_TRANSFERRED:
1135 		ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1136 		/* FALLTHROUGH */
1137 
1138 	case USB_ST_SETUP:
1139 tr_setup:
1140 		if ((sc->sc_flags & SMSC_FLAG_LINK) == 0 ||
1141 			(ifp->if_drv_flags & IFF_DRV_OACTIVE) != 0) {
1142 			/* Don't send anything if there is no link or controller is busy. */
1143 			return;
1144 		}
1145 
1146 		for (nframes = 0; nframes < 16 &&
1147 		    !IFQ_DRV_IS_EMPTY(&ifp->if_snd); nframes++) {
1148 			IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
1149 			if (m == NULL)
1150 				break;
1151 			usbd_xfer_set_frame_offset(xfer, nframes * MCLBYTES,
1152 			    nframes);
1153 			frm_len = 0;
1154 			pc = usbd_xfer_get_frame(xfer, nframes);
1155 
1156 			/* Each frame is prefixed with two 32-bit values describing the
1157 			 * length of the packet and buffer.
1158 			 */
1159 			txhdr = SMSC_TX_CTRL_0_BUF_SIZE(m->m_pkthdr.len) |
1160 					SMSC_TX_CTRL_0_FIRST_SEG | SMSC_TX_CTRL_0_LAST_SEG;
1161 			txhdr = htole32(txhdr);
1162 			usbd_copy_in(pc, 0, &txhdr, sizeof(txhdr));
1163 
1164 			txhdr = SMSC_TX_CTRL_1_PKT_LENGTH(m->m_pkthdr.len);
1165 			txhdr = htole32(txhdr);
1166 			usbd_copy_in(pc, 4, &txhdr, sizeof(txhdr));
1167 
1168 			frm_len += 8;
1169 
1170 			/* Next copy in the actual packet */
1171 			usbd_m_copy_in(pc, frm_len, m, 0, m->m_pkthdr.len);
1172 			frm_len += m->m_pkthdr.len;
1173 
1174 			if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
1175 
1176 			/* If there's a BPF listener, bounce a copy of this frame to him */
1177 			BPF_MTAP(ifp, m);
1178 
1179 			m_freem(m);
1180 
1181 			/* Set frame length. */
1182 			usbd_xfer_set_frame_len(xfer, nframes, frm_len);
1183 		}
1184 		if (nframes != 0) {
1185 			usbd_xfer_set_frames(xfer, nframes);
1186 			usbd_transfer_submit(xfer);
1187 			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1188 		}
1189 		return;
1190 
1191 	default:
1192 		if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
1193 		ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1194 
1195 		if (error != USB_ERR_CANCELLED) {
1196 			smsc_err_printf(sc, "usb error on tx: %s\n", usbd_errstr(error));
1197 			usbd_xfer_set_stall(xfer);
1198 			goto tr_setup;
1199 		}
1200 		return;
1201 	}
1202 }
1203 
1204 /**
1205  *	smsc_tick - Called periodically to monitor the state of the LAN95xx chip
1206  *	@ue: USB ether interface
1207  *
1208  *	Simply calls the mii status functions to check the state of the link.
1209  *
1210  *	LOCKING:
1211  *	Should be called with the SMSC lock held.
1212  */
1213 static void
1214 smsc_tick(struct usb_ether *ue)
1215 {
1216 	struct smsc_softc *sc = uether_getsc(ue);
1217 	struct mii_data *mii = uether_getmii(&sc->sc_ue);
1218 
1219 	SMSC_LOCK_ASSERT(sc, MA_OWNED);
1220 
1221 	mii_tick(mii);
1222 	if ((sc->sc_flags & SMSC_FLAG_LINK) == 0) {
1223 		smsc_miibus_statchg(ue->ue_dev);
1224 		if ((sc->sc_flags & SMSC_FLAG_LINK) != 0)
1225 			smsc_start(ue);
1226 	}
1227 }
1228 
1229 /**
1230  *	smsc_start - Starts communication with the LAN95xx chip
1231  *	@ue: USB ether interface
1232  *
1233  *
1234  *
1235  */
1236 static void
1237 smsc_start(struct usb_ether *ue)
1238 {
1239 	struct smsc_softc *sc = uether_getsc(ue);
1240 
1241 	/*
1242 	 * start the USB transfers, if not already started:
1243 	 */
1244 	usbd_transfer_start(sc->sc_xfer[SMSC_BULK_DT_RD]);
1245 	usbd_transfer_start(sc->sc_xfer[SMSC_BULK_DT_WR]);
1246 }
1247 
1248 /**
1249  *	smsc_stop - Stops communication with the LAN95xx chip
1250  *	@ue: USB ether interface
1251  *
1252  *
1253  *
1254  */
1255 static void
1256 smsc_stop(struct usb_ether *ue)
1257 {
1258 	struct smsc_softc *sc = uether_getsc(ue);
1259 	struct ifnet *ifp = uether_getifp(ue);
1260 
1261 	SMSC_LOCK_ASSERT(sc, MA_OWNED);
1262 
1263 	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
1264 	sc->sc_flags &= ~SMSC_FLAG_LINK;
1265 
1266 	/*
1267 	 * stop all the transfers, if not already stopped:
1268 	 */
1269 	usbd_transfer_stop(sc->sc_xfer[SMSC_BULK_DT_WR]);
1270 	usbd_transfer_stop(sc->sc_xfer[SMSC_BULK_DT_RD]);
1271 }
1272 
1273 /**
1274  *	smsc_phy_init - Initialises the in-built SMSC phy
1275  *	@sc: driver soft context
1276  *
1277  *	Resets the PHY part of the chip and then initialises it to default
1278  *	values.  The 'link down' and 'auto-negotiation complete' interrupts
1279  *	from the PHY are also enabled, however we don't monitor the interrupt
1280  *	endpoints for the moment.
1281  *
1282  *	RETURNS:
1283  *	Returns 0 on success or EIO if failed to reset the PHY.
1284  */
1285 static int
1286 smsc_phy_init(struct smsc_softc *sc)
1287 {
1288 	int bmcr;
1289 	usb_ticks_t start_ticks;
1290 	const usb_ticks_t max_ticks = USB_MS_TO_TICKS(1000);
1291 
1292 	SMSC_LOCK_ASSERT(sc, MA_OWNED);
1293 
1294 	/* Reset phy and wait for reset to complete */
1295 	smsc_miibus_writereg(sc->sc_ue.ue_dev, sc->sc_phyno, MII_BMCR, BMCR_RESET);
1296 
1297 	start_ticks = ticks;
1298 	do {
1299 		uether_pause(&sc->sc_ue, hz / 100);
1300 		bmcr = smsc_miibus_readreg(sc->sc_ue.ue_dev, sc->sc_phyno, MII_BMCR);
1301 	} while ((bmcr & BMCR_RESET) && ((ticks - start_ticks) < max_ticks));
1302 
1303 	if (((usb_ticks_t)(ticks - start_ticks)) >= max_ticks) {
1304 		smsc_err_printf(sc, "PHY reset timed-out");
1305 		return (EIO);
1306 	}
1307 
1308 	smsc_miibus_writereg(sc->sc_ue.ue_dev, sc->sc_phyno, MII_ANAR,
1309 	                     ANAR_10 | ANAR_10_FD | ANAR_TX | ANAR_TX_FD |  /* all modes */
1310 	                     ANAR_CSMA |
1311 	                     ANAR_FC |
1312 	                     ANAR_PAUSE_ASYM);
1313 
1314 	/* Setup the phy to interrupt when the link goes down or autoneg completes */
1315 	smsc_miibus_readreg(sc->sc_ue.ue_dev, sc->sc_phyno, SMSC_PHY_INTR_STAT);
1316 	smsc_miibus_writereg(sc->sc_ue.ue_dev, sc->sc_phyno, SMSC_PHY_INTR_MASK,
1317 	                     (SMSC_PHY_INTR_ANEG_COMP | SMSC_PHY_INTR_LINK_DOWN));
1318 
1319 	/* Restart auto-negotation */
1320 	bmcr = smsc_miibus_readreg(sc->sc_ue.ue_dev, sc->sc_phyno, MII_BMCR);
1321 	bmcr |= BMCR_STARTNEG;
1322 	smsc_miibus_writereg(sc->sc_ue.ue_dev, sc->sc_phyno, MII_BMCR, bmcr);
1323 
1324 	return (0);
1325 }
1326 
1327 
1328 /**
1329  *	smsc_chip_init - Initialises the chip after power on
1330  *	@sc: driver soft context
1331  *
1332  *	This initialisation sequence is modelled on the procedure in the Linux
1333  *	driver.
1334  *
1335  *	RETURNS:
1336  *	Returns 0 on success or an error code on failure.
1337  */
1338 static int
1339 smsc_chip_init(struct smsc_softc *sc)
1340 {
1341 	int err;
1342 	int locked;
1343 	uint32_t reg_val;
1344 	int burst_cap;
1345 
1346 	locked = mtx_owned(&sc->sc_mtx);
1347 	if (!locked)
1348 		SMSC_LOCK(sc);
1349 
1350 	/* Enter H/W config mode */
1351 	smsc_write_reg(sc, SMSC_HW_CFG, SMSC_HW_CFG_LRST);
1352 
1353 	if ((err = smsc_wait_for_bits(sc, SMSC_HW_CFG, SMSC_HW_CFG_LRST)) != 0) {
1354 		smsc_warn_printf(sc, "timed-out waiting for reset to complete\n");
1355 		goto init_failed;
1356 	}
1357 
1358 	/* Reset the PHY */
1359 	smsc_write_reg(sc, SMSC_PM_CTRL, SMSC_PM_CTRL_PHY_RST);
1360 
1361 	if ((err = smsc_wait_for_bits(sc, SMSC_PM_CTRL, SMSC_PM_CTRL_PHY_RST)) != 0) {
1362 		smsc_warn_printf(sc, "timed-out waiting for phy reset to complete\n");
1363 		goto init_failed;
1364 	}
1365 
1366 	/* Set the mac address */
1367 	if ((err = smsc_setmacaddress(sc, sc->sc_ue.ue_eaddr)) != 0) {
1368 		smsc_warn_printf(sc, "failed to set the MAC address\n");
1369 		goto init_failed;
1370 	}
1371 
1372 	/* Don't know what the HW_CFG_BIR bit is, but following the reset sequence
1373 	 * as used in the Linux driver.
1374 	 */
1375 	if ((err = smsc_read_reg(sc, SMSC_HW_CFG, &reg_val)) != 0) {
1376 		smsc_warn_printf(sc, "failed to read HW_CFG: %d\n", err);
1377 		goto init_failed;
1378 	}
1379 	reg_val |= SMSC_HW_CFG_BIR;
1380 	smsc_write_reg(sc, SMSC_HW_CFG, reg_val);
1381 
1382 	/* There is a so called 'turbo mode' that the linux driver supports, it
1383 	 * seems to allow you to jam multiple frames per Rx transaction.  By default
1384 	 * this driver supports that and therefore allows multiple frames per URB.
1385 	 *
1386 	 * The xfer buffer size needs to reflect this as well, therefore based on
1387 	 * the calculations in the Linux driver the RX bufsize is set to 18944,
1388 	 *     bufsz = (16 * 1024 + 5 * 512)
1389 	 *
1390 	 * Burst capability is the number of URBs that can be in a burst of data/
1391 	 * ethernet frames.
1392 	 */
1393 	if (usbd_get_speed(sc->sc_ue.ue_udev) == USB_SPEED_HIGH)
1394 		burst_cap = 37;
1395 	else
1396 		burst_cap = 128;
1397 
1398 	smsc_write_reg(sc, SMSC_BURST_CAP, burst_cap);
1399 
1400 	/* Set the default bulk in delay (magic value from Linux driver) */
1401 	smsc_write_reg(sc, SMSC_BULK_IN_DLY, 0x00002000);
1402 
1403 
1404 
1405 	/*
1406 	 * Initialise the RX interface
1407 	 */
1408 	if ((err = smsc_read_reg(sc, SMSC_HW_CFG, &reg_val)) < 0) {
1409 		smsc_warn_printf(sc, "failed to read HW_CFG: (err = %d)\n", err);
1410 		goto init_failed;
1411 	}
1412 
1413 	/* Adjust the packet offset in the buffer (designed to try and align IP
1414 	 * header on 4 byte boundary)
1415 	 */
1416 	reg_val &= ~SMSC_HW_CFG_RXDOFF;
1417 	reg_val |= (ETHER_ALIGN << 9) & SMSC_HW_CFG_RXDOFF;
1418 
1419 	/* The following setings are used for 'turbo mode', a.k.a multiple frames
1420 	 * per Rx transaction (again info taken form Linux driver).
1421 	 */
1422 	reg_val |= (SMSC_HW_CFG_MEF | SMSC_HW_CFG_BCE);
1423 
1424 	smsc_write_reg(sc, SMSC_HW_CFG, reg_val);
1425 
1426 	/* Clear the status register ? */
1427 	smsc_write_reg(sc, SMSC_INTR_STATUS, 0xffffffff);
1428 
1429 	/* Read and display the revision register */
1430 	if ((err = smsc_read_reg(sc, SMSC_ID_REV, &sc->sc_rev_id)) < 0) {
1431 		smsc_warn_printf(sc, "failed to read ID_REV (err = %d)\n", err);
1432 		goto init_failed;
1433 	}
1434 
1435 	device_printf(sc->sc_ue.ue_dev, "chip 0x%04lx, rev. %04lx\n",
1436 	    (sc->sc_rev_id & SMSC_ID_REV_CHIP_ID_MASK) >> 16,
1437 	    (sc->sc_rev_id & SMSC_ID_REV_CHIP_REV_MASK));
1438 
1439 	/* GPIO/LED setup */
1440 	reg_val = SMSC_LED_GPIO_CFG_SPD_LED | SMSC_LED_GPIO_CFG_LNK_LED |
1441 	          SMSC_LED_GPIO_CFG_FDX_LED;
1442 	smsc_write_reg(sc, SMSC_LED_GPIO_CFG, reg_val);
1443 
1444 	/*
1445 	 * Initialise the TX interface
1446 	 */
1447 	smsc_write_reg(sc, SMSC_FLOW, 0);
1448 
1449 	smsc_write_reg(sc, SMSC_AFC_CFG, AFC_CFG_DEFAULT);
1450 
1451 	/* Read the current MAC configuration */
1452 	if ((err = smsc_read_reg(sc, SMSC_MAC_CSR, &sc->sc_mac_csr)) < 0) {
1453 		smsc_warn_printf(sc, "failed to read MAC_CSR (err=%d)\n", err);
1454 		goto init_failed;
1455 	}
1456 
1457 	/* Vlan */
1458 	smsc_write_reg(sc, SMSC_VLAN1, (uint32_t)ETHERTYPE_VLAN);
1459 
1460 	/*
1461 	 * Initialise the PHY
1462 	 */
1463 	if ((err = smsc_phy_init(sc)) != 0)
1464 		goto init_failed;
1465 
1466 
1467 	/*
1468 	 * Start TX
1469 	 */
1470 	sc->sc_mac_csr |= SMSC_MAC_CSR_TXEN;
1471 	smsc_write_reg(sc, SMSC_MAC_CSR, sc->sc_mac_csr);
1472 	smsc_write_reg(sc, SMSC_TX_CFG, SMSC_TX_CFG_ON);
1473 
1474 	/*
1475 	 * Start RX
1476 	 */
1477 	sc->sc_mac_csr |= SMSC_MAC_CSR_RXEN;
1478 	smsc_write_reg(sc, SMSC_MAC_CSR, sc->sc_mac_csr);
1479 
1480 	if (!locked)
1481 		SMSC_UNLOCK(sc);
1482 
1483 	return (0);
1484 
1485 init_failed:
1486 	if (!locked)
1487 		SMSC_UNLOCK(sc);
1488 
1489 	smsc_err_printf(sc, "smsc_chip_init failed (err=%d)\n", err);
1490 	return (err);
1491 }
1492 
1493 
1494 /**
1495  *	smsc_ioctl - ioctl function for the device
1496  *	@ifp: interface pointer
1497  *	@cmd: the ioctl command
1498  *	@data: data passed in the ioctl call, typically a pointer to struct ifreq.
1499  *
1500  *	The ioctl routine is overridden to detect change requests for the H/W
1501  *	checksum capabilities.
1502  *
1503  *	RETURNS:
1504  *	0 on success and an error code on failure.
1505  */
1506 static int
1507 smsc_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1508 {
1509 	struct usb_ether *ue = ifp->if_softc;
1510 	struct smsc_softc *sc;
1511 	struct ifreq *ifr;
1512 	int rc;
1513 	int mask;
1514 	int reinit;
1515 
1516 	if (cmd == SIOCSIFCAP) {
1517 
1518 		sc = uether_getsc(ue);
1519 		ifr = (struct ifreq *)data;
1520 
1521 		SMSC_LOCK(sc);
1522 
1523 		rc = 0;
1524 		reinit = 0;
1525 
1526 		mask = ifr->ifr_reqcap ^ ifp->if_capenable;
1527 
1528 		/* Modify the RX CSUM enable bits */
1529 		if ((mask & IFCAP_RXCSUM) != 0 &&
1530 		    (ifp->if_capabilities & IFCAP_RXCSUM) != 0) {
1531 			ifp->if_capenable ^= IFCAP_RXCSUM;
1532 
1533 			if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1534 				ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1535 				reinit = 1;
1536 			}
1537 		}
1538 
1539 		SMSC_UNLOCK(sc);
1540 		if (reinit)
1541 			uether_init(ue);
1542 
1543 	} else {
1544 		rc = uether_ioctl(ifp, cmd, data);
1545 	}
1546 
1547 	return (rc);
1548 }
1549 
1550 /**
1551  *	smsc_attach_post - Called after the driver attached to the USB interface
1552  *	@ue: the USB ethernet device
1553  *
1554  *	This is where the chip is intialised for the first time.  This is different
1555  *	from the smsc_init() function in that that one is designed to setup the
1556  *	H/W to match the UE settings and can be called after a reset.
1557  *
1558  *
1559  */
1560 static void
1561 smsc_attach_post(struct usb_ether *ue)
1562 {
1563 	struct smsc_softc *sc = uether_getsc(ue);
1564 	uint32_t mac_h, mac_l;
1565 	int err;
1566 
1567 	smsc_dbg_printf(sc, "smsc_attach_post\n");
1568 
1569 	/* Setup some of the basics */
1570 	sc->sc_phyno = 1;
1571 
1572 
1573 	/* Attempt to get the mac address, if an EEPROM is not attached this
1574 	 * will just return FF:FF:FF:FF:FF:FF, so in such cases we invent a MAC
1575 	 * address based on urandom.
1576 	 */
1577 	memset(sc->sc_ue.ue_eaddr, 0xff, ETHER_ADDR_LEN);
1578 
1579 	/* Check if there is already a MAC address in the register */
1580 	if ((smsc_read_reg(sc, SMSC_MAC_ADDRL, &mac_l) == 0) &&
1581 	    (smsc_read_reg(sc, SMSC_MAC_ADDRH, &mac_h) == 0)) {
1582 		sc->sc_ue.ue_eaddr[5] = (uint8_t)((mac_h >> 8) & 0xff);
1583 		sc->sc_ue.ue_eaddr[4] = (uint8_t)((mac_h) & 0xff);
1584 		sc->sc_ue.ue_eaddr[3] = (uint8_t)((mac_l >> 24) & 0xff);
1585 		sc->sc_ue.ue_eaddr[2] = (uint8_t)((mac_l >> 16) & 0xff);
1586 		sc->sc_ue.ue_eaddr[1] = (uint8_t)((mac_l >> 8) & 0xff);
1587 		sc->sc_ue.ue_eaddr[0] = (uint8_t)((mac_l) & 0xff);
1588 	}
1589 
1590 	/* MAC address is not set so try to read from EEPROM, if that fails generate
1591 	 * a random MAC address.
1592 	 */
1593 	if (!ETHER_IS_VALID(sc->sc_ue.ue_eaddr)) {
1594 
1595 		err = smsc_eeprom_read(sc, 0x01, sc->sc_ue.ue_eaddr, ETHER_ADDR_LEN);
1596 #ifdef FDT
1597 		if ((err != 0) || (!ETHER_IS_VALID(sc->sc_ue.ue_eaddr)))
1598 			err = usb_fdt_get_mac_addr(sc->sc_ue.ue_dev, &sc->sc_ue);
1599 #endif
1600 		if ((err != 0) || (!ETHER_IS_VALID(sc->sc_ue.ue_eaddr))) {
1601 			read_random(sc->sc_ue.ue_eaddr, ETHER_ADDR_LEN);
1602 			sc->sc_ue.ue_eaddr[0] &= ~0x01;     /* unicast */
1603 			sc->sc_ue.ue_eaddr[0] |=  0x02;     /* locally administered */
1604 		}
1605 	}
1606 
1607 	/* Initialise the chip for the first time */
1608 	smsc_chip_init(sc);
1609 }
1610 
1611 
1612 /**
1613  *	smsc_attach_post_sub - Called after the driver attached to the USB interface
1614  *	@ue: the USB ethernet device
1615  *
1616  *	Most of this is boilerplate code and copied from the base USB ethernet
1617  *	driver.  It has been overriden so that we can indicate to the system that
1618  *	the chip supports H/W checksumming.
1619  *
1620  *	RETURNS:
1621  *	Returns 0 on success or a negative error code.
1622  */
1623 static int
1624 smsc_attach_post_sub(struct usb_ether *ue)
1625 {
1626 	struct smsc_softc *sc;
1627 	struct ifnet *ifp;
1628 	int error;
1629 
1630 	sc = uether_getsc(ue);
1631 	ifp = ue->ue_ifp;
1632 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
1633 	ifp->if_start = uether_start;
1634 	ifp->if_ioctl = smsc_ioctl;
1635 	ifp->if_init = uether_init;
1636 	IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
1637 	ifp->if_snd.ifq_drv_maxlen = ifqmaxlen;
1638 	IFQ_SET_READY(&ifp->if_snd);
1639 
1640 	/* The chip supports TCP/UDP checksum offloading on TX and RX paths, however
1641 	 * currently only RX checksum is supported in the driver (see top of file).
1642 	 */
1643 	ifp->if_capabilities |= IFCAP_RXCSUM | IFCAP_VLAN_MTU;
1644 	ifp->if_hwassist = 0;
1645 
1646 	/* TX checksuming is disabled (for now?)
1647 	ifp->if_capabilities |= IFCAP_TXCSUM;
1648 	ifp->if_capenable |= IFCAP_TXCSUM;
1649 	ifp->if_hwassist = CSUM_TCP | CSUM_UDP;
1650 	*/
1651 
1652 	ifp->if_capenable = ifp->if_capabilities;
1653 
1654 	mtx_lock(&Giant);
1655 	error = mii_attach(ue->ue_dev, &ue->ue_miibus, ifp,
1656 	    uether_ifmedia_upd, ue->ue_methods->ue_mii_sts,
1657 	    BMSR_DEFCAPMASK, sc->sc_phyno, MII_OFFSET_ANY, 0);
1658 	mtx_unlock(&Giant);
1659 
1660 	return (error);
1661 }
1662 
1663 
1664 /**
1665  *	smsc_probe - Probe the interface.
1666  *	@dev: smsc device handle
1667  *
1668  *	Checks if the device is a match for this driver.
1669  *
1670  *	RETURNS:
1671  *	Returns 0 on success or an error code on failure.
1672  */
1673 static int
1674 smsc_probe(device_t dev)
1675 {
1676 	struct usb_attach_arg *uaa = device_get_ivars(dev);
1677 
1678 	if (uaa->usb_mode != USB_MODE_HOST)
1679 		return (ENXIO);
1680 	if (uaa->info.bConfigIndex != SMSC_CONFIG_INDEX)
1681 		return (ENXIO);
1682 	if (uaa->info.bIfaceIndex != SMSC_IFACE_IDX)
1683 		return (ENXIO);
1684 
1685 	return (usbd_lookup_id_by_uaa(smsc_devs, sizeof(smsc_devs), uaa));
1686 }
1687 
1688 
1689 /**
1690  *	smsc_attach - Attach the interface.
1691  *	@dev: smsc device handle
1692  *
1693  *	Allocate softc structures, do ifmedia setup and ethernet/BPF attach.
1694  *
1695  *	RETURNS:
1696  *	Returns 0 on success or a negative error code.
1697  */
1698 static int
1699 smsc_attach(device_t dev)
1700 {
1701 	struct usb_attach_arg *uaa = device_get_ivars(dev);
1702 	struct smsc_softc *sc = device_get_softc(dev);
1703 	struct usb_ether *ue = &sc->sc_ue;
1704 	uint8_t iface_index;
1705 	int err;
1706 
1707 	sc->sc_flags = USB_GET_DRIVER_INFO(uaa);
1708 
1709 	device_set_usb_desc(dev);
1710 
1711 	mtx_init(&sc->sc_mtx, device_get_nameunit(dev), NULL, MTX_DEF);
1712 
1713 	/* Setup the endpoints for the SMSC LAN95xx device(s) */
1714 	iface_index = SMSC_IFACE_IDX;
1715 	err = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer,
1716 	                          smsc_config, SMSC_N_TRANSFER, sc, &sc->sc_mtx);
1717 	if (err) {
1718 		device_printf(dev, "error: allocating USB transfers failed\n");
1719 		goto detach;
1720 	}
1721 
1722 	ue->ue_sc = sc;
1723 	ue->ue_dev = dev;
1724 	ue->ue_udev = uaa->device;
1725 	ue->ue_mtx = &sc->sc_mtx;
1726 	ue->ue_methods = &smsc_ue_methods;
1727 
1728 	err = uether_ifattach(ue);
1729 	if (err) {
1730 		device_printf(dev, "error: could not attach interface\n");
1731 		goto detach;
1732 	}
1733 	return (0);			/* success */
1734 
1735 detach:
1736 	smsc_detach(dev);
1737 	return (ENXIO);		/* failure */
1738 }
1739 
1740 /**
1741  *	smsc_detach - Detach the interface.
1742  *	@dev: smsc device handle
1743  *
1744  *	RETURNS:
1745  *	Returns 0.
1746  */
1747 static int
1748 smsc_detach(device_t dev)
1749 {
1750 	struct smsc_softc *sc = device_get_softc(dev);
1751 	struct usb_ether *ue = &sc->sc_ue;
1752 
1753 	usbd_transfer_unsetup(sc->sc_xfer, SMSC_N_TRANSFER);
1754 	uether_ifdetach(ue);
1755 	mtx_destroy(&sc->sc_mtx);
1756 
1757 	return (0);
1758 }
1759 
1760 static device_method_t smsc_methods[] = {
1761 	/* Device interface */
1762 	DEVMETHOD(device_probe, smsc_probe),
1763 	DEVMETHOD(device_attach, smsc_attach),
1764 	DEVMETHOD(device_detach, smsc_detach),
1765 
1766 	/* bus interface */
1767 	DEVMETHOD(bus_print_child, bus_generic_print_child),
1768 	DEVMETHOD(bus_driver_added, bus_generic_driver_added),
1769 
1770 	/* MII interface */
1771 	DEVMETHOD(miibus_readreg, smsc_miibus_readreg),
1772 	DEVMETHOD(miibus_writereg, smsc_miibus_writereg),
1773 	DEVMETHOD(miibus_statchg, smsc_miibus_statchg),
1774 
1775 	DEVMETHOD_END
1776 };
1777 
1778 static driver_t smsc_driver = {
1779 	.name = "smsc",
1780 	.methods = smsc_methods,
1781 	.size = sizeof(struct smsc_softc),
1782 };
1783 
1784 static devclass_t smsc_devclass;
1785 
1786 DRIVER_MODULE(smsc, uhub, smsc_driver, smsc_devclass, NULL, 0);
1787 DRIVER_MODULE(miibus, smsc, miibus_driver, miibus_devclass, 0, 0);
1788 MODULE_DEPEND(smsc, uether, 1, 1, 1);
1789 MODULE_DEPEND(smsc, usb, 1, 1, 1);
1790 MODULE_DEPEND(smsc, ether, 1, 1, 1);
1791 MODULE_DEPEND(smsc, miibus, 1, 1, 1);
1792 MODULE_VERSION(smsc, 1);
1793 USB_PNP_HOST_INFO(smsc_devs);
1794