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