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