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