xref: /netbsd-src/sys/net/if.c (revision 2c6fc41c810f5088457889d00eba558e8bc74d9e)
1 /*	$NetBSD: if.c,v 1.275 2014/05/18 14:46:16 rmind 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.275 2014/05/18 14:46:16 rmind Exp $");
94 
95 #include "opt_inet.h"
96 
97 #include "opt_atalk.h"
98 #include "opt_natm.h"
99 
100 #include <sys/param.h>
101 #include <sys/mbuf.h>
102 #include <sys/systm.h>
103 #include <sys/callout.h>
104 #include <sys/proc.h>
105 #include <sys/socket.h>
106 #include <sys/socketvar.h>
107 #include <sys/domain.h>
108 #include <sys/protosw.h>
109 #include <sys/kernel.h>
110 #include <sys/ioctl.h>
111 #include <sys/sysctl.h>
112 #include <sys/syslog.h>
113 #include <sys/kauth.h>
114 #include <sys/kmem.h>
115 
116 #include <net/if.h>
117 #include <net/if_dl.h>
118 #include <net/if_ether.h>
119 #include <net/if_media.h>
120 #include <net80211/ieee80211.h>
121 #include <net80211/ieee80211_ioctl.h>
122 #include <net/if_types.h>
123 #include <net/radix.h>
124 #include <net/route.h>
125 #include <net/netisr.h>
126 #include <sys/module.h>
127 #ifdef NETATALK
128 #include <netatalk/at_extern.h>
129 #include <netatalk/at.h>
130 #endif
131 #include <net/pfil.h>
132 
133 #ifdef INET6
134 #include <netinet/in.h>
135 #include <netinet6/in6_var.h>
136 #include <netinet6/nd6.h>
137 #endif
138 
139 #include "carp.h"
140 #if NCARP > 0
141 #include <netinet/in_var.h>
142 #include <netinet/ip_carp.h>
143 #endif
144 
145 #include <compat/sys/sockio.h>
146 #include <compat/sys/socket.h>
147 
148 MALLOC_DEFINE(M_IFADDR, "ifaddr", "interface address");
149 MALLOC_DEFINE(M_IFMADDR, "ether_multi", "link-level multicast address");
150 
151 /*
152  * Global list of interfaces.
153  */
154 struct ifnet_head		ifnet_list;
155 static ifnet_t **		ifindex2ifnet = NULL;
156 
157 static u_int			if_index = 1;
158 static size_t			if_indexlim = 0;
159 static uint64_t			index_gen;
160 static kmutex_t			index_gen_mtx;
161 
162 static struct ifaddr **		ifnet_addrs = NULL;
163 
164 static callout_t		if_slowtimo_ch;
165 
166 struct ifnet *lo0ifp;
167 int	ifqmaxlen = IFQ_MAXLEN;
168 
169 static int	if_rt_walktree(struct rtentry *, void *);
170 
171 static struct if_clone *if_clone_lookup(const char *, int *);
172 static int	if_clone_list(struct if_clonereq *);
173 
174 static LIST_HEAD(, if_clone) if_cloners = LIST_HEAD_INITIALIZER(if_cloners);
175 static int if_cloners_count;
176 
177 /* Packet filtering hook for interfaces. */
178 pfil_head_t *	if_pfil;
179 
180 static kauth_listener_t if_listener;
181 
182 static int doifioctl(struct socket *, u_long, void *, struct lwp *);
183 static int ifioctl_attach(struct ifnet *);
184 static void ifioctl_detach(struct ifnet *);
185 static void ifnet_lock_enter(struct ifnet_lock *);
186 static void ifnet_lock_exit(struct ifnet_lock *);
187 static void if_detach_queues(struct ifnet *, struct ifqueue *);
188 static void sysctl_sndq_setup(struct sysctllog **, const char *,
189     struct ifaltq *);
190 
191 #if defined(INET) || defined(INET6)
192 static void sysctl_net_ifq_setup(struct sysctllog **, int, const char *,
193 				 int, const char *, int, struct ifqueue *);
194 #endif
195 
196 static int
197 if_listener_cb(kauth_cred_t cred, kauth_action_t action, void *cookie,
198     void *arg0, void *arg1, void *arg2, void *arg3)
199 {
200 	int result;
201 	enum kauth_network_req req;
202 
203 	result = KAUTH_RESULT_DEFER;
204 	req = (enum kauth_network_req)arg1;
205 
206 	if (action != KAUTH_NETWORK_INTERFACE)
207 		return result;
208 
209 	if ((req == KAUTH_REQ_NETWORK_INTERFACE_GET) ||
210 	    (req == KAUTH_REQ_NETWORK_INTERFACE_SET))
211 		result = KAUTH_RESULT_ALLOW;
212 
213 	return result;
214 }
215 
216 /*
217  * Network interface utility routines.
218  *
219  * Routines with ifa_ifwith* names take sockaddr *'s as
220  * parameters.
221  */
222 void
223 ifinit(void)
224 {
225 #ifdef INET
226 	{extern struct ifqueue ipintrq;
227 	sysctl_net_ifq_setup(NULL, PF_INET, "inet", IPPROTO_IP, "ip",
228 			     IPCTL_IFQ, &ipintrq);}
229 #endif /* INET */
230 #ifdef INET6
231 	{extern struct ifqueue ip6intrq;
232 	sysctl_net_ifq_setup(NULL, PF_INET6, "inet6", IPPROTO_IPV6, "ip6",
233 			     IPV6CTL_IFQ, &ip6intrq);}
234 #endif /* INET6 */
235 
236 	callout_init(&if_slowtimo_ch, 0);
237 	if_slowtimo(NULL);
238 
239 	if_listener = kauth_listen_scope(KAUTH_SCOPE_NETWORK,
240 	    if_listener_cb, NULL);
241 
242 	/* interfaces are available, inform socket code */
243 	ifioctl = doifioctl;
244 }
245 
246 /*
247  * XXX Initialization before configure().
248  * XXX hack to get pfil_add_hook working in autoconf.
249  */
250 void
251 ifinit1(void)
252 {
253 	mutex_init(&index_gen_mtx, MUTEX_DEFAULT, IPL_NONE);
254 	TAILQ_INIT(&ifnet_list);
255 	if_indexlim = 8;
256 
257 	if_pfil = pfil_head_create(PFIL_TYPE_IFNET, NULL);
258 	KASSERT(if_pfil != NULL);
259 }
260 
261 ifnet_t *
262 if_alloc(u_char type)
263 {
264 	return kmem_zalloc(sizeof(ifnet_t), KM_SLEEP);
265 }
266 
267 void
268 if_free(ifnet_t *ifp)
269 {
270 	kmem_free(ifp, sizeof(ifnet_t));
271 }
272 
273 void
274 if_initname(struct ifnet *ifp, const char *name, int unit)
275 {
276 	(void)snprintf(ifp->if_xname, sizeof(ifp->if_xname),
277 	    "%s%d", name, unit);
278 }
279 
280 /*
281  * Null routines used while an interface is going away.  These routines
282  * just return an error.
283  */
284 
285 int
286 if_nulloutput(struct ifnet *ifp, struct mbuf *m,
287     const struct sockaddr *so, struct rtentry *rt)
288 {
289 
290 	return ENXIO;
291 }
292 
293 void
294 if_nullinput(struct ifnet *ifp, struct mbuf *m)
295 {
296 
297 	/* Nothing. */
298 }
299 
300 void
301 if_nullstart(struct ifnet *ifp)
302 {
303 
304 	/* Nothing. */
305 }
306 
307 int
308 if_nullioctl(struct ifnet *ifp, u_long cmd, void *data)
309 {
310 
311 	/* Wake ifioctl_detach(), who may wait for all threads to
312 	 * quit the critical section.
313 	 */
314 	cv_signal(&ifp->if_ioctl_lock->il_emptied);
315 	return ENXIO;
316 }
317 
318 int
319 if_nullinit(struct ifnet *ifp)
320 {
321 
322 	return ENXIO;
323 }
324 
325 void
326 if_nullstop(struct ifnet *ifp, int disable)
327 {
328 
329 	/* Nothing. */
330 }
331 
332 void
333 if_nullwatchdog(struct ifnet *ifp)
334 {
335 
336 	/* Nothing. */
337 }
338 
339 void
340 if_nulldrain(struct ifnet *ifp)
341 {
342 
343 	/* Nothing. */
344 }
345 
346 void
347 if_set_sadl(struct ifnet *ifp, const void *lla, u_char addrlen, bool factory)
348 {
349 	struct ifaddr *ifa;
350 	struct sockaddr_dl *sdl;
351 
352 	ifp->if_addrlen = addrlen;
353 	if_alloc_sadl(ifp);
354 	ifa = ifp->if_dl;
355 	sdl = satosdl(ifa->ifa_addr);
356 
357 	(void)sockaddr_dl_setaddr(sdl, sdl->sdl_len, lla, ifp->if_addrlen);
358 	if (factory) {
359 		ifp->if_hwdl = ifp->if_dl;
360 		IFAREF(ifp->if_hwdl);
361 	}
362 	/* TBD routing socket */
363 }
364 
365 struct ifaddr *
366 if_dl_create(const struct ifnet *ifp, const struct sockaddr_dl **sdlp)
367 {
368 	unsigned socksize, ifasize;
369 	int addrlen, namelen;
370 	struct sockaddr_dl *mask, *sdl;
371 	struct ifaddr *ifa;
372 
373 	namelen = strlen(ifp->if_xname);
374 	addrlen = ifp->if_addrlen;
375 	socksize = roundup(sockaddr_dl_measure(namelen, addrlen), sizeof(long));
376 	ifasize = sizeof(*ifa) + 2 * socksize;
377 	ifa = (struct ifaddr *)malloc(ifasize, M_IFADDR, M_WAITOK|M_ZERO);
378 
379 	sdl = (struct sockaddr_dl *)(ifa + 1);
380 	mask = (struct sockaddr_dl *)(socksize + (char *)sdl);
381 
382 	sockaddr_dl_init(sdl, socksize, ifp->if_index, ifp->if_type,
383 	    ifp->if_xname, namelen, NULL, addrlen);
384 	mask->sdl_len = sockaddr_dl_measure(namelen, 0);
385 	memset(&mask->sdl_data[0], 0xff, namelen);
386 	ifa->ifa_rtrequest = link_rtrequest;
387 	ifa->ifa_addr = (struct sockaddr *)sdl;
388 	ifa->ifa_netmask = (struct sockaddr *)mask;
389 
390 	*sdlp = sdl;
391 
392 	return ifa;
393 }
394 
395 static void
396 if_sadl_setrefs(struct ifnet *ifp, struct ifaddr *ifa)
397 {
398 	const struct sockaddr_dl *sdl;
399 	ifnet_addrs[ifp->if_index] = ifa;
400 	IFAREF(ifa);
401 	ifp->if_dl = ifa;
402 	IFAREF(ifa);
403 	sdl = satosdl(ifa->ifa_addr);
404 	ifp->if_sadl = sdl;
405 }
406 
407 /*
408  * Allocate the link level name for the specified interface.  This
409  * is an attachment helper.  It must be called after ifp->if_addrlen
410  * is initialized, which may not be the case when if_attach() is
411  * called.
412  */
413 void
414 if_alloc_sadl(struct ifnet *ifp)
415 {
416 	struct ifaddr *ifa;
417 	const struct sockaddr_dl *sdl;
418 
419 	/*
420 	 * If the interface already has a link name, release it
421 	 * now.  This is useful for interfaces that can change
422 	 * link types, and thus switch link names often.
423 	 */
424 	if (ifp->if_sadl != NULL)
425 		if_free_sadl(ifp);
426 
427 	ifa = if_dl_create(ifp, &sdl);
428 
429 	ifa_insert(ifp, ifa);
430 	if_sadl_setrefs(ifp, ifa);
431 }
432 
433 static void
434 if_deactivate_sadl(struct ifnet *ifp)
435 {
436 	struct ifaddr *ifa;
437 
438 	KASSERT(ifp->if_dl != NULL);
439 
440 	ifa = ifp->if_dl;
441 
442 	ifp->if_sadl = NULL;
443 
444 	ifnet_addrs[ifp->if_index] = NULL;
445 	IFAFREE(ifa);
446 	ifp->if_dl = NULL;
447 	IFAFREE(ifa);
448 }
449 
450 void
451 if_activate_sadl(struct ifnet *ifp, struct ifaddr *ifa,
452     const struct sockaddr_dl *sdl)
453 {
454 	int s;
455 
456 	s = splnet();
457 
458 	if_deactivate_sadl(ifp);
459 
460 	if_sadl_setrefs(ifp, ifa);
461 	IFADDR_FOREACH(ifa, ifp)
462 		rtinit(ifa, RTM_LLINFO_UPD, 0);
463 	splx(s);
464 }
465 
466 /*
467  * Free the link level name for the specified interface.  This is
468  * a detach helper.  This is called from if_detach() or from
469  * link layer type specific detach functions.
470  */
471 void
472 if_free_sadl(struct ifnet *ifp)
473 {
474 	struct ifaddr *ifa;
475 	int s;
476 
477 	ifa = ifnet_addrs[ifp->if_index];
478 	if (ifa == NULL) {
479 		KASSERT(ifp->if_sadl == NULL);
480 		KASSERT(ifp->if_dl == NULL);
481 		return;
482 	}
483 
484 	KASSERT(ifp->if_sadl != NULL);
485 	KASSERT(ifp->if_dl != NULL);
486 
487 	s = splnet();
488 	rtinit(ifa, RTM_DELETE, 0);
489 	ifa_remove(ifp, ifa);
490 	if_deactivate_sadl(ifp);
491 	if (ifp->if_hwdl == ifa) {
492 		IFAFREE(ifa);
493 		ifp->if_hwdl = NULL;
494 	}
495 	splx(s);
496 }
497 
498 static void
499 if_getindex(ifnet_t *ifp)
500 {
501 	bool hitlimit = false;
502 
503 	mutex_enter(&index_gen_mtx);
504 	ifp->if_index_gen = index_gen++;
505 	mutex_exit(&index_gen_mtx);
506 
507 	ifp->if_index = if_index;
508 	if (ifindex2ifnet == NULL) {
509 		if_index++;
510 		goto skip;
511 	}
512 	while (if_byindex(ifp->if_index)) {
513 		/*
514 		 * If we hit USHRT_MAX, we skip back to 0 since
515 		 * there are a number of places where the value
516 		 * of if_index or if_index itself is compared
517 		 * to or stored in an unsigned short.  By
518 		 * jumping back, we won't botch those assignments
519 		 * or comparisons.
520 		 */
521 		if (++if_index == 0) {
522 			if_index = 1;
523 		} else if (if_index == USHRT_MAX) {
524 			/*
525 			 * However, if we have to jump back to
526 			 * zero *twice* without finding an empty
527 			 * slot in ifindex2ifnet[], then there
528 			 * there are too many (>65535) interfaces.
529 			 */
530 			if (hitlimit) {
531 				panic("too many interfaces");
532 			}
533 			hitlimit = true;
534 			if_index = 1;
535 		}
536 		ifp->if_index = if_index;
537 	}
538 skip:
539 	/*
540 	 * We have some arrays that should be indexed by if_index.
541 	 * since if_index will grow dynamically, they should grow too.
542 	 *	struct ifadd **ifnet_addrs
543 	 *	struct ifnet **ifindex2ifnet
544 	 */
545 	if (ifnet_addrs == NULL || ifindex2ifnet == NULL ||
546 	    ifp->if_index >= if_indexlim) {
547 		size_t m, n, oldlim;
548 		void *q;
549 
550 		oldlim = if_indexlim;
551 		while (ifp->if_index >= if_indexlim)
552 			if_indexlim <<= 1;
553 
554 		/* grow ifnet_addrs */
555 		m = oldlim * sizeof(struct ifaddr *);
556 		n = if_indexlim * sizeof(struct ifaddr *);
557 		q = malloc(n, M_IFADDR, M_WAITOK|M_ZERO);
558 		if (ifnet_addrs != NULL) {
559 			memcpy(q, ifnet_addrs, m);
560 			free(ifnet_addrs, M_IFADDR);
561 		}
562 		ifnet_addrs = (struct ifaddr **)q;
563 
564 		/* grow ifindex2ifnet */
565 		m = oldlim * sizeof(struct ifnet *);
566 		n = if_indexlim * sizeof(struct ifnet *);
567 		q = malloc(n, M_IFADDR, M_WAITOK|M_ZERO);
568 		if (ifindex2ifnet != NULL) {
569 			memcpy(q, ifindex2ifnet, m);
570 			free(ifindex2ifnet, M_IFADDR);
571 		}
572 		ifindex2ifnet = (struct ifnet **)q;
573 	}
574 	ifindex2ifnet[ifp->if_index] = ifp;
575 }
576 
577 /*
578  * Attach an interface to the list of "active" interfaces.
579  */
580 void
581 if_attach(ifnet_t *ifp)
582 {
583 	KASSERT(if_indexlim > 0);
584 	TAILQ_INIT(&ifp->if_addrlist);
585 	TAILQ_INSERT_TAIL(&ifnet_list, ifp, if_list);
586 
587 	if (ifioctl_attach(ifp) != 0)
588 		panic("%s: ifioctl_attach() failed", __func__);
589 
590 	if_getindex(ifp);
591 
592 	/*
593 	 * Link level name is allocated later by a separate call to
594 	 * if_alloc_sadl().
595 	 */
596 
597 	if (ifp->if_snd.ifq_maxlen == 0)
598 		ifp->if_snd.ifq_maxlen = ifqmaxlen;
599 
600 	sysctl_sndq_setup(&ifp->if_sysctl_log, ifp->if_xname, &ifp->if_snd);
601 
602 	ifp->if_broadcastaddr = 0; /* reliably crash if used uninitialized */
603 
604 	ifp->if_link_state = LINK_STATE_UNKNOWN;
605 
606 	ifp->if_capenable = 0;
607 	ifp->if_csum_flags_tx = 0;
608 	ifp->if_csum_flags_rx = 0;
609 
610 #ifdef ALTQ
611 	ifp->if_snd.altq_type = 0;
612 	ifp->if_snd.altq_disc = NULL;
613 	ifp->if_snd.altq_flags &= ALTQF_CANTCHANGE;
614 	ifp->if_snd.altq_tbr  = NULL;
615 	ifp->if_snd.altq_ifp  = ifp;
616 #endif
617 
618 	ifp->if_pfil = pfil_head_create(PFIL_TYPE_IFNET, ifp);
619 	(void)pfil_run_hooks(if_pfil,
620 	    (struct mbuf **)PFIL_IFNET_ATTACH, ifp, PFIL_IFNET);
621 
622 	if (!STAILQ_EMPTY(&domains))
623 		if_attachdomain1(ifp);
624 
625 	/* Announce the interface. */
626 	rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
627 }
628 
629 void
630 if_attachdomain(void)
631 {
632 	struct ifnet *ifp;
633 	int s;
634 
635 	s = splnet();
636 	IFNET_FOREACH(ifp)
637 		if_attachdomain1(ifp);
638 	splx(s);
639 }
640 
641 void
642 if_attachdomain1(struct ifnet *ifp)
643 {
644 	struct domain *dp;
645 	int s;
646 
647 	s = splnet();
648 
649 	/* address family dependent data region */
650 	memset(ifp->if_afdata, 0, sizeof(ifp->if_afdata));
651 	DOMAIN_FOREACH(dp) {
652 		if (dp->dom_ifattach != NULL)
653 			ifp->if_afdata[dp->dom_family] =
654 			    (*dp->dom_ifattach)(ifp);
655 	}
656 
657 	splx(s);
658 }
659 
660 /*
661  * Deactivate an interface.  This points all of the procedure
662  * handles at error stubs.  May be called from interrupt context.
663  */
664 void
665 if_deactivate(struct ifnet *ifp)
666 {
667 	int s;
668 
669 	s = splnet();
670 
671 	ifp->if_output	 = if_nulloutput;
672 	ifp->if_input	 = if_nullinput;
673 	ifp->if_start	 = if_nullstart;
674 	ifp->if_ioctl	 = if_nullioctl;
675 	ifp->if_init	 = if_nullinit;
676 	ifp->if_stop	 = if_nullstop;
677 	ifp->if_watchdog = if_nullwatchdog;
678 	ifp->if_drain	 = if_nulldrain;
679 
680 	/* No more packets may be enqueued. */
681 	ifp->if_snd.ifq_maxlen = 0;
682 
683 	splx(s);
684 }
685 
686 void
687 if_purgeaddrs(struct ifnet *ifp, int family, void (*purgeaddr)(struct ifaddr *))
688 {
689 	struct ifaddr *ifa, *nifa;
690 
691 	for (ifa = IFADDR_FIRST(ifp); ifa != NULL; ifa = nifa) {
692 		nifa = IFADDR_NEXT(ifa);
693 		if (ifa->ifa_addr->sa_family != family)
694 			continue;
695 		(*purgeaddr)(ifa);
696 	}
697 }
698 
699 /*
700  * Detach an interface from the list of "active" interfaces,
701  * freeing any resources as we go along.
702  *
703  * NOTE: This routine must be called with a valid thread context,
704  * as it may block.
705  */
706 void
707 if_detach(struct ifnet *ifp)
708 {
709 	struct socket so;
710 	struct ifaddr *ifa;
711 #ifdef IFAREF_DEBUG
712 	struct ifaddr *last_ifa = NULL;
713 #endif
714 	struct domain *dp;
715 	const struct protosw *pr;
716 	int s, i, family, purged;
717 
718 	/*
719 	 * XXX It's kind of lame that we have to have the
720 	 * XXX socket structure...
721 	 */
722 	memset(&so, 0, sizeof(so));
723 
724 	s = splnet();
725 
726 	/*
727 	 * Do an if_down() to give protocols a chance to do something.
728 	 */
729 	if_down(ifp);
730 
731 #ifdef ALTQ
732 	if (ALTQ_IS_ENABLED(&ifp->if_snd))
733 		altq_disable(&ifp->if_snd);
734 	if (ALTQ_IS_ATTACHED(&ifp->if_snd))
735 		altq_detach(&ifp->if_snd);
736 #endif
737 
738 	sysctl_teardown(&ifp->if_sysctl_log);
739 
740 #if NCARP > 0
741 	/* Remove the interface from any carp group it is a part of.  */
742 	if (ifp->if_carp != NULL && ifp->if_type != IFT_CARP)
743 		carp_ifdetach(ifp);
744 #endif
745 
746 	/*
747 	 * Rip all the addresses off the interface.  This should make
748 	 * all of the routes go away.
749 	 *
750 	 * pr_usrreq calls can remove an arbitrary number of ifaddrs
751 	 * from the list, including our "cursor", ifa.  For safety,
752 	 * and to honor the TAILQ abstraction, I just restart the
753 	 * loop after each removal.  Note that the loop will exit
754 	 * when all of the remaining ifaddrs belong to the AF_LINK
755 	 * family.  I am counting on the historical fact that at
756 	 * least one pr_usrreq in each address domain removes at
757 	 * least one ifaddr.
758 	 */
759 again:
760 	IFADDR_FOREACH(ifa, ifp) {
761 		family = ifa->ifa_addr->sa_family;
762 #ifdef IFAREF_DEBUG
763 		printf("if_detach: ifaddr %p, family %d, refcnt %d\n",
764 		    ifa, family, ifa->ifa_refcnt);
765 		if (last_ifa != NULL && ifa == last_ifa)
766 			panic("if_detach: loop detected");
767 		last_ifa = ifa;
768 #endif
769 		if (family == AF_LINK)
770 			continue;
771 		dp = pffinddomain(family);
772 #ifdef DIAGNOSTIC
773 		if (dp == NULL)
774 			panic("if_detach: no domain for AF %d",
775 			    family);
776 #endif
777 		/*
778 		 * XXX These PURGEIF calls are redundant with the
779 		 * purge-all-families calls below, but are left in for
780 		 * now both to make a smaller change, and to avoid
781 		 * unplanned interactions with clearing of
782 		 * ifp->if_addrlist.
783 		 */
784 		purged = 0;
785 		for (pr = dp->dom_protosw;
786 		     pr < dp->dom_protoswNPROTOSW; pr++) {
787 			so.so_proto = pr;
788 			if (pr->pr_usrreqs) {
789 				(void) (*pr->pr_usrreqs->pr_generic)(&so,
790 				    PRU_PURGEIF, NULL, NULL,
791 				    (struct mbuf *) ifp, curlwp);
792 				purged = 1;
793 			}
794 		}
795 		if (purged == 0) {
796 			/*
797 			 * XXX What's really the best thing to do
798 			 * XXX here?  --thorpej@NetBSD.org
799 			 */
800 			printf("if_detach: WARNING: AF %d not purged\n",
801 			    family);
802 			ifa_remove(ifp, ifa);
803 		}
804 		goto again;
805 	}
806 
807 	if_free_sadl(ifp);
808 
809 	/* Walk the routing table looking for stragglers. */
810 	for (i = 0; i <= AF_MAX; i++) {
811 		while (rt_walktree(i, if_rt_walktree, ifp) == ERESTART)
812 			continue;
813 	}
814 
815 	DOMAIN_FOREACH(dp) {
816 		if (dp->dom_ifdetach != NULL && ifp->if_afdata[dp->dom_family])
817 		{
818 			void *p = ifp->if_afdata[dp->dom_family];
819 			if (p) {
820 				ifp->if_afdata[dp->dom_family] = NULL;
821 				(*dp->dom_ifdetach)(ifp, p);
822 			}
823 		}
824 
825 		/*
826 		 * One would expect multicast memberships (INET and
827 		 * INET6) on UDP sockets to be purged by the PURGEIF
828 		 * calls above, but if all addresses were removed from
829 		 * the interface prior to destruction, the calls will
830 		 * not be made (e.g. ppp, for which pppd(8) generally
831 		 * removes addresses before destroying the interface).
832 		 * Because there is no invariant that multicast
833 		 * memberships only exist for interfaces with IPv4
834 		 * addresses, we must call PURGEIF regardless of
835 		 * addresses.  (Protocols which might store ifnet
836 		 * pointers are marked with PR_PURGEIF.)
837 		 */
838 		for (pr = dp->dom_protosw; pr < dp->dom_protoswNPROTOSW; pr++) {
839 			so.so_proto = pr;
840 			if (pr->pr_usrreqs && pr->pr_flags & PR_PURGEIF)
841 				(void)(*pr->pr_usrreqs->pr_generic)(&so,
842 				    PRU_PURGEIF, NULL, NULL,
843 				    (struct mbuf *)ifp, curlwp);
844 		}
845 	}
846 
847 	(void)pfil_run_hooks(if_pfil,
848 	    (struct mbuf **)PFIL_IFNET_DETACH, ifp, PFIL_IFNET);
849 	(void)pfil_head_destroy(ifp->if_pfil);
850 
851 	/* Announce that the interface is gone. */
852 	rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
853 
854 	ifindex2ifnet[ifp->if_index] = NULL;
855 
856 	TAILQ_REMOVE(&ifnet_list, ifp, if_list);
857 
858 	ifioctl_detach(ifp);
859 
860 	/*
861 	 * remove packets that came from ifp, from software interrupt queues.
862 	 */
863 	DOMAIN_FOREACH(dp) {
864 		for (i = 0; i < __arraycount(dp->dom_ifqueues); i++) {
865 			struct ifqueue *iq = dp->dom_ifqueues[i];
866 			if (iq == NULL)
867 				break;
868 			dp->dom_ifqueues[i] = NULL;
869 			if_detach_queues(ifp, iq);
870 		}
871 	}
872 
873 	splx(s);
874 }
875 
876 static void
877 if_detach_queues(struct ifnet *ifp, struct ifqueue *q)
878 {
879 	struct mbuf *m, *prev, *next;
880 
881 	prev = NULL;
882 	for (m = q->ifq_head; m != NULL; m = next) {
883 		KASSERT((m->m_flags & M_PKTHDR) != 0);
884 
885 		next = m->m_nextpkt;
886 		if (m->m_pkthdr.rcvif != ifp) {
887 			prev = m;
888 			continue;
889 		}
890 
891 		if (prev != NULL)
892 			prev->m_nextpkt = m->m_nextpkt;
893 		else
894 			q->ifq_head = m->m_nextpkt;
895 		if (q->ifq_tail == m)
896 			q->ifq_tail = prev;
897 		q->ifq_len--;
898 
899 		m->m_nextpkt = NULL;
900 		m_freem(m);
901 		IF_DROP(q);
902 	}
903 }
904 
905 /*
906  * Callback for a radix tree walk to delete all references to an
907  * ifnet.
908  */
909 static int
910 if_rt_walktree(struct rtentry *rt, void *v)
911 {
912 	struct ifnet *ifp = (struct ifnet *)v;
913 	int error;
914 
915 	if (rt->rt_ifp != ifp)
916 		return 0;
917 
918 	/* Delete the entry. */
919 	++rt->rt_refcnt;
920 	error = rtrequest(RTM_DELETE, rt_getkey(rt), rt->rt_gateway,
921 	    rt_mask(rt), rt->rt_flags, NULL);
922 	KASSERT((rt->rt_flags & RTF_UP) == 0);
923 	rt->rt_ifp = NULL;
924 	RTFREE(rt);
925 	if (error != 0)
926 		printf("%s: warning: unable to delete rtentry @ %p, "
927 		    "error = %d\n", ifp->if_xname, rt, error);
928 	return ERESTART;
929 }
930 
931 /*
932  * Create a clone network interface.
933  */
934 int
935 if_clone_create(const char *name)
936 {
937 	struct if_clone *ifc;
938 	int unit;
939 
940 	ifc = if_clone_lookup(name, &unit);
941 	if (ifc == NULL)
942 		return EINVAL;
943 
944 	if (ifunit(name) != NULL)
945 		return EEXIST;
946 
947 	return (*ifc->ifc_create)(ifc, unit);
948 }
949 
950 /*
951  * Destroy a clone network interface.
952  */
953 int
954 if_clone_destroy(const char *name)
955 {
956 	struct if_clone *ifc;
957 	struct ifnet *ifp;
958 
959 	ifc = if_clone_lookup(name, NULL);
960 	if (ifc == NULL)
961 		return EINVAL;
962 
963 	ifp = ifunit(name);
964 	if (ifp == NULL)
965 		return ENXIO;
966 
967 	if (ifc->ifc_destroy == NULL)
968 		return EOPNOTSUPP;
969 
970 	return (*ifc->ifc_destroy)(ifp);
971 }
972 
973 /*
974  * Look up a network interface cloner.
975  */
976 static struct if_clone *
977 if_clone_lookup(const char *name, int *unitp)
978 {
979 	struct if_clone *ifc;
980 	const char *cp;
981 	char *dp, ifname[IFNAMSIZ + 3];
982 	int unit;
983 
984 	strcpy(ifname, "if_");
985 	/* separate interface name from unit */
986 	for (dp = ifname + 3, cp = name; cp - name < IFNAMSIZ &&
987 	    *cp && (*cp < '0' || *cp > '9');)
988 		*dp++ = *cp++;
989 
990 	if (cp == name || cp - name == IFNAMSIZ || !*cp)
991 		return NULL;	/* No name or unit number */
992 	*dp++ = '\0';
993 
994 again:
995 	LIST_FOREACH(ifc, &if_cloners, ifc_list) {
996 		if (strcmp(ifname + 3, ifc->ifc_name) == 0)
997 			break;
998 	}
999 
1000 	if (ifc == NULL) {
1001 		if (*ifname == '\0' ||
1002 		    module_autoload(ifname, MODULE_CLASS_DRIVER))
1003 			return NULL;
1004 		*ifname = '\0';
1005 		goto again;
1006 	}
1007 
1008 	unit = 0;
1009 	while (cp - name < IFNAMSIZ && *cp) {
1010 		if (*cp < '0' || *cp > '9' || unit >= INT_MAX / 10) {
1011 			/* Bogus unit number. */
1012 			return NULL;
1013 		}
1014 		unit = (unit * 10) + (*cp++ - '0');
1015 	}
1016 
1017 	if (unitp != NULL)
1018 		*unitp = unit;
1019 	return ifc;
1020 }
1021 
1022 /*
1023  * Register a network interface cloner.
1024  */
1025 void
1026 if_clone_attach(struct if_clone *ifc)
1027 {
1028 
1029 	LIST_INSERT_HEAD(&if_cloners, ifc, ifc_list);
1030 	if_cloners_count++;
1031 }
1032 
1033 /*
1034  * Unregister a network interface cloner.
1035  */
1036 void
1037 if_clone_detach(struct if_clone *ifc)
1038 {
1039 
1040 	LIST_REMOVE(ifc, ifc_list);
1041 	if_cloners_count--;
1042 }
1043 
1044 /*
1045  * Provide list of interface cloners to userspace.
1046  */
1047 static int
1048 if_clone_list(struct if_clonereq *ifcr)
1049 {
1050 	char outbuf[IFNAMSIZ], *dst;
1051 	struct if_clone *ifc;
1052 	int count, error = 0;
1053 
1054 	ifcr->ifcr_total = if_cloners_count;
1055 	if ((dst = ifcr->ifcr_buffer) == NULL) {
1056 		/* Just asking how many there are. */
1057 		return 0;
1058 	}
1059 
1060 	if (ifcr->ifcr_count < 0)
1061 		return EINVAL;
1062 
1063 	count = (if_cloners_count < ifcr->ifcr_count) ?
1064 	    if_cloners_count : ifcr->ifcr_count;
1065 
1066 	for (ifc = LIST_FIRST(&if_cloners); ifc != NULL && count != 0;
1067 	     ifc = LIST_NEXT(ifc, ifc_list), count--, dst += IFNAMSIZ) {
1068 		(void)strncpy(outbuf, ifc->ifc_name, sizeof(outbuf));
1069 		if (outbuf[sizeof(outbuf) - 1] != '\0')
1070 			return ENAMETOOLONG;
1071 		error = copyout(outbuf, dst, sizeof(outbuf));
1072 		if (error != 0)
1073 			break;
1074 	}
1075 
1076 	return error;
1077 }
1078 
1079 void
1080 ifa_insert(struct ifnet *ifp, struct ifaddr *ifa)
1081 {
1082 	ifa->ifa_ifp = ifp;
1083 	TAILQ_INSERT_TAIL(&ifp->if_addrlist, ifa, ifa_list);
1084 	IFAREF(ifa);
1085 }
1086 
1087 void
1088 ifa_remove(struct ifnet *ifp, struct ifaddr *ifa)
1089 {
1090 	KASSERT(ifa->ifa_ifp == ifp);
1091 	TAILQ_REMOVE(&ifp->if_addrlist, ifa, ifa_list);
1092 	IFAFREE(ifa);
1093 }
1094 
1095 static inline int
1096 equal(const struct sockaddr *sa1, const struct sockaddr *sa2)
1097 {
1098 	return sockaddr_cmp(sa1, sa2) == 0;
1099 }
1100 
1101 /*
1102  * Locate an interface based on a complete address.
1103  */
1104 /*ARGSUSED*/
1105 struct ifaddr *
1106 ifa_ifwithaddr(const struct sockaddr *addr)
1107 {
1108 	struct ifnet *ifp;
1109 	struct ifaddr *ifa;
1110 
1111 	IFNET_FOREACH(ifp) {
1112 		if (ifp->if_output == if_nulloutput)
1113 			continue;
1114 		IFADDR_FOREACH(ifa, ifp) {
1115 			if (ifa->ifa_addr->sa_family != addr->sa_family)
1116 				continue;
1117 			if (equal(addr, ifa->ifa_addr))
1118 				return ifa;
1119 			if ((ifp->if_flags & IFF_BROADCAST) &&
1120 			    ifa->ifa_broadaddr &&
1121 			    /* IP6 doesn't have broadcast */
1122 			    ifa->ifa_broadaddr->sa_len != 0 &&
1123 			    equal(ifa->ifa_broadaddr, addr))
1124 				return ifa;
1125 		}
1126 	}
1127 	return NULL;
1128 }
1129 
1130 /*
1131  * Locate the point to point interface with a given destination address.
1132  */
1133 /*ARGSUSED*/
1134 struct ifaddr *
1135 ifa_ifwithdstaddr(const struct sockaddr *addr)
1136 {
1137 	struct ifnet *ifp;
1138 	struct ifaddr *ifa;
1139 
1140 	IFNET_FOREACH(ifp) {
1141 		if (ifp->if_output == if_nulloutput)
1142 			continue;
1143 		if ((ifp->if_flags & IFF_POINTOPOINT) == 0)
1144 			continue;
1145 		IFADDR_FOREACH(ifa, ifp) {
1146 			if (ifa->ifa_addr->sa_family != addr->sa_family ||
1147 			    ifa->ifa_dstaddr == NULL)
1148 				continue;
1149 			if (equal(addr, ifa->ifa_dstaddr))
1150 				return ifa;
1151 		}
1152 	}
1153 	return NULL;
1154 }
1155 
1156 /*
1157  * Find an interface on a specific network.  If many, choice
1158  * is most specific found.
1159  */
1160 struct ifaddr *
1161 ifa_ifwithnet(const struct sockaddr *addr)
1162 {
1163 	struct ifnet *ifp;
1164 	struct ifaddr *ifa;
1165 	const struct sockaddr_dl *sdl;
1166 	struct ifaddr *ifa_maybe = 0;
1167 	u_int af = addr->sa_family;
1168 	const char *addr_data = addr->sa_data, *cplim;
1169 
1170 	if (af == AF_LINK) {
1171 		sdl = satocsdl(addr);
1172 		if (sdl->sdl_index && sdl->sdl_index < if_indexlim &&
1173 		    ifindex2ifnet[sdl->sdl_index] &&
1174 		    ifindex2ifnet[sdl->sdl_index]->if_output != if_nulloutput)
1175 			return ifnet_addrs[sdl->sdl_index];
1176 	}
1177 #ifdef NETATALK
1178 	if (af == AF_APPLETALK) {
1179 		const struct sockaddr_at *sat, *sat2;
1180 		sat = (const struct sockaddr_at *)addr;
1181 		IFNET_FOREACH(ifp) {
1182 			if (ifp->if_output == if_nulloutput)
1183 				continue;
1184 			ifa = at_ifawithnet((const struct sockaddr_at *)addr, ifp);
1185 			if (ifa == NULL)
1186 				continue;
1187 			sat2 = (struct sockaddr_at *)ifa->ifa_addr;
1188 			if (sat2->sat_addr.s_net == sat->sat_addr.s_net)
1189 				return ifa; /* exact match */
1190 			if (ifa_maybe == NULL) {
1191 				/* else keep the if with the right range */
1192 				ifa_maybe = ifa;
1193 			}
1194 		}
1195 		return ifa_maybe;
1196 	}
1197 #endif
1198 	IFNET_FOREACH(ifp) {
1199 		if (ifp->if_output == if_nulloutput)
1200 			continue;
1201 		IFADDR_FOREACH(ifa, ifp) {
1202 			const char *cp, *cp2, *cp3;
1203 
1204 			if (ifa->ifa_addr->sa_family != af ||
1205 			    ifa->ifa_netmask == NULL)
1206  next:				continue;
1207 			cp = addr_data;
1208 			cp2 = ifa->ifa_addr->sa_data;
1209 			cp3 = ifa->ifa_netmask->sa_data;
1210 			cplim = (const char *)ifa->ifa_netmask +
1211 			    ifa->ifa_netmask->sa_len;
1212 			while (cp3 < cplim) {
1213 				if ((*cp++ ^ *cp2++) & *cp3++) {
1214 					/* want to continue for() loop */
1215 					goto next;
1216 				}
1217 			}
1218 			if (ifa_maybe == NULL ||
1219 			    rn_refines((void *)ifa->ifa_netmask,
1220 			    (void *)ifa_maybe->ifa_netmask))
1221 				ifa_maybe = ifa;
1222 		}
1223 	}
1224 	return ifa_maybe;
1225 }
1226 
1227 /*
1228  * Find the interface of the addresss.
1229  */
1230 struct ifaddr *
1231 ifa_ifwithladdr(const struct sockaddr *addr)
1232 {
1233 	struct ifaddr *ia;
1234 
1235 	if ((ia = ifa_ifwithaddr(addr)) || (ia = ifa_ifwithdstaddr(addr)) ||
1236 	    (ia = ifa_ifwithnet(addr)))
1237 		return ia;
1238 	return NULL;
1239 }
1240 
1241 /*
1242  * Find an interface using a specific address family
1243  */
1244 struct ifaddr *
1245 ifa_ifwithaf(int af)
1246 {
1247 	struct ifnet *ifp;
1248 	struct ifaddr *ifa;
1249 
1250 	IFNET_FOREACH(ifp) {
1251 		if (ifp->if_output == if_nulloutput)
1252 			continue;
1253 		IFADDR_FOREACH(ifa, ifp) {
1254 			if (ifa->ifa_addr->sa_family == af)
1255 				return ifa;
1256 		}
1257 	}
1258 	return NULL;
1259 }
1260 
1261 /*
1262  * Find an interface address specific to an interface best matching
1263  * a given address.
1264  */
1265 struct ifaddr *
1266 ifaof_ifpforaddr(const struct sockaddr *addr, struct ifnet *ifp)
1267 {
1268 	struct ifaddr *ifa;
1269 	const char *cp, *cp2, *cp3;
1270 	const char *cplim;
1271 	struct ifaddr *ifa_maybe = 0;
1272 	u_int af = addr->sa_family;
1273 
1274 	if (ifp->if_output == if_nulloutput)
1275 		return NULL;
1276 
1277 	if (af >= AF_MAX)
1278 		return NULL;
1279 
1280 	IFADDR_FOREACH(ifa, ifp) {
1281 		if (ifa->ifa_addr->sa_family != af)
1282 			continue;
1283 		ifa_maybe = ifa;
1284 		if (ifa->ifa_netmask == NULL) {
1285 			if (equal(addr, ifa->ifa_addr) ||
1286 			    (ifa->ifa_dstaddr &&
1287 			     equal(addr, ifa->ifa_dstaddr)))
1288 				return ifa;
1289 			continue;
1290 		}
1291 		cp = addr->sa_data;
1292 		cp2 = ifa->ifa_addr->sa_data;
1293 		cp3 = ifa->ifa_netmask->sa_data;
1294 		cplim = ifa->ifa_netmask->sa_len + (char *)ifa->ifa_netmask;
1295 		for (; cp3 < cplim; cp3++) {
1296 			if ((*cp++ ^ *cp2++) & *cp3)
1297 				break;
1298 		}
1299 		if (cp3 == cplim)
1300 			return ifa;
1301 	}
1302 	return ifa_maybe;
1303 }
1304 
1305 /*
1306  * Default action when installing a route with a Link Level gateway.
1307  * Lookup an appropriate real ifa to point to.
1308  * This should be moved to /sys/net/link.c eventually.
1309  */
1310 void
1311 link_rtrequest(int cmd, struct rtentry *rt, const struct rt_addrinfo *info)
1312 {
1313 	struct ifaddr *ifa;
1314 	const struct sockaddr *dst;
1315 	struct ifnet *ifp;
1316 
1317 	if (cmd != RTM_ADD || (ifa = rt->rt_ifa) == NULL ||
1318 	    (ifp = ifa->ifa_ifp) == NULL || (dst = rt_getkey(rt)) == NULL)
1319 		return;
1320 	if ((ifa = ifaof_ifpforaddr(dst, ifp)) != NULL) {
1321 		rt_replace_ifa(rt, ifa);
1322 		if (ifa->ifa_rtrequest && ifa->ifa_rtrequest != link_rtrequest)
1323 			ifa->ifa_rtrequest(cmd, rt, info);
1324 	}
1325 }
1326 
1327 /*
1328  * Handle a change in the interface link state.
1329  * XXX: We should listen to the routing socket in-kernel rather
1330  * than calling in6_if_link_* functions directly from here.
1331  */
1332 void
1333 if_link_state_change(struct ifnet *ifp, int link_state)
1334 {
1335 	int s;
1336 #if defined(DEBUG) || defined(INET6)
1337 	int old_link_state;
1338 #endif
1339 
1340 	s = splnet();
1341 	if (ifp->if_link_state == link_state) {
1342 		splx(s);
1343 		return;
1344 	}
1345 
1346 #if defined(DEBUG) || defined(INET6)
1347 	old_link_state = ifp->if_link_state;
1348 #endif
1349 	ifp->if_link_state = link_state;
1350 #ifdef DEBUG
1351 	log(LOG_DEBUG, "%s: link state %s (was %s)\n", ifp->if_xname,
1352 		link_state == LINK_STATE_UP ? "UP" :
1353 		link_state == LINK_STATE_DOWN ? "DOWN" :
1354 		"UNKNOWN",
1355 		 old_link_state == LINK_STATE_UP ? "UP" :
1356 		old_link_state == LINK_STATE_DOWN ? "DOWN" :
1357 		"UNKNOWN");
1358 #endif
1359 
1360 #ifdef INET6
1361 	/*
1362 	 * When going from UNKNOWN to UP, we need to mark existing
1363 	 * IPv6 addresses as tentative and restart DAD as we may have
1364 	 * erroneously not found a duplicate.
1365 	 *
1366 	 * This needs to happen before rt_ifmsg to avoid a race where
1367 	 * listeners would have an address and expect it to work right
1368 	 * away.
1369 	 */
1370 	if (in6_present && link_state == LINK_STATE_UP &&
1371 	    old_link_state == LINK_STATE_UNKNOWN)
1372 		in6_if_link_down(ifp);
1373 #endif
1374 
1375 	/* Notify that the link state has changed. */
1376 	rt_ifmsg(ifp);
1377 
1378 #if NCARP > 0
1379 	if (ifp->if_carp)
1380 		carp_carpdev_state(ifp);
1381 #endif
1382 
1383 #ifdef INET6
1384 	if (in6_present) {
1385 		if (link_state == LINK_STATE_DOWN)
1386 			in6_if_link_down(ifp);
1387 		else if (link_state == LINK_STATE_UP)
1388 			in6_if_link_up(ifp);
1389 	}
1390 #endif
1391 
1392 	splx(s);
1393 }
1394 
1395 /*
1396  * Mark an interface down and notify protocols of
1397  * the transition.
1398  * NOTE: must be called at splsoftnet or equivalent.
1399  */
1400 void
1401 if_down(struct ifnet *ifp)
1402 {
1403 	struct ifaddr *ifa;
1404 
1405 	ifp->if_flags &= ~IFF_UP;
1406 	nanotime(&ifp->if_lastchange);
1407 	IFADDR_FOREACH(ifa, ifp)
1408 		pfctlinput(PRC_IFDOWN, ifa->ifa_addr);
1409 	IFQ_PURGE(&ifp->if_snd);
1410 #if NCARP > 0
1411 	if (ifp->if_carp)
1412 		carp_carpdev_state(ifp);
1413 #endif
1414 	rt_ifmsg(ifp);
1415 #ifdef INET6
1416 	if (in6_present)
1417 		in6_if_down(ifp);
1418 #endif
1419 }
1420 
1421 /*
1422  * Mark an interface up and notify protocols of
1423  * the transition.
1424  * NOTE: must be called at splsoftnet or equivalent.
1425  */
1426 void
1427 if_up(struct ifnet *ifp)
1428 {
1429 #ifdef notyet
1430 	struct ifaddr *ifa;
1431 #endif
1432 
1433 	ifp->if_flags |= IFF_UP;
1434 	nanotime(&ifp->if_lastchange);
1435 #ifdef notyet
1436 	/* this has no effect on IP, and will kill all ISO connections XXX */
1437 	IFADDR_FOREACH(ifa, ifp)
1438 		pfctlinput(PRC_IFUP, ifa->ifa_addr);
1439 #endif
1440 #if NCARP > 0
1441 	if (ifp->if_carp)
1442 		carp_carpdev_state(ifp);
1443 #endif
1444 	rt_ifmsg(ifp);
1445 #ifdef INET6
1446 	if (in6_present)
1447 		in6_if_up(ifp);
1448 #endif
1449 }
1450 
1451 /*
1452  * Handle interface watchdog timer routines.  Called
1453  * from softclock, we decrement timers (if set) and
1454  * call the appropriate interface routine on expiration.
1455  */
1456 void
1457 if_slowtimo(void *arg)
1458 {
1459 	struct ifnet *ifp;
1460 	int s = splnet();
1461 
1462 	IFNET_FOREACH(ifp) {
1463 		if (ifp->if_timer == 0 || --ifp->if_timer)
1464 			continue;
1465 		if (ifp->if_watchdog != NULL)
1466 			(*ifp->if_watchdog)(ifp);
1467 	}
1468 	splx(s);
1469 	callout_reset(&if_slowtimo_ch, hz / IFNET_SLOWHZ, if_slowtimo, NULL);
1470 }
1471 
1472 /*
1473  * Set/clear promiscuous mode on interface ifp based on the truth value
1474  * of pswitch.  The calls are reference counted so that only the first
1475  * "on" request actually has an effect, as does the final "off" request.
1476  * Results are undefined if the "off" and "on" requests are not matched.
1477  */
1478 int
1479 ifpromisc(struct ifnet *ifp, int pswitch)
1480 {
1481 	int pcount, ret;
1482 	short nflags;
1483 
1484 	pcount = ifp->if_pcount;
1485 	if (pswitch) {
1486 		/*
1487 		 * Allow the device to be "placed" into promiscuous
1488 		 * mode even if it is not configured up.  It will
1489 		 * consult IFF_PROMISC when it is brought up.
1490 		 */
1491 		if (ifp->if_pcount++ != 0)
1492 			return 0;
1493 		nflags = ifp->if_flags | IFF_PROMISC;
1494 	} else {
1495 		if (--ifp->if_pcount > 0)
1496 			return 0;
1497 		nflags = ifp->if_flags & ~IFF_PROMISC;
1498 	}
1499 	ret = if_flags_set(ifp, nflags);
1500 	/* Restore interface state if not successful. */
1501 	if (ret != 0) {
1502 		ifp->if_pcount = pcount;
1503 	}
1504 	return ret;
1505 }
1506 
1507 /*
1508  * Map interface name to
1509  * interface structure pointer.
1510  */
1511 struct ifnet *
1512 ifunit(const char *name)
1513 {
1514 	struct ifnet *ifp;
1515 	const char *cp = name;
1516 	u_int unit = 0;
1517 	u_int i;
1518 
1519 	/*
1520 	 * If the entire name is a number, treat it as an ifindex.
1521 	 */
1522 	for (i = 0; i < IFNAMSIZ && *cp >= '0' && *cp <= '9'; i++, cp++) {
1523 		unit = unit * 10 + (*cp - '0');
1524 	}
1525 
1526 	/*
1527 	 * If the number took all of the name, then it's a valid ifindex.
1528 	 */
1529 	if (i == IFNAMSIZ || (cp != name && *cp == '\0')) {
1530 		if (unit >= if_indexlim)
1531 			return NULL;
1532 		ifp = ifindex2ifnet[unit];
1533 		if (ifp == NULL || ifp->if_output == if_nulloutput)
1534 			return NULL;
1535 		return ifp;
1536 	}
1537 
1538 	IFNET_FOREACH(ifp) {
1539 		if (ifp->if_output == if_nulloutput)
1540 			continue;
1541 	 	if (strcmp(ifp->if_xname, name) == 0)
1542 			return ifp;
1543 	}
1544 	return NULL;
1545 }
1546 
1547 ifnet_t *
1548 if_byindex(u_int idx)
1549 {
1550 	return (idx < if_indexlim) ? ifindex2ifnet[idx] : NULL;
1551 }
1552 
1553 /* common */
1554 int
1555 ifioctl_common(struct ifnet *ifp, u_long cmd, void *data)
1556 {
1557 	int s;
1558 	struct ifreq *ifr;
1559 	struct ifcapreq *ifcr;
1560 	struct ifdatareq *ifdr;
1561 
1562 	switch (cmd) {
1563 	case SIOCSIFCAP:
1564 		ifcr = data;
1565 		if ((ifcr->ifcr_capenable & ~ifp->if_capabilities) != 0)
1566 			return EINVAL;
1567 
1568 		if (ifcr->ifcr_capenable == ifp->if_capenable)
1569 			return 0;
1570 
1571 		ifp->if_capenable = ifcr->ifcr_capenable;
1572 
1573 		/* Pre-compute the checksum flags mask. */
1574 		ifp->if_csum_flags_tx = 0;
1575 		ifp->if_csum_flags_rx = 0;
1576 		if (ifp->if_capenable & IFCAP_CSUM_IPv4_Tx) {
1577 			ifp->if_csum_flags_tx |= M_CSUM_IPv4;
1578 		}
1579 		if (ifp->if_capenable & IFCAP_CSUM_IPv4_Rx) {
1580 			ifp->if_csum_flags_rx |= M_CSUM_IPv4;
1581 		}
1582 
1583 		if (ifp->if_capenable & IFCAP_CSUM_TCPv4_Tx) {
1584 			ifp->if_csum_flags_tx |= M_CSUM_TCPv4;
1585 		}
1586 		if (ifp->if_capenable & IFCAP_CSUM_TCPv4_Rx) {
1587 			ifp->if_csum_flags_rx |= M_CSUM_TCPv4;
1588 		}
1589 
1590 		if (ifp->if_capenable & IFCAP_CSUM_UDPv4_Tx) {
1591 			ifp->if_csum_flags_tx |= M_CSUM_UDPv4;
1592 		}
1593 		if (ifp->if_capenable & IFCAP_CSUM_UDPv4_Rx) {
1594 			ifp->if_csum_flags_rx |= M_CSUM_UDPv4;
1595 		}
1596 
1597 		if (ifp->if_capenable & IFCAP_CSUM_TCPv6_Tx) {
1598 			ifp->if_csum_flags_tx |= M_CSUM_TCPv6;
1599 		}
1600 		if (ifp->if_capenable & IFCAP_CSUM_TCPv6_Rx) {
1601 			ifp->if_csum_flags_rx |= M_CSUM_TCPv6;
1602 		}
1603 
1604 		if (ifp->if_capenable & IFCAP_CSUM_UDPv6_Tx) {
1605 			ifp->if_csum_flags_tx |= M_CSUM_UDPv6;
1606 		}
1607 		if (ifp->if_capenable & IFCAP_CSUM_UDPv6_Rx) {
1608 			ifp->if_csum_flags_rx |= M_CSUM_UDPv6;
1609 		}
1610 		if (ifp->if_flags & IFF_UP)
1611 			return ENETRESET;
1612 		return 0;
1613 	case SIOCSIFFLAGS:
1614 		ifr = data;
1615 		if (ifp->if_flags & IFF_UP && (ifr->ifr_flags & IFF_UP) == 0) {
1616 			s = splnet();
1617 			if_down(ifp);
1618 			splx(s);
1619 		}
1620 		if (ifr->ifr_flags & IFF_UP && (ifp->if_flags & IFF_UP) == 0) {
1621 			s = splnet();
1622 			if_up(ifp);
1623 			splx(s);
1624 		}
1625 		ifp->if_flags = (ifp->if_flags & IFF_CANTCHANGE) |
1626 			(ifr->ifr_flags &~ IFF_CANTCHANGE);
1627 		break;
1628 	case SIOCGIFFLAGS:
1629 		ifr = data;
1630 		ifr->ifr_flags = ifp->if_flags;
1631 		break;
1632 
1633 	case SIOCGIFMETRIC:
1634 		ifr = data;
1635 		ifr->ifr_metric = ifp->if_metric;
1636 		break;
1637 
1638 	case SIOCGIFMTU:
1639 		ifr = data;
1640 		ifr->ifr_mtu = ifp->if_mtu;
1641 		break;
1642 
1643 	case SIOCGIFDLT:
1644 		ifr = data;
1645 		ifr->ifr_dlt = ifp->if_dlt;
1646 		break;
1647 
1648 	case SIOCGIFCAP:
1649 		ifcr = data;
1650 		ifcr->ifcr_capabilities = ifp->if_capabilities;
1651 		ifcr->ifcr_capenable = ifp->if_capenable;
1652 		break;
1653 
1654 	case SIOCSIFMETRIC:
1655 		ifr = data;
1656 		ifp->if_metric = ifr->ifr_metric;
1657 		break;
1658 
1659 	case SIOCGIFDATA:
1660 		ifdr = data;
1661 		ifdr->ifdr_data = ifp->if_data;
1662 		break;
1663 
1664 	case SIOCGIFINDEX:
1665 		ifr = data;
1666 		ifr->ifr_index = ifp->if_index;
1667 		break;
1668 
1669 	case SIOCZIFDATA:
1670 		ifdr = data;
1671 		ifdr->ifdr_data = ifp->if_data;
1672 		/*
1673 		 * Assumes that the volatile counters that can be
1674 		 * zero'ed are at the end of if_data.
1675 		 */
1676 		memset(&ifp->if_data.ifi_ipackets, 0, sizeof(ifp->if_data) -
1677 		    offsetof(struct if_data, ifi_ipackets));
1678 		/*
1679 		 * The memset() clears to the bottm of if_data. In the area,
1680 		 * if_lastchange is included. Please be careful if new entry
1681 		 * will be added into if_data or rewite this.
1682 		 *
1683 		 * And also, update if_lastchnage.
1684 		 */
1685 		getnanotime(&ifp->if_lastchange);
1686 		break;
1687 	case SIOCSIFMTU:
1688 		ifr = data;
1689 		if (ifp->if_mtu == ifr->ifr_mtu)
1690 			break;
1691 		ifp->if_mtu = ifr->ifr_mtu;
1692 		/*
1693 		 * If the link MTU changed, do network layer specific procedure.
1694 		 */
1695 #ifdef INET6
1696 		if (in6_present)
1697 			nd6_setmtu(ifp);
1698 #endif
1699 		return ENETRESET;
1700 	default:
1701 		return ENOTTY;
1702 	}
1703 	return 0;
1704 }
1705 
1706 int
1707 ifaddrpref_ioctl(struct socket *so, u_long cmd, void *data, struct ifnet *ifp,
1708     lwp_t *l)
1709 {
1710 	struct if_addrprefreq *ifap = (struct if_addrprefreq *)data;
1711 	struct ifaddr *ifa;
1712 	const struct sockaddr *any, *sa;
1713 	union {
1714 		struct sockaddr sa;
1715 		struct sockaddr_storage ss;
1716 	} u, v;
1717 
1718 	switch (cmd) {
1719 	case SIOCSIFADDRPREF:
1720 		if (kauth_authorize_network(l->l_cred, KAUTH_NETWORK_INTERFACE,
1721 		    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp, (void *)cmd,
1722 		    NULL) != 0)
1723 			return EPERM;
1724 	case SIOCGIFADDRPREF:
1725 		break;
1726 	default:
1727 		return EOPNOTSUPP;
1728 	}
1729 
1730 	/* sanity checks */
1731 	if (data == NULL || ifp == NULL) {
1732 		panic("invalid argument to %s", __func__);
1733 		/*NOTREACHED*/
1734 	}
1735 
1736 	/* address must be specified on ADD and DELETE */
1737 	sa = sstocsa(&ifap->ifap_addr);
1738 	if (sa->sa_family != sofamily(so))
1739 		return EINVAL;
1740 	if ((any = sockaddr_any(sa)) == NULL || sa->sa_len != any->sa_len)
1741 		return EINVAL;
1742 
1743 	sockaddr_externalize(&v.sa, sizeof(v.ss), sa);
1744 
1745 	IFADDR_FOREACH(ifa, ifp) {
1746 		if (ifa->ifa_addr->sa_family != sa->sa_family)
1747 			continue;
1748 		sockaddr_externalize(&u.sa, sizeof(u.ss), ifa->ifa_addr);
1749 		if (sockaddr_cmp(&u.sa, &v.sa) == 0)
1750 			break;
1751 	}
1752 	if (ifa == NULL)
1753 		return EADDRNOTAVAIL;
1754 
1755 	switch (cmd) {
1756 	case SIOCSIFADDRPREF:
1757 		ifa->ifa_preference = ifap->ifap_preference;
1758 		return 0;
1759 	case SIOCGIFADDRPREF:
1760 		/* fill in the if_laddrreq structure */
1761 		(void)sockaddr_copy(sstosa(&ifap->ifap_addr),
1762 		    sizeof(ifap->ifap_addr), ifa->ifa_addr);
1763 		ifap->ifap_preference = ifa->ifa_preference;
1764 		return 0;
1765 	default:
1766 		return EOPNOTSUPP;
1767 	}
1768 }
1769 
1770 static void
1771 ifnet_lock_enter(struct ifnet_lock *il)
1772 {
1773 	uint64_t *nenter;
1774 
1775 	/* Before trying to acquire the mutex, increase the count of threads
1776 	 * who have entered or who wait to enter the critical section.
1777 	 * Avoid one costly locked memory transaction by keeping a count for
1778 	 * each CPU.
1779 	 */
1780 	nenter = percpu_getref(il->il_nenter);
1781 	(*nenter)++;
1782 	percpu_putref(il->il_nenter);
1783 	mutex_enter(&il->il_lock);
1784 }
1785 
1786 static void
1787 ifnet_lock_exit(struct ifnet_lock *il)
1788 {
1789 	/* Increase the count of threads who have exited the critical
1790 	 * section.  Increase while we still hold the lock.
1791 	 */
1792 	il->il_nexit++;
1793 	mutex_exit(&il->il_lock);
1794 }
1795 
1796 /*
1797  * Interface ioctls.
1798  */
1799 static int
1800 doifioctl(struct socket *so, u_long cmd, void *data, struct lwp *l)
1801 {
1802 	struct ifnet *ifp;
1803 	struct ifreq *ifr;
1804 	int error = 0;
1805 #if defined(COMPAT_OSOCK) || defined(COMPAT_OIFREQ)
1806 	u_long ocmd = cmd;
1807 #endif
1808 	short oif_flags;
1809 #ifdef COMPAT_OIFREQ
1810 	struct ifreq ifrb;
1811 	struct oifreq *oifr = NULL;
1812 #endif
1813 
1814 	switch (cmd) {
1815 #ifdef COMPAT_OIFREQ
1816 	case OSIOCGIFCONF:
1817 	case OOSIOCGIFCONF:
1818 		return compat_ifconf(cmd, data);
1819 #endif
1820 #ifdef COMPAT_OIFDATA
1821 	case OSIOCGIFDATA:
1822 	case OSIOCZIFDATA:
1823 		return compat_ifdatareq(l, cmd, data);
1824 #endif
1825 	case SIOCGIFCONF:
1826 		return ifconf(cmd, data);
1827 	case SIOCINITIFADDR:
1828 		return EPERM;
1829 	}
1830 
1831 #ifdef COMPAT_OIFREQ
1832 	cmd = compat_cvtcmd(cmd);
1833 	if (cmd != ocmd) {
1834 		oifr = data;
1835 		data = ifr = &ifrb;
1836 		ifreqo2n(oifr, ifr);
1837 	} else
1838 #endif
1839 		ifr = data;
1840 
1841 	ifp = ifunit(ifr->ifr_name);
1842 
1843 	switch (cmd) {
1844 	case SIOCIFCREATE:
1845 	case SIOCIFDESTROY:
1846 		if (l != NULL) {
1847 			error = kauth_authorize_network(l->l_cred,
1848 			    KAUTH_NETWORK_INTERFACE,
1849 			    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp,
1850 			    (void *)cmd, NULL);
1851 			if (error != 0)
1852 				return error;
1853 		}
1854 		return (cmd == SIOCIFCREATE) ?
1855 			if_clone_create(ifr->ifr_name) :
1856 			if_clone_destroy(ifr->ifr_name);
1857 
1858 	case SIOCIFGCLONERS:
1859 		return if_clone_list((struct if_clonereq *)data);
1860 	}
1861 
1862 	if (ifp == NULL)
1863 		return ENXIO;
1864 
1865 	switch (cmd) {
1866 	case SIOCALIFADDR:
1867 	case SIOCDLIFADDR:
1868 	case SIOCSIFADDRPREF:
1869 	case SIOCSIFFLAGS:
1870 	case SIOCSIFCAP:
1871 	case SIOCSIFMETRIC:
1872 	case SIOCZIFDATA:
1873 	case SIOCSIFMTU:
1874 	case SIOCSIFPHYADDR:
1875 	case SIOCDIFPHYADDR:
1876 #ifdef INET6
1877 	case SIOCSIFPHYADDR_IN6:
1878 #endif
1879 	case SIOCSLIFPHYADDR:
1880 	case SIOCADDMULTI:
1881 	case SIOCDELMULTI:
1882 	case SIOCSIFMEDIA:
1883 	case SIOCSDRVSPEC:
1884 	case SIOCG80211:
1885 	case SIOCS80211:
1886 	case SIOCS80211NWID:
1887 	case SIOCS80211NWKEY:
1888 	case SIOCS80211POWER:
1889 	case SIOCS80211BSSID:
1890 	case SIOCS80211CHANNEL:
1891 	case SIOCSLINKSTR:
1892 		if (l != NULL) {
1893 			error = kauth_authorize_network(l->l_cred,
1894 			    KAUTH_NETWORK_INTERFACE,
1895 			    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp,
1896 			    (void *)cmd, NULL);
1897 			if (error != 0)
1898 				return error;
1899 		}
1900 	}
1901 
1902 	oif_flags = ifp->if_flags;
1903 
1904 	ifnet_lock_enter(ifp->if_ioctl_lock);
1905 	error = (*ifp->if_ioctl)(ifp, cmd, data);
1906 	if (error != ENOTTY)
1907 		;
1908 	else if (so->so_proto == NULL)
1909 		error = EOPNOTSUPP;
1910 	else {
1911 #ifdef COMPAT_OSOCK
1912 		error = compat_ifioctl(so, ocmd, cmd, data, l);
1913 #else
1914 		error = (*so->so_proto->pr_usrreqs->pr_generic)(so,
1915 		    PRU_CONTROL, (struct mbuf *)cmd, (struct mbuf *)data,
1916 		    (struct mbuf *)ifp, l);
1917 #endif
1918 	}
1919 
1920 	if (((oif_flags ^ ifp->if_flags) & IFF_UP) != 0) {
1921 #ifdef INET6
1922 		if (in6_present && (ifp->if_flags & IFF_UP) != 0) {
1923 			int s = splnet();
1924 			in6_if_up(ifp);
1925 			splx(s);
1926 		}
1927 #endif
1928 	}
1929 #ifdef COMPAT_OIFREQ
1930 	if (cmd != ocmd)
1931 		ifreqn2o(oifr, ifr);
1932 #endif
1933 
1934 	ifnet_lock_exit(ifp->if_ioctl_lock);
1935 	return error;
1936 }
1937 
1938 /* This callback adds to the sum in `arg' the number of
1939  * threads on `ci' who have entered or who wait to enter the
1940  * critical section.
1941  */
1942 static void
1943 ifnet_lock_sum(void *p, void *arg, struct cpu_info *ci)
1944 {
1945 	uint64_t *sum = arg, *nenter = p;
1946 
1947 	*sum += *nenter;
1948 }
1949 
1950 /* Return the number of threads who have entered or who wait
1951  * to enter the critical section on all CPUs.
1952  */
1953 static uint64_t
1954 ifnet_lock_entrances(struct ifnet_lock *il)
1955 {
1956 	uint64_t sum = 0;
1957 
1958 	percpu_foreach(il->il_nenter, ifnet_lock_sum, &sum);
1959 
1960 	return sum;
1961 }
1962 
1963 static int
1964 ifioctl_attach(struct ifnet *ifp)
1965 {
1966 	struct ifnet_lock *il;
1967 
1968 	/* If the driver has not supplied its own if_ioctl, then
1969 	 * supply the default.
1970 	 */
1971 	if (ifp->if_ioctl == NULL)
1972 		ifp->if_ioctl = ifioctl_common;
1973 
1974 	/* Create an ifnet_lock for synchronizing ifioctls. */
1975 	if ((il = kmem_zalloc(sizeof(*il), KM_SLEEP)) == NULL)
1976 		return ENOMEM;
1977 
1978 	il->il_nenter = percpu_alloc(sizeof(uint64_t));
1979 	if (il->il_nenter == NULL) {
1980 		kmem_free(il, sizeof(*il));
1981 		return ENOMEM;
1982 	}
1983 
1984 	mutex_init(&il->il_lock, MUTEX_DEFAULT, IPL_NONE);
1985 	cv_init(&il->il_emptied, ifp->if_xname);
1986 
1987 	ifp->if_ioctl_lock = il;
1988 
1989 	return 0;
1990 }
1991 
1992 /*
1993  * This must not be called until after `ifp' has been withdrawn from the
1994  * ifnet tables so that ifioctl() cannot get a handle on it by calling
1995  * ifunit().
1996  */
1997 static void
1998 ifioctl_detach(struct ifnet *ifp)
1999 {
2000 	struct ifnet_lock *il;
2001 
2002 	il = ifp->if_ioctl_lock;
2003 	mutex_enter(&il->il_lock);
2004 	/* Install if_nullioctl to make sure that any thread that
2005 	 * subsequently enters the critical section will quit it
2006 	 * immediately and signal the condition variable that we
2007 	 * wait on, below.
2008 	 */
2009 	ifp->if_ioctl = if_nullioctl;
2010 	/* Sleep while threads are still in the critical section or
2011 	 * wait to enter it.
2012 	 */
2013 	while (ifnet_lock_entrances(il) != il->il_nexit)
2014 		cv_wait(&il->il_emptied, &il->il_lock);
2015 	/* At this point, we are the only thread still in the critical
2016 	 * section, and no new thread can get a handle on the ifioctl
2017 	 * lock, so it is safe to free its memory.
2018 	 */
2019 	mutex_exit(&il->il_lock);
2020 	ifp->if_ioctl_lock = NULL;
2021 	percpu_free(il->il_nenter, sizeof(uint64_t));
2022 	il->il_nenter = NULL;
2023 	cv_destroy(&il->il_emptied);
2024 	mutex_destroy(&il->il_lock);
2025 	kmem_free(il, sizeof(*il));
2026 }
2027 
2028 /*
2029  * Return interface configuration
2030  * of system.  List may be used
2031  * in later ioctl's (above) to get
2032  * other information.
2033  *
2034  * Each record is a struct ifreq.  Before the addition of
2035  * sockaddr_storage, the API rule was that sockaddr flavors that did
2036  * not fit would extend beyond the struct ifreq, with the next struct
2037  * ifreq starting sa_len beyond the struct sockaddr.  Because the
2038  * union in struct ifreq includes struct sockaddr_storage, every kind
2039  * of sockaddr must fit.  Thus, there are no longer any overlength
2040  * records.
2041  *
2042  * Records are added to the user buffer if they fit, and ifc_len is
2043  * adjusted to the length that was written.  Thus, the user is only
2044  * assured of getting the complete list if ifc_len on return is at
2045  * least sizeof(struct ifreq) less than it was on entry.
2046  *
2047  * If the user buffer pointer is NULL, this routine copies no data and
2048  * returns the amount of space that would be needed.
2049  *
2050  * Invariants:
2051  * ifrp points to the next part of the user's buffer to be used.  If
2052  * ifrp != NULL, space holds the number of bytes remaining that we may
2053  * write at ifrp.  Otherwise, space holds the number of bytes that
2054  * would have been written had there been adequate space.
2055  */
2056 /*ARGSUSED*/
2057 int
2058 ifconf(u_long cmd, void *data)
2059 {
2060 	struct ifconf *ifc = (struct ifconf *)data;
2061 	struct ifnet *ifp;
2062 	struct ifaddr *ifa;
2063 	struct ifreq ifr, *ifrp;
2064 	int space, error = 0;
2065 	const int sz = (int)sizeof(struct ifreq);
2066 
2067 	if ((ifrp = ifc->ifc_req) == NULL)
2068 		space = 0;
2069 	else
2070 		space = ifc->ifc_len;
2071 	IFNET_FOREACH(ifp) {
2072 		(void)strncpy(ifr.ifr_name, ifp->if_xname,
2073 		    sizeof(ifr.ifr_name));
2074 		if (ifr.ifr_name[sizeof(ifr.ifr_name) - 1] != '\0')
2075 			return ENAMETOOLONG;
2076 		if (IFADDR_EMPTY(ifp)) {
2077 			/* Interface with no addresses - send zero sockaddr. */
2078 			memset(&ifr.ifr_addr, 0, sizeof(ifr.ifr_addr));
2079 			if (ifrp == NULL) {
2080 				space += sz;
2081 				continue;
2082 			}
2083 			if (space >= sz) {
2084 				error = copyout(&ifr, ifrp, sz);
2085 				if (error != 0)
2086 					return error;
2087 				ifrp++;
2088 				space -= sz;
2089 			}
2090 		}
2091 
2092 		IFADDR_FOREACH(ifa, ifp) {
2093 			struct sockaddr *sa = ifa->ifa_addr;
2094 			/* all sockaddrs must fit in sockaddr_storage */
2095 			KASSERT(sa->sa_len <= sizeof(ifr.ifr_ifru));
2096 
2097 			if (ifrp == NULL) {
2098 				space += sz;
2099 				continue;
2100 			}
2101 			memcpy(&ifr.ifr_space, sa, sa->sa_len);
2102 			if (space >= sz) {
2103 				error = copyout(&ifr, ifrp, sz);
2104 				if (error != 0)
2105 					return (error);
2106 				ifrp++; space -= sz;
2107 			}
2108 		}
2109 	}
2110 	if (ifrp != NULL) {
2111 		KASSERT(0 <= space && space <= ifc->ifc_len);
2112 		ifc->ifc_len -= space;
2113 	} else {
2114 		KASSERT(space >= 0);
2115 		ifc->ifc_len = space;
2116 	}
2117 	return (0);
2118 }
2119 
2120 int
2121 ifreq_setaddr(u_long cmd, struct ifreq *ifr, const struct sockaddr *sa)
2122 {
2123 	uint8_t len;
2124 #ifdef COMPAT_OIFREQ
2125 	struct ifreq ifrb;
2126 	struct oifreq *oifr = NULL;
2127 	u_long ocmd = cmd;
2128 	cmd = compat_cvtcmd(cmd);
2129 	if (cmd != ocmd) {
2130 		oifr = (struct oifreq *)(void *)ifr;
2131 		ifr = &ifrb;
2132 		ifreqo2n(oifr, ifr);
2133 		len = sizeof(oifr->ifr_addr);
2134 	} else
2135 #endif
2136 		len = sizeof(ifr->ifr_ifru.ifru_space);
2137 
2138 	if (len < sa->sa_len)
2139 		return EFBIG;
2140 
2141 	memset(&ifr->ifr_addr, 0, len);
2142 	sockaddr_copy(&ifr->ifr_addr, len, sa);
2143 
2144 #ifdef COMPAT_OIFREQ
2145 	if (cmd != ocmd)
2146 		ifreqn2o(oifr, ifr);
2147 #endif
2148 	return 0;
2149 }
2150 
2151 /*
2152  * Queue message on interface, and start output if interface
2153  * not yet active.
2154  */
2155 int
2156 ifq_enqueue(struct ifnet *ifp, struct mbuf *m
2157     ALTQ_COMMA ALTQ_DECL(struct altq_pktattr *pktattr))
2158 {
2159 	int len = m->m_pkthdr.len;
2160 	int mflags = m->m_flags;
2161 	int s = splnet();
2162 	int error;
2163 
2164 	IFQ_ENQUEUE(&ifp->if_snd, m, pktattr, error);
2165 	if (error != 0)
2166 		goto out;
2167 	ifp->if_obytes += len;
2168 	if (mflags & M_MCAST)
2169 		ifp->if_omcasts++;
2170 	if ((ifp->if_flags & IFF_OACTIVE) == 0)
2171 		(*ifp->if_start)(ifp);
2172 out:
2173 	splx(s);
2174 	return error;
2175 }
2176 
2177 /*
2178  * Queue message on interface, possibly using a second fast queue
2179  */
2180 int
2181 ifq_enqueue2(struct ifnet *ifp, struct ifqueue *ifq, struct mbuf *m
2182     ALTQ_COMMA ALTQ_DECL(struct altq_pktattr *pktattr))
2183 {
2184 	int error = 0;
2185 
2186 	if (ifq != NULL
2187 #ifdef ALTQ
2188 	    && ALTQ_IS_ENABLED(&ifp->if_snd) == 0
2189 #endif
2190 	    ) {
2191 		if (IF_QFULL(ifq)) {
2192 			IF_DROP(&ifp->if_snd);
2193 			m_freem(m);
2194 			if (error == 0)
2195 				error = ENOBUFS;
2196 		} else
2197 			IF_ENQUEUE(ifq, m);
2198 	} else
2199 		IFQ_ENQUEUE(&ifp->if_snd, m, pktattr, error);
2200 	if (error != 0) {
2201 		++ifp->if_oerrors;
2202 		return error;
2203 	}
2204 	return 0;
2205 }
2206 
2207 int
2208 if_addr_init(ifnet_t *ifp, struct ifaddr *ifa, const bool src)
2209 {
2210 	int rc;
2211 
2212 	if (ifp->if_initaddr != NULL)
2213 		rc = (*ifp->if_initaddr)(ifp, ifa, src);
2214 	else if (src ||
2215 	         (rc = (*ifp->if_ioctl)(ifp, SIOCSIFDSTADDR, ifa)) == ENOTTY)
2216 		rc = (*ifp->if_ioctl)(ifp, SIOCINITIFADDR, ifa);
2217 
2218 	return rc;
2219 }
2220 
2221 int
2222 if_flags_set(ifnet_t *ifp, const short flags)
2223 {
2224 	int rc;
2225 
2226 	if (ifp->if_setflags != NULL)
2227 		rc = (*ifp->if_setflags)(ifp, flags);
2228 	else {
2229 		short cantflags, chgdflags;
2230 		struct ifreq ifr;
2231 
2232 		chgdflags = ifp->if_flags ^ flags;
2233 		cantflags = chgdflags & IFF_CANTCHANGE;
2234 
2235 		if (cantflags != 0)
2236 			ifp->if_flags ^= cantflags;
2237 
2238                 /* Traditionally, we do not call if_ioctl after
2239                  * setting/clearing only IFF_PROMISC if the interface
2240                  * isn't IFF_UP.  Uphold that tradition.
2241 		 */
2242 		if (chgdflags == IFF_PROMISC && (ifp->if_flags & IFF_UP) == 0)
2243 			return 0;
2244 
2245 		memset(&ifr, 0, sizeof(ifr));
2246 
2247 		ifr.ifr_flags = flags & ~IFF_CANTCHANGE;
2248 		rc = (*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, &ifr);
2249 
2250 		if (rc != 0 && cantflags != 0)
2251 			ifp->if_flags ^= cantflags;
2252 	}
2253 
2254 	return rc;
2255 }
2256 
2257 int
2258 if_mcast_op(ifnet_t *ifp, const unsigned long cmd, const struct sockaddr *sa)
2259 {
2260 	int rc;
2261 	struct ifreq ifr;
2262 
2263 	if (ifp->if_mcastop != NULL)
2264 		rc = (*ifp->if_mcastop)(ifp, cmd, sa);
2265 	else {
2266 		ifreq_setaddr(cmd, &ifr, sa);
2267 		rc = (*ifp->if_ioctl)(ifp, cmd, &ifr);
2268 	}
2269 
2270 	return rc;
2271 }
2272 
2273 static void
2274 sysctl_sndq_setup(struct sysctllog **clog, const char *ifname,
2275     struct ifaltq *ifq)
2276 {
2277 	const struct sysctlnode *cnode, *rnode;
2278 
2279 	if (sysctl_createv(clog, 0, NULL, &rnode,
2280 		       CTLFLAG_PERMANENT,
2281 		       CTLTYPE_NODE, "interfaces",
2282 		       SYSCTL_DESCR("Per-interface controls"),
2283 		       NULL, 0, NULL, 0,
2284 		       CTL_NET, CTL_CREATE, CTL_EOL) != 0)
2285 		goto bad;
2286 
2287 	if (sysctl_createv(clog, 0, &rnode, &rnode,
2288 		       CTLFLAG_PERMANENT,
2289 		       CTLTYPE_NODE, ifname,
2290 		       SYSCTL_DESCR("Interface controls"),
2291 		       NULL, 0, NULL, 0,
2292 		       CTL_CREATE, CTL_EOL) != 0)
2293 		goto bad;
2294 
2295 	if (sysctl_createv(clog, 0, &rnode, &rnode,
2296 		       CTLFLAG_PERMANENT,
2297 		       CTLTYPE_NODE, "sndq",
2298 		       SYSCTL_DESCR("Interface output queue controls"),
2299 		       NULL, 0, NULL, 0,
2300 		       CTL_CREATE, CTL_EOL) != 0)
2301 		goto bad;
2302 
2303 	if (sysctl_createv(clog, 0, &rnode, &cnode,
2304 		       CTLFLAG_PERMANENT,
2305 		       CTLTYPE_INT, "len",
2306 		       SYSCTL_DESCR("Current output queue length"),
2307 		       NULL, 0, &ifq->ifq_len, 0,
2308 		       CTL_CREATE, CTL_EOL) != 0)
2309 		goto bad;
2310 
2311 	if (sysctl_createv(clog, 0, &rnode, &cnode,
2312 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
2313 		       CTLTYPE_INT, "maxlen",
2314 		       SYSCTL_DESCR("Maximum allowed output queue length"),
2315 		       NULL, 0, &ifq->ifq_maxlen, 0,
2316 		       CTL_CREATE, CTL_EOL) != 0)
2317 		goto bad;
2318 
2319 	if (sysctl_createv(clog, 0, &rnode, &cnode,
2320 		       CTLFLAG_PERMANENT,
2321 		       CTLTYPE_INT, "drops",
2322 		       SYSCTL_DESCR("Packets dropped due to full output queue"),
2323 		       NULL, 0, &ifq->ifq_drops, 0,
2324 		       CTL_CREATE, CTL_EOL) != 0)
2325 		goto bad;
2326 
2327 	return;
2328 bad:
2329 	printf("%s: could not attach sysctl nodes\n", ifname);
2330 	return;
2331 }
2332 
2333 #if defined(INET) || defined(INET6)
2334 static void
2335 sysctl_net_ifq_setup(struct sysctllog **clog,
2336 		     int pf, const char *pfname,
2337 		     int ipn, const char *ipname,
2338 		     int qid, struct ifqueue *ifq)
2339 {
2340 
2341 	sysctl_createv(clog, 0, NULL, NULL,
2342 		       CTLFLAG_PERMANENT,
2343 		       CTLTYPE_NODE, pfname, NULL,
2344 		       NULL, 0, NULL, 0,
2345 		       CTL_NET, pf, CTL_EOL);
2346 	sysctl_createv(clog, 0, NULL, NULL,
2347 		       CTLFLAG_PERMANENT,
2348 		       CTLTYPE_NODE, ipname, NULL,
2349 		       NULL, 0, NULL, 0,
2350 		       CTL_NET, pf, ipn, CTL_EOL);
2351 	sysctl_createv(clog, 0, NULL, NULL,
2352 		       CTLFLAG_PERMANENT,
2353 		       CTLTYPE_NODE, "ifq",
2354 		       SYSCTL_DESCR("Protocol input queue controls"),
2355 		       NULL, 0, NULL, 0,
2356 		       CTL_NET, pf, ipn, qid, CTL_EOL);
2357 
2358 	sysctl_createv(clog, 0, NULL, NULL,
2359 		       CTLFLAG_PERMANENT,
2360 		       CTLTYPE_INT, "len",
2361 		       SYSCTL_DESCR("Current input queue length"),
2362 		       NULL, 0, &ifq->ifq_len, 0,
2363 		       CTL_NET, pf, ipn, qid, IFQCTL_LEN, CTL_EOL);
2364 	sysctl_createv(clog, 0, NULL, NULL,
2365 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
2366 		       CTLTYPE_INT, "maxlen",
2367 		       SYSCTL_DESCR("Maximum allowed input queue length"),
2368 		       NULL, 0, &ifq->ifq_maxlen, 0,
2369 		       CTL_NET, pf, ipn, qid, IFQCTL_MAXLEN, CTL_EOL);
2370 #ifdef notyet
2371 	sysctl_createv(clog, 0, NULL, NULL,
2372 		       CTLFLAG_PERMANENT,
2373 		       CTLTYPE_INT, "peak",
2374 		       SYSCTL_DESCR("Highest input queue length"),
2375 		       NULL, 0, &ifq->ifq_peak, 0,
2376 		       CTL_NET, pf, ipn, qid, IFQCTL_PEAK, CTL_EOL);
2377 #endif
2378 	sysctl_createv(clog, 0, NULL, NULL,
2379 		       CTLFLAG_PERMANENT,
2380 		       CTLTYPE_INT, "drops",
2381 		       SYSCTL_DESCR("Packets dropped due to full input queue"),
2382 		       NULL, 0, &ifq->ifq_drops, 0,
2383 		       CTL_NET, pf, ipn, qid, IFQCTL_DROPS, CTL_EOL);
2384 }
2385 #endif /* INET || INET6 */
2386