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