xref: /freebsd/sys/net/if.c (revision 46902503bc85c7b5fcdfb06e027ad756e083b3a4)
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 #ifndef COMPAT_43
2557 	error = ((*so->so_proto->pr_usrreqs->pru_control)(so, cmd,
2558 								 data,
2559 								 ifp, td));
2560 	if (error == EOPNOTSUPP && ifp != NULL && ifp->if_ioctl != NULL)
2561 		error = (*ifp->if_ioctl)(ifp, cmd, data);
2562 #else
2563 	{
2564 		u_long ocmd = cmd;
2565 
2566 		switch (cmd) {
2567 
2568 		case SIOCSIFDSTADDR:
2569 		case SIOCSIFADDR:
2570 		case SIOCSIFBRDADDR:
2571 		case SIOCSIFNETMASK:
2572 #if BYTE_ORDER != BIG_ENDIAN
2573 			if (ifr->ifr_addr.sa_family == 0 &&
2574 			    ifr->ifr_addr.sa_len < 16) {
2575 				ifr->ifr_addr.sa_family = ifr->ifr_addr.sa_len;
2576 				ifr->ifr_addr.sa_len = 16;
2577 			}
2578 #else
2579 			if (ifr->ifr_addr.sa_len == 0)
2580 				ifr->ifr_addr.sa_len = 16;
2581 #endif
2582 			break;
2583 
2584 		case OSIOCGIFADDR:
2585 			cmd = SIOCGIFADDR;
2586 			break;
2587 
2588 		case OSIOCGIFDSTADDR:
2589 			cmd = SIOCGIFDSTADDR;
2590 			break;
2591 
2592 		case OSIOCGIFBRDADDR:
2593 			cmd = SIOCGIFBRDADDR;
2594 			break;
2595 
2596 		case OSIOCGIFNETMASK:
2597 			cmd = SIOCGIFNETMASK;
2598 		}
2599 		error =  ((*so->so_proto->pr_usrreqs->pru_control)(so,
2600 								   cmd,
2601 								   data,
2602 								   ifp, td));
2603 		if (error == EOPNOTSUPP && ifp != NULL &&
2604 		    ifp->if_ioctl != NULL)
2605 			error = (*ifp->if_ioctl)(ifp, cmd, data);
2606 		switch (ocmd) {
2607 
2608 		case OSIOCGIFADDR:
2609 		case OSIOCGIFDSTADDR:
2610 		case OSIOCGIFBRDADDR:
2611 		case OSIOCGIFNETMASK:
2612 			*(u_short *)&ifr->ifr_addr = ifr->ifr_addr.sa_family;
2613 
2614 		}
2615 	}
2616 #endif /* COMPAT_43 */
2617 
2618 	if ((oif_flags ^ ifp->if_flags) & IFF_UP) {
2619 #ifdef INET6
2620 		if (ifp->if_flags & IFF_UP)
2621 			in6_if_up(ifp);
2622 #endif
2623 	}
2624 	if_rele(ifp);
2625 	CURVNET_RESTORE();
2626 	return (error);
2627 }
2628 
2629 /*
2630  * The code common to handling reference counted flags,
2631  * e.g., in ifpromisc() and if_allmulti().
2632  * The "pflag" argument can specify a permanent mode flag to check,
2633  * such as IFF_PPROMISC for promiscuous mode; should be 0 if none.
2634  *
2635  * Only to be used on stack-owned flags, not driver-owned flags.
2636  */
2637 static int
2638 if_setflag(struct ifnet *ifp, int flag, int pflag, int *refcount, int onswitch)
2639 {
2640 	struct ifreq ifr;
2641 	int error;
2642 	int oldflags, oldcount;
2643 
2644 	/* Sanity checks to catch programming errors */
2645 	KASSERT((flag & (IFF_DRV_OACTIVE|IFF_DRV_RUNNING)) == 0,
2646 	    ("%s: setting driver-owned flag %d", __func__, flag));
2647 
2648 	if (onswitch)
2649 		KASSERT(*refcount >= 0,
2650 		    ("%s: increment negative refcount %d for flag %d",
2651 		    __func__, *refcount, flag));
2652 	else
2653 		KASSERT(*refcount > 0,
2654 		    ("%s: decrement non-positive refcount %d for flag %d",
2655 		    __func__, *refcount, flag));
2656 
2657 	/* In case this mode is permanent, just touch refcount */
2658 	if (ifp->if_flags & pflag) {
2659 		*refcount += onswitch ? 1 : -1;
2660 		return (0);
2661 	}
2662 
2663 	/* Save ifnet parameters for if_ioctl() may fail */
2664 	oldcount = *refcount;
2665 	oldflags = ifp->if_flags;
2666 
2667 	/*
2668 	 * See if we aren't the only and touching refcount is enough.
2669 	 * Actually toggle interface flag if we are the first or last.
2670 	 */
2671 	if (onswitch) {
2672 		if ((*refcount)++)
2673 			return (0);
2674 		ifp->if_flags |= flag;
2675 	} else {
2676 		if (--(*refcount))
2677 			return (0);
2678 		ifp->if_flags &= ~flag;
2679 	}
2680 
2681 	/* Call down the driver since we've changed interface flags */
2682 	if (ifp->if_ioctl == NULL) {
2683 		error = EOPNOTSUPP;
2684 		goto recover;
2685 	}
2686 	ifr.ifr_flags = ifp->if_flags & 0xffff;
2687 	ifr.ifr_flagshigh = ifp->if_flags >> 16;
2688 	error = (*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
2689 	if (error)
2690 		goto recover;
2691 	/* Notify userland that interface flags have changed */
2692 	rt_ifmsg(ifp);
2693 	return (0);
2694 
2695 recover:
2696 	/* Recover after driver error */
2697 	*refcount = oldcount;
2698 	ifp->if_flags = oldflags;
2699 	return (error);
2700 }
2701 
2702 /*
2703  * Set/clear promiscuous mode on interface ifp based on the truth value
2704  * of pswitch.  The calls are reference counted so that only the first
2705  * "on" request actually has an effect, as does the final "off" request.
2706  * Results are undefined if the "off" and "on" requests are not matched.
2707  */
2708 int
2709 ifpromisc(struct ifnet *ifp, int pswitch)
2710 {
2711 	int error;
2712 	int oldflags = ifp->if_flags;
2713 
2714 	error = if_setflag(ifp, IFF_PROMISC, IFF_PPROMISC,
2715 			   &ifp->if_pcount, pswitch);
2716 	/* If promiscuous mode status has changed, log a message */
2717 	if (error == 0 && ((ifp->if_flags ^ oldflags) & IFF_PROMISC))
2718 		log(LOG_INFO, "%s: promiscuous mode %s\n",
2719 		    ifp->if_xname,
2720 		    (ifp->if_flags & IFF_PROMISC) ? "enabled" : "disabled");
2721 	return (error);
2722 }
2723 
2724 /*
2725  * Return interface configuration
2726  * of system.  List may be used
2727  * in later ioctl's (above) to get
2728  * other information.
2729  */
2730 /*ARGSUSED*/
2731 static int
2732 ifconf(u_long cmd, caddr_t data)
2733 {
2734 	struct ifconf *ifc = (struct ifconf *)data;
2735 	struct ifnet *ifp;
2736 	struct ifaddr *ifa;
2737 	struct ifreq ifr;
2738 	struct sbuf *sb;
2739 	int error, full = 0, valid_len, max_len;
2740 
2741 	/* Limit initial buffer size to MAXPHYS to avoid DoS from userspace. */
2742 	max_len = MAXPHYS - 1;
2743 
2744 	/* Prevent hostile input from being able to crash the system */
2745 	if (ifc->ifc_len <= 0)
2746 		return (EINVAL);
2747 
2748 again:
2749 	if (ifc->ifc_len <= max_len) {
2750 		max_len = ifc->ifc_len;
2751 		full = 1;
2752 	}
2753 	sb = sbuf_new(NULL, NULL, max_len + 1, SBUF_FIXEDLEN);
2754 	max_len = 0;
2755 	valid_len = 0;
2756 
2757 	IFNET_RLOCK();
2758 	TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2759 		int addrs;
2760 
2761 		/*
2762 		 * Zero the ifr_name buffer to make sure we don't
2763 		 * disclose the contents of the stack.
2764 		 */
2765 		memset(ifr.ifr_name, 0, sizeof(ifr.ifr_name));
2766 
2767 		if (strlcpy(ifr.ifr_name, ifp->if_xname, sizeof(ifr.ifr_name))
2768 		    >= sizeof(ifr.ifr_name)) {
2769 			sbuf_delete(sb);
2770 			IFNET_RUNLOCK();
2771 			return (ENAMETOOLONG);
2772 		}
2773 
2774 		addrs = 0;
2775 		IF_ADDR_RLOCK(ifp);
2776 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
2777 			struct sockaddr *sa = ifa->ifa_addr;
2778 
2779 			if (prison_if(curthread->td_ucred, sa) != 0)
2780 				continue;
2781 			addrs++;
2782 #ifdef COMPAT_43
2783 			if (cmd == OSIOCGIFCONF) {
2784 				struct osockaddr *osa =
2785 					 (struct osockaddr *)&ifr.ifr_addr;
2786 				ifr.ifr_addr = *sa;
2787 				osa->sa_family = sa->sa_family;
2788 				sbuf_bcat(sb, &ifr, sizeof(ifr));
2789 				max_len += sizeof(ifr);
2790 			} else
2791 #endif
2792 			if (sa->sa_len <= sizeof(*sa)) {
2793 				ifr.ifr_addr = *sa;
2794 				sbuf_bcat(sb, &ifr, sizeof(ifr));
2795 				max_len += sizeof(ifr);
2796 			} else {
2797 				sbuf_bcat(sb, &ifr,
2798 				    offsetof(struct ifreq, ifr_addr));
2799 				max_len += offsetof(struct ifreq, ifr_addr);
2800 				sbuf_bcat(sb, sa, sa->sa_len);
2801 				max_len += sa->sa_len;
2802 			}
2803 
2804 			if (sbuf_error(sb) == 0)
2805 				valid_len = sbuf_len(sb);
2806 		}
2807 		IF_ADDR_RUNLOCK(ifp);
2808 		if (addrs == 0) {
2809 			bzero((caddr_t)&ifr.ifr_addr, sizeof(ifr.ifr_addr));
2810 			sbuf_bcat(sb, &ifr, sizeof(ifr));
2811 			max_len += sizeof(ifr);
2812 
2813 			if (sbuf_error(sb) == 0)
2814 				valid_len = sbuf_len(sb);
2815 		}
2816 	}
2817 	IFNET_RUNLOCK();
2818 
2819 	/*
2820 	 * If we didn't allocate enough space (uncommon), try again.  If
2821 	 * we have already allocated as much space as we are allowed,
2822 	 * return what we've got.
2823 	 */
2824 	if (valid_len != max_len && !full) {
2825 		sbuf_delete(sb);
2826 		goto again;
2827 	}
2828 
2829 	ifc->ifc_len = valid_len;
2830 	sbuf_finish(sb);
2831 	error = copyout(sbuf_data(sb), ifc->ifc_req, ifc->ifc_len);
2832 	sbuf_delete(sb);
2833 	return (error);
2834 }
2835 
2836 /*
2837  * Just like ifpromisc(), but for all-multicast-reception mode.
2838  */
2839 int
2840 if_allmulti(struct ifnet *ifp, int onswitch)
2841 {
2842 
2843 	return (if_setflag(ifp, IFF_ALLMULTI, 0, &ifp->if_amcount, onswitch));
2844 }
2845 
2846 struct ifmultiaddr *
2847 if_findmulti(struct ifnet *ifp, struct sockaddr *sa)
2848 {
2849 	struct ifmultiaddr *ifma;
2850 
2851 	IF_ADDR_LOCK_ASSERT(ifp);
2852 
2853 	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2854 		if (sa->sa_family == AF_LINK) {
2855 			if (sa_dl_equal(ifma->ifma_addr, sa))
2856 				break;
2857 		} else {
2858 			if (sa_equal(ifma->ifma_addr, sa))
2859 				break;
2860 		}
2861 	}
2862 
2863 	return ifma;
2864 }
2865 
2866 /*
2867  * Allocate a new ifmultiaddr and initialize based on passed arguments.  We
2868  * make copies of passed sockaddrs.  The ifmultiaddr will not be added to
2869  * the ifnet multicast address list here, so the caller must do that and
2870  * other setup work (such as notifying the device driver).  The reference
2871  * count is initialized to 1.
2872  */
2873 static struct ifmultiaddr *
2874 if_allocmulti(struct ifnet *ifp, struct sockaddr *sa, struct sockaddr *llsa,
2875     int mflags)
2876 {
2877 	struct ifmultiaddr *ifma;
2878 	struct sockaddr *dupsa;
2879 
2880 	ifma = malloc(sizeof *ifma, M_IFMADDR, mflags |
2881 	    M_ZERO);
2882 	if (ifma == NULL)
2883 		return (NULL);
2884 
2885 	dupsa = malloc(sa->sa_len, M_IFMADDR, mflags);
2886 	if (dupsa == NULL) {
2887 		free(ifma, M_IFMADDR);
2888 		return (NULL);
2889 	}
2890 	bcopy(sa, dupsa, sa->sa_len);
2891 	ifma->ifma_addr = dupsa;
2892 
2893 	ifma->ifma_ifp = ifp;
2894 	ifma->ifma_refcount = 1;
2895 	ifma->ifma_protospec = NULL;
2896 
2897 	if (llsa == NULL) {
2898 		ifma->ifma_lladdr = NULL;
2899 		return (ifma);
2900 	}
2901 
2902 	dupsa = malloc(llsa->sa_len, M_IFMADDR, mflags);
2903 	if (dupsa == NULL) {
2904 		free(ifma->ifma_addr, M_IFMADDR);
2905 		free(ifma, M_IFMADDR);
2906 		return (NULL);
2907 	}
2908 	bcopy(llsa, dupsa, llsa->sa_len);
2909 	ifma->ifma_lladdr = dupsa;
2910 
2911 	return (ifma);
2912 }
2913 
2914 /*
2915  * if_freemulti: free ifmultiaddr structure and possibly attached related
2916  * addresses.  The caller is responsible for implementing reference
2917  * counting, notifying the driver, handling routing messages, and releasing
2918  * any dependent link layer state.
2919  */
2920 static void
2921 if_freemulti(struct ifmultiaddr *ifma)
2922 {
2923 
2924 	KASSERT(ifma->ifma_refcount == 0, ("if_freemulti: refcount %d",
2925 	    ifma->ifma_refcount));
2926 	KASSERT(ifma->ifma_protospec == NULL,
2927 	    ("if_freemulti: protospec not NULL"));
2928 
2929 	if (ifma->ifma_lladdr != NULL)
2930 		free(ifma->ifma_lladdr, M_IFMADDR);
2931 	free(ifma->ifma_addr, M_IFMADDR);
2932 	free(ifma, M_IFMADDR);
2933 }
2934 
2935 /*
2936  * Register an additional multicast address with a network interface.
2937  *
2938  * - If the address is already present, bump the reference count on the
2939  *   address and return.
2940  * - If the address is not link-layer, look up a link layer address.
2941  * - Allocate address structures for one or both addresses, and attach to the
2942  *   multicast address list on the interface.  If automatically adding a link
2943  *   layer address, the protocol address will own a reference to the link
2944  *   layer address, to be freed when it is freed.
2945  * - Notify the network device driver of an addition to the multicast address
2946  *   list.
2947  *
2948  * 'sa' points to caller-owned memory with the desired multicast address.
2949  *
2950  * 'retifma' will be used to return a pointer to the resulting multicast
2951  * address reference, if desired.
2952  */
2953 int
2954 if_addmulti(struct ifnet *ifp, struct sockaddr *sa,
2955     struct ifmultiaddr **retifma)
2956 {
2957 	struct ifmultiaddr *ifma, *ll_ifma;
2958 	struct sockaddr *llsa;
2959 	int error;
2960 
2961 	/*
2962 	 * If the address is already present, return a new reference to it;
2963 	 * otherwise, allocate storage and set up a new address.
2964 	 */
2965 	IF_ADDR_WLOCK(ifp);
2966 	ifma = if_findmulti(ifp, sa);
2967 	if (ifma != NULL) {
2968 		ifma->ifma_refcount++;
2969 		if (retifma != NULL)
2970 			*retifma = ifma;
2971 		IF_ADDR_WUNLOCK(ifp);
2972 		return (0);
2973 	}
2974 
2975 	/*
2976 	 * The address isn't already present; resolve the protocol address
2977 	 * into a link layer address, and then look that up, bump its
2978 	 * refcount or allocate an ifma for that also.  If 'llsa' was
2979 	 * returned, we will need to free it later.
2980 	 */
2981 	llsa = NULL;
2982 	ll_ifma = NULL;
2983 	if (ifp->if_resolvemulti != NULL) {
2984 		error = ifp->if_resolvemulti(ifp, &llsa, sa);
2985 		if (error)
2986 			goto unlock_out;
2987 	}
2988 
2989 	/*
2990 	 * Allocate the new address.  Don't hook it up yet, as we may also
2991 	 * need to allocate a link layer multicast address.
2992 	 */
2993 	ifma = if_allocmulti(ifp, sa, llsa, M_NOWAIT);
2994 	if (ifma == NULL) {
2995 		error = ENOMEM;
2996 		goto free_llsa_out;
2997 	}
2998 
2999 	/*
3000 	 * If a link layer address is found, we'll need to see if it's
3001 	 * already present in the address list, or allocate is as well.
3002 	 * When this block finishes, the link layer address will be on the
3003 	 * list.
3004 	 */
3005 	if (llsa != NULL) {
3006 		ll_ifma = if_findmulti(ifp, llsa);
3007 		if (ll_ifma == NULL) {
3008 			ll_ifma = if_allocmulti(ifp, llsa, NULL, M_NOWAIT);
3009 			if (ll_ifma == NULL) {
3010 				--ifma->ifma_refcount;
3011 				if_freemulti(ifma);
3012 				error = ENOMEM;
3013 				goto free_llsa_out;
3014 			}
3015 			TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ll_ifma,
3016 			    ifma_link);
3017 		} else
3018 			ll_ifma->ifma_refcount++;
3019 		ifma->ifma_llifma = ll_ifma;
3020 	}
3021 
3022 	/*
3023 	 * We now have a new multicast address, ifma, and possibly a new or
3024 	 * referenced link layer address.  Add the primary address to the
3025 	 * ifnet address list.
3026 	 */
3027 	TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ifma, ifma_link);
3028 
3029 	if (retifma != NULL)
3030 		*retifma = ifma;
3031 
3032 	/*
3033 	 * Must generate the message while holding the lock so that 'ifma'
3034 	 * pointer is still valid.
3035 	 */
3036 	rt_newmaddrmsg(RTM_NEWMADDR, ifma);
3037 	IF_ADDR_WUNLOCK(ifp);
3038 
3039 	/*
3040 	 * We are certain we have added something, so call down to the
3041 	 * interface to let them know about it.
3042 	 */
3043 	if (ifp->if_ioctl != NULL) {
3044 		(void) (*ifp->if_ioctl)(ifp, SIOCADDMULTI, 0);
3045 	}
3046 
3047 	if (llsa != NULL)
3048 		free(llsa, M_IFMADDR);
3049 
3050 	return (0);
3051 
3052 free_llsa_out:
3053 	if (llsa != NULL)
3054 		free(llsa, M_IFMADDR);
3055 
3056 unlock_out:
3057 	IF_ADDR_WUNLOCK(ifp);
3058 	return (error);
3059 }
3060 
3061 /*
3062  * Delete a multicast group membership by network-layer group address.
3063  *
3064  * Returns ENOENT if the entry could not be found. If ifp no longer
3065  * exists, results are undefined. This entry point should only be used
3066  * from subsystems which do appropriate locking to hold ifp for the
3067  * duration of the call.
3068  * Network-layer protocol domains must use if_delmulti_ifma().
3069  */
3070 int
3071 if_delmulti(struct ifnet *ifp, struct sockaddr *sa)
3072 {
3073 	struct ifmultiaddr *ifma;
3074 	int lastref;
3075 #ifdef INVARIANTS
3076 	struct ifnet *oifp;
3077 
3078 	IFNET_RLOCK_NOSLEEP();
3079 	TAILQ_FOREACH(oifp, &V_ifnet, if_link)
3080 		if (ifp == oifp)
3081 			break;
3082 	if (ifp != oifp)
3083 		ifp = NULL;
3084 	IFNET_RUNLOCK_NOSLEEP();
3085 
3086 	KASSERT(ifp != NULL, ("%s: ifnet went away", __func__));
3087 #endif
3088 	if (ifp == NULL)
3089 		return (ENOENT);
3090 
3091 	IF_ADDR_WLOCK(ifp);
3092 	lastref = 0;
3093 	ifma = if_findmulti(ifp, sa);
3094 	if (ifma != NULL)
3095 		lastref = if_delmulti_locked(ifp, ifma, 0);
3096 	IF_ADDR_WUNLOCK(ifp);
3097 
3098 	if (ifma == NULL)
3099 		return (ENOENT);
3100 
3101 	if (lastref && ifp->if_ioctl != NULL) {
3102 		(void)(*ifp->if_ioctl)(ifp, SIOCDELMULTI, 0);
3103 	}
3104 
3105 	return (0);
3106 }
3107 
3108 /*
3109  * Delete all multicast group membership for an interface.
3110  * Should be used to quickly flush all multicast filters.
3111  */
3112 void
3113 if_delallmulti(struct ifnet *ifp)
3114 {
3115 	struct ifmultiaddr *ifma;
3116 	struct ifmultiaddr *next;
3117 
3118 	IF_ADDR_WLOCK(ifp);
3119 	TAILQ_FOREACH_SAFE(ifma, &ifp->if_multiaddrs, ifma_link, next)
3120 		if_delmulti_locked(ifp, ifma, 0);
3121 	IF_ADDR_WUNLOCK(ifp);
3122 }
3123 
3124 /*
3125  * Delete a multicast group membership by group membership pointer.
3126  * Network-layer protocol domains must use this routine.
3127  *
3128  * It is safe to call this routine if the ifp disappeared.
3129  */
3130 void
3131 if_delmulti_ifma(struct ifmultiaddr *ifma)
3132 {
3133 	struct ifnet *ifp;
3134 	int lastref;
3135 
3136 	ifp = ifma->ifma_ifp;
3137 #ifdef DIAGNOSTIC
3138 	if (ifp == NULL) {
3139 		printf("%s: ifma_ifp seems to be detached\n", __func__);
3140 	} else {
3141 		struct ifnet *oifp;
3142 
3143 		IFNET_RLOCK_NOSLEEP();
3144 		TAILQ_FOREACH(oifp, &V_ifnet, if_link)
3145 			if (ifp == oifp)
3146 				break;
3147 		if (ifp != oifp) {
3148 			printf("%s: ifnet %p disappeared\n", __func__, ifp);
3149 			ifp = NULL;
3150 		}
3151 		IFNET_RUNLOCK_NOSLEEP();
3152 	}
3153 #endif
3154 	/*
3155 	 * If and only if the ifnet instance exists: Acquire the address lock.
3156 	 */
3157 	if (ifp != NULL)
3158 		IF_ADDR_WLOCK(ifp);
3159 
3160 	lastref = if_delmulti_locked(ifp, ifma, 0);
3161 
3162 	if (ifp != NULL) {
3163 		/*
3164 		 * If and only if the ifnet instance exists:
3165 		 *  Release the address lock.
3166 		 *  If the group was left: update the hardware hash filter.
3167 		 */
3168 		IF_ADDR_WUNLOCK(ifp);
3169 		if (lastref && ifp->if_ioctl != NULL) {
3170 			(void)(*ifp->if_ioctl)(ifp, SIOCDELMULTI, 0);
3171 		}
3172 	}
3173 }
3174 
3175 /*
3176  * Perform deletion of network-layer and/or link-layer multicast address.
3177  *
3178  * Return 0 if the reference count was decremented.
3179  * Return 1 if the final reference was released, indicating that the
3180  * hardware hash filter should be reprogrammed.
3181  */
3182 static int
3183 if_delmulti_locked(struct ifnet *ifp, struct ifmultiaddr *ifma, int detaching)
3184 {
3185 	struct ifmultiaddr *ll_ifma;
3186 
3187 	if (ifp != NULL && ifma->ifma_ifp != NULL) {
3188 		KASSERT(ifma->ifma_ifp == ifp,
3189 		    ("%s: inconsistent ifp %p", __func__, ifp));
3190 		IF_ADDR_WLOCK_ASSERT(ifp);
3191 	}
3192 
3193 	ifp = ifma->ifma_ifp;
3194 
3195 	/*
3196 	 * If the ifnet is detaching, null out references to ifnet,
3197 	 * so that upper protocol layers will notice, and not attempt
3198 	 * to obtain locks for an ifnet which no longer exists. The
3199 	 * routing socket announcement must happen before the ifnet
3200 	 * instance is detached from the system.
3201 	 */
3202 	if (detaching) {
3203 #ifdef DIAGNOSTIC
3204 		printf("%s: detaching ifnet instance %p\n", __func__, ifp);
3205 #endif
3206 		/*
3207 		 * ifp may already be nulled out if we are being reentered
3208 		 * to delete the ll_ifma.
3209 		 */
3210 		if (ifp != NULL) {
3211 			rt_newmaddrmsg(RTM_DELMADDR, ifma);
3212 			ifma->ifma_ifp = NULL;
3213 		}
3214 	}
3215 
3216 	if (--ifma->ifma_refcount > 0)
3217 		return 0;
3218 
3219 	/*
3220 	 * If this ifma is a network-layer ifma, a link-layer ifma may
3221 	 * have been associated with it. Release it first if so.
3222 	 */
3223 	ll_ifma = ifma->ifma_llifma;
3224 	if (ll_ifma != NULL) {
3225 		KASSERT(ifma->ifma_lladdr != NULL,
3226 		    ("%s: llifma w/o lladdr", __func__));
3227 		if (detaching)
3228 			ll_ifma->ifma_ifp = NULL;	/* XXX */
3229 		if (--ll_ifma->ifma_refcount == 0) {
3230 			if (ifp != NULL) {
3231 				TAILQ_REMOVE(&ifp->if_multiaddrs, ll_ifma,
3232 				    ifma_link);
3233 			}
3234 			if_freemulti(ll_ifma);
3235 		}
3236 	}
3237 
3238 	if (ifp != NULL)
3239 		TAILQ_REMOVE(&ifp->if_multiaddrs, ifma, ifma_link);
3240 
3241 	if_freemulti(ifma);
3242 
3243 	/*
3244 	 * The last reference to this instance of struct ifmultiaddr
3245 	 * was released; the hardware should be notified of this change.
3246 	 */
3247 	return 1;
3248 }
3249 
3250 /*
3251  * Set the link layer address on an interface.
3252  *
3253  * At this time we only support certain types of interfaces,
3254  * and we don't allow the length of the address to change.
3255  */
3256 int
3257 if_setlladdr(struct ifnet *ifp, const u_char *lladdr, int len)
3258 {
3259 	struct sockaddr_dl *sdl;
3260 	struct ifaddr *ifa;
3261 	struct ifreq ifr;
3262 
3263 	IF_ADDR_RLOCK(ifp);
3264 	ifa = ifp->if_addr;
3265 	if (ifa == NULL) {
3266 		IF_ADDR_RUNLOCK(ifp);
3267 		return (EINVAL);
3268 	}
3269 	ifa_ref(ifa);
3270 	IF_ADDR_RUNLOCK(ifp);
3271 	sdl = (struct sockaddr_dl *)ifa->ifa_addr;
3272 	if (sdl == NULL) {
3273 		ifa_free(ifa);
3274 		return (EINVAL);
3275 	}
3276 	if (len != sdl->sdl_alen) {	/* don't allow length to change */
3277 		ifa_free(ifa);
3278 		return (EINVAL);
3279 	}
3280 	switch (ifp->if_type) {
3281 	case IFT_ETHER:
3282 	case IFT_FDDI:
3283 	case IFT_XETHER:
3284 	case IFT_ISO88025:
3285 	case IFT_L2VLAN:
3286 	case IFT_BRIDGE:
3287 	case IFT_ARCNET:
3288 	case IFT_IEEE8023ADLAG:
3289 	case IFT_IEEE80211:
3290 		bcopy(lladdr, LLADDR(sdl), len);
3291 		ifa_free(ifa);
3292 		break;
3293 	default:
3294 		ifa_free(ifa);
3295 		return (ENODEV);
3296 	}
3297 
3298 	/*
3299 	 * If the interface is already up, we need
3300 	 * to re-init it in order to reprogram its
3301 	 * address filter.
3302 	 */
3303 	if ((ifp->if_flags & IFF_UP) != 0) {
3304 		if (ifp->if_ioctl) {
3305 			ifp->if_flags &= ~IFF_UP;
3306 			ifr.ifr_flags = ifp->if_flags & 0xffff;
3307 			ifr.ifr_flagshigh = ifp->if_flags >> 16;
3308 			(*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
3309 			ifp->if_flags |= IFF_UP;
3310 			ifr.ifr_flags = ifp->if_flags & 0xffff;
3311 			ifr.ifr_flagshigh = ifp->if_flags >> 16;
3312 			(*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
3313 		}
3314 #ifdef INET
3315 		/*
3316 		 * Also send gratuitous ARPs to notify other nodes about
3317 		 * the address change.
3318 		 */
3319 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
3320 			if (ifa->ifa_addr->sa_family == AF_INET)
3321 				arp_ifinit(ifp, ifa);
3322 		}
3323 #endif
3324 	}
3325 	return (0);
3326 }
3327 
3328 /*
3329  * The name argument must be a pointer to storage which will last as
3330  * long as the interface does.  For physical devices, the result of
3331  * device_get_name(dev) is a good choice and for pseudo-devices a
3332  * static string works well.
3333  */
3334 void
3335 if_initname(struct ifnet *ifp, const char *name, int unit)
3336 {
3337 	ifp->if_dname = name;
3338 	ifp->if_dunit = unit;
3339 	if (unit != IF_DUNIT_NONE)
3340 		snprintf(ifp->if_xname, IFNAMSIZ, "%s%d", name, unit);
3341 	else
3342 		strlcpy(ifp->if_xname, name, IFNAMSIZ);
3343 }
3344 
3345 int
3346 if_printf(struct ifnet *ifp, const char * fmt, ...)
3347 {
3348 	va_list ap;
3349 	int retval;
3350 
3351 	retval = printf("%s: ", ifp->if_xname);
3352 	va_start(ap, fmt);
3353 	retval += vprintf(fmt, ap);
3354 	va_end(ap);
3355 	return (retval);
3356 }
3357 
3358 void
3359 if_start(struct ifnet *ifp)
3360 {
3361 
3362 	(*(ifp)->if_start)(ifp);
3363 }
3364 
3365 /*
3366  * Backwards compatibility interface for drivers
3367  * that have not implemented it
3368  */
3369 static int
3370 if_transmit(struct ifnet *ifp, struct mbuf *m)
3371 {
3372 	int error;
3373 
3374 	IFQ_HANDOFF(ifp, m, error);
3375 	return (error);
3376 }
3377 
3378 int
3379 if_handoff(struct ifqueue *ifq, struct mbuf *m, struct ifnet *ifp, int adjust)
3380 {
3381 	int active = 0;
3382 
3383 	IF_LOCK(ifq);
3384 	if (_IF_QFULL(ifq)) {
3385 		_IF_DROP(ifq);
3386 		IF_UNLOCK(ifq);
3387 		m_freem(m);
3388 		return (0);
3389 	}
3390 	if (ifp != NULL) {
3391 		ifp->if_obytes += m->m_pkthdr.len + adjust;
3392 		if (m->m_flags & (M_BCAST|M_MCAST))
3393 			ifp->if_omcasts++;
3394 		active = ifp->if_drv_flags & IFF_DRV_OACTIVE;
3395 	}
3396 	_IF_ENQUEUE(ifq, m);
3397 	IF_UNLOCK(ifq);
3398 	if (ifp != NULL && !active)
3399 		(*(ifp)->if_start)(ifp);
3400 	return (1);
3401 }
3402 
3403 void
3404 if_register_com_alloc(u_char type,
3405     if_com_alloc_t *a, if_com_free_t *f)
3406 {
3407 
3408 	KASSERT(if_com_alloc[type] == NULL,
3409 	    ("if_register_com_alloc: %d already registered", type));
3410 	KASSERT(if_com_free[type] == NULL,
3411 	    ("if_register_com_alloc: %d free already registered", type));
3412 
3413 	if_com_alloc[type] = a;
3414 	if_com_free[type] = f;
3415 }
3416 
3417 void
3418 if_deregister_com_alloc(u_char type)
3419 {
3420 
3421 	KASSERT(if_com_alloc[type] != NULL,
3422 	    ("if_deregister_com_alloc: %d not registered", type));
3423 	KASSERT(if_com_free[type] != NULL,
3424 	    ("if_deregister_com_alloc: %d free not registered", type));
3425 	if_com_alloc[type] = NULL;
3426 	if_com_free[type] = NULL;
3427 }
3428