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