xref: /netbsd-src/sys/net/if.c (revision 975a152cfcdb39ae6e496af647af0c7275ca0b61)
1 /*	$NetBSD: if.c,v 1.265 2013/06/29 21:06:58 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.265 2013/06/29 21:06:58 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/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 old_link_state, s;
1327 
1328 	s = splnet();
1329 	if (ifp->if_link_state == link_state) {
1330 		splx(s);
1331 		return;
1332 	}
1333 
1334 	old_link_state = ifp->if_link_state;
1335 	ifp->if_link_state = link_state;
1336 #ifdef DEBUG
1337 	log(LOG_DEBUG, "%s: link state %s (was %s)\n", ifp->if_xname,
1338 		link_state == LINK_STATE_UP ? "UP" :
1339 		link_state == LINK_STATE_DOWN ? "DOWN" :
1340 		"UNKNOWN",
1341 		 old_link_state == LINK_STATE_UP ? "UP" :
1342 		old_link_state == LINK_STATE_DOWN ? "DOWN" :
1343 		"UNKNOWN");
1344 #endif
1345 
1346 #ifdef INET6
1347 	/*
1348 	 * When going from UNKNOWN to UP, we need to mark existing
1349 	 * IPv6 addresses as tentative and restart DAD as we may have
1350 	 * erroneously not found a duplicate.
1351 	 *
1352 	 * This needs to happen before rt_ifmsg to avoid a race where
1353 	 * listeners would have an address and expect it to work right
1354 	 * away.
1355 	 */
1356 	if (link_state == LINK_STATE_UP &&
1357 	    old_link_state == LINK_STATE_UNKNOWN)
1358 		in6_if_link_down(ifp);
1359 #endif
1360 
1361 	/* Notify that the link state has changed. */
1362 	rt_ifmsg(ifp);
1363 
1364 #if NCARP > 0
1365 	if (ifp->if_carp)
1366 		carp_carpdev_state(ifp);
1367 #endif
1368 
1369 #ifdef INET6
1370 	if (link_state == LINK_STATE_DOWN)
1371 		in6_if_link_down(ifp);
1372 	else if (link_state == LINK_STATE_UP)
1373 		in6_if_link_up(ifp);
1374 #endif
1375 
1376 	splx(s);
1377 }
1378 
1379 /*
1380  * Mark an interface down and notify protocols of
1381  * the transition.
1382  * NOTE: must be called at splsoftnet or equivalent.
1383  */
1384 void
1385 if_down(struct ifnet *ifp)
1386 {
1387 	struct ifaddr *ifa;
1388 
1389 	ifp->if_flags &= ~IFF_UP;
1390 	nanotime(&ifp->if_lastchange);
1391 	IFADDR_FOREACH(ifa, ifp)
1392 		pfctlinput(PRC_IFDOWN, ifa->ifa_addr);
1393 	IFQ_PURGE(&ifp->if_snd);
1394 #if NCARP > 0
1395 	if (ifp->if_carp)
1396 		carp_carpdev_state(ifp);
1397 #endif
1398 	rt_ifmsg(ifp);
1399 #ifdef INET6
1400 	in6_if_down(ifp);
1401 #endif
1402 }
1403 
1404 /*
1405  * Mark an interface up and notify protocols of
1406  * the transition.
1407  * NOTE: must be called at splsoftnet or equivalent.
1408  */
1409 void
1410 if_up(struct ifnet *ifp)
1411 {
1412 #ifdef notyet
1413 	struct ifaddr *ifa;
1414 #endif
1415 
1416 	ifp->if_flags |= IFF_UP;
1417 	nanotime(&ifp->if_lastchange);
1418 #ifdef notyet
1419 	/* this has no effect on IP, and will kill all ISO connections XXX */
1420 	IFADDR_FOREACH(ifa, ifp)
1421 		pfctlinput(PRC_IFUP, ifa->ifa_addr);
1422 #endif
1423 #if NCARP > 0
1424 	if (ifp->if_carp)
1425 		carp_carpdev_state(ifp);
1426 #endif
1427 	rt_ifmsg(ifp);
1428 #ifdef INET6
1429 	in6_if_up(ifp);
1430 #endif
1431 }
1432 
1433 /*
1434  * Handle interface watchdog timer routines.  Called
1435  * from softclock, we decrement timers (if set) and
1436  * call the appropriate interface routine on expiration.
1437  */
1438 void
1439 if_slowtimo(void *arg)
1440 {
1441 	struct ifnet *ifp;
1442 	int s = splnet();
1443 
1444 	IFNET_FOREACH(ifp) {
1445 		if (ifp->if_timer == 0 || --ifp->if_timer)
1446 			continue;
1447 		if (ifp->if_watchdog != NULL)
1448 			(*ifp->if_watchdog)(ifp);
1449 	}
1450 	splx(s);
1451 	callout_reset(&if_slowtimo_ch, hz / IFNET_SLOWHZ, if_slowtimo, NULL);
1452 }
1453 
1454 /*
1455  * Set/clear promiscuous mode on interface ifp based on the truth value
1456  * of pswitch.  The calls are reference counted so that only the first
1457  * "on" request actually has an effect, as does the final "off" request.
1458  * Results are undefined if the "off" and "on" requests are not matched.
1459  */
1460 int
1461 ifpromisc(struct ifnet *ifp, int pswitch)
1462 {
1463 	int pcount, ret;
1464 	short nflags;
1465 
1466 	pcount = ifp->if_pcount;
1467 	if (pswitch) {
1468 		/*
1469 		 * Allow the device to be "placed" into promiscuous
1470 		 * mode even if it is not configured up.  It will
1471 		 * consult IFF_PROMISC when it is brought up.
1472 		 */
1473 		if (ifp->if_pcount++ != 0)
1474 			return 0;
1475 		nflags = ifp->if_flags | IFF_PROMISC;
1476 	} else {
1477 		if (--ifp->if_pcount > 0)
1478 			return 0;
1479 		nflags = ifp->if_flags & ~IFF_PROMISC;
1480 	}
1481 	ret = if_flags_set(ifp, nflags);
1482 	/* Restore interface state if not successful. */
1483 	if (ret != 0) {
1484 		ifp->if_pcount = pcount;
1485 	}
1486 	return ret;
1487 }
1488 
1489 /*
1490  * Map interface name to
1491  * interface structure pointer.
1492  */
1493 struct ifnet *
1494 ifunit(const char *name)
1495 {
1496 	struct ifnet *ifp;
1497 	const char *cp = name;
1498 	u_int unit = 0;
1499 	u_int i;
1500 
1501 	/*
1502 	 * If the entire name is a number, treat it as an ifindex.
1503 	 */
1504 	for (i = 0; i < IFNAMSIZ && *cp >= '0' && *cp <= '9'; i++, cp++) {
1505 		unit = unit * 10 + (*cp - '0');
1506 	}
1507 
1508 	/*
1509 	 * If the number took all of the name, then it's a valid ifindex.
1510 	 */
1511 	if (i == IFNAMSIZ || (cp != name && *cp == '\0')) {
1512 		if (unit >= if_indexlim)
1513 			return NULL;
1514 		ifp = ifindex2ifnet[unit];
1515 		if (ifp == NULL || ifp->if_output == if_nulloutput)
1516 			return NULL;
1517 		return ifp;
1518 	}
1519 
1520 	IFNET_FOREACH(ifp) {
1521 		if (ifp->if_output == if_nulloutput)
1522 			continue;
1523 	 	if (strcmp(ifp->if_xname, name) == 0)
1524 			return ifp;
1525 	}
1526 	return NULL;
1527 }
1528 
1529 ifnet_t *
1530 if_byindex(u_int idx)
1531 {
1532 
1533 	return (idx < if_indexlim) ? ifindex2ifnet[idx] : NULL;
1534 }
1535 
1536 /* common */
1537 int
1538 ifioctl_common(struct ifnet *ifp, u_long cmd, void *data)
1539 {
1540 	int s;
1541 	struct ifreq *ifr;
1542 	struct ifcapreq *ifcr;
1543 	struct ifdatareq *ifdr;
1544 
1545 	switch (cmd) {
1546 	case SIOCSIFCAP:
1547 		ifcr = data;
1548 		if ((ifcr->ifcr_capenable & ~ifp->if_capabilities) != 0)
1549 			return EINVAL;
1550 
1551 		if (ifcr->ifcr_capenable == ifp->if_capenable)
1552 			return 0;
1553 
1554 		ifp->if_capenable = ifcr->ifcr_capenable;
1555 
1556 		/* Pre-compute the checksum flags mask. */
1557 		ifp->if_csum_flags_tx = 0;
1558 		ifp->if_csum_flags_rx = 0;
1559 		if (ifp->if_capenable & IFCAP_CSUM_IPv4_Tx) {
1560 			ifp->if_csum_flags_tx |= M_CSUM_IPv4;
1561 		}
1562 		if (ifp->if_capenable & IFCAP_CSUM_IPv4_Rx) {
1563 			ifp->if_csum_flags_rx |= M_CSUM_IPv4;
1564 		}
1565 
1566 		if (ifp->if_capenable & IFCAP_CSUM_TCPv4_Tx) {
1567 			ifp->if_csum_flags_tx |= M_CSUM_TCPv4;
1568 		}
1569 		if (ifp->if_capenable & IFCAP_CSUM_TCPv4_Rx) {
1570 			ifp->if_csum_flags_rx |= M_CSUM_TCPv4;
1571 		}
1572 
1573 		if (ifp->if_capenable & IFCAP_CSUM_UDPv4_Tx) {
1574 			ifp->if_csum_flags_tx |= M_CSUM_UDPv4;
1575 		}
1576 		if (ifp->if_capenable & IFCAP_CSUM_UDPv4_Rx) {
1577 			ifp->if_csum_flags_rx |= M_CSUM_UDPv4;
1578 		}
1579 
1580 		if (ifp->if_capenable & IFCAP_CSUM_TCPv6_Tx) {
1581 			ifp->if_csum_flags_tx |= M_CSUM_TCPv6;
1582 		}
1583 		if (ifp->if_capenable & IFCAP_CSUM_TCPv6_Rx) {
1584 			ifp->if_csum_flags_rx |= M_CSUM_TCPv6;
1585 		}
1586 
1587 		if (ifp->if_capenable & IFCAP_CSUM_UDPv6_Tx) {
1588 			ifp->if_csum_flags_tx |= M_CSUM_UDPv6;
1589 		}
1590 		if (ifp->if_capenable & IFCAP_CSUM_UDPv6_Rx) {
1591 			ifp->if_csum_flags_rx |= M_CSUM_UDPv6;
1592 		}
1593 		if (ifp->if_flags & IFF_UP)
1594 			return ENETRESET;
1595 		return 0;
1596 	case SIOCSIFFLAGS:
1597 		ifr = data;
1598 		if (ifp->if_flags & IFF_UP && (ifr->ifr_flags & IFF_UP) == 0) {
1599 			s = splnet();
1600 			if_down(ifp);
1601 			splx(s);
1602 		}
1603 		if (ifr->ifr_flags & IFF_UP && (ifp->if_flags & IFF_UP) == 0) {
1604 			s = splnet();
1605 			if_up(ifp);
1606 			splx(s);
1607 		}
1608 		ifp->if_flags = (ifp->if_flags & IFF_CANTCHANGE) |
1609 			(ifr->ifr_flags &~ IFF_CANTCHANGE);
1610 		break;
1611 	case SIOCGIFFLAGS:
1612 		ifr = data;
1613 		ifr->ifr_flags = ifp->if_flags;
1614 		break;
1615 
1616 	case SIOCGIFMETRIC:
1617 		ifr = data;
1618 		ifr->ifr_metric = ifp->if_metric;
1619 		break;
1620 
1621 	case SIOCGIFMTU:
1622 		ifr = data;
1623 		ifr->ifr_mtu = ifp->if_mtu;
1624 		break;
1625 
1626 	case SIOCGIFDLT:
1627 		ifr = data;
1628 		ifr->ifr_dlt = ifp->if_dlt;
1629 		break;
1630 
1631 	case SIOCGIFCAP:
1632 		ifcr = data;
1633 		ifcr->ifcr_capabilities = ifp->if_capabilities;
1634 		ifcr->ifcr_capenable = ifp->if_capenable;
1635 		break;
1636 
1637 	case SIOCSIFMETRIC:
1638 		ifr = data;
1639 		ifp->if_metric = ifr->ifr_metric;
1640 		break;
1641 
1642 	case SIOCGIFDATA:
1643 		ifdr = data;
1644 		ifdr->ifdr_data = ifp->if_data;
1645 		break;
1646 
1647 	case SIOCZIFDATA:
1648 		ifdr = data;
1649 		ifdr->ifdr_data = ifp->if_data;
1650 		/*
1651 		 * Assumes that the volatile counters that can be
1652 		 * zero'ed are at the end of if_data.
1653 		 */
1654 		memset(&ifp->if_data.ifi_ipackets, 0, sizeof(ifp->if_data) -
1655 		    offsetof(struct if_data, ifi_ipackets));
1656 		/*
1657 		 * The memset() clears to the bottm of if_data. In the area,
1658 		 * if_lastchange is included. Please be careful if new entry
1659 		 * will be added into if_data or rewite this.
1660 		 *
1661 		 * And also, update if_lastchnage.
1662 		 */
1663 		getnanotime(&ifp->if_lastchange);
1664 		break;
1665 	case SIOCSIFMTU:
1666 		ifr = data;
1667 		if (ifp->if_mtu == ifr->ifr_mtu)
1668 			break;
1669 		ifp->if_mtu = ifr->ifr_mtu;
1670 		/*
1671 		 * If the link MTU changed, do network layer specific procedure.
1672 		 */
1673 #ifdef INET6
1674 		nd6_setmtu(ifp);
1675 #endif
1676 		return ENETRESET;
1677 	default:
1678 		return ENOTTY;
1679 	}
1680 	return 0;
1681 }
1682 
1683 int
1684 ifaddrpref_ioctl(struct socket *so, u_long cmd, void *data, struct ifnet *ifp,
1685     lwp_t *l)
1686 {
1687 	struct if_addrprefreq *ifap = (struct if_addrprefreq *)data;
1688 	struct ifaddr *ifa;
1689 	const struct sockaddr *any, *sa;
1690 	union {
1691 		struct sockaddr sa;
1692 		struct sockaddr_storage ss;
1693 	} u, v;
1694 
1695 	switch (cmd) {
1696 	case SIOCSIFADDRPREF:
1697 		if (kauth_authorize_network(l->l_cred, KAUTH_NETWORK_INTERFACE,
1698 		    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp, (void *)cmd,
1699 		    NULL) != 0)
1700 			return EPERM;
1701 	case SIOCGIFADDRPREF:
1702 		break;
1703 	default:
1704 		return EOPNOTSUPP;
1705 	}
1706 
1707 	/* sanity checks */
1708 	if (data == NULL || ifp == NULL) {
1709 		panic("invalid argument to %s", __func__);
1710 		/*NOTREACHED*/
1711 	}
1712 
1713 	/* address must be specified on ADD and DELETE */
1714 	sa = sstocsa(&ifap->ifap_addr);
1715 	if (sa->sa_family != sofamily(so))
1716 		return EINVAL;
1717 	if ((any = sockaddr_any(sa)) == NULL || sa->sa_len != any->sa_len)
1718 		return EINVAL;
1719 
1720 	sockaddr_externalize(&v.sa, sizeof(v.ss), sa);
1721 
1722 	IFADDR_FOREACH(ifa, ifp) {
1723 		if (ifa->ifa_addr->sa_family != sa->sa_family)
1724 			continue;
1725 		sockaddr_externalize(&u.sa, sizeof(u.ss), ifa->ifa_addr);
1726 		if (sockaddr_cmp(&u.sa, &v.sa) == 0)
1727 			break;
1728 	}
1729 	if (ifa == NULL)
1730 		return EADDRNOTAVAIL;
1731 
1732 	switch (cmd) {
1733 	case SIOCSIFADDRPREF:
1734 		ifa->ifa_preference = ifap->ifap_preference;
1735 		return 0;
1736 	case SIOCGIFADDRPREF:
1737 		/* fill in the if_laddrreq structure */
1738 		(void)sockaddr_copy(sstosa(&ifap->ifap_addr),
1739 		    sizeof(ifap->ifap_addr), ifa->ifa_addr);
1740 		ifap->ifap_preference = ifa->ifa_preference;
1741 		return 0;
1742 	default:
1743 		return EOPNOTSUPP;
1744 	}
1745 }
1746 
1747 static void
1748 ifnet_lock_enter(struct ifnet_lock *il)
1749 {
1750 	uint64_t *nenter;
1751 
1752 	/* Before trying to acquire the mutex, increase the count of threads
1753 	 * who have entered or who wait to enter the critical section.
1754 	 * Avoid one costly locked memory transaction by keeping a count for
1755 	 * each CPU.
1756 	 */
1757 	nenter = percpu_getref(il->il_nenter);
1758 	(*nenter)++;
1759 	percpu_putref(il->il_nenter);
1760 	mutex_enter(&il->il_lock);
1761 }
1762 
1763 static void
1764 ifnet_lock_exit(struct ifnet_lock *il)
1765 {
1766 	/* Increase the count of threads who have exited the critical
1767 	 * section.  Increase while we still hold the lock.
1768 	 */
1769 	il->il_nexit++;
1770 	mutex_exit(&il->il_lock);
1771 }
1772 
1773 /*
1774  * Interface ioctls.
1775  */
1776 int
1777 ifioctl(struct socket *so, u_long cmd, void *data, struct lwp *l)
1778 {
1779 	struct ifnet *ifp;
1780 	struct ifreq *ifr;
1781 	int error = 0;
1782 #if defined(COMPAT_OSOCK) || defined(COMPAT_OIFREQ)
1783 	u_long ocmd = cmd;
1784 #endif
1785 	short oif_flags;
1786 #ifdef COMPAT_OIFREQ
1787 	struct ifreq ifrb;
1788 	struct oifreq *oifr = NULL;
1789 #endif
1790 
1791 	switch (cmd) {
1792 #ifdef COMPAT_OIFREQ
1793 	case OSIOCGIFCONF:
1794 	case OOSIOCGIFCONF:
1795 		return compat_ifconf(cmd, data);
1796 #endif
1797 #ifdef COMPAT_OIFDATA
1798 	case OSIOCGIFDATA:
1799 	case OSIOCZIFDATA:
1800 		return compat_ifdatareq(l, cmd, data);
1801 #endif
1802 	case SIOCGIFCONF:
1803 		return ifconf(cmd, data);
1804 	case SIOCINITIFADDR:
1805 		return EPERM;
1806 	}
1807 
1808 #ifdef COMPAT_OIFREQ
1809 	cmd = compat_cvtcmd(cmd);
1810 	if (cmd != ocmd) {
1811 		oifr = data;
1812 		data = ifr = &ifrb;
1813 		ifreqo2n(oifr, ifr);
1814 	} else
1815 #endif
1816 		ifr = data;
1817 
1818 	ifp = ifunit(ifr->ifr_name);
1819 
1820 	switch (cmd) {
1821 	case SIOCIFCREATE:
1822 	case SIOCIFDESTROY:
1823 		if (l != NULL) {
1824 			error = kauth_authorize_network(l->l_cred,
1825 			    KAUTH_NETWORK_INTERFACE,
1826 			    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp,
1827 			    (void *)cmd, NULL);
1828 			if (error != 0)
1829 				return error;
1830 		}
1831 		return (cmd == SIOCIFCREATE) ?
1832 			if_clone_create(ifr->ifr_name) :
1833 			if_clone_destroy(ifr->ifr_name);
1834 
1835 	case SIOCIFGCLONERS:
1836 		return if_clone_list((struct if_clonereq *)data);
1837 	}
1838 
1839 	if (ifp == NULL)
1840 		return ENXIO;
1841 
1842 	switch (cmd) {
1843 	case SIOCALIFADDR:
1844 	case SIOCDLIFADDR:
1845 	case SIOCSIFADDRPREF:
1846 	case SIOCSIFFLAGS:
1847 	case SIOCSIFCAP:
1848 	case SIOCSIFMETRIC:
1849 	case SIOCZIFDATA:
1850 	case SIOCSIFMTU:
1851 	case SIOCSIFPHYADDR:
1852 	case SIOCDIFPHYADDR:
1853 #ifdef INET6
1854 	case SIOCSIFPHYADDR_IN6:
1855 #endif
1856 	case SIOCSLIFPHYADDR:
1857 	case SIOCADDMULTI:
1858 	case SIOCDELMULTI:
1859 	case SIOCSIFMEDIA:
1860 	case SIOCSDRVSPEC:
1861 	case SIOCG80211:
1862 	case SIOCS80211:
1863 	case SIOCS80211NWID:
1864 	case SIOCS80211NWKEY:
1865 	case SIOCS80211POWER:
1866 	case SIOCS80211BSSID:
1867 	case SIOCS80211CHANNEL:
1868 	case SIOCSLINKSTR:
1869 		if (l != NULL) {
1870 			error = kauth_authorize_network(l->l_cred,
1871 			    KAUTH_NETWORK_INTERFACE,
1872 			    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp,
1873 			    (void *)cmd, NULL);
1874 			if (error != 0)
1875 				return error;
1876 		}
1877 	}
1878 
1879 	oif_flags = ifp->if_flags;
1880 
1881 	ifnet_lock_enter(ifp->if_ioctl_lock);
1882 	error = (*ifp->if_ioctl)(ifp, cmd, data);
1883 	if (error != ENOTTY)
1884 		;
1885 	else if (so->so_proto == NULL)
1886 		error = EOPNOTSUPP;
1887 	else {
1888 #ifdef COMPAT_OSOCK
1889 		error = compat_ifioctl(so, ocmd, cmd, data, l);
1890 #else
1891 		error = (*so->so_proto->pr_usrreq)(so, PRU_CONTROL,
1892 		    (struct mbuf *)cmd, (struct mbuf *)data,
1893 		    (struct mbuf *)ifp, l);
1894 #endif
1895 	}
1896 
1897 	if (((oif_flags ^ ifp->if_flags) & IFF_UP) != 0) {
1898 #ifdef INET6
1899 		if ((ifp->if_flags & IFF_UP) != 0) {
1900 			int s = splnet();
1901 			in6_if_up(ifp);
1902 			splx(s);
1903 		}
1904 #endif
1905 	}
1906 #ifdef COMPAT_OIFREQ
1907 	if (cmd != ocmd)
1908 		ifreqn2o(oifr, ifr);
1909 #endif
1910 
1911 	ifnet_lock_exit(ifp->if_ioctl_lock);
1912 	return error;
1913 }
1914 
1915 /* This callback adds to the sum in `arg' the number of
1916  * threads on `ci' who have entered or who wait to enter the
1917  * critical section.
1918  */
1919 static void
1920 ifnet_lock_sum(void *p, void *arg, struct cpu_info *ci)
1921 {
1922 	uint64_t *sum = arg, *nenter = p;
1923 
1924 	*sum += *nenter;
1925 }
1926 
1927 /* Return the number of threads who have entered or who wait
1928  * to enter the critical section on all CPUs.
1929  */
1930 static uint64_t
1931 ifnet_lock_entrances(struct ifnet_lock *il)
1932 {
1933 	uint64_t sum = 0;
1934 
1935 	percpu_foreach(il->il_nenter, ifnet_lock_sum, &sum);
1936 
1937 	return sum;
1938 }
1939 
1940 static int
1941 ifioctl_attach(struct ifnet *ifp)
1942 {
1943 	struct ifnet_lock *il;
1944 
1945 	/* If the driver has not supplied its own if_ioctl, then
1946 	 * supply the default.
1947 	 */
1948 	if (ifp->if_ioctl == NULL)
1949 		ifp->if_ioctl = ifioctl_common;
1950 
1951 	/* Create an ifnet_lock for synchronizing ifioctls. */
1952 	if ((il = kmem_zalloc(sizeof(*il), KM_SLEEP)) == NULL)
1953 		return ENOMEM;
1954 
1955 	il->il_nenter = percpu_alloc(sizeof(uint64_t));
1956 	if (il->il_nenter == NULL) {
1957 		kmem_free(il, sizeof(*il));
1958 		return ENOMEM;
1959 	}
1960 
1961 	mutex_init(&il->il_lock, MUTEX_DEFAULT, IPL_NONE);
1962 	cv_init(&il->il_emptied, ifp->if_xname);
1963 
1964 	ifp->if_ioctl_lock = il;
1965 
1966 	return 0;
1967 }
1968 
1969 /*
1970  * This must not be called until after `ifp' has been withdrawn from the
1971  * ifnet tables so that ifioctl() cannot get a handle on it by calling
1972  * ifunit().
1973  */
1974 static void
1975 ifioctl_detach(struct ifnet *ifp)
1976 {
1977 	struct ifnet_lock *il;
1978 
1979 	il = ifp->if_ioctl_lock;
1980 	mutex_enter(&il->il_lock);
1981 	/* Install if_nullioctl to make sure that any thread that
1982 	 * subsequently enters the critical section will quit it
1983 	 * immediately and signal the condition variable that we
1984 	 * wait on, below.
1985 	 */
1986 	ifp->if_ioctl = if_nullioctl;
1987 	/* Sleep while threads are still in the critical section or
1988 	 * wait to enter it.
1989 	 */
1990 	while (ifnet_lock_entrances(il) != il->il_nexit)
1991 		cv_wait(&il->il_emptied, &il->il_lock);
1992 	/* At this point, we are the only thread still in the critical
1993 	 * section, and no new thread can get a handle on the ifioctl
1994 	 * lock, so it is safe to free its memory.
1995 	 */
1996 	mutex_exit(&il->il_lock);
1997 	ifp->if_ioctl_lock = NULL;
1998 	percpu_free(il->il_nenter, sizeof(uint64_t));
1999 	il->il_nenter = NULL;
2000 	cv_destroy(&il->il_emptied);
2001 	mutex_destroy(&il->il_lock);
2002 	kmem_free(il, sizeof(*il));
2003 }
2004 
2005 /*
2006  * Return interface configuration
2007  * of system.  List may be used
2008  * in later ioctl's (above) to get
2009  * other information.
2010  *
2011  * Each record is a struct ifreq.  Before the addition of
2012  * sockaddr_storage, the API rule was that sockaddr flavors that did
2013  * not fit would extend beyond the struct ifreq, with the next struct
2014  * ifreq starting sa_len beyond the struct sockaddr.  Because the
2015  * union in struct ifreq includes struct sockaddr_storage, every kind
2016  * of sockaddr must fit.  Thus, there are no longer any overlength
2017  * records.
2018  *
2019  * Records are added to the user buffer if they fit, and ifc_len is
2020  * adjusted to the length that was written.  Thus, the user is only
2021  * assured of getting the complete list if ifc_len on return is at
2022  * least sizeof(struct ifreq) less than it was on entry.
2023  *
2024  * If the user buffer pointer is NULL, this routine copies no data and
2025  * returns the amount of space that would be needed.
2026  *
2027  * Invariants:
2028  * ifrp points to the next part of the user's buffer to be used.  If
2029  * ifrp != NULL, space holds the number of bytes remaining that we may
2030  * write at ifrp.  Otherwise, space holds the number of bytes that
2031  * would have been written had there been adequate space.
2032  */
2033 /*ARGSUSED*/
2034 int
2035 ifconf(u_long cmd, void *data)
2036 {
2037 	struct ifconf *ifc = (struct ifconf *)data;
2038 	struct ifnet *ifp;
2039 	struct ifaddr *ifa;
2040 	struct ifreq ifr, *ifrp;
2041 	int space, error = 0;
2042 	const int sz = (int)sizeof(struct ifreq);
2043 
2044 	if ((ifrp = ifc->ifc_req) == NULL)
2045 		space = 0;
2046 	else
2047 		space = ifc->ifc_len;
2048 	IFNET_FOREACH(ifp) {
2049 		(void)strncpy(ifr.ifr_name, ifp->if_xname,
2050 		    sizeof(ifr.ifr_name));
2051 		if (ifr.ifr_name[sizeof(ifr.ifr_name) - 1] != '\0')
2052 			return ENAMETOOLONG;
2053 		if (IFADDR_EMPTY(ifp)) {
2054 			/* Interface with no addresses - send zero sockaddr. */
2055 			memset(&ifr.ifr_addr, 0, sizeof(ifr.ifr_addr));
2056 			if (ifrp == NULL) {
2057 				space += sz;
2058 				continue;
2059 			}
2060 			if (space >= sz) {
2061 				error = copyout(&ifr, ifrp, sz);
2062 				if (error != 0)
2063 					return error;
2064 				ifrp++;
2065 				space -= sz;
2066 			}
2067 		}
2068 
2069 		IFADDR_FOREACH(ifa, ifp) {
2070 			struct sockaddr *sa = ifa->ifa_addr;
2071 			/* all sockaddrs must fit in sockaddr_storage */
2072 			KASSERT(sa->sa_len <= sizeof(ifr.ifr_ifru));
2073 
2074 			if (ifrp == NULL) {
2075 				space += sz;
2076 				continue;
2077 			}
2078 			memcpy(&ifr.ifr_space, sa, sa->sa_len);
2079 			if (space >= sz) {
2080 				error = copyout(&ifr, ifrp, sz);
2081 				if (error != 0)
2082 					return (error);
2083 				ifrp++; space -= sz;
2084 			}
2085 		}
2086 	}
2087 	if (ifrp != NULL) {
2088 		KASSERT(0 <= space && space <= ifc->ifc_len);
2089 		ifc->ifc_len -= space;
2090 	} else {
2091 		KASSERT(space >= 0);
2092 		ifc->ifc_len = space;
2093 	}
2094 	return (0);
2095 }
2096 
2097 int
2098 ifreq_setaddr(u_long cmd, struct ifreq *ifr, const struct sockaddr *sa)
2099 {
2100 	uint8_t len;
2101 #ifdef COMPAT_OIFREQ
2102 	struct ifreq ifrb;
2103 	struct oifreq *oifr = NULL;
2104 	u_long ocmd = cmd;
2105 	cmd = compat_cvtcmd(cmd);
2106 	if (cmd != ocmd) {
2107 		oifr = (struct oifreq *)(void *)ifr;
2108 		ifr = &ifrb;
2109 		ifreqo2n(oifr, ifr);
2110 		len = sizeof(oifr->ifr_addr);
2111 	} else
2112 #endif
2113 		len = sizeof(ifr->ifr_ifru.ifru_space);
2114 
2115 	if (len < sa->sa_len)
2116 		return EFBIG;
2117 
2118 	memset(&ifr->ifr_addr, 0, len);
2119 	sockaddr_copy(&ifr->ifr_addr, len, sa);
2120 
2121 #ifdef COMPAT_OIFREQ
2122 	if (cmd != ocmd)
2123 		ifreqn2o(oifr, ifr);
2124 #endif
2125 	return 0;
2126 }
2127 
2128 /*
2129  * Queue message on interface, and start output if interface
2130  * not yet active.
2131  */
2132 int
2133 ifq_enqueue(struct ifnet *ifp, struct mbuf *m
2134     ALTQ_COMMA ALTQ_DECL(struct altq_pktattr *pktattr))
2135 {
2136 	int len = m->m_pkthdr.len;
2137 	int mflags = m->m_flags;
2138 	int s = splnet();
2139 	int error;
2140 
2141 	IFQ_ENQUEUE(&ifp->if_snd, m, pktattr, error);
2142 	if (error != 0)
2143 		goto out;
2144 	ifp->if_obytes += len;
2145 	if (mflags & M_MCAST)
2146 		ifp->if_omcasts++;
2147 	if ((ifp->if_flags & IFF_OACTIVE) == 0)
2148 		(*ifp->if_start)(ifp);
2149 out:
2150 	splx(s);
2151 	return error;
2152 }
2153 
2154 /*
2155  * Queue message on interface, possibly using a second fast queue
2156  */
2157 int
2158 ifq_enqueue2(struct ifnet *ifp, struct ifqueue *ifq, struct mbuf *m
2159     ALTQ_COMMA ALTQ_DECL(struct altq_pktattr *pktattr))
2160 {
2161 	int error = 0;
2162 
2163 	if (ifq != NULL
2164 #ifdef ALTQ
2165 	    && ALTQ_IS_ENABLED(&ifp->if_snd) == 0
2166 #endif
2167 	    ) {
2168 		if (IF_QFULL(ifq)) {
2169 			IF_DROP(&ifp->if_snd);
2170 			m_freem(m);
2171 			if (error == 0)
2172 				error = ENOBUFS;
2173 		} else
2174 			IF_ENQUEUE(ifq, m);
2175 	} else
2176 		IFQ_ENQUEUE(&ifp->if_snd, m, pktattr, error);
2177 	if (error != 0) {
2178 		++ifp->if_oerrors;
2179 		return error;
2180 	}
2181 	return 0;
2182 }
2183 
2184 int
2185 if_addr_init(ifnet_t *ifp, struct ifaddr *ifa, const bool src)
2186 {
2187 	int rc;
2188 
2189 	if (ifp->if_initaddr != NULL)
2190 		rc = (*ifp->if_initaddr)(ifp, ifa, src);
2191 	else if (src ||
2192 	         (rc = (*ifp->if_ioctl)(ifp, SIOCSIFDSTADDR, ifa)) == ENOTTY)
2193 		rc = (*ifp->if_ioctl)(ifp, SIOCINITIFADDR, ifa);
2194 
2195 	return rc;
2196 }
2197 
2198 int
2199 if_flags_set(ifnet_t *ifp, const short flags)
2200 {
2201 	int rc;
2202 
2203 	if (ifp->if_setflags != NULL)
2204 		rc = (*ifp->if_setflags)(ifp, flags);
2205 	else {
2206 		short cantflags, chgdflags;
2207 		struct ifreq ifr;
2208 
2209 		chgdflags = ifp->if_flags ^ flags;
2210 		cantflags = chgdflags & IFF_CANTCHANGE;
2211 
2212 		if (cantflags != 0)
2213 			ifp->if_flags ^= cantflags;
2214 
2215                 /* Traditionally, we do not call if_ioctl after
2216                  * setting/clearing only IFF_PROMISC if the interface
2217                  * isn't IFF_UP.  Uphold that tradition.
2218 		 */
2219 		if (chgdflags == IFF_PROMISC && (ifp->if_flags & IFF_UP) == 0)
2220 			return 0;
2221 
2222 		memset(&ifr, 0, sizeof(ifr));
2223 
2224 		ifr.ifr_flags = flags & ~IFF_CANTCHANGE;
2225 		rc = (*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, &ifr);
2226 
2227 		if (rc != 0 && cantflags != 0)
2228 			ifp->if_flags ^= cantflags;
2229 	}
2230 
2231 	return rc;
2232 }
2233 
2234 int
2235 if_mcast_op(ifnet_t *ifp, const unsigned long cmd, const struct sockaddr *sa)
2236 {
2237 	int rc;
2238 	struct ifreq ifr;
2239 
2240 	if (ifp->if_mcastop != NULL)
2241 		rc = (*ifp->if_mcastop)(ifp, cmd, sa);
2242 	else {
2243 		ifreq_setaddr(cmd, &ifr, sa);
2244 		rc = (*ifp->if_ioctl)(ifp, cmd, &ifr);
2245 	}
2246 
2247 	return rc;
2248 }
2249 
2250 static void
2251 sysctl_sndq_setup(struct sysctllog **clog, const char *ifname,
2252     struct ifaltq *ifq)
2253 {
2254 	const struct sysctlnode *cnode, *rnode;
2255 
2256 	if (sysctl_createv(clog, 0, NULL, &rnode,
2257 		       CTLFLAG_PERMANENT,
2258 		       CTLTYPE_NODE, "net", NULL,
2259 		       NULL, 0, NULL, 0,
2260 		       CTL_NET, CTL_EOL) != 0)
2261 		goto bad;
2262 
2263 	if (sysctl_createv(clog, 0, &rnode, &rnode,
2264 		       CTLFLAG_PERMANENT,
2265 		       CTLTYPE_NODE, "interfaces",
2266 		       SYSCTL_DESCR("Per-interface controls"),
2267 		       NULL, 0, NULL, 0,
2268 		       CTL_CREATE, CTL_EOL) != 0)
2269 		goto bad;
2270 
2271 	if (sysctl_createv(clog, 0, &rnode, &rnode,
2272 		       CTLFLAG_PERMANENT,
2273 		       CTLTYPE_NODE, ifname,
2274 		       SYSCTL_DESCR("Interface controls"),
2275 		       NULL, 0, NULL, 0,
2276 		       CTL_CREATE, CTL_EOL) != 0)
2277 		goto bad;
2278 
2279 	if (sysctl_createv(clog, 0, &rnode, &rnode,
2280 		       CTLFLAG_PERMANENT,
2281 		       CTLTYPE_NODE, "sndq",
2282 		       SYSCTL_DESCR("Interface output queue controls"),
2283 		       NULL, 0, NULL, 0,
2284 		       CTL_CREATE, CTL_EOL) != 0)
2285 		goto bad;
2286 
2287 	if (sysctl_createv(clog, 0, &rnode, &cnode,
2288 		       CTLFLAG_PERMANENT,
2289 		       CTLTYPE_INT, "len",
2290 		       SYSCTL_DESCR("Current output queue length"),
2291 		       NULL, 0, &ifq->ifq_len, 0,
2292 		       CTL_CREATE, CTL_EOL) != 0)
2293 		goto bad;
2294 
2295 	if (sysctl_createv(clog, 0, &rnode, &cnode,
2296 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
2297 		       CTLTYPE_INT, "maxlen",
2298 		       SYSCTL_DESCR("Maximum allowed output queue length"),
2299 		       NULL, 0, &ifq->ifq_maxlen, 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, "drops",
2306 		       SYSCTL_DESCR("Packets dropped due to full output queue"),
2307 		       NULL, 0, &ifq->ifq_drops, 0,
2308 		       CTL_CREATE, CTL_EOL) != 0)
2309 		goto bad;
2310 
2311 	return;
2312 bad:
2313 	printf("%s: could not attach sysctl nodes\n", ifname);
2314 	return;
2315 }
2316 
2317 #if defined(INET) || defined(INET6)
2318 static void
2319 sysctl_net_ifq_setup(struct sysctllog **clog,
2320 		     int pf, const char *pfname,
2321 		     int ipn, const char *ipname,
2322 		     int qid, struct ifqueue *ifq)
2323 {
2324 
2325 	sysctl_createv(clog, 0, NULL, NULL,
2326 		       CTLFLAG_PERMANENT,
2327 		       CTLTYPE_NODE, "net", NULL,
2328 		       NULL, 0, NULL, 0,
2329 		       CTL_NET, CTL_EOL);
2330 	sysctl_createv(clog, 0, NULL, NULL,
2331 		       CTLFLAG_PERMANENT,
2332 		       CTLTYPE_NODE, pfname, NULL,
2333 		       NULL, 0, NULL, 0,
2334 		       CTL_NET, pf, CTL_EOL);
2335 	sysctl_createv(clog, 0, NULL, NULL,
2336 		       CTLFLAG_PERMANENT,
2337 		       CTLTYPE_NODE, ipname, NULL,
2338 		       NULL, 0, NULL, 0,
2339 		       CTL_NET, pf, ipn, CTL_EOL);
2340 	sysctl_createv(clog, 0, NULL, NULL,
2341 		       CTLFLAG_PERMANENT,
2342 		       CTLTYPE_NODE, "ifq",
2343 		       SYSCTL_DESCR("Protocol input queue controls"),
2344 		       NULL, 0, NULL, 0,
2345 		       CTL_NET, pf, ipn, qid, CTL_EOL);
2346 
2347 	sysctl_createv(clog, 0, NULL, NULL,
2348 		       CTLFLAG_PERMANENT,
2349 		       CTLTYPE_INT, "len",
2350 		       SYSCTL_DESCR("Current input queue length"),
2351 		       NULL, 0, &ifq->ifq_len, 0,
2352 		       CTL_NET, pf, ipn, qid, IFQCTL_LEN, CTL_EOL);
2353 	sysctl_createv(clog, 0, NULL, NULL,
2354 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
2355 		       CTLTYPE_INT, "maxlen",
2356 		       SYSCTL_DESCR("Maximum allowed input queue length"),
2357 		       NULL, 0, &ifq->ifq_maxlen, 0,
2358 		       CTL_NET, pf, ipn, qid, IFQCTL_MAXLEN, CTL_EOL);
2359 #ifdef notyet
2360 	sysctl_createv(clog, 0, NULL, NULL,
2361 		       CTLFLAG_PERMANENT,
2362 		       CTLTYPE_INT, "peak",
2363 		       SYSCTL_DESCR("Highest input queue length"),
2364 		       NULL, 0, &ifq->ifq_peak, 0,
2365 		       CTL_NET, pf, ipn, qid, IFQCTL_PEAK, CTL_EOL);
2366 #endif
2367 	sysctl_createv(clog, 0, NULL, NULL,
2368 		       CTLFLAG_PERMANENT,
2369 		       CTLTYPE_INT, "drops",
2370 		       SYSCTL_DESCR("Packets dropped due to full input queue"),
2371 		       NULL, 0, &ifq->ifq_drops, 0,
2372 		       CTL_NET, pf, ipn, qid, IFQCTL_DROPS, CTL_EOL);
2373 }
2374 #endif /* INET || INET6 */
2375