xref: /freebsd/sys/dev/usb/net/if_smsc.c (revision c243e4902be8df1e643c76b5f18b68bb77cc5268)
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 	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 ((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 	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 ((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 				uether_rxmbuf(ue, m, pktlen);
1046 			}
1047 
1048 			/* Update the offset to move to the next potential packet */
1049 			off += pktlen;
1050 		}
1051 
1052 		/* FALLTHROUGH */
1053 
1054 	case USB_ST_SETUP:
1055 tr_setup:
1056 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
1057 		usbd_transfer_submit(xfer);
1058 		uether_rxflush(ue);
1059 		return;
1060 
1061 	default:
1062 		if (error != USB_ERR_CANCELLED) {
1063 			smsc_warn_printf(sc, "bulk read error, %s\n", usbd_errstr(error));
1064 			usbd_xfer_set_stall(xfer);
1065 			goto tr_setup;
1066 		}
1067 		return;
1068 	}
1069 }
1070 
1071 /**
1072  *	smsc_bulk_write_callback - Write callback used to send ethernet frame(s)
1073  *	@xfer: the USB transfer
1074  *	@error: error code if the transfers is in an errored state
1075  *
1076  *	The main write function that pulls ethernet frames off the queue and sends
1077  *	them out.
1078  *
1079  *	LOCKING:
1080  *
1081  */
1082 static void
1083 smsc_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error)
1084 {
1085 	struct smsc_softc *sc = usbd_xfer_softc(xfer);
1086 	struct ifnet *ifp = uether_getifp(&sc->sc_ue);
1087 	struct usb_page_cache *pc;
1088 	struct mbuf *m;
1089 	uint32_t txhdr;
1090 	uint32_t frm_len = 0;
1091 	int nframes;
1092 
1093 	switch (USB_GET_STATE(xfer)) {
1094 	case USB_ST_TRANSFERRED:
1095 		ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1096 		/* FALLTHROUGH */
1097 
1098 	case USB_ST_SETUP:
1099 tr_setup:
1100 		if ((sc->sc_flags & SMSC_FLAG_LINK) == 0 ||
1101 			(ifp->if_drv_flags & IFF_DRV_OACTIVE) != 0) {
1102 			/* Don't send anything if there is no link or controller is busy. */
1103 			return;
1104 		}
1105 
1106 		for (nframes = 0; nframes < 16 &&
1107 		    !IFQ_DRV_IS_EMPTY(&ifp->if_snd); nframes++) {
1108 			IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
1109 			if (m == NULL)
1110 				break;
1111 			usbd_xfer_set_frame_offset(xfer, nframes * MCLBYTES,
1112 			    nframes);
1113 			frm_len = 0;
1114 			pc = usbd_xfer_get_frame(xfer, nframes);
1115 
1116 			/* Each frame is prefixed with two 32-bit values describing the
1117 			 * length of the packet and buffer.
1118 			 */
1119 			txhdr = SMSC_TX_CTRL_0_BUF_SIZE(m->m_pkthdr.len) |
1120 					SMSC_TX_CTRL_0_FIRST_SEG | SMSC_TX_CTRL_0_LAST_SEG;
1121 			txhdr = htole32(txhdr);
1122 			usbd_copy_in(pc, 0, &txhdr, sizeof(txhdr));
1123 
1124 			txhdr = SMSC_TX_CTRL_1_PKT_LENGTH(m->m_pkthdr.len);
1125 			txhdr = htole32(txhdr);
1126 			usbd_copy_in(pc, 4, &txhdr, sizeof(txhdr));
1127 
1128 			frm_len += 8;
1129 
1130 			/* Next copy in the actual packet */
1131 			usbd_m_copy_in(pc, frm_len, m, 0, m->m_pkthdr.len);
1132 			frm_len += m->m_pkthdr.len;
1133 
1134 			ifp->if_opackets++;
1135 
1136 			/* If there's a BPF listener, bounce a copy of this frame to him */
1137 			BPF_MTAP(ifp, m);
1138 
1139 			m_freem(m);
1140 
1141 			/* Set frame length. */
1142 			usbd_xfer_set_frame_len(xfer, nframes, frm_len);
1143 		}
1144 		if (nframes != 0) {
1145 			usbd_xfer_set_frames(xfer, nframes);
1146 			usbd_transfer_submit(xfer);
1147 			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1148 		}
1149 		return;
1150 
1151 	default:
1152 		ifp->if_oerrors++;
1153 		ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1154 
1155 		if (error != USB_ERR_CANCELLED) {
1156 			smsc_err_printf(sc, "usb error on tx: %s\n", usbd_errstr(error));
1157 			usbd_xfer_set_stall(xfer);
1158 			goto tr_setup;
1159 		}
1160 		return;
1161 	}
1162 }
1163 
1164 /**
1165  *	smsc_tick - Called periodically to monitor the state of the LAN95xx chip
1166  *	@ue: USB ether interface
1167  *
1168  *	Simply calls the mii status functions to check the state of the link.
1169  *
1170  *	LOCKING:
1171  *	Should be called with the SMSC lock held.
1172  */
1173 static void
1174 smsc_tick(struct usb_ether *ue)
1175 {
1176 	struct smsc_softc *sc = uether_getsc(ue);
1177 	struct mii_data *mii = uether_getmii(&sc->sc_ue);;
1178 
1179 	SMSC_LOCK_ASSERT(sc, MA_OWNED);
1180 
1181 	mii_tick(mii);
1182 	if ((sc->sc_flags & SMSC_FLAG_LINK) == 0) {
1183 		smsc_miibus_statchg(ue->ue_dev);
1184 		if ((sc->sc_flags & SMSC_FLAG_LINK) != 0)
1185 			smsc_start(ue);
1186 	}
1187 }
1188 
1189 /**
1190  *	smsc_start - Starts communication with the LAN95xx chip
1191  *	@ue: USB ether interface
1192  *
1193  *
1194  *
1195  */
1196 static void
1197 smsc_start(struct usb_ether *ue)
1198 {
1199 	struct smsc_softc *sc = uether_getsc(ue);
1200 
1201 	/*
1202 	 * start the USB transfers, if not already started:
1203 	 */
1204 	usbd_transfer_start(sc->sc_xfer[SMSC_BULK_DT_RD]);
1205 	usbd_transfer_start(sc->sc_xfer[SMSC_BULK_DT_WR]);
1206 }
1207 
1208 /**
1209  *	smsc_stop - Stops communication with the LAN95xx chip
1210  *	@ue: USB ether interface
1211  *
1212  *
1213  *
1214  */
1215 static void
1216 smsc_stop(struct usb_ether *ue)
1217 {
1218 	struct smsc_softc *sc = uether_getsc(ue);
1219 	struct ifnet *ifp = uether_getifp(ue);
1220 
1221 	SMSC_LOCK_ASSERT(sc, MA_OWNED);
1222 
1223 	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
1224 	sc->sc_flags &= ~SMSC_FLAG_LINK;
1225 
1226 	/*
1227 	 * stop all the transfers, if not already stopped:
1228 	 */
1229 	usbd_transfer_stop(sc->sc_xfer[SMSC_BULK_DT_WR]);
1230 	usbd_transfer_stop(sc->sc_xfer[SMSC_BULK_DT_RD]);
1231 }
1232 
1233 /**
1234  *	smsc_phy_init - Initialises the in-built SMSC phy
1235  *	@sc: driver soft context
1236  *
1237  *	Resets the PHY part of the chip and then initialises it to default
1238  *	values.  The 'link down' and 'auto-negotiation complete' interrupts
1239  *	from the PHY are also enabled, however we don't monitor the interrupt
1240  *	endpoints for the moment.
1241  *
1242  *	RETURNS:
1243  *	Returns 0 on success or EIO if failed to reset the PHY.
1244  */
1245 static int
1246 smsc_phy_init(struct smsc_softc *sc)
1247 {
1248 	int bmcr;
1249 	usb_ticks_t start_ticks;
1250 	usb_ticks_t max_ticks = USB_MS_TO_TICKS(1000);
1251 
1252 	SMSC_LOCK_ASSERT(sc, MA_OWNED);
1253 
1254 	/* Reset phy and wait for reset to complete */
1255 	smsc_miibus_writereg(sc->sc_ue.ue_dev, sc->sc_phyno, MII_BMCR, BMCR_RESET);
1256 
1257 	start_ticks = ticks;
1258 	do {
1259 		uether_pause(&sc->sc_ue, hz / 100);
1260 		bmcr = smsc_miibus_readreg(sc->sc_ue.ue_dev, sc->sc_phyno, MII_BMCR);
1261 	} while ((bmcr & MII_BMCR) && ((ticks - start_ticks) < max_ticks));
1262 
1263 	if ((ticks - start_ticks) >= max_ticks) {
1264 		smsc_err_printf(sc, "PHY reset timed-out");
1265 		return (EIO);
1266 	}
1267 
1268 	smsc_miibus_writereg(sc->sc_ue.ue_dev, sc->sc_phyno, MII_ANAR,
1269 	                     ANAR_10 | ANAR_10_FD | ANAR_TX | ANAR_TX_FD |  /* all modes */
1270 	                     ANAR_CSMA |
1271 	                     ANAR_FC |
1272 	                     ANAR_PAUSE_ASYM);
1273 
1274 	/* Setup the phy to interrupt when the link goes down or autoneg completes */
1275 	smsc_miibus_readreg(sc->sc_ue.ue_dev, sc->sc_phyno, SMSC_PHY_INTR_STAT);
1276 	smsc_miibus_writereg(sc->sc_ue.ue_dev, sc->sc_phyno, SMSC_PHY_INTR_MASK,
1277 	                     (SMSC_PHY_INTR_ANEG_COMP | SMSC_PHY_INTR_LINK_DOWN));
1278 
1279 	/* Restart auto-negotation */
1280 	bmcr = smsc_miibus_readreg(sc->sc_ue.ue_dev, sc->sc_phyno, MII_BMCR);
1281 	bmcr |= BMCR_STARTNEG;
1282 	smsc_miibus_writereg(sc->sc_ue.ue_dev, sc->sc_phyno, MII_BMCR, bmcr);
1283 
1284 	return (0);
1285 }
1286 
1287 
1288 /**
1289  *	smsc_chip_init - Initialises the chip after power on
1290  *	@sc: driver soft context
1291  *
1292  *	This initialisation sequence is modelled on the procedure in the Linux
1293  *	driver.
1294  *
1295  *	RETURNS:
1296  *	Returns 0 on success or an error code on failure.
1297  */
1298 static int
1299 smsc_chip_init(struct smsc_softc *sc)
1300 {
1301 	int err;
1302 	int locked;
1303 	uint32_t reg_val;
1304 	int burst_cap;
1305 
1306 	locked = mtx_owned(&sc->sc_mtx);
1307 	if (!locked)
1308 		SMSC_LOCK(sc);
1309 
1310 	/* Enter H/W config mode */
1311 	smsc_write_reg(sc, SMSC_HW_CFG, SMSC_HW_CFG_LRST);
1312 
1313 	if ((err = smsc_wait_for_bits(sc, SMSC_HW_CFG, SMSC_HW_CFG_LRST)) != 0) {
1314 		smsc_warn_printf(sc, "timed-out waiting for reset to complete\n");
1315 		goto init_failed;
1316 	}
1317 
1318 	/* Reset the PHY */
1319 	smsc_write_reg(sc, SMSC_PM_CTRL, SMSC_PM_CTRL_PHY_RST);
1320 
1321 	if ((err = smsc_wait_for_bits(sc, SMSC_PM_CTRL, SMSC_PM_CTRL_PHY_RST) != 0)) {
1322 		smsc_warn_printf(sc, "timed-out waiting for phy reset to complete\n");
1323 		goto init_failed;
1324 	}
1325 
1326 	/* Set the mac address */
1327 	if ((err = smsc_setmacaddress(sc, sc->sc_ue.ue_eaddr)) != 0) {
1328 		smsc_warn_printf(sc, "failed to set the MAC address\n");
1329 		goto init_failed;
1330 	}
1331 
1332 	/* Don't know what the HW_CFG_BIR bit is, but following the reset sequence
1333 	 * as used in the Linux driver.
1334 	 */
1335 	if ((err = smsc_read_reg(sc, SMSC_HW_CFG, &reg_val)) != 0) {
1336 		smsc_warn_printf(sc, "failed to read HW_CFG: %d\n", err);
1337 		goto init_failed;
1338 	}
1339 	reg_val |= SMSC_HW_CFG_BIR;
1340 	smsc_write_reg(sc, SMSC_HW_CFG, reg_val);
1341 
1342 	/* There is a so called 'turbo mode' that the linux driver supports, it
1343 	 * seems to allow you to jam multiple frames per Rx transaction.  By default
1344 	 * this driver supports that and therefore allows multiple frames per URB.
1345 	 *
1346 	 * The xfer buffer size needs to reflect this as well, therefore based on
1347 	 * the calculations in the Linux driver the RX bufsize is set to 18944,
1348 	 *     bufsz = (16 * 1024 + 5 * 512)
1349 	 *
1350 	 * Burst capability is the number of URBs that can be in a burst of data/
1351 	 * ethernet frames.
1352 	 */
1353 	if (usbd_get_speed(sc->sc_ue.ue_udev) == USB_SPEED_HIGH)
1354 		burst_cap = 37;
1355 	else
1356 		burst_cap = 128;
1357 
1358 	smsc_write_reg(sc, SMSC_BURST_CAP, burst_cap);
1359 
1360 	/* Set the default bulk in delay (magic value from Linux driver) */
1361 	smsc_write_reg(sc, SMSC_BULK_IN_DLY, 0x00002000);
1362 
1363 
1364 
1365 	/*
1366 	 * Initialise the RX interface
1367 	 */
1368 	if ((err = smsc_read_reg(sc, SMSC_HW_CFG, &reg_val)) < 0) {
1369 		smsc_warn_printf(sc, "failed to read HW_CFG: (err = %d)\n", err);
1370 		goto init_failed;
1371 	}
1372 
1373 	/* Adjust the packet offset in the buffer (designed to try and align IP
1374 	 * header on 4 byte boundary)
1375 	 */
1376 	reg_val &= ~SMSC_HW_CFG_RXDOFF;
1377 	reg_val |= (ETHER_ALIGN << 9) & SMSC_HW_CFG_RXDOFF;
1378 
1379 	/* The following setings are used for 'turbo mode', a.k.a multiple frames
1380 	 * per Rx transaction (again info taken form Linux driver).
1381 	 */
1382 	reg_val |= (SMSC_HW_CFG_MEF | SMSC_HW_CFG_BCE);
1383 
1384 	smsc_write_reg(sc, SMSC_HW_CFG, reg_val);
1385 
1386 	/* Clear the status register ? */
1387 	smsc_write_reg(sc, SMSC_INTR_STATUS, 0xffffffff);
1388 
1389 	/* Read and display the revision register */
1390 	if ((err = smsc_read_reg(sc, SMSC_ID_REV, &sc->sc_rev_id)) < 0) {
1391 		smsc_warn_printf(sc, "failed to read ID_REV (err = %d)\n", err);
1392 		goto init_failed;
1393 	}
1394 
1395 	device_printf(sc->sc_ue.ue_dev, "chip 0x%04lx, rev. %04lx\n",
1396 	    (sc->sc_rev_id & SMSC_ID_REV_CHIP_ID_MASK) >> 16,
1397 	    (sc->sc_rev_id & SMSC_ID_REV_CHIP_REV_MASK));
1398 
1399 	/* GPIO/LED setup */
1400 	reg_val = SMSC_LED_GPIO_CFG_SPD_LED | SMSC_LED_GPIO_CFG_LNK_LED |
1401 	          SMSC_LED_GPIO_CFG_FDX_LED;
1402 	smsc_write_reg(sc, SMSC_LED_GPIO_CFG, reg_val);
1403 
1404 	/*
1405 	 * Initialise the TX interface
1406 	 */
1407 	smsc_write_reg(sc, SMSC_FLOW, 0);
1408 
1409 	smsc_write_reg(sc, SMSC_AFC_CFG, AFC_CFG_DEFAULT);
1410 
1411 	/* Read the current MAC configuration */
1412 	if ((err = smsc_read_reg(sc, SMSC_MAC_CSR, &sc->sc_mac_csr)) < 0) {
1413 		smsc_warn_printf(sc, "failed to read MAC_CSR (err=%d)\n", err);
1414 		goto init_failed;
1415 	}
1416 
1417 	/* Vlan */
1418 	smsc_write_reg(sc, SMSC_VLAN1, (uint32_t)ETHERTYPE_VLAN);
1419 
1420 	/*
1421 	 * Initialise the PHY
1422 	 */
1423 	if ((err = smsc_phy_init(sc)) != 0)
1424 		goto init_failed;
1425 
1426 
1427 	/*
1428 	 * Start TX
1429 	 */
1430 	sc->sc_mac_csr |= SMSC_MAC_CSR_TXEN;
1431 	smsc_write_reg(sc, SMSC_MAC_CSR, sc->sc_mac_csr);
1432 	smsc_write_reg(sc, SMSC_TX_CFG, SMSC_TX_CFG_ON);
1433 
1434 	/*
1435 	 * Start RX
1436 	 */
1437 	sc->sc_mac_csr |= SMSC_MAC_CSR_RXEN;
1438 	smsc_write_reg(sc, SMSC_MAC_CSR, sc->sc_mac_csr);
1439 
1440 	if (!locked)
1441 		SMSC_UNLOCK(sc);
1442 
1443 	return (0);
1444 
1445 init_failed:
1446 	if (!locked)
1447 		SMSC_UNLOCK(sc);
1448 
1449 	smsc_err_printf(sc, "smsc_chip_init failed (err=%d)\n", err);
1450 	return (err);
1451 }
1452 
1453 
1454 /**
1455  *	smsc_ioctl - ioctl function for the device
1456  *	@ifp: interface pointer
1457  *	@cmd: the ioctl command
1458  *	@data: data passed in the ioctl call, typically a pointer to struct ifreq.
1459  *
1460  *	The ioctl routine is overridden to detect change requests for the H/W
1461  *	checksum capabilities.
1462  *
1463  *	RETURNS:
1464  *	0 on success and an error code on failure.
1465  */
1466 static int
1467 smsc_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1468 {
1469 	struct usb_ether *ue = ifp->if_softc;
1470 	struct smsc_softc *sc;
1471 	struct ifreq *ifr;
1472 	int rc;
1473 	int mask;
1474 	int reinit;
1475 
1476 	if (cmd == SIOCSIFCAP) {
1477 
1478 		sc = uether_getsc(ue);
1479 		ifr = (struct ifreq *)data;
1480 
1481 		SMSC_LOCK(sc);
1482 
1483 		rc = 0;
1484 		reinit = 0;
1485 
1486 		mask = ifr->ifr_reqcap ^ ifp->if_capenable;
1487 
1488 		/* Modify the RX CSUM enable bits */
1489 		if ((mask & IFCAP_RXCSUM) != 0 &&
1490 		    (ifp->if_capabilities & IFCAP_RXCSUM) != 0) {
1491 			ifp->if_capenable ^= IFCAP_RXCSUM;
1492 
1493 			if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1494 				ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1495 				reinit = 1;
1496 			}
1497 		}
1498 
1499 		SMSC_UNLOCK(sc);
1500 		if (reinit)
1501 #if __FreeBSD_version > 1000000
1502 			uether_init(ue);
1503 #else
1504 			ifp->if_init(ue);
1505 #endif
1506 
1507 	} else {
1508 		rc = uether_ioctl(ifp, cmd, data);
1509 	}
1510 
1511 	return (rc);
1512 }
1513 
1514 
1515 /**
1516  *	smsc_attach_post - Called after the driver attached to the USB interface
1517  *	@ue: the USB ethernet device
1518  *
1519  *	This is where the chip is intialised for the first time.  This is different
1520  *	from the smsc_init() function in that that one is designed to setup the
1521  *	H/W to match the UE settings and can be called after a reset.
1522  *
1523  *
1524  */
1525 static void
1526 smsc_attach_post(struct usb_ether *ue)
1527 {
1528 	struct smsc_softc *sc = uether_getsc(ue);
1529 	uint32_t mac_h, mac_l;
1530 	int err;
1531 
1532 	smsc_dbg_printf(sc, "smsc_attach_post\n");
1533 
1534 	/* Setup some of the basics */
1535 	sc->sc_phyno = 1;
1536 
1537 
1538 	/* Attempt to get the mac address, if an EEPROM is not attached this
1539 	 * will just return FF:FF:FF:FF:FF:FF, so in such cases we invent a MAC
1540 	 * address based on urandom.
1541 	 */
1542 	memset(sc->sc_ue.ue_eaddr, 0xff, ETHER_ADDR_LEN);
1543 
1544 	/* Check if there is already a MAC address in the register */
1545 	if ((smsc_read_reg(sc, SMSC_MAC_ADDRL, &mac_l) == 0) &&
1546 	    (smsc_read_reg(sc, SMSC_MAC_ADDRH, &mac_h) == 0)) {
1547 		sc->sc_ue.ue_eaddr[5] = (uint8_t)((mac_h >> 8) & 0xff);
1548 		sc->sc_ue.ue_eaddr[4] = (uint8_t)((mac_h) & 0xff);
1549 		sc->sc_ue.ue_eaddr[3] = (uint8_t)((mac_l >> 24) & 0xff);
1550 		sc->sc_ue.ue_eaddr[2] = (uint8_t)((mac_l >> 16) & 0xff);
1551 		sc->sc_ue.ue_eaddr[1] = (uint8_t)((mac_l >> 8) & 0xff);
1552 		sc->sc_ue.ue_eaddr[0] = (uint8_t)((mac_l) & 0xff);
1553 	}
1554 
1555 	/* MAC address is not set so try to read from EEPROM, if that fails generate
1556 	 * a random MAC address.
1557 	 */
1558 	if (!ETHER_IS_VALID(sc->sc_ue.ue_eaddr)) {
1559 
1560 		err = smsc_eeprom_read(sc, 0x01, sc->sc_ue.ue_eaddr, ETHER_ADDR_LEN);
1561 		if ((err != 0) || (!ETHER_IS_VALID(sc->sc_ue.ue_eaddr))) {
1562 
1563 			read_random(sc->sc_ue.ue_eaddr, ETHER_ADDR_LEN);
1564 			sc->sc_ue.ue_eaddr[0] &= ~0x01;     /* unicast */
1565 			sc->sc_ue.ue_eaddr[0] |=  0x02;     /* locally administered */
1566 		}
1567 	}
1568 
1569 	/* Initialise the chip for the first time */
1570 	smsc_chip_init(sc);
1571 }
1572 
1573 
1574 /**
1575  *	smsc_attach_post_sub - Called after the driver attached to the USB interface
1576  *	@ue: the USB ethernet device
1577  *
1578  *	Most of this is boilerplate code and copied from the base USB ethernet
1579  *	driver.  It has been overriden so that we can indicate to the system that
1580  *	the chip supports H/W checksumming.
1581  *
1582  *	RETURNS:
1583  *	Returns 0 on success or a negative error code.
1584  */
1585 #if __FreeBSD_version > 1000000
1586 static int
1587 smsc_attach_post_sub(struct usb_ether *ue)
1588 {
1589 	struct smsc_softc *sc;
1590 	struct ifnet *ifp;
1591 	int error;
1592 
1593 	sc = uether_getsc(ue);
1594 	ifp = ue->ue_ifp;
1595 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
1596 	ifp->if_start = uether_start;
1597 	ifp->if_ioctl = smsc_ioctl;
1598 	ifp->if_init = uether_init;
1599 	IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
1600 	ifp->if_snd.ifq_drv_maxlen = ifqmaxlen;
1601 	IFQ_SET_READY(&ifp->if_snd);
1602 
1603 	/* The chip supports TCP/UDP checksum offloading on TX and RX paths, however
1604 	 * currently only RX checksum is supported in the driver (see top of file).
1605 	 */
1606 	ifp->if_capabilities |= IFCAP_RXCSUM;
1607 	ifp->if_hwassist = 0;
1608 
1609 	/* TX checksuming is disabled (for now?)
1610 	ifp->if_capabilities |= IFCAP_TXCSUM;
1611 	ifp->if_capenable |= IFCAP_TXCSUM;
1612 	ifp->if_hwassist = CSUM_TCP | CSUM_UDP;
1613 	*/
1614 
1615 	ifp->if_capenable = ifp->if_capabilities;
1616 
1617 	mtx_lock(&Giant);
1618 	error = mii_attach(ue->ue_dev, &ue->ue_miibus, ifp,
1619 	    uether_ifmedia_upd, ue->ue_methods->ue_mii_sts,
1620 	    BMSR_DEFCAPMASK, sc->sc_phyno, MII_OFFSET_ANY, 0);
1621 	mtx_unlock(&Giant);
1622 
1623 	return (error);
1624 }
1625 #endif /* __FreeBSD_version > 1000000 */
1626 
1627 
1628 /**
1629  *	smsc_probe - Probe the interface.
1630  *	@dev: smsc device handle
1631  *
1632  *	Checks if the device is a match for this driver.
1633  *
1634  *	RETURNS:
1635  *	Returns 0 on success or an error code on failure.
1636  */
1637 static int
1638 smsc_probe(device_t dev)
1639 {
1640 	struct usb_attach_arg *uaa = device_get_ivars(dev);
1641 
1642 	if (uaa->usb_mode != USB_MODE_HOST)
1643 		return (ENXIO);
1644 	if (uaa->info.bConfigIndex != SMSC_CONFIG_INDEX)
1645 		return (ENXIO);
1646 	if (uaa->info.bIfaceIndex != SMSC_IFACE_IDX)
1647 		return (ENXIO);
1648 
1649 	return (usbd_lookup_id_by_uaa(smsc_devs, sizeof(smsc_devs), uaa));
1650 }
1651 
1652 
1653 /**
1654  *	smsc_attach - Attach the interface.
1655  *	@dev: smsc device handle
1656  *
1657  *	Allocate softc structures, do ifmedia setup and ethernet/BPF attach.
1658  *
1659  *	RETURNS:
1660  *	Returns 0 on success or a negative error code.
1661  */
1662 static int
1663 smsc_attach(device_t dev)
1664 {
1665 	struct usb_attach_arg *uaa = device_get_ivars(dev);
1666 	struct smsc_softc *sc = device_get_softc(dev);
1667 	struct usb_ether *ue = &sc->sc_ue;
1668 	uint8_t iface_index;
1669 	int err;
1670 
1671 	sc->sc_flags = USB_GET_DRIVER_INFO(uaa);
1672 
1673 	device_set_usb_desc(dev);
1674 
1675 	mtx_init(&sc->sc_mtx, device_get_nameunit(dev), NULL, MTX_DEF);
1676 
1677 	/* Setup the endpoints for the SMSC LAN95xx device(s) */
1678 	iface_index = SMSC_IFACE_IDX;
1679 	err = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer,
1680 	                          smsc_config, SMSC_N_TRANSFER, sc, &sc->sc_mtx);
1681 	if (err) {
1682 		device_printf(dev, "error: allocating USB transfers failed\n");
1683 		goto detach;
1684 	}
1685 
1686 	ue->ue_sc = sc;
1687 	ue->ue_dev = dev;
1688 	ue->ue_udev = uaa->device;
1689 	ue->ue_mtx = &sc->sc_mtx;
1690 	ue->ue_methods = &smsc_ue_methods;
1691 
1692 	err = uether_ifattach(ue);
1693 	if (err) {
1694 		device_printf(dev, "error: could not attach interface\n");
1695 		goto detach;
1696 	}
1697 	return (0);			/* success */
1698 
1699 detach:
1700 	smsc_detach(dev);
1701 	return (ENXIO);		/* failure */
1702 }
1703 
1704 /**
1705  *	smsc_detach - Detach the interface.
1706  *	@dev: smsc device handle
1707  *
1708  *	RETURNS:
1709  *	Returns 0.
1710  */
1711 static int
1712 smsc_detach(device_t dev)
1713 {
1714 	struct smsc_softc *sc = device_get_softc(dev);
1715 	struct usb_ether *ue = &sc->sc_ue;
1716 
1717 	usbd_transfer_unsetup(sc->sc_xfer, SMSC_N_TRANSFER);
1718 	uether_ifdetach(ue);
1719 	mtx_destroy(&sc->sc_mtx);
1720 
1721 	return (0);
1722 }
1723 
1724 static device_method_t smsc_methods[] = {
1725 	/* Device interface */
1726 	DEVMETHOD(device_probe, smsc_probe),
1727 	DEVMETHOD(device_attach, smsc_attach),
1728 	DEVMETHOD(device_detach, smsc_detach),
1729 
1730 	/* bus interface */
1731 	DEVMETHOD(bus_print_child, bus_generic_print_child),
1732 	DEVMETHOD(bus_driver_added, bus_generic_driver_added),
1733 
1734 	/* MII interface */
1735 	DEVMETHOD(miibus_readreg, smsc_miibus_readreg),
1736 	DEVMETHOD(miibus_writereg, smsc_miibus_writereg),
1737 	DEVMETHOD(miibus_statchg, smsc_miibus_statchg),
1738 
1739 	{0, 0}
1740 };
1741 
1742 static driver_t smsc_driver = {
1743 	.name = "smsc",
1744 	.methods = smsc_methods,
1745 	.size = sizeof(struct smsc_softc),
1746 };
1747 
1748 static devclass_t smsc_devclass;
1749 
1750 DRIVER_MODULE(smsc, uhub, smsc_driver, smsc_devclass, NULL, 0);
1751 DRIVER_MODULE(miibus, smsc, miibus_driver, miibus_devclass, 0, 0);
1752 MODULE_DEPEND(smsc, uether, 1, 1, 1);
1753 MODULE_DEPEND(smsc, usb, 1, 1, 1);
1754 MODULE_DEPEND(smsc, ether, 1, 1, 1);
1755 MODULE_DEPEND(smsc, miibus, 1, 1, 1);
1756 MODULE_VERSION(smsc, 1);
1757