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