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