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