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