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