xref: /freebsd/sys/net/if.c (revision 8d20be1e22095c27faf8fe8b2f0d089739cc742e)
1 /*-
2  * Copyright (c) 1980, 1986, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *	@(#)if.c	8.5 (Berkeley) 1/9/95
30  * $FreeBSD$
31  */
32 
33 #include "opt_compat.h"
34 #include "opt_inet6.h"
35 #include "opt_inet.h"
36 
37 #include <sys/param.h>
38 #include <sys/types.h>
39 #include <sys/conf.h>
40 #include <sys/malloc.h>
41 #include <sys/sbuf.h>
42 #include <sys/bus.h>
43 #include <sys/mbuf.h>
44 #include <sys/systm.h>
45 #include <sys/priv.h>
46 #include <sys/proc.h>
47 #include <sys/socket.h>
48 #include <sys/socketvar.h>
49 #include <sys/protosw.h>
50 #include <sys/kernel.h>
51 #include <sys/lock.h>
52 #include <sys/refcount.h>
53 #include <sys/module.h>
54 #include <sys/rwlock.h>
55 #include <sys/sockio.h>
56 #include <sys/syslog.h>
57 #include <sys/sysctl.h>
58 #include <sys/taskqueue.h>
59 #include <sys/domain.h>
60 #include <sys/jail.h>
61 #include <sys/priv.h>
62 
63 #include <machine/stdarg.h>
64 #include <vm/uma.h>
65 
66 #include <net/if.h>
67 #include <net/if_arp.h>
68 #include <net/if_clone.h>
69 #include <net/if_dl.h>
70 #include <net/if_types.h>
71 #include <net/if_var.h>
72 #include <net/radix.h>
73 #include <net/route.h>
74 #include <net/vnet.h>
75 
76 #if defined(INET) || defined(INET6)
77 #include <netinet/in.h>
78 #include <netinet/in_var.h>
79 #include <netinet/ip.h>
80 #include <netinet/ip_carp.h>
81 #ifdef INET
82 #include <netinet/if_ether.h>
83 #endif /* INET */
84 #ifdef INET6
85 #include <netinet6/in6_var.h>
86 #include <netinet6/in6_ifattach.h>
87 #endif /* INET6 */
88 #endif /* INET || INET6 */
89 
90 #include <security/mac/mac_framework.h>
91 
92 #ifdef COMPAT_FREEBSD32
93 #include <sys/mount.h>
94 #include <compat/freebsd32/freebsd32.h>
95 #endif
96 
97 struct ifindex_entry {
98 	struct  ifnet *ife_ifnet;
99 };
100 
101 SYSCTL_NODE(_net, PF_LINK, link, CTLFLAG_RW, 0, "Link layers");
102 SYSCTL_NODE(_net_link, 0, generic, CTLFLAG_RW, 0, "Generic link-management");
103 
104 TUNABLE_INT("net.link.ifqmaxlen", &ifqmaxlen);
105 SYSCTL_INT(_net_link, OID_AUTO, ifqmaxlen, CTLFLAG_RDTUN,
106     &ifqmaxlen, 0, "max send queue size");
107 
108 /* Log link state change events */
109 static int log_link_state_change = 1;
110 
111 SYSCTL_INT(_net_link, OID_AUTO, log_link_state_change, CTLFLAG_RW,
112 	&log_link_state_change, 0,
113 	"log interface link state change events");
114 
115 /* Interface description */
116 static unsigned int ifdescr_maxlen = 1024;
117 SYSCTL_UINT(_net, OID_AUTO, ifdescr_maxlen, CTLFLAG_RW,
118 	&ifdescr_maxlen, 0,
119 	"administrative maximum length for interface description");
120 
121 static MALLOC_DEFINE(M_IFDESCR, "ifdescr", "ifnet descriptions");
122 
123 /* global sx for non-critical path ifdescr */
124 static struct sx ifdescr_sx;
125 SX_SYSINIT(ifdescr_sx, &ifdescr_sx, "ifnet descr");
126 
127 void	(*bridge_linkstate_p)(struct ifnet *ifp);
128 void	(*ng_ether_link_state_p)(struct ifnet *ifp, int state);
129 void	(*lagg_linkstate_p)(struct ifnet *ifp, int state);
130 /* These are external hooks for CARP. */
131 void	(*carp_linkstate_p)(struct ifnet *ifp);
132 void	(*carp_demote_adj_p)(int, char *);
133 int	(*carp_master_p)(struct ifaddr *);
134 #if defined(INET) || defined(INET6)
135 int	(*carp_forus_p)(struct ifnet *ifp, u_char *dhost);
136 int	(*carp_output_p)(struct ifnet *ifp, struct mbuf *m,
137     const struct sockaddr *sa);
138 int	(*carp_ioctl_p)(struct ifreq *, u_long, struct thread *);
139 int	(*carp_attach_p)(struct ifaddr *, int);
140 void	(*carp_detach_p)(struct ifaddr *);
141 #endif
142 #ifdef INET
143 int	(*carp_iamatch_p)(struct ifaddr *, uint8_t **);
144 #endif
145 #ifdef INET6
146 struct ifaddr *(*carp_iamatch6_p)(struct ifnet *ifp, struct in6_addr *taddr6);
147 caddr_t	(*carp_macmatch6_p)(struct ifnet *ifp, struct mbuf *m,
148     const struct in6_addr *taddr);
149 #endif
150 
151 struct mbuf *(*tbr_dequeue_ptr)(struct ifaltq *, int) = NULL;
152 
153 /*
154  * XXX: Style; these should be sorted alphabetically, and unprototyped
155  * static functions should be prototyped. Currently they are sorted by
156  * declaration order.
157  */
158 static void	if_attachdomain(void *);
159 static void	if_attachdomain1(struct ifnet *);
160 static int	ifconf(u_long, caddr_t);
161 static void	if_freemulti(struct ifmultiaddr *);
162 static void	if_init(void *);
163 static void	if_grow(void);
164 static void	if_route(struct ifnet *, int flag, int fam);
165 static int	if_setflag(struct ifnet *, int, int, int *, int);
166 static int	if_transmit(struct ifnet *ifp, struct mbuf *m);
167 static void	if_unroute(struct ifnet *, int flag, int fam);
168 static void	link_rtrequest(int, struct rtentry *, struct rt_addrinfo *);
169 static int	if_rtdel(struct radix_node *, void *);
170 static int	ifhwioctl(u_long, struct ifnet *, caddr_t, struct thread *);
171 static int	if_delmulti_locked(struct ifnet *, struct ifmultiaddr *, int);
172 static void	do_link_state_change(void *, int);
173 static int	if_getgroup(struct ifgroupreq *, struct ifnet *);
174 static int	if_getgroupmembers(struct ifgroupreq *);
175 static void	if_delgroups(struct ifnet *);
176 static void	if_attach_internal(struct ifnet *, int);
177 static void	if_detach_internal(struct ifnet *, int);
178 
179 #ifdef INET6
180 /*
181  * XXX: declare here to avoid to include many inet6 related files..
182  * should be more generalized?
183  */
184 extern void	nd6_setmtu(struct ifnet *);
185 #endif
186 
187 VNET_DEFINE(int, if_index);
188 int	ifqmaxlen = IFQ_MAXLEN;
189 VNET_DEFINE(struct ifnethead, ifnet);	/* depend on static init XXX */
190 VNET_DEFINE(struct ifgrouphead, ifg_head);
191 
192 static VNET_DEFINE(int, if_indexlim) = 8;
193 
194 /* Table of ifnet by index. */
195 VNET_DEFINE(struct ifindex_entry *, ifindex_table);
196 
197 #define	V_if_indexlim		VNET(if_indexlim)
198 #define	V_ifindex_table		VNET(ifindex_table)
199 
200 /*
201  * The global network interface list (V_ifnet) and related state (such as
202  * if_index, if_indexlim, and ifindex_table) are protected by an sxlock and
203  * an rwlock.  Either may be acquired shared to stablize the list, but both
204  * must be acquired writable to modify the list.  This model allows us to
205  * both stablize the interface list during interrupt thread processing, but
206  * also to stablize it over long-running ioctls, without introducing priority
207  * inversions and deadlocks.
208  */
209 struct rwlock ifnet_rwlock;
210 struct sx ifnet_sxlock;
211 
212 /*
213  * The allocation of network interfaces is a rather non-atomic affair; we
214  * need to select an index before we are ready to expose the interface for
215  * use, so will use this pointer value to indicate reservation.
216  */
217 #define	IFNET_HOLD	(void *)(uintptr_t)(-1)
218 
219 static	if_com_alloc_t *if_com_alloc[256];
220 static	if_com_free_t *if_com_free[256];
221 
222 static MALLOC_DEFINE(M_IFNET, "ifnet", "interface internals");
223 MALLOC_DEFINE(M_IFADDR, "ifaddr", "interface address");
224 MALLOC_DEFINE(M_IFMADDR, "ether_multi", "link-level multicast address");
225 
226 struct ifnet *
227 ifnet_byindex_locked(u_short idx)
228 {
229 
230 	if (idx > V_if_index)
231 		return (NULL);
232 	if (V_ifindex_table[idx].ife_ifnet == IFNET_HOLD)
233 		return (NULL);
234 	return (V_ifindex_table[idx].ife_ifnet);
235 }
236 
237 struct ifnet *
238 ifnet_byindex(u_short idx)
239 {
240 	struct ifnet *ifp;
241 
242 	IFNET_RLOCK_NOSLEEP();
243 	ifp = ifnet_byindex_locked(idx);
244 	IFNET_RUNLOCK_NOSLEEP();
245 	return (ifp);
246 }
247 
248 struct ifnet *
249 ifnet_byindex_ref(u_short idx)
250 {
251 	struct ifnet *ifp;
252 
253 	IFNET_RLOCK_NOSLEEP();
254 	ifp = ifnet_byindex_locked(idx);
255 	if (ifp == NULL || (ifp->if_flags & IFF_DYING)) {
256 		IFNET_RUNLOCK_NOSLEEP();
257 		return (NULL);
258 	}
259 	if_ref(ifp);
260 	IFNET_RUNLOCK_NOSLEEP();
261 	return (ifp);
262 }
263 
264 /*
265  * Allocate an ifindex array entry; return 0 on success or an error on
266  * failure.
267  */
268 static int
269 ifindex_alloc_locked(u_short *idxp)
270 {
271 	u_short idx;
272 
273 	IFNET_WLOCK_ASSERT();
274 
275 retry:
276 	/*
277 	 * Try to find an empty slot below V_if_index.  If we fail, take the
278 	 * next slot.
279 	 */
280 	for (idx = 1; idx <= V_if_index; idx++) {
281 		if (V_ifindex_table[idx].ife_ifnet == NULL)
282 			break;
283 	}
284 
285 	/* Catch if_index overflow. */
286 	if (idx < 1)
287 		return (ENOSPC);
288 	if (idx >= V_if_indexlim) {
289 		if_grow();
290 		goto retry;
291 	}
292 	if (idx > V_if_index)
293 		V_if_index = idx;
294 	*idxp = idx;
295 	return (0);
296 }
297 
298 static void
299 ifindex_free_locked(u_short idx)
300 {
301 
302 	IFNET_WLOCK_ASSERT();
303 
304 	V_ifindex_table[idx].ife_ifnet = NULL;
305 	while (V_if_index > 0 &&
306 	    V_ifindex_table[V_if_index].ife_ifnet == NULL)
307 		V_if_index--;
308 }
309 
310 static void
311 ifindex_free(u_short idx)
312 {
313 
314 	IFNET_WLOCK();
315 	ifindex_free_locked(idx);
316 	IFNET_WUNLOCK();
317 }
318 
319 static void
320 ifnet_setbyindex_locked(u_short idx, struct ifnet *ifp)
321 {
322 
323 	IFNET_WLOCK_ASSERT();
324 
325 	V_ifindex_table[idx].ife_ifnet = ifp;
326 }
327 
328 static void
329 ifnet_setbyindex(u_short idx, struct ifnet *ifp)
330 {
331 
332 	IFNET_WLOCK();
333 	ifnet_setbyindex_locked(idx, ifp);
334 	IFNET_WUNLOCK();
335 }
336 
337 struct ifaddr *
338 ifaddr_byindex(u_short idx)
339 {
340 	struct ifaddr *ifa;
341 
342 	IFNET_RLOCK_NOSLEEP();
343 	ifa = ifnet_byindex_locked(idx)->if_addr;
344 	if (ifa != NULL)
345 		ifa_ref(ifa);
346 	IFNET_RUNLOCK_NOSLEEP();
347 	return (ifa);
348 }
349 
350 /*
351  * Network interface utility routines.
352  *
353  * Routines with ifa_ifwith* names take sockaddr *'s as
354  * parameters.
355  */
356 
357 static void
358 vnet_if_init(const void *unused __unused)
359 {
360 
361 	TAILQ_INIT(&V_ifnet);
362 	TAILQ_INIT(&V_ifg_head);
363 	IFNET_WLOCK();
364 	if_grow();				/* create initial table */
365 	IFNET_WUNLOCK();
366 	vnet_if_clone_init();
367 }
368 VNET_SYSINIT(vnet_if_init, SI_SUB_INIT_IF, SI_ORDER_SECOND, vnet_if_init,
369     NULL);
370 
371 /* ARGSUSED*/
372 static void
373 if_init(void *dummy __unused)
374 {
375 
376 	IFNET_LOCK_INIT();
377 	if_clone_init();
378 }
379 SYSINIT(interfaces, SI_SUB_INIT_IF, SI_ORDER_FIRST, if_init, NULL);
380 
381 
382 #ifdef VIMAGE
383 static void
384 vnet_if_uninit(const void *unused __unused)
385 {
386 
387 	VNET_ASSERT(TAILQ_EMPTY(&V_ifnet), ("%s:%d tailq &V_ifnet=%p "
388 	    "not empty", __func__, __LINE__, &V_ifnet));
389 	VNET_ASSERT(TAILQ_EMPTY(&V_ifg_head), ("%s:%d tailq &V_ifg_head=%p "
390 	    "not empty", __func__, __LINE__, &V_ifg_head));
391 
392 	free((caddr_t)V_ifindex_table, M_IFNET);
393 }
394 VNET_SYSUNINIT(vnet_if_uninit, SI_SUB_INIT_IF, SI_ORDER_FIRST,
395     vnet_if_uninit, NULL);
396 #endif
397 
398 static void
399 if_grow(void)
400 {
401 	int oldlim;
402 	u_int n;
403 	struct ifindex_entry *e;
404 
405 	IFNET_WLOCK_ASSERT();
406 	oldlim = V_if_indexlim;
407 	IFNET_WUNLOCK();
408 	n = (oldlim << 1) * sizeof(*e);
409 	e = malloc(n, M_IFNET, M_WAITOK | M_ZERO);
410 	IFNET_WLOCK();
411 	if (V_if_indexlim != oldlim) {
412 		free(e, M_IFNET);
413 		return;
414 	}
415 	if (V_ifindex_table != NULL) {
416 		memcpy((caddr_t)e, (caddr_t)V_ifindex_table, n/2);
417 		free((caddr_t)V_ifindex_table, M_IFNET);
418 	}
419 	V_if_indexlim <<= 1;
420 	V_ifindex_table = e;
421 }
422 
423 /*
424  * Allocate a struct ifnet and an index for an interface.  A layer 2
425  * common structure will also be allocated if an allocation routine is
426  * registered for the passed type.
427  */
428 struct ifnet *
429 if_alloc(u_char type)
430 {
431 	struct ifnet *ifp;
432 	u_short idx;
433 
434 	ifp = malloc(sizeof(struct ifnet), M_IFNET, M_WAITOK|M_ZERO);
435 	IFNET_WLOCK();
436 	if (ifindex_alloc_locked(&idx) != 0) {
437 		IFNET_WUNLOCK();
438 		free(ifp, M_IFNET);
439 		return (NULL);
440 	}
441 	ifnet_setbyindex_locked(idx, IFNET_HOLD);
442 	IFNET_WUNLOCK();
443 	ifp->if_index = idx;
444 	ifp->if_type = type;
445 	ifp->if_alloctype = type;
446 	if (if_com_alloc[type] != NULL) {
447 		ifp->if_l2com = if_com_alloc[type](type, ifp);
448 		if (ifp->if_l2com == NULL) {
449 			free(ifp, M_IFNET);
450 			ifindex_free(idx);
451 			return (NULL);
452 		}
453 	}
454 
455 	IF_ADDR_LOCK_INIT(ifp);
456 	TASK_INIT(&ifp->if_linktask, 0, do_link_state_change, ifp);
457 	ifp->if_afdata_initialized = 0;
458 	IF_AFDATA_LOCK_INIT(ifp);
459 	TAILQ_INIT(&ifp->if_addrhead);
460 	TAILQ_INIT(&ifp->if_multiaddrs);
461 	TAILQ_INIT(&ifp->if_groups);
462 #ifdef MAC
463 	mac_ifnet_init(ifp);
464 #endif
465 	ifq_init(&ifp->if_snd, ifp);
466 
467 	refcount_init(&ifp->if_refcount, 1);	/* Index reference. */
468 	ifnet_setbyindex(ifp->if_index, ifp);
469 	return (ifp);
470 }
471 
472 /*
473  * Do the actual work of freeing a struct ifnet, and layer 2 common
474  * structure.  This call is made when the last reference to an
475  * interface is released.
476  */
477 static void
478 if_free_internal(struct ifnet *ifp)
479 {
480 
481 	KASSERT((ifp->if_flags & IFF_DYING),
482 	    ("if_free_internal: interface not dying"));
483 
484 	if (if_com_free[ifp->if_alloctype] != NULL)
485 		if_com_free[ifp->if_alloctype](ifp->if_l2com,
486 		    ifp->if_alloctype);
487 
488 #ifdef MAC
489 	mac_ifnet_destroy(ifp);
490 #endif /* MAC */
491 	if (ifp->if_description != NULL)
492 		free(ifp->if_description, M_IFDESCR);
493 	IF_AFDATA_DESTROY(ifp);
494 	IF_ADDR_LOCK_DESTROY(ifp);
495 	ifq_delete(&ifp->if_snd);
496 	free(ifp, M_IFNET);
497 }
498 
499 /*
500  * Deregister an interface and free the associated storage.
501  */
502 void
503 if_free(struct ifnet *ifp)
504 {
505 
506 	ifp->if_flags |= IFF_DYING;			/* XXX: Locking */
507 
508 	CURVNET_SET_QUIET(ifp->if_vnet);
509 	IFNET_WLOCK();
510 	KASSERT(ifp == ifnet_byindex_locked(ifp->if_index),
511 	    ("%s: freeing unallocated ifnet", ifp->if_xname));
512 
513 	ifindex_free_locked(ifp->if_index);
514 	IFNET_WUNLOCK();
515 
516 	if (refcount_release(&ifp->if_refcount))
517 		if_free_internal(ifp);
518 	CURVNET_RESTORE();
519 }
520 
521 /*
522  * Interfaces to keep an ifnet type-stable despite the possibility of the
523  * driver calling if_free().  If there are additional references, we defer
524  * freeing the underlying data structure.
525  */
526 void
527 if_ref(struct ifnet *ifp)
528 {
529 
530 	/* We don't assert the ifnet list lock here, but arguably should. */
531 	refcount_acquire(&ifp->if_refcount);
532 }
533 
534 void
535 if_rele(struct ifnet *ifp)
536 {
537 
538 	if (!refcount_release(&ifp->if_refcount))
539 		return;
540 	if_free_internal(ifp);
541 }
542 
543 void
544 ifq_init(struct ifaltq *ifq, struct ifnet *ifp)
545 {
546 
547 	mtx_init(&ifq->ifq_mtx, ifp->if_xname, "if send queue", MTX_DEF);
548 
549 	if (ifq->ifq_maxlen == 0)
550 		ifq->ifq_maxlen = ifqmaxlen;
551 
552 	ifq->altq_type = 0;
553 	ifq->altq_disc = NULL;
554 	ifq->altq_flags &= ALTQF_CANTCHANGE;
555 	ifq->altq_tbr  = NULL;
556 	ifq->altq_ifp  = ifp;
557 }
558 
559 void
560 ifq_delete(struct ifaltq *ifq)
561 {
562 	mtx_destroy(&ifq->ifq_mtx);
563 }
564 
565 /*
566  * Perform generic interface initalization tasks and attach the interface
567  * to the list of "active" interfaces.  If vmove flag is set on entry
568  * to if_attach_internal(), perform only a limited subset of initialization
569  * tasks, given that we are moving from one vnet to another an ifnet which
570  * has already been fully initialized.
571  *
572  * XXX:
573  *  - The decision to return void and thus require this function to
574  *    succeed is questionable.
575  *  - We should probably do more sanity checking.  For instance we don't
576  *    do anything to insure if_xname is unique or non-empty.
577  */
578 void
579 if_attach(struct ifnet *ifp)
580 {
581 
582 	if_attach_internal(ifp, 0);
583 }
584 
585 static void
586 if_attach_internal(struct ifnet *ifp, int vmove)
587 {
588 	unsigned socksize, ifasize;
589 	int namelen, masklen;
590 	struct sockaddr_dl *sdl;
591 	struct ifaddr *ifa;
592 
593 	if (ifp->if_index == 0 || ifp != ifnet_byindex(ifp->if_index))
594 		panic ("%s: BUG: if_attach called without if_alloc'd input()\n",
595 		    ifp->if_xname);
596 
597 #ifdef VIMAGE
598 	ifp->if_vnet = curvnet;
599 	if (ifp->if_home_vnet == NULL)
600 		ifp->if_home_vnet = curvnet;
601 #endif
602 
603 	if_addgroup(ifp, IFG_ALL);
604 
605 	getmicrotime(&ifp->if_lastchange);
606 	ifp->if_data.ifi_epoch = time_uptime;
607 	ifp->if_data.ifi_datalen = sizeof(struct if_data);
608 
609 	KASSERT((ifp->if_transmit == NULL && ifp->if_qflush == NULL) ||
610 	    (ifp->if_transmit != NULL && ifp->if_qflush != NULL),
611 	    ("transmit and qflush must both either be set or both be NULL"));
612 	if (ifp->if_transmit == NULL) {
613 		ifp->if_transmit = if_transmit;
614 		ifp->if_qflush = if_qflush;
615 	}
616 
617 	if (!vmove) {
618 #ifdef MAC
619 		mac_ifnet_create(ifp);
620 #endif
621 
622 		/*
623 		 * Create a Link Level name for this device.
624 		 */
625 		namelen = strlen(ifp->if_xname);
626 		/*
627 		 * Always save enough space for any possiable name so we
628 		 * can do a rename in place later.
629 		 */
630 		masklen = offsetof(struct sockaddr_dl, sdl_data[0]) + IFNAMSIZ;
631 		socksize = masklen + ifp->if_addrlen;
632 		if (socksize < sizeof(*sdl))
633 			socksize = sizeof(*sdl);
634 		socksize = roundup2(socksize, sizeof(long));
635 		ifasize = sizeof(*ifa) + 2 * socksize;
636 		ifa = ifa_alloc(ifasize, M_WAITOK);
637 		sdl = (struct sockaddr_dl *)(ifa + 1);
638 		sdl->sdl_len = socksize;
639 		sdl->sdl_family = AF_LINK;
640 		bcopy(ifp->if_xname, sdl->sdl_data, namelen);
641 		sdl->sdl_nlen = namelen;
642 		sdl->sdl_index = ifp->if_index;
643 		sdl->sdl_type = ifp->if_type;
644 		ifp->if_addr = ifa;
645 		ifa->ifa_ifp = ifp;
646 		ifa->ifa_rtrequest = link_rtrequest;
647 		ifa->ifa_addr = (struct sockaddr *)sdl;
648 		sdl = (struct sockaddr_dl *)(socksize + (caddr_t)sdl);
649 		ifa->ifa_netmask = (struct sockaddr *)sdl;
650 		sdl->sdl_len = masklen;
651 		while (namelen != 0)
652 			sdl->sdl_data[--namelen] = 0xff;
653 		TAILQ_INSERT_HEAD(&ifp->if_addrhead, ifa, ifa_link);
654 		/* Reliably crash if used uninitialized. */
655 		ifp->if_broadcastaddr = NULL;
656 
657 #if defined(INET) || defined(INET6)
658 		/* Initialize to max value. */
659 		if (ifp->if_hw_tsomax == 0)
660 			ifp->if_hw_tsomax = IP_MAXPACKET;
661 		KASSERT(ifp->if_hw_tsomax <= IP_MAXPACKET &&
662 		    ifp->if_hw_tsomax >= IP_MAXPACKET / 8,
663 		    ("%s: tsomax outside of range", __func__));
664 #endif
665 	}
666 #ifdef VIMAGE
667 	else {
668 		/*
669 		 * Update the interface index in the link layer address
670 		 * of the interface.
671 		 */
672 		for (ifa = ifp->if_addr; ifa != NULL;
673 		    ifa = TAILQ_NEXT(ifa, ifa_link)) {
674 			if (ifa->ifa_addr->sa_family == AF_LINK) {
675 				sdl = (struct sockaddr_dl *)ifa->ifa_addr;
676 				sdl->sdl_index = ifp->if_index;
677 			}
678 		}
679 	}
680 #endif
681 
682 	IFNET_WLOCK();
683 	TAILQ_INSERT_TAIL(&V_ifnet, ifp, if_link);
684 #ifdef VIMAGE
685 	curvnet->vnet_ifcnt++;
686 #endif
687 	IFNET_WUNLOCK();
688 
689 	if (domain_init_status >= 2)
690 		if_attachdomain1(ifp);
691 
692 	EVENTHANDLER_INVOKE(ifnet_arrival_event, ifp);
693 	if (IS_DEFAULT_VNET(curvnet))
694 		devctl_notify("IFNET", ifp->if_xname, "ATTACH", NULL);
695 
696 	/* Announce the interface. */
697 	rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
698 }
699 
700 static void
701 if_attachdomain(void *dummy)
702 {
703 	struct ifnet *ifp;
704 
705 	TAILQ_FOREACH(ifp, &V_ifnet, if_link)
706 		if_attachdomain1(ifp);
707 }
708 SYSINIT(domainifattach, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_SECOND,
709     if_attachdomain, NULL);
710 
711 static void
712 if_attachdomain1(struct ifnet *ifp)
713 {
714 	struct domain *dp;
715 
716 	/*
717 	 * Since dp->dom_ifattach calls malloc() with M_WAITOK, we
718 	 * cannot lock ifp->if_afdata initialization, entirely.
719 	 */
720 	if (IF_AFDATA_TRYLOCK(ifp) == 0)
721 		return;
722 	if (ifp->if_afdata_initialized >= domain_init_status) {
723 		IF_AFDATA_UNLOCK(ifp);
724 		log(LOG_WARNING, "%s called more than once on %s\n",
725 		    __func__, ifp->if_xname);
726 		return;
727 	}
728 	ifp->if_afdata_initialized = domain_init_status;
729 	IF_AFDATA_UNLOCK(ifp);
730 
731 	/* address family dependent data region */
732 	bzero(ifp->if_afdata, sizeof(ifp->if_afdata));
733 	for (dp = domains; dp; dp = dp->dom_next) {
734 		if (dp->dom_ifattach)
735 			ifp->if_afdata[dp->dom_family] =
736 			    (*dp->dom_ifattach)(ifp);
737 	}
738 }
739 
740 /*
741  * Remove any unicast or broadcast network addresses from an interface.
742  */
743 void
744 if_purgeaddrs(struct ifnet *ifp)
745 {
746 	struct ifaddr *ifa, *next;
747 
748 	TAILQ_FOREACH_SAFE(ifa, &ifp->if_addrhead, ifa_link, next) {
749 		if (ifa->ifa_addr->sa_family == AF_LINK)
750 			continue;
751 #ifdef INET
752 		/* XXX: Ugly!! ad hoc just for INET */
753 		if (ifa->ifa_addr->sa_family == AF_INET) {
754 			struct ifaliasreq ifr;
755 
756 			bzero(&ifr, sizeof(ifr));
757 			ifr.ifra_addr = *ifa->ifa_addr;
758 			if (ifa->ifa_dstaddr)
759 				ifr.ifra_broadaddr = *ifa->ifa_dstaddr;
760 			if (in_control(NULL, SIOCDIFADDR, (caddr_t)&ifr, ifp,
761 			    NULL) == 0)
762 				continue;
763 		}
764 #endif /* INET */
765 #ifdef INET6
766 		if (ifa->ifa_addr->sa_family == AF_INET6) {
767 			in6_purgeaddr(ifa);
768 			/* ifp_addrhead is already updated */
769 			continue;
770 		}
771 #endif /* INET6 */
772 		TAILQ_REMOVE(&ifp->if_addrhead, ifa, ifa_link);
773 		ifa_free(ifa);
774 	}
775 }
776 
777 /*
778  * Remove any multicast network addresses from an interface when an ifnet
779  * is going away.
780  */
781 static void
782 if_purgemaddrs(struct ifnet *ifp)
783 {
784 	struct ifmultiaddr *ifma;
785 	struct ifmultiaddr *next;
786 
787 	IF_ADDR_WLOCK(ifp);
788 	TAILQ_FOREACH_SAFE(ifma, &ifp->if_multiaddrs, ifma_link, next)
789 		if_delmulti_locked(ifp, ifma, 1);
790 	IF_ADDR_WUNLOCK(ifp);
791 }
792 
793 /*
794  * Detach an interface, removing it from the list of "active" interfaces.
795  * If vmove flag is set on entry to if_detach_internal(), perform only a
796  * limited subset of cleanup tasks, given that we are moving an ifnet from
797  * one vnet to another, where it must be fully operational.
798  *
799  * XXXRW: There are some significant questions about event ordering, and
800  * how to prevent things from starting to use the interface during detach.
801  */
802 void
803 if_detach(struct ifnet *ifp)
804 {
805 
806 	CURVNET_SET_QUIET(ifp->if_vnet);
807 	if_detach_internal(ifp, 0);
808 	CURVNET_RESTORE();
809 }
810 
811 static void
812 if_detach_internal(struct ifnet *ifp, int vmove)
813 {
814 	struct ifaddr *ifa;
815 	struct radix_node_head	*rnh;
816 	int i, j;
817 	struct domain *dp;
818  	struct ifnet *iter;
819  	int found = 0;
820 
821 	IFNET_WLOCK();
822 	TAILQ_FOREACH(iter, &V_ifnet, if_link)
823 		if (iter == ifp) {
824 			TAILQ_REMOVE(&V_ifnet, ifp, if_link);
825 			found = 1;
826 			break;
827 		}
828 #ifdef VIMAGE
829 	if (found)
830 		curvnet->vnet_ifcnt--;
831 #endif
832 	IFNET_WUNLOCK();
833 	if (!found) {
834 		if (vmove)
835 			panic("%s: ifp=%p not on the ifnet tailq %p",
836 			    __func__, ifp, &V_ifnet);
837 		else
838 			return; /* XXX this should panic as well? */
839 	}
840 
841 	/*
842 	 * Remove/wait for pending events.
843 	 */
844 	taskqueue_drain(taskqueue_swi, &ifp->if_linktask);
845 
846 	/*
847 	 * Remove routes and flush queues.
848 	 */
849 	if_down(ifp);
850 #ifdef ALTQ
851 	if (ALTQ_IS_ENABLED(&ifp->if_snd))
852 		altq_disable(&ifp->if_snd);
853 	if (ALTQ_IS_ATTACHED(&ifp->if_snd))
854 		altq_detach(&ifp->if_snd);
855 #endif
856 
857 	if_purgeaddrs(ifp);
858 
859 #ifdef INET
860 	in_ifdetach(ifp);
861 #endif
862 
863 #ifdef INET6
864 	/*
865 	 * Remove all IPv6 kernel structs related to ifp.  This should be done
866 	 * before removing routing entries below, since IPv6 interface direct
867 	 * routes are expected to be removed by the IPv6-specific kernel API.
868 	 * Otherwise, the kernel will detect some inconsistency and bark it.
869 	 */
870 	in6_ifdetach(ifp);
871 #endif
872 	if_purgemaddrs(ifp);
873 
874 	if (!vmove) {
875 		/*
876 		 * Prevent further calls into the device driver via ifnet.
877 		 */
878 		if_dead(ifp);
879 
880 		/*
881 		 * Remove link ifaddr pointer and maybe decrement if_index.
882 		 * Clean up all addresses.
883 		 */
884 		ifp->if_addr = NULL;
885 
886 		/* We can now free link ifaddr. */
887 		if (!TAILQ_EMPTY(&ifp->if_addrhead)) {
888 			ifa = TAILQ_FIRST(&ifp->if_addrhead);
889 			TAILQ_REMOVE(&ifp->if_addrhead, ifa, ifa_link);
890 			ifa_free(ifa);
891 		}
892 	}
893 
894 	/*
895 	 * Delete all remaining routes using this interface
896 	 * Unfortuneatly the only way to do this is to slog through
897 	 * the entire routing table looking for routes which point
898 	 * to this interface...oh well...
899 	 */
900 	for (i = 1; i <= AF_MAX; i++) {
901 		for (j = 0; j < rt_numfibs; j++) {
902 			rnh = rt_tables_get_rnh(j, i);
903 			if (rnh == NULL)
904 				continue;
905 			RADIX_NODE_HEAD_LOCK(rnh);
906 			(void) rnh->rnh_walktree(rnh, if_rtdel, ifp);
907 			RADIX_NODE_HEAD_UNLOCK(rnh);
908 		}
909 	}
910 
911 	/* Announce that the interface is gone. */
912 	rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
913 	EVENTHANDLER_INVOKE(ifnet_departure_event, ifp);
914 	if (IS_DEFAULT_VNET(curvnet))
915 		devctl_notify("IFNET", ifp->if_xname, "DETACH", NULL);
916 	if_delgroups(ifp);
917 
918 	/*
919 	 * We cannot hold the lock over dom_ifdetach calls as they might
920 	 * sleep, for example trying to drain a callout, thus open up the
921 	 * theoretical race with re-attaching.
922 	 */
923 	IF_AFDATA_LOCK(ifp);
924 	i = ifp->if_afdata_initialized;
925 	ifp->if_afdata_initialized = 0;
926 	IF_AFDATA_UNLOCK(ifp);
927 	for (dp = domains; i > 0 && dp; dp = dp->dom_next) {
928 		if (dp->dom_ifdetach && ifp->if_afdata[dp->dom_family])
929 			(*dp->dom_ifdetach)(ifp,
930 			    ifp->if_afdata[dp->dom_family]);
931 	}
932 }
933 
934 #ifdef VIMAGE
935 /*
936  * if_vmove() performs a limited version of if_detach() in current
937  * vnet and if_attach()es the ifnet to the vnet specified as 2nd arg.
938  * An attempt is made to shrink if_index in current vnet, find an
939  * unused if_index in target vnet and calls if_grow() if necessary,
940  * and finally find an unused if_xname for the target vnet.
941  */
942 void
943 if_vmove(struct ifnet *ifp, struct vnet *new_vnet)
944 {
945 	u_short idx;
946 
947 	/*
948 	 * Detach from current vnet, but preserve LLADDR info, do not
949 	 * mark as dead etc. so that the ifnet can be reattached later.
950 	 */
951 	if_detach_internal(ifp, 1);
952 
953 	/*
954 	 * Unlink the ifnet from ifindex_table[] in current vnet, and shrink
955 	 * the if_index for that vnet if possible.
956 	 *
957 	 * NOTE: IFNET_WLOCK/IFNET_WUNLOCK() are assumed to be unvirtualized,
958 	 * or we'd lock on one vnet and unlock on another.
959 	 */
960 	IFNET_WLOCK();
961 	ifindex_free_locked(ifp->if_index);
962 	IFNET_WUNLOCK();
963 
964 	/*
965 	 * Perform interface-specific reassignment tasks, if provided by
966 	 * the driver.
967 	 */
968 	if (ifp->if_reassign != NULL)
969 		ifp->if_reassign(ifp, new_vnet, NULL);
970 
971 	/*
972 	 * Switch to the context of the target vnet.
973 	 */
974 	CURVNET_SET_QUIET(new_vnet);
975 
976 	IFNET_WLOCK();
977 	if (ifindex_alloc_locked(&idx) != 0) {
978 		IFNET_WUNLOCK();
979 		panic("if_index overflow");
980 	}
981 	ifp->if_index = idx;
982 	ifnet_setbyindex_locked(ifp->if_index, ifp);
983 	IFNET_WUNLOCK();
984 
985 	if_attach_internal(ifp, 1);
986 
987 	CURVNET_RESTORE();
988 }
989 
990 /*
991  * Move an ifnet to or from another child prison/vnet, specified by the jail id.
992  */
993 static int
994 if_vmove_loan(struct thread *td, struct ifnet *ifp, char *ifname, int jid)
995 {
996 	struct prison *pr;
997 	struct ifnet *difp;
998 
999 	/* Try to find the prison within our visibility. */
1000 	sx_slock(&allprison_lock);
1001 	pr = prison_find_child(td->td_ucred->cr_prison, jid);
1002 	sx_sunlock(&allprison_lock);
1003 	if (pr == NULL)
1004 		return (ENXIO);
1005 	prison_hold_locked(pr);
1006 	mtx_unlock(&pr->pr_mtx);
1007 
1008 	/* Do not try to move the iface from and to the same prison. */
1009 	if (pr->pr_vnet == ifp->if_vnet) {
1010 		prison_free(pr);
1011 		return (EEXIST);
1012 	}
1013 
1014 	/* Make sure the named iface does not exists in the dst. prison/vnet. */
1015 	/* XXX Lock interfaces to avoid races. */
1016 	CURVNET_SET_QUIET(pr->pr_vnet);
1017 	difp = ifunit(ifname);
1018 	CURVNET_RESTORE();
1019 	if (difp != NULL) {
1020 		prison_free(pr);
1021 		return (EEXIST);
1022 	}
1023 
1024 	/* Move the interface into the child jail/vnet. */
1025 	if_vmove(ifp, pr->pr_vnet);
1026 
1027 	/* Report the new if_xname back to the userland. */
1028 	sprintf(ifname, "%s", ifp->if_xname);
1029 
1030 	prison_free(pr);
1031 	return (0);
1032 }
1033 
1034 static int
1035 if_vmove_reclaim(struct thread *td, char *ifname, int jid)
1036 {
1037 	struct prison *pr;
1038 	struct vnet *vnet_dst;
1039 	struct ifnet *ifp;
1040 
1041 	/* Try to find the prison within our visibility. */
1042 	sx_slock(&allprison_lock);
1043 	pr = prison_find_child(td->td_ucred->cr_prison, jid);
1044 	sx_sunlock(&allprison_lock);
1045 	if (pr == NULL)
1046 		return (ENXIO);
1047 	prison_hold_locked(pr);
1048 	mtx_unlock(&pr->pr_mtx);
1049 
1050 	/* Make sure the named iface exists in the source prison/vnet. */
1051 	CURVNET_SET(pr->pr_vnet);
1052 	ifp = ifunit(ifname);		/* XXX Lock to avoid races. */
1053 	if (ifp == NULL) {
1054 		CURVNET_RESTORE();
1055 		prison_free(pr);
1056 		return (ENXIO);
1057 	}
1058 
1059 	/* Do not try to move the iface from and to the same prison. */
1060 	vnet_dst = TD_TO_VNET(td);
1061 	if (vnet_dst == ifp->if_vnet) {
1062 		CURVNET_RESTORE();
1063 		prison_free(pr);
1064 		return (EEXIST);
1065 	}
1066 
1067 	/* Get interface back from child jail/vnet. */
1068 	if_vmove(ifp, vnet_dst);
1069 	CURVNET_RESTORE();
1070 
1071 	/* Report the new if_xname back to the userland. */
1072 	sprintf(ifname, "%s", ifp->if_xname);
1073 
1074 	prison_free(pr);
1075 	return (0);
1076 }
1077 #endif /* VIMAGE */
1078 
1079 /*
1080  * Add a group to an interface
1081  */
1082 int
1083 if_addgroup(struct ifnet *ifp, const char *groupname)
1084 {
1085 	struct ifg_list		*ifgl;
1086 	struct ifg_group	*ifg = NULL;
1087 	struct ifg_member	*ifgm;
1088 	int 			 new = 0;
1089 
1090 	if (groupname[0] && groupname[strlen(groupname) - 1] >= '0' &&
1091 	    groupname[strlen(groupname) - 1] <= '9')
1092 		return (EINVAL);
1093 
1094 	IFNET_WLOCK();
1095 	TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
1096 		if (!strcmp(ifgl->ifgl_group->ifg_group, groupname)) {
1097 			IFNET_WUNLOCK();
1098 			return (EEXIST);
1099 		}
1100 
1101 	if ((ifgl = (struct ifg_list *)malloc(sizeof(struct ifg_list), M_TEMP,
1102 	    M_NOWAIT)) == NULL) {
1103 	    	IFNET_WUNLOCK();
1104 		return (ENOMEM);
1105 	}
1106 
1107 	if ((ifgm = (struct ifg_member *)malloc(sizeof(struct ifg_member),
1108 	    M_TEMP, M_NOWAIT)) == NULL) {
1109 		free(ifgl, M_TEMP);
1110 		IFNET_WUNLOCK();
1111 		return (ENOMEM);
1112 	}
1113 
1114 	TAILQ_FOREACH(ifg, &V_ifg_head, ifg_next)
1115 		if (!strcmp(ifg->ifg_group, groupname))
1116 			break;
1117 
1118 	if (ifg == NULL) {
1119 		if ((ifg = (struct ifg_group *)malloc(sizeof(struct ifg_group),
1120 		    M_TEMP, M_NOWAIT)) == NULL) {
1121 			free(ifgl, M_TEMP);
1122 			free(ifgm, M_TEMP);
1123 			IFNET_WUNLOCK();
1124 			return (ENOMEM);
1125 		}
1126 		strlcpy(ifg->ifg_group, groupname, sizeof(ifg->ifg_group));
1127 		ifg->ifg_refcnt = 0;
1128 		TAILQ_INIT(&ifg->ifg_members);
1129 		TAILQ_INSERT_TAIL(&V_ifg_head, ifg, ifg_next);
1130 		new = 1;
1131 	}
1132 
1133 	ifg->ifg_refcnt++;
1134 	ifgl->ifgl_group = ifg;
1135 	ifgm->ifgm_ifp = ifp;
1136 
1137 	IF_ADDR_WLOCK(ifp);
1138 	TAILQ_INSERT_TAIL(&ifg->ifg_members, ifgm, ifgm_next);
1139 	TAILQ_INSERT_TAIL(&ifp->if_groups, ifgl, ifgl_next);
1140 	IF_ADDR_WUNLOCK(ifp);
1141 
1142 	IFNET_WUNLOCK();
1143 
1144 	if (new)
1145 		EVENTHANDLER_INVOKE(group_attach_event, ifg);
1146 	EVENTHANDLER_INVOKE(group_change_event, groupname);
1147 
1148 	return (0);
1149 }
1150 
1151 /*
1152  * Remove a group from an interface
1153  */
1154 int
1155 if_delgroup(struct ifnet *ifp, const char *groupname)
1156 {
1157 	struct ifg_list		*ifgl;
1158 	struct ifg_member	*ifgm;
1159 
1160 	IFNET_WLOCK();
1161 	TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
1162 		if (!strcmp(ifgl->ifgl_group->ifg_group, groupname))
1163 			break;
1164 	if (ifgl == NULL) {
1165 		IFNET_WUNLOCK();
1166 		return (ENOENT);
1167 	}
1168 
1169 	IF_ADDR_WLOCK(ifp);
1170 	TAILQ_REMOVE(&ifp->if_groups, ifgl, ifgl_next);
1171 	IF_ADDR_WUNLOCK(ifp);
1172 
1173 	TAILQ_FOREACH(ifgm, &ifgl->ifgl_group->ifg_members, ifgm_next)
1174 		if (ifgm->ifgm_ifp == ifp)
1175 			break;
1176 
1177 	if (ifgm != NULL) {
1178 		TAILQ_REMOVE(&ifgl->ifgl_group->ifg_members, ifgm, ifgm_next);
1179 		free(ifgm, M_TEMP);
1180 	}
1181 
1182 	if (--ifgl->ifgl_group->ifg_refcnt == 0) {
1183 		TAILQ_REMOVE(&V_ifg_head, ifgl->ifgl_group, ifg_next);
1184 		IFNET_WUNLOCK();
1185 		EVENTHANDLER_INVOKE(group_detach_event, ifgl->ifgl_group);
1186 		free(ifgl->ifgl_group, M_TEMP);
1187 	} else
1188 		IFNET_WUNLOCK();
1189 
1190 	free(ifgl, M_TEMP);
1191 
1192 	EVENTHANDLER_INVOKE(group_change_event, groupname);
1193 
1194 	return (0);
1195 }
1196 
1197 /*
1198  * Remove an interface from all groups
1199  */
1200 static void
1201 if_delgroups(struct ifnet *ifp)
1202 {
1203 	struct ifg_list		*ifgl;
1204 	struct ifg_member	*ifgm;
1205 	char groupname[IFNAMSIZ];
1206 
1207 	IFNET_WLOCK();
1208 	while (!TAILQ_EMPTY(&ifp->if_groups)) {
1209 		ifgl = TAILQ_FIRST(&ifp->if_groups);
1210 
1211 		strlcpy(groupname, ifgl->ifgl_group->ifg_group, IFNAMSIZ);
1212 
1213 		IF_ADDR_WLOCK(ifp);
1214 		TAILQ_REMOVE(&ifp->if_groups, ifgl, ifgl_next);
1215 		IF_ADDR_WUNLOCK(ifp);
1216 
1217 		TAILQ_FOREACH(ifgm, &ifgl->ifgl_group->ifg_members, ifgm_next)
1218 			if (ifgm->ifgm_ifp == ifp)
1219 				break;
1220 
1221 		if (ifgm != NULL) {
1222 			TAILQ_REMOVE(&ifgl->ifgl_group->ifg_members, ifgm,
1223 			    ifgm_next);
1224 			free(ifgm, M_TEMP);
1225 		}
1226 
1227 		if (--ifgl->ifgl_group->ifg_refcnt == 0) {
1228 			TAILQ_REMOVE(&V_ifg_head, ifgl->ifgl_group, ifg_next);
1229 			IFNET_WUNLOCK();
1230 			EVENTHANDLER_INVOKE(group_detach_event,
1231 			    ifgl->ifgl_group);
1232 			free(ifgl->ifgl_group, M_TEMP);
1233 		} else
1234 			IFNET_WUNLOCK();
1235 
1236 		free(ifgl, M_TEMP);
1237 
1238 		EVENTHANDLER_INVOKE(group_change_event, groupname);
1239 
1240 		IFNET_WLOCK();
1241 	}
1242 	IFNET_WUNLOCK();
1243 }
1244 
1245 /*
1246  * Stores all groups from an interface in memory pointed
1247  * to by data
1248  */
1249 static int
1250 if_getgroup(struct ifgroupreq *data, struct ifnet *ifp)
1251 {
1252 	int			 len, error;
1253 	struct ifg_list		*ifgl;
1254 	struct ifg_req		 ifgrq, *ifgp;
1255 	struct ifgroupreq	*ifgr = data;
1256 
1257 	if (ifgr->ifgr_len == 0) {
1258 		IF_ADDR_RLOCK(ifp);
1259 		TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
1260 			ifgr->ifgr_len += sizeof(struct ifg_req);
1261 		IF_ADDR_RUNLOCK(ifp);
1262 		return (0);
1263 	}
1264 
1265 	len = ifgr->ifgr_len;
1266 	ifgp = ifgr->ifgr_groups;
1267 	/* XXX: wire */
1268 	IF_ADDR_RLOCK(ifp);
1269 	TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next) {
1270 		if (len < sizeof(ifgrq)) {
1271 			IF_ADDR_RUNLOCK(ifp);
1272 			return (EINVAL);
1273 		}
1274 		bzero(&ifgrq, sizeof ifgrq);
1275 		strlcpy(ifgrq.ifgrq_group, ifgl->ifgl_group->ifg_group,
1276 		    sizeof(ifgrq.ifgrq_group));
1277 		if ((error = copyout(&ifgrq, ifgp, sizeof(struct ifg_req)))) {
1278 		    	IF_ADDR_RUNLOCK(ifp);
1279 			return (error);
1280 		}
1281 		len -= sizeof(ifgrq);
1282 		ifgp++;
1283 	}
1284 	IF_ADDR_RUNLOCK(ifp);
1285 
1286 	return (0);
1287 }
1288 
1289 /*
1290  * Stores all members of a group in memory pointed to by data
1291  */
1292 static int
1293 if_getgroupmembers(struct ifgroupreq *data)
1294 {
1295 	struct ifgroupreq	*ifgr = data;
1296 	struct ifg_group	*ifg;
1297 	struct ifg_member	*ifgm;
1298 	struct ifg_req		 ifgrq, *ifgp;
1299 	int			 len, error;
1300 
1301 	IFNET_RLOCK();
1302 	TAILQ_FOREACH(ifg, &V_ifg_head, ifg_next)
1303 		if (!strcmp(ifg->ifg_group, ifgr->ifgr_name))
1304 			break;
1305 	if (ifg == NULL) {
1306 		IFNET_RUNLOCK();
1307 		return (ENOENT);
1308 	}
1309 
1310 	if (ifgr->ifgr_len == 0) {
1311 		TAILQ_FOREACH(ifgm, &ifg->ifg_members, ifgm_next)
1312 			ifgr->ifgr_len += sizeof(ifgrq);
1313 		IFNET_RUNLOCK();
1314 		return (0);
1315 	}
1316 
1317 	len = ifgr->ifgr_len;
1318 	ifgp = ifgr->ifgr_groups;
1319 	TAILQ_FOREACH(ifgm, &ifg->ifg_members, ifgm_next) {
1320 		if (len < sizeof(ifgrq)) {
1321 			IFNET_RUNLOCK();
1322 			return (EINVAL);
1323 		}
1324 		bzero(&ifgrq, sizeof ifgrq);
1325 		strlcpy(ifgrq.ifgrq_member, ifgm->ifgm_ifp->if_xname,
1326 		    sizeof(ifgrq.ifgrq_member));
1327 		if ((error = copyout(&ifgrq, ifgp, sizeof(struct ifg_req)))) {
1328 			IFNET_RUNLOCK();
1329 			return (error);
1330 		}
1331 		len -= sizeof(ifgrq);
1332 		ifgp++;
1333 	}
1334 	IFNET_RUNLOCK();
1335 
1336 	return (0);
1337 }
1338 
1339 /*
1340  * Delete Routes for a Network Interface
1341  *
1342  * Called for each routing entry via the rnh->rnh_walktree() call above
1343  * to delete all route entries referencing a detaching network interface.
1344  *
1345  * Arguments:
1346  *	rn	pointer to node in the routing table
1347  *	arg	argument passed to rnh->rnh_walktree() - detaching interface
1348  *
1349  * Returns:
1350  *	0	successful
1351  *	errno	failed - reason indicated
1352  *
1353  */
1354 static int
1355 if_rtdel(struct radix_node *rn, void *arg)
1356 {
1357 	struct rtentry	*rt = (struct rtentry *)rn;
1358 	struct ifnet	*ifp = arg;
1359 	int		err;
1360 
1361 	if (rt->rt_ifp == ifp) {
1362 
1363 		/*
1364 		 * Protect (sorta) against walktree recursion problems
1365 		 * with cloned routes
1366 		 */
1367 		if ((rt->rt_flags & RTF_UP) == 0)
1368 			return (0);
1369 
1370 		err = rtrequest_fib(RTM_DELETE, rt_key(rt), rt->rt_gateway,
1371 				rt_mask(rt),
1372 				rt->rt_flags|RTF_RNH_LOCKED|RTF_PINNED,
1373 				(struct rtentry **) NULL, rt->rt_fibnum);
1374 		if (err) {
1375 			log(LOG_WARNING, "if_rtdel: error %d\n", err);
1376 		}
1377 	}
1378 
1379 	return (0);
1380 }
1381 
1382 /*
1383  * Wrapper functions for struct ifnet address list locking macros.  These are
1384  * used by kernel modules to avoid encoding programming interface or binary
1385  * interface assumptions that may be violated when kernel-internal locking
1386  * approaches change.
1387  */
1388 void
1389 if_addr_rlock(struct ifnet *ifp)
1390 {
1391 
1392 	IF_ADDR_RLOCK(ifp);
1393 }
1394 
1395 void
1396 if_addr_runlock(struct ifnet *ifp)
1397 {
1398 
1399 	IF_ADDR_RUNLOCK(ifp);
1400 }
1401 
1402 void
1403 if_maddr_rlock(struct ifnet *ifp)
1404 {
1405 
1406 	IF_ADDR_RLOCK(ifp);
1407 }
1408 
1409 void
1410 if_maddr_runlock(struct ifnet *ifp)
1411 {
1412 
1413 	IF_ADDR_RUNLOCK(ifp);
1414 }
1415 
1416 /*
1417  * Initialization, destruction and refcounting functions for ifaddrs.
1418  */
1419 struct ifaddr *
1420 ifa_alloc(size_t size, int flags)
1421 {
1422 	struct ifaddr *ifa;
1423 
1424 	KASSERT(size >= sizeof(struct ifaddr),
1425 	    ("%s: invalid size %zu", __func__, size));
1426 
1427 	ifa = malloc(size, M_IFADDR, M_ZERO | flags);
1428 	if (ifa == NULL)
1429 		return (NULL);
1430 
1431 	if ((ifa->ifa_opackets = counter_u64_alloc(flags)) == NULL)
1432 		goto fail;
1433 	if ((ifa->ifa_ipackets = counter_u64_alloc(flags)) == NULL)
1434 		goto fail;
1435 	if ((ifa->ifa_obytes = counter_u64_alloc(flags)) == NULL)
1436 		goto fail;
1437 	if ((ifa->ifa_ibytes = counter_u64_alloc(flags)) == NULL)
1438 		goto fail;
1439 
1440 	refcount_init(&ifa->ifa_refcnt, 1);
1441 
1442 	return (ifa);
1443 
1444 fail:
1445 	/* free(NULL) is okay */
1446 	counter_u64_free(ifa->ifa_opackets);
1447 	counter_u64_free(ifa->ifa_ipackets);
1448 	counter_u64_free(ifa->ifa_obytes);
1449 	counter_u64_free(ifa->ifa_ibytes);
1450 	free(ifa, M_IFADDR);
1451 
1452 	return (NULL);
1453 }
1454 
1455 void
1456 ifa_ref(struct ifaddr *ifa)
1457 {
1458 
1459 	refcount_acquire(&ifa->ifa_refcnt);
1460 }
1461 
1462 void
1463 ifa_free(struct ifaddr *ifa)
1464 {
1465 
1466 	if (refcount_release(&ifa->ifa_refcnt)) {
1467 		counter_u64_free(ifa->ifa_opackets);
1468 		counter_u64_free(ifa->ifa_ipackets);
1469 		counter_u64_free(ifa->ifa_obytes);
1470 		counter_u64_free(ifa->ifa_ibytes);
1471 		free(ifa, M_IFADDR);
1472 	}
1473 }
1474 
1475 int
1476 ifa_add_loopback_route(struct ifaddr *ifa, struct sockaddr *ia)
1477 {
1478 	int error = 0;
1479 	struct rtentry *rt = NULL;
1480 	struct rt_addrinfo info;
1481 	static struct sockaddr_dl null_sdl = {sizeof(null_sdl), AF_LINK};
1482 
1483 	bzero(&info, sizeof(info));
1484 	info.rti_ifp = V_loif;
1485 	info.rti_flags = ifa->ifa_flags | RTF_HOST | RTF_STATIC;
1486 	info.rti_info[RTAX_DST] = ia;
1487 	info.rti_info[RTAX_GATEWAY] = (struct sockaddr *)&null_sdl;
1488 	error = rtrequest1_fib(RTM_ADD, &info, &rt, 0);
1489 
1490 	if (error == 0 && rt != NULL) {
1491 		RT_LOCK(rt);
1492 		((struct sockaddr_dl *)rt->rt_gateway)->sdl_type  =
1493 			ifa->ifa_ifp->if_type;
1494 		((struct sockaddr_dl *)rt->rt_gateway)->sdl_index =
1495 			ifa->ifa_ifp->if_index;
1496 		RT_REMREF(rt);
1497 		RT_UNLOCK(rt);
1498 	} else if (error != 0)
1499 		log(LOG_DEBUG, "%s: insertion failed: %u\n", __func__, error);
1500 
1501 	return (error);
1502 }
1503 
1504 int
1505 ifa_del_loopback_route(struct ifaddr *ifa, struct sockaddr *ia)
1506 {
1507 	int error = 0;
1508 	struct rt_addrinfo info;
1509 	struct sockaddr_dl null_sdl;
1510 
1511 	bzero(&null_sdl, sizeof(null_sdl));
1512 	null_sdl.sdl_len = sizeof(null_sdl);
1513 	null_sdl.sdl_family = AF_LINK;
1514 	null_sdl.sdl_type = ifa->ifa_ifp->if_type;
1515 	null_sdl.sdl_index = ifa->ifa_ifp->if_index;
1516 	bzero(&info, sizeof(info));
1517 	info.rti_flags = ifa->ifa_flags | RTF_HOST | RTF_STATIC;
1518 	info.rti_info[RTAX_DST] = ia;
1519 	info.rti_info[RTAX_GATEWAY] = (struct sockaddr *)&null_sdl;
1520 	error = rtrequest1_fib(RTM_DELETE, &info, NULL, 0);
1521 
1522 	if (error != 0)
1523 		log(LOG_DEBUG, "%s: deletion failed: %u\n", __func__, error);
1524 
1525 	return (error);
1526 }
1527 
1528 /*
1529  * XXX: Because sockaddr_dl has deeper structure than the sockaddr
1530  * structs used to represent other address families, it is necessary
1531  * to perform a different comparison.
1532  */
1533 
1534 #define	sa_equal(a1, a2)	\
1535 	(bcmp((a1), (a2), ((a1))->sa_len) == 0)
1536 
1537 #define	sa_dl_equal(a1, a2)	\
1538 	((((struct sockaddr_dl *)(a1))->sdl_len ==			\
1539 	 ((struct sockaddr_dl *)(a2))->sdl_len) &&			\
1540 	 (bcmp(LLADDR((struct sockaddr_dl *)(a1)),			\
1541 	       LLADDR((struct sockaddr_dl *)(a2)),			\
1542 	       ((struct sockaddr_dl *)(a1))->sdl_alen) == 0))
1543 
1544 /*
1545  * Locate an interface based on a complete address.
1546  */
1547 /*ARGSUSED*/
1548 static struct ifaddr *
1549 ifa_ifwithaddr_internal(struct sockaddr *addr, int getref)
1550 {
1551 	struct ifnet *ifp;
1552 	struct ifaddr *ifa;
1553 
1554 	IFNET_RLOCK_NOSLEEP();
1555 	TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
1556 		IF_ADDR_RLOCK(ifp);
1557 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1558 			if (ifa->ifa_addr->sa_family != addr->sa_family)
1559 				continue;
1560 			if (sa_equal(addr, ifa->ifa_addr)) {
1561 				if (getref)
1562 					ifa_ref(ifa);
1563 				IF_ADDR_RUNLOCK(ifp);
1564 				goto done;
1565 			}
1566 			/* IP6 doesn't have broadcast */
1567 			if ((ifp->if_flags & IFF_BROADCAST) &&
1568 			    ifa->ifa_broadaddr &&
1569 			    ifa->ifa_broadaddr->sa_len != 0 &&
1570 			    sa_equal(ifa->ifa_broadaddr, addr)) {
1571 				if (getref)
1572 					ifa_ref(ifa);
1573 				IF_ADDR_RUNLOCK(ifp);
1574 				goto done;
1575 			}
1576 		}
1577 		IF_ADDR_RUNLOCK(ifp);
1578 	}
1579 	ifa = NULL;
1580 done:
1581 	IFNET_RUNLOCK_NOSLEEP();
1582 	return (ifa);
1583 }
1584 
1585 struct ifaddr *
1586 ifa_ifwithaddr(struct sockaddr *addr)
1587 {
1588 
1589 	return (ifa_ifwithaddr_internal(addr, 1));
1590 }
1591 
1592 int
1593 ifa_ifwithaddr_check(struct sockaddr *addr)
1594 {
1595 
1596 	return (ifa_ifwithaddr_internal(addr, 0) != NULL);
1597 }
1598 
1599 /*
1600  * Locate an interface based on the broadcast address.
1601  */
1602 /* ARGSUSED */
1603 struct ifaddr *
1604 ifa_ifwithbroadaddr(struct sockaddr *addr)
1605 {
1606 	struct ifnet *ifp;
1607 	struct ifaddr *ifa;
1608 
1609 	IFNET_RLOCK_NOSLEEP();
1610 	TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
1611 		IF_ADDR_RLOCK(ifp);
1612 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1613 			if (ifa->ifa_addr->sa_family != addr->sa_family)
1614 				continue;
1615 			if ((ifp->if_flags & IFF_BROADCAST) &&
1616 			    ifa->ifa_broadaddr &&
1617 			    ifa->ifa_broadaddr->sa_len != 0 &&
1618 			    sa_equal(ifa->ifa_broadaddr, addr)) {
1619 				ifa_ref(ifa);
1620 				IF_ADDR_RUNLOCK(ifp);
1621 				goto done;
1622 			}
1623 		}
1624 		IF_ADDR_RUNLOCK(ifp);
1625 	}
1626 	ifa = NULL;
1627 done:
1628 	IFNET_RUNLOCK_NOSLEEP();
1629 	return (ifa);
1630 }
1631 
1632 /*
1633  * Locate the point to point interface with a given destination address.
1634  */
1635 /*ARGSUSED*/
1636 struct ifaddr *
1637 ifa_ifwithdstaddr(struct sockaddr *addr)
1638 {
1639 	struct ifnet *ifp;
1640 	struct ifaddr *ifa;
1641 
1642 	IFNET_RLOCK_NOSLEEP();
1643 	TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
1644 		if ((ifp->if_flags & IFF_POINTOPOINT) == 0)
1645 			continue;
1646 		IF_ADDR_RLOCK(ifp);
1647 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1648 			if (ifa->ifa_addr->sa_family != addr->sa_family)
1649 				continue;
1650 			if (ifa->ifa_dstaddr != NULL &&
1651 			    sa_equal(addr, ifa->ifa_dstaddr)) {
1652 				ifa_ref(ifa);
1653 				IF_ADDR_RUNLOCK(ifp);
1654 				goto done;
1655 			}
1656 		}
1657 		IF_ADDR_RUNLOCK(ifp);
1658 	}
1659 	ifa = NULL;
1660 done:
1661 	IFNET_RUNLOCK_NOSLEEP();
1662 	return (ifa);
1663 }
1664 
1665 /*
1666  * Find an interface on a specific network.  If many, choice
1667  * is most specific found.
1668  */
1669 struct ifaddr *
1670 ifa_ifwithnet(struct sockaddr *addr, int ignore_ptp)
1671 {
1672 	struct ifnet *ifp;
1673 	struct ifaddr *ifa;
1674 	struct ifaddr *ifa_maybe = NULL;
1675 	u_int af = addr->sa_family;
1676 	char *addr_data = addr->sa_data, *cplim;
1677 
1678 	/*
1679 	 * AF_LINK addresses can be looked up directly by their index number,
1680 	 * so do that if we can.
1681 	 */
1682 	if (af == AF_LINK) {
1683 	    struct sockaddr_dl *sdl = (struct sockaddr_dl *)addr;
1684 	    if (sdl->sdl_index && sdl->sdl_index <= V_if_index)
1685 		return (ifaddr_byindex(sdl->sdl_index));
1686 	}
1687 
1688 	/*
1689 	 * Scan though each interface, looking for ones that have addresses
1690 	 * in this address family.  Maintain a reference on ifa_maybe once
1691 	 * we find one, as we release the IF_ADDR_RLOCK() that kept it stable
1692 	 * when we move onto the next interface.
1693 	 */
1694 	IFNET_RLOCK_NOSLEEP();
1695 	TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
1696 		IF_ADDR_RLOCK(ifp);
1697 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1698 			char *cp, *cp2, *cp3;
1699 
1700 			if (ifa->ifa_addr->sa_family != af)
1701 next:				continue;
1702 			if (af == AF_INET &&
1703 			    ifp->if_flags & IFF_POINTOPOINT && !ignore_ptp) {
1704 				/*
1705 				 * This is a bit broken as it doesn't
1706 				 * take into account that the remote end may
1707 				 * be a single node in the network we are
1708 				 * looking for.
1709 				 * The trouble is that we don't know the
1710 				 * netmask for the remote end.
1711 				 */
1712 				if (ifa->ifa_dstaddr != NULL &&
1713 				    sa_equal(addr, ifa->ifa_dstaddr)) {
1714 					ifa_ref(ifa);
1715 					IF_ADDR_RUNLOCK(ifp);
1716 					goto done;
1717 				}
1718 			} else {
1719 				/*
1720 				 * if we have a special address handler,
1721 				 * then use it instead of the generic one.
1722 				 */
1723 				if (ifa->ifa_claim_addr) {
1724 					if ((*ifa->ifa_claim_addr)(ifa, addr)) {
1725 						ifa_ref(ifa);
1726 						IF_ADDR_RUNLOCK(ifp);
1727 						goto done;
1728 					}
1729 					continue;
1730 				}
1731 
1732 				/*
1733 				 * Scan all the bits in the ifa's address.
1734 				 * If a bit dissagrees with what we are
1735 				 * looking for, mask it with the netmask
1736 				 * to see if it really matters.
1737 				 * (A byte at a time)
1738 				 */
1739 				if (ifa->ifa_netmask == 0)
1740 					continue;
1741 				cp = addr_data;
1742 				cp2 = ifa->ifa_addr->sa_data;
1743 				cp3 = ifa->ifa_netmask->sa_data;
1744 				cplim = ifa->ifa_netmask->sa_len
1745 					+ (char *)ifa->ifa_netmask;
1746 				while (cp3 < cplim)
1747 					if ((*cp++ ^ *cp2++) & *cp3++)
1748 						goto next; /* next address! */
1749 				/*
1750 				 * If the netmask of what we just found
1751 				 * is more specific than what we had before
1752 				 * (if we had one), or if the virtual status
1753 				 * of new prefix is better than of the old one,
1754 				 * then remember the new one before continuing
1755 				 * to search for an even better one.
1756 				 */
1757 				if (ifa_maybe == NULL ||
1758 				    ifa_preferred(ifa_maybe, ifa) ||
1759 				    rn_refines((caddr_t)ifa->ifa_netmask,
1760 				    (caddr_t)ifa_maybe->ifa_netmask)) {
1761 					if (ifa_maybe != NULL)
1762 						ifa_free(ifa_maybe);
1763 					ifa_maybe = ifa;
1764 					ifa_ref(ifa_maybe);
1765 				}
1766 			}
1767 		}
1768 		IF_ADDR_RUNLOCK(ifp);
1769 	}
1770 	ifa = ifa_maybe;
1771 	ifa_maybe = NULL;
1772 done:
1773 	IFNET_RUNLOCK_NOSLEEP();
1774 	if (ifa_maybe != NULL)
1775 		ifa_free(ifa_maybe);
1776 	return (ifa);
1777 }
1778 
1779 /*
1780  * Find an interface address specific to an interface best matching
1781  * a given address.
1782  */
1783 struct ifaddr *
1784 ifaof_ifpforaddr(struct sockaddr *addr, struct ifnet *ifp)
1785 {
1786 	struct ifaddr *ifa;
1787 	char *cp, *cp2, *cp3;
1788 	char *cplim;
1789 	struct ifaddr *ifa_maybe = NULL;
1790 	u_int af = addr->sa_family;
1791 
1792 	if (af >= AF_MAX)
1793 		return (NULL);
1794 	IF_ADDR_RLOCK(ifp);
1795 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1796 		if (ifa->ifa_addr->sa_family != af)
1797 			continue;
1798 		if (ifa_maybe == NULL)
1799 			ifa_maybe = ifa;
1800 		if (ifa->ifa_netmask == 0) {
1801 			if (sa_equal(addr, ifa->ifa_addr) ||
1802 			    (ifa->ifa_dstaddr &&
1803 			    sa_equal(addr, ifa->ifa_dstaddr)))
1804 				goto done;
1805 			continue;
1806 		}
1807 		if (ifp->if_flags & IFF_POINTOPOINT) {
1808 			if (sa_equal(addr, ifa->ifa_dstaddr))
1809 				goto done;
1810 		} else {
1811 			cp = addr->sa_data;
1812 			cp2 = ifa->ifa_addr->sa_data;
1813 			cp3 = ifa->ifa_netmask->sa_data;
1814 			cplim = ifa->ifa_netmask->sa_len + (char *)ifa->ifa_netmask;
1815 			for (; cp3 < cplim; cp3++)
1816 				if ((*cp++ ^ *cp2++) & *cp3)
1817 					break;
1818 			if (cp3 == cplim)
1819 				goto done;
1820 		}
1821 	}
1822 	ifa = ifa_maybe;
1823 done:
1824 	if (ifa != NULL)
1825 		ifa_ref(ifa);
1826 	IF_ADDR_RUNLOCK(ifp);
1827 	return (ifa);
1828 }
1829 
1830 /*
1831  * See whether new ifa is better than current one:
1832  * 1) A non-virtual one is preferred over virtual.
1833  * 2) A virtual in master state preferred over any other state.
1834  *
1835  * Used in several address selecting functions.
1836  */
1837 int
1838 ifa_preferred(struct ifaddr *cur, struct ifaddr *next)
1839 {
1840 
1841 	return (cur->ifa_carp && (!next->ifa_carp ||
1842 	    ((*carp_master_p)(next) && !(*carp_master_p)(cur))));
1843 }
1844 
1845 #include <net/if_llatbl.h>
1846 
1847 /*
1848  * Default action when installing a route with a Link Level gateway.
1849  * Lookup an appropriate real ifa to point to.
1850  * This should be moved to /sys/net/link.c eventually.
1851  */
1852 static void
1853 link_rtrequest(int cmd, struct rtentry *rt, struct rt_addrinfo *info)
1854 {
1855 	struct ifaddr *ifa, *oifa;
1856 	struct sockaddr *dst;
1857 	struct ifnet *ifp;
1858 
1859 	RT_LOCK_ASSERT(rt);
1860 
1861 	if (cmd != RTM_ADD || ((ifa = rt->rt_ifa) == 0) ||
1862 	    ((ifp = ifa->ifa_ifp) == 0) || ((dst = rt_key(rt)) == 0))
1863 		return;
1864 	ifa = ifaof_ifpforaddr(dst, ifp);
1865 	if (ifa) {
1866 		oifa = rt->rt_ifa;
1867 		rt->rt_ifa = ifa;
1868 		ifa_free(oifa);
1869 		if (ifa->ifa_rtrequest && ifa->ifa_rtrequest != link_rtrequest)
1870 			ifa->ifa_rtrequest(cmd, rt, info);
1871 	}
1872 }
1873 
1874 /*
1875  * Mark an interface down and notify protocols of
1876  * the transition.
1877  */
1878 static void
1879 if_unroute(struct ifnet *ifp, int flag, int fam)
1880 {
1881 	struct ifaddr *ifa;
1882 
1883 	KASSERT(flag == IFF_UP, ("if_unroute: flag != IFF_UP"));
1884 
1885 	ifp->if_flags &= ~flag;
1886 	getmicrotime(&ifp->if_lastchange);
1887 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
1888 		if (fam == PF_UNSPEC || (fam == ifa->ifa_addr->sa_family))
1889 			pfctlinput(PRC_IFDOWN, ifa->ifa_addr);
1890 	ifp->if_qflush(ifp);
1891 
1892 	if (ifp->if_carp)
1893 		(*carp_linkstate_p)(ifp);
1894 	rt_ifmsg(ifp);
1895 }
1896 
1897 /*
1898  * Mark an interface up and notify protocols of
1899  * the transition.
1900  */
1901 static void
1902 if_route(struct ifnet *ifp, int flag, int fam)
1903 {
1904 	struct ifaddr *ifa;
1905 
1906 	KASSERT(flag == IFF_UP, ("if_route: flag != IFF_UP"));
1907 
1908 	ifp->if_flags |= flag;
1909 	getmicrotime(&ifp->if_lastchange);
1910 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
1911 		if (fam == PF_UNSPEC || (fam == ifa->ifa_addr->sa_family))
1912 			pfctlinput(PRC_IFUP, ifa->ifa_addr);
1913 	if (ifp->if_carp)
1914 		(*carp_linkstate_p)(ifp);
1915 	rt_ifmsg(ifp);
1916 #ifdef INET6
1917 	in6_if_up(ifp);
1918 #endif
1919 }
1920 
1921 void	(*vlan_link_state_p)(struct ifnet *);	/* XXX: private from if_vlan */
1922 void	(*vlan_trunk_cap_p)(struct ifnet *);		/* XXX: private from if_vlan */
1923 struct ifnet *(*vlan_trunkdev_p)(struct ifnet *);
1924 struct	ifnet *(*vlan_devat_p)(struct ifnet *, uint16_t);
1925 int	(*vlan_tag_p)(struct ifnet *, uint16_t *);
1926 int	(*vlan_setcookie_p)(struct ifnet *, void *);
1927 void	*(*vlan_cookie_p)(struct ifnet *);
1928 
1929 /*
1930  * Handle a change in the interface link state. To avoid LORs
1931  * between driver lock and upper layer locks, as well as possible
1932  * recursions, we post event to taskqueue, and all job
1933  * is done in static do_link_state_change().
1934  */
1935 void
1936 if_link_state_change(struct ifnet *ifp, int link_state)
1937 {
1938 	/* Return if state hasn't changed. */
1939 	if (ifp->if_link_state == link_state)
1940 		return;
1941 
1942 	ifp->if_link_state = link_state;
1943 
1944 	taskqueue_enqueue(taskqueue_swi, &ifp->if_linktask);
1945 }
1946 
1947 static void
1948 do_link_state_change(void *arg, int pending)
1949 {
1950 	struct ifnet *ifp = (struct ifnet *)arg;
1951 	int link_state = ifp->if_link_state;
1952 	CURVNET_SET(ifp->if_vnet);
1953 
1954 	/* Notify that the link state has changed. */
1955 	rt_ifmsg(ifp);
1956 	if (ifp->if_vlantrunk != NULL)
1957 		(*vlan_link_state_p)(ifp);
1958 
1959 	if ((ifp->if_type == IFT_ETHER || ifp->if_type == IFT_L2VLAN) &&
1960 	    IFP2AC(ifp)->ac_netgraph != NULL)
1961 		(*ng_ether_link_state_p)(ifp, link_state);
1962 	if (ifp->if_carp)
1963 		(*carp_linkstate_p)(ifp);
1964 	if (ifp->if_bridge)
1965 		(*bridge_linkstate_p)(ifp);
1966 	if (ifp->if_lagg)
1967 		(*lagg_linkstate_p)(ifp, link_state);
1968 
1969 	if (IS_DEFAULT_VNET(curvnet))
1970 		devctl_notify("IFNET", ifp->if_xname,
1971 		    (link_state == LINK_STATE_UP) ? "LINK_UP" : "LINK_DOWN",
1972 		    NULL);
1973 	if (pending > 1)
1974 		if_printf(ifp, "%d link states coalesced\n", pending);
1975 	if (log_link_state_change)
1976 		log(LOG_NOTICE, "%s: link state changed to %s\n", ifp->if_xname,
1977 		    (link_state == LINK_STATE_UP) ? "UP" : "DOWN" );
1978 	EVENTHANDLER_INVOKE(ifnet_link_event, ifp, ifp->if_link_state);
1979 	CURVNET_RESTORE();
1980 }
1981 
1982 /*
1983  * Mark an interface down and notify protocols of
1984  * the transition.
1985  */
1986 void
1987 if_down(struct ifnet *ifp)
1988 {
1989 
1990 	if_unroute(ifp, IFF_UP, AF_UNSPEC);
1991 }
1992 
1993 /*
1994  * Mark an interface up and notify protocols of
1995  * the transition.
1996  */
1997 void
1998 if_up(struct ifnet *ifp)
1999 {
2000 
2001 	if_route(ifp, IFF_UP, AF_UNSPEC);
2002 }
2003 
2004 /*
2005  * Flush an interface queue.
2006  */
2007 void
2008 if_qflush(struct ifnet *ifp)
2009 {
2010 	struct mbuf *m, *n;
2011 	struct ifaltq *ifq;
2012 
2013 	ifq = &ifp->if_snd;
2014 	IFQ_LOCK(ifq);
2015 #ifdef ALTQ
2016 	if (ALTQ_IS_ENABLED(ifq))
2017 		ALTQ_PURGE(ifq);
2018 #endif
2019 	n = ifq->ifq_head;
2020 	while ((m = n) != 0) {
2021 		n = m->m_act;
2022 		m_freem(m);
2023 	}
2024 	ifq->ifq_head = 0;
2025 	ifq->ifq_tail = 0;
2026 	ifq->ifq_len = 0;
2027 	IFQ_UNLOCK(ifq);
2028 }
2029 
2030 /*
2031  * Map interface name to interface structure pointer, with or without
2032  * returning a reference.
2033  */
2034 struct ifnet *
2035 ifunit_ref(const char *name)
2036 {
2037 	struct ifnet *ifp;
2038 
2039 	IFNET_RLOCK_NOSLEEP();
2040 	TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2041 		if (strncmp(name, ifp->if_xname, IFNAMSIZ) == 0 &&
2042 		    !(ifp->if_flags & IFF_DYING))
2043 			break;
2044 	}
2045 	if (ifp != NULL)
2046 		if_ref(ifp);
2047 	IFNET_RUNLOCK_NOSLEEP();
2048 	return (ifp);
2049 }
2050 
2051 struct ifnet *
2052 ifunit(const char *name)
2053 {
2054 	struct ifnet *ifp;
2055 
2056 	IFNET_RLOCK_NOSLEEP();
2057 	TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2058 		if (strncmp(name, ifp->if_xname, IFNAMSIZ) == 0)
2059 			break;
2060 	}
2061 	IFNET_RUNLOCK_NOSLEEP();
2062 	return (ifp);
2063 }
2064 
2065 /*
2066  * Hardware specific interface ioctls.
2067  */
2068 static int
2069 ifhwioctl(u_long cmd, struct ifnet *ifp, caddr_t data, struct thread *td)
2070 {
2071 	struct ifreq *ifr;
2072 	struct ifstat *ifs;
2073 	int error = 0;
2074 	int new_flags, temp_flags;
2075 	size_t namelen, onamelen;
2076 	size_t descrlen;
2077 	char *descrbuf, *odescrbuf;
2078 	char new_name[IFNAMSIZ];
2079 	struct ifaddr *ifa;
2080 	struct sockaddr_dl *sdl;
2081 
2082 	ifr = (struct ifreq *)data;
2083 	switch (cmd) {
2084 	case SIOCGIFINDEX:
2085 		ifr->ifr_index = ifp->if_index;
2086 		break;
2087 
2088 	case SIOCGIFFLAGS:
2089 		temp_flags = ifp->if_flags | ifp->if_drv_flags;
2090 		ifr->ifr_flags = temp_flags & 0xffff;
2091 		ifr->ifr_flagshigh = temp_flags >> 16;
2092 		break;
2093 
2094 	case SIOCGIFCAP:
2095 		ifr->ifr_reqcap = ifp->if_capabilities;
2096 		ifr->ifr_curcap = ifp->if_capenable;
2097 		break;
2098 
2099 #ifdef MAC
2100 	case SIOCGIFMAC:
2101 		error = mac_ifnet_ioctl_get(td->td_ucred, ifr, ifp);
2102 		break;
2103 #endif
2104 
2105 	case SIOCGIFMETRIC:
2106 		ifr->ifr_metric = ifp->if_metric;
2107 		break;
2108 
2109 	case SIOCGIFMTU:
2110 		ifr->ifr_mtu = ifp->if_mtu;
2111 		break;
2112 
2113 	case SIOCGIFPHYS:
2114 		ifr->ifr_phys = ifp->if_physical;
2115 		break;
2116 
2117 	case SIOCGIFDESCR:
2118 		error = 0;
2119 		sx_slock(&ifdescr_sx);
2120 		if (ifp->if_description == NULL)
2121 			error = ENOMSG;
2122 		else {
2123 			/* space for terminating nul */
2124 			descrlen = strlen(ifp->if_description) + 1;
2125 			if (ifr->ifr_buffer.length < descrlen)
2126 				ifr->ifr_buffer.buffer = NULL;
2127 			else
2128 				error = copyout(ifp->if_description,
2129 				    ifr->ifr_buffer.buffer, descrlen);
2130 			ifr->ifr_buffer.length = descrlen;
2131 		}
2132 		sx_sunlock(&ifdescr_sx);
2133 		break;
2134 
2135 	case SIOCSIFDESCR:
2136 		error = priv_check(td, PRIV_NET_SETIFDESCR);
2137 		if (error)
2138 			return (error);
2139 
2140 		/*
2141 		 * Copy only (length-1) bytes to make sure that
2142 		 * if_description is always nul terminated.  The
2143 		 * length parameter is supposed to count the
2144 		 * terminating nul in.
2145 		 */
2146 		if (ifr->ifr_buffer.length > ifdescr_maxlen)
2147 			return (ENAMETOOLONG);
2148 		else if (ifr->ifr_buffer.length == 0)
2149 			descrbuf = NULL;
2150 		else {
2151 			descrbuf = malloc(ifr->ifr_buffer.length, M_IFDESCR,
2152 			    M_WAITOK | M_ZERO);
2153 			error = copyin(ifr->ifr_buffer.buffer, descrbuf,
2154 			    ifr->ifr_buffer.length - 1);
2155 			if (error) {
2156 				free(descrbuf, M_IFDESCR);
2157 				break;
2158 			}
2159 		}
2160 
2161 		sx_xlock(&ifdescr_sx);
2162 		odescrbuf = ifp->if_description;
2163 		ifp->if_description = descrbuf;
2164 		sx_xunlock(&ifdescr_sx);
2165 
2166 		getmicrotime(&ifp->if_lastchange);
2167 		free(odescrbuf, M_IFDESCR);
2168 		break;
2169 
2170 	case SIOCGIFFIB:
2171 		ifr->ifr_fib = ifp->if_fib;
2172 		break;
2173 
2174 	case SIOCSIFFIB:
2175 		error = priv_check(td, PRIV_NET_SETIFFIB);
2176 		if (error)
2177 			return (error);
2178 		if (ifr->ifr_fib >= rt_numfibs)
2179 			return (EINVAL);
2180 
2181 		ifp->if_fib = ifr->ifr_fib;
2182 		break;
2183 
2184 	case SIOCSIFFLAGS:
2185 		error = priv_check(td, PRIV_NET_SETIFFLAGS);
2186 		if (error)
2187 			return (error);
2188 		/*
2189 		 * Currently, no driver owned flags pass the IFF_CANTCHANGE
2190 		 * check, so we don't need special handling here yet.
2191 		 */
2192 		new_flags = (ifr->ifr_flags & 0xffff) |
2193 		    (ifr->ifr_flagshigh << 16);
2194 		if (ifp->if_flags & IFF_SMART) {
2195 			/* Smart drivers twiddle their own routes */
2196 		} else if (ifp->if_flags & IFF_UP &&
2197 		    (new_flags & IFF_UP) == 0) {
2198 			if_down(ifp);
2199 		} else if (new_flags & IFF_UP &&
2200 		    (ifp->if_flags & IFF_UP) == 0) {
2201 			if_up(ifp);
2202 		}
2203 		/* See if permanently promiscuous mode bit is about to flip */
2204 		if ((ifp->if_flags ^ new_flags) & IFF_PPROMISC) {
2205 			if (new_flags & IFF_PPROMISC)
2206 				ifp->if_flags |= IFF_PROMISC;
2207 			else if (ifp->if_pcount == 0)
2208 				ifp->if_flags &= ~IFF_PROMISC;
2209 			log(LOG_INFO, "%s: permanently promiscuous mode %s\n",
2210 			    ifp->if_xname,
2211 			    (new_flags & IFF_PPROMISC) ? "enabled" : "disabled");
2212 		}
2213 		ifp->if_flags = (ifp->if_flags & IFF_CANTCHANGE) |
2214 			(new_flags &~ IFF_CANTCHANGE);
2215 		if (ifp->if_ioctl) {
2216 			(void) (*ifp->if_ioctl)(ifp, cmd, data);
2217 		}
2218 		getmicrotime(&ifp->if_lastchange);
2219 		break;
2220 
2221 	case SIOCSIFCAP:
2222 		error = priv_check(td, PRIV_NET_SETIFCAP);
2223 		if (error)
2224 			return (error);
2225 		if (ifp->if_ioctl == NULL)
2226 			return (EOPNOTSUPP);
2227 		if (ifr->ifr_reqcap & ~ifp->if_capabilities)
2228 			return (EINVAL);
2229 		error = (*ifp->if_ioctl)(ifp, cmd, data);
2230 		if (error == 0)
2231 			getmicrotime(&ifp->if_lastchange);
2232 		break;
2233 
2234 #ifdef MAC
2235 	case SIOCSIFMAC:
2236 		error = mac_ifnet_ioctl_set(td->td_ucred, ifr, ifp);
2237 		break;
2238 #endif
2239 
2240 	case SIOCSIFNAME:
2241 		error = priv_check(td, PRIV_NET_SETIFNAME);
2242 		if (error)
2243 			return (error);
2244 		error = copyinstr(ifr->ifr_data, new_name, IFNAMSIZ, NULL);
2245 		if (error != 0)
2246 			return (error);
2247 		if (new_name[0] == '\0')
2248 			return (EINVAL);
2249 		if (ifunit(new_name) != NULL)
2250 			return (EEXIST);
2251 
2252 		/*
2253 		 * XXX: Locking.  Nothing else seems to lock if_flags,
2254 		 * and there are numerous other races with the
2255 		 * ifunit() checks not being atomic with namespace
2256 		 * changes (renames, vmoves, if_attach, etc).
2257 		 */
2258 		ifp->if_flags |= IFF_RENAMING;
2259 
2260 		/* Announce the departure of the interface. */
2261 		rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
2262 		EVENTHANDLER_INVOKE(ifnet_departure_event, ifp);
2263 
2264 		log(LOG_INFO, "%s: changing name to '%s'\n",
2265 		    ifp->if_xname, new_name);
2266 
2267 		IF_ADDR_WLOCK(ifp);
2268 		strlcpy(ifp->if_xname, new_name, sizeof(ifp->if_xname));
2269 		ifa = ifp->if_addr;
2270 		sdl = (struct sockaddr_dl *)ifa->ifa_addr;
2271 		namelen = strlen(new_name);
2272 		onamelen = sdl->sdl_nlen;
2273 		/*
2274 		 * Move the address if needed.  This is safe because we
2275 		 * allocate space for a name of length IFNAMSIZ when we
2276 		 * create this in if_attach().
2277 		 */
2278 		if (namelen != onamelen) {
2279 			bcopy(sdl->sdl_data + onamelen,
2280 			    sdl->sdl_data + namelen, sdl->sdl_alen);
2281 		}
2282 		bcopy(new_name, sdl->sdl_data, namelen);
2283 		sdl->sdl_nlen = namelen;
2284 		sdl = (struct sockaddr_dl *)ifa->ifa_netmask;
2285 		bzero(sdl->sdl_data, onamelen);
2286 		while (namelen != 0)
2287 			sdl->sdl_data[--namelen] = 0xff;
2288 		IF_ADDR_WUNLOCK(ifp);
2289 
2290 		EVENTHANDLER_INVOKE(ifnet_arrival_event, ifp);
2291 		/* Announce the return of the interface. */
2292 		rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
2293 
2294 		ifp->if_flags &= ~IFF_RENAMING;
2295 		break;
2296 
2297 #ifdef VIMAGE
2298 	case SIOCSIFVNET:
2299 		error = priv_check(td, PRIV_NET_SETIFVNET);
2300 		if (error)
2301 			return (error);
2302 		error = if_vmove_loan(td, ifp, ifr->ifr_name, ifr->ifr_jid);
2303 		break;
2304 #endif
2305 
2306 	case SIOCSIFMETRIC:
2307 		error = priv_check(td, PRIV_NET_SETIFMETRIC);
2308 		if (error)
2309 			return (error);
2310 		ifp->if_metric = ifr->ifr_metric;
2311 		getmicrotime(&ifp->if_lastchange);
2312 		break;
2313 
2314 	case SIOCSIFPHYS:
2315 		error = priv_check(td, PRIV_NET_SETIFPHYS);
2316 		if (error)
2317 			return (error);
2318 		if (ifp->if_ioctl == NULL)
2319 			return (EOPNOTSUPP);
2320 		error = (*ifp->if_ioctl)(ifp, cmd, data);
2321 		if (error == 0)
2322 			getmicrotime(&ifp->if_lastchange);
2323 		break;
2324 
2325 	case SIOCSIFMTU:
2326 	{
2327 		u_long oldmtu = ifp->if_mtu;
2328 
2329 		error = priv_check(td, PRIV_NET_SETIFMTU);
2330 		if (error)
2331 			return (error);
2332 		if (ifr->ifr_mtu < IF_MINMTU || ifr->ifr_mtu > IF_MAXMTU)
2333 			return (EINVAL);
2334 		if (ifp->if_ioctl == NULL)
2335 			return (EOPNOTSUPP);
2336 		error = (*ifp->if_ioctl)(ifp, cmd, data);
2337 		if (error == 0) {
2338 			getmicrotime(&ifp->if_lastchange);
2339 			rt_ifmsg(ifp);
2340 		}
2341 		/*
2342 		 * If the link MTU changed, do network layer specific procedure.
2343 		 */
2344 		if (ifp->if_mtu != oldmtu) {
2345 #ifdef INET6
2346 			nd6_setmtu(ifp);
2347 #endif
2348 		}
2349 		break;
2350 	}
2351 
2352 	case SIOCADDMULTI:
2353 	case SIOCDELMULTI:
2354 		if (cmd == SIOCADDMULTI)
2355 			error = priv_check(td, PRIV_NET_ADDMULTI);
2356 		else
2357 			error = priv_check(td, PRIV_NET_DELMULTI);
2358 		if (error)
2359 			return (error);
2360 
2361 		/* Don't allow group membership on non-multicast interfaces. */
2362 		if ((ifp->if_flags & IFF_MULTICAST) == 0)
2363 			return (EOPNOTSUPP);
2364 
2365 		/* Don't let users screw up protocols' entries. */
2366 		if (ifr->ifr_addr.sa_family != AF_LINK)
2367 			return (EINVAL);
2368 
2369 		if (cmd == SIOCADDMULTI) {
2370 			struct ifmultiaddr *ifma;
2371 
2372 			/*
2373 			 * Userland is only permitted to join groups once
2374 			 * via the if_addmulti() KPI, because it cannot hold
2375 			 * struct ifmultiaddr * between calls. It may also
2376 			 * lose a race while we check if the membership
2377 			 * already exists.
2378 			 */
2379 			IF_ADDR_RLOCK(ifp);
2380 			ifma = if_findmulti(ifp, &ifr->ifr_addr);
2381 			IF_ADDR_RUNLOCK(ifp);
2382 			if (ifma != NULL)
2383 				error = EADDRINUSE;
2384 			else
2385 				error = if_addmulti(ifp, &ifr->ifr_addr, &ifma);
2386 		} else {
2387 			error = if_delmulti(ifp, &ifr->ifr_addr);
2388 		}
2389 		if (error == 0)
2390 			getmicrotime(&ifp->if_lastchange);
2391 		break;
2392 
2393 	case SIOCSIFPHYADDR:
2394 	case SIOCDIFPHYADDR:
2395 #ifdef INET6
2396 	case SIOCSIFPHYADDR_IN6:
2397 #endif
2398 	case SIOCSLIFPHYADDR:
2399 	case SIOCSIFMEDIA:
2400 	case SIOCSIFGENERIC:
2401 		error = priv_check(td, PRIV_NET_HWIOCTL);
2402 		if (error)
2403 			return (error);
2404 		if (ifp->if_ioctl == NULL)
2405 			return (EOPNOTSUPP);
2406 		error = (*ifp->if_ioctl)(ifp, cmd, data);
2407 		if (error == 0)
2408 			getmicrotime(&ifp->if_lastchange);
2409 		break;
2410 
2411 	case SIOCGIFSTATUS:
2412 		ifs = (struct ifstat *)data;
2413 		ifs->ascii[0] = '\0';
2414 
2415 	case SIOCGIFPSRCADDR:
2416 	case SIOCGIFPDSTADDR:
2417 	case SIOCGLIFPHYADDR:
2418 	case SIOCGIFMEDIA:
2419 	case SIOCGIFGENERIC:
2420 		if (ifp->if_ioctl == NULL)
2421 			return (EOPNOTSUPP);
2422 		error = (*ifp->if_ioctl)(ifp, cmd, data);
2423 		break;
2424 
2425 	case SIOCSIFLLADDR:
2426 		error = priv_check(td, PRIV_NET_SETLLADDR);
2427 		if (error)
2428 			return (error);
2429 		error = if_setlladdr(ifp,
2430 		    ifr->ifr_addr.sa_data, ifr->ifr_addr.sa_len);
2431 		EVENTHANDLER_INVOKE(iflladdr_event, ifp);
2432 		break;
2433 
2434 	case SIOCAIFGROUP:
2435 	{
2436 		struct ifgroupreq *ifgr = (struct ifgroupreq *)ifr;
2437 
2438 		error = priv_check(td, PRIV_NET_ADDIFGROUP);
2439 		if (error)
2440 			return (error);
2441 		if ((error = if_addgroup(ifp, ifgr->ifgr_group)))
2442 			return (error);
2443 		break;
2444 	}
2445 
2446 	case SIOCGIFGROUP:
2447 		if ((error = if_getgroup((struct ifgroupreq *)ifr, ifp)))
2448 			return (error);
2449 		break;
2450 
2451 	case SIOCDIFGROUP:
2452 	{
2453 		struct ifgroupreq *ifgr = (struct ifgroupreq *)ifr;
2454 
2455 		error = priv_check(td, PRIV_NET_DELIFGROUP);
2456 		if (error)
2457 			return (error);
2458 		if ((error = if_delgroup(ifp, ifgr->ifgr_group)))
2459 			return (error);
2460 		break;
2461 	}
2462 
2463 	default:
2464 		error = ENOIOCTL;
2465 		break;
2466 	}
2467 	return (error);
2468 }
2469 
2470 #ifdef COMPAT_FREEBSD32
2471 struct ifconf32 {
2472 	int32_t	ifc_len;
2473 	union {
2474 		uint32_t	ifcu_buf;
2475 		uint32_t	ifcu_req;
2476 	} ifc_ifcu;
2477 };
2478 #define	SIOCGIFCONF32	_IOWR('i', 36, struct ifconf32)
2479 #endif
2480 
2481 /*
2482  * Interface ioctls.
2483  */
2484 int
2485 ifioctl(struct socket *so, u_long cmd, caddr_t data, struct thread *td)
2486 {
2487 	struct ifnet *ifp;
2488 	struct ifreq *ifr;
2489 	int error;
2490 	int oif_flags;
2491 
2492 	CURVNET_SET(so->so_vnet);
2493 	switch (cmd) {
2494 	case SIOCGIFCONF:
2495 	case OSIOCGIFCONF:
2496 		error = ifconf(cmd, data);
2497 		CURVNET_RESTORE();
2498 		return (error);
2499 
2500 #ifdef COMPAT_FREEBSD32
2501 	case SIOCGIFCONF32:
2502 		{
2503 			struct ifconf32 *ifc32;
2504 			struct ifconf ifc;
2505 
2506 			ifc32 = (struct ifconf32 *)data;
2507 			ifc.ifc_len = ifc32->ifc_len;
2508 			ifc.ifc_buf = PTRIN(ifc32->ifc_buf);
2509 
2510 			error = ifconf(SIOCGIFCONF, (void *)&ifc);
2511 			CURVNET_RESTORE();
2512 			if (error == 0)
2513 				ifc32->ifc_len = ifc.ifc_len;
2514 			return (error);
2515 		}
2516 #endif
2517 	}
2518 	ifr = (struct ifreq *)data;
2519 
2520 	switch (cmd) {
2521 #ifdef VIMAGE
2522 	case SIOCSIFRVNET:
2523 		error = priv_check(td, PRIV_NET_SETIFVNET);
2524 		if (error == 0)
2525 			error = if_vmove_reclaim(td, ifr->ifr_name,
2526 			    ifr->ifr_jid);
2527 		CURVNET_RESTORE();
2528 		return (error);
2529 #endif
2530 	case SIOCIFCREATE:
2531 	case SIOCIFCREATE2:
2532 		error = priv_check(td, PRIV_NET_IFCREATE);
2533 		if (error == 0)
2534 			error = if_clone_create(ifr->ifr_name,
2535 			    sizeof(ifr->ifr_name),
2536 			    cmd == SIOCIFCREATE2 ? ifr->ifr_data : NULL);
2537 		CURVNET_RESTORE();
2538 		return (error);
2539 	case SIOCIFDESTROY:
2540 		error = priv_check(td, PRIV_NET_IFDESTROY);
2541 		if (error == 0)
2542 			error = if_clone_destroy(ifr->ifr_name);
2543 		CURVNET_RESTORE();
2544 		return (error);
2545 
2546 	case SIOCIFGCLONERS:
2547 		error = if_clone_list((struct if_clonereq *)data);
2548 		CURVNET_RESTORE();
2549 		return (error);
2550 	case SIOCGIFGMEMB:
2551 		error = if_getgroupmembers((struct ifgroupreq *)data);
2552 		CURVNET_RESTORE();
2553 		return (error);
2554 #if defined(INET) || defined(INET6)
2555 	case SIOCSVH:
2556 	case SIOCGVH:
2557 		if (carp_ioctl_p == NULL)
2558 			error = EPROTONOSUPPORT;
2559 		else
2560 			error = (*carp_ioctl_p)(ifr, cmd, td);
2561 		CURVNET_RESTORE();
2562 		return (error);
2563 #endif
2564 	}
2565 
2566 	ifp = ifunit_ref(ifr->ifr_name);
2567 	if (ifp == NULL) {
2568 		CURVNET_RESTORE();
2569 		return (ENXIO);
2570 	}
2571 
2572 	error = ifhwioctl(cmd, ifp, data, td);
2573 	if (error != ENOIOCTL) {
2574 		if_rele(ifp);
2575 		CURVNET_RESTORE();
2576 		return (error);
2577 	}
2578 
2579 	oif_flags = ifp->if_flags;
2580 	if (so->so_proto == NULL) {
2581 		if_rele(ifp);
2582 		CURVNET_RESTORE();
2583 		return (EOPNOTSUPP);
2584 	}
2585 
2586 	/*
2587 	 * Pass the request on to the socket control method, and if the
2588 	 * latter returns EOPNOTSUPP, directly to the interface.
2589 	 *
2590 	 * Make an exception for the legacy SIOCSIF* requests.  Drivers
2591 	 * trust SIOCSIFADDR et al to come from an already privileged
2592 	 * layer, and do not perform any credentials checks or input
2593 	 * validation.
2594 	 */
2595 #ifndef COMPAT_43
2596 	error = ((*so->so_proto->pr_usrreqs->pru_control)(so, cmd,
2597 								 data,
2598 								 ifp, td));
2599 	if (error == EOPNOTSUPP && ifp != NULL && ifp->if_ioctl != NULL &&
2600 	    cmd != SIOCSIFADDR && cmd != SIOCSIFBRDADDR &&
2601 	    cmd != SIOCSIFDSTADDR && cmd != SIOCSIFNETMASK)
2602 		error = (*ifp->if_ioctl)(ifp, cmd, data);
2603 #else
2604 	{
2605 		u_long ocmd = cmd;
2606 
2607 		switch (cmd) {
2608 
2609 		case SIOCSIFDSTADDR:
2610 		case SIOCSIFADDR:
2611 		case SIOCSIFBRDADDR:
2612 		case SIOCSIFNETMASK:
2613 #if BYTE_ORDER != BIG_ENDIAN
2614 			if (ifr->ifr_addr.sa_family == 0 &&
2615 			    ifr->ifr_addr.sa_len < 16) {
2616 				ifr->ifr_addr.sa_family = ifr->ifr_addr.sa_len;
2617 				ifr->ifr_addr.sa_len = 16;
2618 			}
2619 #else
2620 			if (ifr->ifr_addr.sa_len == 0)
2621 				ifr->ifr_addr.sa_len = 16;
2622 #endif
2623 			break;
2624 
2625 		case OSIOCGIFADDR:
2626 			cmd = SIOCGIFADDR;
2627 			break;
2628 
2629 		case OSIOCGIFDSTADDR:
2630 			cmd = SIOCGIFDSTADDR;
2631 			break;
2632 
2633 		case OSIOCGIFBRDADDR:
2634 			cmd = SIOCGIFBRDADDR;
2635 			break;
2636 
2637 		case OSIOCGIFNETMASK:
2638 			cmd = SIOCGIFNETMASK;
2639 		}
2640 		error =  ((*so->so_proto->pr_usrreqs->pru_control)(so,
2641 								   cmd,
2642 								   data,
2643 								   ifp, td));
2644 		if (error == EOPNOTSUPP && ifp != NULL &&
2645 		    ifp->if_ioctl != NULL &&
2646 		    cmd != SIOCSIFADDR && cmd != SIOCSIFBRDADDR &&
2647 		    cmd != SIOCSIFDSTADDR && cmd != SIOCSIFNETMASK)
2648 			error = (*ifp->if_ioctl)(ifp, cmd, data);
2649 		switch (ocmd) {
2650 
2651 		case OSIOCGIFADDR:
2652 		case OSIOCGIFDSTADDR:
2653 		case OSIOCGIFBRDADDR:
2654 		case OSIOCGIFNETMASK:
2655 			*(u_short *)&ifr->ifr_addr = ifr->ifr_addr.sa_family;
2656 
2657 		}
2658 	}
2659 #endif /* COMPAT_43 */
2660 
2661 	if ((oif_flags ^ ifp->if_flags) & IFF_UP) {
2662 #ifdef INET6
2663 		if (ifp->if_flags & IFF_UP)
2664 			in6_if_up(ifp);
2665 #endif
2666 	}
2667 	if_rele(ifp);
2668 	CURVNET_RESTORE();
2669 	return (error);
2670 }
2671 
2672 /*
2673  * The code common to handling reference counted flags,
2674  * e.g., in ifpromisc() and if_allmulti().
2675  * The "pflag" argument can specify a permanent mode flag to check,
2676  * such as IFF_PPROMISC for promiscuous mode; should be 0 if none.
2677  *
2678  * Only to be used on stack-owned flags, not driver-owned flags.
2679  */
2680 static int
2681 if_setflag(struct ifnet *ifp, int flag, int pflag, int *refcount, int onswitch)
2682 {
2683 	struct ifreq ifr;
2684 	int error;
2685 	int oldflags, oldcount;
2686 
2687 	/* Sanity checks to catch programming errors */
2688 	KASSERT((flag & (IFF_DRV_OACTIVE|IFF_DRV_RUNNING)) == 0,
2689 	    ("%s: setting driver-owned flag %d", __func__, flag));
2690 
2691 	if (onswitch)
2692 		KASSERT(*refcount >= 0,
2693 		    ("%s: increment negative refcount %d for flag %d",
2694 		    __func__, *refcount, flag));
2695 	else
2696 		KASSERT(*refcount > 0,
2697 		    ("%s: decrement non-positive refcount %d for flag %d",
2698 		    __func__, *refcount, flag));
2699 
2700 	/* In case this mode is permanent, just touch refcount */
2701 	if (ifp->if_flags & pflag) {
2702 		*refcount += onswitch ? 1 : -1;
2703 		return (0);
2704 	}
2705 
2706 	/* Save ifnet parameters for if_ioctl() may fail */
2707 	oldcount = *refcount;
2708 	oldflags = ifp->if_flags;
2709 
2710 	/*
2711 	 * See if we aren't the only and touching refcount is enough.
2712 	 * Actually toggle interface flag if we are the first or last.
2713 	 */
2714 	if (onswitch) {
2715 		if ((*refcount)++)
2716 			return (0);
2717 		ifp->if_flags |= flag;
2718 	} else {
2719 		if (--(*refcount))
2720 			return (0);
2721 		ifp->if_flags &= ~flag;
2722 	}
2723 
2724 	/* Call down the driver since we've changed interface flags */
2725 	if (ifp->if_ioctl == NULL) {
2726 		error = EOPNOTSUPP;
2727 		goto recover;
2728 	}
2729 	ifr.ifr_flags = ifp->if_flags & 0xffff;
2730 	ifr.ifr_flagshigh = ifp->if_flags >> 16;
2731 	error = (*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
2732 	if (error)
2733 		goto recover;
2734 	/* Notify userland that interface flags have changed */
2735 	rt_ifmsg(ifp);
2736 	return (0);
2737 
2738 recover:
2739 	/* Recover after driver error */
2740 	*refcount = oldcount;
2741 	ifp->if_flags = oldflags;
2742 	return (error);
2743 }
2744 
2745 /*
2746  * Set/clear promiscuous mode on interface ifp based on the truth value
2747  * of pswitch.  The calls are reference counted so that only the first
2748  * "on" request actually has an effect, as does the final "off" request.
2749  * Results are undefined if the "off" and "on" requests are not matched.
2750  */
2751 int
2752 ifpromisc(struct ifnet *ifp, int pswitch)
2753 {
2754 	int error;
2755 	int oldflags = ifp->if_flags;
2756 
2757 	error = if_setflag(ifp, IFF_PROMISC, IFF_PPROMISC,
2758 			   &ifp->if_pcount, pswitch);
2759 	/* If promiscuous mode status has changed, log a message */
2760 	if (error == 0 && ((ifp->if_flags ^ oldflags) & IFF_PROMISC))
2761 		log(LOG_INFO, "%s: promiscuous mode %s\n",
2762 		    ifp->if_xname,
2763 		    (ifp->if_flags & IFF_PROMISC) ? "enabled" : "disabled");
2764 	return (error);
2765 }
2766 
2767 /*
2768  * Return interface configuration
2769  * of system.  List may be used
2770  * in later ioctl's (above) to get
2771  * other information.
2772  */
2773 /*ARGSUSED*/
2774 static int
2775 ifconf(u_long cmd, caddr_t data)
2776 {
2777 	struct ifconf *ifc = (struct ifconf *)data;
2778 	struct ifnet *ifp;
2779 	struct ifaddr *ifa;
2780 	struct ifreq ifr;
2781 	struct sbuf *sb;
2782 	int error, full = 0, valid_len, max_len;
2783 
2784 	/* Limit initial buffer size to MAXPHYS to avoid DoS from userspace. */
2785 	max_len = MAXPHYS - 1;
2786 
2787 	/* Prevent hostile input from being able to crash the system */
2788 	if (ifc->ifc_len <= 0)
2789 		return (EINVAL);
2790 
2791 again:
2792 	if (ifc->ifc_len <= max_len) {
2793 		max_len = ifc->ifc_len;
2794 		full = 1;
2795 	}
2796 	sb = sbuf_new(NULL, NULL, max_len + 1, SBUF_FIXEDLEN);
2797 	max_len = 0;
2798 	valid_len = 0;
2799 
2800 	IFNET_RLOCK();
2801 	TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2802 		int addrs;
2803 
2804 		/*
2805 		 * Zero the ifr_name buffer to make sure we don't
2806 		 * disclose the contents of the stack.
2807 		 */
2808 		memset(ifr.ifr_name, 0, sizeof(ifr.ifr_name));
2809 
2810 		if (strlcpy(ifr.ifr_name, ifp->if_xname, sizeof(ifr.ifr_name))
2811 		    >= sizeof(ifr.ifr_name)) {
2812 			sbuf_delete(sb);
2813 			IFNET_RUNLOCK();
2814 			return (ENAMETOOLONG);
2815 		}
2816 
2817 		addrs = 0;
2818 		IF_ADDR_RLOCK(ifp);
2819 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
2820 			struct sockaddr *sa = ifa->ifa_addr;
2821 
2822 			if (prison_if(curthread->td_ucred, sa) != 0)
2823 				continue;
2824 			addrs++;
2825 #ifdef COMPAT_43
2826 			if (cmd == OSIOCGIFCONF) {
2827 				struct osockaddr *osa =
2828 					 (struct osockaddr *)&ifr.ifr_addr;
2829 				ifr.ifr_addr = *sa;
2830 				osa->sa_family = sa->sa_family;
2831 				sbuf_bcat(sb, &ifr, sizeof(ifr));
2832 				max_len += sizeof(ifr);
2833 			} else
2834 #endif
2835 			if (sa->sa_len <= sizeof(*sa)) {
2836 				ifr.ifr_addr = *sa;
2837 				sbuf_bcat(sb, &ifr, sizeof(ifr));
2838 				max_len += sizeof(ifr);
2839 			} else {
2840 				sbuf_bcat(sb, &ifr,
2841 				    offsetof(struct ifreq, ifr_addr));
2842 				max_len += offsetof(struct ifreq, ifr_addr);
2843 				sbuf_bcat(sb, sa, sa->sa_len);
2844 				max_len += sa->sa_len;
2845 			}
2846 
2847 			if (sbuf_error(sb) == 0)
2848 				valid_len = sbuf_len(sb);
2849 		}
2850 		IF_ADDR_RUNLOCK(ifp);
2851 		if (addrs == 0) {
2852 			bzero((caddr_t)&ifr.ifr_addr, sizeof(ifr.ifr_addr));
2853 			sbuf_bcat(sb, &ifr, sizeof(ifr));
2854 			max_len += sizeof(ifr);
2855 
2856 			if (sbuf_error(sb) == 0)
2857 				valid_len = sbuf_len(sb);
2858 		}
2859 	}
2860 	IFNET_RUNLOCK();
2861 
2862 	/*
2863 	 * If we didn't allocate enough space (uncommon), try again.  If
2864 	 * we have already allocated as much space as we are allowed,
2865 	 * return what we've got.
2866 	 */
2867 	if (valid_len != max_len && !full) {
2868 		sbuf_delete(sb);
2869 		goto again;
2870 	}
2871 
2872 	ifc->ifc_len = valid_len;
2873 	sbuf_finish(sb);
2874 	error = copyout(sbuf_data(sb), ifc->ifc_req, ifc->ifc_len);
2875 	sbuf_delete(sb);
2876 	return (error);
2877 }
2878 
2879 /*
2880  * Just like ifpromisc(), but for all-multicast-reception mode.
2881  */
2882 int
2883 if_allmulti(struct ifnet *ifp, int onswitch)
2884 {
2885 
2886 	return (if_setflag(ifp, IFF_ALLMULTI, 0, &ifp->if_amcount, onswitch));
2887 }
2888 
2889 struct ifmultiaddr *
2890 if_findmulti(struct ifnet *ifp, struct sockaddr *sa)
2891 {
2892 	struct ifmultiaddr *ifma;
2893 
2894 	IF_ADDR_LOCK_ASSERT(ifp);
2895 
2896 	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2897 		if (sa->sa_family == AF_LINK) {
2898 			if (sa_dl_equal(ifma->ifma_addr, sa))
2899 				break;
2900 		} else {
2901 			if (sa_equal(ifma->ifma_addr, sa))
2902 				break;
2903 		}
2904 	}
2905 
2906 	return ifma;
2907 }
2908 
2909 /*
2910  * Allocate a new ifmultiaddr and initialize based on passed arguments.  We
2911  * make copies of passed sockaddrs.  The ifmultiaddr will not be added to
2912  * the ifnet multicast address list here, so the caller must do that and
2913  * other setup work (such as notifying the device driver).  The reference
2914  * count is initialized to 1.
2915  */
2916 static struct ifmultiaddr *
2917 if_allocmulti(struct ifnet *ifp, struct sockaddr *sa, struct sockaddr *llsa,
2918     int mflags)
2919 {
2920 	struct ifmultiaddr *ifma;
2921 	struct sockaddr *dupsa;
2922 
2923 	ifma = malloc(sizeof *ifma, M_IFMADDR, mflags |
2924 	    M_ZERO);
2925 	if (ifma == NULL)
2926 		return (NULL);
2927 
2928 	dupsa = malloc(sa->sa_len, M_IFMADDR, mflags);
2929 	if (dupsa == NULL) {
2930 		free(ifma, M_IFMADDR);
2931 		return (NULL);
2932 	}
2933 	bcopy(sa, dupsa, sa->sa_len);
2934 	ifma->ifma_addr = dupsa;
2935 
2936 	ifma->ifma_ifp = ifp;
2937 	ifma->ifma_refcount = 1;
2938 	ifma->ifma_protospec = NULL;
2939 
2940 	if (llsa == NULL) {
2941 		ifma->ifma_lladdr = NULL;
2942 		return (ifma);
2943 	}
2944 
2945 	dupsa = malloc(llsa->sa_len, M_IFMADDR, mflags);
2946 	if (dupsa == NULL) {
2947 		free(ifma->ifma_addr, M_IFMADDR);
2948 		free(ifma, M_IFMADDR);
2949 		return (NULL);
2950 	}
2951 	bcopy(llsa, dupsa, llsa->sa_len);
2952 	ifma->ifma_lladdr = dupsa;
2953 
2954 	return (ifma);
2955 }
2956 
2957 /*
2958  * if_freemulti: free ifmultiaddr structure and possibly attached related
2959  * addresses.  The caller is responsible for implementing reference
2960  * counting, notifying the driver, handling routing messages, and releasing
2961  * any dependent link layer state.
2962  */
2963 static void
2964 if_freemulti(struct ifmultiaddr *ifma)
2965 {
2966 
2967 	KASSERT(ifma->ifma_refcount == 0, ("if_freemulti: refcount %d",
2968 	    ifma->ifma_refcount));
2969 	KASSERT(ifma->ifma_protospec == NULL,
2970 	    ("if_freemulti: protospec not NULL"));
2971 
2972 	if (ifma->ifma_lladdr != NULL)
2973 		free(ifma->ifma_lladdr, M_IFMADDR);
2974 	free(ifma->ifma_addr, M_IFMADDR);
2975 	free(ifma, M_IFMADDR);
2976 }
2977 
2978 /*
2979  * Register an additional multicast address with a network interface.
2980  *
2981  * - If the address is already present, bump the reference count on the
2982  *   address and return.
2983  * - If the address is not link-layer, look up a link layer address.
2984  * - Allocate address structures for one or both addresses, and attach to the
2985  *   multicast address list on the interface.  If automatically adding a link
2986  *   layer address, the protocol address will own a reference to the link
2987  *   layer address, to be freed when it is freed.
2988  * - Notify the network device driver of an addition to the multicast address
2989  *   list.
2990  *
2991  * 'sa' points to caller-owned memory with the desired multicast address.
2992  *
2993  * 'retifma' will be used to return a pointer to the resulting multicast
2994  * address reference, if desired.
2995  */
2996 int
2997 if_addmulti(struct ifnet *ifp, struct sockaddr *sa,
2998     struct ifmultiaddr **retifma)
2999 {
3000 	struct ifmultiaddr *ifma, *ll_ifma;
3001 	struct sockaddr *llsa;
3002 	int error;
3003 
3004 	/*
3005 	 * If the address is already present, return a new reference to it;
3006 	 * otherwise, allocate storage and set up a new address.
3007 	 */
3008 	IF_ADDR_WLOCK(ifp);
3009 	ifma = if_findmulti(ifp, sa);
3010 	if (ifma != NULL) {
3011 		ifma->ifma_refcount++;
3012 		if (retifma != NULL)
3013 			*retifma = ifma;
3014 		IF_ADDR_WUNLOCK(ifp);
3015 		return (0);
3016 	}
3017 
3018 	/*
3019 	 * The address isn't already present; resolve the protocol address
3020 	 * into a link layer address, and then look that up, bump its
3021 	 * refcount or allocate an ifma for that also.  If 'llsa' was
3022 	 * returned, we will need to free it later.
3023 	 */
3024 	llsa = NULL;
3025 	ll_ifma = NULL;
3026 	if (ifp->if_resolvemulti != NULL) {
3027 		error = ifp->if_resolvemulti(ifp, &llsa, sa);
3028 		if (error)
3029 			goto unlock_out;
3030 	}
3031 
3032 	/*
3033 	 * Allocate the new address.  Don't hook it up yet, as we may also
3034 	 * need to allocate a link layer multicast address.
3035 	 */
3036 	ifma = if_allocmulti(ifp, sa, llsa, M_NOWAIT);
3037 	if (ifma == NULL) {
3038 		error = ENOMEM;
3039 		goto free_llsa_out;
3040 	}
3041 
3042 	/*
3043 	 * If a link layer address is found, we'll need to see if it's
3044 	 * already present in the address list, or allocate is as well.
3045 	 * When this block finishes, the link layer address will be on the
3046 	 * list.
3047 	 */
3048 	if (llsa != NULL) {
3049 		ll_ifma = if_findmulti(ifp, llsa);
3050 		if (ll_ifma == NULL) {
3051 			ll_ifma = if_allocmulti(ifp, llsa, NULL, M_NOWAIT);
3052 			if (ll_ifma == NULL) {
3053 				--ifma->ifma_refcount;
3054 				if_freemulti(ifma);
3055 				error = ENOMEM;
3056 				goto free_llsa_out;
3057 			}
3058 			TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ll_ifma,
3059 			    ifma_link);
3060 		} else
3061 			ll_ifma->ifma_refcount++;
3062 		ifma->ifma_llifma = ll_ifma;
3063 	}
3064 
3065 	/*
3066 	 * We now have a new multicast address, ifma, and possibly a new or
3067 	 * referenced link layer address.  Add the primary address to the
3068 	 * ifnet address list.
3069 	 */
3070 	TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ifma, ifma_link);
3071 
3072 	if (retifma != NULL)
3073 		*retifma = ifma;
3074 
3075 	/*
3076 	 * Must generate the message while holding the lock so that 'ifma'
3077 	 * pointer is still valid.
3078 	 */
3079 	rt_newmaddrmsg(RTM_NEWMADDR, ifma);
3080 	IF_ADDR_WUNLOCK(ifp);
3081 
3082 	/*
3083 	 * We are certain we have added something, so call down to the
3084 	 * interface to let them know about it.
3085 	 */
3086 	if (ifp->if_ioctl != NULL) {
3087 		(void) (*ifp->if_ioctl)(ifp, SIOCADDMULTI, 0);
3088 	}
3089 
3090 	if (llsa != NULL)
3091 		free(llsa, M_IFMADDR);
3092 
3093 	return (0);
3094 
3095 free_llsa_out:
3096 	if (llsa != NULL)
3097 		free(llsa, M_IFMADDR);
3098 
3099 unlock_out:
3100 	IF_ADDR_WUNLOCK(ifp);
3101 	return (error);
3102 }
3103 
3104 /*
3105  * Delete a multicast group membership by network-layer group address.
3106  *
3107  * Returns ENOENT if the entry could not be found. If ifp no longer
3108  * exists, results are undefined. This entry point should only be used
3109  * from subsystems which do appropriate locking to hold ifp for the
3110  * duration of the call.
3111  * Network-layer protocol domains must use if_delmulti_ifma().
3112  */
3113 int
3114 if_delmulti(struct ifnet *ifp, struct sockaddr *sa)
3115 {
3116 	struct ifmultiaddr *ifma;
3117 	int lastref;
3118 #ifdef INVARIANTS
3119 	struct ifnet *oifp;
3120 
3121 	IFNET_RLOCK_NOSLEEP();
3122 	TAILQ_FOREACH(oifp, &V_ifnet, if_link)
3123 		if (ifp == oifp)
3124 			break;
3125 	if (ifp != oifp)
3126 		ifp = NULL;
3127 	IFNET_RUNLOCK_NOSLEEP();
3128 
3129 	KASSERT(ifp != NULL, ("%s: ifnet went away", __func__));
3130 #endif
3131 	if (ifp == NULL)
3132 		return (ENOENT);
3133 
3134 	IF_ADDR_WLOCK(ifp);
3135 	lastref = 0;
3136 	ifma = if_findmulti(ifp, sa);
3137 	if (ifma != NULL)
3138 		lastref = if_delmulti_locked(ifp, ifma, 0);
3139 	IF_ADDR_WUNLOCK(ifp);
3140 
3141 	if (ifma == NULL)
3142 		return (ENOENT);
3143 
3144 	if (lastref && ifp->if_ioctl != NULL) {
3145 		(void)(*ifp->if_ioctl)(ifp, SIOCDELMULTI, 0);
3146 	}
3147 
3148 	return (0);
3149 }
3150 
3151 /*
3152  * Delete all multicast group membership for an interface.
3153  * Should be used to quickly flush all multicast filters.
3154  */
3155 void
3156 if_delallmulti(struct ifnet *ifp)
3157 {
3158 	struct ifmultiaddr *ifma;
3159 	struct ifmultiaddr *next;
3160 
3161 	IF_ADDR_WLOCK(ifp);
3162 	TAILQ_FOREACH_SAFE(ifma, &ifp->if_multiaddrs, ifma_link, next)
3163 		if_delmulti_locked(ifp, ifma, 0);
3164 	IF_ADDR_WUNLOCK(ifp);
3165 }
3166 
3167 /*
3168  * Delete a multicast group membership by group membership pointer.
3169  * Network-layer protocol domains must use this routine.
3170  *
3171  * It is safe to call this routine if the ifp disappeared.
3172  */
3173 void
3174 if_delmulti_ifma(struct ifmultiaddr *ifma)
3175 {
3176 	struct ifnet *ifp;
3177 	int lastref;
3178 
3179 	ifp = ifma->ifma_ifp;
3180 #ifdef DIAGNOSTIC
3181 	if (ifp == NULL) {
3182 		printf("%s: ifma_ifp seems to be detached\n", __func__);
3183 	} else {
3184 		struct ifnet *oifp;
3185 
3186 		IFNET_RLOCK_NOSLEEP();
3187 		TAILQ_FOREACH(oifp, &V_ifnet, if_link)
3188 			if (ifp == oifp)
3189 				break;
3190 		if (ifp != oifp) {
3191 			printf("%s: ifnet %p disappeared\n", __func__, ifp);
3192 			ifp = NULL;
3193 		}
3194 		IFNET_RUNLOCK_NOSLEEP();
3195 	}
3196 #endif
3197 	/*
3198 	 * If and only if the ifnet instance exists: Acquire the address lock.
3199 	 */
3200 	if (ifp != NULL)
3201 		IF_ADDR_WLOCK(ifp);
3202 
3203 	lastref = if_delmulti_locked(ifp, ifma, 0);
3204 
3205 	if (ifp != NULL) {
3206 		/*
3207 		 * If and only if the ifnet instance exists:
3208 		 *  Release the address lock.
3209 		 *  If the group was left: update the hardware hash filter.
3210 		 */
3211 		IF_ADDR_WUNLOCK(ifp);
3212 		if (lastref && ifp->if_ioctl != NULL) {
3213 			(void)(*ifp->if_ioctl)(ifp, SIOCDELMULTI, 0);
3214 		}
3215 	}
3216 }
3217 
3218 /*
3219  * Perform deletion of network-layer and/or link-layer multicast address.
3220  *
3221  * Return 0 if the reference count was decremented.
3222  * Return 1 if the final reference was released, indicating that the
3223  * hardware hash filter should be reprogrammed.
3224  */
3225 static int
3226 if_delmulti_locked(struct ifnet *ifp, struct ifmultiaddr *ifma, int detaching)
3227 {
3228 	struct ifmultiaddr *ll_ifma;
3229 
3230 	if (ifp != NULL && ifma->ifma_ifp != NULL) {
3231 		KASSERT(ifma->ifma_ifp == ifp,
3232 		    ("%s: inconsistent ifp %p", __func__, ifp));
3233 		IF_ADDR_WLOCK_ASSERT(ifp);
3234 	}
3235 
3236 	ifp = ifma->ifma_ifp;
3237 
3238 	/*
3239 	 * If the ifnet is detaching, null out references to ifnet,
3240 	 * so that upper protocol layers will notice, and not attempt
3241 	 * to obtain locks for an ifnet which no longer exists. The
3242 	 * routing socket announcement must happen before the ifnet
3243 	 * instance is detached from the system.
3244 	 */
3245 	if (detaching) {
3246 #ifdef DIAGNOSTIC
3247 		printf("%s: detaching ifnet instance %p\n", __func__, ifp);
3248 #endif
3249 		/*
3250 		 * ifp may already be nulled out if we are being reentered
3251 		 * to delete the ll_ifma.
3252 		 */
3253 		if (ifp != NULL) {
3254 			rt_newmaddrmsg(RTM_DELMADDR, ifma);
3255 			ifma->ifma_ifp = NULL;
3256 		}
3257 	}
3258 
3259 	if (--ifma->ifma_refcount > 0)
3260 		return 0;
3261 
3262 	/*
3263 	 * If this ifma is a network-layer ifma, a link-layer ifma may
3264 	 * have been associated with it. Release it first if so.
3265 	 */
3266 	ll_ifma = ifma->ifma_llifma;
3267 	if (ll_ifma != NULL) {
3268 		KASSERT(ifma->ifma_lladdr != NULL,
3269 		    ("%s: llifma w/o lladdr", __func__));
3270 		if (detaching)
3271 			ll_ifma->ifma_ifp = NULL;	/* XXX */
3272 		if (--ll_ifma->ifma_refcount == 0) {
3273 			if (ifp != NULL) {
3274 				TAILQ_REMOVE(&ifp->if_multiaddrs, ll_ifma,
3275 				    ifma_link);
3276 			}
3277 			if_freemulti(ll_ifma);
3278 		}
3279 	}
3280 
3281 	if (ifp != NULL)
3282 		TAILQ_REMOVE(&ifp->if_multiaddrs, ifma, ifma_link);
3283 
3284 	if_freemulti(ifma);
3285 
3286 	/*
3287 	 * The last reference to this instance of struct ifmultiaddr
3288 	 * was released; the hardware should be notified of this change.
3289 	 */
3290 	return 1;
3291 }
3292 
3293 /*
3294  * Set the link layer address on an interface.
3295  *
3296  * At this time we only support certain types of interfaces,
3297  * and we don't allow the length of the address to change.
3298  */
3299 int
3300 if_setlladdr(struct ifnet *ifp, const u_char *lladdr, int len)
3301 {
3302 	struct sockaddr_dl *sdl;
3303 	struct ifaddr *ifa;
3304 	struct ifreq ifr;
3305 
3306 	IF_ADDR_RLOCK(ifp);
3307 	ifa = ifp->if_addr;
3308 	if (ifa == NULL) {
3309 		IF_ADDR_RUNLOCK(ifp);
3310 		return (EINVAL);
3311 	}
3312 	ifa_ref(ifa);
3313 	IF_ADDR_RUNLOCK(ifp);
3314 	sdl = (struct sockaddr_dl *)ifa->ifa_addr;
3315 	if (sdl == NULL) {
3316 		ifa_free(ifa);
3317 		return (EINVAL);
3318 	}
3319 	if (len != sdl->sdl_alen) {	/* don't allow length to change */
3320 		ifa_free(ifa);
3321 		return (EINVAL);
3322 	}
3323 	switch (ifp->if_type) {
3324 	case IFT_ETHER:
3325 	case IFT_FDDI:
3326 	case IFT_XETHER:
3327 	case IFT_ISO88025:
3328 	case IFT_L2VLAN:
3329 	case IFT_BRIDGE:
3330 	case IFT_ARCNET:
3331 	case IFT_IEEE8023ADLAG:
3332 	case IFT_IEEE80211:
3333 		bcopy(lladdr, LLADDR(sdl), len);
3334 		ifa_free(ifa);
3335 		break;
3336 	default:
3337 		ifa_free(ifa);
3338 		return (ENODEV);
3339 	}
3340 
3341 	/*
3342 	 * If the interface is already up, we need
3343 	 * to re-init it in order to reprogram its
3344 	 * address filter.
3345 	 */
3346 	if ((ifp->if_flags & IFF_UP) != 0) {
3347 		if (ifp->if_ioctl) {
3348 			ifp->if_flags &= ~IFF_UP;
3349 			ifr.ifr_flags = ifp->if_flags & 0xffff;
3350 			ifr.ifr_flagshigh = ifp->if_flags >> 16;
3351 			(*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
3352 			ifp->if_flags |= IFF_UP;
3353 			ifr.ifr_flags = ifp->if_flags & 0xffff;
3354 			ifr.ifr_flagshigh = ifp->if_flags >> 16;
3355 			(*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
3356 		}
3357 #ifdef INET
3358 		/*
3359 		 * Also send gratuitous ARPs to notify other nodes about
3360 		 * the address change.
3361 		 */
3362 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
3363 			if (ifa->ifa_addr->sa_family == AF_INET)
3364 				arp_ifinit(ifp, ifa);
3365 		}
3366 #endif
3367 	}
3368 	return (0);
3369 }
3370 
3371 /*
3372  * The name argument must be a pointer to storage which will last as
3373  * long as the interface does.  For physical devices, the result of
3374  * device_get_name(dev) is a good choice and for pseudo-devices a
3375  * static string works well.
3376  */
3377 void
3378 if_initname(struct ifnet *ifp, const char *name, int unit)
3379 {
3380 	ifp->if_dname = name;
3381 	ifp->if_dunit = unit;
3382 	if (unit != IF_DUNIT_NONE)
3383 		snprintf(ifp->if_xname, IFNAMSIZ, "%s%d", name, unit);
3384 	else
3385 		strlcpy(ifp->if_xname, name, IFNAMSIZ);
3386 }
3387 
3388 int
3389 if_printf(struct ifnet *ifp, const char * fmt, ...)
3390 {
3391 	va_list ap;
3392 	int retval;
3393 
3394 	retval = printf("%s: ", ifp->if_xname);
3395 	va_start(ap, fmt);
3396 	retval += vprintf(fmt, ap);
3397 	va_end(ap);
3398 	return (retval);
3399 }
3400 
3401 void
3402 if_start(struct ifnet *ifp)
3403 {
3404 
3405 	(*(ifp)->if_start)(ifp);
3406 }
3407 
3408 /*
3409  * Backwards compatibility interface for drivers
3410  * that have not implemented it
3411  */
3412 static int
3413 if_transmit(struct ifnet *ifp, struct mbuf *m)
3414 {
3415 	int error;
3416 
3417 	IFQ_HANDOFF(ifp, m, error);
3418 	return (error);
3419 }
3420 
3421 int
3422 if_handoff(struct ifqueue *ifq, struct mbuf *m, struct ifnet *ifp, int adjust)
3423 {
3424 	int active = 0;
3425 
3426 	IF_LOCK(ifq);
3427 	if (_IF_QFULL(ifq)) {
3428 		_IF_DROP(ifq);
3429 		IF_UNLOCK(ifq);
3430 		m_freem(m);
3431 		return (0);
3432 	}
3433 	if (ifp != NULL) {
3434 		ifp->if_obytes += m->m_pkthdr.len + adjust;
3435 		if (m->m_flags & (M_BCAST|M_MCAST))
3436 			ifp->if_omcasts++;
3437 		active = ifp->if_drv_flags & IFF_DRV_OACTIVE;
3438 	}
3439 	_IF_ENQUEUE(ifq, m);
3440 	IF_UNLOCK(ifq);
3441 	if (ifp != NULL && !active)
3442 		(*(ifp)->if_start)(ifp);
3443 	return (1);
3444 }
3445 
3446 void
3447 if_register_com_alloc(u_char type,
3448     if_com_alloc_t *a, if_com_free_t *f)
3449 {
3450 
3451 	KASSERT(if_com_alloc[type] == NULL,
3452 	    ("if_register_com_alloc: %d already registered", type));
3453 	KASSERT(if_com_free[type] == NULL,
3454 	    ("if_register_com_alloc: %d free already registered", type));
3455 
3456 	if_com_alloc[type] = a;
3457 	if_com_free[type] = f;
3458 }
3459 
3460 void
3461 if_deregister_com_alloc(u_char type)
3462 {
3463 
3464 	KASSERT(if_com_alloc[type] != NULL,
3465 	    ("if_deregister_com_alloc: %d not registered", type));
3466 	KASSERT(if_com_free[type] != NULL,
3467 	    ("if_deregister_com_alloc: %d free not registered", type));
3468 	if_com_alloc[type] = NULL;
3469 	if_com_free[type] = NULL;
3470 }
3471