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