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