xref: /netbsd-src/sys/net/if.c (revision ecf6466c633518f478c293c388551b29e46729cc)
1 /*	$NetBSD: if.c,v 1.468 2020/01/20 18:38:18 thorpej Exp $	*/
2 
3 /*-
4  * Copyright (c) 1999, 2000, 2001, 2008 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by William Studenmund and Jason R. Thorpe.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 /*
33  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
34  * All rights reserved.
35  *
36  * Redistribution and use in source and binary forms, with or without
37  * modification, are permitted provided that the following conditions
38  * are met:
39  * 1. Redistributions of source code must retain the above copyright
40  *    notice, this list of conditions and the following disclaimer.
41  * 2. Redistributions in binary form must reproduce the above copyright
42  *    notice, this list of conditions and the following disclaimer in the
43  *    documentation and/or other materials provided with the distribution.
44  * 3. Neither the name of the project nor the names of its contributors
45  *    may be used to endorse or promote products derived from this software
46  *    without specific prior written permission.
47  *
48  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
49  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
52  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58  * SUCH DAMAGE.
59  */
60 
61 /*
62  * Copyright (c) 1980, 1986, 1993
63  *	The Regents of the University of California.  All rights reserved.
64  *
65  * Redistribution and use in source and binary forms, with or without
66  * modification, are permitted provided that the following conditions
67  * are met:
68  * 1. Redistributions of source code must retain the above copyright
69  *    notice, this list of conditions and the following disclaimer.
70  * 2. Redistributions in binary form must reproduce the above copyright
71  *    notice, this list of conditions and the following disclaimer in the
72  *    documentation and/or other materials provided with the distribution.
73  * 3. Neither the name of the University nor the names of its contributors
74  *    may be used to endorse or promote products derived from this software
75  *    without specific prior written permission.
76  *
77  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
78  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
79  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
80  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
81  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
82  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
83  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
84  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
85  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
86  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
87  * SUCH DAMAGE.
88  *
89  *	@(#)if.c	8.5 (Berkeley) 1/9/95
90  */
91 
92 #include <sys/cdefs.h>
93 __KERNEL_RCSID(0, "$NetBSD: if.c,v 1.468 2020/01/20 18:38:18 thorpej Exp $");
94 
95 #if defined(_KERNEL_OPT)
96 #include "opt_inet.h"
97 #include "opt_ipsec.h"
98 #include "opt_atalk.h"
99 #include "opt_wlan.h"
100 #include "opt_net_mpsafe.h"
101 #include "opt_mrouting.h"
102 #endif
103 
104 #include <sys/param.h>
105 #include <sys/mbuf.h>
106 #include <sys/systm.h>
107 #include <sys/callout.h>
108 #include <sys/proc.h>
109 #include <sys/socket.h>
110 #include <sys/socketvar.h>
111 #include <sys/domain.h>
112 #include <sys/protosw.h>
113 #include <sys/kernel.h>
114 #include <sys/ioctl.h>
115 #include <sys/sysctl.h>
116 #include <sys/syslog.h>
117 #include <sys/kauth.h>
118 #include <sys/kmem.h>
119 #include <sys/xcall.h>
120 #include <sys/cpu.h>
121 #include <sys/intr.h>
122 #include <sys/module_hook.h>
123 #include <sys/compat_stub.h>
124 #include <sys/msan.h>
125 
126 #include <net/if.h>
127 #include <net/if_dl.h>
128 #include <net/if_ether.h>
129 #include <net/if_media.h>
130 #include <net80211/ieee80211.h>
131 #include <net80211/ieee80211_ioctl.h>
132 #include <net/if_types.h>
133 #include <net/route.h>
134 #include <net/netisr.h>
135 #include <sys/module.h>
136 #ifdef NETATALK
137 #include <netatalk/at_extern.h>
138 #include <netatalk/at.h>
139 #endif
140 #include <net/pfil.h>
141 #include <netinet/in.h>
142 #include <netinet/in_var.h>
143 #include <netinet/ip_encap.h>
144 #include <net/bpf.h>
145 
146 #ifdef INET6
147 #include <netinet6/in6_var.h>
148 #include <netinet6/nd6.h>
149 #endif
150 
151 #include "ether.h"
152 
153 #include "bridge.h"
154 #if NBRIDGE > 0
155 #include <net/if_bridgevar.h>
156 #endif
157 
158 #include "carp.h"
159 #if NCARP > 0
160 #include <netinet/ip_carp.h>
161 #endif
162 
163 #include <compat/sys/sockio.h>
164 
165 MALLOC_DEFINE(M_IFADDR, "ifaddr", "interface address");
166 MALLOC_DEFINE(M_IFMADDR, "ether_multi", "link-level multicast address");
167 
168 /*
169  * Global list of interfaces.
170  */
171 /* DEPRECATED. Remove it once kvm(3) users disappeared */
172 struct ifnet_head		ifnet_list;
173 
174 struct pslist_head		ifnet_pslist;
175 static ifnet_t **		ifindex2ifnet = NULL;
176 static u_int			if_index = 1;
177 static size_t			if_indexlim = 0;
178 static uint64_t			index_gen;
179 /* Mutex to protect the above objects. */
180 kmutex_t			ifnet_mtx __cacheline_aligned;
181 static struct psref_class	*ifnet_psref_class __read_mostly;
182 static pserialize_t		ifnet_psz;
183 
184 static kmutex_t			if_clone_mtx;
185 
186 struct ifnet *lo0ifp;
187 int	ifqmaxlen = IFQ_MAXLEN;
188 
189 struct psref_class		*ifa_psref_class __read_mostly;
190 
191 static int	if_delroute_matcher(struct rtentry *, void *);
192 
193 static bool if_is_unit(const char *);
194 static struct if_clone *if_clone_lookup(const char *, int *);
195 
196 static LIST_HEAD(, if_clone) if_cloners = LIST_HEAD_INITIALIZER(if_cloners);
197 static int if_cloners_count;
198 
199 /* Packet filtering hook for interfaces. */
200 pfil_head_t *			if_pfil __read_mostly;
201 
202 static kauth_listener_t if_listener;
203 
204 static int doifioctl(struct socket *, u_long, void *, struct lwp *);
205 static void if_detach_queues(struct ifnet *, struct ifqueue *);
206 static void sysctl_sndq_setup(struct sysctllog **, const char *,
207     struct ifaltq *);
208 static void if_slowtimo(void *);
209 static void if_attachdomain1(struct ifnet *);
210 static int ifconf(u_long, void *);
211 static int if_transmit(struct ifnet *, struct mbuf *);
212 static int if_clone_create(const char *);
213 static int if_clone_destroy(const char *);
214 static void if_link_state_change_si(void *);
215 static void if_up_locked(struct ifnet *);
216 static void _if_down(struct ifnet *);
217 static void if_down_deactivated(struct ifnet *);
218 
219 struct if_percpuq {
220 	struct ifnet	*ipq_ifp;
221 	void		*ipq_si;
222 	struct percpu	*ipq_ifqs;	/* struct ifqueue */
223 };
224 
225 static struct mbuf *if_percpuq_dequeue(struct if_percpuq *);
226 
227 static void if_percpuq_drops(void *, void *, struct cpu_info *);
228 static int sysctl_percpuq_drops_handler(SYSCTLFN_PROTO);
229 static void sysctl_percpuq_setup(struct sysctllog **, const char *,
230     struct if_percpuq *);
231 
232 struct if_deferred_start {
233 	struct ifnet	*ids_ifp;
234 	void		(*ids_if_start)(struct ifnet *);
235 	void		*ids_si;
236 };
237 
238 static void if_deferred_start_softint(void *);
239 static void if_deferred_start_common(struct ifnet *);
240 static void if_deferred_start_destroy(struct ifnet *);
241 
242 #if defined(INET) || defined(INET6)
243 static void sysctl_net_pktq_setup(struct sysctllog **, int);
244 #endif
245 
246 /*
247  * Hook for if_vlan - needed by if_agr
248  */
249 struct if_vlan_vlan_input_hook_t if_vlan_vlan_input_hook;
250 
251 static void if_sysctl_setup(struct sysctllog **);
252 
253 static int
254 if_listener_cb(kauth_cred_t cred, kauth_action_t action, void *cookie,
255     void *arg0, void *arg1, void *arg2, void *arg3)
256 {
257 	int result;
258 	enum kauth_network_req req;
259 
260 	result = KAUTH_RESULT_DEFER;
261 	req = (enum kauth_network_req)arg1;
262 
263 	if (action != KAUTH_NETWORK_INTERFACE)
264 		return result;
265 
266 	if ((req == KAUTH_REQ_NETWORK_INTERFACE_GET) ||
267 	    (req == KAUTH_REQ_NETWORK_INTERFACE_SET))
268 		result = KAUTH_RESULT_ALLOW;
269 
270 	return result;
271 }
272 
273 /*
274  * Network interface utility routines.
275  *
276  * Routines with ifa_ifwith* names take sockaddr *'s as
277  * parameters.
278  */
279 void
280 ifinit(void)
281 {
282 
283 #if (defined(INET) || defined(INET6))
284 	encapinit();
285 #endif
286 
287 	if_listener = kauth_listen_scope(KAUTH_SCOPE_NETWORK,
288 	    if_listener_cb, NULL);
289 
290 	/* interfaces are available, inform socket code */
291 	ifioctl = doifioctl;
292 }
293 
294 /*
295  * XXX Initialization before configure().
296  * XXX hack to get pfil_add_hook working in autoconf.
297  */
298 void
299 ifinit1(void)
300 {
301 
302 #ifdef NET_MPSAFE
303 	printf("NET_MPSAFE enabled\n");
304 #endif
305 
306 	mutex_init(&if_clone_mtx, MUTEX_DEFAULT, IPL_NONE);
307 
308 	TAILQ_INIT(&ifnet_list);
309 	mutex_init(&ifnet_mtx, MUTEX_DEFAULT, IPL_NONE);
310 	ifnet_psz = pserialize_create();
311 	ifnet_psref_class = psref_class_create("ifnet", IPL_SOFTNET);
312 	ifa_psref_class = psref_class_create("ifa", IPL_SOFTNET);
313 	PSLIST_INIT(&ifnet_pslist);
314 
315 	if_indexlim = 8;
316 
317 	if_pfil = pfil_head_create(PFIL_TYPE_IFNET, NULL);
318 	KASSERT(if_pfil != NULL);
319 
320 #if NETHER > 0 || defined(NETATALK) || defined(WLAN)
321 	etherinit();
322 #endif
323 }
324 
325 /* XXX must be after domaininit() */
326 void
327 ifinit_post(void)
328 {
329 
330 	if_sysctl_setup(NULL);
331 }
332 
333 ifnet_t *
334 if_alloc(u_char type)
335 {
336 	return kmem_zalloc(sizeof(ifnet_t), KM_SLEEP);
337 }
338 
339 void
340 if_free(ifnet_t *ifp)
341 {
342 	kmem_free(ifp, sizeof(ifnet_t));
343 }
344 
345 void
346 if_initname(struct ifnet *ifp, const char *name, int unit)
347 {
348 	(void)snprintf(ifp->if_xname, sizeof(ifp->if_xname),
349 	    "%s%d", name, unit);
350 }
351 
352 /*
353  * Null routines used while an interface is going away.  These routines
354  * just return an error.
355  */
356 
357 int
358 if_nulloutput(struct ifnet *ifp, struct mbuf *m,
359     const struct sockaddr *so, const struct rtentry *rt)
360 {
361 
362 	return ENXIO;
363 }
364 
365 void
366 if_nullinput(struct ifnet *ifp, struct mbuf *m)
367 {
368 
369 	/* Nothing. */
370 }
371 
372 void
373 if_nullstart(struct ifnet *ifp)
374 {
375 
376 	/* Nothing. */
377 }
378 
379 int
380 if_nulltransmit(struct ifnet *ifp, struct mbuf *m)
381 {
382 
383 	m_freem(m);
384 	return ENXIO;
385 }
386 
387 int
388 if_nullioctl(struct ifnet *ifp, u_long cmd, void *data)
389 {
390 
391 	return ENXIO;
392 }
393 
394 int
395 if_nullinit(struct ifnet *ifp)
396 {
397 
398 	return ENXIO;
399 }
400 
401 void
402 if_nullstop(struct ifnet *ifp, int disable)
403 {
404 
405 	/* Nothing. */
406 }
407 
408 void
409 if_nullslowtimo(struct ifnet *ifp)
410 {
411 
412 	/* Nothing. */
413 }
414 
415 void
416 if_nulldrain(struct ifnet *ifp)
417 {
418 
419 	/* Nothing. */
420 }
421 
422 void
423 if_set_sadl(struct ifnet *ifp, const void *lla, u_char addrlen, bool factory)
424 {
425 	struct ifaddr *ifa;
426 	struct sockaddr_dl *sdl;
427 
428 	ifp->if_addrlen = addrlen;
429 	if_alloc_sadl(ifp);
430 	ifa = ifp->if_dl;
431 	sdl = satosdl(ifa->ifa_addr);
432 
433 	(void)sockaddr_dl_setaddr(sdl, sdl->sdl_len, lla, ifp->if_addrlen);
434 	if (factory) {
435 		KASSERT(ifp->if_hwdl == NULL);
436 		ifp->if_hwdl = ifp->if_dl;
437 		ifaref(ifp->if_hwdl);
438 	}
439 	/* TBD routing socket */
440 }
441 
442 struct ifaddr *
443 if_dl_create(const struct ifnet *ifp, const struct sockaddr_dl **sdlp)
444 {
445 	unsigned socksize, ifasize;
446 	int addrlen, namelen;
447 	struct sockaddr_dl *mask, *sdl;
448 	struct ifaddr *ifa;
449 
450 	namelen = strlen(ifp->if_xname);
451 	addrlen = ifp->if_addrlen;
452 	socksize = roundup(sockaddr_dl_measure(namelen, addrlen), sizeof(long));
453 	ifasize = sizeof(*ifa) + 2 * socksize;
454 	ifa = malloc(ifasize, M_IFADDR, M_WAITOK | M_ZERO);
455 
456 	sdl = (struct sockaddr_dl *)(ifa + 1);
457 	mask = (struct sockaddr_dl *)(socksize + (char *)sdl);
458 
459 	sockaddr_dl_init(sdl, socksize, ifp->if_index, ifp->if_type,
460 	    ifp->if_xname, namelen, NULL, addrlen);
461 	mask->sdl_family = AF_LINK;
462 	mask->sdl_len = sockaddr_dl_measure(namelen, 0);
463 	memset(&mask->sdl_data[0], 0xff, namelen);
464 	ifa->ifa_rtrequest = link_rtrequest;
465 	ifa->ifa_addr = (struct sockaddr *)sdl;
466 	ifa->ifa_netmask = (struct sockaddr *)mask;
467 	ifa_psref_init(ifa);
468 
469 	*sdlp = sdl;
470 
471 	return ifa;
472 }
473 
474 static void
475 if_sadl_setrefs(struct ifnet *ifp, struct ifaddr *ifa)
476 {
477 	const struct sockaddr_dl *sdl;
478 
479 	ifp->if_dl = ifa;
480 	ifaref(ifa);
481 	sdl = satosdl(ifa->ifa_addr);
482 	ifp->if_sadl = sdl;
483 }
484 
485 /*
486  * Allocate the link level name for the specified interface.  This
487  * is an attachment helper.  It must be called after ifp->if_addrlen
488  * is initialized, which may not be the case when if_attach() is
489  * called.
490  */
491 void
492 if_alloc_sadl(struct ifnet *ifp)
493 {
494 	struct ifaddr *ifa;
495 	const struct sockaddr_dl *sdl;
496 
497 	/*
498 	 * If the interface already has a link name, release it
499 	 * now.  This is useful for interfaces that can change
500 	 * link types, and thus switch link names often.
501 	 */
502 	if (ifp->if_sadl != NULL)
503 		if_free_sadl(ifp, 0);
504 
505 	ifa = if_dl_create(ifp, &sdl);
506 
507 	ifa_insert(ifp, ifa);
508 	if_sadl_setrefs(ifp, ifa);
509 }
510 
511 static void
512 if_deactivate_sadl(struct ifnet *ifp)
513 {
514 	struct ifaddr *ifa;
515 
516 	KASSERT(ifp->if_dl != NULL);
517 
518 	ifa = ifp->if_dl;
519 
520 	ifp->if_sadl = NULL;
521 
522 	ifp->if_dl = NULL;
523 	ifafree(ifa);
524 }
525 
526 static void
527 if_replace_sadl(struct ifnet *ifp, struct ifaddr *ifa)
528 {
529 	struct ifaddr *old;
530 
531 	KASSERT(ifp->if_dl != NULL);
532 
533 	old = ifp->if_dl;
534 
535 	ifaref(ifa);
536 	/* XXX Update if_dl and if_sadl atomically */
537 	ifp->if_dl = ifa;
538 	ifp->if_sadl = satosdl(ifa->ifa_addr);
539 
540 	ifafree(old);
541 }
542 
543 void
544 if_activate_sadl(struct ifnet *ifp, struct ifaddr *ifa0,
545     const struct sockaddr_dl *sdl)
546 {
547 	int s, ss;
548 	struct ifaddr *ifa;
549 	int bound = curlwp_bind();
550 
551 	KASSERT(ifa_held(ifa0));
552 
553 	s = splsoftnet();
554 
555 	if_replace_sadl(ifp, ifa0);
556 
557 	ss = pserialize_read_enter();
558 	IFADDR_READER_FOREACH(ifa, ifp) {
559 		struct psref psref;
560 		ifa_acquire(ifa, &psref);
561 		pserialize_read_exit(ss);
562 
563 		rtinit(ifa, RTM_LLINFO_UPD, 0);
564 
565 		ss = pserialize_read_enter();
566 		ifa_release(ifa, &psref);
567 	}
568 	pserialize_read_exit(ss);
569 
570 	splx(s);
571 	curlwp_bindx(bound);
572 }
573 
574 /*
575  * Free the link level name for the specified interface.  This is
576  * a detach helper.  This is called from if_detach().
577  */
578 void
579 if_free_sadl(struct ifnet *ifp, int factory)
580 {
581 	struct ifaddr *ifa;
582 	int s;
583 
584 	if (factory && ifp->if_hwdl != NULL) {
585 		ifa = ifp->if_hwdl;
586 		ifp->if_hwdl = NULL;
587 		ifafree(ifa);
588 	}
589 
590 	ifa = ifp->if_dl;
591 	if (ifa == NULL) {
592 		KASSERT(ifp->if_sadl == NULL);
593 		return;
594 	}
595 
596 	KASSERT(ifp->if_sadl != NULL);
597 
598 	s = splsoftnet();
599 	KASSERT(ifa->ifa_addr->sa_family == AF_LINK);
600 	ifa_remove(ifp, ifa);
601 	if_deactivate_sadl(ifp);
602 	splx(s);
603 }
604 
605 static void
606 if_getindex(ifnet_t *ifp)
607 {
608 	bool hitlimit = false;
609 
610 	ifp->if_index_gen = index_gen++;
611 
612 	ifp->if_index = if_index;
613 	if (ifindex2ifnet == NULL) {
614 		if_index++;
615 		goto skip;
616 	}
617 	while (if_byindex(ifp->if_index)) {
618 		/*
619 		 * If we hit USHRT_MAX, we skip back to 0 since
620 		 * there are a number of places where the value
621 		 * of if_index or if_index itself is compared
622 		 * to or stored in an unsigned short.  By
623 		 * jumping back, we won't botch those assignments
624 		 * or comparisons.
625 		 */
626 		if (++if_index == 0) {
627 			if_index = 1;
628 		} else if (if_index == USHRT_MAX) {
629 			/*
630 			 * However, if we have to jump back to
631 			 * zero *twice* without finding an empty
632 			 * slot in ifindex2ifnet[], then there
633 			 * there are too many (>65535) interfaces.
634 			 */
635 			if (hitlimit) {
636 				panic("too many interfaces");
637 			}
638 			hitlimit = true;
639 			if_index = 1;
640 		}
641 		ifp->if_index = if_index;
642 	}
643 skip:
644 	/*
645 	 * ifindex2ifnet is indexed by if_index. Since if_index will
646 	 * grow dynamically, it should grow too.
647 	 */
648 	if (ifindex2ifnet == NULL || ifp->if_index >= if_indexlim) {
649 		size_t m, n, oldlim;
650 		void *q;
651 
652 		oldlim = if_indexlim;
653 		while (ifp->if_index >= if_indexlim)
654 			if_indexlim <<= 1;
655 
656 		/* grow ifindex2ifnet */
657 		m = oldlim * sizeof(struct ifnet *);
658 		n = if_indexlim * sizeof(struct ifnet *);
659 		q = malloc(n, M_IFADDR, M_WAITOK | M_ZERO);
660 		if (ifindex2ifnet != NULL) {
661 			memcpy(q, ifindex2ifnet, m);
662 			free(ifindex2ifnet, M_IFADDR);
663 		}
664 		ifindex2ifnet = (struct ifnet **)q;
665 	}
666 	ifindex2ifnet[ifp->if_index] = ifp;
667 }
668 
669 /*
670  * Initialize an interface and assign an index for it.
671  *
672  * It must be called prior to a device specific attach routine
673  * (e.g., ether_ifattach and ieee80211_ifattach) or if_alloc_sadl,
674  * and be followed by if_register:
675  *
676  *     if_initialize(ifp);
677  *     ether_ifattach(ifp, enaddr);
678  *     if_register(ifp);
679  */
680 int
681 if_initialize(ifnet_t *ifp)
682 {
683 	int rv = 0;
684 
685 	KASSERT(if_indexlim > 0);
686 	TAILQ_INIT(&ifp->if_addrlist);
687 
688 	/*
689 	 * Link level name is allocated later by a separate call to
690 	 * if_alloc_sadl().
691 	 */
692 
693 	if (ifp->if_snd.ifq_maxlen == 0)
694 		ifp->if_snd.ifq_maxlen = ifqmaxlen;
695 
696 	ifp->if_broadcastaddr = 0; /* reliably crash if used uninitialized */
697 
698 	ifp->if_link_state = LINK_STATE_UNKNOWN;
699 	ifp->if_link_queue = -1; /* all bits set, see link_state_change() */
700 
701 	ifp->if_capenable = 0;
702 	ifp->if_csum_flags_tx = 0;
703 	ifp->if_csum_flags_rx = 0;
704 
705 #ifdef ALTQ
706 	ifp->if_snd.altq_type = 0;
707 	ifp->if_snd.altq_disc = NULL;
708 	ifp->if_snd.altq_flags &= ALTQF_CANTCHANGE;
709 	ifp->if_snd.altq_tbr  = NULL;
710 	ifp->if_snd.altq_ifp  = ifp;
711 #endif
712 
713 	IFQ_LOCK_INIT(&ifp->if_snd);
714 
715 	ifp->if_pfil = pfil_head_create(PFIL_TYPE_IFNET, ifp);
716 	pfil_run_ifhooks(if_pfil, PFIL_IFNET_ATTACH, ifp);
717 
718 	IF_AFDATA_LOCK_INIT(ifp);
719 
720 	if (if_is_link_state_changeable(ifp)) {
721 		u_int flags = SOFTINT_NET;
722 		flags |= if_is_mpsafe(ifp) ? SOFTINT_MPSAFE : 0;
723 		ifp->if_link_si = softint_establish(flags,
724 		    if_link_state_change_si, ifp);
725 		if (ifp->if_link_si == NULL) {
726 			rv = ENOMEM;
727 			goto fail;
728 		}
729 	}
730 
731 	PSLIST_ENTRY_INIT(ifp, if_pslist_entry);
732 	PSLIST_INIT(&ifp->if_addr_pslist);
733 	psref_target_init(&ifp->if_psref, ifnet_psref_class);
734 	ifp->if_ioctl_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
735 	LIST_INIT(&ifp->if_multiaddrs);
736 
737 	IFNET_GLOBAL_LOCK();
738 	if_getindex(ifp);
739 	IFNET_GLOBAL_UNLOCK();
740 
741 	return 0;
742 
743 fail:
744 	IF_AFDATA_LOCK_DESTROY(ifp);
745 
746 	pfil_run_ifhooks(if_pfil, PFIL_IFNET_DETACH, ifp);
747 	(void)pfil_head_destroy(ifp->if_pfil);
748 
749 	IFQ_LOCK_DESTROY(&ifp->if_snd);
750 
751 	return rv;
752 }
753 
754 /*
755  * Register an interface to the list of "active" interfaces.
756  */
757 void
758 if_register(ifnet_t *ifp)
759 {
760 	/*
761 	 * If the driver has not supplied its own if_ioctl, then
762 	 * supply the default.
763 	 */
764 	if (ifp->if_ioctl == NULL)
765 		ifp->if_ioctl = ifioctl_common;
766 
767 	sysctl_sndq_setup(&ifp->if_sysctl_log, ifp->if_xname, &ifp->if_snd);
768 
769 	if (!STAILQ_EMPTY(&domains))
770 		if_attachdomain1(ifp);
771 
772 	/* Announce the interface. */
773 	rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
774 
775 	if (ifp->if_slowtimo != NULL) {
776 		ifp->if_slowtimo_ch =
777 		    kmem_zalloc(sizeof(*ifp->if_slowtimo_ch), KM_SLEEP);
778 		callout_init(ifp->if_slowtimo_ch, 0);
779 		callout_setfunc(ifp->if_slowtimo_ch, if_slowtimo, ifp);
780 		if_slowtimo(ifp);
781 	}
782 
783 	if (ifp->if_transmit == NULL || ifp->if_transmit == if_nulltransmit)
784 		ifp->if_transmit = if_transmit;
785 
786 	IFNET_GLOBAL_LOCK();
787 	TAILQ_INSERT_TAIL(&ifnet_list, ifp, if_list);
788 	IFNET_WRITER_INSERT_TAIL(ifp);
789 	IFNET_GLOBAL_UNLOCK();
790 }
791 
792 /*
793  * The if_percpuq framework
794  *
795  * It allows network device drivers to execute the network stack
796  * in softint (so called softint-based if_input). It utilizes
797  * softint and percpu ifqueue. It doesn't distribute any packets
798  * between CPUs, unlike pktqueue(9).
799  *
800  * Currently we support two options for device drivers to apply the framework:
801  * - Use it implicitly with less changes
802  *   - If you use if_attach in driver's _attach function and if_input in
803  *     driver's Rx interrupt handler, a packet is queued and a softint handles
804  *     the packet implicitly
805  * - Use it explicitly in each driver (recommended)
806  *   - You can use if_percpuq_* directly in your driver
807  *   - In this case, you need to allocate struct if_percpuq in driver's softc
808  *   - See wm(4) as a reference implementation
809  */
810 
811 static void
812 if_percpuq_softint(void *arg)
813 {
814 	struct if_percpuq *ipq = arg;
815 	struct ifnet *ifp = ipq->ipq_ifp;
816 	struct mbuf *m;
817 
818 	while ((m = if_percpuq_dequeue(ipq)) != NULL) {
819 		ifp->if_ipackets++;
820 		bpf_mtap(ifp, m, BPF_D_IN);
821 
822 		ifp->_if_input(ifp, m);
823 	}
824 }
825 
826 static void
827 if_percpuq_init_ifq(void *p, void *arg __unused, struct cpu_info *ci __unused)
828 {
829 	struct ifqueue *const ifq = p;
830 
831 	memset(ifq, 0, sizeof(*ifq));
832 	ifq->ifq_maxlen = IFQ_MAXLEN;
833 }
834 
835 struct if_percpuq *
836 if_percpuq_create(struct ifnet *ifp)
837 {
838 	struct if_percpuq *ipq;
839 	u_int flags = SOFTINT_NET;
840 
841 	flags |= if_is_mpsafe(ifp) ? SOFTINT_MPSAFE : 0;
842 
843 	ipq = kmem_zalloc(sizeof(*ipq), KM_SLEEP);
844 	ipq->ipq_ifp = ifp;
845 	ipq->ipq_si = softint_establish(flags, if_percpuq_softint, ipq);
846 	ipq->ipq_ifqs = percpu_alloc(sizeof(struct ifqueue));
847 	percpu_foreach(ipq->ipq_ifqs, &if_percpuq_init_ifq, NULL);
848 
849 	sysctl_percpuq_setup(&ifp->if_sysctl_log, ifp->if_xname, ipq);
850 
851 	return ipq;
852 }
853 
854 static struct mbuf *
855 if_percpuq_dequeue(struct if_percpuq *ipq)
856 {
857 	struct mbuf *m;
858 	struct ifqueue *ifq;
859 	int s;
860 
861 	s = splnet();
862 	ifq = percpu_getref(ipq->ipq_ifqs);
863 	IF_DEQUEUE(ifq, m);
864 	percpu_putref(ipq->ipq_ifqs);
865 	splx(s);
866 
867 	return m;
868 }
869 
870 static void
871 if_percpuq_purge_ifq(void *p, void *arg __unused, struct cpu_info *ci __unused)
872 {
873 	struct ifqueue *const ifq = p;
874 
875 	IF_PURGE(ifq);
876 }
877 
878 void
879 if_percpuq_destroy(struct if_percpuq *ipq)
880 {
881 
882 	/* if_detach may already destroy it */
883 	if (ipq == NULL)
884 		return;
885 
886 	softint_disestablish(ipq->ipq_si);
887 	percpu_foreach(ipq->ipq_ifqs, &if_percpuq_purge_ifq, NULL);
888 	percpu_free(ipq->ipq_ifqs, sizeof(struct ifqueue));
889 	kmem_free(ipq, sizeof(*ipq));
890 }
891 
892 void
893 if_percpuq_enqueue(struct if_percpuq *ipq, struct mbuf *m)
894 {
895 	struct ifqueue *ifq;
896 	int s;
897 
898 	KASSERT(ipq != NULL);
899 
900 	s = splnet();
901 	ifq = percpu_getref(ipq->ipq_ifqs);
902 	if (IF_QFULL(ifq)) {
903 		IF_DROP(ifq);
904 		percpu_putref(ipq->ipq_ifqs);
905 		m_freem(m);
906 		goto out;
907 	}
908 	IF_ENQUEUE(ifq, m);
909 	percpu_putref(ipq->ipq_ifqs);
910 
911 	softint_schedule(ipq->ipq_si);
912 out:
913 	splx(s);
914 }
915 
916 static void
917 if_percpuq_drops(void *p, void *arg, struct cpu_info *ci __unused)
918 {
919 	struct ifqueue *const ifq = p;
920 	int *sum = arg;
921 
922 	*sum += ifq->ifq_drops;
923 }
924 
925 static int
926 sysctl_percpuq_drops_handler(SYSCTLFN_ARGS)
927 {
928 	struct sysctlnode node;
929 	struct if_percpuq *ipq;
930 	int sum = 0;
931 	int error;
932 
933 	node = *rnode;
934 	ipq = node.sysctl_data;
935 
936 	percpu_foreach(ipq->ipq_ifqs, if_percpuq_drops, &sum);
937 
938 	node.sysctl_data = &sum;
939 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
940 	if (error != 0 || newp == NULL)
941 		return error;
942 
943 	return 0;
944 }
945 
946 static void
947 sysctl_percpuq_setup(struct sysctllog **clog, const char* ifname,
948     struct if_percpuq *ipq)
949 {
950 	const struct sysctlnode *cnode, *rnode;
951 
952 	if (sysctl_createv(clog, 0, NULL, &rnode,
953 		       CTLFLAG_PERMANENT,
954 		       CTLTYPE_NODE, "interfaces",
955 		       SYSCTL_DESCR("Per-interface controls"),
956 		       NULL, 0, NULL, 0,
957 		       CTL_NET, CTL_CREATE, CTL_EOL) != 0)
958 		goto bad;
959 
960 	if (sysctl_createv(clog, 0, &rnode, &rnode,
961 		       CTLFLAG_PERMANENT,
962 		       CTLTYPE_NODE, ifname,
963 		       SYSCTL_DESCR("Interface controls"),
964 		       NULL, 0, NULL, 0,
965 		       CTL_CREATE, CTL_EOL) != 0)
966 		goto bad;
967 
968 	if (sysctl_createv(clog, 0, &rnode, &rnode,
969 		       CTLFLAG_PERMANENT,
970 		       CTLTYPE_NODE, "rcvq",
971 		       SYSCTL_DESCR("Interface input queue controls"),
972 		       NULL, 0, NULL, 0,
973 		       CTL_CREATE, CTL_EOL) != 0)
974 		goto bad;
975 
976 #ifdef NOTYET
977 	/* XXX Should show each per-CPU queue length? */
978 	if (sysctl_createv(clog, 0, &rnode, &rnode,
979 		       CTLFLAG_PERMANENT,
980 		       CTLTYPE_INT, "len",
981 		       SYSCTL_DESCR("Current input queue length"),
982 		       sysctl_percpuq_len, 0, NULL, 0,
983 		       CTL_CREATE, CTL_EOL) != 0)
984 		goto bad;
985 
986 	if (sysctl_createv(clog, 0, &rnode, &cnode,
987 		       CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
988 		       CTLTYPE_INT, "maxlen",
989 		       SYSCTL_DESCR("Maximum allowed input queue length"),
990 		       sysctl_percpuq_maxlen_handler, 0, (void *)ipq, 0,
991 		       CTL_CREATE, CTL_EOL) != 0)
992 		goto bad;
993 #endif
994 
995 	if (sysctl_createv(clog, 0, &rnode, &cnode,
996 		       CTLFLAG_PERMANENT,
997 		       CTLTYPE_INT, "drops",
998 		       SYSCTL_DESCR("Total packets dropped due to full input queue"),
999 		       sysctl_percpuq_drops_handler, 0, (void *)ipq, 0,
1000 		       CTL_CREATE, CTL_EOL) != 0)
1001 		goto bad;
1002 
1003 	return;
1004 bad:
1005 	printf("%s: could not attach sysctl nodes\n", ifname);
1006 	return;
1007 }
1008 
1009 /*
1010  * The deferred if_start framework
1011  *
1012  * The common APIs to defer if_start to softint when if_start is requested
1013  * from a device driver running in hardware interrupt context.
1014  */
1015 /*
1016  * Call ifp->if_start (or equivalent) in a dedicated softint for
1017  * deferred if_start.
1018  */
1019 static void
1020 if_deferred_start_softint(void *arg)
1021 {
1022 	struct if_deferred_start *ids = arg;
1023 	struct ifnet *ifp = ids->ids_ifp;
1024 
1025 	ids->ids_if_start(ifp);
1026 }
1027 
1028 /*
1029  * The default callback function for deferred if_start.
1030  */
1031 static void
1032 if_deferred_start_common(struct ifnet *ifp)
1033 {
1034 	int s;
1035 
1036 	s = splnet();
1037 	if_start_lock(ifp);
1038 	splx(s);
1039 }
1040 
1041 static inline bool
1042 if_snd_is_used(struct ifnet *ifp)
1043 {
1044 
1045 	return ALTQ_IS_ENABLED(&ifp->if_snd) ||
1046 		ifp->if_transmit == if_transmit ||
1047 		ifp->if_transmit == NULL || ifp->if_transmit == if_nulltransmit;
1048 }
1049 
1050 /*
1051  * Schedule deferred if_start.
1052  */
1053 void
1054 if_schedule_deferred_start(struct ifnet *ifp)
1055 {
1056 
1057 	KASSERT(ifp->if_deferred_start != NULL);
1058 
1059 	if (if_snd_is_used(ifp) && IFQ_IS_EMPTY(&ifp->if_snd))
1060 		return;
1061 
1062 	softint_schedule(ifp->if_deferred_start->ids_si);
1063 }
1064 
1065 /*
1066  * Create an instance of deferred if_start. A driver should call the function
1067  * only if the driver needs deferred if_start. Drivers can setup their own
1068  * deferred if_start function via 2nd argument.
1069  */
1070 void
1071 if_deferred_start_init(struct ifnet *ifp, void (*func)(struct ifnet *))
1072 {
1073 	struct if_deferred_start *ids;
1074 	u_int flags = SOFTINT_NET;
1075 
1076 	flags |= if_is_mpsafe(ifp) ? SOFTINT_MPSAFE : 0;
1077 
1078 	ids = kmem_zalloc(sizeof(*ids), KM_SLEEP);
1079 	ids->ids_ifp = ifp;
1080 	ids->ids_si = softint_establish(flags, if_deferred_start_softint, ids);
1081 	if (func != NULL)
1082 		ids->ids_if_start = func;
1083 	else
1084 		ids->ids_if_start = if_deferred_start_common;
1085 
1086 	ifp->if_deferred_start = ids;
1087 }
1088 
1089 static void
1090 if_deferred_start_destroy(struct ifnet *ifp)
1091 {
1092 
1093 	if (ifp->if_deferred_start == NULL)
1094 		return;
1095 
1096 	softint_disestablish(ifp->if_deferred_start->ids_si);
1097 	kmem_free(ifp->if_deferred_start, sizeof(*ifp->if_deferred_start));
1098 	ifp->if_deferred_start = NULL;
1099 }
1100 
1101 /*
1102  * The common interface input routine that is called by device drivers,
1103  * which should be used only when the driver's rx handler already runs
1104  * in softint.
1105  */
1106 void
1107 if_input(struct ifnet *ifp, struct mbuf *m)
1108 {
1109 
1110 	KASSERT(ifp->if_percpuq == NULL);
1111 	KASSERT(!cpu_intr_p());
1112 
1113 	ifp->if_ipackets++;
1114 	bpf_mtap(ifp, m, BPF_D_IN);
1115 
1116 	ifp->_if_input(ifp, m);
1117 }
1118 
1119 /*
1120  * DEPRECATED. Use if_initialize and if_register instead.
1121  * See the above comment of if_initialize.
1122  *
1123  * Note that it implicitly enables if_percpuq to make drivers easy to
1124  * migrate softint-based if_input without much changes. If you don't
1125  * want to enable it, use if_initialize instead.
1126  */
1127 int
1128 if_attach(ifnet_t *ifp)
1129 {
1130 	int rv;
1131 
1132 	rv = if_initialize(ifp);
1133 	if (rv != 0)
1134 		return rv;
1135 
1136 	ifp->if_percpuq = if_percpuq_create(ifp);
1137 	if_register(ifp);
1138 
1139 	return 0;
1140 }
1141 
1142 void
1143 if_attachdomain(void)
1144 {
1145 	struct ifnet *ifp;
1146 	int s;
1147 	int bound = curlwp_bind();
1148 
1149 	s = pserialize_read_enter();
1150 	IFNET_READER_FOREACH(ifp) {
1151 		struct psref psref;
1152 		psref_acquire(&psref, &ifp->if_psref, ifnet_psref_class);
1153 		pserialize_read_exit(s);
1154 		if_attachdomain1(ifp);
1155 		s = pserialize_read_enter();
1156 		psref_release(&psref, &ifp->if_psref, ifnet_psref_class);
1157 	}
1158 	pserialize_read_exit(s);
1159 	curlwp_bindx(bound);
1160 }
1161 
1162 static void
1163 if_attachdomain1(struct ifnet *ifp)
1164 {
1165 	struct domain *dp;
1166 	int s;
1167 
1168 	s = splsoftnet();
1169 
1170 	/* address family dependent data region */
1171 	memset(ifp->if_afdata, 0, sizeof(ifp->if_afdata));
1172 	DOMAIN_FOREACH(dp) {
1173 		if (dp->dom_ifattach != NULL)
1174 			ifp->if_afdata[dp->dom_family] =
1175 			    (*dp->dom_ifattach)(ifp);
1176 	}
1177 
1178 	splx(s);
1179 }
1180 
1181 /*
1182  * Deactivate an interface.  This points all of the procedure
1183  * handles at error stubs.  May be called from interrupt context.
1184  */
1185 void
1186 if_deactivate(struct ifnet *ifp)
1187 {
1188 	int s;
1189 
1190 	s = splsoftnet();
1191 
1192 	ifp->if_output	 = if_nulloutput;
1193 	ifp->_if_input	 = if_nullinput;
1194 	ifp->if_start	 = if_nullstart;
1195 	ifp->if_transmit = if_nulltransmit;
1196 	ifp->if_ioctl	 = if_nullioctl;
1197 	ifp->if_init	 = if_nullinit;
1198 	ifp->if_stop	 = if_nullstop;
1199 	ifp->if_slowtimo = if_nullslowtimo;
1200 	ifp->if_drain	 = if_nulldrain;
1201 
1202 	/* No more packets may be enqueued. */
1203 	ifp->if_snd.ifq_maxlen = 0;
1204 
1205 	splx(s);
1206 }
1207 
1208 bool
1209 if_is_deactivated(const struct ifnet *ifp)
1210 {
1211 
1212 	return ifp->if_output == if_nulloutput;
1213 }
1214 
1215 void
1216 if_purgeaddrs(struct ifnet *ifp, int family, void (*purgeaddr)(struct ifaddr *))
1217 {
1218 	struct ifaddr *ifa, *nifa;
1219 	int s;
1220 
1221 	s = pserialize_read_enter();
1222 	for (ifa = IFADDR_READER_FIRST(ifp); ifa; ifa = nifa) {
1223 		nifa = IFADDR_READER_NEXT(ifa);
1224 		if (ifa->ifa_addr->sa_family != family)
1225 			continue;
1226 		pserialize_read_exit(s);
1227 
1228 		(*purgeaddr)(ifa);
1229 
1230 		s = pserialize_read_enter();
1231 	}
1232 	pserialize_read_exit(s);
1233 }
1234 
1235 #ifdef IFAREF_DEBUG
1236 static struct ifaddr **ifa_list;
1237 static int ifa_list_size;
1238 
1239 /* Depends on only one if_attach runs at once */
1240 static void
1241 if_build_ifa_list(struct ifnet *ifp)
1242 {
1243 	struct ifaddr *ifa;
1244 	int i;
1245 
1246 	KASSERT(ifa_list == NULL);
1247 	KASSERT(ifa_list_size == 0);
1248 
1249 	IFADDR_READER_FOREACH(ifa, ifp)
1250 		ifa_list_size++;
1251 
1252 	ifa_list = kmem_alloc(sizeof(*ifa) * ifa_list_size, KM_SLEEP);
1253 	i = 0;
1254 	IFADDR_READER_FOREACH(ifa, ifp) {
1255 		ifa_list[i++] = ifa;
1256 		ifaref(ifa);
1257 	}
1258 }
1259 
1260 static void
1261 if_check_and_free_ifa_list(struct ifnet *ifp)
1262 {
1263 	int i;
1264 	struct ifaddr *ifa;
1265 
1266 	if (ifa_list == NULL)
1267 		return;
1268 
1269 	for (i = 0; i < ifa_list_size; i++) {
1270 		char buf[64];
1271 
1272 		ifa = ifa_list[i];
1273 		sockaddr_format(ifa->ifa_addr, buf, sizeof(buf));
1274 		if (ifa->ifa_refcnt > 1) {
1275 			log(LOG_WARNING,
1276 			    "ifa(%s) still referenced (refcnt=%d)\n",
1277 			    buf, ifa->ifa_refcnt - 1);
1278 		} else
1279 			log(LOG_DEBUG,
1280 			    "ifa(%s) not referenced (refcnt=%d)\n",
1281 			    buf, ifa->ifa_refcnt - 1);
1282 		ifafree(ifa);
1283 	}
1284 
1285 	kmem_free(ifa_list, sizeof(*ifa) * ifa_list_size);
1286 	ifa_list = NULL;
1287 	ifa_list_size = 0;
1288 }
1289 #endif
1290 
1291 /*
1292  * Detach an interface from the list of "active" interfaces,
1293  * freeing any resources as we go along.
1294  *
1295  * NOTE: This routine must be called with a valid thread context,
1296  * as it may block.
1297  */
1298 void
1299 if_detach(struct ifnet *ifp)
1300 {
1301 	struct socket so;
1302 	struct ifaddr *ifa;
1303 #ifdef IFAREF_DEBUG
1304 	struct ifaddr *last_ifa = NULL;
1305 #endif
1306 	struct domain *dp;
1307 	const struct protosw *pr;
1308 	int s, i, family, purged;
1309 
1310 #ifdef IFAREF_DEBUG
1311 	if_build_ifa_list(ifp);
1312 #endif
1313 	/*
1314 	 * XXX It's kind of lame that we have to have the
1315 	 * XXX socket structure...
1316 	 */
1317 	memset(&so, 0, sizeof(so));
1318 
1319 	s = splnet();
1320 
1321 	sysctl_teardown(&ifp->if_sysctl_log);
1322 	IFNET_LOCK(ifp);
1323 	if_deactivate(ifp);
1324 	IFNET_UNLOCK(ifp);
1325 
1326 	/*
1327 	 * Unlink from the list and wait for all readers to leave
1328 	 * from pserialize read sections.  Note that we can't do
1329 	 * psref_target_destroy here.  See below.
1330 	 */
1331 	IFNET_GLOBAL_LOCK();
1332 	ifindex2ifnet[ifp->if_index] = NULL;
1333 	TAILQ_REMOVE(&ifnet_list, ifp, if_list);
1334 	IFNET_WRITER_REMOVE(ifp);
1335 	pserialize_perform(ifnet_psz);
1336 	IFNET_GLOBAL_UNLOCK();
1337 
1338 	if (ifp->if_slowtimo != NULL && ifp->if_slowtimo_ch != NULL) {
1339 		ifp->if_slowtimo = NULL;
1340 		callout_halt(ifp->if_slowtimo_ch, NULL);
1341 		callout_destroy(ifp->if_slowtimo_ch);
1342 		kmem_free(ifp->if_slowtimo_ch, sizeof(*ifp->if_slowtimo_ch));
1343 	}
1344 	if_deferred_start_destroy(ifp);
1345 
1346 	/*
1347 	 * Do an if_down() to give protocols a chance to do something.
1348 	 */
1349 	if_down_deactivated(ifp);
1350 
1351 #ifdef ALTQ
1352 	if (ALTQ_IS_ENABLED(&ifp->if_snd))
1353 		altq_disable(&ifp->if_snd);
1354 	if (ALTQ_IS_ATTACHED(&ifp->if_snd))
1355 		altq_detach(&ifp->if_snd);
1356 #endif
1357 
1358 #if NCARP > 0
1359 	/* Remove the interface from any carp group it is a part of.  */
1360 	if (ifp->if_carp != NULL && ifp->if_type != IFT_CARP)
1361 		carp_ifdetach(ifp);
1362 #endif
1363 
1364 	/*
1365 	 * Rip all the addresses off the interface.  This should make
1366 	 * all of the routes go away.
1367 	 *
1368 	 * pr_usrreq calls can remove an arbitrary number of ifaddrs
1369 	 * from the list, including our "cursor", ifa.  For safety,
1370 	 * and to honor the TAILQ abstraction, I just restart the
1371 	 * loop after each removal.  Note that the loop will exit
1372 	 * when all of the remaining ifaddrs belong to the AF_LINK
1373 	 * family.  I am counting on the historical fact that at
1374 	 * least one pr_usrreq in each address domain removes at
1375 	 * least one ifaddr.
1376 	 */
1377 again:
1378 	/*
1379 	 * At this point, no other one tries to remove ifa in the list,
1380 	 * so we don't need to take a lock or psref.  Avoid using
1381 	 * IFADDR_READER_FOREACH to pass over an inspection of contract
1382 	 * violations of pserialize.
1383 	 */
1384 	IFADDR_WRITER_FOREACH(ifa, ifp) {
1385 		family = ifa->ifa_addr->sa_family;
1386 #ifdef IFAREF_DEBUG
1387 		printf("if_detach: ifaddr %p, family %d, refcnt %d\n",
1388 		    ifa, family, ifa->ifa_refcnt);
1389 		if (last_ifa != NULL && ifa == last_ifa)
1390 			panic("if_detach: loop detected");
1391 		last_ifa = ifa;
1392 #endif
1393 		if (family == AF_LINK)
1394 			continue;
1395 		dp = pffinddomain(family);
1396 		KASSERTMSG(dp != NULL, "no domain for AF %d", family);
1397 		/*
1398 		 * XXX These PURGEIF calls are redundant with the
1399 		 * purge-all-families calls below, but are left in for
1400 		 * now both to make a smaller change, and to avoid
1401 		 * unplanned interactions with clearing of
1402 		 * ifp->if_addrlist.
1403 		 */
1404 		purged = 0;
1405 		for (pr = dp->dom_protosw;
1406 		     pr < dp->dom_protoswNPROTOSW; pr++) {
1407 			so.so_proto = pr;
1408 			if (pr->pr_usrreqs) {
1409 				(void) (*pr->pr_usrreqs->pr_purgeif)(&so, ifp);
1410 				purged = 1;
1411 			}
1412 		}
1413 		if (purged == 0) {
1414 			/*
1415 			 * XXX What's really the best thing to do
1416 			 * XXX here?  --thorpej@NetBSD.org
1417 			 */
1418 			printf("if_detach: WARNING: AF %d not purged\n",
1419 			    family);
1420 			ifa_remove(ifp, ifa);
1421 		}
1422 		goto again;
1423 	}
1424 
1425 	if_free_sadl(ifp, 1);
1426 
1427 restart:
1428 	IFADDR_WRITER_FOREACH(ifa, ifp) {
1429 		family = ifa->ifa_addr->sa_family;
1430 		KASSERT(family == AF_LINK);
1431 		ifa_remove(ifp, ifa);
1432 		goto restart;
1433 	}
1434 
1435 	/* Delete stray routes from the routing table. */
1436 	for (i = 0; i <= AF_MAX; i++)
1437 		rt_delete_matched_entries(i, if_delroute_matcher, ifp);
1438 
1439 	DOMAIN_FOREACH(dp) {
1440 		if (dp->dom_ifdetach != NULL && ifp->if_afdata[dp->dom_family])
1441 		{
1442 			void *p = ifp->if_afdata[dp->dom_family];
1443 			if (p) {
1444 				ifp->if_afdata[dp->dom_family] = NULL;
1445 				(*dp->dom_ifdetach)(ifp, p);
1446 			}
1447 		}
1448 
1449 		/*
1450 		 * One would expect multicast memberships (INET and
1451 		 * INET6) on UDP sockets to be purged by the PURGEIF
1452 		 * calls above, but if all addresses were removed from
1453 		 * the interface prior to destruction, the calls will
1454 		 * not be made (e.g. ppp, for which pppd(8) generally
1455 		 * removes addresses before destroying the interface).
1456 		 * Because there is no invariant that multicast
1457 		 * memberships only exist for interfaces with IPv4
1458 		 * addresses, we must call PURGEIF regardless of
1459 		 * addresses.  (Protocols which might store ifnet
1460 		 * pointers are marked with PR_PURGEIF.)
1461 		 */
1462 		for (pr = dp->dom_protosw; pr < dp->dom_protoswNPROTOSW; pr++) {
1463 			so.so_proto = pr;
1464 			if (pr->pr_usrreqs && pr->pr_flags & PR_PURGEIF)
1465 				(void)(*pr->pr_usrreqs->pr_purgeif)(&so, ifp);
1466 		}
1467 	}
1468 
1469 	/*
1470 	 * Must be done after the above pr_purgeif because if_psref may be
1471 	 * still used in pr_purgeif.
1472 	 */
1473 	psref_target_destroy(&ifp->if_psref, ifnet_psref_class);
1474 	PSLIST_ENTRY_DESTROY(ifp, if_pslist_entry);
1475 
1476 	pfil_run_ifhooks(if_pfil, PFIL_IFNET_DETACH, ifp);
1477 	(void)pfil_head_destroy(ifp->if_pfil);
1478 
1479 	/* Announce that the interface is gone. */
1480 	rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
1481 
1482 	IF_AFDATA_LOCK_DESTROY(ifp);
1483 
1484 	if (if_is_link_state_changeable(ifp)) {
1485 		softint_disestablish(ifp->if_link_si);
1486 		ifp->if_link_si = NULL;
1487 	}
1488 
1489 	/*
1490 	 * remove packets that came from ifp, from software interrupt queues.
1491 	 */
1492 	DOMAIN_FOREACH(dp) {
1493 		for (i = 0; i < __arraycount(dp->dom_ifqueues); i++) {
1494 			struct ifqueue *iq = dp->dom_ifqueues[i];
1495 			if (iq == NULL)
1496 				break;
1497 			dp->dom_ifqueues[i] = NULL;
1498 			if_detach_queues(ifp, iq);
1499 		}
1500 	}
1501 
1502 	/*
1503 	 * IP queues have to be processed separately: net-queue barrier
1504 	 * ensures that the packets are dequeued while a cross-call will
1505 	 * ensure that the interrupts have completed. FIXME: not quite..
1506 	 */
1507 #ifdef INET
1508 	pktq_barrier(ip_pktq);
1509 #endif
1510 #ifdef INET6
1511 	if (in6_present)
1512 		pktq_barrier(ip6_pktq);
1513 #endif
1514 	xc_barrier(0);
1515 
1516 	if (ifp->if_percpuq != NULL) {
1517 		if_percpuq_destroy(ifp->if_percpuq);
1518 		ifp->if_percpuq = NULL;
1519 	}
1520 
1521 	mutex_obj_free(ifp->if_ioctl_lock);
1522 	ifp->if_ioctl_lock = NULL;
1523 	mutex_obj_free(ifp->if_snd.ifq_lock);
1524 
1525 	splx(s);
1526 
1527 #ifdef IFAREF_DEBUG
1528 	if_check_and_free_ifa_list(ifp);
1529 #endif
1530 }
1531 
1532 static void
1533 if_detach_queues(struct ifnet *ifp, struct ifqueue *q)
1534 {
1535 	struct mbuf *m, *prev, *next;
1536 
1537 	prev = NULL;
1538 	for (m = q->ifq_head; m != NULL; m = next) {
1539 		KASSERT((m->m_flags & M_PKTHDR) != 0);
1540 
1541 		next = m->m_nextpkt;
1542 		if (m->m_pkthdr.rcvif_index != ifp->if_index) {
1543 			prev = m;
1544 			continue;
1545 		}
1546 
1547 		if (prev != NULL)
1548 			prev->m_nextpkt = m->m_nextpkt;
1549 		else
1550 			q->ifq_head = m->m_nextpkt;
1551 		if (q->ifq_tail == m)
1552 			q->ifq_tail = prev;
1553 		q->ifq_len--;
1554 
1555 		m->m_nextpkt = NULL;
1556 		m_freem(m);
1557 		IF_DROP(q);
1558 	}
1559 }
1560 
1561 /*
1562  * Callback for a radix tree walk to delete all references to an
1563  * ifnet.
1564  */
1565 static int
1566 if_delroute_matcher(struct rtentry *rt, void *v)
1567 {
1568 	struct ifnet *ifp = (struct ifnet *)v;
1569 
1570 	if (rt->rt_ifp == ifp)
1571 		return 1;
1572 	else
1573 		return 0;
1574 }
1575 
1576 /*
1577  * Create a clone network interface.
1578  */
1579 static int
1580 if_clone_create(const char *name)
1581 {
1582 	struct if_clone *ifc;
1583 	int unit;
1584 	struct ifnet *ifp;
1585 	struct psref psref;
1586 
1587 	KASSERT(mutex_owned(&if_clone_mtx));
1588 
1589 	ifc = if_clone_lookup(name, &unit);
1590 	if (ifc == NULL)
1591 		return EINVAL;
1592 
1593 	ifp = if_get(name, &psref);
1594 	if (ifp != NULL) {
1595 		if_put(ifp, &psref);
1596 		return EEXIST;
1597 	}
1598 
1599 	return (*ifc->ifc_create)(ifc, unit);
1600 }
1601 
1602 /*
1603  * Destroy a clone network interface.
1604  */
1605 static int
1606 if_clone_destroy(const char *name)
1607 {
1608 	struct if_clone *ifc;
1609 	struct ifnet *ifp;
1610 	struct psref psref;
1611 	int error;
1612 	int (*if_ioctl)(struct ifnet *, u_long, void *);
1613 
1614 	KASSERT(mutex_owned(&if_clone_mtx));
1615 
1616 	ifc = if_clone_lookup(name, NULL);
1617 	if (ifc == NULL)
1618 		return EINVAL;
1619 
1620 	if (ifc->ifc_destroy == NULL)
1621 		return EOPNOTSUPP;
1622 
1623 	ifp = if_get(name, &psref);
1624 	if (ifp == NULL)
1625 		return ENXIO;
1626 
1627 	/* We have to disable ioctls here */
1628 	IFNET_LOCK(ifp);
1629 	if_ioctl = ifp->if_ioctl;
1630 	ifp->if_ioctl = if_nullioctl;
1631 	IFNET_UNLOCK(ifp);
1632 
1633 	/*
1634 	 * We cannot call ifc_destroy with holding ifp.
1635 	 * Releasing ifp here is safe thanks to if_clone_mtx.
1636 	 */
1637 	if_put(ifp, &psref);
1638 
1639 	error = (*ifc->ifc_destroy)(ifp);
1640 
1641 	if (error != 0) {
1642 		/* We have to restore if_ioctl on error */
1643 		IFNET_LOCK(ifp);
1644 		ifp->if_ioctl = if_ioctl;
1645 		IFNET_UNLOCK(ifp);
1646 	}
1647 
1648 	return error;
1649 }
1650 
1651 static bool
1652 if_is_unit(const char *name)
1653 {
1654 
1655 	while (*name != '\0') {
1656 		if (*name < '0' || *name > '9')
1657 			return false;
1658 		name++;
1659 	}
1660 
1661 	return true;
1662 }
1663 
1664 /*
1665  * Look up a network interface cloner.
1666  */
1667 static struct if_clone *
1668 if_clone_lookup(const char *name, int *unitp)
1669 {
1670 	struct if_clone *ifc;
1671 	const char *cp;
1672 	char *dp, ifname[IFNAMSIZ + 3];
1673 	int unit;
1674 
1675 	KASSERT(mutex_owned(&if_clone_mtx));
1676 
1677 	strcpy(ifname, "if_");
1678 	/* separate interface name from unit */
1679 	/* TODO: search unit number from backward */
1680 	for (dp = ifname + 3, cp = name; cp - name < IFNAMSIZ &&
1681 	    *cp && !if_is_unit(cp);)
1682 		*dp++ = *cp++;
1683 
1684 	if (cp == name || cp - name == IFNAMSIZ || !*cp)
1685 		return NULL;	/* No name or unit number */
1686 	*dp++ = '\0';
1687 
1688 again:
1689 	LIST_FOREACH(ifc, &if_cloners, ifc_list) {
1690 		if (strcmp(ifname + 3, ifc->ifc_name) == 0)
1691 			break;
1692 	}
1693 
1694 	if (ifc == NULL) {
1695 		int error;
1696 		if (*ifname == '\0')
1697 			return NULL;
1698 		mutex_exit(&if_clone_mtx);
1699 		error = module_autoload(ifname, MODULE_CLASS_DRIVER);
1700 		mutex_enter(&if_clone_mtx);
1701 		if (error)
1702 			return NULL;
1703 		*ifname = '\0';
1704 		goto again;
1705 	}
1706 
1707 	unit = 0;
1708 	while (cp - name < IFNAMSIZ && *cp) {
1709 		if (*cp < '0' || *cp > '9' || unit >= INT_MAX / 10) {
1710 			/* Bogus unit number. */
1711 			return NULL;
1712 		}
1713 		unit = (unit * 10) + (*cp++ - '0');
1714 	}
1715 
1716 	if (unitp != NULL)
1717 		*unitp = unit;
1718 	return ifc;
1719 }
1720 
1721 /*
1722  * Register a network interface cloner.
1723  */
1724 void
1725 if_clone_attach(struct if_clone *ifc)
1726 {
1727 
1728 	mutex_enter(&if_clone_mtx);
1729 	LIST_INSERT_HEAD(&if_cloners, ifc, ifc_list);
1730 	if_cloners_count++;
1731 	mutex_exit(&if_clone_mtx);
1732 }
1733 
1734 /*
1735  * Unregister a network interface cloner.
1736  */
1737 void
1738 if_clone_detach(struct if_clone *ifc)
1739 {
1740 
1741 	mutex_enter(&if_clone_mtx);
1742 	LIST_REMOVE(ifc, ifc_list);
1743 	if_cloners_count--;
1744 	mutex_exit(&if_clone_mtx);
1745 }
1746 
1747 /*
1748  * Provide list of interface cloners to userspace.
1749  */
1750 int
1751 if_clone_list(int buf_count, char *buffer, int *total)
1752 {
1753 	char outbuf[IFNAMSIZ], *dst;
1754 	struct if_clone *ifc;
1755 	int count, error = 0;
1756 
1757 	mutex_enter(&if_clone_mtx);
1758 	*total = if_cloners_count;
1759 	if ((dst = buffer) == NULL) {
1760 		/* Just asking how many there are. */
1761 		goto out;
1762 	}
1763 
1764 	if (buf_count < 0) {
1765 		error = EINVAL;
1766 		goto out;
1767 	}
1768 
1769 	count = (if_cloners_count < buf_count) ?
1770 	    if_cloners_count : buf_count;
1771 
1772 	for (ifc = LIST_FIRST(&if_cloners); ifc != NULL && count != 0;
1773 	     ifc = LIST_NEXT(ifc, ifc_list), count--, dst += IFNAMSIZ) {
1774 		(void)strncpy(outbuf, ifc->ifc_name, sizeof(outbuf));
1775 		if (outbuf[sizeof(outbuf) - 1] != '\0') {
1776 			error = ENAMETOOLONG;
1777 			goto out;
1778 		}
1779 		error = copyout(outbuf, dst, sizeof(outbuf));
1780 		if (error != 0)
1781 			break;
1782 	}
1783 
1784 out:
1785 	mutex_exit(&if_clone_mtx);
1786 	return error;
1787 }
1788 
1789 void
1790 ifa_psref_init(struct ifaddr *ifa)
1791 {
1792 
1793 	psref_target_init(&ifa->ifa_psref, ifa_psref_class);
1794 }
1795 
1796 void
1797 ifaref(struct ifaddr *ifa)
1798 {
1799 
1800 	atomic_inc_uint(&ifa->ifa_refcnt);
1801 }
1802 
1803 void
1804 ifafree(struct ifaddr *ifa)
1805 {
1806 	KASSERT(ifa != NULL);
1807 	KASSERTMSG(ifa->ifa_refcnt > 0, "ifa_refcnt=%d", ifa->ifa_refcnt);
1808 
1809 	if (atomic_dec_uint_nv(&ifa->ifa_refcnt) == 0) {
1810 		free(ifa, M_IFADDR);
1811 	}
1812 }
1813 
1814 bool
1815 ifa_is_destroying(struct ifaddr *ifa)
1816 {
1817 
1818 	return ISSET(ifa->ifa_flags, IFA_DESTROYING);
1819 }
1820 
1821 void
1822 ifa_insert(struct ifnet *ifp, struct ifaddr *ifa)
1823 {
1824 
1825 	ifa->ifa_ifp = ifp;
1826 
1827 	/*
1828 	 * Check MP-safety for IFEF_MPSAFE drivers.
1829 	 * Check !IFF_RUNNING for initialization routines that normally don't
1830 	 * take IFNET_LOCK but it's safe because there is no competitor.
1831 	 * XXX there are false positive cases because IFF_RUNNING can be off on
1832 	 * if_stop.
1833 	 */
1834 	KASSERT(!if_is_mpsafe(ifp) || !ISSET(ifp->if_flags, IFF_RUNNING) ||
1835 	    IFNET_LOCKED(ifp));
1836 
1837 	TAILQ_INSERT_TAIL(&ifp->if_addrlist, ifa, ifa_list);
1838 	IFADDR_ENTRY_INIT(ifa);
1839 	IFADDR_WRITER_INSERT_TAIL(ifp, ifa);
1840 
1841 	ifaref(ifa);
1842 }
1843 
1844 void
1845 ifa_remove(struct ifnet *ifp, struct ifaddr *ifa)
1846 {
1847 
1848 	KASSERT(ifa->ifa_ifp == ifp);
1849 	/*
1850 	 * Check MP-safety for IFEF_MPSAFE drivers.
1851 	 * if_is_deactivated indicates ifa_remove is called form if_detach
1852 	 * where is safe even if IFNET_LOCK isn't held.
1853 	 */
1854 	KASSERT(!if_is_mpsafe(ifp) || if_is_deactivated(ifp) || IFNET_LOCKED(ifp));
1855 
1856 	TAILQ_REMOVE(&ifp->if_addrlist, ifa, ifa_list);
1857 	IFADDR_WRITER_REMOVE(ifa);
1858 #ifdef NET_MPSAFE
1859 	IFNET_GLOBAL_LOCK();
1860 	pserialize_perform(ifnet_psz);
1861 	IFNET_GLOBAL_UNLOCK();
1862 #endif
1863 
1864 #ifdef NET_MPSAFE
1865 	psref_target_destroy(&ifa->ifa_psref, ifa_psref_class);
1866 #endif
1867 	IFADDR_ENTRY_DESTROY(ifa);
1868 	ifafree(ifa);
1869 }
1870 
1871 void
1872 ifa_acquire(struct ifaddr *ifa, struct psref *psref)
1873 {
1874 
1875 	PSREF_DEBUG_FILL_RETURN_ADDRESS(psref);
1876 	psref_acquire(psref, &ifa->ifa_psref, ifa_psref_class);
1877 }
1878 
1879 void
1880 ifa_release(struct ifaddr *ifa, struct psref *psref)
1881 {
1882 
1883 	if (ifa == NULL)
1884 		return;
1885 
1886 	psref_release(psref, &ifa->ifa_psref, ifa_psref_class);
1887 }
1888 
1889 bool
1890 ifa_held(struct ifaddr *ifa)
1891 {
1892 
1893 	return psref_held(&ifa->ifa_psref, ifa_psref_class);
1894 }
1895 
1896 static inline int
1897 equal(const struct sockaddr *sa1, const struct sockaddr *sa2)
1898 {
1899 	return sockaddr_cmp(sa1, sa2) == 0;
1900 }
1901 
1902 /*
1903  * Locate an interface based on a complete address.
1904  */
1905 /*ARGSUSED*/
1906 struct ifaddr *
1907 ifa_ifwithaddr(const struct sockaddr *addr)
1908 {
1909 	struct ifnet *ifp;
1910 	struct ifaddr *ifa;
1911 
1912 	IFNET_READER_FOREACH(ifp) {
1913 		if (if_is_deactivated(ifp))
1914 			continue;
1915 		IFADDR_READER_FOREACH(ifa, ifp) {
1916 			if (ifa->ifa_addr->sa_family != addr->sa_family)
1917 				continue;
1918 			if (equal(addr, ifa->ifa_addr))
1919 				return ifa;
1920 			if ((ifp->if_flags & IFF_BROADCAST) &&
1921 			    ifa->ifa_broadaddr &&
1922 			    /* IP6 doesn't have broadcast */
1923 			    ifa->ifa_broadaddr->sa_len != 0 &&
1924 			    equal(ifa->ifa_broadaddr, addr))
1925 				return ifa;
1926 		}
1927 	}
1928 	return NULL;
1929 }
1930 
1931 struct ifaddr *
1932 ifa_ifwithaddr_psref(const struct sockaddr *addr, struct psref *psref)
1933 {
1934 	struct ifaddr *ifa;
1935 	int s = pserialize_read_enter();
1936 
1937 	ifa = ifa_ifwithaddr(addr);
1938 	if (ifa != NULL)
1939 		ifa_acquire(ifa, psref);
1940 	pserialize_read_exit(s);
1941 
1942 	return ifa;
1943 }
1944 
1945 /*
1946  * Locate the point to point interface with a given destination address.
1947  */
1948 /*ARGSUSED*/
1949 struct ifaddr *
1950 ifa_ifwithdstaddr(const struct sockaddr *addr)
1951 {
1952 	struct ifnet *ifp;
1953 	struct ifaddr *ifa;
1954 
1955 	IFNET_READER_FOREACH(ifp) {
1956 		if (if_is_deactivated(ifp))
1957 			continue;
1958 		if ((ifp->if_flags & IFF_POINTOPOINT) == 0)
1959 			continue;
1960 		IFADDR_READER_FOREACH(ifa, ifp) {
1961 			if (ifa->ifa_addr->sa_family != addr->sa_family ||
1962 			    ifa->ifa_dstaddr == NULL)
1963 				continue;
1964 			if (equal(addr, ifa->ifa_dstaddr))
1965 				return ifa;
1966 		}
1967 	}
1968 
1969 	return NULL;
1970 }
1971 
1972 struct ifaddr *
1973 ifa_ifwithdstaddr_psref(const struct sockaddr *addr, struct psref *psref)
1974 {
1975 	struct ifaddr *ifa;
1976 	int s;
1977 
1978 	s = pserialize_read_enter();
1979 	ifa = ifa_ifwithdstaddr(addr);
1980 	if (ifa != NULL)
1981 		ifa_acquire(ifa, psref);
1982 	pserialize_read_exit(s);
1983 
1984 	return ifa;
1985 }
1986 
1987 /*
1988  * Find an interface on a specific network.  If many, choice
1989  * is most specific found.
1990  */
1991 struct ifaddr *
1992 ifa_ifwithnet(const struct sockaddr *addr)
1993 {
1994 	struct ifnet *ifp;
1995 	struct ifaddr *ifa, *ifa_maybe = NULL;
1996 	const struct sockaddr_dl *sdl;
1997 	u_int af = addr->sa_family;
1998 	const char *addr_data = addr->sa_data, *cplim;
1999 
2000 	if (af == AF_LINK) {
2001 		sdl = satocsdl(addr);
2002 		if (sdl->sdl_index && sdl->sdl_index < if_indexlim &&
2003 		    ifindex2ifnet[sdl->sdl_index] &&
2004 		    !if_is_deactivated(ifindex2ifnet[sdl->sdl_index])) {
2005 			return ifindex2ifnet[sdl->sdl_index]->if_dl;
2006 		}
2007 	}
2008 #ifdef NETATALK
2009 	if (af == AF_APPLETALK) {
2010 		const struct sockaddr_at *sat, *sat2;
2011 		sat = (const struct sockaddr_at *)addr;
2012 		IFNET_READER_FOREACH(ifp) {
2013 			if (if_is_deactivated(ifp))
2014 				continue;
2015 			ifa = at_ifawithnet((const struct sockaddr_at *)addr, ifp);
2016 			if (ifa == NULL)
2017 				continue;
2018 			sat2 = (struct sockaddr_at *)ifa->ifa_addr;
2019 			if (sat2->sat_addr.s_net == sat->sat_addr.s_net)
2020 				return ifa; /* exact match */
2021 			if (ifa_maybe == NULL) {
2022 				/* else keep the if with the right range */
2023 				ifa_maybe = ifa;
2024 			}
2025 		}
2026 		return ifa_maybe;
2027 	}
2028 #endif
2029 	IFNET_READER_FOREACH(ifp) {
2030 		if (if_is_deactivated(ifp))
2031 			continue;
2032 		IFADDR_READER_FOREACH(ifa, ifp) {
2033 			const char *cp, *cp2, *cp3;
2034 
2035 			if (ifa->ifa_addr->sa_family != af ||
2036 			    ifa->ifa_netmask == NULL)
2037  next:				continue;
2038 			cp = addr_data;
2039 			cp2 = ifa->ifa_addr->sa_data;
2040 			cp3 = ifa->ifa_netmask->sa_data;
2041 			cplim = (const char *)ifa->ifa_netmask +
2042 			    ifa->ifa_netmask->sa_len;
2043 			while (cp3 < cplim) {
2044 				if ((*cp++ ^ *cp2++) & *cp3++) {
2045 					/* want to continue for() loop */
2046 					goto next;
2047 				}
2048 			}
2049 			if (ifa_maybe == NULL ||
2050 			    rt_refines(ifa->ifa_netmask,
2051 			               ifa_maybe->ifa_netmask))
2052 				ifa_maybe = ifa;
2053 		}
2054 	}
2055 	return ifa_maybe;
2056 }
2057 
2058 struct ifaddr *
2059 ifa_ifwithnet_psref(const struct sockaddr *addr, struct psref *psref)
2060 {
2061 	struct ifaddr *ifa;
2062 	int s;
2063 
2064 	s = pserialize_read_enter();
2065 	ifa = ifa_ifwithnet(addr);
2066 	if (ifa != NULL)
2067 		ifa_acquire(ifa, psref);
2068 	pserialize_read_exit(s);
2069 
2070 	return ifa;
2071 }
2072 
2073 /*
2074  * Find the interface of the addresss.
2075  */
2076 struct ifaddr *
2077 ifa_ifwithladdr(const struct sockaddr *addr)
2078 {
2079 	struct ifaddr *ia;
2080 
2081 	if ((ia = ifa_ifwithaddr(addr)) || (ia = ifa_ifwithdstaddr(addr)) ||
2082 	    (ia = ifa_ifwithnet(addr)))
2083 		return ia;
2084 	return NULL;
2085 }
2086 
2087 struct ifaddr *
2088 ifa_ifwithladdr_psref(const struct sockaddr *addr, struct psref *psref)
2089 {
2090 	struct ifaddr *ifa;
2091 	int s;
2092 
2093 	s = pserialize_read_enter();
2094 	ifa = ifa_ifwithladdr(addr);
2095 	if (ifa != NULL)
2096 		ifa_acquire(ifa, psref);
2097 	pserialize_read_exit(s);
2098 
2099 	return ifa;
2100 }
2101 
2102 /*
2103  * Find an interface using a specific address family
2104  */
2105 struct ifaddr *
2106 ifa_ifwithaf(int af)
2107 {
2108 	struct ifnet *ifp;
2109 	struct ifaddr *ifa = NULL;
2110 	int s;
2111 
2112 	s = pserialize_read_enter();
2113 	IFNET_READER_FOREACH(ifp) {
2114 		if (if_is_deactivated(ifp))
2115 			continue;
2116 		IFADDR_READER_FOREACH(ifa, ifp) {
2117 			if (ifa->ifa_addr->sa_family == af)
2118 				goto out;
2119 		}
2120 	}
2121 out:
2122 	pserialize_read_exit(s);
2123 	return ifa;
2124 }
2125 
2126 /*
2127  * Find an interface address specific to an interface best matching
2128  * a given address.
2129  */
2130 struct ifaddr *
2131 ifaof_ifpforaddr(const struct sockaddr *addr, struct ifnet *ifp)
2132 {
2133 	struct ifaddr *ifa;
2134 	const char *cp, *cp2, *cp3;
2135 	const char *cplim;
2136 	struct ifaddr *ifa_maybe = 0;
2137 	u_int af = addr->sa_family;
2138 
2139 	if (if_is_deactivated(ifp))
2140 		return NULL;
2141 
2142 	if (af >= AF_MAX)
2143 		return NULL;
2144 
2145 	IFADDR_READER_FOREACH(ifa, ifp) {
2146 		if (ifa->ifa_addr->sa_family != af)
2147 			continue;
2148 		ifa_maybe = ifa;
2149 		if (ifa->ifa_netmask == NULL) {
2150 			if (equal(addr, ifa->ifa_addr) ||
2151 			    (ifa->ifa_dstaddr &&
2152 			     equal(addr, ifa->ifa_dstaddr)))
2153 				return ifa;
2154 			continue;
2155 		}
2156 		cp = addr->sa_data;
2157 		cp2 = ifa->ifa_addr->sa_data;
2158 		cp3 = ifa->ifa_netmask->sa_data;
2159 		cplim = ifa->ifa_netmask->sa_len + (char *)ifa->ifa_netmask;
2160 		for (; cp3 < cplim; cp3++) {
2161 			if ((*cp++ ^ *cp2++) & *cp3)
2162 				break;
2163 		}
2164 		if (cp3 == cplim)
2165 			return ifa;
2166 	}
2167 	return ifa_maybe;
2168 }
2169 
2170 struct ifaddr *
2171 ifaof_ifpforaddr_psref(const struct sockaddr *addr, struct ifnet *ifp,
2172     struct psref *psref)
2173 {
2174 	struct ifaddr *ifa;
2175 	int s;
2176 
2177 	s = pserialize_read_enter();
2178 	ifa = ifaof_ifpforaddr(addr, ifp);
2179 	if (ifa != NULL)
2180 		ifa_acquire(ifa, psref);
2181 	pserialize_read_exit(s);
2182 
2183 	return ifa;
2184 }
2185 
2186 /*
2187  * Default action when installing a route with a Link Level gateway.
2188  * Lookup an appropriate real ifa to point to.
2189  * This should be moved to /sys/net/link.c eventually.
2190  */
2191 void
2192 link_rtrequest(int cmd, struct rtentry *rt, const struct rt_addrinfo *info)
2193 {
2194 	struct ifaddr *ifa;
2195 	const struct sockaddr *dst;
2196 	struct ifnet *ifp;
2197 	struct psref psref;
2198 
2199 	if (cmd != RTM_ADD || ISSET(info->rti_flags, RTF_DONTCHANGEIFA))
2200 		return;
2201 	ifp = rt->rt_ifa->ifa_ifp;
2202 	dst = rt_getkey(rt);
2203 	if ((ifa = ifaof_ifpforaddr_psref(dst, ifp, &psref)) != NULL) {
2204 		rt_replace_ifa(rt, ifa);
2205 		if (ifa->ifa_rtrequest && ifa->ifa_rtrequest != link_rtrequest)
2206 			ifa->ifa_rtrequest(cmd, rt, info);
2207 		ifa_release(ifa, &psref);
2208 	}
2209 }
2210 
2211 /*
2212  * bitmask macros to manage a densely packed link_state change queue.
2213  * Because we need to store LINK_STATE_UNKNOWN(0), LINK_STATE_DOWN(1) and
2214  * LINK_STATE_UP(2) we need 2 bits for each state change.
2215  * As a state change to store is 0, treat all bits set as an unset item.
2216  */
2217 #define LQ_ITEM_BITS		2
2218 #define LQ_ITEM_MASK		((1 << LQ_ITEM_BITS) - 1)
2219 #define LQ_MASK(i)		(LQ_ITEM_MASK << (i) * LQ_ITEM_BITS)
2220 #define LINK_STATE_UNSET	LQ_ITEM_MASK
2221 #define LQ_ITEM(q, i)		(((q) & LQ_MASK((i))) >> (i) * LQ_ITEM_BITS)
2222 #define LQ_STORE(q, i, v)						      \
2223 	do {								      \
2224 		(q) &= ~LQ_MASK((i));					      \
2225 		(q) |= (v) << (i) * LQ_ITEM_BITS;			      \
2226 	} while (0 /* CONSTCOND */)
2227 #define LQ_MAX(q)		((sizeof((q)) * NBBY) / LQ_ITEM_BITS)
2228 #define LQ_POP(q, v)							      \
2229 	do {								      \
2230 		(v) = LQ_ITEM((q), 0);					      \
2231 		(q) >>= LQ_ITEM_BITS;					      \
2232 		(q) |= LINK_STATE_UNSET << (LQ_MAX((q)) - 1) * LQ_ITEM_BITS;  \
2233 	} while (0 /* CONSTCOND */)
2234 #define LQ_PUSH(q, v)							      \
2235 	do {								      \
2236 		(q) >>= LQ_ITEM_BITS;					      \
2237 		(q) |= (v) << (LQ_MAX((q)) - 1) * LQ_ITEM_BITS;		      \
2238 	} while (0 /* CONSTCOND */)
2239 #define LQ_FIND_UNSET(q, i)						      \
2240 	for ((i) = 0; i < LQ_MAX((q)); (i)++) {				      \
2241 		if (LQ_ITEM((q), (i)) == LINK_STATE_UNSET)		      \
2242 			break;						      \
2243 	}
2244 
2245 /*
2246  * XXX reusing (ifp)->if_snd->ifq_lock rather than having another spin mutex
2247  * for each ifnet.  It doesn't matter because:
2248  * - if IFEF_MPSAFE is enabled, if_snd isn't used and lock contentions on
2249  *   ifq_lock don't happen
2250  * - if IFEF_MPSAFE is disabled, there is no lock contention on ifq_lock
2251  *   because if_snd, if_link_state_change and if_link_state_change_softint
2252  *   are all called with KERNEL_LOCK
2253  */
2254 #define IF_LINK_STATE_CHANGE_LOCK(ifp)		\
2255 	mutex_enter((ifp)->if_snd.ifq_lock)
2256 #define IF_LINK_STATE_CHANGE_UNLOCK(ifp)	\
2257 	mutex_exit((ifp)->if_snd.ifq_lock)
2258 
2259 /*
2260  * Handle a change in the interface link state and
2261  * queue notifications.
2262  */
2263 void
2264 if_link_state_change(struct ifnet *ifp, int link_state)
2265 {
2266 	int idx;
2267 
2268 	KASSERTMSG(if_is_link_state_changeable(ifp),
2269 	    "%s: IFEF_NO_LINK_STATE_CHANGE must not be set, but if_extflags=0x%x",
2270 	    ifp->if_xname, ifp->if_extflags);
2271 
2272 	/* Ensure change is to a valid state */
2273 	switch (link_state) {
2274 	case LINK_STATE_UNKNOWN:	/* FALLTHROUGH */
2275 	case LINK_STATE_DOWN:		/* FALLTHROUGH */
2276 	case LINK_STATE_UP:
2277 		break;
2278 	default:
2279 #ifdef DEBUG
2280 		printf("%s: invalid link state %d\n",
2281 		    ifp->if_xname, link_state);
2282 #endif
2283 		return;
2284 	}
2285 
2286 	IF_LINK_STATE_CHANGE_LOCK(ifp);
2287 
2288 	/* Find the last unset event in the queue. */
2289 	LQ_FIND_UNSET(ifp->if_link_queue, idx);
2290 
2291 	/*
2292 	 * Ensure link_state doesn't match the last event in the queue.
2293 	 * ifp->if_link_state is not checked and set here because
2294 	 * that would present an inconsistent picture to the system.
2295 	 */
2296 	if (idx != 0 &&
2297 	    LQ_ITEM(ifp->if_link_queue, idx - 1) == (uint8_t)link_state)
2298 		goto out;
2299 
2300 	/* Handle queue overflow. */
2301 	if (idx == LQ_MAX(ifp->if_link_queue)) {
2302 		uint8_t lost;
2303 
2304 		/*
2305 		 * The DOWN state must be protected from being pushed off
2306 		 * the queue to ensure that userland will always be
2307 		 * in a sane state.
2308 		 * Because DOWN is protected, there is no need to protect
2309 		 * UNKNOWN.
2310 		 * It should be invalid to change from any other state to
2311 		 * UNKNOWN anyway ...
2312 		 */
2313 		lost = LQ_ITEM(ifp->if_link_queue, 0);
2314 		LQ_PUSH(ifp->if_link_queue, (uint8_t)link_state);
2315 		if (lost == LINK_STATE_DOWN) {
2316 			lost = LQ_ITEM(ifp->if_link_queue, 0);
2317 			LQ_STORE(ifp->if_link_queue, 0, LINK_STATE_DOWN);
2318 		}
2319 		printf("%s: lost link state change %s\n",
2320 		    ifp->if_xname,
2321 		    lost == LINK_STATE_UP ? "UP" :
2322 		    lost == LINK_STATE_DOWN ? "DOWN" :
2323 		    "UNKNOWN");
2324 	} else
2325 		LQ_STORE(ifp->if_link_queue, idx, (uint8_t)link_state);
2326 
2327 	softint_schedule(ifp->if_link_si);
2328 
2329 out:
2330 	IF_LINK_STATE_CHANGE_UNLOCK(ifp);
2331 }
2332 
2333 /*
2334  * Handle interface link state change notifications.
2335  */
2336 void
2337 if_link_state_change_softint(struct ifnet *ifp, int link_state)
2338 {
2339 	struct domain *dp;
2340 	int s = splnet();
2341 	bool notify;
2342 
2343 	KASSERT(!cpu_intr_p());
2344 
2345 	IF_LINK_STATE_CHANGE_LOCK(ifp);
2346 
2347 	/* Ensure the change is still valid. */
2348 	if (ifp->if_link_state == link_state) {
2349 		IF_LINK_STATE_CHANGE_UNLOCK(ifp);
2350 		splx(s);
2351 		return;
2352 	}
2353 
2354 #ifdef DEBUG
2355 	log(LOG_DEBUG, "%s: link state %s (was %s)\n", ifp->if_xname,
2356 		link_state == LINK_STATE_UP ? "UP" :
2357 		link_state == LINK_STATE_DOWN ? "DOWN" :
2358 		"UNKNOWN",
2359 		ifp->if_link_state == LINK_STATE_UP ? "UP" :
2360 		ifp->if_link_state == LINK_STATE_DOWN ? "DOWN" :
2361 		"UNKNOWN");
2362 #endif
2363 
2364 	/*
2365 	 * When going from UNKNOWN to UP, we need to mark existing
2366 	 * addresses as tentative and restart DAD as we may have
2367 	 * erroneously not found a duplicate.
2368 	 *
2369 	 * This needs to happen before rt_ifmsg to avoid a race where
2370 	 * listeners would have an address and expect it to work right
2371 	 * away.
2372 	 */
2373 	notify = (link_state == LINK_STATE_UP &&
2374 	    ifp->if_link_state == LINK_STATE_UNKNOWN);
2375 	ifp->if_link_state = link_state;
2376 	/* The following routines may sleep so release the spin mutex */
2377 	IF_LINK_STATE_CHANGE_UNLOCK(ifp);
2378 
2379 	KERNEL_LOCK_UNLESS_NET_MPSAFE();
2380 	if (notify) {
2381 		DOMAIN_FOREACH(dp) {
2382 			if (dp->dom_if_link_state_change != NULL)
2383 				dp->dom_if_link_state_change(ifp,
2384 				    LINK_STATE_DOWN);
2385 		}
2386 	}
2387 
2388 	/* Notify that the link state has changed. */
2389 	rt_ifmsg(ifp);
2390 
2391 #if NCARP > 0
2392 	if (ifp->if_carp)
2393 		carp_carpdev_state(ifp);
2394 #endif
2395 
2396 	DOMAIN_FOREACH(dp) {
2397 		if (dp->dom_if_link_state_change != NULL)
2398 			dp->dom_if_link_state_change(ifp, link_state);
2399 	}
2400 	KERNEL_UNLOCK_UNLESS_NET_MPSAFE();
2401 	splx(s);
2402 }
2403 
2404 /*
2405  * Process the interface link state change queue.
2406  */
2407 static void
2408 if_link_state_change_si(void *arg)
2409 {
2410 	struct ifnet *ifp = arg;
2411 	int s;
2412 	uint8_t state;
2413 	bool schedule;
2414 
2415 	SOFTNET_KERNEL_LOCK_UNLESS_NET_MPSAFE();
2416 	s = splnet();
2417 
2418 	/* Pop a link state change from the queue and process it. */
2419 	IF_LINK_STATE_CHANGE_LOCK(ifp);
2420 	LQ_POP(ifp->if_link_queue, state);
2421 	IF_LINK_STATE_CHANGE_UNLOCK(ifp);
2422 
2423 	if_link_state_change_softint(ifp, state);
2424 
2425 	/* If there is a link state change to come, schedule it. */
2426 	IF_LINK_STATE_CHANGE_LOCK(ifp);
2427 	schedule = (LQ_ITEM(ifp->if_link_queue, 0) != LINK_STATE_UNSET);
2428 	IF_LINK_STATE_CHANGE_UNLOCK(ifp);
2429 	if (schedule)
2430 		softint_schedule(ifp->if_link_si);
2431 
2432 	splx(s);
2433 	SOFTNET_KERNEL_UNLOCK_UNLESS_NET_MPSAFE();
2434 }
2435 
2436 /*
2437  * Default action when installing a local route on a point-to-point
2438  * interface.
2439  */
2440 void
2441 p2p_rtrequest(int req, struct rtentry *rt,
2442     __unused const struct rt_addrinfo *info)
2443 {
2444 	struct ifnet *ifp = rt->rt_ifp;
2445 	struct ifaddr *ifa, *lo0ifa;
2446 	int s = pserialize_read_enter();
2447 
2448 	switch (req) {
2449 	case RTM_ADD:
2450 		if ((rt->rt_flags & RTF_LOCAL) == 0)
2451 			break;
2452 
2453 		rt->rt_ifp = lo0ifp;
2454 
2455 		if (ISSET(info->rti_flags, RTF_DONTCHANGEIFA))
2456 			break;
2457 
2458 		IFADDR_READER_FOREACH(ifa, ifp) {
2459 			if (equal(rt_getkey(rt), ifa->ifa_addr))
2460 				break;
2461 		}
2462 		if (ifa == NULL)
2463 			break;
2464 
2465 		/*
2466 		 * Ensure lo0 has an address of the same family.
2467 		 */
2468 		IFADDR_READER_FOREACH(lo0ifa, lo0ifp) {
2469 			if (lo0ifa->ifa_addr->sa_family ==
2470 			    ifa->ifa_addr->sa_family)
2471 				break;
2472 		}
2473 		if (lo0ifa == NULL)
2474 			break;
2475 
2476 		/*
2477 		 * Make sure to set rt->rt_ifa to the interface
2478 		 * address we are using, otherwise we will have trouble
2479 		 * with source address selection.
2480 		 */
2481 		if (ifa != rt->rt_ifa)
2482 			rt_replace_ifa(rt, ifa);
2483 		break;
2484 	case RTM_DELETE:
2485 	default:
2486 		break;
2487 	}
2488 	pserialize_read_exit(s);
2489 }
2490 
2491 static void
2492 _if_down(struct ifnet *ifp)
2493 {
2494 	struct ifaddr *ifa;
2495 	struct domain *dp;
2496 	int s, bound;
2497 	struct psref psref;
2498 
2499 	ifp->if_flags &= ~IFF_UP;
2500 	nanotime(&ifp->if_lastchange);
2501 
2502 	bound = curlwp_bind();
2503 	s = pserialize_read_enter();
2504 	IFADDR_READER_FOREACH(ifa, ifp) {
2505 		ifa_acquire(ifa, &psref);
2506 		pserialize_read_exit(s);
2507 
2508 		pfctlinput(PRC_IFDOWN, ifa->ifa_addr);
2509 
2510 		s = pserialize_read_enter();
2511 		ifa_release(ifa, &psref);
2512 	}
2513 	pserialize_read_exit(s);
2514 	curlwp_bindx(bound);
2515 
2516 	IFQ_PURGE(&ifp->if_snd);
2517 #if NCARP > 0
2518 	if (ifp->if_carp)
2519 		carp_carpdev_state(ifp);
2520 #endif
2521 	rt_ifmsg(ifp);
2522 	DOMAIN_FOREACH(dp) {
2523 		if (dp->dom_if_down)
2524 			dp->dom_if_down(ifp);
2525 	}
2526 }
2527 
2528 static void
2529 if_down_deactivated(struct ifnet *ifp)
2530 {
2531 
2532 	KASSERT(if_is_deactivated(ifp));
2533 	_if_down(ifp);
2534 }
2535 
2536 void
2537 if_down_locked(struct ifnet *ifp)
2538 {
2539 
2540 	KASSERT(IFNET_LOCKED(ifp));
2541 	_if_down(ifp);
2542 }
2543 
2544 /*
2545  * Mark an interface down and notify protocols of
2546  * the transition.
2547  * NOTE: must be called at splsoftnet or equivalent.
2548  */
2549 void
2550 if_down(struct ifnet *ifp)
2551 {
2552 
2553 	IFNET_LOCK(ifp);
2554 	if_down_locked(ifp);
2555 	IFNET_UNLOCK(ifp);
2556 }
2557 
2558 /*
2559  * Must be called with holding if_ioctl_lock.
2560  */
2561 static void
2562 if_up_locked(struct ifnet *ifp)
2563 {
2564 #ifdef notyet
2565 	struct ifaddr *ifa;
2566 #endif
2567 	struct domain *dp;
2568 
2569 	KASSERT(IFNET_LOCKED(ifp));
2570 
2571 	KASSERT(!if_is_deactivated(ifp));
2572 	ifp->if_flags |= IFF_UP;
2573 	nanotime(&ifp->if_lastchange);
2574 #ifdef notyet
2575 	/* this has no effect on IP, and will kill all ISO connections XXX */
2576 	IFADDR_READER_FOREACH(ifa, ifp)
2577 		pfctlinput(PRC_IFUP, ifa->ifa_addr);
2578 #endif
2579 #if NCARP > 0
2580 	if (ifp->if_carp)
2581 		carp_carpdev_state(ifp);
2582 #endif
2583 	rt_ifmsg(ifp);
2584 	DOMAIN_FOREACH(dp) {
2585 		if (dp->dom_if_up)
2586 			dp->dom_if_up(ifp);
2587 	}
2588 }
2589 
2590 /*
2591  * Handle interface slowtimo timer routine.  Called
2592  * from softclock, we decrement timer (if set) and
2593  * call the appropriate interface routine on expiration.
2594  */
2595 static void
2596 if_slowtimo(void *arg)
2597 {
2598 	void (*slowtimo)(struct ifnet *);
2599 	struct ifnet *ifp = arg;
2600 	int s;
2601 
2602 	slowtimo = ifp->if_slowtimo;
2603 	if (__predict_false(slowtimo == NULL))
2604 		return;
2605 
2606 	s = splnet();
2607 	if (ifp->if_timer != 0 && --ifp->if_timer == 0)
2608 		(*slowtimo)(ifp);
2609 
2610 	splx(s);
2611 
2612 	if (__predict_true(ifp->if_slowtimo != NULL))
2613 		callout_schedule(ifp->if_slowtimo_ch, hz / IFNET_SLOWHZ);
2614 }
2615 
2616 /*
2617  * Mark an interface up and notify protocols of
2618  * the transition.
2619  * NOTE: must be called at splsoftnet or equivalent.
2620  */
2621 void
2622 if_up(struct ifnet *ifp)
2623 {
2624 
2625 	IFNET_LOCK(ifp);
2626 	if_up_locked(ifp);
2627 	IFNET_UNLOCK(ifp);
2628 }
2629 
2630 /*
2631  * Set/clear promiscuous mode on interface ifp based on the truth value
2632  * of pswitch.  The calls are reference counted so that only the first
2633  * "on" request actually has an effect, as does the final "off" request.
2634  * Results are undefined if the "off" and "on" requests are not matched.
2635  */
2636 int
2637 ifpromisc_locked(struct ifnet *ifp, int pswitch)
2638 {
2639 	int pcount, ret = 0;
2640 	u_short nflags;
2641 
2642 	KASSERT(IFNET_LOCKED(ifp));
2643 
2644 	pcount = ifp->if_pcount;
2645 	if (pswitch) {
2646 		/*
2647 		 * Allow the device to be "placed" into promiscuous
2648 		 * mode even if it is not configured up.  It will
2649 		 * consult IFF_PROMISC when it is brought up.
2650 		 */
2651 		if (ifp->if_pcount++ != 0)
2652 			goto out;
2653 		nflags = ifp->if_flags | IFF_PROMISC;
2654 	} else {
2655 		if (--ifp->if_pcount > 0)
2656 			goto out;
2657 		nflags = ifp->if_flags & ~IFF_PROMISC;
2658 	}
2659 	ret = if_flags_set(ifp, nflags);
2660 	/* Restore interface state if not successful. */
2661 	if (ret != 0) {
2662 		ifp->if_pcount = pcount;
2663 	}
2664 out:
2665 	return ret;
2666 }
2667 
2668 int
2669 ifpromisc(struct ifnet *ifp, int pswitch)
2670 {
2671 	int e;
2672 
2673 	IFNET_LOCK(ifp);
2674 	e = ifpromisc_locked(ifp, pswitch);
2675 	IFNET_UNLOCK(ifp);
2676 
2677 	return e;
2678 }
2679 
2680 /*
2681  * Map interface name to
2682  * interface structure pointer.
2683  */
2684 struct ifnet *
2685 ifunit(const char *name)
2686 {
2687 	struct ifnet *ifp;
2688 	const char *cp = name;
2689 	u_int unit = 0;
2690 	u_int i;
2691 	int s;
2692 
2693 	/*
2694 	 * If the entire name is a number, treat it as an ifindex.
2695 	 */
2696 	for (i = 0; i < IFNAMSIZ && *cp >= '0' && *cp <= '9'; i++, cp++) {
2697 		unit = unit * 10 + (*cp - '0');
2698 	}
2699 
2700 	/*
2701 	 * If the number took all of the name, then it's a valid ifindex.
2702 	 */
2703 	if (i == IFNAMSIZ || (cp != name && *cp == '\0'))
2704 		return if_byindex(unit);
2705 
2706 	ifp = NULL;
2707 	s = pserialize_read_enter();
2708 	IFNET_READER_FOREACH(ifp) {
2709 		if (if_is_deactivated(ifp))
2710 			continue;
2711 	 	if (strcmp(ifp->if_xname, name) == 0)
2712 			goto out;
2713 	}
2714 out:
2715 	pserialize_read_exit(s);
2716 	return ifp;
2717 }
2718 
2719 /*
2720  * Get a reference of an ifnet object by an interface name.
2721  * The returned reference is protected by psref(9). The caller
2722  * must release a returned reference by if_put after use.
2723  */
2724 struct ifnet *
2725 if_get(const char *name, struct psref *psref)
2726 {
2727 	struct ifnet *ifp;
2728 	const char *cp = name;
2729 	u_int unit = 0;
2730 	u_int i;
2731 	int s;
2732 
2733 	/*
2734 	 * If the entire name is a number, treat it as an ifindex.
2735 	 */
2736 	for (i = 0; i < IFNAMSIZ && *cp >= '0' && *cp <= '9'; i++, cp++) {
2737 		unit = unit * 10 + (*cp - '0');
2738 	}
2739 
2740 	/*
2741 	 * If the number took all of the name, then it's a valid ifindex.
2742 	 */
2743 	if (i == IFNAMSIZ || (cp != name && *cp == '\0'))
2744 		return if_get_byindex(unit, psref);
2745 
2746 	ifp = NULL;
2747 	s = pserialize_read_enter();
2748 	IFNET_READER_FOREACH(ifp) {
2749 		if (if_is_deactivated(ifp))
2750 			continue;
2751 		if (strcmp(ifp->if_xname, name) == 0) {
2752 			PSREF_DEBUG_FILL_RETURN_ADDRESS(psref);
2753 			psref_acquire(psref, &ifp->if_psref,
2754 			    ifnet_psref_class);
2755 			goto out;
2756 		}
2757 	}
2758 out:
2759 	pserialize_read_exit(s);
2760 	return ifp;
2761 }
2762 
2763 /*
2764  * Release a reference of an ifnet object given by if_get, if_get_byindex
2765  * or if_get_bylla.
2766  */
2767 void
2768 if_put(const struct ifnet *ifp, struct psref *psref)
2769 {
2770 
2771 	if (ifp == NULL)
2772 		return;
2773 
2774 	psref_release(psref, &ifp->if_psref, ifnet_psref_class);
2775 }
2776 
2777 /*
2778  * Return ifp having idx. Return NULL if not found.  Normally if_byindex
2779  * should be used.
2780  */
2781 ifnet_t *
2782 _if_byindex(u_int idx)
2783 {
2784 
2785 	return (__predict_true(idx < if_indexlim)) ? ifindex2ifnet[idx] : NULL;
2786 }
2787 
2788 /*
2789  * Return ifp having idx. Return NULL if not found or the found ifp is
2790  * already deactivated.
2791  */
2792 ifnet_t *
2793 if_byindex(u_int idx)
2794 {
2795 	ifnet_t *ifp;
2796 
2797 	ifp = _if_byindex(idx);
2798 	if (ifp != NULL && if_is_deactivated(ifp))
2799 		ifp = NULL;
2800 	return ifp;
2801 }
2802 
2803 /*
2804  * Get a reference of an ifnet object by an interface index.
2805  * The returned reference is protected by psref(9). The caller
2806  * must release a returned reference by if_put after use.
2807  */
2808 ifnet_t *
2809 if_get_byindex(u_int idx, struct psref *psref)
2810 {
2811 	ifnet_t *ifp;
2812 	int s;
2813 
2814 	s = pserialize_read_enter();
2815 	ifp = if_byindex(idx);
2816 	if (__predict_true(ifp != NULL)) {
2817 		PSREF_DEBUG_FILL_RETURN_ADDRESS(psref);
2818 		psref_acquire(psref, &ifp->if_psref, ifnet_psref_class);
2819 	}
2820 	pserialize_read_exit(s);
2821 
2822 	return ifp;
2823 }
2824 
2825 ifnet_t *
2826 if_get_bylla(const void *lla, unsigned char lla_len, struct psref *psref)
2827 {
2828 	ifnet_t *ifp;
2829 	int s;
2830 
2831 	s = pserialize_read_enter();
2832 	IFNET_READER_FOREACH(ifp) {
2833 		if (if_is_deactivated(ifp))
2834 			continue;
2835 		if (ifp->if_addrlen != lla_len)
2836 			continue;
2837 		if (memcmp(lla, CLLADDR(ifp->if_sadl), lla_len) == 0) {
2838 			psref_acquire(psref, &ifp->if_psref,
2839 			    ifnet_psref_class);
2840 			break;
2841 		}
2842 	}
2843 	pserialize_read_exit(s);
2844 
2845 	return ifp;
2846 }
2847 
2848 /*
2849  * Note that it's safe only if the passed ifp is guaranteed to not be freed,
2850  * for example using pserialize or the ifp is already held or some other
2851  * object is held which guarantes the ifp to not be freed indirectly.
2852  */
2853 void
2854 if_acquire(struct ifnet *ifp, struct psref *psref)
2855 {
2856 
2857 	KASSERT(ifp->if_index != 0);
2858 	psref_acquire(psref, &ifp->if_psref, ifnet_psref_class);
2859 }
2860 
2861 bool
2862 if_held(struct ifnet *ifp)
2863 {
2864 
2865 	return psref_held(&ifp->if_psref, ifnet_psref_class);
2866 }
2867 
2868 /*
2869  * Some tunnel interfaces can nest, e.g. IPv4 over IPv4 gif(4) tunnel over IPv4.
2870  * Check the tunnel nesting count.
2871  * Return > 0, if tunnel nesting count is more than limit.
2872  * Return 0, if tunnel nesting count is equal or less than limit.
2873  */
2874 int
2875 if_tunnel_check_nesting(struct ifnet *ifp, struct mbuf *m, int limit)
2876 {
2877 	struct m_tag *mtag;
2878 	int *count;
2879 
2880 	mtag = m_tag_find(m, PACKET_TAG_TUNNEL_INFO);
2881 	if (mtag != NULL) {
2882 		count = (int *)(mtag + 1);
2883 		if (++(*count) > limit) {
2884 			log(LOG_NOTICE,
2885 			    "%s: recursively called too many times(%d)\n",
2886 			    ifp->if_xname, *count);
2887 			return EIO;
2888 		}
2889 	} else {
2890 		mtag = m_tag_get(PACKET_TAG_TUNNEL_INFO, sizeof(*count),
2891 		    M_NOWAIT);
2892 		if (mtag != NULL) {
2893 			m_tag_prepend(m, mtag);
2894 			count = (int *)(mtag + 1);
2895 			*count = 0;
2896 		} else {
2897 			log(LOG_DEBUG,
2898 			    "%s: m_tag_get() failed, recursion calls are not prevented.\n",
2899 			    ifp->if_xname);
2900 		}
2901 	}
2902 
2903 	return 0;
2904 }
2905 
2906 static void
2907 if_tunnel_ro_init_pc(void *p, void *arg __unused, struct cpu_info *ci __unused)
2908 {
2909 	struct tunnel_ro *tro = p;
2910 
2911 	tro->tr_ro = kmem_zalloc(sizeof(*tro->tr_ro), KM_SLEEP);
2912 	tro->tr_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
2913 }
2914 
2915 percpu_t *
2916 if_tunnel_alloc_ro_percpu(void)
2917 {
2918 	percpu_t *ro_percpu;
2919 
2920 	ro_percpu = percpu_alloc(sizeof(struct tunnel_ro));
2921 	percpu_foreach(ro_percpu, if_tunnel_ro_init_pc, NULL);
2922 
2923 	return ro_percpu;
2924 }
2925 
2926 static void
2927 if_tunnel_ro_fini_pc(void *p, void *arg __unused, struct cpu_info *ci __unused)
2928 {
2929 	struct tunnel_ro *tro = p;
2930 
2931 	rtcache_free(tro->tr_ro);
2932 	kmem_free(tro->tr_ro, sizeof(*tro->tr_ro));
2933 
2934 	mutex_obj_free(tro->tr_lock);
2935 }
2936 
2937 void
2938 if_tunnel_free_ro_percpu(percpu_t *ro_percpu)
2939 {
2940 
2941 	percpu_foreach(ro_percpu, if_tunnel_ro_fini_pc, NULL);
2942 	percpu_free(ro_percpu, sizeof(struct tunnel_ro));
2943 }
2944 
2945 
2946 static void
2947 if_tunnel_rtcache_free_pc(void *p, void *arg __unused, struct cpu_info *ci __unused)
2948 {
2949 	struct tunnel_ro *tro = p;
2950 
2951 	mutex_enter(tro->tr_lock);
2952 	rtcache_free(tro->tr_ro);
2953 	mutex_exit(tro->tr_lock);
2954 }
2955 
2956 void if_tunnel_ro_percpu_rtcache_free(percpu_t *ro_percpu)
2957 {
2958 
2959 	percpu_foreach(ro_percpu, if_tunnel_rtcache_free_pc, NULL);
2960 }
2961 
2962 
2963 /* common */
2964 int
2965 ifioctl_common(struct ifnet *ifp, u_long cmd, void *data)
2966 {
2967 	int s;
2968 	struct ifreq *ifr;
2969 	struct ifcapreq *ifcr;
2970 	struct ifdatareq *ifdr;
2971 	unsigned short flags;
2972 	char *descr;
2973 	int error;
2974 
2975 	switch (cmd) {
2976 	case SIOCSIFCAP:
2977 		ifcr = data;
2978 		if ((ifcr->ifcr_capenable & ~ifp->if_capabilities) != 0)
2979 			return EINVAL;
2980 
2981 		if (ifcr->ifcr_capenable == ifp->if_capenable)
2982 			return 0;
2983 
2984 		ifp->if_capenable = ifcr->ifcr_capenable;
2985 
2986 		/* Pre-compute the checksum flags mask. */
2987 		ifp->if_csum_flags_tx = 0;
2988 		ifp->if_csum_flags_rx = 0;
2989 		if (ifp->if_capenable & IFCAP_CSUM_IPv4_Tx)
2990 			ifp->if_csum_flags_tx |= M_CSUM_IPv4;
2991 		if (ifp->if_capenable & IFCAP_CSUM_IPv4_Rx)
2992 			ifp->if_csum_flags_rx |= M_CSUM_IPv4;
2993 
2994 		if (ifp->if_capenable & IFCAP_CSUM_TCPv4_Tx)
2995 			ifp->if_csum_flags_tx |= M_CSUM_TCPv4;
2996 		if (ifp->if_capenable & IFCAP_CSUM_TCPv4_Rx)
2997 			ifp->if_csum_flags_rx |= M_CSUM_TCPv4;
2998 
2999 		if (ifp->if_capenable & IFCAP_CSUM_UDPv4_Tx)
3000 			ifp->if_csum_flags_tx |= M_CSUM_UDPv4;
3001 		if (ifp->if_capenable & IFCAP_CSUM_UDPv4_Rx)
3002 			ifp->if_csum_flags_rx |= M_CSUM_UDPv4;
3003 
3004 		if (ifp->if_capenable & IFCAP_CSUM_TCPv6_Tx)
3005 			ifp->if_csum_flags_tx |= M_CSUM_TCPv6;
3006 		if (ifp->if_capenable & IFCAP_CSUM_TCPv6_Rx)
3007 			ifp->if_csum_flags_rx |= M_CSUM_TCPv6;
3008 
3009 		if (ifp->if_capenable & IFCAP_CSUM_UDPv6_Tx)
3010 			ifp->if_csum_flags_tx |= M_CSUM_UDPv6;
3011 		if (ifp->if_capenable & IFCAP_CSUM_UDPv6_Rx)
3012 			ifp->if_csum_flags_rx |= M_CSUM_UDPv6;
3013 
3014 		if (ifp->if_capenable & IFCAP_TSOv4)
3015 			ifp->if_csum_flags_tx |= M_CSUM_TSOv4;
3016 		if (ifp->if_capenable & IFCAP_TSOv6)
3017 			ifp->if_csum_flags_tx |= M_CSUM_TSOv6;
3018 
3019 #if NBRIDGE > 0
3020 		if (ifp->if_bridge != NULL)
3021 			bridge_calc_csum_flags(ifp->if_bridge);
3022 #endif
3023 
3024 		if (ifp->if_flags & IFF_UP)
3025 			return ENETRESET;
3026 		return 0;
3027 	case SIOCSIFFLAGS:
3028 		ifr = data;
3029 		/*
3030 		 * If if_is_mpsafe(ifp), KERNEL_LOCK isn't held here, but if_up
3031 		 * and if_down aren't MP-safe yet, so we must hold the lock.
3032 		 */
3033 		KERNEL_LOCK_IF_IFP_MPSAFE(ifp);
3034 		if (ifp->if_flags & IFF_UP && (ifr->ifr_flags & IFF_UP) == 0) {
3035 			s = splsoftnet();
3036 			if_down_locked(ifp);
3037 			splx(s);
3038 		}
3039 		if (ifr->ifr_flags & IFF_UP && (ifp->if_flags & IFF_UP) == 0) {
3040 			s = splsoftnet();
3041 			if_up_locked(ifp);
3042 			splx(s);
3043 		}
3044 		KERNEL_UNLOCK_IF_IFP_MPSAFE(ifp);
3045 		flags = (ifp->if_flags & IFF_CANTCHANGE) |
3046 		    (ifr->ifr_flags &~ IFF_CANTCHANGE);
3047 		if (ifp->if_flags != flags) {
3048 			ifp->if_flags = flags;
3049 			/* Notify that the flags have changed. */
3050 			rt_ifmsg(ifp);
3051 		}
3052 		break;
3053 	case SIOCGIFFLAGS:
3054 		ifr = data;
3055 		ifr->ifr_flags = ifp->if_flags;
3056 		break;
3057 
3058 	case SIOCGIFMETRIC:
3059 		ifr = data;
3060 		ifr->ifr_metric = ifp->if_metric;
3061 		break;
3062 
3063 	case SIOCGIFMTU:
3064 		ifr = data;
3065 		ifr->ifr_mtu = ifp->if_mtu;
3066 		break;
3067 
3068 	case SIOCGIFDLT:
3069 		ifr = data;
3070 		ifr->ifr_dlt = ifp->if_dlt;
3071 		break;
3072 
3073 	case SIOCGIFCAP:
3074 		ifcr = data;
3075 		ifcr->ifcr_capabilities = ifp->if_capabilities;
3076 		ifcr->ifcr_capenable = ifp->if_capenable;
3077 		break;
3078 
3079 	case SIOCSIFMETRIC:
3080 		ifr = data;
3081 		ifp->if_metric = ifr->ifr_metric;
3082 		break;
3083 
3084 	case SIOCGIFDATA:
3085 		ifdr = data;
3086 		ifdr->ifdr_data = ifp->if_data;
3087 		break;
3088 
3089 	case SIOCGIFINDEX:
3090 		ifr = data;
3091 		ifr->ifr_index = ifp->if_index;
3092 		break;
3093 
3094 	case SIOCZIFDATA:
3095 		ifdr = data;
3096 		ifdr->ifdr_data = ifp->if_data;
3097 		/*
3098 		 * Assumes that the volatile counters that can be
3099 		 * zero'ed are at the end of if_data.
3100 		 */
3101 		memset(&ifp->if_data.ifi_ipackets, 0, sizeof(ifp->if_data) -
3102 		    offsetof(struct if_data, ifi_ipackets));
3103 		/*
3104 		 * The memset() clears to the bottm of if_data. In the area,
3105 		 * if_lastchange is included. Please be careful if new entry
3106 		 * will be added into if_data or rewite this.
3107 		 *
3108 		 * And also, update if_lastchnage.
3109 		 */
3110 		getnanotime(&ifp->if_lastchange);
3111 		break;
3112 	case SIOCSIFMTU:
3113 		ifr = data;
3114 		if (ifp->if_mtu == ifr->ifr_mtu)
3115 			break;
3116 		ifp->if_mtu = ifr->ifr_mtu;
3117 		/*
3118 		 * If the link MTU changed, do network layer specific procedure.
3119 		 */
3120 #ifdef INET6
3121 		KERNEL_LOCK_UNLESS_NET_MPSAFE();
3122 		if (in6_present)
3123 			nd6_setmtu(ifp);
3124 		KERNEL_UNLOCK_UNLESS_NET_MPSAFE();
3125 #endif
3126 		return ENETRESET;
3127 	case SIOCSIFDESCR:
3128 		error = kauth_authorize_network(curlwp->l_cred,
3129 		    KAUTH_NETWORK_INTERFACE,
3130 		    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp, KAUTH_ARG(cmd),
3131 		    NULL);
3132 		if (error)
3133 			return error;
3134 
3135 		ifr = data;
3136 
3137 		if (ifr->ifr_buflen > IFDESCRSIZE)
3138 			return ENAMETOOLONG;
3139 
3140 		if (ifr->ifr_buf == NULL || ifr->ifr_buflen == 0) {
3141 			/* unset description */
3142 			descr = NULL;
3143 		} else {
3144 			descr = kmem_zalloc(IFDESCRSIZE, KM_SLEEP);
3145 			/*
3146 			 * copy (IFDESCRSIZE - 1) bytes to ensure
3147 			 * terminating nul
3148 			 */
3149 			error = copyin(ifr->ifr_buf, descr, IFDESCRSIZE - 1);
3150 			if (error) {
3151 				kmem_free(descr, IFDESCRSIZE);
3152 				return error;
3153 			}
3154 		}
3155 
3156 		if (ifp->if_description != NULL)
3157 			kmem_free(ifp->if_description, IFDESCRSIZE);
3158 
3159 		ifp->if_description = descr;
3160 		break;
3161 
3162  	case SIOCGIFDESCR:
3163 		ifr = data;
3164 		descr = ifp->if_description;
3165 
3166 		if (descr == NULL)
3167 			return ENOMSG;
3168 
3169 		if (ifr->ifr_buflen < IFDESCRSIZE)
3170 			return EINVAL;
3171 
3172 		error = copyout(descr, ifr->ifr_buf, IFDESCRSIZE);
3173 		if (error)
3174 			return error;
3175  		break;
3176 
3177 	default:
3178 		return ENOTTY;
3179 	}
3180 	return 0;
3181 }
3182 
3183 int
3184 ifaddrpref_ioctl(struct socket *so, u_long cmd, void *data, struct ifnet *ifp)
3185 {
3186 	struct if_addrprefreq *ifap = (struct if_addrprefreq *)data;
3187 	struct ifaddr *ifa;
3188 	const struct sockaddr *any, *sa;
3189 	union {
3190 		struct sockaddr sa;
3191 		struct sockaddr_storage ss;
3192 	} u, v;
3193 	int s, error = 0;
3194 
3195 	switch (cmd) {
3196 	case SIOCSIFADDRPREF:
3197 		error = kauth_authorize_network(curlwp->l_cred,
3198 		    KAUTH_NETWORK_INTERFACE,
3199 		    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp, KAUTH_ARG(cmd),
3200 		    NULL);
3201 		if (error)
3202 			return error;
3203 		break;
3204 	case SIOCGIFADDRPREF:
3205 		break;
3206 	default:
3207 		return EOPNOTSUPP;
3208 	}
3209 
3210 	/* sanity checks */
3211 	if (data == NULL || ifp == NULL) {
3212 		panic("invalid argument to %s", __func__);
3213 		/*NOTREACHED*/
3214 	}
3215 
3216 	/* address must be specified on ADD and DELETE */
3217 	sa = sstocsa(&ifap->ifap_addr);
3218 	if (sa->sa_family != sofamily(so))
3219 		return EINVAL;
3220 	if ((any = sockaddr_any(sa)) == NULL || sa->sa_len != any->sa_len)
3221 		return EINVAL;
3222 
3223 	sockaddr_externalize(&v.sa, sizeof(v.ss), sa);
3224 
3225 	s = pserialize_read_enter();
3226 	IFADDR_READER_FOREACH(ifa, ifp) {
3227 		if (ifa->ifa_addr->sa_family != sa->sa_family)
3228 			continue;
3229 		sockaddr_externalize(&u.sa, sizeof(u.ss), ifa->ifa_addr);
3230 		if (sockaddr_cmp(&u.sa, &v.sa) == 0)
3231 			break;
3232 	}
3233 	if (ifa == NULL) {
3234 		error = EADDRNOTAVAIL;
3235 		goto out;
3236 	}
3237 
3238 	switch (cmd) {
3239 	case SIOCSIFADDRPREF:
3240 		ifa->ifa_preference = ifap->ifap_preference;
3241 		goto out;
3242 	case SIOCGIFADDRPREF:
3243 		/* fill in the if_laddrreq structure */
3244 		(void)sockaddr_copy(sstosa(&ifap->ifap_addr),
3245 		    sizeof(ifap->ifap_addr), ifa->ifa_addr);
3246 		ifap->ifap_preference = ifa->ifa_preference;
3247 		goto out;
3248 	default:
3249 		error = EOPNOTSUPP;
3250 	}
3251 out:
3252 	pserialize_read_exit(s);
3253 	return error;
3254 }
3255 
3256 /*
3257  * Interface ioctls.
3258  */
3259 static int
3260 doifioctl(struct socket *so, u_long cmd, void *data, struct lwp *l)
3261 {
3262 	struct ifnet *ifp;
3263 	struct ifreq *ifr;
3264 	int error = 0;
3265 	u_long ocmd = cmd;
3266 	u_short oif_flags;
3267 	struct ifreq ifrb;
3268 	struct oifreq *oifr = NULL;
3269 	int r;
3270 	struct psref psref;
3271 	int bound;
3272 	bool do_if43_post = false;
3273 	bool do_ifm80_post = false;
3274 
3275 	switch (cmd) {
3276 	case SIOCGIFCONF:
3277 		return ifconf(cmd, data);
3278 	case SIOCINITIFADDR:
3279 		return EPERM;
3280 	default:
3281 		MODULE_HOOK_CALL(uipc_syscalls_40_hook, (cmd, data), enosys(),
3282 		    error);
3283 		if (error != ENOSYS)
3284 			return error;
3285 		MODULE_HOOK_CALL(uipc_syscalls_50_hook, (l, cmd, data),
3286 		    enosys(), error);
3287 		if (error != ENOSYS)
3288 			return error;
3289 		error = 0;
3290 		break;
3291 	}
3292 
3293 	ifr = data;
3294 	/* Pre-conversion */
3295 	MODULE_HOOK_CALL(if_cvtcmd_43_hook, (&cmd, ocmd), enosys(), error);
3296 	if (cmd != ocmd) {
3297 		oifr = data;
3298 		data = ifr = &ifrb;
3299 		IFREQO2N_43(oifr, ifr);
3300 		do_if43_post = true;
3301 	}
3302 	MODULE_HOOK_CALL(ifmedia_80_pre_hook, (ifr, &cmd, &do_ifm80_post),
3303 	    enosys(), error);
3304 
3305 	switch (cmd) {
3306 	case SIOCIFCREATE:
3307 	case SIOCIFDESTROY:
3308 		bound = curlwp_bind();
3309 		if (l != NULL) {
3310 			ifp = if_get(ifr->ifr_name, &psref);
3311 			error = kauth_authorize_network(l->l_cred,
3312 			    KAUTH_NETWORK_INTERFACE,
3313 			    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp,
3314 			    KAUTH_ARG(cmd), NULL);
3315 			if (ifp != NULL)
3316 				if_put(ifp, &psref);
3317 			if (error != 0) {
3318 				curlwp_bindx(bound);
3319 				return error;
3320 			}
3321 		}
3322 		KERNEL_LOCK_UNLESS_NET_MPSAFE();
3323 		mutex_enter(&if_clone_mtx);
3324 		r = (cmd == SIOCIFCREATE) ?
3325 			if_clone_create(ifr->ifr_name) :
3326 			if_clone_destroy(ifr->ifr_name);
3327 		mutex_exit(&if_clone_mtx);
3328 		KERNEL_UNLOCK_UNLESS_NET_MPSAFE();
3329 		curlwp_bindx(bound);
3330 		return r;
3331 
3332 	case SIOCIFGCLONERS:
3333 		{
3334 			struct if_clonereq *req = (struct if_clonereq *)data;
3335 			return if_clone_list(req->ifcr_count, req->ifcr_buffer,
3336 			    &req->ifcr_total);
3337 		}
3338 	}
3339 
3340 	bound = curlwp_bind();
3341 	ifp = if_get(ifr->ifr_name, &psref);
3342 	if (ifp == NULL) {
3343 		curlwp_bindx(bound);
3344 		return ENXIO;
3345 	}
3346 
3347 	switch (cmd) {
3348 	case SIOCALIFADDR:
3349 	case SIOCDLIFADDR:
3350 	case SIOCSIFADDRPREF:
3351 	case SIOCSIFFLAGS:
3352 	case SIOCSIFCAP:
3353 	case SIOCSIFMETRIC:
3354 	case SIOCZIFDATA:
3355 	case SIOCSIFMTU:
3356 	case SIOCSIFPHYADDR:
3357 	case SIOCDIFPHYADDR:
3358 #ifdef INET6
3359 	case SIOCSIFPHYADDR_IN6:
3360 #endif
3361 	case SIOCSLIFPHYADDR:
3362 	case SIOCADDMULTI:
3363 	case SIOCDELMULTI:
3364 	case SIOCSETHERCAP:
3365 	case SIOCSIFMEDIA:
3366 	case SIOCSDRVSPEC:
3367 	case SIOCG80211:
3368 	case SIOCS80211:
3369 	case SIOCS80211NWID:
3370 	case SIOCS80211NWKEY:
3371 	case SIOCS80211POWER:
3372 	case SIOCS80211BSSID:
3373 	case SIOCS80211CHANNEL:
3374 	case SIOCSLINKSTR:
3375 		if (l != NULL) {
3376 			error = kauth_authorize_network(l->l_cred,
3377 			    KAUTH_NETWORK_INTERFACE,
3378 			    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp,
3379 			    KAUTH_ARG(cmd), NULL);
3380 			if (error != 0)
3381 				goto out;
3382 		}
3383 	}
3384 
3385 	oif_flags = ifp->if_flags;
3386 
3387 	KERNEL_LOCK_UNLESS_IFP_MPSAFE(ifp);
3388 	IFNET_LOCK(ifp);
3389 
3390 	error = (*ifp->if_ioctl)(ifp, cmd, data);
3391 	if (error != ENOTTY)
3392 		;
3393 	else if (so->so_proto == NULL)
3394 		error = EOPNOTSUPP;
3395 	else {
3396 		KERNEL_LOCK_IF_IFP_MPSAFE(ifp);
3397 		MODULE_HOOK_CALL(if_ifioctl_43_hook,
3398 			     (so, ocmd, cmd, data, l), enosys(), error);
3399 		if (error == ENOSYS)
3400 			error = (*so->so_proto->pr_usrreqs->pr_ioctl)(so,
3401 			    cmd, data, ifp);
3402 		KERNEL_UNLOCK_IF_IFP_MPSAFE(ifp);
3403 	}
3404 
3405 	if (((oif_flags ^ ifp->if_flags) & IFF_UP) != 0) {
3406 		if ((ifp->if_flags & IFF_UP) != 0) {
3407 			int s = splsoftnet();
3408 			if_up_locked(ifp);
3409 			splx(s);
3410 		}
3411 	}
3412 
3413 	/* Post-conversion */
3414 	if (do_ifm80_post && (error == 0))
3415 		MODULE_HOOK_CALL(ifmedia_80_post_hook, (ifr, cmd),
3416 		    enosys(), error);
3417 	if (do_if43_post)
3418 		IFREQN2O_43(oifr, ifr);
3419 
3420 	IFNET_UNLOCK(ifp);
3421 	KERNEL_UNLOCK_UNLESS_IFP_MPSAFE(ifp);
3422 out:
3423 	if_put(ifp, &psref);
3424 	curlwp_bindx(bound);
3425 	return error;
3426 }
3427 
3428 /*
3429  * Return interface configuration
3430  * of system.  List may be used
3431  * in later ioctl's (above) to get
3432  * other information.
3433  *
3434  * Each record is a struct ifreq.  Before the addition of
3435  * sockaddr_storage, the API rule was that sockaddr flavors that did
3436  * not fit would extend beyond the struct ifreq, with the next struct
3437  * ifreq starting sa_len beyond the struct sockaddr.  Because the
3438  * union in struct ifreq includes struct sockaddr_storage, every kind
3439  * of sockaddr must fit.  Thus, there are no longer any overlength
3440  * records.
3441  *
3442  * Records are added to the user buffer if they fit, and ifc_len is
3443  * adjusted to the length that was written.  Thus, the user is only
3444  * assured of getting the complete list if ifc_len on return is at
3445  * least sizeof(struct ifreq) less than it was on entry.
3446  *
3447  * If the user buffer pointer is NULL, this routine copies no data and
3448  * returns the amount of space that would be needed.
3449  *
3450  * Invariants:
3451  * ifrp points to the next part of the user's buffer to be used.  If
3452  * ifrp != NULL, space holds the number of bytes remaining that we may
3453  * write at ifrp.  Otherwise, space holds the number of bytes that
3454  * would have been written had there been adequate space.
3455  */
3456 /*ARGSUSED*/
3457 static int
3458 ifconf(u_long cmd, void *data)
3459 {
3460 	struct ifconf *ifc = (struct ifconf *)data;
3461 	struct ifnet *ifp;
3462 	struct ifaddr *ifa;
3463 	struct ifreq ifr, *ifrp = NULL;
3464 	int space = 0, error = 0;
3465 	const int sz = (int)sizeof(struct ifreq);
3466 	const bool docopy = ifc->ifc_req != NULL;
3467 	int s;
3468 	int bound;
3469 	struct psref psref;
3470 
3471 	memset(&ifr, 0, sizeof(ifr));
3472 	if (docopy) {
3473 		space = ifc->ifc_len;
3474 		ifrp = ifc->ifc_req;
3475 	}
3476 
3477 	bound = curlwp_bind();
3478 	s = pserialize_read_enter();
3479 	IFNET_READER_FOREACH(ifp) {
3480 		psref_acquire(&psref, &ifp->if_psref, ifnet_psref_class);
3481 		pserialize_read_exit(s);
3482 
3483 		(void)strncpy(ifr.ifr_name, ifp->if_xname,
3484 		    sizeof(ifr.ifr_name));
3485 		if (ifr.ifr_name[sizeof(ifr.ifr_name) - 1] != '\0') {
3486 			error = ENAMETOOLONG;
3487 			goto release_exit;
3488 		}
3489 		if (IFADDR_READER_EMPTY(ifp)) {
3490 			/* Interface with no addresses - send zero sockaddr. */
3491 			memset(&ifr.ifr_addr, 0, sizeof(ifr.ifr_addr));
3492 			if (!docopy) {
3493 				space += sz;
3494 				goto next;
3495 			}
3496 			if (space >= sz) {
3497 				error = copyout(&ifr, ifrp, sz);
3498 				if (error != 0)
3499 					goto release_exit;
3500 				ifrp++;
3501 				space -= sz;
3502 			}
3503 		}
3504 
3505 		s = pserialize_read_enter();
3506 		IFADDR_READER_FOREACH(ifa, ifp) {
3507 			struct sockaddr *sa = ifa->ifa_addr;
3508 			/* all sockaddrs must fit in sockaddr_storage */
3509 			KASSERT(sa->sa_len <= sizeof(ifr.ifr_ifru));
3510 
3511 			if (!docopy) {
3512 				space += sz;
3513 				continue;
3514 			}
3515 			memcpy(&ifr.ifr_space, sa, sa->sa_len);
3516 			pserialize_read_exit(s);
3517 
3518 			if (space >= sz) {
3519 				error = copyout(&ifr, ifrp, sz);
3520 				if (error != 0)
3521 					goto release_exit;
3522 				ifrp++; space -= sz;
3523 			}
3524 			s = pserialize_read_enter();
3525 		}
3526 		pserialize_read_exit(s);
3527 
3528         next:
3529 		s = pserialize_read_enter();
3530 		psref_release(&psref, &ifp->if_psref, ifnet_psref_class);
3531 	}
3532 	pserialize_read_exit(s);
3533 	curlwp_bindx(bound);
3534 
3535 	if (docopy) {
3536 		KASSERT(0 <= space && space <= ifc->ifc_len);
3537 		ifc->ifc_len -= space;
3538 	} else {
3539 		KASSERT(space >= 0);
3540 		ifc->ifc_len = space;
3541 	}
3542 	return (0);
3543 
3544 release_exit:
3545 	psref_release(&psref, &ifp->if_psref, ifnet_psref_class);
3546 	curlwp_bindx(bound);
3547 	return error;
3548 }
3549 
3550 int
3551 ifreq_setaddr(u_long cmd, struct ifreq *ifr, const struct sockaddr *sa)
3552 {
3553 	uint8_t len = sizeof(ifr->ifr_ifru.ifru_space);
3554 	struct ifreq ifrb;
3555 	struct oifreq *oifr = NULL;
3556 	u_long ocmd = cmd;
3557 	int hook;
3558 
3559 	MODULE_HOOK_CALL(if_cvtcmd_43_hook, (&cmd, ocmd), enosys(), hook);
3560 	if (hook != ENOSYS) {
3561 		if (cmd != ocmd) {
3562 			oifr = (struct oifreq *)(void *)ifr;
3563 			ifr = &ifrb;
3564 			IFREQO2N_43(oifr, ifr);
3565 				len = sizeof(oifr->ifr_addr);
3566 		}
3567 	}
3568 
3569 	if (len < sa->sa_len)
3570 		return EFBIG;
3571 
3572 	memset(&ifr->ifr_addr, 0, len);
3573 	sockaddr_copy(&ifr->ifr_addr, len, sa);
3574 
3575 	if (cmd != ocmd)
3576 		IFREQN2O_43(oifr, ifr);
3577 	return 0;
3578 }
3579 
3580 /*
3581  * wrapper function for the drivers which doesn't have if_transmit().
3582  */
3583 static int
3584 if_transmit(struct ifnet *ifp, struct mbuf *m)
3585 {
3586 	int s, error;
3587 	size_t pktlen = m->m_pkthdr.len;
3588 	bool mcast = (m->m_flags & M_MCAST) != 0;
3589 
3590 	s = splnet();
3591 
3592 	IFQ_ENQUEUE(&ifp->if_snd, m, error);
3593 	if (error != 0) {
3594 		/* mbuf is already freed */
3595 		goto out;
3596 	}
3597 
3598 	ifp->if_obytes += pktlen;
3599 	if (mcast)
3600 		ifp->if_omcasts++;
3601 
3602 	if ((ifp->if_flags & IFF_OACTIVE) == 0)
3603 		if_start_lock(ifp);
3604 out:
3605 	splx(s);
3606 
3607 	return error;
3608 }
3609 
3610 int
3611 if_transmit_lock(struct ifnet *ifp, struct mbuf *m)
3612 {
3613 	int error;
3614 
3615 	kmsan_check_mbuf(m);
3616 
3617 #ifdef ALTQ
3618 	KERNEL_LOCK(1, NULL);
3619 	if (ALTQ_IS_ENABLED(&ifp->if_snd)) {
3620 		error = if_transmit(ifp, m);
3621 		KERNEL_UNLOCK_ONE(NULL);
3622 	} else {
3623 		KERNEL_UNLOCK_ONE(NULL);
3624 		error = (*ifp->if_transmit)(ifp, m);
3625 		/* mbuf is alredy freed */
3626 	}
3627 #else /* !ALTQ */
3628 	error = (*ifp->if_transmit)(ifp, m);
3629 	/* mbuf is alredy freed */
3630 #endif /* !ALTQ */
3631 
3632 	return error;
3633 }
3634 
3635 /*
3636  * Queue message on interface, and start output if interface
3637  * not yet active.
3638  */
3639 int
3640 ifq_enqueue(struct ifnet *ifp, struct mbuf *m)
3641 {
3642 
3643 	return if_transmit_lock(ifp, m);
3644 }
3645 
3646 /*
3647  * Queue message on interface, possibly using a second fast queue
3648  */
3649 int
3650 ifq_enqueue2(struct ifnet *ifp, struct ifqueue *ifq, struct mbuf *m)
3651 {
3652 	int error = 0;
3653 
3654 	if (ifq != NULL
3655 #ifdef ALTQ
3656 	    && ALTQ_IS_ENABLED(&ifp->if_snd) == 0
3657 #endif
3658 	    ) {
3659 		if (IF_QFULL(ifq)) {
3660 			IF_DROP(&ifp->if_snd);
3661 			m_freem(m);
3662 			if (error == 0)
3663 				error = ENOBUFS;
3664 		} else
3665 			IF_ENQUEUE(ifq, m);
3666 	} else
3667 		IFQ_ENQUEUE(&ifp->if_snd, m, error);
3668 	if (error != 0) {
3669 		++ifp->if_oerrors;
3670 		return error;
3671 	}
3672 	return 0;
3673 }
3674 
3675 int
3676 if_addr_init(ifnet_t *ifp, struct ifaddr *ifa, const bool src)
3677 {
3678 	int rc;
3679 
3680 	KASSERT(IFNET_LOCKED(ifp));
3681 	if (ifp->if_initaddr != NULL)
3682 		rc = (*ifp->if_initaddr)(ifp, ifa, src);
3683 	else if (src ||
3684 	         (rc = (*ifp->if_ioctl)(ifp, SIOCSIFDSTADDR, ifa)) == ENOTTY)
3685 		rc = (*ifp->if_ioctl)(ifp, SIOCINITIFADDR, ifa);
3686 
3687 	return rc;
3688 }
3689 
3690 int
3691 if_do_dad(struct ifnet *ifp)
3692 {
3693 	if ((ifp->if_flags & IFF_LOOPBACK) != 0)
3694 		return 0;
3695 
3696 	switch (ifp->if_type) {
3697 	case IFT_FAITH:
3698 		/*
3699 		 * These interfaces do not have the IFF_LOOPBACK flag,
3700 		 * but loop packets back.  We do not have to do DAD on such
3701 		 * interfaces.  We should even omit it, because loop-backed
3702 		 * responses would confuse the DAD procedure.
3703 		 */
3704 		return 0;
3705 	default:
3706 		/*
3707 		 * Our DAD routine requires the interface up and running.
3708 		 * However, some interfaces can be up before the RUNNING
3709 		 * status.  Additionaly, users may try to assign addresses
3710 		 * before the interface becomes up (or running).
3711 		 * We simply skip DAD in such a case as a work around.
3712 		 * XXX: we should rather mark "tentative" on such addresses,
3713 		 * and do DAD after the interface becomes ready.
3714 		 */
3715 		if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) !=
3716 		    (IFF_UP | IFF_RUNNING))
3717 			return 0;
3718 
3719 		return 1;
3720 	}
3721 }
3722 
3723 int
3724 if_flags_set(ifnet_t *ifp, const u_short flags)
3725 {
3726 	int rc;
3727 
3728 	KASSERT(IFNET_LOCKED(ifp));
3729 
3730 	if (ifp->if_setflags != NULL)
3731 		rc = (*ifp->if_setflags)(ifp, flags);
3732 	else {
3733 		u_short cantflags, chgdflags;
3734 		struct ifreq ifr;
3735 
3736 		chgdflags = ifp->if_flags ^ flags;
3737 		cantflags = chgdflags & IFF_CANTCHANGE;
3738 
3739 		if (cantflags != 0)
3740 			ifp->if_flags ^= cantflags;
3741 
3742                 /* Traditionally, we do not call if_ioctl after
3743                  * setting/clearing only IFF_PROMISC if the interface
3744                  * isn't IFF_UP.  Uphold that tradition.
3745 		 */
3746 		if (chgdflags == IFF_PROMISC && (ifp->if_flags & IFF_UP) == 0)
3747 			return 0;
3748 
3749 		memset(&ifr, 0, sizeof(ifr));
3750 
3751 		ifr.ifr_flags = flags & ~IFF_CANTCHANGE;
3752 		rc = (*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, &ifr);
3753 
3754 		if (rc != 0 && cantflags != 0)
3755 			ifp->if_flags ^= cantflags;
3756 	}
3757 
3758 	return rc;
3759 }
3760 
3761 int
3762 if_mcast_op(ifnet_t *ifp, const unsigned long cmd, const struct sockaddr *sa)
3763 {
3764 	int rc;
3765 	struct ifreq ifr;
3766 
3767 	if (ifp->if_mcastop != NULL)
3768 		rc = (*ifp->if_mcastop)(ifp, cmd, sa);
3769 	else {
3770 		ifreq_setaddr(cmd, &ifr, sa);
3771 		rc = (*ifp->if_ioctl)(ifp, cmd, &ifr);
3772 	}
3773 
3774 	return rc;
3775 }
3776 
3777 static void
3778 sysctl_sndq_setup(struct sysctllog **clog, const char *ifname,
3779     struct ifaltq *ifq)
3780 {
3781 	const struct sysctlnode *cnode, *rnode;
3782 
3783 	if (sysctl_createv(clog, 0, NULL, &rnode,
3784 		       CTLFLAG_PERMANENT,
3785 		       CTLTYPE_NODE, "interfaces",
3786 		       SYSCTL_DESCR("Per-interface controls"),
3787 		       NULL, 0, NULL, 0,
3788 		       CTL_NET, CTL_CREATE, CTL_EOL) != 0)
3789 		goto bad;
3790 
3791 	if (sysctl_createv(clog, 0, &rnode, &rnode,
3792 		       CTLFLAG_PERMANENT,
3793 		       CTLTYPE_NODE, ifname,
3794 		       SYSCTL_DESCR("Interface controls"),
3795 		       NULL, 0, NULL, 0,
3796 		       CTL_CREATE, CTL_EOL) != 0)
3797 		goto bad;
3798 
3799 	if (sysctl_createv(clog, 0, &rnode, &rnode,
3800 		       CTLFLAG_PERMANENT,
3801 		       CTLTYPE_NODE, "sndq",
3802 		       SYSCTL_DESCR("Interface output queue controls"),
3803 		       NULL, 0, NULL, 0,
3804 		       CTL_CREATE, CTL_EOL) != 0)
3805 		goto bad;
3806 
3807 	if (sysctl_createv(clog, 0, &rnode, &cnode,
3808 		       CTLFLAG_PERMANENT,
3809 		       CTLTYPE_INT, "len",
3810 		       SYSCTL_DESCR("Current output queue length"),
3811 		       NULL, 0, &ifq->ifq_len, 0,
3812 		       CTL_CREATE, CTL_EOL) != 0)
3813 		goto bad;
3814 
3815 	if (sysctl_createv(clog, 0, &rnode, &cnode,
3816 		       CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
3817 		       CTLTYPE_INT, "maxlen",
3818 		       SYSCTL_DESCR("Maximum allowed output queue length"),
3819 		       NULL, 0, &ifq->ifq_maxlen, 0,
3820 		       CTL_CREATE, CTL_EOL) != 0)
3821 		goto bad;
3822 
3823 	if (sysctl_createv(clog, 0, &rnode, &cnode,
3824 		       CTLFLAG_PERMANENT,
3825 		       CTLTYPE_INT, "drops",
3826 		       SYSCTL_DESCR("Packets dropped due to full output queue"),
3827 		       NULL, 0, &ifq->ifq_drops, 0,
3828 		       CTL_CREATE, CTL_EOL) != 0)
3829 		goto bad;
3830 
3831 	return;
3832 bad:
3833 	printf("%s: could not attach sysctl nodes\n", ifname);
3834 	return;
3835 }
3836 
3837 #if defined(INET) || defined(INET6)
3838 
3839 #define	SYSCTL_NET_PKTQ(q, cn, c)					\
3840 	static int							\
3841 	sysctl_net_##q##_##cn(SYSCTLFN_ARGS)				\
3842 	{								\
3843 		return sysctl_pktq_count(SYSCTLFN_CALL(rnode), q, c);	\
3844 	}
3845 
3846 #if defined(INET)
3847 static int
3848 sysctl_net_ip_pktq_maxlen(SYSCTLFN_ARGS)
3849 {
3850 	return sysctl_pktq_maxlen(SYSCTLFN_CALL(rnode), ip_pktq);
3851 }
3852 SYSCTL_NET_PKTQ(ip_pktq, items, PKTQ_NITEMS)
3853 SYSCTL_NET_PKTQ(ip_pktq, drops, PKTQ_DROPS)
3854 #endif
3855 
3856 #if defined(INET6)
3857 static int
3858 sysctl_net_ip6_pktq_maxlen(SYSCTLFN_ARGS)
3859 {
3860 	return sysctl_pktq_maxlen(SYSCTLFN_CALL(rnode), ip6_pktq);
3861 }
3862 SYSCTL_NET_PKTQ(ip6_pktq, items, PKTQ_NITEMS)
3863 SYSCTL_NET_PKTQ(ip6_pktq, drops, PKTQ_DROPS)
3864 #endif
3865 
3866 static void
3867 sysctl_net_pktq_setup(struct sysctllog **clog, int pf)
3868 {
3869 	sysctlfn len_func = NULL, maxlen_func = NULL, drops_func = NULL;
3870 	const char *pfname = NULL, *ipname = NULL;
3871 	int ipn = 0, qid = 0;
3872 
3873 	switch (pf) {
3874 #if defined(INET)
3875 	case PF_INET:
3876 		len_func = sysctl_net_ip_pktq_items;
3877 		maxlen_func = sysctl_net_ip_pktq_maxlen;
3878 		drops_func = sysctl_net_ip_pktq_drops;
3879 		pfname = "inet", ipn = IPPROTO_IP;
3880 		ipname = "ip", qid = IPCTL_IFQ;
3881 		break;
3882 #endif
3883 #if defined(INET6)
3884 	case PF_INET6:
3885 		len_func = sysctl_net_ip6_pktq_items;
3886 		maxlen_func = sysctl_net_ip6_pktq_maxlen;
3887 		drops_func = sysctl_net_ip6_pktq_drops;
3888 		pfname = "inet6", ipn = IPPROTO_IPV6;
3889 		ipname = "ip6", qid = IPV6CTL_IFQ;
3890 		break;
3891 #endif
3892 	default:
3893 		KASSERT(false);
3894 	}
3895 
3896 	sysctl_createv(clog, 0, NULL, NULL,
3897 		       CTLFLAG_PERMANENT,
3898 		       CTLTYPE_NODE, pfname, NULL,
3899 		       NULL, 0, NULL, 0,
3900 		       CTL_NET, pf, CTL_EOL);
3901 	sysctl_createv(clog, 0, NULL, NULL,
3902 		       CTLFLAG_PERMANENT,
3903 		       CTLTYPE_NODE, ipname, NULL,
3904 		       NULL, 0, NULL, 0,
3905 		       CTL_NET, pf, ipn, CTL_EOL);
3906 	sysctl_createv(clog, 0, NULL, NULL,
3907 		       CTLFLAG_PERMANENT,
3908 		       CTLTYPE_NODE, "ifq",
3909 		       SYSCTL_DESCR("Protocol input queue controls"),
3910 		       NULL, 0, NULL, 0,
3911 		       CTL_NET, pf, ipn, qid, CTL_EOL);
3912 
3913 	sysctl_createv(clog, 0, NULL, NULL,
3914 		       CTLFLAG_PERMANENT,
3915 		       CTLTYPE_QUAD, "len",
3916 		       SYSCTL_DESCR("Current input queue length"),
3917 		       len_func, 0, NULL, 0,
3918 		       CTL_NET, pf, ipn, qid, IFQCTL_LEN, CTL_EOL);
3919 	sysctl_createv(clog, 0, NULL, NULL,
3920 		       CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
3921 		       CTLTYPE_INT, "maxlen",
3922 		       SYSCTL_DESCR("Maximum allowed input queue length"),
3923 		       maxlen_func, 0, NULL, 0,
3924 		       CTL_NET, pf, ipn, qid, IFQCTL_MAXLEN, CTL_EOL);
3925 	sysctl_createv(clog, 0, NULL, NULL,
3926 		       CTLFLAG_PERMANENT,
3927 		       CTLTYPE_QUAD, "drops",
3928 		       SYSCTL_DESCR("Packets dropped due to full input queue"),
3929 		       drops_func, 0, NULL, 0,
3930 		       CTL_NET, pf, ipn, qid, IFQCTL_DROPS, CTL_EOL);
3931 }
3932 #endif /* INET || INET6 */
3933 
3934 static int
3935 if_sdl_sysctl(SYSCTLFN_ARGS)
3936 {
3937 	struct ifnet *ifp;
3938 	const struct sockaddr_dl *sdl;
3939 	struct psref psref;
3940 	int error = 0;
3941 	int bound;
3942 
3943 	if (namelen != 1)
3944 		return EINVAL;
3945 
3946 	bound = curlwp_bind();
3947 	ifp = if_get_byindex(name[0], &psref);
3948 	if (ifp == NULL) {
3949 		error = ENODEV;
3950 		goto out0;
3951 	}
3952 
3953 	sdl = ifp->if_sadl;
3954 	if (sdl == NULL) {
3955 		*oldlenp = 0;
3956 		goto out1;
3957 	}
3958 
3959 	if (oldp == NULL) {
3960 		*oldlenp = sdl->sdl_alen;
3961 		goto out1;
3962 	}
3963 
3964 	if (*oldlenp >= sdl->sdl_alen)
3965 		*oldlenp = sdl->sdl_alen;
3966 	error = sysctl_copyout(l, &sdl->sdl_data[sdl->sdl_nlen], oldp, *oldlenp);
3967 out1:
3968 	if_put(ifp, &psref);
3969 out0:
3970 	curlwp_bindx(bound);
3971 	return error;
3972 }
3973 
3974 static void
3975 if_sysctl_setup(struct sysctllog **clog)
3976 {
3977 	const struct sysctlnode *rnode = NULL;
3978 
3979 	sysctl_createv(clog, 0, NULL, &rnode,
3980 		       CTLFLAG_PERMANENT,
3981 		       CTLTYPE_NODE, "sdl",
3982 		       SYSCTL_DESCR("Get active link-layer address"),
3983 		       if_sdl_sysctl, 0, NULL, 0,
3984 		       CTL_NET, CTL_CREATE, CTL_EOL);
3985 
3986 #if defined(INET)
3987 	sysctl_net_pktq_setup(NULL, PF_INET);
3988 #endif
3989 #ifdef INET6
3990 	if (in6_present)
3991 		sysctl_net_pktq_setup(NULL, PF_INET6);
3992 #endif
3993 }
3994