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