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