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