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