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