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