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