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