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: stable/9/sys/net/if.c 280257 2015-03-19 13:33:15Z ae $
31  */
32 
33 #include "opt_compat.h"
34 #include "opt_inet6.h"
35 #include "opt_inet.h"
36 
37 #include <sys/param.h>
38 #include <sys/types.h>
39 #include <sys/conf.h>
40 #include <sys/malloc.h>
41 #include <sys/sbuf.h>
42 #include <sys/bus.h>
43 #include <sys/mbuf.h>
44 #include <sys/systm.h>
45 #include <sys/priv.h>
46 #include <sys/proc.h>
47 #include <sys/socket.h>
48 #include <sys/socketvar.h>
49 #include <sys/protosw.h>
50 #include <sys/kernel.h>
51 #include <sys/lock.h>
52 #include <sys/refcount.h>
53 #include <sys/module.h>
54 #include <sys/rwlock.h>
55 #include <sys/sockio.h>
56 #include <sys/syslog.h>
57 #include <sys/sysctl.h>
58 #include <sys/taskqueue.h>
59 #include <sys/domain.h>
60 #include <sys/jail.h>
61 #include <sys/priv.h>
62 
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 #include <net/ethernet.h>
78 #include <netinet/in.h>
79 #include <netinet/in_var.h>
80 #include <netinet/ip.h>
81 #include <netinet/ip_carp.h>
82 #ifdef INET
83 #include <netinet/if_ether.h>
84 #endif /* INET */
85 #ifdef INET6
86 #include <netinet6/in6_var.h>
87 #include <netinet6/in6_ifattach.h>
88 #endif /* INET6 */
89 #endif /* INET || INET6 */
90 
91 #include <security/mac/mac_framework.h>
92 
93 #ifdef COMPAT_FREEBSD32
94 #include <sys/mount.h>
95 #include <compat/freebsd32/freebsd32.h>
96 #endif
97 
98 struct ifindex_entry {
99 	struct  ifnet *ife_ifnet;
100 };
101 
102 SYSCTL_NODE(_net, PF_LINK, link, CTLFLAG_RW, 0, "Link layers");
103 SYSCTL_NODE(_net_link, 0, generic, CTLFLAG_RW, 0, "Generic link-management");
104 
105 TUNABLE_INT("net.link.ifqmaxlen", &ifqmaxlen);
106 SYSCTL_INT(_net_link, OID_AUTO, ifqmaxlen, CTLFLAG_RDTUN,
107     &ifqmaxlen, 0, "max send queue size");
108 
109 /* Log link state change events */
110 static int log_link_state_change = 1;
111 
112 SYSCTL_INT(_net_link, OID_AUTO, log_link_state_change, CTLFLAG_RW,
113 	&log_link_state_change, 0,
114 	"log interface link state change events");
115 
116 /* Interface description */
117 static unsigned int ifdescr_maxlen = 1024;
118 SYSCTL_UINT(_net, OID_AUTO, ifdescr_maxlen, CTLFLAG_RW,
119 	&ifdescr_maxlen, 0,
120 	"administrative maximum length for interface description");
121 
122 static MALLOC_DEFINE(M_IFDESCR, "ifdescr", "ifnet descriptions");
123 
124 /* global sx for non-critical path ifdescr */
125 static struct sx ifdescr_sx;
126 SX_SYSINIT(ifdescr_sx, &ifdescr_sx, "ifnet descr");
127 
128 void	(*bridge_linkstate_p)(struct ifnet *ifp);
129 void	(*ng_ether_link_state_p)(struct ifnet *ifp, int state);
130 void	(*lagg_linkstate_p)(struct ifnet *ifp, int state);
131 /* These are external hooks for CARP. */
132 void	(*carp_linkstate_p)(struct ifnet *ifp);
133 #if defined(INET) || defined(INET6)
134 struct ifnet *(*carp_forus_p)(struct ifnet *ifp, u_char *dhost);
135 int	(*carp_output_p)(struct ifnet *ifp, struct mbuf *m,
136     struct sockaddr *sa, struct rtentry *rt);
137 #endif
138 #ifdef INET
139 int (*carp_iamatch_p)(struct ifnet *, struct in_ifaddr *, struct in_addr *,
140     u_int8_t **);
141 #endif
142 #ifdef INET6
143 struct ifaddr *(*carp_iamatch6_p)(struct ifnet *ifp, struct in6_addr *taddr6);
144 caddr_t (*carp_macmatch6_p)(struct ifnet *ifp, struct mbuf *m,
145     const struct in6_addr *taddr);
146 #endif
147 
148 struct mbuf *(*tbr_dequeue_ptr)(struct ifaltq *, int) = NULL;
149 
150 /*
151  * XXX: Style; these should be sorted alphabetically, and unprototyped
152  * static functions should be prototyped. Currently they are sorted by
153  * declaration order.
154  */
155 static void	if_attachdomain(void *);
156 static void	if_attachdomain1(struct ifnet *);
157 static int	ifconf(u_long, caddr_t);
158 static void	if_freemulti(struct ifmultiaddr *);
159 static void	if_init(void *);
160 static void	if_grow(void);
161 static void	if_input_default(struct ifnet *, struct mbuf *);
162 static void	if_route(struct ifnet *, int flag, int fam);
163 static int	if_setflag(struct ifnet *, int, int, int *, int);
164 static int	if_transmit(struct ifnet *ifp, struct mbuf *m);
165 static void	if_unroute(struct ifnet *, int flag, int fam);
166 static void	link_rtrequest(int, struct rtentry *, struct rt_addrinfo *);
167 static int	if_rtdel(struct radix_node *, void *);
168 static int	ifhwioctl(u_long, struct ifnet *, caddr_t, struct thread *);
169 static int	if_delmulti_locked(struct ifnet *, struct ifmultiaddr *, int);
170 static void	do_link_state_change(void *, int);
171 static int	if_getgroup(struct ifgroupreq *, struct ifnet *);
172 static int	if_getgroupmembers(struct ifgroupreq *);
173 static void	if_delgroups(struct ifnet *);
174 static void	if_attach_internal(struct ifnet *, int);
175 static void	if_detach_internal(struct ifnet *, int);
176 
177 #ifdef INET6
178 /*
179  * XXX: declare here to avoid to include many inet6 related files..
180  * should be more generalized?
181  */
182 extern void	nd6_setmtu(struct ifnet *);
183 #endif
184 
185 VNET_DEFINE(int, if_index);
186 int	ifqmaxlen = IFQ_MAXLEN;
187 VNET_DEFINE(struct ifnethead, ifnet);	/* depend on static init XXX */
188 VNET_DEFINE(struct ifgrouphead, ifg_head);
189 
190 static VNET_DEFINE(int, if_indexlim) = 8;
191 
192 /* Table of ifnet by index. */
193 VNET_DEFINE(struct ifindex_entry *, ifindex_table);
194 
195 #define	V_if_indexlim		VNET(if_indexlim)
196 #define	V_ifindex_table		VNET(ifindex_table)
197 
198 /*
199  * The global network interface list (V_ifnet) and related state (such as
200  * if_index, if_indexlim, and ifindex_table) are protected by an sxlock and
201  * an rwlock.  Either may be acquired shared to stablize the list, but both
202  * must be acquired writable to modify the list.  This model allows us to
203  * both stablize the interface list during interrupt thread processing, but
204  * also to stablize it over long-running ioctls, without introducing priority
205  * inversions and deadlocks.
206  */
207 struct rwlock ifnet_rwlock;
208 struct sx ifnet_sxlock;
209 
210 /*
211  * The allocation of network interfaces is a rather non-atomic affair; we
212  * need to select an index before we are ready to expose the interface for
213  * use, so will use this pointer value to indicate reservation.
214  */
215 #define	IFNET_HOLD	(void *)(uintptr_t)(-1)
216 
217 static	if_com_alloc_t *if_com_alloc[256];
218 static	if_com_free_t *if_com_free[256];
219 
220 static MALLOC_DEFINE(M_IFNET, "ifnet", "interface internals");
221 MALLOC_DEFINE(M_IFADDR, "ifaddr", "interface address");
222 MALLOC_DEFINE(M_IFMADDR, "ether_multi", "link-level multicast address");
223 
224 struct ifnet *
ifnet_byindex_locked(u_short idx)225 ifnet_byindex_locked(u_short idx)
226 {
227 
228 	if (idx > V_if_index)
229 		return (NULL);
230 	if (V_ifindex_table[idx].ife_ifnet == IFNET_HOLD)
231 		return (NULL);
232 	return (V_ifindex_table[idx].ife_ifnet);
233 }
234 
235 struct ifnet *
ifnet_byindex(u_short idx)236 ifnet_byindex(u_short idx)
237 {
238 	struct ifnet *ifp;
239 
240 	IFNET_RLOCK_NOSLEEP();
241 	ifp = ifnet_byindex_locked(idx);
242 	IFNET_RUNLOCK_NOSLEEP();
243 	return (ifp);
244 }
245 
246 struct ifnet *
ifnet_byindex_ref(u_short idx)247 ifnet_byindex_ref(u_short idx)
248 {
249 	struct ifnet *ifp;
250 
251 	IFNET_RLOCK_NOSLEEP();
252 	ifp = ifnet_byindex_locked(idx);
253 	if (ifp == NULL || (ifp->if_flags & IFF_DYING)) {
254 		IFNET_RUNLOCK_NOSLEEP();
255 		return (NULL);
256 	}
257 	if_ref(ifp);
258 	IFNET_RUNLOCK_NOSLEEP();
259 	return (ifp);
260 }
261 
262 /*
263  * Allocate an ifindex array entry; return 0 on success or an error on
264  * failure.
265  */
266 static int
ifindex_alloc_locked(u_short * idxp)267 ifindex_alloc_locked(u_short *idxp)
268 {
269 	u_short idx;
270 
271 	IFNET_WLOCK_ASSERT();
272 
273 retry:
274 	/*
275 	 * Try to find an empty slot below V_if_index.  If we fail, take the
276 	 * next slot.
277 	 */
278 	for (idx = 1; idx <= V_if_index; idx++) {
279 		if (V_ifindex_table[idx].ife_ifnet == NULL)
280 			break;
281 	}
282 
283 	/* Catch if_index overflow. */
284 	if (idx < 1)
285 		return (ENOSPC);
286 	if (idx >= V_if_indexlim) {
287 		if_grow();
288 		goto retry;
289 	}
290 	if (idx > V_if_index)
291 		V_if_index = idx;
292 	*idxp = idx;
293 	return (0);
294 }
295 
296 static void
ifindex_free_locked(u_short idx)297 ifindex_free_locked(u_short idx)
298 {
299 
300 	IFNET_WLOCK_ASSERT();
301 
302 	V_ifindex_table[idx].ife_ifnet = NULL;
303 	while (V_if_index > 0 &&
304 	    V_ifindex_table[V_if_index].ife_ifnet == NULL)
305 		V_if_index--;
306 }
307 
308 static void
ifindex_free(u_short idx)309 ifindex_free(u_short idx)
310 {
311 
312 	IFNET_WLOCK();
313 	ifindex_free_locked(idx);
314 	IFNET_WUNLOCK();
315 }
316 
317 static void
ifnet_setbyindex_locked(u_short idx,struct ifnet * ifp)318 ifnet_setbyindex_locked(u_short idx, struct ifnet *ifp)
319 {
320 
321 	IFNET_WLOCK_ASSERT();
322 
323 	V_ifindex_table[idx].ife_ifnet = ifp;
324 }
325 
326 static void
ifnet_setbyindex(u_short idx,struct ifnet * ifp)327 ifnet_setbyindex(u_short idx, struct ifnet *ifp)
328 {
329 
330 	IFNET_WLOCK();
331 	ifnet_setbyindex_locked(idx, ifp);
332 	IFNET_WUNLOCK();
333 }
334 
335 struct ifaddr *
ifaddr_byindex(u_short idx)336 ifaddr_byindex(u_short idx)
337 {
338 	struct ifaddr *ifa;
339 
340 	IFNET_RLOCK_NOSLEEP();
341 	ifa = ifnet_byindex_locked(idx)->if_addr;
342 	if (ifa != NULL)
343 		ifa_ref(ifa);
344 	IFNET_RUNLOCK_NOSLEEP();
345 	return (ifa);
346 }
347 
348 /*
349  * Network interface utility routines.
350  *
351  * Routines with ifa_ifwith* names take sockaddr *'s as
352  * parameters.
353  */
354 
355 static void
vnet_if_init(const void * unused __unused)356 vnet_if_init(const void *unused __unused)
357 {
358 
359 	TAILQ_INIT(&V_ifnet);
360 	TAILQ_INIT(&V_ifg_head);
361 	IFNET_WLOCK();
362 	if_grow();				/* create initial table */
363 	IFNET_WUNLOCK();
364 	vnet_if_clone_init();
365 }
366 VNET_SYSINIT(vnet_if_init, SI_SUB_INIT_IF, SI_ORDER_SECOND, vnet_if_init,
367     NULL);
368 
369 /* ARGSUSED*/
370 static void
if_init(void * dummy __unused)371 if_init(void *dummy __unused)
372 {
373 
374 	IFNET_LOCK_INIT();
375 	if_clone_init();
376 }
377 SYSINIT(interfaces, SI_SUB_INIT_IF, SI_ORDER_FIRST, if_init, NULL);
378 
379 
380 #ifdef VIMAGE
381 static void
vnet_if_uninit(const void * unused __unused)382 vnet_if_uninit(const void *unused __unused)
383 {
384 
385 	VNET_ASSERT(TAILQ_EMPTY(&V_ifnet), ("%s:%d tailq &V_ifnet=%p "
386 	    "not empty", __func__, __LINE__, &V_ifnet));
387 	VNET_ASSERT(TAILQ_EMPTY(&V_ifg_head), ("%s:%d tailq &V_ifg_head=%p "
388 	    "not empty", __func__, __LINE__, &V_ifg_head));
389 
390 	free((caddr_t)V_ifindex_table, M_IFNET);
391 }
392 VNET_SYSUNINIT(vnet_if_uninit, SI_SUB_INIT_IF, SI_ORDER_FIRST,
393     vnet_if_uninit, NULL);
394 #endif
395 
396 static void
if_grow(void)397 if_grow(void)
398 {
399 	int oldlim;
400 	u_int n;
401 	struct ifindex_entry *e;
402 
403 	IFNET_WLOCK_ASSERT();
404 	oldlim = V_if_indexlim;
405 	IFNET_WUNLOCK();
406 	n = (oldlim << 1) * sizeof(*e);
407 	e = malloc(n, M_IFNET, M_WAITOK | M_ZERO);
408 	IFNET_WLOCK();
409 	if (V_if_indexlim != oldlim) {
410 		free(e, M_IFNET);
411 		return;
412 	}
413 	if (V_ifindex_table != NULL) {
414 		memcpy((caddr_t)e, (caddr_t)V_ifindex_table, n/2);
415 		free((caddr_t)V_ifindex_table, M_IFNET);
416 	}
417 	V_if_indexlim <<= 1;
418 	V_ifindex_table = e;
419 }
420 
421 /*
422  * Allocate a struct ifnet and an index for an interface.  A layer 2
423  * common structure will also be allocated if an allocation routine is
424  * registered for the passed type.
425  */
426 struct ifnet *
if_alloc(u_char type)427 if_alloc(u_char type)
428 {
429 	struct ifnet *ifp;
430 	u_short idx;
431 
432 	ifp = malloc(sizeof(struct ifnet), M_IFNET, M_WAITOK|M_ZERO);
433 	IFNET_WLOCK();
434 	if (ifindex_alloc_locked(&idx) != 0) {
435 		IFNET_WUNLOCK();
436 		free(ifp, M_IFNET);
437 		return (NULL);
438 	}
439 	ifnet_setbyindex_locked(idx, IFNET_HOLD);
440 	IFNET_WUNLOCK();
441 	ifp->if_index = idx;
442 	ifp->if_type = type;
443 	ifp->if_alloctype = type;
444 	if (if_com_alloc[type] != NULL) {
445 		ifp->if_l2com = if_com_alloc[type](type, ifp);
446 		if (ifp->if_l2com == NULL) {
447 			free(ifp, M_IFNET);
448 			ifindex_free(idx);
449 			return (NULL);
450 		}
451 	}
452 
453 	IF_ADDR_LOCK_INIT(ifp);
454 	TASK_INIT(&ifp->if_linktask, 0, do_link_state_change, ifp);
455 	ifp->if_afdata_initialized = 0;
456 	IF_AFDATA_LOCK_INIT(ifp);
457 	TAILQ_INIT(&ifp->if_addrhead);
458 	TAILQ_INIT(&ifp->if_prefixhead);
459 	TAILQ_INIT(&ifp->if_multiaddrs);
460 	TAILQ_INIT(&ifp->if_groups);
461 #ifdef MAC
462 	mac_ifnet_init(ifp);
463 #endif
464 	ifq_init(&ifp->if_snd, ifp);
465 
466 	refcount_init(&ifp->if_refcount, 1);	/* Index reference. */
467 	ifnet_setbyindex(ifp->if_index, ifp);
468 	return (ifp);
469 }
470 
471 /*
472  * Do the actual work of freeing a struct ifnet, and layer 2 common
473  * structure.  This call is made when the last reference to an
474  * interface is released.
475  */
476 static void
if_free_internal(struct ifnet * ifp)477 if_free_internal(struct ifnet *ifp)
478 {
479 
480 	KASSERT((ifp->if_flags & IFF_DYING),
481 	    ("if_free_internal: interface not dying"));
482 
483 	if (if_com_free[ifp->if_alloctype] != NULL)
484 		if_com_free[ifp->if_alloctype](ifp->if_l2com,
485 		    ifp->if_alloctype);
486 
487 #ifdef MAC
488 	mac_ifnet_destroy(ifp);
489 #endif /* MAC */
490 	if (ifp->if_description != NULL)
491 		free(ifp->if_description, M_IFDESCR);
492 	IF_AFDATA_DESTROY(ifp);
493 	IF_ADDR_LOCK_DESTROY(ifp);
494 	ifq_delete(&ifp->if_snd);
495 	free(ifp, M_IFNET);
496 }
497 
498 /*
499  * This version should only be called by intefaces that switch their type
500  * after calling if_alloc().  if_free_type() will go away again now that we
501  * have if_alloctype to cache the original allocation type.  For now, assert
502  * that they match, since we require that in practice.
503  */
504 void
if_free_type(struct ifnet * ifp,u_char type)505 if_free_type(struct ifnet *ifp, u_char type)
506 {
507 
508 	KASSERT(ifp->if_alloctype == type,
509 	    ("if_free_type: type (%d) != alloctype (%d)", type,
510 	    ifp->if_alloctype));
511 
512 	ifp->if_flags |= IFF_DYING;			/* XXX: Locking */
513 
514 	CURVNET_SET_QUIET(ifp->if_vnet);
515 	IFNET_WLOCK();
516 	KASSERT(ifp == ifnet_byindex_locked(ifp->if_index),
517 	    ("%s: freeing unallocated ifnet", ifp->if_xname));
518 
519 	ifindex_free_locked(ifp->if_index);
520 	IFNET_WUNLOCK();
521 
522 	if (refcount_release(&ifp->if_refcount))
523 		if_free_internal(ifp);
524 	CURVNET_RESTORE();
525 }
526 
527 /*
528  * This is the normal version of if_free(), used by device drivers to free a
529  * detached network interface.  The contents of if_free_type() will move into
530  * here when if_free_type() goes away.
531  */
532 void
if_free(struct ifnet * ifp)533 if_free(struct ifnet *ifp)
534 {
535 
536 	if_free_type(ifp, ifp->if_alloctype);
537 }
538 
539 /*
540  * Interfaces to keep an ifnet type-stable despite the possibility of the
541  * driver calling if_free().  If there are additional references, we defer
542  * freeing the underlying data structure.
543  */
544 void
if_ref(struct ifnet * ifp)545 if_ref(struct ifnet *ifp)
546 {
547 
548 	/* We don't assert the ifnet list lock here, but arguably should. */
549 	refcount_acquire(&ifp->if_refcount);
550 }
551 
552 void
if_rele(struct ifnet * ifp)553 if_rele(struct ifnet *ifp)
554 {
555 
556 	if (!refcount_release(&ifp->if_refcount))
557 		return;
558 	if_free_internal(ifp);
559 }
560 
561 void
ifq_init(struct ifaltq * ifq,struct ifnet * ifp)562 ifq_init(struct ifaltq *ifq, struct ifnet *ifp)
563 {
564 
565 	mtx_init(&ifq->ifq_mtx, ifp->if_xname, "if send queue", MTX_DEF);
566 
567 	if (ifq->ifq_maxlen == 0)
568 		ifq->ifq_maxlen = ifqmaxlen;
569 
570 	ifq->altq_type = 0;
571 	ifq->altq_disc = NULL;
572 	ifq->altq_flags &= ALTQF_CANTCHANGE;
573 	ifq->altq_tbr  = NULL;
574 	ifq->altq_ifp  = ifp;
575 }
576 
577 void
ifq_delete(struct ifaltq * ifq)578 ifq_delete(struct ifaltq *ifq)
579 {
580 	mtx_destroy(&ifq->ifq_mtx);
581 }
582 
583 /*
584  * Perform generic interface initalization tasks and attach the interface
585  * to the list of "active" interfaces.  If vmove flag is set on entry
586  * to if_attach_internal(), perform only a limited subset of initialization
587  * tasks, given that we are moving from one vnet to another an ifnet which
588  * has already been fully initialized.
589  *
590  * XXX:
591  *  - The decision to return void and thus require this function to
592  *    succeed is questionable.
593  *  - We should probably do more sanity checking.  For instance we don't
594  *    do anything to insure if_xname is unique or non-empty.
595  */
596 void
if_attach(struct ifnet * ifp)597 if_attach(struct ifnet *ifp)
598 {
599 
600 	if_attach_internal(ifp, 0);
601 }
602 
603 /*
604  * Compute the least common TSO limit.
605  */
606 void
if_hw_tsomax_common(struct ifnet * ifp,struct ifnet_hw_tsomax * pmax)607 if_hw_tsomax_common(struct ifnet *ifp, struct ifnet_hw_tsomax *pmax)
608 {
609 	/*
610 	 * 1) If there is no limit currently, take the limit from
611 	 * the network adapter.
612 	 *
613 	 * 2) If the network adapter has a limit below the current
614 	 * limit, apply it.
615 	 */
616 	if (pmax->tsomaxbytes == 0 || (ifp->if_hw_tsomax != 0 &&
617 	    ifp->if_hw_tsomax < pmax->tsomaxbytes)) {
618 		pmax->tsomaxbytes = ifp->if_hw_tsomax;
619 	}
620 	if (pmax->tsomaxsegcount == 0 || (ifp->if_hw_tsomaxsegcount != 0 &&
621 	    ifp->if_hw_tsomaxsegcount < pmax->tsomaxsegcount)) {
622 		pmax->tsomaxsegcount = ifp->if_hw_tsomaxsegcount;
623 	}
624 	if (pmax->tsomaxsegsize == 0 || (ifp->if_hw_tsomaxsegsize != 0 &&
625 	    ifp->if_hw_tsomaxsegsize < pmax->tsomaxsegsize)) {
626 		pmax->tsomaxsegsize = ifp->if_hw_tsomaxsegsize;
627 	}
628 }
629 
630 /*
631  * Update TSO limit of a network adapter.
632  *
633  * Returns zero if no change. Else non-zero.
634  */
635 int
if_hw_tsomax_update(struct ifnet * ifp,struct ifnet_hw_tsomax * pmax)636 if_hw_tsomax_update(struct ifnet *ifp, struct ifnet_hw_tsomax *pmax)
637 {
638 	int retval = 0;
639 	if (ifp->if_hw_tsomax != pmax->tsomaxbytes) {
640 		ifp->if_hw_tsomax = pmax->tsomaxbytes;
641 		retval++;
642 	}
643 	if (ifp->if_hw_tsomaxsegsize != pmax->tsomaxsegsize) {
644 		ifp->if_hw_tsomaxsegsize = pmax->tsomaxsegsize;
645 		retval++;
646 	}
647 	if (ifp->if_hw_tsomaxsegcount != pmax->tsomaxsegcount) {
648 		ifp->if_hw_tsomaxsegcount = pmax->tsomaxsegcount;
649 		retval++;
650 	}
651 	return (retval);
652 }
653 
654 static void
if_attach_internal(struct ifnet * ifp,int vmove)655 if_attach_internal(struct ifnet *ifp, int vmove)
656 {
657 	unsigned socksize, ifasize;
658 	int namelen, masklen;
659 	struct sockaddr_dl *sdl;
660 	struct ifaddr *ifa;
661 
662 	if (ifp->if_index == 0 || ifp != ifnet_byindex(ifp->if_index))
663 		panic ("%s: BUG: if_attach called without if_alloc'd input()\n",
664 		    ifp->if_xname);
665 
666 #ifdef VIMAGE
667 	ifp->if_vnet = curvnet;
668 	if (ifp->if_home_vnet == NULL)
669 		ifp->if_home_vnet = curvnet;
670 #endif
671 
672 	if_addgroup(ifp, IFG_ALL);
673 
674 	getmicrotime(&ifp->if_lastchange);
675 	ifp->if_data.ifi_epoch = time_uptime;
676 	ifp->if_data.ifi_datalen = sizeof(struct if_data);
677 
678 	KASSERT((ifp->if_transmit == NULL && ifp->if_qflush == NULL) ||
679 	    (ifp->if_transmit != NULL && ifp->if_qflush != NULL),
680 	    ("transmit and qflush must both either be set or both be NULL"));
681 	if (ifp->if_transmit == NULL) {
682 		ifp->if_transmit = if_transmit;
683 		ifp->if_qflush = if_qflush;
684 	}
685 	if (ifp->if_input == NULL)
686 		ifp->if_input = if_input_default;
687 
688 	if (!vmove) {
689 #ifdef MAC
690 		mac_ifnet_create(ifp);
691 #endif
692 
693 		/*
694 		 * Create a Link Level name for this device.
695 		 */
696 		namelen = strlen(ifp->if_xname);
697 		/*
698 		 * Always save enough space for any possiable name so we
699 		 * can do a rename in place later.
700 		 */
701 		masklen = offsetof(struct sockaddr_dl, sdl_data[0]) + IFNAMSIZ;
702 		socksize = masklen + ifp->if_addrlen;
703 		if (socksize < sizeof(*sdl))
704 			socksize = sizeof(*sdl);
705 		socksize = roundup2(socksize, sizeof(long));
706 		ifasize = sizeof(*ifa) + 2 * socksize;
707 		ifa = malloc(ifasize, M_IFADDR, M_WAITOK | M_ZERO);
708 		ifa_init(ifa);
709 		sdl = (struct sockaddr_dl *)(ifa + 1);
710 		sdl->sdl_len = socksize;
711 		sdl->sdl_family = AF_LINK;
712 		bcopy(ifp->if_xname, sdl->sdl_data, namelen);
713 		sdl->sdl_nlen = namelen;
714 		sdl->sdl_index = ifp->if_index;
715 		sdl->sdl_type = ifp->if_type;
716 		ifp->if_addr = ifa;
717 		ifa->ifa_ifp = ifp;
718 		ifa->ifa_rtrequest = link_rtrequest;
719 		ifa->ifa_addr = (struct sockaddr *)sdl;
720 		sdl = (struct sockaddr_dl *)(socksize + (caddr_t)sdl);
721 		ifa->ifa_netmask = (struct sockaddr *)sdl;
722 		sdl->sdl_len = masklen;
723 		while (namelen != 0)
724 			sdl->sdl_data[--namelen] = 0xff;
725 		TAILQ_INSERT_HEAD(&ifp->if_addrhead, ifa, ifa_link);
726 		/* Reliably crash if used uninitialized. */
727 		ifp->if_broadcastaddr = NULL;
728 
729 #if defined(INET) || defined(INET6)
730 		/* Use defaults for TSO, if nothing is set */
731 		if (ifp->if_hw_tsomax == 0 &&
732 		    ifp->if_hw_tsomaxsegcount == 0 &&
733 		    ifp->if_hw_tsomaxsegsize == 0) {
734 			/*
735 			 * The TSO defaults needs to be such that an
736 			 * NFS mbuf list of 35 mbufs totalling just
737 			 * below 64K works and that a chain of mbufs
738 			 * can be defragged into at most 32 segments:
739 			 */
740 			ifp->if_hw_tsomax = min(IP_MAXPACKET, (32 * MCLBYTES) -
741 			    (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN));
742 			ifp->if_hw_tsomaxsegcount = 35;
743 			ifp->if_hw_tsomaxsegsize = 2048;	/* 2K */
744 
745 			/* XXX some drivers set IFCAP_TSO after ethernet attach */
746 			if (ifp->if_capabilities & IFCAP_TSO) {
747 				if_printf(ifp, "Using defaults for TSO: %u/%u/%u\n",
748 				    ifp->if_hw_tsomax,
749 				    ifp->if_hw_tsomaxsegcount,
750 				    ifp->if_hw_tsomaxsegsize);
751 			}
752 		}
753 #endif
754 	}
755 #ifdef VIMAGE
756 	else {
757 		/*
758 		 * Update the interface index in the link layer address
759 		 * of the interface.
760 		 */
761 		for (ifa = ifp->if_addr; ifa != NULL;
762 		    ifa = TAILQ_NEXT(ifa, ifa_link)) {
763 			if (ifa->ifa_addr->sa_family == AF_LINK) {
764 				sdl = (struct sockaddr_dl *)ifa->ifa_addr;
765 				sdl->sdl_index = ifp->if_index;
766 			}
767 		}
768 	}
769 #endif
770 
771 	IFNET_WLOCK();
772 	TAILQ_INSERT_TAIL(&V_ifnet, ifp, if_link);
773 #ifdef VIMAGE
774 	curvnet->vnet_ifcnt++;
775 #endif
776 	IFNET_WUNLOCK();
777 
778 	if (domain_init_status >= 2)
779 		if_attachdomain1(ifp);
780 
781 	EVENTHANDLER_INVOKE(ifnet_arrival_event, ifp);
782 	if (IS_DEFAULT_VNET(curvnet))
783 		devctl_notify("IFNET", ifp->if_xname, "ATTACH", NULL);
784 
785 	/* Announce the interface. */
786 	rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
787 }
788 
789 static void
if_attachdomain(void * dummy)790 if_attachdomain(void *dummy)
791 {
792 	struct ifnet *ifp;
793 	int s;
794 
795 	s = splnet();
796 	TAILQ_FOREACH(ifp, &V_ifnet, if_link)
797 		if_attachdomain1(ifp);
798 	splx(s);
799 }
800 SYSINIT(domainifattach, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_SECOND,
801     if_attachdomain, NULL);
802 
803 static void
if_attachdomain1(struct ifnet * ifp)804 if_attachdomain1(struct ifnet *ifp)
805 {
806 	struct domain *dp;
807 	int s;
808 
809 	s = splnet();
810 
811 	/*
812 	 * Since dp->dom_ifattach calls malloc() with M_WAITOK, we
813 	 * cannot lock ifp->if_afdata initialization, entirely.
814 	 */
815 	if (IF_AFDATA_TRYLOCK(ifp) == 0) {
816 		splx(s);
817 		return;
818 	}
819 	if (ifp->if_afdata_initialized >= domain_init_status) {
820 		IF_AFDATA_UNLOCK(ifp);
821 		splx(s);
822 		printf("if_attachdomain called more than once on %s\n",
823 		    ifp->if_xname);
824 		return;
825 	}
826 	ifp->if_afdata_initialized = domain_init_status;
827 	IF_AFDATA_UNLOCK(ifp);
828 
829 	/* address family dependent data region */
830 	bzero(ifp->if_afdata, sizeof(ifp->if_afdata));
831 	for (dp = domains; dp; dp = dp->dom_next) {
832 		if (dp->dom_ifattach)
833 			ifp->if_afdata[dp->dom_family] =
834 			    (*dp->dom_ifattach)(ifp);
835 	}
836 
837 	splx(s);
838 }
839 
840 /*
841  * Remove any unicast or broadcast network addresses from an interface.
842  */
843 void
if_purgeaddrs(struct ifnet * ifp)844 if_purgeaddrs(struct ifnet *ifp)
845 {
846 	struct ifaddr *ifa, *next;
847 
848 	TAILQ_FOREACH_SAFE(ifa, &ifp->if_addrhead, ifa_link, next) {
849 		if (ifa->ifa_addr->sa_family == AF_LINK)
850 			continue;
851 #ifdef INET
852 		/* XXX: Ugly!! ad hoc just for INET */
853 		if (ifa->ifa_addr->sa_family == AF_INET) {
854 			struct ifaliasreq ifr;
855 
856 			bzero(&ifr, sizeof(ifr));
857 			ifr.ifra_addr = *ifa->ifa_addr;
858 			if (ifa->ifa_dstaddr)
859 				ifr.ifra_broadaddr = *ifa->ifa_dstaddr;
860 			if (in_control(NULL, SIOCDIFADDR, (caddr_t)&ifr, ifp,
861 			    NULL) == 0)
862 				continue;
863 		}
864 #endif /* INET */
865 #ifdef INET6
866 		if (ifa->ifa_addr->sa_family == AF_INET6) {
867 			in6_purgeaddr(ifa);
868 			/* ifp_addrhead is already updated */
869 			continue;
870 		}
871 #endif /* INET6 */
872 		TAILQ_REMOVE(&ifp->if_addrhead, ifa, ifa_link);
873 		ifa_free(ifa);
874 	}
875 }
876 
877 /*
878  * Remove any multicast network addresses from an interface when an ifnet
879  * is going away.
880  */
881 static void
if_purgemaddrs(struct ifnet * ifp)882 if_purgemaddrs(struct ifnet *ifp)
883 {
884 	struct ifmultiaddr *ifma;
885 	struct ifmultiaddr *next;
886 
887 	IF_ADDR_WLOCK(ifp);
888 	TAILQ_FOREACH_SAFE(ifma, &ifp->if_multiaddrs, ifma_link, next)
889 		if_delmulti_locked(ifp, ifma, 1);
890 	IF_ADDR_WUNLOCK(ifp);
891 }
892 
893 /*
894  * Detach an interface, removing it from the list of "active" interfaces.
895  * If vmove flag is set on entry to if_detach_internal(), perform only a
896  * limited subset of cleanup tasks, given that we are moving an ifnet from
897  * one vnet to another, where it must be fully operational.
898  *
899  * XXXRW: There are some significant questions about event ordering, and
900  * how to prevent things from starting to use the interface during detach.
901  */
902 void
if_detach(struct ifnet * ifp)903 if_detach(struct ifnet *ifp)
904 {
905 
906 	CURVNET_SET_QUIET(ifp->if_vnet);
907 	if_detach_internal(ifp, 0);
908 	CURVNET_RESTORE();
909 }
910 
911 static void
if_detach_internal(struct ifnet * ifp,int vmove)912 if_detach_internal(struct ifnet *ifp, int vmove)
913 {
914 	struct ifaddr *ifa;
915 	struct radix_node_head	*rnh;
916 	int i, j;
917 	struct domain *dp;
918  	struct ifnet *iter;
919  	int found = 0;
920 
921 	IFNET_WLOCK();
922 	TAILQ_FOREACH(iter, &V_ifnet, if_link)
923 		if (iter == ifp) {
924 			TAILQ_REMOVE(&V_ifnet, ifp, if_link);
925 			found = 1;
926 			break;
927 		}
928 #ifdef VIMAGE
929 	if (found)
930 		curvnet->vnet_ifcnt--;
931 #endif
932 	IFNET_WUNLOCK();
933 	if (!found) {
934 		if (vmove)
935 			panic("%s: ifp=%p not on the ifnet tailq %p",
936 			    __func__, ifp, &V_ifnet);
937 		else
938 			return; /* XXX this should panic as well? */
939 	}
940 
941 	/*
942 	 * Remove/wait for pending events.
943 	 */
944 	taskqueue_drain(taskqueue_swi, &ifp->if_linktask);
945 
946 	/*
947 	 * Remove routes and flush queues.
948 	 */
949 	if_down(ifp);
950 #ifdef ALTQ
951 	if (ALTQ_IS_ENABLED(&ifp->if_snd))
952 		altq_disable(&ifp->if_snd);
953 	if (ALTQ_IS_ATTACHED(&ifp->if_snd))
954 		altq_detach(&ifp->if_snd);
955 #endif
956 
957 	if_purgeaddrs(ifp);
958 
959 #ifdef INET
960 	in_ifdetach(ifp);
961 #endif
962 
963 #ifdef INET6
964 	/*
965 	 * Remove all IPv6 kernel structs related to ifp.  This should be done
966 	 * before removing routing entries below, since IPv6 interface direct
967 	 * routes are expected to be removed by the IPv6-specific kernel API.
968 	 * Otherwise, the kernel will detect some inconsistency and bark it.
969 	 */
970 	in6_ifdetach(ifp);
971 #endif
972 	if_purgemaddrs(ifp);
973 
974 	if (!vmove) {
975 		/*
976 		 * Prevent further calls into the device driver via ifnet.
977 		 */
978 		if_dead(ifp);
979 
980 		/*
981 		 * Remove link ifaddr pointer and maybe decrement if_index.
982 		 * Clean up all addresses.
983 		 */
984 		ifp->if_addr = NULL;
985 
986 		/* We can now free link ifaddr. */
987 		if (!TAILQ_EMPTY(&ifp->if_addrhead)) {
988 			ifa = TAILQ_FIRST(&ifp->if_addrhead);
989 			TAILQ_REMOVE(&ifp->if_addrhead, ifa, ifa_link);
990 			ifa_free(ifa);
991 		}
992 	}
993 
994 	/*
995 	 * Delete all remaining routes using this interface
996 	 * Unfortuneatly the only way to do this is to slog through
997 	 * the entire routing table looking for routes which point
998 	 * to this interface...oh well...
999 	 */
1000 	for (i = 1; i <= AF_MAX; i++) {
1001 		for (j = 0; j < rt_numfibs; j++) {
1002 			rnh = rt_tables_get_rnh(j, i);
1003 			if (rnh == NULL)
1004 				continue;
1005 			RADIX_NODE_HEAD_LOCK(rnh);
1006 			(void) rnh->rnh_walktree(rnh, if_rtdel, ifp);
1007 			RADIX_NODE_HEAD_UNLOCK(rnh);
1008 		}
1009 	}
1010 
1011 	/* Announce that the interface is gone. */
1012 	rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
1013 	EVENTHANDLER_INVOKE(ifnet_departure_event, ifp);
1014 	if (IS_DEFAULT_VNET(curvnet))
1015 		devctl_notify("IFNET", ifp->if_xname, "DETACH", NULL);
1016 	if_delgroups(ifp);
1017 
1018 	/*
1019 	 * We cannot hold the lock over dom_ifdetach calls as they might
1020 	 * sleep, for example trying to drain a callout, thus open up the
1021 	 * theoretical race with re-attaching.
1022 	 */
1023 	IF_AFDATA_LOCK(ifp);
1024 	i = ifp->if_afdata_initialized;
1025 	ifp->if_afdata_initialized = 0;
1026 	IF_AFDATA_UNLOCK(ifp);
1027 	for (dp = domains; i > 0 && dp; dp = dp->dom_next) {
1028 		if (dp->dom_ifdetach && ifp->if_afdata[dp->dom_family])
1029 			(*dp->dom_ifdetach)(ifp,
1030 			    ifp->if_afdata[dp->dom_family]);
1031 	}
1032 }
1033 
1034 #ifdef VIMAGE
1035 /*
1036  * if_vmove() performs a limited version of if_detach() in current
1037  * vnet and if_attach()es the ifnet to the vnet specified as 2nd arg.
1038  * An attempt is made to shrink if_index in current vnet, find an
1039  * unused if_index in target vnet and calls if_grow() if necessary,
1040  * and finally find an unused if_xname for the target vnet.
1041  */
1042 void
if_vmove(struct ifnet * ifp,struct vnet * new_vnet)1043 if_vmove(struct ifnet *ifp, struct vnet *new_vnet)
1044 {
1045 	u_short idx;
1046 
1047 	/*
1048 	 * Detach from current vnet, but preserve LLADDR info, do not
1049 	 * mark as dead etc. so that the ifnet can be reattached later.
1050 	 */
1051 	if_detach_internal(ifp, 1);
1052 
1053 	/*
1054 	 * Unlink the ifnet from ifindex_table[] in current vnet, and shrink
1055 	 * the if_index for that vnet if possible.
1056 	 *
1057 	 * NOTE: IFNET_WLOCK/IFNET_WUNLOCK() are assumed to be unvirtualized,
1058 	 * or we'd lock on one vnet and unlock on another.
1059 	 */
1060 	IFNET_WLOCK();
1061 	ifindex_free_locked(ifp->if_index);
1062 	IFNET_WUNLOCK();
1063 
1064 	/*
1065 	 * Perform interface-specific reassignment tasks, if provided by
1066 	 * the driver.
1067 	 */
1068 	if (ifp->if_reassign != NULL)
1069 		ifp->if_reassign(ifp, new_vnet, NULL);
1070 
1071 	/*
1072 	 * Switch to the context of the target vnet.
1073 	 */
1074 	CURVNET_SET_QUIET(new_vnet);
1075 
1076 	IFNET_WLOCK();
1077 	if (ifindex_alloc_locked(&idx) != 0) {
1078 		IFNET_WUNLOCK();
1079 		panic("if_index overflow");
1080 	}
1081 	ifp->if_index = idx;
1082 	ifnet_setbyindex_locked(ifp->if_index, ifp);
1083 	IFNET_WUNLOCK();
1084 
1085 	if_attach_internal(ifp, 1);
1086 
1087 	CURVNET_RESTORE();
1088 }
1089 
1090 /*
1091  * Move an ifnet to or from another child prison/vnet, specified by the jail id.
1092  */
1093 static int
if_vmove_loan(struct thread * td,struct ifnet * ifp,char * ifname,int jid)1094 if_vmove_loan(struct thread *td, struct ifnet *ifp, char *ifname, int jid)
1095 {
1096 	struct prison *pr;
1097 	struct ifnet *difp;
1098 
1099 	/* Try to find the prison within our visibility. */
1100 	sx_slock(&allprison_lock);
1101 	pr = prison_find_child(td->td_ucred->cr_prison, jid);
1102 	sx_sunlock(&allprison_lock);
1103 	if (pr == NULL)
1104 		return (ENXIO);
1105 	prison_hold_locked(pr);
1106 	mtx_unlock(&pr->pr_mtx);
1107 
1108 	/* Do not try to move the iface from and to the same prison. */
1109 	if (pr->pr_vnet == ifp->if_vnet) {
1110 		prison_free(pr);
1111 		return (EEXIST);
1112 	}
1113 
1114 	/* Make sure the named iface does not exists in the dst. prison/vnet. */
1115 	/* XXX Lock interfaces to avoid races. */
1116 	CURVNET_SET_QUIET(pr->pr_vnet);
1117 	difp = ifunit(ifname);
1118 	CURVNET_RESTORE();
1119 	if (difp != NULL) {
1120 		prison_free(pr);
1121 		return (EEXIST);
1122 	}
1123 
1124 	/* Move the interface into the child jail/vnet. */
1125 	if_vmove(ifp, pr->pr_vnet);
1126 
1127 	/* Report the new if_xname back to the userland. */
1128 	sprintf(ifname, "%s", ifp->if_xname);
1129 
1130 	prison_free(pr);
1131 	return (0);
1132 }
1133 
1134 static int
if_vmove_reclaim(struct thread * td,char * ifname,int jid)1135 if_vmove_reclaim(struct thread *td, char *ifname, int jid)
1136 {
1137 	struct prison *pr;
1138 	struct vnet *vnet_dst;
1139 	struct ifnet *ifp;
1140 
1141 	/* Try to find the prison within our visibility. */
1142 	sx_slock(&allprison_lock);
1143 	pr = prison_find_child(td->td_ucred->cr_prison, jid);
1144 	sx_sunlock(&allprison_lock);
1145 	if (pr == NULL)
1146 		return (ENXIO);
1147 	prison_hold_locked(pr);
1148 	mtx_unlock(&pr->pr_mtx);
1149 
1150 	/* Make sure the named iface exists in the source prison/vnet. */
1151 	CURVNET_SET(pr->pr_vnet);
1152 	ifp = ifunit(ifname);		/* XXX Lock to avoid races. */
1153 	if (ifp == NULL) {
1154 		CURVNET_RESTORE();
1155 		prison_free(pr);
1156 		return (ENXIO);
1157 	}
1158 
1159 	/* Do not try to move the iface from and to the same prison. */
1160 	vnet_dst = TD_TO_VNET(td);
1161 	if (vnet_dst == ifp->if_vnet) {
1162 		CURVNET_RESTORE();
1163 		prison_free(pr);
1164 		return (EEXIST);
1165 	}
1166 
1167 	/* Get interface back from child jail/vnet. */
1168 	if_vmove(ifp, vnet_dst);
1169 	CURVNET_RESTORE();
1170 
1171 	/* Report the new if_xname back to the userland. */
1172 	sprintf(ifname, "%s", ifp->if_xname);
1173 
1174 	prison_free(pr);
1175 	return (0);
1176 }
1177 #endif /* VIMAGE */
1178 
1179 /*
1180  * Add a group to an interface
1181  */
1182 int
if_addgroup(struct ifnet * ifp,const char * groupname)1183 if_addgroup(struct ifnet *ifp, const char *groupname)
1184 {
1185 	struct ifg_list		*ifgl;
1186 	struct ifg_group	*ifg = NULL;
1187 	struct ifg_member	*ifgm;
1188 
1189 	if (groupname[0] && groupname[strlen(groupname) - 1] >= '0' &&
1190 	    groupname[strlen(groupname) - 1] <= '9')
1191 		return (EINVAL);
1192 
1193 	IFNET_WLOCK();
1194 	TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
1195 		if (!strcmp(ifgl->ifgl_group->ifg_group, groupname)) {
1196 			IFNET_WUNLOCK();
1197 			return (EEXIST);
1198 		}
1199 
1200 	if ((ifgl = (struct ifg_list *)malloc(sizeof(struct ifg_list), M_TEMP,
1201 	    M_NOWAIT)) == NULL) {
1202 	    	IFNET_WUNLOCK();
1203 		return (ENOMEM);
1204 	}
1205 
1206 	if ((ifgm = (struct ifg_member *)malloc(sizeof(struct ifg_member),
1207 	    M_TEMP, M_NOWAIT)) == NULL) {
1208 		free(ifgl, M_TEMP);
1209 		IFNET_WUNLOCK();
1210 		return (ENOMEM);
1211 	}
1212 
1213 	TAILQ_FOREACH(ifg, &V_ifg_head, ifg_next)
1214 		if (!strcmp(ifg->ifg_group, groupname))
1215 			break;
1216 
1217 	if (ifg == NULL) {
1218 		if ((ifg = (struct ifg_group *)malloc(sizeof(struct ifg_group),
1219 		    M_TEMP, M_NOWAIT)) == NULL) {
1220 			free(ifgl, M_TEMP);
1221 			free(ifgm, M_TEMP);
1222 			IFNET_WUNLOCK();
1223 			return (ENOMEM);
1224 		}
1225 		strlcpy(ifg->ifg_group, groupname, sizeof(ifg->ifg_group));
1226 		ifg->ifg_refcnt = 0;
1227 		TAILQ_INIT(&ifg->ifg_members);
1228 		EVENTHANDLER_INVOKE(group_attach_event, ifg);
1229 		TAILQ_INSERT_TAIL(&V_ifg_head, ifg, ifg_next);
1230 	}
1231 
1232 	ifg->ifg_refcnt++;
1233 	ifgl->ifgl_group = ifg;
1234 	ifgm->ifgm_ifp = ifp;
1235 
1236 	IF_ADDR_WLOCK(ifp);
1237 	TAILQ_INSERT_TAIL(&ifg->ifg_members, ifgm, ifgm_next);
1238 	TAILQ_INSERT_TAIL(&ifp->if_groups, ifgl, ifgl_next);
1239 	IF_ADDR_WUNLOCK(ifp);
1240 
1241 	IFNET_WUNLOCK();
1242 
1243 	EVENTHANDLER_INVOKE(group_change_event, groupname);
1244 
1245 	return (0);
1246 }
1247 
1248 /*
1249  * Remove a group from an interface
1250  */
1251 int
if_delgroup(struct ifnet * ifp,const char * groupname)1252 if_delgroup(struct ifnet *ifp, const char *groupname)
1253 {
1254 	struct ifg_list		*ifgl;
1255 	struct ifg_member	*ifgm;
1256 
1257 	IFNET_WLOCK();
1258 	TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
1259 		if (!strcmp(ifgl->ifgl_group->ifg_group, groupname))
1260 			break;
1261 	if (ifgl == NULL) {
1262 		IFNET_WUNLOCK();
1263 		return (ENOENT);
1264 	}
1265 
1266 	IF_ADDR_WLOCK(ifp);
1267 	TAILQ_REMOVE(&ifp->if_groups, ifgl, ifgl_next);
1268 	IF_ADDR_WUNLOCK(ifp);
1269 
1270 	TAILQ_FOREACH(ifgm, &ifgl->ifgl_group->ifg_members, ifgm_next)
1271 		if (ifgm->ifgm_ifp == ifp)
1272 			break;
1273 
1274 	if (ifgm != NULL) {
1275 		TAILQ_REMOVE(&ifgl->ifgl_group->ifg_members, ifgm, ifgm_next);
1276 		free(ifgm, M_TEMP);
1277 	}
1278 
1279 	if (--ifgl->ifgl_group->ifg_refcnt == 0) {
1280 		TAILQ_REMOVE(&V_ifg_head, ifgl->ifgl_group, ifg_next);
1281 		EVENTHANDLER_INVOKE(group_detach_event, ifgl->ifgl_group);
1282 		free(ifgl->ifgl_group, M_TEMP);
1283 	}
1284 	IFNET_WUNLOCK();
1285 
1286 	free(ifgl, M_TEMP);
1287 
1288 	EVENTHANDLER_INVOKE(group_change_event, groupname);
1289 
1290 	return (0);
1291 }
1292 
1293 /*
1294  * Remove an interface from all groups
1295  */
1296 static void
if_delgroups(struct ifnet * ifp)1297 if_delgroups(struct ifnet *ifp)
1298 {
1299 	struct ifg_list		*ifgl;
1300 	struct ifg_member	*ifgm;
1301 	char groupname[IFNAMSIZ];
1302 
1303 	IFNET_WLOCK();
1304 	while (!TAILQ_EMPTY(&ifp->if_groups)) {
1305 		ifgl = TAILQ_FIRST(&ifp->if_groups);
1306 
1307 		strlcpy(groupname, ifgl->ifgl_group->ifg_group, IFNAMSIZ);
1308 
1309 		IF_ADDR_WLOCK(ifp);
1310 		TAILQ_REMOVE(&ifp->if_groups, ifgl, ifgl_next);
1311 		IF_ADDR_WUNLOCK(ifp);
1312 
1313 		TAILQ_FOREACH(ifgm, &ifgl->ifgl_group->ifg_members, ifgm_next)
1314 			if (ifgm->ifgm_ifp == ifp)
1315 				break;
1316 
1317 		if (ifgm != NULL) {
1318 			TAILQ_REMOVE(&ifgl->ifgl_group->ifg_members, ifgm,
1319 			    ifgm_next);
1320 			free(ifgm, M_TEMP);
1321 		}
1322 
1323 		if (--ifgl->ifgl_group->ifg_refcnt == 0) {
1324 			TAILQ_REMOVE(&V_ifg_head, ifgl->ifgl_group, ifg_next);
1325 			EVENTHANDLER_INVOKE(group_detach_event,
1326 			    ifgl->ifgl_group);
1327 			free(ifgl->ifgl_group, M_TEMP);
1328 		}
1329 		IFNET_WUNLOCK();
1330 
1331 		free(ifgl, M_TEMP);
1332 
1333 		EVENTHANDLER_INVOKE(group_change_event, groupname);
1334 
1335 		IFNET_WLOCK();
1336 	}
1337 	IFNET_WUNLOCK();
1338 }
1339 
1340 /*
1341  * Stores all groups from an interface in memory pointed
1342  * to by data
1343  */
1344 static int
if_getgroup(struct ifgroupreq * data,struct ifnet * ifp)1345 if_getgroup(struct ifgroupreq *data, struct ifnet *ifp)
1346 {
1347 	int			 len, error;
1348 	struct ifg_list		*ifgl;
1349 	struct ifg_req		 ifgrq, *ifgp;
1350 	struct ifgroupreq	*ifgr = data;
1351 
1352 	if (ifgr->ifgr_len == 0) {
1353 		IF_ADDR_RLOCK(ifp);
1354 		TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
1355 			ifgr->ifgr_len += sizeof(struct ifg_req);
1356 		IF_ADDR_RUNLOCK(ifp);
1357 		return (0);
1358 	}
1359 
1360 	len = ifgr->ifgr_len;
1361 	ifgp = ifgr->ifgr_groups;
1362 	/* XXX: wire */
1363 	IF_ADDR_RLOCK(ifp);
1364 	TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next) {
1365 		if (len < sizeof(ifgrq)) {
1366 			IF_ADDR_RUNLOCK(ifp);
1367 			return (EINVAL);
1368 		}
1369 		bzero(&ifgrq, sizeof ifgrq);
1370 		strlcpy(ifgrq.ifgrq_group, ifgl->ifgl_group->ifg_group,
1371 		    sizeof(ifgrq.ifgrq_group));
1372 		if ((error = copyout(&ifgrq, ifgp, sizeof(struct ifg_req)))) {
1373 		    	IF_ADDR_RUNLOCK(ifp);
1374 			return (error);
1375 		}
1376 		len -= sizeof(ifgrq);
1377 		ifgp++;
1378 	}
1379 	IF_ADDR_RUNLOCK(ifp);
1380 
1381 	return (0);
1382 }
1383 
1384 /*
1385  * Stores all members of a group in memory pointed to by data
1386  */
1387 static int
if_getgroupmembers(struct ifgroupreq * data)1388 if_getgroupmembers(struct ifgroupreq *data)
1389 {
1390 	struct ifgroupreq	*ifgr = data;
1391 	struct ifg_group	*ifg;
1392 	struct ifg_member	*ifgm;
1393 	struct ifg_req		 ifgrq, *ifgp;
1394 	int			 len, error;
1395 
1396 	IFNET_RLOCK();
1397 	TAILQ_FOREACH(ifg, &V_ifg_head, ifg_next)
1398 		if (!strcmp(ifg->ifg_group, ifgr->ifgr_name))
1399 			break;
1400 	if (ifg == NULL) {
1401 		IFNET_RUNLOCK();
1402 		return (ENOENT);
1403 	}
1404 
1405 	if (ifgr->ifgr_len == 0) {
1406 		TAILQ_FOREACH(ifgm, &ifg->ifg_members, ifgm_next)
1407 			ifgr->ifgr_len += sizeof(ifgrq);
1408 		IFNET_RUNLOCK();
1409 		return (0);
1410 	}
1411 
1412 	len = ifgr->ifgr_len;
1413 	ifgp = ifgr->ifgr_groups;
1414 	TAILQ_FOREACH(ifgm, &ifg->ifg_members, ifgm_next) {
1415 		if (len < sizeof(ifgrq)) {
1416 			IFNET_RUNLOCK();
1417 			return (EINVAL);
1418 		}
1419 		bzero(&ifgrq, sizeof ifgrq);
1420 		strlcpy(ifgrq.ifgrq_member, ifgm->ifgm_ifp->if_xname,
1421 		    sizeof(ifgrq.ifgrq_member));
1422 		if ((error = copyout(&ifgrq, ifgp, sizeof(struct ifg_req)))) {
1423 			IFNET_RUNLOCK();
1424 			return (error);
1425 		}
1426 		len -= sizeof(ifgrq);
1427 		ifgp++;
1428 	}
1429 	IFNET_RUNLOCK();
1430 
1431 	return (0);
1432 }
1433 
1434 /*
1435  * Delete Routes for a Network Interface
1436  *
1437  * Called for each routing entry via the rnh->rnh_walktree() call above
1438  * to delete all route entries referencing a detaching network interface.
1439  *
1440  * Arguments:
1441  *	rn	pointer to node in the routing table
1442  *	arg	argument passed to rnh->rnh_walktree() - detaching interface
1443  *
1444  * Returns:
1445  *	0	successful
1446  *	errno	failed - reason indicated
1447  *
1448  */
1449 static int
if_rtdel(struct radix_node * rn,void * arg)1450 if_rtdel(struct radix_node *rn, void *arg)
1451 {
1452 	struct rtentry	*rt = (struct rtentry *)rn;
1453 	struct ifnet	*ifp = arg;
1454 	int		err;
1455 
1456 	if (rt->rt_ifp == ifp) {
1457 
1458 		/*
1459 		 * Protect (sorta) against walktree recursion problems
1460 		 * with cloned routes
1461 		 */
1462 		if ((rt->rt_flags & RTF_UP) == 0)
1463 			return (0);
1464 
1465 		err = rtrequest_fib(RTM_DELETE, rt_key(rt), rt->rt_gateway,
1466 				rt_mask(rt),
1467 				rt->rt_flags|RTF_RNH_LOCKED|RTF_PINNED,
1468 				(struct rtentry **) NULL, rt->rt_fibnum);
1469 		if (err) {
1470 			log(LOG_WARNING, "if_rtdel: error %d\n", err);
1471 		}
1472 	}
1473 
1474 	return (0);
1475 }
1476 
1477 /*
1478  * Wrapper functions for struct ifnet address list locking macros.  These are
1479  * used by kernel modules to avoid encoding programming interface or binary
1480  * interface assumptions that may be violated when kernel-internal locking
1481  * approaches change.
1482  */
1483 void
if_addr_rlock(struct ifnet * ifp)1484 if_addr_rlock(struct ifnet *ifp)
1485 {
1486 
1487 	IF_ADDR_RLOCK(ifp);
1488 }
1489 
1490 void
if_addr_runlock(struct ifnet * ifp)1491 if_addr_runlock(struct ifnet *ifp)
1492 {
1493 
1494 	IF_ADDR_RUNLOCK(ifp);
1495 }
1496 
1497 void
if_maddr_rlock(struct ifnet * ifp)1498 if_maddr_rlock(struct ifnet *ifp)
1499 {
1500 
1501 	IF_ADDR_RLOCK(ifp);
1502 }
1503 
1504 void
if_maddr_runlock(struct ifnet * ifp)1505 if_maddr_runlock(struct ifnet *ifp)
1506 {
1507 
1508 	IF_ADDR_RUNLOCK(ifp);
1509 }
1510 
1511 /*
1512  * Reference count functions for ifaddrs.
1513  */
1514 void
ifa_init(struct ifaddr * ifa)1515 ifa_init(struct ifaddr *ifa)
1516 {
1517 
1518 	mtx_init(&ifa->ifa_mtx, "ifaddr", NULL, MTX_DEF);
1519 	refcount_init(&ifa->ifa_refcnt, 1);
1520 }
1521 
1522 void
ifa_ref(struct ifaddr * ifa)1523 ifa_ref(struct ifaddr *ifa)
1524 {
1525 
1526 	refcount_acquire(&ifa->ifa_refcnt);
1527 }
1528 
1529 void
ifa_free(struct ifaddr * ifa)1530 ifa_free(struct ifaddr *ifa)
1531 {
1532 
1533 	if (refcount_release(&ifa->ifa_refcnt)) {
1534 		mtx_destroy(&ifa->ifa_mtx);
1535 		free(ifa, M_IFADDR);
1536 	}
1537 }
1538 
1539 int
ifa_add_loopback_route(struct ifaddr * ifa,struct sockaddr * ia)1540 ifa_add_loopback_route(struct ifaddr *ifa, struct sockaddr *ia)
1541 {
1542 	int error = 0;
1543 	struct rtentry *rt = NULL;
1544 	struct rt_addrinfo info;
1545 	static struct sockaddr_dl null_sdl = {sizeof(null_sdl), AF_LINK};
1546 
1547 	bzero(&info, sizeof(info));
1548 	info.rti_ifp = V_loif;
1549 	info.rti_flags = ifa->ifa_flags | RTF_HOST | RTF_STATIC;
1550 	info.rti_info[RTAX_DST] = ia;
1551 	info.rti_info[RTAX_GATEWAY] = (struct sockaddr *)&null_sdl;
1552 	error = rtrequest1_fib(RTM_ADD, &info, &rt, ifa->ifa_ifp->if_fib);
1553 
1554 	if (error == 0 && rt != NULL) {
1555 		RT_LOCK(rt);
1556 		((struct sockaddr_dl *)rt->rt_gateway)->sdl_type  =
1557 			ifa->ifa_ifp->if_type;
1558 		((struct sockaddr_dl *)rt->rt_gateway)->sdl_index =
1559 			ifa->ifa_ifp->if_index;
1560 		RT_REMREF(rt);
1561 		RT_UNLOCK(rt);
1562 	} else if (error != 0)
1563 		log(LOG_INFO, "ifa_add_loopback_route: insertion failed\n");
1564 
1565 	return (error);
1566 }
1567 
1568 int
ifa_del_loopback_route(struct ifaddr * ifa,struct sockaddr * ia)1569 ifa_del_loopback_route(struct ifaddr *ifa, struct sockaddr *ia)
1570 {
1571 	int error = 0;
1572 	struct rt_addrinfo info;
1573 	struct sockaddr_dl null_sdl;
1574 
1575 	bzero(&null_sdl, sizeof(null_sdl));
1576 	null_sdl.sdl_len = sizeof(null_sdl);
1577 	null_sdl.sdl_family = AF_LINK;
1578 	null_sdl.sdl_type = ifa->ifa_ifp->if_type;
1579 	null_sdl.sdl_index = ifa->ifa_ifp->if_index;
1580 	bzero(&info, sizeof(info));
1581 	info.rti_flags = ifa->ifa_flags | RTF_HOST | RTF_STATIC;
1582 	info.rti_info[RTAX_DST] = ia;
1583 	info.rti_info[RTAX_GATEWAY] = (struct sockaddr *)&null_sdl;
1584 	error = rtrequest1_fib(RTM_DELETE, &info, NULL, ifa->ifa_ifp->if_fib);
1585 
1586 	if (error != 0)
1587 		log(LOG_INFO, "ifa_del_loopback_route: deletion failed\n");
1588 
1589 	return (error);
1590 }
1591 
1592 /*
1593  * XXX: Because sockaddr_dl has deeper structure than the sockaddr
1594  * structs used to represent other address families, it is necessary
1595  * to perform a different comparison.
1596  */
1597 
1598 #define	sa_equal(a1, a2)	\
1599 	(bcmp((a1), (a2), ((a1))->sa_len) == 0)
1600 
1601 #define	sa_dl_equal(a1, a2)	\
1602 	((((struct sockaddr_dl *)(a1))->sdl_len ==			\
1603 	 ((struct sockaddr_dl *)(a2))->sdl_len) &&			\
1604 	 (bcmp(LLADDR((struct sockaddr_dl *)(a1)),			\
1605 	       LLADDR((struct sockaddr_dl *)(a2)),			\
1606 	       ((struct sockaddr_dl *)(a1))->sdl_alen) == 0))
1607 
1608 /*
1609  * Locate an interface based on a complete address.
1610  */
1611 /*ARGSUSED*/
1612 static struct ifaddr *
ifa_ifwithaddr_internal(struct sockaddr * addr,int getref)1613 ifa_ifwithaddr_internal(struct sockaddr *addr, int getref)
1614 {
1615 	struct ifnet *ifp;
1616 	struct ifaddr *ifa;
1617 
1618 	IFNET_RLOCK_NOSLEEP();
1619 	TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
1620 		IF_ADDR_RLOCK(ifp);
1621 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1622 			if (ifa->ifa_addr->sa_family != addr->sa_family)
1623 				continue;
1624 			if (sa_equal(addr, ifa->ifa_addr)) {
1625 				if (getref)
1626 					ifa_ref(ifa);
1627 				IF_ADDR_RUNLOCK(ifp);
1628 				goto done;
1629 			}
1630 			/* IP6 doesn't have broadcast */
1631 			if ((ifp->if_flags & IFF_BROADCAST) &&
1632 			    ifa->ifa_broadaddr &&
1633 			    ifa->ifa_broadaddr->sa_len != 0 &&
1634 			    sa_equal(ifa->ifa_broadaddr, addr)) {
1635 				if (getref)
1636 					ifa_ref(ifa);
1637 				IF_ADDR_RUNLOCK(ifp);
1638 				goto done;
1639 			}
1640 		}
1641 		IF_ADDR_RUNLOCK(ifp);
1642 	}
1643 	ifa = NULL;
1644 done:
1645 	IFNET_RUNLOCK_NOSLEEP();
1646 	return (ifa);
1647 }
1648 
1649 struct ifaddr *
ifa_ifwithaddr(struct sockaddr * addr)1650 ifa_ifwithaddr(struct sockaddr *addr)
1651 {
1652 
1653 	return (ifa_ifwithaddr_internal(addr, 1));
1654 }
1655 
1656 int
ifa_ifwithaddr_check(struct sockaddr * addr)1657 ifa_ifwithaddr_check(struct sockaddr *addr)
1658 {
1659 
1660 	return (ifa_ifwithaddr_internal(addr, 0) != NULL);
1661 }
1662 
1663 /*
1664  * Locate an interface based on the broadcast address.
1665  */
1666 /* ARGSUSED */
1667 struct ifaddr *
ifa_ifwithbroadaddr(struct sockaddr * addr)1668 ifa_ifwithbroadaddr(struct sockaddr *addr)
1669 {
1670 	struct ifnet *ifp;
1671 	struct ifaddr *ifa;
1672 
1673 	IFNET_RLOCK_NOSLEEP();
1674 	TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
1675 		IF_ADDR_RLOCK(ifp);
1676 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1677 			if (ifa->ifa_addr->sa_family != addr->sa_family)
1678 				continue;
1679 			if ((ifp->if_flags & IFF_BROADCAST) &&
1680 			    ifa->ifa_broadaddr &&
1681 			    ifa->ifa_broadaddr->sa_len != 0 &&
1682 			    sa_equal(ifa->ifa_broadaddr, addr)) {
1683 				ifa_ref(ifa);
1684 				IF_ADDR_RUNLOCK(ifp);
1685 				goto done;
1686 			}
1687 		}
1688 		IF_ADDR_RUNLOCK(ifp);
1689 	}
1690 	ifa = NULL;
1691 done:
1692 	IFNET_RUNLOCK_NOSLEEP();
1693 	return (ifa);
1694 }
1695 
1696 /*
1697  * Locate the point to point interface with a given destination address.
1698  */
1699 /*ARGSUSED*/
1700 struct ifaddr *
ifa_ifwithdstaddr_fib(struct sockaddr * addr,int fibnum)1701 ifa_ifwithdstaddr_fib(struct sockaddr *addr, int fibnum)
1702 {
1703 	struct ifnet *ifp;
1704 	struct ifaddr *ifa;
1705 
1706 	IFNET_RLOCK_NOSLEEP();
1707 	TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
1708 		if ((ifp->if_flags & IFF_POINTOPOINT) == 0)
1709 			continue;
1710 		if ((fibnum != RT_ALL_FIBS) && (ifp->if_fib != fibnum))
1711 			continue;
1712 		IF_ADDR_RLOCK(ifp);
1713 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1714 			if (ifa->ifa_addr->sa_family != addr->sa_family)
1715 				continue;
1716 			if (ifa->ifa_dstaddr != NULL &&
1717 			    sa_equal(addr, ifa->ifa_dstaddr)) {
1718 				ifa_ref(ifa);
1719 				IF_ADDR_RUNLOCK(ifp);
1720 				goto done;
1721 			}
1722 		}
1723 		IF_ADDR_RUNLOCK(ifp);
1724 	}
1725 	ifa = NULL;
1726 done:
1727 	IFNET_RUNLOCK_NOSLEEP();
1728 	return (ifa);
1729 }
1730 
1731 struct ifaddr *
ifa_ifwithdstaddr(struct sockaddr * addr)1732 ifa_ifwithdstaddr(struct sockaddr *addr)
1733 {
1734 
1735 	return (ifa_ifwithdstaddr_fib(addr, RT_ALL_FIBS));
1736 }
1737 
1738 /*
1739  * Find an interface on a specific network.  If many, choice
1740  * is most specific found.
1741  */
1742 struct ifaddr *
ifa_ifwithnet_fib(struct sockaddr * addr,int ignore_ptp,int fibnum)1743 ifa_ifwithnet_fib(struct sockaddr *addr, int ignore_ptp, int fibnum)
1744 {
1745 	struct ifnet *ifp;
1746 	struct ifaddr *ifa;
1747 	struct ifaddr *ifa_maybe = NULL;
1748 	u_int af = addr->sa_family;
1749 	char *addr_data = addr->sa_data, *cplim;
1750 
1751 	/*
1752 	 * AF_LINK addresses can be looked up directly by their index number,
1753 	 * so do that if we can.
1754 	 */
1755 	if (af == AF_LINK) {
1756 	    struct sockaddr_dl *sdl = (struct sockaddr_dl *)addr;
1757 	    if (sdl->sdl_index && sdl->sdl_index <= V_if_index)
1758 		return (ifaddr_byindex(sdl->sdl_index));
1759 	}
1760 
1761 	/*
1762 	 * Scan though each interface, looking for ones that have addresses
1763 	 * in this address family and the requested fib.  Maintain a reference
1764 	 * on ifa_maybe once we find one, as we release the IF_ADDR_RLOCK() that
1765 	 * kept it stable when we move onto the next interface.
1766 	 */
1767 	IFNET_RLOCK_NOSLEEP();
1768 	TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
1769 		if ((fibnum != RT_ALL_FIBS) && (ifp->if_fib != fibnum))
1770 			continue;
1771 		IF_ADDR_RLOCK(ifp);
1772 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1773 			char *cp, *cp2, *cp3;
1774 
1775 			if (ifa->ifa_addr->sa_family != af)
1776 next:				continue;
1777 			if (af == AF_INET &&
1778 			    ifp->if_flags & IFF_POINTOPOINT && !ignore_ptp) {
1779 				/*
1780 				 * This is a bit broken as it doesn't
1781 				 * take into account that the remote end may
1782 				 * be a single node in the network we are
1783 				 * looking for.
1784 				 * The trouble is that we don't know the
1785 				 * netmask for the remote end.
1786 				 */
1787 				if (ifa->ifa_dstaddr != NULL &&
1788 				    sa_equal(addr, ifa->ifa_dstaddr)) {
1789 					ifa_ref(ifa);
1790 					IF_ADDR_RUNLOCK(ifp);
1791 					goto done;
1792 				}
1793 			} else {
1794 				/*
1795 				 * if we have a special address handler,
1796 				 * then use it instead of the generic one.
1797 				 */
1798 				if (ifa->ifa_claim_addr) {
1799 					if ((*ifa->ifa_claim_addr)(ifa, addr)) {
1800 						ifa_ref(ifa);
1801 						IF_ADDR_RUNLOCK(ifp);
1802 						goto done;
1803 					}
1804 					continue;
1805 				}
1806 
1807 				/*
1808 				 * Scan all the bits in the ifa's address.
1809 				 * If a bit dissagrees with what we are
1810 				 * looking for, mask it with the netmask
1811 				 * to see if it really matters.
1812 				 * (A byte at a time)
1813 				 */
1814 				if (ifa->ifa_netmask == 0)
1815 					continue;
1816 				cp = addr_data;
1817 				cp2 = ifa->ifa_addr->sa_data;
1818 				cp3 = ifa->ifa_netmask->sa_data;
1819 				cplim = ifa->ifa_netmask->sa_len
1820 					+ (char *)ifa->ifa_netmask;
1821 				while (cp3 < cplim)
1822 					if ((*cp++ ^ *cp2++) & *cp3++)
1823 						goto next; /* next address! */
1824 				/*
1825 				 * If the netmask of what we just found
1826 				 * is more specific than what we had before
1827 				 * (if we had one) then remember the new one
1828 				 * before continuing to search
1829 				 * for an even better one.
1830 				 */
1831 				if (ifa_maybe == NULL ||
1832 				    rn_refines((caddr_t)ifa->ifa_netmask,
1833 				    (caddr_t)ifa_maybe->ifa_netmask)) {
1834 					if (ifa_maybe != NULL)
1835 						ifa_free(ifa_maybe);
1836 					ifa_maybe = ifa;
1837 					ifa_ref(ifa_maybe);
1838 				}
1839 			}
1840 		}
1841 		IF_ADDR_RUNLOCK(ifp);
1842 	}
1843 	ifa = ifa_maybe;
1844 	ifa_maybe = NULL;
1845 done:
1846 	IFNET_RUNLOCK_NOSLEEP();
1847 	if (ifa_maybe != NULL)
1848 		ifa_free(ifa_maybe);
1849 	return (ifa);
1850 }
1851 
1852 struct ifaddr *
ifa_ifwithnet(struct sockaddr * addr,int ignore_ptp)1853 ifa_ifwithnet(struct sockaddr *addr, int ignore_ptp)
1854 {
1855 
1856 	return (ifa_ifwithnet_fib(addr, ignore_ptp, RT_ALL_FIBS));
1857 }
1858 
1859 /*
1860  * Find an interface address specific to an interface best matching
1861  * a given address.
1862  */
1863 struct ifaddr *
ifaof_ifpforaddr(struct sockaddr * addr,struct ifnet * ifp)1864 ifaof_ifpforaddr(struct sockaddr *addr, struct ifnet *ifp)
1865 {
1866 	struct ifaddr *ifa;
1867 	char *cp, *cp2, *cp3;
1868 	char *cplim;
1869 	struct ifaddr *ifa_maybe = NULL;
1870 	u_int af = addr->sa_family;
1871 
1872 	if (af >= AF_MAX)
1873 		return (NULL);
1874 	IF_ADDR_RLOCK(ifp);
1875 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1876 		if (ifa->ifa_addr->sa_family != af)
1877 			continue;
1878 		if (ifa_maybe == NULL)
1879 			ifa_maybe = ifa;
1880 		if (ifa->ifa_netmask == 0) {
1881 			if (sa_equal(addr, ifa->ifa_addr) ||
1882 			    (ifa->ifa_dstaddr &&
1883 			    sa_equal(addr, ifa->ifa_dstaddr)))
1884 				goto done;
1885 			continue;
1886 		}
1887 		if (ifp->if_flags & IFF_POINTOPOINT) {
1888 			if (sa_equal(addr, ifa->ifa_dstaddr))
1889 				goto done;
1890 		} else {
1891 			cp = addr->sa_data;
1892 			cp2 = ifa->ifa_addr->sa_data;
1893 			cp3 = ifa->ifa_netmask->sa_data;
1894 			cplim = ifa->ifa_netmask->sa_len + (char *)ifa->ifa_netmask;
1895 			for (; cp3 < cplim; cp3++)
1896 				if ((*cp++ ^ *cp2++) & *cp3)
1897 					break;
1898 			if (cp3 == cplim)
1899 				goto done;
1900 		}
1901 	}
1902 	ifa = ifa_maybe;
1903 done:
1904 	if (ifa != NULL)
1905 		ifa_ref(ifa);
1906 	IF_ADDR_RUNLOCK(ifp);
1907 	return (ifa);
1908 }
1909 
1910 #include <net/if_llatbl.h>
1911 
1912 /*
1913  * Default action when installing a route with a Link Level gateway.
1914  * Lookup an appropriate real ifa to point to.
1915  * This should be moved to /sys/net/link.c eventually.
1916  */
1917 static void
link_rtrequest(int cmd,struct rtentry * rt,struct rt_addrinfo * info)1918 link_rtrequest(int cmd, struct rtentry *rt, struct rt_addrinfo *info)
1919 {
1920 	struct ifaddr *ifa, *oifa;
1921 	struct sockaddr *dst;
1922 	struct ifnet *ifp;
1923 
1924 	RT_LOCK_ASSERT(rt);
1925 
1926 	if (cmd != RTM_ADD || ((ifa = rt->rt_ifa) == 0) ||
1927 	    ((ifp = ifa->ifa_ifp) == 0) || ((dst = rt_key(rt)) == 0))
1928 		return;
1929 	ifa = ifaof_ifpforaddr(dst, ifp);
1930 	if (ifa) {
1931 		oifa = rt->rt_ifa;
1932 		rt->rt_ifa = ifa;
1933 		ifa_free(oifa);
1934 		if (ifa->ifa_rtrequest && ifa->ifa_rtrequest != link_rtrequest)
1935 			ifa->ifa_rtrequest(cmd, rt, info);
1936 	}
1937 }
1938 
1939 /*
1940  * Mark an interface down and notify protocols of
1941  * the transition.
1942  * NOTE: must be called at splnet or eqivalent.
1943  */
1944 static void
if_unroute(struct ifnet * ifp,int flag,int fam)1945 if_unroute(struct ifnet *ifp, int flag, int fam)
1946 {
1947 	struct ifaddr *ifa;
1948 
1949 	KASSERT(flag == IFF_UP, ("if_unroute: flag != IFF_UP"));
1950 
1951 	ifp->if_flags &= ~flag;
1952 	getmicrotime(&ifp->if_lastchange);
1953 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
1954 		if (fam == PF_UNSPEC || (fam == ifa->ifa_addr->sa_family))
1955 			pfctlinput(PRC_IFDOWN, ifa->ifa_addr);
1956 	ifp->if_qflush(ifp);
1957 
1958 	if (ifp->if_carp)
1959 		(*carp_linkstate_p)(ifp);
1960 	rt_ifmsg(ifp);
1961 }
1962 
1963 /*
1964  * Mark an interface up and notify protocols of
1965  * the transition.
1966  * NOTE: must be called at splnet or eqivalent.
1967  */
1968 static void
if_route(struct ifnet * ifp,int flag,int fam)1969 if_route(struct ifnet *ifp, int flag, int fam)
1970 {
1971 	struct ifaddr *ifa;
1972 
1973 	KASSERT(flag == IFF_UP, ("if_route: flag != IFF_UP"));
1974 
1975 	ifp->if_flags |= flag;
1976 	getmicrotime(&ifp->if_lastchange);
1977 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
1978 		if (fam == PF_UNSPEC || (fam == ifa->ifa_addr->sa_family))
1979 			pfctlinput(PRC_IFUP, ifa->ifa_addr);
1980 	if (ifp->if_carp)
1981 		(*carp_linkstate_p)(ifp);
1982 	rt_ifmsg(ifp);
1983 #ifdef INET6
1984 	in6_if_up(ifp);
1985 #endif
1986 }
1987 
1988 void	(*vlan_link_state_p)(struct ifnet *);	/* XXX: private from if_vlan */
1989 void	(*vlan_trunk_cap_p)(struct ifnet *);		/* XXX: private from if_vlan */
1990 struct ifnet *(*vlan_trunkdev_p)(struct ifnet *);
1991 struct	ifnet *(*vlan_devat_p)(struct ifnet *, uint16_t);
1992 int	(*vlan_tag_p)(struct ifnet *, uint16_t *);
1993 int	(*vlan_setcookie_p)(struct ifnet *, void *);
1994 void	*(*vlan_cookie_p)(struct ifnet *);
1995 
1996 /*
1997  * Handle a change in the interface link state. To avoid LORs
1998  * between driver lock and upper layer locks, as well as possible
1999  * recursions, we post event to taskqueue, and all job
2000  * is done in static do_link_state_change().
2001  */
2002 void
if_link_state_change(struct ifnet * ifp,int link_state)2003 if_link_state_change(struct ifnet *ifp, int link_state)
2004 {
2005 	/* Return if state hasn't changed. */
2006 	if (ifp->if_link_state == link_state)
2007 		return;
2008 
2009 	ifp->if_link_state = link_state;
2010 
2011 	taskqueue_enqueue(taskqueue_swi, &ifp->if_linktask);
2012 }
2013 
2014 static void
do_link_state_change(void * arg,int pending)2015 do_link_state_change(void *arg, int pending)
2016 {
2017 	struct ifnet *ifp = (struct ifnet *)arg;
2018 	int link_state = ifp->if_link_state;
2019 	CURVNET_SET(ifp->if_vnet);
2020 
2021 	/* Notify that the link state has changed. */
2022 	rt_ifmsg(ifp);
2023 	if (ifp->if_vlantrunk != NULL)
2024 		(*vlan_link_state_p)(ifp);
2025 
2026 	if ((ifp->if_type == IFT_ETHER || ifp->if_type == IFT_L2VLAN) &&
2027 	    IFP2AC(ifp)->ac_netgraph != NULL)
2028 		(*ng_ether_link_state_p)(ifp, link_state);
2029 	if (ifp->if_carp)
2030 		(*carp_linkstate_p)(ifp);
2031 	if (ifp->if_bridge)
2032 		(*bridge_linkstate_p)(ifp);
2033 	if (ifp->if_lagg)
2034 		(*lagg_linkstate_p)(ifp, link_state);
2035 
2036 	if (IS_DEFAULT_VNET(curvnet))
2037 		devctl_notify("IFNET", ifp->if_xname,
2038 		    (link_state == LINK_STATE_UP) ? "LINK_UP" : "LINK_DOWN",
2039 		    NULL);
2040 	if (pending > 1)
2041 		if_printf(ifp, "%d link states coalesced\n", pending);
2042 	if (log_link_state_change)
2043 		log(LOG_NOTICE, "%s: link state changed to %s\n", ifp->if_xname,
2044 		    (link_state == LINK_STATE_UP) ? "UP" : "DOWN" );
2045 	EVENTHANDLER_INVOKE(ifnet_link_event, ifp, ifp->if_link_state);
2046 	CURVNET_RESTORE();
2047 }
2048 
2049 /*
2050  * Mark an interface down and notify protocols of
2051  * the transition.
2052  * NOTE: must be called at splnet or eqivalent.
2053  */
2054 void
if_down(struct ifnet * ifp)2055 if_down(struct ifnet *ifp)
2056 {
2057 
2058 	if_unroute(ifp, IFF_UP, AF_UNSPEC);
2059 }
2060 
2061 /*
2062  * Mark an interface up and notify protocols of
2063  * the transition.
2064  * NOTE: must be called at splnet or eqivalent.
2065  */
2066 void
if_up(struct ifnet * ifp)2067 if_up(struct ifnet *ifp)
2068 {
2069 
2070 	if_route(ifp, IFF_UP, AF_UNSPEC);
2071 }
2072 
2073 /*
2074  * Flush an interface queue.
2075  */
2076 void
if_qflush(struct ifnet * ifp)2077 if_qflush(struct ifnet *ifp)
2078 {
2079 	struct mbuf *m, *n;
2080 	struct ifaltq *ifq;
2081 
2082 	ifq = &ifp->if_snd;
2083 	IFQ_LOCK(ifq);
2084 #ifdef ALTQ
2085 	if (ALTQ_IS_ENABLED(ifq))
2086 		ALTQ_PURGE(ifq);
2087 #endif
2088 	n = ifq->ifq_head;
2089 	while ((m = n) != 0) {
2090 		n = m->m_act;
2091 		m_freem(m);
2092 	}
2093 	ifq->ifq_head = 0;
2094 	ifq->ifq_tail = 0;
2095 	ifq->ifq_len = 0;
2096 	IFQ_UNLOCK(ifq);
2097 }
2098 
2099 /*
2100  * Map interface name to interface structure pointer, with or without
2101  * returning a reference.
2102  */
2103 struct ifnet *
ifunit_ref(const char * name)2104 ifunit_ref(const char *name)
2105 {
2106 	struct ifnet *ifp;
2107 
2108 	IFNET_RLOCK_NOSLEEP();
2109 	TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2110 		if (strncmp(name, ifp->if_xname, IFNAMSIZ) == 0 &&
2111 		    !(ifp->if_flags & IFF_DYING))
2112 			break;
2113 	}
2114 	if (ifp != NULL)
2115 		if_ref(ifp);
2116 	IFNET_RUNLOCK_NOSLEEP();
2117 	return (ifp);
2118 }
2119 
2120 struct ifnet *
ifunit(const char * name)2121 ifunit(const char *name)
2122 {
2123 	struct ifnet *ifp;
2124 
2125 	IFNET_RLOCK_NOSLEEP();
2126 	TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2127 		if (strncmp(name, ifp->if_xname, IFNAMSIZ) == 0)
2128 			break;
2129 	}
2130 	IFNET_RUNLOCK_NOSLEEP();
2131 	return (ifp);
2132 }
2133 
2134 /*
2135  * Hardware specific interface ioctls.
2136  */
2137 static int
ifhwioctl(u_long cmd,struct ifnet * ifp,caddr_t data,struct thread * td)2138 ifhwioctl(u_long cmd, struct ifnet *ifp, caddr_t data, struct thread *td)
2139 {
2140 	struct ifreq *ifr;
2141 	struct ifstat *ifs;
2142 	int error = 0;
2143 	int new_flags, temp_flags;
2144 	size_t namelen, onamelen;
2145 	size_t descrlen;
2146 	char *descrbuf, *odescrbuf;
2147 	char new_name[IFNAMSIZ];
2148 	struct ifaddr *ifa;
2149 	struct sockaddr_dl *sdl;
2150 
2151 	ifr = (struct ifreq *)data;
2152 	switch (cmd) {
2153 	case SIOCGIFINDEX:
2154 		ifr->ifr_index = ifp->if_index;
2155 		break;
2156 
2157 	case SIOCGIFFLAGS:
2158 		temp_flags = ifp->if_flags | ifp->if_drv_flags;
2159 		ifr->ifr_flags = temp_flags & 0xffff;
2160 		ifr->ifr_flagshigh = temp_flags >> 16;
2161 		break;
2162 
2163 	case SIOCGIFCAP:
2164 		ifr->ifr_reqcap = ifp->if_capabilities;
2165 		ifr->ifr_curcap = ifp->if_capenable;
2166 		break;
2167 
2168 #ifdef MAC
2169 	case SIOCGIFMAC:
2170 		error = mac_ifnet_ioctl_get(td->td_ucred, ifr, ifp);
2171 		break;
2172 #endif
2173 
2174 	case SIOCGIFMETRIC:
2175 		ifr->ifr_metric = ifp->if_metric;
2176 		break;
2177 
2178 	case SIOCGIFMTU:
2179 		ifr->ifr_mtu = ifp->if_mtu;
2180 		break;
2181 
2182 	case SIOCGIFPHYS:
2183 		ifr->ifr_phys = ifp->if_physical;
2184 		break;
2185 
2186 	case SIOCGIFDESCR:
2187 		error = 0;
2188 		sx_slock(&ifdescr_sx);
2189 		if (ifp->if_description == NULL)
2190 			error = ENOMSG;
2191 		else {
2192 			/* space for terminating nul */
2193 			descrlen = strlen(ifp->if_description) + 1;
2194 			if (ifr->ifr_buffer.length < descrlen)
2195 				ifr->ifr_buffer.buffer = NULL;
2196 			else
2197 				error = copyout(ifp->if_description,
2198 				    ifr->ifr_buffer.buffer, descrlen);
2199 			ifr->ifr_buffer.length = descrlen;
2200 		}
2201 		sx_sunlock(&ifdescr_sx);
2202 		break;
2203 
2204 	case SIOCSIFDESCR:
2205 		error = priv_check(td, PRIV_NET_SETIFDESCR);
2206 		if (error)
2207 			return (error);
2208 
2209 		/*
2210 		 * Copy only (length-1) bytes to make sure that
2211 		 * if_description is always nul terminated.  The
2212 		 * length parameter is supposed to count the
2213 		 * terminating nul in.
2214 		 */
2215 		if (ifr->ifr_buffer.length > ifdescr_maxlen)
2216 			return (ENAMETOOLONG);
2217 		else if (ifr->ifr_buffer.length == 0)
2218 			descrbuf = NULL;
2219 		else {
2220 			descrbuf = malloc(ifr->ifr_buffer.length, M_IFDESCR,
2221 			    M_WAITOK | M_ZERO);
2222 			error = copyin(ifr->ifr_buffer.buffer, descrbuf,
2223 			    ifr->ifr_buffer.length - 1);
2224 			if (error) {
2225 				free(descrbuf, M_IFDESCR);
2226 				break;
2227 			}
2228 		}
2229 
2230 		sx_xlock(&ifdescr_sx);
2231 		odescrbuf = ifp->if_description;
2232 		ifp->if_description = descrbuf;
2233 		sx_xunlock(&ifdescr_sx);
2234 
2235 		getmicrotime(&ifp->if_lastchange);
2236 		free(odescrbuf, M_IFDESCR);
2237 		break;
2238 
2239 	case SIOCGIFFIB:
2240 		ifr->ifr_fib = ifp->if_fib;
2241 		break;
2242 
2243 	case SIOCSIFFIB:
2244 		error = priv_check(td, PRIV_NET_SETIFFIB);
2245 		if (error)
2246 			return (error);
2247 		if (ifr->ifr_fib >= rt_numfibs)
2248 			return (EINVAL);
2249 
2250 		ifp->if_fib = ifr->ifr_fib;
2251 		break;
2252 
2253 	case SIOCSIFFLAGS:
2254 		error = priv_check(td, PRIV_NET_SETIFFLAGS);
2255 		if (error)
2256 			return (error);
2257 		/*
2258 		 * Currently, no driver owned flags pass the IFF_CANTCHANGE
2259 		 * check, so we don't need special handling here yet.
2260 		 */
2261 		new_flags = (ifr->ifr_flags & 0xffff) |
2262 		    (ifr->ifr_flagshigh << 16);
2263 		if (ifp->if_flags & IFF_SMART) {
2264 			/* Smart drivers twiddle their own routes */
2265 		} else if (ifp->if_flags & IFF_UP &&
2266 		    (new_flags & IFF_UP) == 0) {
2267 			int s = splimp();
2268 			if_down(ifp);
2269 			splx(s);
2270 		} else if (new_flags & IFF_UP &&
2271 		    (ifp->if_flags & IFF_UP) == 0) {
2272 			int s = splimp();
2273 			if_up(ifp);
2274 			splx(s);
2275 		}
2276 		/* See if permanently promiscuous mode bit is about to flip */
2277 		if ((ifp->if_flags ^ new_flags) & IFF_PPROMISC) {
2278 			if (new_flags & IFF_PPROMISC)
2279 				ifp->if_flags |= IFF_PROMISC;
2280 			else if (ifp->if_pcount == 0)
2281 				ifp->if_flags &= ~IFF_PROMISC;
2282 			log(LOG_INFO, "%s: permanently promiscuous mode %s\n",
2283 			    ifp->if_xname,
2284 			    (new_flags & IFF_PPROMISC) ? "enabled" : "disabled");
2285 		}
2286 		ifp->if_flags = (ifp->if_flags & IFF_CANTCHANGE) |
2287 			(new_flags &~ IFF_CANTCHANGE);
2288 		if (ifp->if_ioctl) {
2289 			(void) (*ifp->if_ioctl)(ifp, cmd, data);
2290 		}
2291 		getmicrotime(&ifp->if_lastchange);
2292 		break;
2293 
2294 	case SIOCSIFCAP:
2295 		error = priv_check(td, PRIV_NET_SETIFCAP);
2296 		if (error)
2297 			return (error);
2298 		if (ifp->if_ioctl == NULL)
2299 			return (EOPNOTSUPP);
2300 		if (ifr->ifr_reqcap & ~ifp->if_capabilities)
2301 			return (EINVAL);
2302 		error = (*ifp->if_ioctl)(ifp, cmd, data);
2303 		if (error == 0)
2304 			getmicrotime(&ifp->if_lastchange);
2305 		break;
2306 
2307 #ifdef MAC
2308 	case SIOCSIFMAC:
2309 		error = mac_ifnet_ioctl_set(td->td_ucred, ifr, ifp);
2310 		break;
2311 #endif
2312 
2313 	case SIOCSIFNAME:
2314 		error = priv_check(td, PRIV_NET_SETIFNAME);
2315 		if (error)
2316 			return (error);
2317 		error = copyinstr(ifr->ifr_data, new_name, IFNAMSIZ, NULL);
2318 		if (error != 0)
2319 			return (error);
2320 		if (new_name[0] == '\0')
2321 			return (EINVAL);
2322 		if (ifunit(new_name) != NULL)
2323 			return (EEXIST);
2324 
2325 		/*
2326 		 * XXX: Locking.  Nothing else seems to lock if_flags,
2327 		 * and there are numerous other races with the
2328 		 * ifunit() checks not being atomic with namespace
2329 		 * changes (renames, vmoves, if_attach, etc).
2330 		 */
2331 		ifp->if_flags |= IFF_RENAMING;
2332 
2333 		/* Announce the departure of the interface. */
2334 		rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
2335 		EVENTHANDLER_INVOKE(ifnet_departure_event, ifp);
2336 
2337 		log(LOG_INFO, "%s: changing name to '%s'\n",
2338 		    ifp->if_xname, new_name);
2339 
2340 		strlcpy(ifp->if_xname, new_name, sizeof(ifp->if_xname));
2341 		ifa = ifp->if_addr;
2342 		IFA_LOCK(ifa);
2343 		sdl = (struct sockaddr_dl *)ifa->ifa_addr;
2344 		namelen = strlen(new_name);
2345 		onamelen = sdl->sdl_nlen;
2346 		/*
2347 		 * Move the address if needed.  This is safe because we
2348 		 * allocate space for a name of length IFNAMSIZ when we
2349 		 * create this in if_attach().
2350 		 */
2351 		if (namelen != onamelen) {
2352 			bcopy(sdl->sdl_data + onamelen,
2353 			    sdl->sdl_data + namelen, sdl->sdl_alen);
2354 		}
2355 		bcopy(new_name, sdl->sdl_data, namelen);
2356 		sdl->sdl_nlen = namelen;
2357 		sdl = (struct sockaddr_dl *)ifa->ifa_netmask;
2358 		bzero(sdl->sdl_data, onamelen);
2359 		while (namelen != 0)
2360 			sdl->sdl_data[--namelen] = 0xff;
2361 		IFA_UNLOCK(ifa);
2362 
2363 		EVENTHANDLER_INVOKE(ifnet_arrival_event, ifp);
2364 		/* Announce the return of the interface. */
2365 		rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
2366 
2367 		ifp->if_flags &= ~IFF_RENAMING;
2368 		break;
2369 
2370 #ifdef VIMAGE
2371 	case SIOCSIFVNET:
2372 		error = priv_check(td, PRIV_NET_SETIFVNET);
2373 		if (error)
2374 			return (error);
2375 		error = if_vmove_loan(td, ifp, ifr->ifr_name, ifr->ifr_jid);
2376 		break;
2377 #endif
2378 
2379 	case SIOCSIFMETRIC:
2380 		error = priv_check(td, PRIV_NET_SETIFMETRIC);
2381 		if (error)
2382 			return (error);
2383 		ifp->if_metric = ifr->ifr_metric;
2384 		getmicrotime(&ifp->if_lastchange);
2385 		break;
2386 
2387 	case SIOCSIFPHYS:
2388 		error = priv_check(td, PRIV_NET_SETIFPHYS);
2389 		if (error)
2390 			return (error);
2391 		if (ifp->if_ioctl == NULL)
2392 			return (EOPNOTSUPP);
2393 		error = (*ifp->if_ioctl)(ifp, cmd, data);
2394 		if (error == 0)
2395 			getmicrotime(&ifp->if_lastchange);
2396 		break;
2397 
2398 	case SIOCSIFMTU:
2399 	{
2400 		u_long oldmtu = ifp->if_mtu;
2401 
2402 		error = priv_check(td, PRIV_NET_SETIFMTU);
2403 		if (error)
2404 			return (error);
2405 		if (ifr->ifr_mtu < IF_MINMTU || ifr->ifr_mtu > IF_MAXMTU)
2406 			return (EINVAL);
2407 		if (ifp->if_ioctl == NULL)
2408 			return (EOPNOTSUPP);
2409 		error = (*ifp->if_ioctl)(ifp, cmd, data);
2410 		if (error == 0) {
2411 			getmicrotime(&ifp->if_lastchange);
2412 			rt_ifmsg(ifp);
2413 		}
2414 		/*
2415 		 * If the link MTU changed, do network layer specific procedure.
2416 		 */
2417 		if (ifp->if_mtu != oldmtu) {
2418 #ifdef INET6
2419 			nd6_setmtu(ifp);
2420 #endif
2421 		}
2422 		break;
2423 	}
2424 
2425 	case SIOCADDMULTI:
2426 	case SIOCDELMULTI:
2427 		if (cmd == SIOCADDMULTI)
2428 			error = priv_check(td, PRIV_NET_ADDMULTI);
2429 		else
2430 			error = priv_check(td, PRIV_NET_DELMULTI);
2431 		if (error)
2432 			return (error);
2433 
2434 		/* Don't allow group membership on non-multicast interfaces. */
2435 		if ((ifp->if_flags & IFF_MULTICAST) == 0)
2436 			return (EOPNOTSUPP);
2437 
2438 		/* Don't let users screw up protocols' entries. */
2439 		if (ifr->ifr_addr.sa_family != AF_LINK)
2440 			return (EINVAL);
2441 
2442 		if (cmd == SIOCADDMULTI) {
2443 			struct ifmultiaddr *ifma;
2444 
2445 			/*
2446 			 * Userland is only permitted to join groups once
2447 			 * via the if_addmulti() KPI, because it cannot hold
2448 			 * struct ifmultiaddr * between calls. It may also
2449 			 * lose a race while we check if the membership
2450 			 * already exists.
2451 			 */
2452 			IF_ADDR_RLOCK(ifp);
2453 			ifma = if_findmulti(ifp, &ifr->ifr_addr);
2454 			IF_ADDR_RUNLOCK(ifp);
2455 			if (ifma != NULL)
2456 				error = EADDRINUSE;
2457 			else
2458 				error = if_addmulti(ifp, &ifr->ifr_addr, &ifma);
2459 		} else {
2460 			error = if_delmulti(ifp, &ifr->ifr_addr);
2461 		}
2462 		if (error == 0)
2463 			getmicrotime(&ifp->if_lastchange);
2464 		break;
2465 
2466 	case SIOCSIFPHYADDR:
2467 	case SIOCDIFPHYADDR:
2468 #ifdef INET6
2469 	case SIOCSIFPHYADDR_IN6:
2470 #endif
2471 	case SIOCSLIFPHYADDR:
2472 	case SIOCSIFMEDIA:
2473 	case SIOCSIFGENERIC:
2474 		error = priv_check(td, PRIV_NET_HWIOCTL);
2475 		if (error)
2476 			return (error);
2477 		if (ifp->if_ioctl == NULL)
2478 			return (EOPNOTSUPP);
2479 		error = (*ifp->if_ioctl)(ifp, cmd, data);
2480 		if (error == 0)
2481 			getmicrotime(&ifp->if_lastchange);
2482 		break;
2483 
2484 	case SIOCGIFSTATUS:
2485 		ifs = (struct ifstat *)data;
2486 		ifs->ascii[0] = '\0';
2487 
2488 	case SIOCGIFPSRCADDR:
2489 	case SIOCGIFPDSTADDR:
2490 	case SIOCGLIFPHYADDR:
2491 	case SIOCGIFMEDIA:
2492 	case SIOCGIFGENERIC:
2493 		if (ifp->if_ioctl == NULL)
2494 			return (EOPNOTSUPP);
2495 		error = (*ifp->if_ioctl)(ifp, cmd, data);
2496 		break;
2497 
2498 	case SIOCSIFLLADDR:
2499 		error = priv_check(td, PRIV_NET_SETLLADDR);
2500 		if (error)
2501 			return (error);
2502 		error = if_setlladdr(ifp,
2503 		    ifr->ifr_addr.sa_data, ifr->ifr_addr.sa_len);
2504 		EVENTHANDLER_INVOKE(iflladdr_event, ifp);
2505 		break;
2506 
2507 	case SIOCAIFGROUP:
2508 	{
2509 		struct ifgroupreq *ifgr = (struct ifgroupreq *)ifr;
2510 
2511 		error = priv_check(td, PRIV_NET_ADDIFGROUP);
2512 		if (error)
2513 			return (error);
2514 		if ((error = if_addgroup(ifp, ifgr->ifgr_group)))
2515 			return (error);
2516 		break;
2517 	}
2518 
2519 	case SIOCGIFGROUP:
2520 		if ((error = if_getgroup((struct ifgroupreq *)ifr, ifp)))
2521 			return (error);
2522 		break;
2523 
2524 	case SIOCDIFGROUP:
2525 	{
2526 		struct ifgroupreq *ifgr = (struct ifgroupreq *)ifr;
2527 
2528 		error = priv_check(td, PRIV_NET_DELIFGROUP);
2529 		if (error)
2530 			return (error);
2531 		if ((error = if_delgroup(ifp, ifgr->ifgr_group)))
2532 			return (error);
2533 		break;
2534 	}
2535 
2536 	default:
2537 		error = ENOIOCTL;
2538 		break;
2539 	}
2540 	return (error);
2541 }
2542 
2543 #ifdef COMPAT_FREEBSD32
2544 struct ifconf32 {
2545 	int32_t	ifc_len;
2546 	union {
2547 		uint32_t	ifcu_buf;
2548 		uint32_t	ifcu_req;
2549 	} ifc_ifcu;
2550 };
2551 #define	SIOCGIFCONF32	_IOWR('i', 36, struct ifconf32)
2552 #endif
2553 
2554 /*
2555  * Interface ioctls.
2556  */
2557 int
ifioctl(struct socket * so,u_long cmd,caddr_t data,struct thread * td)2558 ifioctl(struct socket *so, u_long cmd, caddr_t data, struct thread *td)
2559 {
2560 	struct ifnet *ifp;
2561 	struct ifreq *ifr;
2562 	int error;
2563 	int oif_flags;
2564 
2565 	CURVNET_SET(so->so_vnet);
2566 	switch (cmd) {
2567 	case SIOCGIFCONF:
2568 	case OSIOCGIFCONF:
2569 		error = ifconf(cmd, data);
2570 		CURVNET_RESTORE();
2571 		return (error);
2572 
2573 #ifdef COMPAT_FREEBSD32
2574 	case SIOCGIFCONF32:
2575 		{
2576 			struct ifconf32 *ifc32;
2577 			struct ifconf ifc;
2578 
2579 			ifc32 = (struct ifconf32 *)data;
2580 			ifc.ifc_len = ifc32->ifc_len;
2581 			ifc.ifc_buf = PTRIN(ifc32->ifc_buf);
2582 
2583 			error = ifconf(SIOCGIFCONF, (void *)&ifc);
2584 			CURVNET_RESTORE();
2585 			if (error == 0)
2586 				ifc32->ifc_len = ifc.ifc_len;
2587 			return (error);
2588 		}
2589 #endif
2590 	}
2591 	ifr = (struct ifreq *)data;
2592 
2593 	switch (cmd) {
2594 #ifdef VIMAGE
2595 	case SIOCSIFRVNET:
2596 		error = priv_check(td, PRIV_NET_SETIFVNET);
2597 		if (error == 0)
2598 			error = if_vmove_reclaim(td, ifr->ifr_name,
2599 			    ifr->ifr_jid);
2600 		CURVNET_RESTORE();
2601 		return (error);
2602 #endif
2603 	case SIOCIFCREATE:
2604 	case SIOCIFCREATE2:
2605 		error = priv_check(td, PRIV_NET_IFCREATE);
2606 		if (error == 0)
2607 			error = if_clone_create(ifr->ifr_name,
2608 			    sizeof(ifr->ifr_name),
2609 			    cmd == SIOCIFCREATE2 ? ifr->ifr_data : NULL);
2610 		CURVNET_RESTORE();
2611 		return (error);
2612 	case SIOCIFDESTROY:
2613 		error = priv_check(td, PRIV_NET_IFDESTROY);
2614 		if (error == 0)
2615 			error = if_clone_destroy(ifr->ifr_name);
2616 		CURVNET_RESTORE();
2617 		return (error);
2618 
2619 	case SIOCIFGCLONERS:
2620 		error = if_clone_list((struct if_clonereq *)data);
2621 		CURVNET_RESTORE();
2622 		return (error);
2623 	case SIOCGIFGMEMB:
2624 		error = if_getgroupmembers((struct ifgroupreq *)data);
2625 		CURVNET_RESTORE();
2626 		return (error);
2627 	}
2628 
2629 	ifp = ifunit_ref(ifr->ifr_name);
2630 	if (ifp == NULL) {
2631 		CURVNET_RESTORE();
2632 		return (ENXIO);
2633 	}
2634 
2635 	error = ifhwioctl(cmd, ifp, data, td);
2636 	if (error != ENOIOCTL) {
2637 		if_rele(ifp);
2638 		CURVNET_RESTORE();
2639 		return (error);
2640 	}
2641 
2642 	oif_flags = ifp->if_flags;
2643 	if (so->so_proto == NULL) {
2644 		if_rele(ifp);
2645 		CURVNET_RESTORE();
2646 		return (EOPNOTSUPP);
2647 	}
2648 
2649 	/*
2650 	 * Pass the request on to the socket control method, and if the
2651 	 * latter returns EOPNOTSUPP, directly to the interface.
2652 	 *
2653 	 * Make an exception for the legacy SIOCSIF* requests.  Drivers
2654 	 * trust SIOCSIFADDR et al to come from an already privileged
2655 	 * layer, and do not perform any credentials checks or input
2656 	 * validation.
2657 	 */
2658 #ifndef COMPAT_43
2659 	error = ((*so->so_proto->pr_usrreqs->pru_control)(so, cmd,
2660 								 data,
2661 								 ifp, td));
2662 	if (error == EOPNOTSUPP && ifp != NULL && ifp->if_ioctl != NULL &&
2663 	    cmd != SIOCSIFADDR && cmd != SIOCSIFBRDADDR &&
2664 	    cmd != SIOCSIFDSTADDR && cmd != SIOCSIFNETMASK)
2665 		error = (*ifp->if_ioctl)(ifp, cmd, data);
2666 #else
2667 	{
2668 		u_long ocmd = cmd;
2669 
2670 		switch (cmd) {
2671 
2672 		case SIOCSIFDSTADDR:
2673 		case SIOCSIFADDR:
2674 		case SIOCSIFBRDADDR:
2675 		case SIOCSIFNETMASK:
2676 #if BYTE_ORDER != BIG_ENDIAN
2677 			if (ifr->ifr_addr.sa_family == 0 &&
2678 			    ifr->ifr_addr.sa_len < 16) {
2679 				ifr->ifr_addr.sa_family = ifr->ifr_addr.sa_len;
2680 				ifr->ifr_addr.sa_len = 16;
2681 			}
2682 #else
2683 			if (ifr->ifr_addr.sa_len == 0)
2684 				ifr->ifr_addr.sa_len = 16;
2685 #endif
2686 			break;
2687 
2688 		case OSIOCGIFADDR:
2689 			cmd = SIOCGIFADDR;
2690 			break;
2691 
2692 		case OSIOCGIFDSTADDR:
2693 			cmd = SIOCGIFDSTADDR;
2694 			break;
2695 
2696 		case OSIOCGIFBRDADDR:
2697 			cmd = SIOCGIFBRDADDR;
2698 			break;
2699 
2700 		case OSIOCGIFNETMASK:
2701 			cmd = SIOCGIFNETMASK;
2702 		}
2703 		error =  ((*so->so_proto->pr_usrreqs->pru_control)(so,
2704 								   cmd,
2705 								   data,
2706 								   ifp, td));
2707 		if (error == EOPNOTSUPP && ifp != NULL &&
2708 		    ifp->if_ioctl != NULL &&
2709 		    cmd != SIOCSIFADDR && cmd != SIOCSIFBRDADDR &&
2710 		    cmd != SIOCSIFDSTADDR && cmd != SIOCSIFNETMASK)
2711 			error = (*ifp->if_ioctl)(ifp, cmd, data);
2712 		switch (ocmd) {
2713 
2714 		case OSIOCGIFADDR:
2715 		case OSIOCGIFDSTADDR:
2716 		case OSIOCGIFBRDADDR:
2717 		case OSIOCGIFNETMASK:
2718 			*(u_short *)&ifr->ifr_addr = ifr->ifr_addr.sa_family;
2719 
2720 		}
2721 	}
2722 #endif /* COMPAT_43 */
2723 
2724 	if ((oif_flags ^ ifp->if_flags) & IFF_UP) {
2725 #ifdef INET6
2726 		if (ifp->if_flags & IFF_UP) {
2727 			int s = splimp();
2728 			in6_if_up(ifp);
2729 			splx(s);
2730 		}
2731 #endif
2732 	}
2733 	if_rele(ifp);
2734 	CURVNET_RESTORE();
2735 	return (error);
2736 }
2737 
2738 /*
2739  * The code common to handling reference counted flags,
2740  * e.g., in ifpromisc() and if_allmulti().
2741  * The "pflag" argument can specify a permanent mode flag to check,
2742  * such as IFF_PPROMISC for promiscuous mode; should be 0 if none.
2743  *
2744  * Only to be used on stack-owned flags, not driver-owned flags.
2745  */
2746 static int
if_setflag(struct ifnet * ifp,int flag,int pflag,int * refcount,int onswitch)2747 if_setflag(struct ifnet *ifp, int flag, int pflag, int *refcount, int onswitch)
2748 {
2749 	struct ifreq ifr;
2750 	int error;
2751 	int oldflags, oldcount;
2752 
2753 	/* Sanity checks to catch programming errors */
2754 	KASSERT((flag & (IFF_DRV_OACTIVE|IFF_DRV_RUNNING)) == 0,
2755 	    ("%s: setting driver-owned flag %d", __func__, flag));
2756 
2757 	if (onswitch)
2758 		KASSERT(*refcount >= 0,
2759 		    ("%s: increment negative refcount %d for flag %d",
2760 		    __func__, *refcount, flag));
2761 	else
2762 		KASSERT(*refcount > 0,
2763 		    ("%s: decrement non-positive refcount %d for flag %d",
2764 		    __func__, *refcount, flag));
2765 
2766 	/* In case this mode is permanent, just touch refcount */
2767 	if (ifp->if_flags & pflag) {
2768 		*refcount += onswitch ? 1 : -1;
2769 		return (0);
2770 	}
2771 
2772 	/* Save ifnet parameters for if_ioctl() may fail */
2773 	oldcount = *refcount;
2774 	oldflags = ifp->if_flags;
2775 
2776 	/*
2777 	 * See if we aren't the only and touching refcount is enough.
2778 	 * Actually toggle interface flag if we are the first or last.
2779 	 */
2780 	if (onswitch) {
2781 		if ((*refcount)++)
2782 			return (0);
2783 		ifp->if_flags |= flag;
2784 	} else {
2785 		if (--(*refcount))
2786 			return (0);
2787 		ifp->if_flags &= ~flag;
2788 	}
2789 
2790 	/* Call down the driver since we've changed interface flags */
2791 	if (ifp->if_ioctl == NULL) {
2792 		error = EOPNOTSUPP;
2793 		goto recover;
2794 	}
2795 	ifr.ifr_flags = ifp->if_flags & 0xffff;
2796 	ifr.ifr_flagshigh = ifp->if_flags >> 16;
2797 	error = (*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
2798 	if (error)
2799 		goto recover;
2800 	/* Notify userland that interface flags have changed */
2801 	rt_ifmsg(ifp);
2802 	return (0);
2803 
2804 recover:
2805 	/* Recover after driver error */
2806 	*refcount = oldcount;
2807 	ifp->if_flags = oldflags;
2808 	return (error);
2809 }
2810 
2811 /*
2812  * Set/clear promiscuous mode on interface ifp based on the truth value
2813  * of pswitch.  The calls are reference counted so that only the first
2814  * "on" request actually has an effect, as does the final "off" request.
2815  * Results are undefined if the "off" and "on" requests are not matched.
2816  */
2817 int
ifpromisc(struct ifnet * ifp,int pswitch)2818 ifpromisc(struct ifnet *ifp, int pswitch)
2819 {
2820 	int error;
2821 	int oldflags = ifp->if_flags;
2822 
2823 	error = if_setflag(ifp, IFF_PROMISC, IFF_PPROMISC,
2824 			   &ifp->if_pcount, pswitch);
2825 	/* If promiscuous mode status has changed, log a message */
2826 	if (error == 0 && ((ifp->if_flags ^ oldflags) & IFF_PROMISC))
2827 		log(LOG_INFO, "%s: promiscuous mode %s\n",
2828 		    ifp->if_xname,
2829 		    (ifp->if_flags & IFF_PROMISC) ? "enabled" : "disabled");
2830 	return (error);
2831 }
2832 
2833 /*
2834  * Return interface configuration
2835  * of system.  List may be used
2836  * in later ioctl's (above) to get
2837  * other information.
2838  */
2839 /*ARGSUSED*/
2840 static int
ifconf(u_long cmd,caddr_t data)2841 ifconf(u_long cmd, caddr_t data)
2842 {
2843 	struct ifconf *ifc = (struct ifconf *)data;
2844 	struct ifnet *ifp;
2845 	struct ifaddr *ifa;
2846 	struct ifreq ifr;
2847 	struct sbuf *sb;
2848 	int error, full = 0, valid_len, max_len;
2849 
2850 	/* Limit initial buffer size to MAXPHYS to avoid DoS from userspace. */
2851 	max_len = MAXPHYS - 1;
2852 
2853 	/* Prevent hostile input from being able to crash the system */
2854 	if (ifc->ifc_len <= 0)
2855 		return (EINVAL);
2856 
2857 again:
2858 	if (ifc->ifc_len <= max_len) {
2859 		max_len = ifc->ifc_len;
2860 		full = 1;
2861 	}
2862 	sb = sbuf_new(NULL, NULL, max_len + 1, SBUF_FIXEDLEN);
2863 	max_len = 0;
2864 	valid_len = 0;
2865 
2866 	IFNET_RLOCK();
2867 	TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2868 		int addrs;
2869 
2870 		/*
2871 		 * Zero the ifr_name buffer to make sure we don't
2872 		 * disclose the contents of the stack.
2873 		 */
2874 		memset(ifr.ifr_name, 0, sizeof(ifr.ifr_name));
2875 
2876 		if (strlcpy(ifr.ifr_name, ifp->if_xname, sizeof(ifr.ifr_name))
2877 		    >= sizeof(ifr.ifr_name)) {
2878 			sbuf_delete(sb);
2879 			IFNET_RUNLOCK();
2880 			return (ENAMETOOLONG);
2881 		}
2882 
2883 		addrs = 0;
2884 		IF_ADDR_RLOCK(ifp);
2885 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
2886 			struct sockaddr *sa = ifa->ifa_addr;
2887 
2888 			if (prison_if(curthread->td_ucred, sa) != 0)
2889 				continue;
2890 			addrs++;
2891 #ifdef COMPAT_43
2892 			if (cmd == OSIOCGIFCONF) {
2893 				struct osockaddr *osa =
2894 					 (struct osockaddr *)&ifr.ifr_addr;
2895 				ifr.ifr_addr = *sa;
2896 				osa->sa_family = sa->sa_family;
2897 				sbuf_bcat(sb, &ifr, sizeof(ifr));
2898 				max_len += sizeof(ifr);
2899 			} else
2900 #endif
2901 			if (sa->sa_len <= sizeof(*sa)) {
2902 				ifr.ifr_addr = *sa;
2903 				sbuf_bcat(sb, &ifr, sizeof(ifr));
2904 				max_len += sizeof(ifr);
2905 			} else {
2906 				sbuf_bcat(sb, &ifr,
2907 				    offsetof(struct ifreq, ifr_addr));
2908 				max_len += offsetof(struct ifreq, ifr_addr);
2909 				sbuf_bcat(sb, sa, sa->sa_len);
2910 				max_len += sa->sa_len;
2911 			}
2912 
2913 			if (sbuf_error(sb) == 0)
2914 				valid_len = sbuf_len(sb);
2915 		}
2916 		IF_ADDR_RUNLOCK(ifp);
2917 		if (addrs == 0) {
2918 			bzero((caddr_t)&ifr.ifr_addr, sizeof(ifr.ifr_addr));
2919 			sbuf_bcat(sb, &ifr, sizeof(ifr));
2920 			max_len += sizeof(ifr);
2921 
2922 			if (sbuf_error(sb) == 0)
2923 				valid_len = sbuf_len(sb);
2924 		}
2925 	}
2926 	IFNET_RUNLOCK();
2927 
2928 	/*
2929 	 * If we didn't allocate enough space (uncommon), try again.  If
2930 	 * we have already allocated as much space as we are allowed,
2931 	 * return what we've got.
2932 	 */
2933 	if (valid_len != max_len && !full) {
2934 		sbuf_delete(sb);
2935 		goto again;
2936 	}
2937 
2938 	ifc->ifc_len = valid_len;
2939 	sbuf_finish(sb);
2940 	error = copyout(sbuf_data(sb), ifc->ifc_req, ifc->ifc_len);
2941 	sbuf_delete(sb);
2942 	return (error);
2943 }
2944 
2945 /*
2946  * Just like ifpromisc(), but for all-multicast-reception mode.
2947  */
2948 int
if_allmulti(struct ifnet * ifp,int onswitch)2949 if_allmulti(struct ifnet *ifp, int onswitch)
2950 {
2951 
2952 	return (if_setflag(ifp, IFF_ALLMULTI, 0, &ifp->if_amcount, onswitch));
2953 }
2954 
2955 struct ifmultiaddr *
if_findmulti(struct ifnet * ifp,struct sockaddr * sa)2956 if_findmulti(struct ifnet *ifp, struct sockaddr *sa)
2957 {
2958 	struct ifmultiaddr *ifma;
2959 
2960 	IF_ADDR_LOCK_ASSERT(ifp);
2961 
2962 	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2963 		if (sa->sa_family == AF_LINK) {
2964 			if (sa_dl_equal(ifma->ifma_addr, sa))
2965 				break;
2966 		} else {
2967 			if (sa_equal(ifma->ifma_addr, sa))
2968 				break;
2969 		}
2970 	}
2971 
2972 	return ifma;
2973 }
2974 
2975 /*
2976  * Allocate a new ifmultiaddr and initialize based on passed arguments.  We
2977  * make copies of passed sockaddrs.  The ifmultiaddr will not be added to
2978  * the ifnet multicast address list here, so the caller must do that and
2979  * other setup work (such as notifying the device driver).  The reference
2980  * count is initialized to 1.
2981  */
2982 static struct ifmultiaddr *
if_allocmulti(struct ifnet * ifp,struct sockaddr * sa,struct sockaddr * llsa,int mflags)2983 if_allocmulti(struct ifnet *ifp, struct sockaddr *sa, struct sockaddr *llsa,
2984     int mflags)
2985 {
2986 	struct ifmultiaddr *ifma;
2987 	struct sockaddr *dupsa;
2988 
2989 	ifma = malloc(sizeof *ifma, M_IFMADDR, mflags |
2990 	    M_ZERO);
2991 	if (ifma == NULL)
2992 		return (NULL);
2993 
2994 	dupsa = malloc(sa->sa_len, M_IFMADDR, mflags);
2995 	if (dupsa == NULL) {
2996 		free(ifma, M_IFMADDR);
2997 		return (NULL);
2998 	}
2999 	bcopy(sa, dupsa, sa->sa_len);
3000 	ifma->ifma_addr = dupsa;
3001 
3002 	ifma->ifma_ifp = ifp;
3003 	ifma->ifma_refcount = 1;
3004 	ifma->ifma_protospec = NULL;
3005 
3006 	if (llsa == NULL) {
3007 		ifma->ifma_lladdr = NULL;
3008 		return (ifma);
3009 	}
3010 
3011 	dupsa = malloc(llsa->sa_len, M_IFMADDR, mflags);
3012 	if (dupsa == NULL) {
3013 		free(ifma->ifma_addr, M_IFMADDR);
3014 		free(ifma, M_IFMADDR);
3015 		return (NULL);
3016 	}
3017 	bcopy(llsa, dupsa, llsa->sa_len);
3018 	ifma->ifma_lladdr = dupsa;
3019 
3020 	return (ifma);
3021 }
3022 
3023 /*
3024  * if_freemulti: free ifmultiaddr structure and possibly attached related
3025  * addresses.  The caller is responsible for implementing reference
3026  * counting, notifying the driver, handling routing messages, and releasing
3027  * any dependent link layer state.
3028  */
3029 static void
if_freemulti(struct ifmultiaddr * ifma)3030 if_freemulti(struct ifmultiaddr *ifma)
3031 {
3032 
3033 	KASSERT(ifma->ifma_refcount == 0, ("if_freemulti: refcount %d",
3034 	    ifma->ifma_refcount));
3035 	KASSERT(ifma->ifma_protospec == NULL,
3036 	    ("if_freemulti: protospec not NULL"));
3037 
3038 	if (ifma->ifma_lladdr != NULL)
3039 		free(ifma->ifma_lladdr, M_IFMADDR);
3040 	free(ifma->ifma_addr, M_IFMADDR);
3041 	free(ifma, M_IFMADDR);
3042 }
3043 
3044 /*
3045  * Register an additional multicast address with a network interface.
3046  *
3047  * - If the address is already present, bump the reference count on the
3048  *   address and return.
3049  * - If the address is not link-layer, look up a link layer address.
3050  * - Allocate address structures for one or both addresses, and attach to the
3051  *   multicast address list on the interface.  If automatically adding a link
3052  *   layer address, the protocol address will own a reference to the link
3053  *   layer address, to be freed when it is freed.
3054  * - Notify the network device driver of an addition to the multicast address
3055  *   list.
3056  *
3057  * 'sa' points to caller-owned memory with the desired multicast address.
3058  *
3059  * 'retifma' will be used to return a pointer to the resulting multicast
3060  * address reference, if desired.
3061  */
3062 int
if_addmulti(struct ifnet * ifp,struct sockaddr * sa,struct ifmultiaddr ** retifma)3063 if_addmulti(struct ifnet *ifp, struct sockaddr *sa,
3064     struct ifmultiaddr **retifma)
3065 {
3066 	struct ifmultiaddr *ifma, *ll_ifma;
3067 	struct sockaddr *llsa;
3068 	int error;
3069 
3070 	/*
3071 	 * If the address is already present, return a new reference to it;
3072 	 * otherwise, allocate storage and set up a new address.
3073 	 */
3074 	IF_ADDR_WLOCK(ifp);
3075 	ifma = if_findmulti(ifp, sa);
3076 	if (ifma != NULL) {
3077 		ifma->ifma_refcount++;
3078 		if (retifma != NULL)
3079 			*retifma = ifma;
3080 		IF_ADDR_WUNLOCK(ifp);
3081 		return (0);
3082 	}
3083 
3084 	/*
3085 	 * The address isn't already present; resolve the protocol address
3086 	 * into a link layer address, and then look that up, bump its
3087 	 * refcount or allocate an ifma for that also.  If 'llsa' was
3088 	 * returned, we will need to free it later.
3089 	 */
3090 	llsa = NULL;
3091 	ll_ifma = NULL;
3092 	if (ifp->if_resolvemulti != NULL) {
3093 		error = ifp->if_resolvemulti(ifp, &llsa, sa);
3094 		if (error)
3095 			goto unlock_out;
3096 	}
3097 
3098 	/*
3099 	 * Allocate the new address.  Don't hook it up yet, as we may also
3100 	 * need to allocate a link layer multicast address.
3101 	 */
3102 	ifma = if_allocmulti(ifp, sa, llsa, M_NOWAIT);
3103 	if (ifma == NULL) {
3104 		error = ENOMEM;
3105 		goto free_llsa_out;
3106 	}
3107 
3108 	/*
3109 	 * If a link layer address is found, we'll need to see if it's
3110 	 * already present in the address list, or allocate is as well.
3111 	 * When this block finishes, the link layer address will be on the
3112 	 * list.
3113 	 */
3114 	if (llsa != NULL) {
3115 		ll_ifma = if_findmulti(ifp, llsa);
3116 		if (ll_ifma == NULL) {
3117 			ll_ifma = if_allocmulti(ifp, llsa, NULL, M_NOWAIT);
3118 			if (ll_ifma == NULL) {
3119 				--ifma->ifma_refcount;
3120 				if_freemulti(ifma);
3121 				error = ENOMEM;
3122 				goto free_llsa_out;
3123 			}
3124 			TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ll_ifma,
3125 			    ifma_link);
3126 		} else
3127 			ll_ifma->ifma_refcount++;
3128 		ifma->ifma_llifma = ll_ifma;
3129 	}
3130 
3131 	/*
3132 	 * We now have a new multicast address, ifma, and possibly a new or
3133 	 * referenced link layer address.  Add the primary address to the
3134 	 * ifnet address list.
3135 	 */
3136 	TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ifma, ifma_link);
3137 
3138 	if (retifma != NULL)
3139 		*retifma = ifma;
3140 
3141 	/*
3142 	 * Must generate the message while holding the lock so that 'ifma'
3143 	 * pointer is still valid.
3144 	 */
3145 	rt_newmaddrmsg(RTM_NEWMADDR, ifma);
3146 	IF_ADDR_WUNLOCK(ifp);
3147 
3148 	/*
3149 	 * We are certain we have added something, so call down to the
3150 	 * interface to let them know about it.
3151 	 */
3152 	if (ifp->if_ioctl != NULL) {
3153 		(void) (*ifp->if_ioctl)(ifp, SIOCADDMULTI, 0);
3154 	}
3155 
3156 	if (llsa != NULL)
3157 		free(llsa, M_IFMADDR);
3158 
3159 	return (0);
3160 
3161 free_llsa_out:
3162 	if (llsa != NULL)
3163 		free(llsa, M_IFMADDR);
3164 
3165 unlock_out:
3166 	IF_ADDR_WUNLOCK(ifp);
3167 	return (error);
3168 }
3169 
3170 /*
3171  * Delete a multicast group membership by network-layer group address.
3172  *
3173  * Returns ENOENT if the entry could not be found. If ifp no longer
3174  * exists, results are undefined. This entry point should only be used
3175  * from subsystems which do appropriate locking to hold ifp for the
3176  * duration of the call.
3177  * Network-layer protocol domains must use if_delmulti_ifma().
3178  */
3179 int
if_delmulti(struct ifnet * ifp,struct sockaddr * sa)3180 if_delmulti(struct ifnet *ifp, struct sockaddr *sa)
3181 {
3182 	struct ifmultiaddr *ifma;
3183 	int lastref;
3184 #ifdef INVARIANTS
3185 	struct ifnet *oifp;
3186 
3187 	IFNET_RLOCK_NOSLEEP();
3188 	TAILQ_FOREACH(oifp, &V_ifnet, if_link)
3189 		if (ifp == oifp)
3190 			break;
3191 	if (ifp != oifp)
3192 		ifp = NULL;
3193 	IFNET_RUNLOCK_NOSLEEP();
3194 
3195 	KASSERT(ifp != NULL, ("%s: ifnet went away", __func__));
3196 #endif
3197 	if (ifp == NULL)
3198 		return (ENOENT);
3199 
3200 	IF_ADDR_WLOCK(ifp);
3201 	lastref = 0;
3202 	ifma = if_findmulti(ifp, sa);
3203 	if (ifma != NULL)
3204 		lastref = if_delmulti_locked(ifp, ifma, 0);
3205 	IF_ADDR_WUNLOCK(ifp);
3206 
3207 	if (ifma == NULL)
3208 		return (ENOENT);
3209 
3210 	if (lastref && ifp->if_ioctl != NULL) {
3211 		(void)(*ifp->if_ioctl)(ifp, SIOCDELMULTI, 0);
3212 	}
3213 
3214 	return (0);
3215 }
3216 
3217 /*
3218  * Delete all multicast group membership for an interface.
3219  * Should be used to quickly flush all multicast filters.
3220  */
3221 void
if_delallmulti(struct ifnet * ifp)3222 if_delallmulti(struct ifnet *ifp)
3223 {
3224 	struct ifmultiaddr *ifma;
3225 	struct ifmultiaddr *next;
3226 
3227 	IF_ADDR_WLOCK(ifp);
3228 	TAILQ_FOREACH_SAFE(ifma, &ifp->if_multiaddrs, ifma_link, next)
3229 		if_delmulti_locked(ifp, ifma, 0);
3230 	IF_ADDR_WUNLOCK(ifp);
3231 }
3232 
3233 /*
3234  * Delete a multicast group membership by group membership pointer.
3235  * Network-layer protocol domains must use this routine.
3236  *
3237  * It is safe to call this routine if the ifp disappeared.
3238  */
3239 void
if_delmulti_ifma(struct ifmultiaddr * ifma)3240 if_delmulti_ifma(struct ifmultiaddr *ifma)
3241 {
3242 	struct ifnet *ifp;
3243 	int lastref;
3244 
3245 	ifp = ifma->ifma_ifp;
3246 #ifdef DIAGNOSTIC
3247 	if (ifp == NULL) {
3248 		printf("%s: ifma_ifp seems to be detached\n", __func__);
3249 	} else {
3250 		struct ifnet *oifp;
3251 
3252 		IFNET_RLOCK_NOSLEEP();
3253 		TAILQ_FOREACH(oifp, &V_ifnet, if_link)
3254 			if (ifp == oifp)
3255 				break;
3256 		if (ifp != oifp) {
3257 			printf("%s: ifnet %p disappeared\n", __func__, ifp);
3258 			ifp = NULL;
3259 		}
3260 		IFNET_RUNLOCK_NOSLEEP();
3261 	}
3262 #endif
3263 	/*
3264 	 * If and only if the ifnet instance exists: Acquire the address lock.
3265 	 */
3266 	if (ifp != NULL)
3267 		IF_ADDR_WLOCK(ifp);
3268 
3269 	lastref = if_delmulti_locked(ifp, ifma, 0);
3270 
3271 	if (ifp != NULL) {
3272 		/*
3273 		 * If and only if the ifnet instance exists:
3274 		 *  Release the address lock.
3275 		 *  If the group was left: update the hardware hash filter.
3276 		 */
3277 		IF_ADDR_WUNLOCK(ifp);
3278 		if (lastref && ifp->if_ioctl != NULL) {
3279 			(void)(*ifp->if_ioctl)(ifp, SIOCDELMULTI, 0);
3280 		}
3281 	}
3282 }
3283 
3284 /*
3285  * Perform deletion of network-layer and/or link-layer multicast address.
3286  *
3287  * Return 0 if the reference count was decremented.
3288  * Return 1 if the final reference was released, indicating that the
3289  * hardware hash filter should be reprogrammed.
3290  */
3291 static int
if_delmulti_locked(struct ifnet * ifp,struct ifmultiaddr * ifma,int detaching)3292 if_delmulti_locked(struct ifnet *ifp, struct ifmultiaddr *ifma, int detaching)
3293 {
3294 	struct ifmultiaddr *ll_ifma;
3295 
3296 	if (ifp != NULL && ifma->ifma_ifp != NULL) {
3297 		KASSERT(ifma->ifma_ifp == ifp,
3298 		    ("%s: inconsistent ifp %p", __func__, ifp));
3299 		IF_ADDR_WLOCK_ASSERT(ifp);
3300 	}
3301 
3302 	ifp = ifma->ifma_ifp;
3303 
3304 	/*
3305 	 * If the ifnet is detaching, null out references to ifnet,
3306 	 * so that upper protocol layers will notice, and not attempt
3307 	 * to obtain locks for an ifnet which no longer exists. The
3308 	 * routing socket announcement must happen before the ifnet
3309 	 * instance is detached from the system.
3310 	 */
3311 	if (detaching) {
3312 #ifdef DIAGNOSTIC
3313 		printf("%s: detaching ifnet instance %p\n", __func__, ifp);
3314 #endif
3315 		/*
3316 		 * ifp may already be nulled out if we are being reentered
3317 		 * to delete the ll_ifma.
3318 		 */
3319 		if (ifp != NULL) {
3320 			rt_newmaddrmsg(RTM_DELMADDR, ifma);
3321 			ifma->ifma_ifp = NULL;
3322 		}
3323 	}
3324 
3325 	if (--ifma->ifma_refcount > 0)
3326 		return 0;
3327 
3328 	/*
3329 	 * If this ifma is a network-layer ifma, a link-layer ifma may
3330 	 * have been associated with it. Release it first if so.
3331 	 */
3332 	ll_ifma = ifma->ifma_llifma;
3333 	if (ll_ifma != NULL) {
3334 		KASSERT(ifma->ifma_lladdr != NULL,
3335 		    ("%s: llifma w/o lladdr", __func__));
3336 		if (detaching)
3337 			ll_ifma->ifma_ifp = NULL;	/* XXX */
3338 		if (--ll_ifma->ifma_refcount == 0) {
3339 			if (ifp != NULL) {
3340 				TAILQ_REMOVE(&ifp->if_multiaddrs, ll_ifma,
3341 				    ifma_link);
3342 			}
3343 			if_freemulti(ll_ifma);
3344 		}
3345 	}
3346 
3347 	if (ifp != NULL)
3348 		TAILQ_REMOVE(&ifp->if_multiaddrs, ifma, ifma_link);
3349 
3350 	if_freemulti(ifma);
3351 
3352 	/*
3353 	 * The last reference to this instance of struct ifmultiaddr
3354 	 * was released; the hardware should be notified of this change.
3355 	 */
3356 	return 1;
3357 }
3358 
3359 /*
3360  * Set the link layer address on an interface.
3361  *
3362  * At this time we only support certain types of interfaces,
3363  * and we don't allow the length of the address to change.
3364  */
3365 int
if_setlladdr(struct ifnet * ifp,const u_char * lladdr,int len)3366 if_setlladdr(struct ifnet *ifp, const u_char *lladdr, int len)
3367 {
3368 	struct sockaddr_dl *sdl;
3369 	struct ifaddr *ifa;
3370 	struct ifreq ifr;
3371 
3372 	IF_ADDR_RLOCK(ifp);
3373 	ifa = ifp->if_addr;
3374 	if (ifa == NULL) {
3375 		IF_ADDR_RUNLOCK(ifp);
3376 		return (EINVAL);
3377 	}
3378 	ifa_ref(ifa);
3379 	IF_ADDR_RUNLOCK(ifp);
3380 	sdl = (struct sockaddr_dl *)ifa->ifa_addr;
3381 	if (sdl == NULL) {
3382 		ifa_free(ifa);
3383 		return (EINVAL);
3384 	}
3385 	if (len != sdl->sdl_alen) {	/* don't allow length to change */
3386 		ifa_free(ifa);
3387 		return (EINVAL);
3388 	}
3389 	switch (ifp->if_type) {
3390 	case IFT_ETHER:
3391 	case IFT_FDDI:
3392 	case IFT_XETHER:
3393 	case IFT_ISO88025:
3394 	case IFT_L2VLAN:
3395 	case IFT_BRIDGE:
3396 	case IFT_ARCNET:
3397 	case IFT_IEEE8023ADLAG:
3398 	case IFT_IEEE80211:
3399 		bcopy(lladdr, LLADDR(sdl), len);
3400 		ifa_free(ifa);
3401 		break;
3402 	default:
3403 		ifa_free(ifa);
3404 		return (ENODEV);
3405 	}
3406 
3407 	/*
3408 	 * If the interface is already up, we need
3409 	 * to re-init it in order to reprogram its
3410 	 * address filter.
3411 	 */
3412 	if ((ifp->if_flags & IFF_UP) != 0) {
3413 		if (ifp->if_ioctl) {
3414 			ifp->if_flags &= ~IFF_UP;
3415 			ifr.ifr_flags = ifp->if_flags & 0xffff;
3416 			ifr.ifr_flagshigh = ifp->if_flags >> 16;
3417 			(*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
3418 			ifp->if_flags |= IFF_UP;
3419 			ifr.ifr_flags = ifp->if_flags & 0xffff;
3420 			ifr.ifr_flagshigh = ifp->if_flags >> 16;
3421 			(*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
3422 		}
3423 #ifdef INET
3424 		/*
3425 		 * Also send gratuitous ARPs to notify other nodes about
3426 		 * the address change.
3427 		 */
3428 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
3429 			if (ifa->ifa_addr->sa_family == AF_INET)
3430 				arp_ifinit(ifp, ifa);
3431 		}
3432 #endif
3433 	}
3434 	return (0);
3435 }
3436 
3437 /*
3438  * The name argument must be a pointer to storage which will last as
3439  * long as the interface does.  For physical devices, the result of
3440  * device_get_name(dev) is a good choice and for pseudo-devices a
3441  * static string works well.
3442  */
3443 void
if_initname(struct ifnet * ifp,const char * name,int unit)3444 if_initname(struct ifnet *ifp, const char *name, int unit)
3445 {
3446 	ifp->if_dname = name;
3447 	ifp->if_dunit = unit;
3448 	if (unit != IF_DUNIT_NONE)
3449 		snprintf(ifp->if_xname, IFNAMSIZ, "%s%d", name, unit);
3450 	else
3451 		strlcpy(ifp->if_xname, name, IFNAMSIZ);
3452 }
3453 
3454 int
if_printf(struct ifnet * ifp,const char * fmt,...)3455 if_printf(struct ifnet *ifp, const char * fmt, ...)
3456 {
3457 	va_list ap;
3458 	int retval;
3459 
3460 	retval = printf("%s: ", ifp->if_xname);
3461 	va_start(ap, fmt);
3462 	retval += vprintf(fmt, ap);
3463 	va_end(ap);
3464 	return (retval);
3465 }
3466 
3467 void
if_start(struct ifnet * ifp)3468 if_start(struct ifnet *ifp)
3469 {
3470 
3471 	(*(ifp)->if_start)(ifp);
3472 }
3473 
3474 /*
3475  * Backwards compatibility interface for drivers
3476  * that have not implemented it
3477  */
3478 static int
if_transmit(struct ifnet * ifp,struct mbuf * m)3479 if_transmit(struct ifnet *ifp, struct mbuf *m)
3480 {
3481 	int error;
3482 
3483 	IFQ_HANDOFF(ifp, m, error);
3484 	return (error);
3485 }
3486 
3487 static void
if_input_default(struct ifnet * ifp __unused,struct mbuf * m)3488 if_input_default(struct ifnet *ifp __unused, struct mbuf *m)
3489 {
3490 
3491 	m_freem(m);
3492 }
3493 
3494 int
if_handoff(struct ifqueue * ifq,struct mbuf * m,struct ifnet * ifp,int adjust)3495 if_handoff(struct ifqueue *ifq, struct mbuf *m, struct ifnet *ifp, int adjust)
3496 {
3497 	int active = 0;
3498 
3499 	IF_LOCK(ifq);
3500 	if (_IF_QFULL(ifq)) {
3501 		_IF_DROP(ifq);
3502 		IF_UNLOCK(ifq);
3503 		m_freem(m);
3504 		return (0);
3505 	}
3506 	if (ifp != NULL) {
3507 		ifp->if_obytes += m->m_pkthdr.len + adjust;
3508 		if (m->m_flags & (M_BCAST|M_MCAST))
3509 			ifp->if_omcasts++;
3510 		active = ifp->if_drv_flags & IFF_DRV_OACTIVE;
3511 	}
3512 	_IF_ENQUEUE(ifq, m);
3513 	IF_UNLOCK(ifq);
3514 	if (ifp != NULL && !active)
3515 		(*(ifp)->if_start)(ifp);
3516 	return (1);
3517 }
3518 
3519 void
if_register_com_alloc(u_char type,if_com_alloc_t * a,if_com_free_t * f)3520 if_register_com_alloc(u_char type,
3521     if_com_alloc_t *a, if_com_free_t *f)
3522 {
3523 
3524 	KASSERT(if_com_alloc[type] == NULL,
3525 	    ("if_register_com_alloc: %d already registered", type));
3526 	KASSERT(if_com_free[type] == NULL,
3527 	    ("if_register_com_alloc: %d free already registered", type));
3528 
3529 	if_com_alloc[type] = a;
3530 	if_com_free[type] = f;
3531 }
3532 
3533 void
if_deregister_com_alloc(u_char type)3534 if_deregister_com_alloc(u_char type)
3535 {
3536 
3537 	KASSERT(if_com_alloc[type] != NULL,
3538 	    ("if_deregister_com_alloc: %d not registered", type));
3539 	KASSERT(if_com_free[type] != NULL,
3540 	    ("if_deregister_com_alloc: %d free not registered", type));
3541 	if_com_alloc[type] = NULL;
3542 	if_com_free[type] = NULL;
3543 }
3544