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