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