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