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