Home | History | Annotate | Line # | Download | only in usb
usbnet.c revision 1.98
      1 /*	$NetBSD: usbnet.c,v 1.98 2022/08/20 12:28:25 riastradh Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 2019 Matthew R. Green
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
     21  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
     22  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
     23  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
     24  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     26  * SUCH DAMAGE.
     27  */
     28 
     29 /*
     30  * Common code shared between USB network drivers.
     31  */
     32 
     33 #include <sys/cdefs.h>
     34 __KERNEL_RCSID(0, "$NetBSD: usbnet.c,v 1.98 2022/08/20 12:28:25 riastradh Exp $");
     35 
     36 #include <sys/param.h>
     37 #include <sys/kernel.h>
     38 #include <sys/kmem.h>
     39 #include <sys/module.h>
     40 #include <sys/atomic.h>
     41 
     42 #include <dev/usb/usbnet.h>
     43 #include <dev/usb/usbhist.h>
     44 
     45 struct usbnet_cdata {
     46 	struct usbnet_chain	*uncd_tx_chain;
     47 	struct usbnet_chain	*uncd_rx_chain;
     48 
     49 	int			uncd_tx_prod;
     50 	int			uncd_tx_cnt;
     51 };
     52 
     53 struct usbnet_private {
     54 	/*
     55 	 * - unp_core_lock protects most of this structure, the public one,
     56 	 *   and the MII / media data.
     57 	 * - unp_rxlock protects the rx path and its data
     58 	 * - unp_txlock protects the tx path and its data
     59 	 *
     60 	 * the lock ordering is:
     61 	 *	ifnet lock -> unp_core_lock -> unp_rxlock -> unp_txlock
     62 	 *				    -> unp_mcastlock
     63 	 * - ifnet lock is not needed for unp_core_lock, but if ifnet lock is
     64 	 *   involved, it must be taken first
     65 	 */
     66 	kmutex_t		unp_core_lock;
     67 	kmutex_t		unp_rxlock;
     68 	kmutex_t		unp_txlock;
     69 
     70 	kmutex_t		unp_mcastlock;
     71 	bool			unp_mcastactive;
     72 
     73 	struct usbnet_cdata	unp_cdata;
     74 
     75 	struct ethercom		unp_ec;
     76 	struct mii_data		unp_mii;
     77 	struct usb_task		unp_ticktask;
     78 	struct callout		unp_stat_ch;
     79 	struct usbd_pipe	*unp_ep[USBNET_ENDPT_MAX];
     80 
     81 	volatile bool		unp_dying;
     82 	bool			unp_stopping;
     83 	bool			unp_attached;
     84 	bool			unp_ifp_attached;
     85 	bool			unp_link;
     86 
     87 	int			unp_timer;
     88 	unsigned short		unp_if_flags;
     89 	unsigned		unp_number;
     90 
     91 	krndsource_t		unp_rndsrc;
     92 
     93 	struct timeval		unp_rx_notice;
     94 	struct timeval		unp_tx_notice;
     95 	struct timeval		unp_intr_notice;
     96 };
     97 
     98 #define un_cdata(un)	(&(un)->un_pri->unp_cdata)
     99 
    100 volatile unsigned usbnet_number;
    101 
    102 static void usbnet_isowned_rx(struct usbnet *);
    103 static void usbnet_isowned_tx(struct usbnet *);
    104 
    105 static inline void
    106 usbnet_isowned_core(struct usbnet *un)
    107 {
    108 	KASSERT(mutex_owned(&un->un_pri->unp_core_lock));
    109 }
    110 
    111 static int usbnet_modcmd(modcmd_t, void *);
    112 
    113 #ifdef USB_DEBUG
    114 #ifndef USBNET_DEBUG
    115 #define usbnetdebug 0
    116 #else
    117 static int usbnetdebug = 0;
    118 
    119 SYSCTL_SETUP(sysctl_hw_usbnet_setup, "sysctl hw.usbnet setup")
    120 {
    121 	int err;
    122 	const struct sysctlnode *rnode;
    123 	const struct sysctlnode *cnode;
    124 
    125 	err = sysctl_createv(clog, 0, NULL, &rnode,
    126 	    CTLFLAG_PERMANENT, CTLTYPE_NODE, "usbnet",
    127 	    SYSCTL_DESCR("usbnet global controls"),
    128 	    NULL, 0, NULL, 0, CTL_HW, CTL_CREATE, CTL_EOL);
    129 
    130 	if (err)
    131 		goto fail;
    132 
    133 	/* control debugging printfs */
    134 	err = sysctl_createv(clog, 0, &rnode, &cnode,
    135 	    CTLFLAG_PERMANENT | CTLFLAG_READWRITE, CTLTYPE_INT,
    136 	    "debug", SYSCTL_DESCR("Enable debugging output"),
    137 	    NULL, 0, &usbnetdebug, sizeof(usbnetdebug), CTL_CREATE, CTL_EOL);
    138 	if (err)
    139 		goto fail;
    140 
    141 	return;
    142 fail:
    143 	aprint_error("%s: sysctl_createv failed (err = %d)\n", __func__, err);
    144 }
    145 
    146 #endif /* USBNET_DEBUG */
    147 #endif /* USB_DEBUG */
    148 
    149 #define DPRINTF(FMT,A,B,C,D)	USBHIST_LOGN(usbnetdebug,1,FMT,A,B,C,D)
    150 #define DPRINTFN(N,FMT,A,B,C,D)	USBHIST_LOGN(usbnetdebug,N,FMT,A,B,C,D)
    151 #define USBNETHIST_FUNC()	USBHIST_FUNC()
    152 #define USBNETHIST_CALLED(name)	USBHIST_CALLED(usbnetdebug)
    153 #define USBNETHIST_CALLARGS(FMT,A,B,C,D) \
    154 				USBHIST_CALLARGS(usbnetdebug,FMT,A,B,C,D)
    155 #define USBNETHIST_CALLARGSN(N,FMT,A,B,C,D) \
    156 				USBHIST_CALLARGSN(usbnetdebug,N,FMT,A,B,C,D)
    157 
    158 /* Callback vectors. */
    159 
    160 static void
    161 uno_stop(struct usbnet *un, struct ifnet *ifp, int disable)
    162 {
    163 	KASSERTMSG(IFNET_LOCKED(ifp), "%s", ifp->if_xname);
    164 	usbnet_isowned_core(un);
    165 	if (un->un_ops->uno_stop)
    166 		(*un->un_ops->uno_stop)(ifp, disable);
    167 }
    168 
    169 static int
    170 uno_ioctl(struct usbnet *un, struct ifnet *ifp, u_long cmd, void *data)
    171 {
    172 
    173 	KASSERTMSG(cmd != SIOCADDMULTI, "%s", ifp->if_xname);
    174 	KASSERTMSG(cmd != SIOCDELMULTI, "%s", ifp->if_xname);
    175 	KASSERTMSG(IFNET_LOCKED(ifp), "%s", ifp->if_xname);
    176 
    177 	if (un->un_ops->uno_ioctl)
    178 		return (*un->un_ops->uno_ioctl)(ifp, cmd, data);
    179 	return 0;
    180 }
    181 
    182 static int
    183 uno_override_ioctl(struct usbnet *un, struct ifnet *ifp, u_long cmd, void *data)
    184 {
    185 
    186 	switch (cmd) {
    187 	case SIOCADDMULTI:
    188 	case SIOCDELMULTI:
    189 		break;
    190 	default:
    191 		KASSERTMSG(IFNET_LOCKED(ifp), "%s", ifp->if_xname);
    192 	}
    193 
    194 	return (*un->un_ops->uno_override_ioctl)(ifp, cmd, data);
    195 }
    196 
    197 static int
    198 uno_init(struct usbnet *un, struct ifnet *ifp)
    199 {
    200 	KASSERTMSG(IFNET_LOCKED(ifp), "%s", ifp->if_xname);
    201 	return un->un_ops->uno_init ? (*un->un_ops->uno_init)(ifp) : 0;
    202 }
    203 
    204 static int
    205 uno_read_reg(struct usbnet *un, int phy, int reg, uint16_t *val)
    206 {
    207 	usbnet_isowned_core(un);
    208 	return (*un->un_ops->uno_read_reg)(un, phy, reg, val);
    209 }
    210 
    211 static int
    212 uno_write_reg(struct usbnet *un, int phy, int reg, uint16_t val)
    213 {
    214 	usbnet_isowned_core(un);
    215 	return (*un->un_ops->uno_write_reg)(un, phy, reg, val);
    216 }
    217 
    218 static void
    219 uno_mii_statchg(struct usbnet *un, struct ifnet *ifp)
    220 {
    221 	usbnet_isowned_core(un);
    222 	(*un->un_ops->uno_statchg)(ifp);
    223 }
    224 
    225 static unsigned
    226 uno_tx_prepare(struct usbnet *un, struct mbuf *m, struct usbnet_chain *c)
    227 {
    228 	usbnet_isowned_tx(un);
    229 	return (*un->un_ops->uno_tx_prepare)(un, m, c);
    230 }
    231 
    232 static void
    233 uno_rx_loop(struct usbnet *un, struct usbnet_chain *c, uint32_t total_len)
    234 {
    235 	usbnet_isowned_rx(un);
    236 	(*un->un_ops->uno_rx_loop)(un, c, total_len);
    237 }
    238 
    239 static void
    240 uno_tick(struct usbnet *un)
    241 {
    242 	if (un->un_ops->uno_tick)
    243 		(*un->un_ops->uno_tick)(un);
    244 }
    245 
    246 static void
    247 uno_intr(struct usbnet *un, usbd_status status)
    248 {
    249 	if (un->un_ops->uno_intr)
    250 		(*un->un_ops->uno_intr)(un, status);
    251 }
    252 
    253 /* Interrupt handling. */
    254 
    255 static struct mbuf *
    256 usbnet_newbuf(size_t buflen)
    257 {
    258 	struct mbuf *m;
    259 
    260 	if (buflen > MCLBYTES - ETHER_ALIGN)
    261 		return NULL;
    262 
    263 	MGETHDR(m, M_DONTWAIT, MT_DATA);
    264 	if (m == NULL)
    265 		return NULL;
    266 
    267 	if (buflen > MHLEN - ETHER_ALIGN) {
    268 		MCLGET(m, M_DONTWAIT);
    269 		if (!(m->m_flags & M_EXT)) {
    270 			m_freem(m);
    271 			return NULL;
    272 		}
    273 	}
    274 
    275 	m->m_len = m->m_pkthdr.len = ETHER_ALIGN + buflen;
    276 	m_adj(m, ETHER_ALIGN);
    277 
    278 	return m;
    279 }
    280 
    281 /*
    282  * usbnet_rxeof() is designed to be the done callback for rx completion.
    283  * it provides generic setup and finalisation, calls a different usbnet
    284  * rx_loop callback in the middle, which can use usbnet_enqueue() to
    285  * enqueue a packet for higher levels (or usbnet_input() if previously
    286  * using if_input() path.)
    287  */
    288 void
    289 usbnet_enqueue(struct usbnet * const un, uint8_t *buf, size_t buflen,
    290 	       int csum_flags, uint32_t csum_data, int mbuf_flags)
    291 {
    292 	USBNETHIST_FUNC();
    293 	struct ifnet * const ifp = usbnet_ifp(un);
    294 	struct usbnet_private * const unp __unused = un->un_pri;
    295 	struct mbuf *m;
    296 
    297 	USBNETHIST_CALLARGSN(5, "%jd: enter: len=%ju csf %#jx mbf %#jx",
    298 	    unp->unp_number, buflen, csum_flags, mbuf_flags);
    299 
    300 	usbnet_isowned_rx(un);
    301 
    302 	m = usbnet_newbuf(buflen);
    303 	if (m == NULL) {
    304 		DPRINTF("%jd: no memory", unp->unp_number, 0, 0, 0);
    305 		if_statinc(ifp, if_ierrors);
    306 		return;
    307 	}
    308 
    309 	m_set_rcvif(m, ifp);
    310 	m->m_pkthdr.csum_flags = csum_flags;
    311 	m->m_pkthdr.csum_data = csum_data;
    312 	m->m_flags |= mbuf_flags;
    313 	memcpy(mtod(m, uint8_t *), buf, buflen);
    314 
    315 	/* push the packet up */
    316 	if_percpuq_enqueue(ifp->if_percpuq, m);
    317 }
    318 
    319 void
    320 usbnet_input(struct usbnet * const un, uint8_t *buf, size_t buflen)
    321 {
    322 	USBNETHIST_FUNC();
    323 	struct ifnet * const ifp = usbnet_ifp(un);
    324 	struct usbnet_private * const unp __unused = un->un_pri;
    325 	struct mbuf *m;
    326 
    327 	USBNETHIST_CALLARGSN(5, "%jd: enter: buf %#jx len %ju",
    328 	    unp->unp_number, (uintptr_t)buf, buflen, 0);
    329 
    330 	usbnet_isowned_rx(un);
    331 
    332 	m = usbnet_newbuf(buflen);
    333 	if (m == NULL) {
    334 		if_statinc(ifp, if_ierrors);
    335 		return;
    336 	}
    337 
    338 	m_set_rcvif(m, ifp);
    339 	memcpy(mtod(m, char *), buf, buflen);
    340 
    341 	/* push the packet up */
    342 	if_input(ifp, m);
    343 }
    344 
    345 /*
    346  * A frame has been uploaded: pass the resulting mbuf chain up to
    347  * the higher level protocols.
    348  */
    349 static void
    350 usbnet_rxeof(struct usbd_xfer *xfer, void *priv, usbd_status status)
    351 {
    352 	USBNETHIST_FUNC();
    353 	struct usbnet_chain * const c = priv;
    354 	struct usbnet * const un = c->unc_un;
    355 	struct usbnet_private * const unp = un->un_pri;
    356 	uint32_t total_len;
    357 
    358 	USBNETHIST_CALLARGSN(5, "%jd: enter: status %#jx xfer %#jx",
    359 	    unp->unp_number, status, (uintptr_t)xfer, 0);
    360 
    361 	mutex_enter(&unp->unp_rxlock);
    362 
    363 	if (usbnet_isdying(un) || unp->unp_stopping ||
    364 	    status == USBD_INVAL || status == USBD_NOT_STARTED ||
    365 	    status == USBD_CANCELLED)
    366 		goto out;
    367 
    368 	if (status != USBD_NORMAL_COMPLETION) {
    369 		if (usbd_ratecheck(&unp->unp_rx_notice))
    370 			device_printf(un->un_dev, "usb errors on rx: %s\n",
    371 			    usbd_errstr(status));
    372 		if (status == USBD_STALLED)
    373 			usbd_clear_endpoint_stall_async(unp->unp_ep[USBNET_ENDPT_RX]);
    374 		goto done;
    375 	}
    376 
    377 	usbd_get_xfer_status(xfer, NULL, NULL, &total_len, NULL);
    378 
    379 	if (total_len > un->un_rx_bufsz) {
    380 		aprint_error_dev(un->un_dev,
    381 		    "rxeof: too large transfer (%u > %u)\n",
    382 		    total_len, un->un_rx_bufsz);
    383 		goto done;
    384 	}
    385 
    386 	uno_rx_loop(un, c, total_len);
    387 	usbnet_isowned_rx(un);
    388 
    389 done:
    390 	if (usbnet_isdying(un) || unp->unp_stopping)
    391 		goto out;
    392 
    393 	mutex_exit(&unp->unp_rxlock);
    394 
    395 	/* Setup new transfer. */
    396 	usbd_setup_xfer(xfer, c, c->unc_buf, un->un_rx_bufsz,
    397 	    un->un_rx_xfer_flags, USBD_NO_TIMEOUT, usbnet_rxeof);
    398 	usbd_transfer(xfer);
    399 	return;
    400 
    401 out:
    402 	mutex_exit(&unp->unp_rxlock);
    403 }
    404 
    405 static void
    406 usbnet_txeof(struct usbd_xfer *xfer, void *priv, usbd_status status)
    407 {
    408 	USBNETHIST_FUNC(); USBNETHIST_CALLED();
    409 	struct usbnet_chain * const c = priv;
    410 	struct usbnet * const un = c->unc_un;
    411 	struct usbnet_cdata * const cd = un_cdata(un);
    412 	struct usbnet_private * const unp = un->un_pri;
    413 	struct ifnet * const ifp = usbnet_ifp(un);
    414 
    415 	USBNETHIST_CALLARGSN(5, "%jd: enter: status %#jx xfer %#jx",
    416 	    unp->unp_number, status, (uintptr_t)xfer, 0);
    417 
    418 	mutex_enter(&unp->unp_txlock);
    419 	if (unp->unp_stopping || usbnet_isdying(un)) {
    420 		mutex_exit(&unp->unp_txlock);
    421 		return;
    422 	}
    423 
    424 	KASSERT(cd->uncd_tx_cnt > 0);
    425 	cd->uncd_tx_cnt--;
    426 
    427 	unp->unp_timer = 0;
    428 
    429 	switch (status) {
    430 	case USBD_NOT_STARTED:
    431 	case USBD_CANCELLED:
    432 		break;
    433 
    434 	case USBD_NORMAL_COMPLETION:
    435 		if_statinc(ifp, if_opackets);
    436 		break;
    437 
    438 	default:
    439 
    440 		if_statinc(ifp, if_oerrors);
    441 		if (usbd_ratecheck(&unp->unp_tx_notice))
    442 			device_printf(un->un_dev, "usb error on tx: %s\n",
    443 			    usbd_errstr(status));
    444 		if (status == USBD_STALLED)
    445 			usbd_clear_endpoint_stall_async(unp->unp_ep[USBNET_ENDPT_TX]);
    446 		break;
    447 	}
    448 
    449 	mutex_exit(&unp->unp_txlock);
    450 
    451 	if (status == USBD_NORMAL_COMPLETION && !IFQ_IS_EMPTY(&ifp->if_snd))
    452 		(*ifp->if_start)(ifp);
    453 }
    454 
    455 static void
    456 usbnet_pipe_intr(struct usbd_xfer *xfer, void *priv, usbd_status status)
    457 {
    458 	USBNETHIST_FUNC();
    459 	struct usbnet * const un = priv;
    460 	struct usbnet_private * const unp = un->un_pri;
    461 	struct usbnet_intr * const uni = un->un_intr;
    462 
    463 	if (uni == NULL || usbnet_isdying(un) || unp->unp_stopping ||
    464 	    status == USBD_INVAL || status == USBD_NOT_STARTED ||
    465 	    status == USBD_CANCELLED) {
    466 		USBNETHIST_CALLARGS("%jd: uni %#jx d/s %#jx status %#jx",
    467 		    unp->unp_number, (uintptr_t)uni,
    468 		    (usbnet_isdying(un) << 8) | unp->unp_stopping, status);
    469 		return;
    470 	}
    471 
    472 	if (status != USBD_NORMAL_COMPLETION) {
    473 		if (usbd_ratecheck(&unp->unp_intr_notice)) {
    474 			aprint_error_dev(un->un_dev, "usb error on intr: %s\n",
    475 			    usbd_errstr(status));
    476 		}
    477 		if (status == USBD_STALLED)
    478 			usbd_clear_endpoint_stall_async(unp->unp_ep[USBNET_ENDPT_INTR]);
    479 		USBNETHIST_CALLARGS("%jd: not normal status %#jx",
    480 		    unp->unp_number, status, 0, 0);
    481 		return;
    482 	}
    483 
    484 	uno_intr(un, status);
    485 }
    486 
    487 static void
    488 usbnet_start_locked(struct ifnet *ifp)
    489 {
    490 	USBNETHIST_FUNC();
    491 	struct usbnet * const un = ifp->if_softc;
    492 	struct usbnet_cdata * const cd = un_cdata(un);
    493 	struct usbnet_private * const unp = un->un_pri;
    494 	struct mbuf *m;
    495 	unsigned length;
    496 	bool done_transmit = false;
    497 	int idx, count;
    498 
    499 	USBNETHIST_CALLARGS("%jd: tx_cnt %jd list_cnt %jd link %jd",
    500 	    unp->unp_number, cd->uncd_tx_cnt, un->un_tx_list_cnt,
    501 	    unp->unp_link);
    502 
    503 	usbnet_isowned_tx(un);
    504 	KASSERT(cd->uncd_tx_cnt <= un->un_tx_list_cnt);
    505 
    506 	if (!unp->unp_link || (ifp->if_flags & IFF_RUNNING) == 0) {
    507 		DPRINTF("start called no link (%jx) or running (flags %jx)",
    508 		    unp->unp_link, ifp->if_flags, 0, 0);
    509 		return;
    510 	}
    511 
    512 	if (cd->uncd_tx_cnt == un->un_tx_list_cnt) {
    513 		DPRINTF("start called, tx busy (%#jx == %#jx)",
    514 		    cd->uncd_tx_cnt, un->un_tx_list_cnt, 0, 0);
    515 		return;
    516 	}
    517 
    518 	idx = cd->uncd_tx_prod;
    519 	count = 0;
    520 	while (cd->uncd_tx_cnt < un->un_tx_list_cnt) {
    521 		IFQ_POLL(&ifp->if_snd, m);
    522 		if (m == NULL) {
    523 			DPRINTF("start called, queue empty", 0, 0, 0, 0);
    524 			break;
    525 		}
    526 		KASSERT(m->m_pkthdr.len <= un->un_tx_bufsz);
    527 
    528 		struct usbnet_chain *c = &cd->uncd_tx_chain[idx];
    529 
    530 		length = uno_tx_prepare(un, m, c);
    531 		if (length == 0) {
    532 			DPRINTF("uno_tx_prepare gave zero length", 0, 0, 0, 0);
    533 			if_statinc(ifp, if_oerrors);
    534 			break;
    535 		}
    536 
    537 		if (__predict_false(c->unc_xfer == NULL)) {
    538 			DPRINTF("unc_xfer is NULL", 0, 0, 0, 0);
    539 			if_statinc(ifp, if_oerrors);
    540 			break;
    541 		}
    542 
    543 		usbd_setup_xfer(c->unc_xfer, c, c->unc_buf, length,
    544 		    un->un_tx_xfer_flags, 10000, usbnet_txeof);
    545 
    546 		/* Transmit */
    547 		usbd_status err = usbd_transfer(c->unc_xfer);
    548 		if (err != USBD_IN_PROGRESS) {
    549 			DPRINTF("usbd_transfer on %#jx for %ju bytes: %jd",
    550 			    (uintptr_t)c->unc_buf, length, err, 0);
    551 			if_statinc(ifp, if_oerrors);
    552 			break;
    553 		}
    554 		done_transmit = true;
    555 
    556 		IFQ_DEQUEUE(&ifp->if_snd, m);
    557 
    558 		/*
    559 		 * If there's a BPF listener, bounce a copy of this frame
    560 		 * to him.
    561 		 */
    562 		bpf_mtap(ifp, m, BPF_D_OUT);
    563 		m_freem(m);
    564 
    565 		idx = (idx + 1) % un->un_tx_list_cnt;
    566 		cd->uncd_tx_cnt++;
    567 		count++;
    568 	}
    569 	cd->uncd_tx_prod = idx;
    570 
    571 	DPRINTF("finished with start; tx_cnt %jd list_cnt %jd link %jd",
    572 	    cd->uncd_tx_cnt, un->un_tx_list_cnt, unp->unp_link, 0);
    573 
    574 	/*
    575 	 * Set a timeout in case the chip goes out to lunch.
    576 	 */
    577 	if (done_transmit)
    578 		unp->unp_timer = 5;
    579 
    580 	if (count != 0)
    581 		rnd_add_uint32(&unp->unp_rndsrc, count);
    582 }
    583 
    584 static void
    585 usbnet_if_start(struct ifnet *ifp)
    586 {
    587 	struct usbnet * const un = ifp->if_softc;
    588 	struct usbnet_private * const unp = un->un_pri;
    589 
    590 	USBNETHIST_FUNC();
    591 	USBNETHIST_CALLARGS("%jd: stopping %jd",
    592 	    unp->unp_number, unp->unp_stopping, 0, 0);
    593 
    594 	mutex_enter(&unp->unp_txlock);
    595 	if (!unp->unp_stopping)
    596 		usbnet_start_locked(ifp);
    597 	mutex_exit(&unp->unp_txlock);
    598 }
    599 
    600 /*
    601  * Chain management.
    602  *
    603  * RX and TX are identical. Keep them that way.
    604  */
    605 
    606 /* Start of common RX functions */
    607 
    608 static size_t
    609 usbnet_rx_list_size(struct usbnet_cdata * const cd, struct usbnet * const un)
    610 {
    611 	return sizeof(*cd->uncd_rx_chain) * un->un_rx_list_cnt;
    612 }
    613 
    614 static void
    615 usbnet_rx_list_alloc(struct usbnet * const un)
    616 {
    617 	struct usbnet_cdata * const cd = un_cdata(un);
    618 
    619 	cd->uncd_rx_chain = kmem_zalloc(usbnet_rx_list_size(cd, un), KM_SLEEP);
    620 }
    621 
    622 static void
    623 usbnet_rx_list_free(struct usbnet * const un)
    624 {
    625 	struct usbnet_cdata * const cd = un_cdata(un);
    626 
    627 	if (cd->uncd_rx_chain) {
    628 		kmem_free(cd->uncd_rx_chain, usbnet_rx_list_size(cd, un));
    629 		cd->uncd_rx_chain = NULL;
    630 	}
    631 }
    632 
    633 static int
    634 usbnet_rx_list_init(struct usbnet * const un)
    635 {
    636 	struct usbnet_cdata * const cd = un_cdata(un);
    637 	struct usbnet_private * const unp = un->un_pri;
    638 
    639 	for (size_t i = 0; i < un->un_rx_list_cnt; i++) {
    640 		struct usbnet_chain *c = &cd->uncd_rx_chain[i];
    641 
    642 		c->unc_un = un;
    643 		if (c->unc_xfer == NULL) {
    644 			int err = usbd_create_xfer(unp->unp_ep[USBNET_ENDPT_RX],
    645 			    un->un_rx_bufsz, un->un_rx_xfer_flags, 0,
    646 			    &c->unc_xfer);
    647 			if (err)
    648 				return err;
    649 			c->unc_buf = usbd_get_buffer(c->unc_xfer);
    650 		}
    651 	}
    652 
    653 	return 0;
    654 }
    655 
    656 static void
    657 usbnet_rx_list_fini(struct usbnet * const un)
    658 {
    659 	struct usbnet_cdata * const cd = un_cdata(un);
    660 
    661 	for (size_t i = 0; i < un->un_rx_list_cnt; i++) {
    662 		struct usbnet_chain *c = &cd->uncd_rx_chain[i];
    663 
    664 		if (c->unc_xfer != NULL) {
    665 			usbd_destroy_xfer(c->unc_xfer);
    666 			c->unc_xfer = NULL;
    667 			c->unc_buf = NULL;
    668 		}
    669 	}
    670 }
    671 
    672 /* End of common RX functions */
    673 
    674 static void
    675 usbnet_rx_start_pipes(struct usbnet * const un)
    676 {
    677 	struct usbnet_cdata * const cd = un_cdata(un);
    678 	struct usbnet_private * const unp = un->un_pri;
    679 
    680 	mutex_enter(&unp->unp_rxlock);
    681 	mutex_enter(&unp->unp_txlock);
    682 	unp->unp_stopping = false;
    683 
    684 	for (size_t i = 0; i < un->un_rx_list_cnt; i++) {
    685 		struct usbnet_chain *c = &cd->uncd_rx_chain[i];
    686 
    687 		usbd_setup_xfer(c->unc_xfer, c, c->unc_buf, un->un_rx_bufsz,
    688 		    un->un_rx_xfer_flags, USBD_NO_TIMEOUT, usbnet_rxeof);
    689 		usbd_transfer(c->unc_xfer);
    690 	}
    691 
    692 	mutex_exit(&unp->unp_txlock);
    693 	mutex_exit(&unp->unp_rxlock);
    694 }
    695 
    696 /* Start of common TX functions */
    697 
    698 static size_t
    699 usbnet_tx_list_size(struct usbnet_cdata * const cd, struct usbnet * const un)
    700 {
    701 	return sizeof(*cd->uncd_tx_chain) * un->un_tx_list_cnt;
    702 }
    703 
    704 static void
    705 usbnet_tx_list_alloc(struct usbnet * const un)
    706 {
    707 	struct usbnet_cdata * const cd = un_cdata(un);
    708 
    709 	cd->uncd_tx_chain = kmem_zalloc(usbnet_tx_list_size(cd, un), KM_SLEEP);
    710 }
    711 
    712 static void
    713 usbnet_tx_list_free(struct usbnet * const un)
    714 {
    715 	struct usbnet_cdata * const cd = un_cdata(un);
    716 
    717 	if (cd->uncd_tx_chain) {
    718 		kmem_free(cd->uncd_tx_chain, usbnet_tx_list_size(cd, un));
    719 		cd->uncd_tx_chain = NULL;
    720 	}
    721 }
    722 
    723 static int
    724 usbnet_tx_list_init(struct usbnet * const un)
    725 {
    726 	struct usbnet_cdata * const cd = un_cdata(un);
    727 	struct usbnet_private * const unp = un->un_pri;
    728 
    729 	for (size_t i = 0; i < un->un_tx_list_cnt; i++) {
    730 		struct usbnet_chain *c = &cd->uncd_tx_chain[i];
    731 
    732 		c->unc_un = un;
    733 		if (c->unc_xfer == NULL) {
    734 			int err = usbd_create_xfer(unp->unp_ep[USBNET_ENDPT_TX],
    735 			    un->un_tx_bufsz, un->un_tx_xfer_flags, 0,
    736 			    &c->unc_xfer);
    737 			if (err)
    738 				return err;
    739 			c->unc_buf = usbd_get_buffer(c->unc_xfer);
    740 		}
    741 	}
    742 
    743 	return 0;
    744 }
    745 
    746 static void
    747 usbnet_tx_list_fini(struct usbnet * const un)
    748 {
    749 	struct usbnet_cdata * const cd = un_cdata(un);
    750 
    751 	for (size_t i = 0; i < un->un_tx_list_cnt; i++) {
    752 		struct usbnet_chain *c = &cd->uncd_tx_chain[i];
    753 
    754 		if (c->unc_xfer != NULL) {
    755 			usbd_destroy_xfer(c->unc_xfer);
    756 			c->unc_xfer = NULL;
    757 			c->unc_buf = NULL;
    758 		}
    759 	}
    760 	cd->uncd_tx_prod = cd->uncd_tx_cnt = 0;
    761 }
    762 
    763 /* End of common TX functions */
    764 
    765 /* Endpoint pipe management. */
    766 
    767 static void
    768 usbnet_ep_close_pipes(struct usbnet * const un)
    769 {
    770 	struct usbnet_private * const unp = un->un_pri;
    771 
    772 	for (size_t i = 0; i < __arraycount(unp->unp_ep); i++) {
    773 		if (unp->unp_ep[i] == NULL)
    774 			continue;
    775 		usbd_close_pipe(unp->unp_ep[i]);
    776 		unp->unp_ep[i] = NULL;
    777 	}
    778 }
    779 
    780 static usbd_status
    781 usbnet_ep_open_pipes(struct usbnet * const un)
    782 {
    783 	struct usbnet_intr * const uni = un->un_intr;
    784 	struct usbnet_private * const unp = un->un_pri;
    785 
    786 	for (size_t i = 0; i < __arraycount(unp->unp_ep); i++) {
    787 		usbd_status err;
    788 
    789 		if (un->un_ed[i] == 0)
    790 			continue;
    791 
    792 		if (i == USBNET_ENDPT_INTR && uni) {
    793 			err = usbd_open_pipe_intr(un->un_iface, un->un_ed[i],
    794 			    USBD_EXCLUSIVE_USE | USBD_MPSAFE, &unp->unp_ep[i], un,
    795 			    uni->uni_buf, uni->uni_bufsz, usbnet_pipe_intr,
    796 			    uni->uni_interval);
    797 		} else {
    798 			err = usbd_open_pipe(un->un_iface, un->un_ed[i],
    799 			    USBD_EXCLUSIVE_USE | USBD_MPSAFE, &unp->unp_ep[i]);
    800 		}
    801 		if (err) {
    802 			usbnet_ep_close_pipes(un);
    803 			return err;
    804 		}
    805 	}
    806 
    807 	return USBD_NORMAL_COMPLETION;
    808 }
    809 
    810 static void
    811 usbnet_ep_stop_pipes(struct usbnet * const un)
    812 {
    813 	struct usbnet_private * const unp = un->un_pri;
    814 
    815 	for (size_t i = 0; i < __arraycount(unp->unp_ep); i++) {
    816 		if (unp->unp_ep[i] == NULL)
    817 			continue;
    818 		usbd_abort_pipe(unp->unp_ep[i]);
    819 	}
    820 }
    821 
    822 static int
    823 usbnet_init_rx_tx(struct usbnet * const un)
    824 {
    825 	USBNETHIST_FUNC(); USBNETHIST_CALLED();
    826 	struct usbnet_private * const unp = un->un_pri;
    827 	struct ifnet * const ifp = usbnet_ifp(un);
    828 	usbd_status err;
    829 	int error = 0;
    830 
    831 	KASSERTMSG(IFNET_LOCKED(ifp), "%s", ifp->if_xname);
    832 
    833 	usbnet_isowned_core(un);
    834 
    835 	if (usbnet_isdying(un)) {
    836 		return EIO;
    837 	}
    838 
    839 	/* Open RX and TX pipes. */
    840 	err = usbnet_ep_open_pipes(un);
    841 	if (err) {
    842 		aprint_error_dev(un->un_dev, "open rx/tx pipes failed: %s\n",
    843 		    usbd_errstr(err));
    844 		error = EIO;
    845 		goto out;
    846 	}
    847 
    848 	/* Init RX ring. */
    849 	if (usbnet_rx_list_init(un)) {
    850 		aprint_error_dev(un->un_dev, "rx list init failed\n");
    851 		error = ENOBUFS;
    852 		goto out;
    853 	}
    854 
    855 	/* Init TX ring. */
    856 	if (usbnet_tx_list_init(un)) {
    857 		aprint_error_dev(un->un_dev, "tx list init failed\n");
    858 		error = ENOBUFS;
    859 		goto out;
    860 	}
    861 
    862 	/* Indicate we are up and running. */
    863 	KASSERTMSG(IFNET_LOCKED(ifp), "%s", ifp->if_xname);
    864 	ifp->if_flags |= IFF_RUNNING;
    865 
    866 	/*
    867 	 * If the hardware has a multicast filter, program it and then
    868 	 * allow updates to it while we're running.
    869 	 */
    870 	if (un->un_ops->uno_mcast) {
    871 		mutex_enter(&unp->unp_mcastlock);
    872 		(*un->un_ops->uno_mcast)(ifp);
    873 		unp->unp_mcastactive = true;
    874 		mutex_exit(&unp->unp_mcastlock);
    875 	}
    876 
    877 	/* Start up the receive pipe(s). */
    878 	usbnet_rx_start_pipes(un);
    879 
    880 	callout_schedule(&unp->unp_stat_ch, hz);
    881 
    882 out:
    883 	if (error) {
    884 		usbnet_rx_list_fini(un);
    885 		usbnet_tx_list_fini(un);
    886 		usbnet_ep_close_pipes(un);
    887 	}
    888 
    889 	/*
    890 	 * For devices without any media autodetection, treat success
    891 	 * here as an active link.
    892 	 */
    893 	if (un->un_ops->uno_statchg == NULL)
    894 		usbnet_set_link(un, error == 0);
    895 
    896 	usbnet_isowned_core(un);
    897 
    898 	return error;
    899 }
    900 
    901 /* MII management. */
    902 
    903 static int
    904 usbnet_mii_readreg(device_t dev, int phy, int reg, uint16_t *val)
    905 {
    906 	USBNETHIST_FUNC();
    907 	struct usbnet * const un = device_private(dev);
    908 	int err;
    909 
    910 	/* MII layer ensures core_lock is held. */
    911 	usbnet_isowned_core(un);
    912 
    913 	if (usbnet_isdying(un)) {
    914 		return EIO;
    915 	}
    916 
    917 	err = uno_read_reg(un, phy, reg, val);
    918 	if (err) {
    919 		USBNETHIST_CALLARGS("%jd: read PHY failed: %jd",
    920 		    un->un_pri->unp_number, err, 0, 0);
    921 		return err;
    922 	}
    923 
    924 	return 0;
    925 }
    926 
    927 static int
    928 usbnet_mii_writereg(device_t dev, int phy, int reg, uint16_t val)
    929 {
    930 	USBNETHIST_FUNC();
    931 	struct usbnet * const un = device_private(dev);
    932 	int err;
    933 
    934 	/* MII layer ensures core_lock is held. */
    935 	usbnet_isowned_core(un);
    936 
    937 	if (usbnet_isdying(un)) {
    938 		return EIO;
    939 	}
    940 
    941 	err = uno_write_reg(un, phy, reg, val);
    942 	if (err) {
    943 		USBNETHIST_CALLARGS("%jd: write PHY failed: %jd",
    944 		    un->un_pri->unp_number, err, 0, 0);
    945 		return err;
    946 	}
    947 
    948 	return 0;
    949 }
    950 
    951 static void
    952 usbnet_mii_statchg(struct ifnet *ifp)
    953 {
    954 	USBNETHIST_FUNC(); USBNETHIST_CALLED();
    955 	struct usbnet * const un = ifp->if_softc;
    956 
    957 	/* MII layer ensures core_lock is held. */
    958 	usbnet_isowned_core(un);
    959 
    960 	uno_mii_statchg(un, ifp);
    961 }
    962 
    963 static int
    964 usbnet_media_upd(struct ifnet *ifp)
    965 {
    966 	USBNETHIST_FUNC(); USBNETHIST_CALLED();
    967 	struct usbnet * const un = ifp->if_softc;
    968 	struct usbnet_private * const unp = un->un_pri;
    969 	struct mii_data * const mii = usbnet_mii(un);
    970 
    971 	/* ifmedia layer ensures core_lock is held. */
    972 	usbnet_isowned_core(un);
    973 
    974 	/* ifmedia changes only with IFNET_LOCK held.  */
    975 	KASSERTMSG(IFNET_LOCKED(ifp), "%s", ifp->if_xname);
    976 
    977 	if (usbnet_isdying(un))
    978 		return EIO;
    979 
    980 	unp->unp_link = false;
    981 
    982 	if (mii->mii_instance) {
    983 		struct mii_softc *miisc;
    984 
    985 		LIST_FOREACH(miisc, &mii->mii_phys, mii_list)
    986 			mii_phy_reset(miisc);
    987 	}
    988 
    989 	if (unp->unp_stopping)
    990 		return 0;
    991 	return ether_mediachange(ifp);
    992 }
    993 
    994 /* ioctl */
    995 
    996 static int
    997 usbnet_ifflags_cb(struct ethercom *ec)
    998 {
    999 	USBNETHIST_FUNC(); USBNETHIST_CALLED();
   1000 	struct ifnet *ifp = &ec->ec_if;
   1001 	struct usbnet *un = ifp->if_softc;
   1002 	struct usbnet_private * const unp = un->un_pri;
   1003 	int rv = 0;
   1004 
   1005 	KASSERTMSG(IFNET_LOCKED(ifp), "%s", ifp->if_xname);
   1006 
   1007 	const u_short changed = ifp->if_flags ^ unp->unp_if_flags;
   1008 	if ((changed & ~(IFF_CANTCHANGE | IFF_DEBUG)) == 0) {
   1009 		unp->unp_if_flags = ifp->if_flags;
   1010 		if ((changed & IFF_PROMISC) != 0)
   1011 			rv = ENETRESET;
   1012 	} else {
   1013 		rv = ENETRESET;
   1014 	}
   1015 
   1016 	return rv;
   1017 }
   1018 
   1019 static int
   1020 usbnet_if_ioctl(struct ifnet *ifp, u_long cmd, void *data)
   1021 {
   1022 	USBNETHIST_FUNC();
   1023 	struct usbnet * const un = ifp->if_softc;
   1024 	struct usbnet_private * const unp __unused = un->un_pri;
   1025 	int error;
   1026 
   1027 	USBNETHIST_CALLARGSN(11, "%jd: enter %#jx data %#jx",
   1028 	    unp->unp_number, cmd, (uintptr_t)data, 0);
   1029 
   1030 	if (un->un_ops->uno_override_ioctl)
   1031 		return uno_override_ioctl(un, ifp, cmd, data);
   1032 
   1033 	error = ether_ioctl(ifp, cmd, data);
   1034 	if (error == ENETRESET) {
   1035 		switch (cmd) {
   1036 		case SIOCADDMULTI:
   1037 		case SIOCDELMULTI:
   1038 			/*
   1039 			 * If there's a hardware multicast filter, and
   1040 			 * it has been programmed by usbnet_init_rx_tx
   1041 			 * and is active, update it now.  Otherwise,
   1042 			 * drop the update on the floor -- it will be
   1043 			 * observed by usbnet_init_rx_tx next time we
   1044 			 * bring the interface up.
   1045 			 */
   1046 			if (un->un_ops->uno_mcast) {
   1047 				mutex_enter(&unp->unp_mcastlock);
   1048 				if (unp->unp_mcastactive)
   1049 					(*un->un_ops->uno_mcast)(ifp);
   1050 				mutex_exit(&unp->unp_mcastlock);
   1051 			}
   1052 			error = 0;
   1053 			break;
   1054 		default:
   1055 			error = uno_ioctl(un, ifp, cmd, data);
   1056 		}
   1057 	}
   1058 
   1059 	return error;
   1060 }
   1061 
   1062 /*
   1063  * Generic stop network function:
   1064  *	- mark as stopping
   1065  *	- call DD routine to stop the device
   1066  *	- turn off running, timer, statchg callout, link
   1067  *	- stop transfers
   1068  *	- free RX and TX resources
   1069  *	- close pipes
   1070  *
   1071  * usbnet_if_stop() is for the if_stop handler.
   1072  */
   1073 static void
   1074 usbnet_stop(struct usbnet *un, struct ifnet *ifp, int disable)
   1075 {
   1076 	struct usbnet_private * const unp = un->un_pri;
   1077 
   1078 	USBNETHIST_FUNC(); USBNETHIST_CALLED();
   1079 
   1080 	KASSERTMSG(IFNET_LOCKED(ifp), "%s", ifp->if_xname);
   1081 	usbnet_isowned_core(un);
   1082 
   1083 	/*
   1084 	 * For drivers with hardware multicast filter update callbacks:
   1085 	 * Prevent concurrent access to the hardware registers by
   1086 	 * multicast filter updates, which happens without IFNET_LOCK
   1087 	 * or the usbnet core lock.
   1088 	 */
   1089 	if (un->un_ops->uno_mcast) {
   1090 		mutex_enter(&unp->unp_mcastlock);
   1091 		unp->unp_mcastactive = false;
   1092 		mutex_exit(&unp->unp_mcastlock);
   1093 	}
   1094 
   1095 	/*
   1096 	 * Prevent new activity (rescheduling ticks, xfers, &c.) and
   1097 	 * clear the watchdog timer.
   1098 	 */
   1099 	mutex_enter(&unp->unp_rxlock);
   1100 	mutex_enter(&unp->unp_txlock);
   1101 	unp->unp_stopping = true;
   1102 	unp->unp_timer = 0;
   1103 	mutex_exit(&unp->unp_txlock);
   1104 	mutex_exit(&unp->unp_rxlock);
   1105 
   1106 	/*
   1107 	 * Stop the timer first, then the task -- if the timer was
   1108 	 * already firing, we stop the task or wait for it complete
   1109 	 * only after if last fired.  Setting unp_stopping prevents the
   1110 	 * timer task from being scheduled again.
   1111 	 */
   1112 	callout_halt(&unp->unp_stat_ch, &unp->unp_core_lock);
   1113 	usb_rem_task_wait(un->un_udev, &unp->unp_ticktask, USB_TASKQ_DRIVER,
   1114 	    &unp->unp_core_lock);
   1115 
   1116 	/* Stop transfers. */
   1117 	usbnet_ep_stop_pipes(un);
   1118 
   1119 	/*
   1120 	 * Now that the software is quiescent, ask the driver to stop
   1121 	 * the hardware.  The driver's uno_stop routine now has
   1122 	 * exclusive access to any registers that might previously have
   1123 	 * been used by to ifmedia, mii, or ioctl callbacks.
   1124 	 *
   1125 	 * Don't bother if the device is being detached, though -- if
   1126 	 * it's been unplugged then there's no point in trying to touch
   1127 	 * the registers.
   1128 	 */
   1129 	if (!usbnet_isdying(un))
   1130 		uno_stop(un, ifp, disable);
   1131 
   1132 	/* Free RX/TX resources. */
   1133 	usbnet_rx_list_fini(un);
   1134 	usbnet_tx_list_fini(un);
   1135 
   1136 	/* Close pipes. */
   1137 	usbnet_ep_close_pipes(un);
   1138 
   1139 	/* Everything is quesced now. */
   1140 	KASSERTMSG(IFNET_LOCKED(ifp), "%s", ifp->if_xname);
   1141 	ifp->if_flags &= ~IFF_RUNNING;
   1142 }
   1143 
   1144 static void
   1145 usbnet_if_stop(struct ifnet *ifp, int disable)
   1146 {
   1147 	struct usbnet * const un = ifp->if_softc;
   1148 	struct usbnet_private * const unp = un->un_pri;
   1149 
   1150 	KASSERTMSG(IFNET_LOCKED(ifp), "%s", ifp->if_xname);
   1151 
   1152 	/*
   1153 	 * If we're already stopped, nothing to do.
   1154 	 *
   1155 	 * XXX This should be an assertion, but it may require some
   1156 	 * analysis -- and possibly some tweaking -- of sys/net to
   1157 	 * ensure.
   1158 	 */
   1159 	if ((ifp->if_flags & IFF_RUNNING) == 0)
   1160 		return;
   1161 
   1162 	mutex_enter(&unp->unp_core_lock);
   1163 	usbnet_stop(un, ifp, disable);
   1164 	mutex_exit(&unp->unp_core_lock);
   1165 }
   1166 
   1167 /*
   1168  * Generic tick task function.
   1169  *
   1170  * usbnet_tick() is triggered from a callout, and triggers a call to
   1171  * usbnet_tick_task() from the usb_task subsystem.
   1172  */
   1173 static void
   1174 usbnet_tick(void *arg)
   1175 {
   1176 	USBNETHIST_FUNC();
   1177 	struct usbnet * const un = arg;
   1178 	struct usbnet_private * const unp = un->un_pri;
   1179 
   1180 	USBNETHIST_CALLARGSN(10, "%jd: enter", unp->unp_number, 0, 0, 0);
   1181 
   1182 	/* Perform periodic stuff in process context */
   1183 	usb_add_task(un->un_udev, &unp->unp_ticktask, USB_TASKQ_DRIVER);
   1184 }
   1185 
   1186 static void
   1187 usbnet_watchdog(struct ifnet *ifp)
   1188 {
   1189 	USBNETHIST_FUNC(); USBNETHIST_CALLED();
   1190 	struct usbnet * const un = ifp->if_softc;
   1191 	struct usbnet_private * const unp = un->un_pri;
   1192 	struct usbnet_cdata * const cd = un_cdata(un);
   1193 
   1194 	if_statinc(ifp, if_oerrors);
   1195 	device_printf(un->un_dev, "watchdog timeout\n");
   1196 
   1197 	if (cd->uncd_tx_cnt > 0) {
   1198 		DPRINTF("uncd_tx_cnt=%ju non zero, aborting pipe", 0, 0, 0, 0);
   1199 		usbd_abort_pipe(unp->unp_ep[USBNET_ENDPT_TX]);
   1200 		if (cd->uncd_tx_cnt != 0)
   1201 			DPRINTF("uncd_tx_cnt now %ju", cd->uncd_tx_cnt, 0, 0, 0);
   1202 	}
   1203 
   1204 	if (!IFQ_IS_EMPTY(&ifp->if_snd))
   1205 		(*ifp->if_start)(ifp);
   1206 }
   1207 
   1208 static void
   1209 usbnet_tick_task(void *arg)
   1210 {
   1211 	USBNETHIST_FUNC();
   1212 	struct usbnet * const un = arg;
   1213 	struct usbnet_private * const unp = un->un_pri;
   1214 	struct ifnet * const ifp = usbnet_ifp(un);
   1215 	struct mii_data * const mii = usbnet_mii(un);
   1216 
   1217 	USBNETHIST_CALLARGSN(8, "%jd: enter", unp->unp_number, 0, 0, 0);
   1218 
   1219 	mutex_enter(&unp->unp_txlock);
   1220 	const bool timeout = unp->unp_timer != 0 && --unp->unp_timer == 0;
   1221 	mutex_exit(&unp->unp_txlock);
   1222 	if (timeout)
   1223 		usbnet_watchdog(ifp);
   1224 
   1225 	DPRINTFN(8, "mii %#jx ifp %#jx", (uintptr_t)mii, (uintptr_t)ifp, 0, 0);
   1226 	if (mii) {
   1227 		mutex_enter(&unp->unp_core_lock);
   1228 		mii_tick(mii);
   1229 		if (!unp->unp_link)
   1230 			(*mii->mii_statchg)(ifp);
   1231 		mutex_exit(&unp->unp_core_lock);
   1232 	}
   1233 
   1234 	/* Call driver if requested. */
   1235 	uno_tick(un);
   1236 
   1237 	mutex_enter(&unp->unp_core_lock);
   1238 	if (!unp->unp_stopping && !usbnet_isdying(un))
   1239 		callout_schedule(&unp->unp_stat_ch, hz);
   1240 	mutex_exit(&unp->unp_core_lock);
   1241 }
   1242 
   1243 static int
   1244 usbnet_if_init(struct ifnet *ifp)
   1245 {
   1246 	USBNETHIST_FUNC(); USBNETHIST_CALLED();
   1247 	struct usbnet * const un = ifp->if_softc;
   1248 	int error;
   1249 
   1250 	KASSERTMSG(IFNET_LOCKED(ifp), "%s", ifp->if_xname);
   1251 
   1252 	/*
   1253 	 * Prevent anyone from bringing the interface back up once
   1254 	 * we're detaching.
   1255 	 */
   1256 	if (usbnet_isdying(un))
   1257 		return EIO;
   1258 
   1259 	/*
   1260 	 * If we're already running, nothing to do.
   1261 	 *
   1262 	 * XXX This should be an assertion, but it may require some
   1263 	 * analysis -- and possibly some tweaking -- of sys/net to
   1264 	 * ensure.
   1265 	 */
   1266 	if (ifp->if_flags & IFF_RUNNING)
   1267 		return 0;
   1268 
   1269 	mutex_enter(&un->un_pri->unp_core_lock);
   1270 	error = uno_init(un, ifp);
   1271 	if (error)
   1272 		goto out;
   1273 	error = usbnet_init_rx_tx(un);
   1274 	if (error)
   1275 		goto out;
   1276 out:	mutex_exit(&un->un_pri->unp_core_lock);
   1277 
   1278 	return error;
   1279 }
   1280 
   1281 
   1282 /* Various accessors. */
   1283 
   1284 void
   1285 usbnet_set_link(struct usbnet *un, bool link)
   1286 {
   1287 	un->un_pri->unp_link = link;
   1288 }
   1289 
   1290 struct ifnet *
   1291 usbnet_ifp(struct usbnet *un)
   1292 {
   1293 	return &un->un_pri->unp_ec.ec_if;
   1294 }
   1295 
   1296 struct ethercom *
   1297 usbnet_ec(struct usbnet *un)
   1298 {
   1299 	return &un->un_pri->unp_ec;
   1300 }
   1301 
   1302 struct mii_data *
   1303 usbnet_mii(struct usbnet *un)
   1304 {
   1305 	return un->un_pri->unp_ec.ec_mii;
   1306 }
   1307 
   1308 krndsource_t *
   1309 usbnet_rndsrc(struct usbnet *un)
   1310 {
   1311 	return &un->un_pri->unp_rndsrc;
   1312 }
   1313 
   1314 void *
   1315 usbnet_softc(struct usbnet *un)
   1316 {
   1317 	return un->un_sc;
   1318 }
   1319 
   1320 bool
   1321 usbnet_havelink(struct usbnet *un)
   1322 {
   1323 	return un->un_pri->unp_link;
   1324 }
   1325 
   1326 bool
   1327 usbnet_isdying(struct usbnet *un)
   1328 {
   1329 	return atomic_load_relaxed(&un->un_pri->unp_dying);
   1330 }
   1331 
   1332 
   1333 /* Locking. */
   1334 
   1335 static void
   1336 usbnet_isowned_rx(struct usbnet *un)
   1337 {
   1338 	KASSERT(mutex_owned(&un->un_pri->unp_rxlock));
   1339 }
   1340 
   1341 static void
   1342 usbnet_isowned_tx(struct usbnet *un)
   1343 {
   1344 	KASSERT(mutex_owned(&un->un_pri->unp_txlock));
   1345 }
   1346 
   1347 /* Autoconf management. */
   1348 
   1349 static bool
   1350 usbnet_empty_eaddr(struct usbnet * const un)
   1351 {
   1352 	return (un->un_eaddr[0] == 0 && un->un_eaddr[1] == 0 &&
   1353 		un->un_eaddr[2] == 0 && un->un_eaddr[3] == 0 &&
   1354 		un->un_eaddr[4] == 0 && un->un_eaddr[5] == 0);
   1355 }
   1356 
   1357 /*
   1358  * usbnet_attach() and usbnet_attach_ifp() perform setup of the relevant
   1359  * 'usbnet'.  The first is enough to enable device access (eg, endpoints
   1360  * are connected and commands can be sent), and the second connects the
   1361  * device to the system networking.
   1362  *
   1363  * Always call usbnet_detach(), even if usbnet_attach_ifp() is skippped.
   1364  * Also usable as driver detach directly.
   1365  *
   1366  * To skip ethernet configuration (eg, point-to-point), make sure that
   1367  * the un_eaddr[] is fully zero.
   1368  */
   1369 
   1370 void
   1371 usbnet_attach(struct usbnet *un)
   1372 {
   1373 	USBNETHIST_FUNC(); USBNETHIST_CALLED();
   1374 
   1375 	/* Required inputs.  */
   1376 	KASSERT(un->un_ops->uno_tx_prepare);
   1377 	KASSERT(un->un_ops->uno_rx_loop);
   1378 	KASSERT(un->un_rx_bufsz);
   1379 	KASSERT(un->un_tx_bufsz);
   1380 	KASSERT(un->un_rx_list_cnt);
   1381 	KASSERT(un->un_tx_list_cnt);
   1382 
   1383 	/* Unfortunate fact.  */
   1384 	KASSERT(un == device_private(un->un_dev));
   1385 
   1386 	un->un_pri = kmem_zalloc(sizeof(*un->un_pri), KM_SLEEP);
   1387 	struct usbnet_private * const unp = un->un_pri;
   1388 
   1389 	usb_init_task(&unp->unp_ticktask, usbnet_tick_task, un,
   1390 	    USB_TASKQ_MPSAFE);
   1391 	callout_init(&unp->unp_stat_ch, CALLOUT_MPSAFE);
   1392 	callout_setfunc(&unp->unp_stat_ch, usbnet_tick, un);
   1393 
   1394 	mutex_init(&unp->unp_txlock, MUTEX_DEFAULT, IPL_SOFTUSB);
   1395 	mutex_init(&unp->unp_rxlock, MUTEX_DEFAULT, IPL_SOFTUSB);
   1396 	mutex_init(&unp->unp_core_lock, MUTEX_DEFAULT, IPL_NONE);
   1397 	mutex_init(&unp->unp_mcastlock, MUTEX_DEFAULT, IPL_SOFTCLOCK);
   1398 
   1399 	rnd_attach_source(&unp->unp_rndsrc, device_xname(un->un_dev),
   1400 	    RND_TYPE_NET, RND_FLAG_DEFAULT);
   1401 
   1402 	usbnet_rx_list_alloc(un);
   1403 	usbnet_tx_list_alloc(un);
   1404 
   1405 	unp->unp_number = atomic_inc_uint_nv(&usbnet_number);
   1406 
   1407 	unp->unp_attached = true;
   1408 }
   1409 
   1410 static void
   1411 usbnet_attach_mii(struct usbnet *un, const struct usbnet_mii *unm)
   1412 {
   1413 	USBNETHIST_FUNC(); USBNETHIST_CALLED();
   1414 	struct usbnet_private * const unp = un->un_pri;
   1415 	struct mii_data * const mii = &unp->unp_mii;
   1416 	struct ifnet * const ifp = usbnet_ifp(un);
   1417 
   1418 	KASSERT(un->un_ops->uno_read_reg);
   1419 	KASSERT(un->un_ops->uno_write_reg);
   1420 	KASSERT(un->un_ops->uno_statchg);
   1421 
   1422 	mii->mii_ifp = ifp;
   1423 	mii->mii_readreg = usbnet_mii_readreg;
   1424 	mii->mii_writereg = usbnet_mii_writereg;
   1425 	mii->mii_statchg = usbnet_mii_statchg;
   1426 	mii->mii_flags = MIIF_AUTOTSLEEP;
   1427 
   1428 	usbnet_ec(un)->ec_mii = mii;
   1429 	ifmedia_init_with_lock(&mii->mii_media, 0,
   1430 	    usbnet_media_upd, ether_mediastatus, &unp->unp_core_lock);
   1431 	mii_attach(un->un_dev, mii, unm->un_mii_capmask, unm->un_mii_phyloc,
   1432 	    unm->un_mii_offset, unm->un_mii_flags);
   1433 
   1434 	if (LIST_FIRST(&mii->mii_phys) == NULL) {
   1435 		ifmedia_add(&mii->mii_media, IFM_ETHER | IFM_NONE, 0, NULL);
   1436 		ifmedia_set(&mii->mii_media, IFM_ETHER | IFM_NONE);
   1437 	} else
   1438 		ifmedia_set(&mii->mii_media, IFM_ETHER | IFM_AUTO);
   1439 }
   1440 
   1441 void
   1442 usbnet_attach_ifp(struct usbnet *un,
   1443 		  unsigned if_flags,		/* additional if_flags */
   1444 		  unsigned if_extflags,		/* additional if_extflags */
   1445 		  const struct usbnet_mii *unm)	/* additional mii_attach flags */
   1446 {
   1447 	USBNETHIST_FUNC(); USBNETHIST_CALLED();
   1448 	struct usbnet_private * const unp = un->un_pri;
   1449 	struct ifnet * const ifp = usbnet_ifp(un);
   1450 
   1451 	KASSERT(unp->unp_attached);
   1452 	KASSERT(!unp->unp_ifp_attached);
   1453 
   1454 	ifp->if_softc = un;
   1455 	strlcpy(ifp->if_xname, device_xname(un->un_dev), IFNAMSIZ);
   1456 	ifp->if_flags = if_flags;
   1457 	ifp->if_extflags = IFEF_MPSAFE | if_extflags;
   1458 	ifp->if_ioctl = usbnet_if_ioctl;
   1459 	ifp->if_start = usbnet_if_start;
   1460 	ifp->if_init = usbnet_if_init;
   1461 	ifp->if_stop = usbnet_if_stop;
   1462 
   1463 	if (unm)
   1464 		usbnet_attach_mii(un, unm);
   1465 	else
   1466 		unp->unp_link = true;
   1467 
   1468 	/* Attach the interface. */
   1469 	if_initialize(ifp);
   1470 	if (ifp->_if_input == NULL)
   1471 		ifp->if_percpuq = if_percpuq_create(ifp);
   1472 	if_register(ifp);
   1473 	unp->unp_ifp_attached = true;
   1474 
   1475 	/*
   1476 	 * If ethernet address is all zero, skip ether_ifattach() and
   1477 	 * instead attach bpf here..
   1478 	 */
   1479 	if (!usbnet_empty_eaddr(un)) {
   1480 		ether_set_ifflags_cb(&unp->unp_ec, usbnet_ifflags_cb);
   1481 		aprint_normal_dev(un->un_dev, "Ethernet address %s\n",
   1482 		    ether_sprintf(un->un_eaddr));
   1483 		ether_ifattach(ifp, un->un_eaddr);
   1484 	} else {
   1485 		if_alloc_sadl(ifp);
   1486 		bpf_attach(ifp, DLT_RAW, 0);
   1487 	}
   1488 
   1489 	/* Now ready, and attached. */
   1490 	IFQ_SET_READY(&ifp->if_snd);
   1491 
   1492 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, un->un_udev, un->un_dev);
   1493 
   1494 	if (!pmf_device_register(un->un_dev, NULL, NULL))
   1495 		aprint_error_dev(un->un_dev, "couldn't establish power handler\n");
   1496 }
   1497 
   1498 int
   1499 usbnet_detach(device_t self, int flags)
   1500 {
   1501 	USBNETHIST_FUNC(); USBNETHIST_CALLED();
   1502 	struct usbnet * const un = device_private(self);
   1503 	struct usbnet_private * const unp = un->un_pri;
   1504 
   1505 	/* Detached before attached finished, so just bail out. */
   1506 	if (unp == NULL || !unp->unp_attached)
   1507 		return 0;
   1508 
   1509 	struct ifnet * const ifp = usbnet_ifp(un);
   1510 	struct mii_data * const mii = usbnet_mii(un);
   1511 
   1512 	/*
   1513 	 * Prevent new activity.  After we stop the interface, it
   1514 	 * cannot be brought back up.
   1515 	 */
   1516 	atomic_store_relaxed(&unp->unp_dying, true);
   1517 
   1518 	/*
   1519 	 * If we're still running on the network, stop and wait for all
   1520 	 * asynchronous activity to finish.
   1521 	 *
   1522 	 * If usbnet_attach_ifp never ran, IFNET_LOCK won't work, but
   1523 	 * no activity is possible, so just skip this part.
   1524 	 */
   1525 	if (unp->unp_ifp_attached) {
   1526 		IFNET_LOCK(ifp);
   1527 		if (ifp->if_flags & IFF_RUNNING) {
   1528 			usbnet_if_stop(ifp, 1);
   1529 		}
   1530 		IFNET_UNLOCK(ifp);
   1531 	}
   1532 
   1533 	/*
   1534 	 * The callout and tick task can't be scheduled anew at this
   1535 	 * point, and usbnet_if_stop has waited for them to complete.
   1536 	 */
   1537 	KASSERT(!callout_pending(&unp->unp_stat_ch));
   1538 	KASSERT(!usb_task_pending(un->un_udev, &unp->unp_ticktask));
   1539 
   1540 	if (mii) {
   1541 		mii_detach(mii, MII_PHY_ANY, MII_OFFSET_ANY);
   1542 		ifmedia_fini(&mii->mii_media);
   1543 	}
   1544 	if (unp->unp_ifp_attached) {
   1545 		if (!usbnet_empty_eaddr(un))
   1546 			ether_ifdetach(ifp);
   1547 		else
   1548 			bpf_detach(ifp);
   1549 		if_detach(ifp);
   1550 	}
   1551 	usbnet_ec(un)->ec_mii = NULL;
   1552 
   1553 	usbnet_rx_list_free(un);
   1554 	usbnet_tx_list_free(un);
   1555 
   1556 	rnd_detach_source(&unp->unp_rndsrc);
   1557 
   1558 	mutex_destroy(&unp->unp_mcastlock);
   1559 	mutex_destroy(&unp->unp_core_lock);
   1560 	mutex_destroy(&unp->unp_rxlock);
   1561 	mutex_destroy(&unp->unp_txlock);
   1562 
   1563 	callout_destroy(&unp->unp_stat_ch);
   1564 
   1565 	pmf_device_deregister(un->un_dev);
   1566 
   1567 	/*
   1568 	 * Notify userland that we're going away, if we arrived in the
   1569 	 * first place.
   1570 	 */
   1571 	if (unp->unp_ifp_attached) {
   1572 		usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, un->un_udev,
   1573 		    un->un_dev);
   1574 	}
   1575 
   1576 	kmem_free(unp, sizeof(*unp));
   1577 	un->un_pri = NULL;
   1578 
   1579 	return 0;
   1580 }
   1581 
   1582 int
   1583 usbnet_activate(device_t self, devact_t act)
   1584 {
   1585 	USBNETHIST_FUNC(); USBNETHIST_CALLED();
   1586 	struct usbnet * const un = device_private(self);
   1587 	struct usbnet_private * const unp = un->un_pri;
   1588 	struct ifnet * const ifp = usbnet_ifp(un);
   1589 
   1590 	switch (act) {
   1591 	case DVACT_DEACTIVATE:
   1592 		if_deactivate(ifp);
   1593 
   1594 		atomic_store_relaxed(&unp->unp_dying, true);
   1595 
   1596 		mutex_enter(&unp->unp_rxlock);
   1597 		mutex_enter(&unp->unp_txlock);
   1598 		unp->unp_stopping = true;
   1599 		mutex_exit(&unp->unp_txlock);
   1600 		mutex_exit(&unp->unp_rxlock);
   1601 
   1602 		return 0;
   1603 	default:
   1604 		return EOPNOTSUPP;
   1605 	}
   1606 }
   1607 
   1608 MODULE(MODULE_CLASS_MISC, usbnet, NULL);
   1609 
   1610 static int
   1611 usbnet_modcmd(modcmd_t cmd, void *arg)
   1612 {
   1613 	switch (cmd) {
   1614 	case MODULE_CMD_INIT:
   1615 		return 0;
   1616 	case MODULE_CMD_FINI:
   1617 		return 0;
   1618 	case MODULE_CMD_STAT:
   1619 	case MODULE_CMD_AUTOUNLOAD:
   1620 	default:
   1621 		return ENOTTY;
   1622 	}
   1623 }
   1624