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