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