]> CyberLeo.Net >> Repos - FreeBSD/releng/8.1.git/blob - sys/net/if.c
Copy stable/8 to releng/8.1 in preparation for 8.1-RC1.
[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)
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 && ifp->if_flags & IFF_POINTOPOINT) {
1672                                 /*
1673                                  * This is a bit broken as it doesn't
1674                                  * take into account that the remote end may
1675                                  * be a single node in the network we are
1676                                  * looking for.
1677                                  * The trouble is that we don't know the
1678                                  * netmask for the remote end.
1679                                  */
1680                                 if (ifa->ifa_dstaddr != NULL &&
1681                                     sa_equal(addr, ifa->ifa_dstaddr)) {
1682                                         ifa_ref(ifa);
1683                                         IF_ADDR_UNLOCK(ifp);
1684                                         goto done;
1685                                 }
1686                         } else {
1687                                 /*
1688                                  * if we have a special address handler,
1689                                  * then use it instead of the generic one.
1690                                  */
1691                                 if (ifa->ifa_claim_addr) {
1692                                         if ((*ifa->ifa_claim_addr)(ifa, addr)) {
1693                                                 ifa_ref(ifa);
1694                                                 IF_ADDR_UNLOCK(ifp);
1695                                                 goto done;
1696                                         }
1697                                         continue;
1698                                 }
1699
1700                                 /*
1701                                  * Scan all the bits in the ifa's address.
1702                                  * If a bit dissagrees with what we are
1703                                  * looking for, mask it with the netmask
1704                                  * to see if it really matters.
1705                                  * (A byte at a time)
1706                                  */
1707                                 if (ifa->ifa_netmask == 0)
1708                                         continue;
1709                                 cp = addr_data;
1710                                 cp2 = ifa->ifa_addr->sa_data;
1711                                 cp3 = ifa->ifa_netmask->sa_data;
1712                                 cplim = ifa->ifa_netmask->sa_len
1713                                         + (char *)ifa->ifa_netmask;
1714                                 while (cp3 < cplim)
1715                                         if ((*cp++ ^ *cp2++) & *cp3++)
1716                                                 goto next; /* next address! */
1717                                 /*
1718                                  * If the netmask of what we just found
1719                                  * is more specific than what we had before
1720                                  * (if we had one) then remember the new one
1721                                  * before continuing to search
1722                                  * for an even better one.
1723                                  */
1724                                 if (ifa_maybe == NULL ||
1725                                     rn_refines((caddr_t)ifa->ifa_netmask,
1726                                     (caddr_t)ifa_maybe->ifa_netmask)) {
1727                                         if (ifa_maybe != NULL)
1728                                                 ifa_free(ifa_maybe);
1729                                         ifa_maybe = ifa;
1730                                         ifa_ref(ifa_maybe);
1731                                 }
1732                         }
1733                 }
1734                 IF_ADDR_UNLOCK(ifp);
1735         }
1736         ifa = ifa_maybe;
1737         ifa_maybe = NULL;
1738 done:
1739         IFNET_RUNLOCK_NOSLEEP();
1740         if (ifa_maybe != NULL)
1741                 ifa_free(ifa_maybe);
1742         return (ifa);
1743 }
1744
1745 /*
1746  * Find an interface address specific to an interface best matching
1747  * a given address.
1748  */
1749 struct ifaddr *
1750 ifaof_ifpforaddr(struct sockaddr *addr, struct ifnet *ifp)
1751 {
1752         struct ifaddr *ifa;
1753         char *cp, *cp2, *cp3;
1754         char *cplim;
1755         struct ifaddr *ifa_maybe = NULL;
1756         u_int af = addr->sa_family;
1757
1758         if (af >= AF_MAX)
1759                 return (0);
1760         IF_ADDR_LOCK(ifp);
1761         TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1762                 if (ifa->ifa_addr->sa_family != af)
1763                         continue;
1764                 if (ifa_maybe == NULL)
1765                         ifa_maybe = ifa;
1766                 if (ifa->ifa_netmask == 0) {
1767                         if (sa_equal(addr, ifa->ifa_addr) ||
1768                             (ifa->ifa_dstaddr &&
1769                             sa_equal(addr, ifa->ifa_dstaddr)))
1770                                 goto done;
1771                         continue;
1772                 }
1773                 if (ifp->if_flags & IFF_POINTOPOINT) {
1774                         if (sa_equal(addr, ifa->ifa_dstaddr))
1775                                 goto done;
1776                 } else {
1777                         cp = addr->sa_data;
1778                         cp2 = ifa->ifa_addr->sa_data;
1779                         cp3 = ifa->ifa_netmask->sa_data;
1780                         cplim = ifa->ifa_netmask->sa_len + (char *)ifa->ifa_netmask;
1781                         for (; cp3 < cplim; cp3++)
1782                                 if ((*cp++ ^ *cp2++) & *cp3)
1783                                         break;
1784                         if (cp3 == cplim)
1785                                 goto done;
1786                 }
1787         }
1788         ifa = ifa_maybe;
1789 done:
1790         if (ifa != NULL)
1791                 ifa_ref(ifa);
1792         IF_ADDR_UNLOCK(ifp);
1793         return (ifa);
1794 }
1795
1796 #include <net/if_llatbl.h>
1797
1798 /*
1799  * Default action when installing a route with a Link Level gateway.
1800  * Lookup an appropriate real ifa to point to.
1801  * This should be moved to /sys/net/link.c eventually.
1802  */
1803 static void
1804 link_rtrequest(int cmd, struct rtentry *rt, struct rt_addrinfo *info)
1805 {
1806         struct ifaddr *ifa, *oifa;
1807         struct sockaddr *dst;
1808         struct ifnet *ifp;
1809
1810         RT_LOCK_ASSERT(rt);
1811
1812         if (cmd != RTM_ADD || ((ifa = rt->rt_ifa) == 0) ||
1813             ((ifp = ifa->ifa_ifp) == 0) || ((dst = rt_key(rt)) == 0))
1814                 return;
1815         ifa = ifaof_ifpforaddr(dst, ifp);
1816         if (ifa) {
1817                 oifa = rt->rt_ifa;
1818                 rt->rt_ifa = ifa;
1819                 ifa_free(oifa);
1820                 if (ifa->ifa_rtrequest && ifa->ifa_rtrequest != link_rtrequest)
1821                         ifa->ifa_rtrequest(cmd, rt, info);
1822         }
1823 }
1824
1825 /*
1826  * Mark an interface down and notify protocols of
1827  * the transition.
1828  * NOTE: must be called at splnet or eqivalent.
1829  */
1830 static void
1831 if_unroute(struct ifnet *ifp, int flag, int fam)
1832 {
1833         struct ifaddr *ifa;
1834
1835         KASSERT(flag == IFF_UP, ("if_unroute: flag != IFF_UP"));
1836
1837         ifp->if_flags &= ~flag;
1838         getmicrotime(&ifp->if_lastchange);
1839         TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
1840                 if (fam == PF_UNSPEC || (fam == ifa->ifa_addr->sa_family))
1841                         pfctlinput(PRC_IFDOWN, ifa->ifa_addr);
1842         ifp->if_qflush(ifp);
1843
1844 #if defined(INET) || defined(INET6)
1845 #ifdef DEV_CARP
1846         if (ifp->if_carp)
1847                 carp_carpdev_state(ifp->if_carp);
1848 #endif
1849 #endif
1850         rt_ifmsg(ifp);
1851 }
1852
1853 /*
1854  * Mark an interface up and notify protocols of
1855  * the transition.
1856  * NOTE: must be called at splnet or eqivalent.
1857  */
1858 static void
1859 if_route(struct ifnet *ifp, int flag, int fam)
1860 {
1861         struct ifaddr *ifa;
1862
1863         KASSERT(flag == IFF_UP, ("if_route: flag != IFF_UP"));
1864
1865         ifp->if_flags |= flag;
1866         getmicrotime(&ifp->if_lastchange);
1867         TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
1868                 if (fam == PF_UNSPEC || (fam == ifa->ifa_addr->sa_family))
1869                         pfctlinput(PRC_IFUP, ifa->ifa_addr);
1870 #if defined(INET) || defined(INET6)
1871 #ifdef DEV_CARP
1872         if (ifp->if_carp)
1873                 carp_carpdev_state(ifp->if_carp);
1874 #endif
1875 #endif
1876         rt_ifmsg(ifp);
1877 #ifdef INET6
1878         in6_if_up(ifp);
1879 #endif
1880 }
1881
1882 void    (*vlan_link_state_p)(struct ifnet *, int);      /* XXX: private from if_vlan */
1883 void    (*vlan_trunk_cap_p)(struct ifnet *);            /* XXX: private from if_vlan */
1884
1885 /*
1886  * Handle a change in the interface link state. To avoid LORs
1887  * between driver lock and upper layer locks, as well as possible
1888  * recursions, we post event to taskqueue, and all job
1889  * is done in static do_link_state_change().
1890  */
1891 void
1892 if_link_state_change(struct ifnet *ifp, int link_state)
1893 {
1894         /* Return if state hasn't changed. */
1895         if (ifp->if_link_state == link_state)
1896                 return;
1897
1898         ifp->if_link_state = link_state;
1899
1900         taskqueue_enqueue(taskqueue_swi, &ifp->if_linktask);
1901 }
1902
1903 static void
1904 do_link_state_change(void *arg, int pending)
1905 {
1906         struct ifnet *ifp = (struct ifnet *)arg;
1907         int link_state = ifp->if_link_state;
1908         CURVNET_SET(ifp->if_vnet);
1909
1910         /* Notify that the link state has changed. */
1911         rt_ifmsg(ifp);
1912         if (ifp->if_vlantrunk != NULL)
1913                 (*vlan_link_state_p)(ifp, 0);
1914
1915         if ((ifp->if_type == IFT_ETHER || ifp->if_type == IFT_L2VLAN) &&
1916             IFP2AC(ifp)->ac_netgraph != NULL)
1917                 (*ng_ether_link_state_p)(ifp, link_state);
1918 #if defined(INET) || defined(INET6)
1919 #ifdef DEV_CARP
1920         if (ifp->if_carp)
1921                 carp_carpdev_state(ifp->if_carp);
1922 #endif
1923 #endif
1924         if (ifp->if_bridge) {
1925                 KASSERT(bstp_linkstate_p != NULL,("if_bridge bstp not loaded!"));
1926                 (*bstp_linkstate_p)(ifp, link_state);
1927         }
1928         if (ifp->if_lagg) {
1929                 KASSERT(lagg_linkstate_p != NULL,("if_lagg not loaded!"));
1930                 (*lagg_linkstate_p)(ifp, link_state);
1931         }
1932
1933         if (IS_DEFAULT_VNET(curvnet))
1934                 devctl_notify("IFNET", ifp->if_xname,
1935                     (link_state == LINK_STATE_UP) ? "LINK_UP" : "LINK_DOWN",
1936                     NULL);
1937         if (pending > 1)
1938                 if_printf(ifp, "%d link states coalesced\n", pending);
1939         if (log_link_state_change)
1940                 log(LOG_NOTICE, "%s: link state changed to %s\n", ifp->if_xname,
1941                     (link_state == LINK_STATE_UP) ? "UP" : "DOWN" );
1942         CURVNET_RESTORE();
1943 }
1944
1945 /*
1946  * Mark an interface down and notify protocols of
1947  * the transition.
1948  * NOTE: must be called at splnet or eqivalent.
1949  */
1950 void
1951 if_down(struct ifnet *ifp)
1952 {
1953
1954         if_unroute(ifp, IFF_UP, AF_UNSPEC);
1955 }
1956
1957 /*
1958  * Mark an interface up and notify protocols of
1959  * the transition.
1960  * NOTE: must be called at splnet or eqivalent.
1961  */
1962 void
1963 if_up(struct ifnet *ifp)
1964 {
1965
1966         if_route(ifp, IFF_UP, AF_UNSPEC);
1967 }
1968
1969 /*
1970  * Flush an interface queue.
1971  */
1972 void
1973 if_qflush(struct ifnet *ifp)
1974 {
1975         struct mbuf *m, *n;
1976         struct ifaltq *ifq;
1977         
1978         ifq = &ifp->if_snd;
1979         IFQ_LOCK(ifq);
1980 #ifdef ALTQ
1981         if (ALTQ_IS_ENABLED(ifq))
1982                 ALTQ_PURGE(ifq);
1983 #endif
1984         n = ifq->ifq_head;
1985         while ((m = n) != 0) {
1986                 n = m->m_act;
1987                 m_freem(m);
1988         }
1989         ifq->ifq_head = 0;
1990         ifq->ifq_tail = 0;
1991         ifq->ifq_len = 0;
1992         IFQ_UNLOCK(ifq);
1993 }
1994
1995 /*
1996  * Handle interface watchdog timer routines.  Called
1997  * from softclock, we decrement timers (if set) and
1998  * call the appropriate interface routine on expiration.
1999  *
2000  * XXXRW: Note that because timeouts run with Giant, if_watchdog() is called
2001  * holding Giant.
2002  */
2003 static void
2004 if_slowtimo(void *arg)
2005 {
2006         VNET_ITERATOR_DECL(vnet_iter);
2007         struct ifnet *ifp;
2008         int s = splimp();
2009
2010         VNET_LIST_RLOCK_NOSLEEP();
2011         IFNET_RLOCK_NOSLEEP();
2012         VNET_FOREACH(vnet_iter) {
2013                 CURVNET_SET(vnet_iter);
2014                 TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2015                         if (ifp->if_timer == 0 || --ifp->if_timer)
2016                                 continue;
2017                         if (ifp->if_watchdog)
2018                                 (*ifp->if_watchdog)(ifp);
2019                 }
2020                 CURVNET_RESTORE();
2021         }
2022         IFNET_RUNLOCK_NOSLEEP();
2023         VNET_LIST_RUNLOCK_NOSLEEP();
2024         splx(s);
2025         timeout(if_slowtimo, (void *)0, hz / IFNET_SLOWHZ);
2026 }
2027
2028 /*
2029  * Map interface name to interface structure pointer, with or without
2030  * returning a reference.
2031  */
2032 struct ifnet *
2033 ifunit_ref(const char *name)
2034 {
2035         struct ifnet *ifp;
2036
2037         IFNET_RLOCK_NOSLEEP();
2038         TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2039                 if (strncmp(name, ifp->if_xname, IFNAMSIZ) == 0 &&
2040                     !(ifp->if_flags & IFF_DYING))
2041                         break;
2042         }
2043         if (ifp != NULL)
2044                 if_ref(ifp);
2045         IFNET_RUNLOCK_NOSLEEP();
2046         return (ifp);
2047 }
2048
2049 struct ifnet *
2050 ifunit(const char *name)
2051 {
2052         struct ifnet *ifp;
2053
2054         IFNET_RLOCK_NOSLEEP();
2055         TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2056                 if (strncmp(name, ifp->if_xname, IFNAMSIZ) == 0)
2057                         break;
2058         }
2059         IFNET_RUNLOCK_NOSLEEP();
2060         return (ifp);
2061 }
2062
2063 /*
2064  * Hardware specific interface ioctls.
2065  */
2066 static int
2067 ifhwioctl(u_long cmd, struct ifnet *ifp, caddr_t data, struct thread *td)
2068 {
2069         struct ifreq *ifr;
2070         struct ifstat *ifs;
2071         int error = 0;
2072         int new_flags, temp_flags;
2073         size_t namelen, onamelen;
2074         size_t descrlen;
2075         char *descrbuf, *odescrbuf;
2076         char new_name[IFNAMSIZ];
2077         struct ifaddr *ifa;
2078         struct sockaddr_dl *sdl;
2079
2080         ifr = (struct ifreq *)data;
2081         switch (cmd) {
2082         case SIOCGIFINDEX:
2083                 ifr->ifr_index = ifp->if_index;
2084                 break;
2085
2086         case SIOCGIFFLAGS:
2087                 temp_flags = ifp->if_flags | ifp->if_drv_flags;
2088                 ifr->ifr_flags = temp_flags & 0xffff;
2089                 ifr->ifr_flagshigh = temp_flags >> 16;
2090                 break;
2091
2092         case SIOCGIFCAP:
2093                 ifr->ifr_reqcap = ifp->if_capabilities;
2094                 ifr->ifr_curcap = ifp->if_capenable;
2095                 break;
2096
2097 #ifdef MAC
2098         case SIOCGIFMAC:
2099                 error = mac_ifnet_ioctl_get(td->td_ucred, ifr, ifp);
2100                 break;
2101 #endif
2102
2103         case SIOCGIFMETRIC:
2104                 ifr->ifr_metric = ifp->if_metric;
2105                 break;
2106
2107         case SIOCGIFMTU:
2108                 ifr->ifr_mtu = ifp->if_mtu;
2109                 break;
2110
2111         case SIOCGIFPHYS:
2112                 ifr->ifr_phys = ifp->if_physical;
2113                 break;
2114
2115         case SIOCGIFDESCR:
2116                 error = 0;
2117                 sx_slock(&ifdescr_sx);
2118                 if (ifp->if_description == NULL)
2119                         error = ENOMSG;
2120                 else {
2121                         /* space for terminating nul */
2122                         descrlen = strlen(ifp->if_description) + 1;
2123                         if (ifr->ifr_buffer.length < descrlen)
2124                                 ifr->ifr_buffer.buffer = NULL;
2125                         else
2126                                 error = copyout(ifp->if_description,
2127                                     ifr->ifr_buffer.buffer, descrlen);
2128                         ifr->ifr_buffer.length = descrlen;
2129                 }
2130                 sx_sunlock(&ifdescr_sx);
2131                 break;
2132
2133         case SIOCSIFDESCR:
2134                 error = priv_check(td, PRIV_NET_SETIFDESCR);
2135                 if (error)
2136                         return (error);
2137
2138                 /*
2139                  * Copy only (length-1) bytes to make sure that
2140                  * if_description is always nul terminated.  The
2141                  * length parameter is supposed to count the
2142                  * terminating nul in.
2143                  */
2144                 if (ifr->ifr_buffer.length > ifdescr_maxlen)
2145                         return (ENAMETOOLONG);
2146                 else if (ifr->ifr_buffer.length == 0)
2147                         descrbuf = NULL;
2148                 else {
2149                         descrbuf = malloc(ifr->ifr_buffer.length, M_IFDESCR,
2150                             M_WAITOK | M_ZERO);
2151                         error = copyin(ifr->ifr_buffer.buffer, descrbuf,
2152                             ifr->ifr_buffer.length - 1);
2153                         if (error) {
2154                                 free(descrbuf, M_IFDESCR);
2155                                 break;
2156                         }
2157                 }
2158
2159                 sx_xlock(&ifdescr_sx);
2160                 odescrbuf = ifp->if_description;
2161                 ifp->if_description = descrbuf;
2162                 sx_xunlock(&ifdescr_sx);
2163
2164                 getmicrotime(&ifp->if_lastchange);
2165                 free(odescrbuf, M_IFDESCR);
2166                 break;
2167
2168         case SIOCSIFFLAGS:
2169                 error = priv_check(td, PRIV_NET_SETIFFLAGS);
2170                 if (error)
2171                         return (error);
2172                 /*
2173                  * Currently, no driver owned flags pass the IFF_CANTCHANGE
2174                  * check, so we don't need special handling here yet.
2175                  */
2176                 new_flags = (ifr->ifr_flags & 0xffff) |
2177                     (ifr->ifr_flagshigh << 16);
2178                 if (ifp->if_flags & IFF_SMART) {
2179                         /* Smart drivers twiddle their own routes */
2180                 } else if (ifp->if_flags & IFF_UP &&
2181                     (new_flags & IFF_UP) == 0) {
2182                         int s = splimp();
2183                         if_down(ifp);
2184                         splx(s);
2185                 } else if (new_flags & IFF_UP &&
2186                     (ifp->if_flags & IFF_UP) == 0) {
2187                         int s = splimp();
2188                         if_up(ifp);
2189                         splx(s);
2190                 }
2191                 /* See if permanently promiscuous mode bit is about to flip */
2192                 if ((ifp->if_flags ^ new_flags) & IFF_PPROMISC) {
2193                         if (new_flags & IFF_PPROMISC)
2194                                 ifp->if_flags |= IFF_PROMISC;
2195                         else if (ifp->if_pcount == 0)
2196                                 ifp->if_flags &= ~IFF_PROMISC;
2197                         log(LOG_INFO, "%s: permanently promiscuous mode %s\n",
2198                             ifp->if_xname,
2199                             (new_flags & IFF_PPROMISC) ? "enabled" : "disabled");
2200                 }
2201                 ifp->if_flags = (ifp->if_flags & IFF_CANTCHANGE) |
2202                         (new_flags &~ IFF_CANTCHANGE);
2203                 if (ifp->if_ioctl) {
2204                         (void) (*ifp->if_ioctl)(ifp, cmd, data);
2205                 }
2206                 getmicrotime(&ifp->if_lastchange);
2207                 break;
2208
2209         case SIOCSIFCAP:
2210                 error = priv_check(td, PRIV_NET_SETIFCAP);
2211                 if (error)
2212                         return (error);
2213                 if (ifp->if_ioctl == NULL)
2214                         return (EOPNOTSUPP);
2215                 if (ifr->ifr_reqcap & ~ifp->if_capabilities)
2216                         return (EINVAL);
2217                 error = (*ifp->if_ioctl)(ifp, cmd, data);
2218                 if (error == 0)
2219                         getmicrotime(&ifp->if_lastchange);
2220                 break;
2221
2222 #ifdef MAC
2223         case SIOCSIFMAC:
2224                 error = mac_ifnet_ioctl_set(td->td_ucred, ifr, ifp);
2225                 break;
2226 #endif
2227
2228         case SIOCSIFNAME:
2229                 error = priv_check(td, PRIV_NET_SETIFNAME);
2230                 if (error)
2231                         return (error);
2232                 error = copyinstr(ifr->ifr_data, new_name, IFNAMSIZ, NULL);
2233                 if (error != 0)
2234                         return (error);
2235                 if (new_name[0] == '\0')
2236                         return (EINVAL);
2237                 if (ifunit(new_name) != NULL)
2238                         return (EEXIST);
2239
2240                 /*
2241                  * XXX: Locking.  Nothing else seems to lock if_flags,
2242                  * and there are numerous other races with the
2243                  * ifunit() checks not being atomic with namespace
2244                  * changes (renames, vmoves, if_attach, etc).
2245                  */
2246                 ifp->if_flags |= IFF_RENAMING;
2247                 
2248                 /* Announce the departure of the interface. */
2249                 rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
2250                 EVENTHANDLER_INVOKE(ifnet_departure_event, ifp);
2251
2252                 log(LOG_INFO, "%s: changing name to '%s'\n",
2253                     ifp->if_xname, new_name);
2254
2255                 strlcpy(ifp->if_xname, new_name, sizeof(ifp->if_xname));
2256                 ifa = ifp->if_addr;
2257                 IFA_LOCK(ifa);
2258                 sdl = (struct sockaddr_dl *)ifa->ifa_addr;
2259                 namelen = strlen(new_name);
2260                 onamelen = sdl->sdl_nlen;
2261                 /*
2262                  * Move the address if needed.  This is safe because we
2263                  * allocate space for a name of length IFNAMSIZ when we
2264                  * create this in if_attach().
2265                  */
2266                 if (namelen != onamelen) {
2267                         bcopy(sdl->sdl_data + onamelen,
2268                             sdl->sdl_data + namelen, sdl->sdl_alen);
2269                 }
2270                 bcopy(new_name, sdl->sdl_data, namelen);
2271                 sdl->sdl_nlen = namelen;
2272                 sdl = (struct sockaddr_dl *)ifa->ifa_netmask;
2273                 bzero(sdl->sdl_data, onamelen);
2274                 while (namelen != 0)
2275                         sdl->sdl_data[--namelen] = 0xff;
2276                 IFA_UNLOCK(ifa);
2277
2278                 EVENTHANDLER_INVOKE(ifnet_arrival_event, ifp);
2279                 /* Announce the return of the interface. */
2280                 rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
2281
2282                 ifp->if_flags &= ~IFF_RENAMING;
2283                 break;
2284
2285 #ifdef VIMAGE
2286         case SIOCSIFVNET:
2287                 error = priv_check(td, PRIV_NET_SETIFVNET);
2288                 if (error)
2289                         return (error);
2290                 error = if_vmove_loan(td, ifp, ifr->ifr_name, ifr->ifr_jid);
2291                 break;
2292 #endif
2293
2294         case SIOCSIFMETRIC:
2295                 error = priv_check(td, PRIV_NET_SETIFMETRIC);
2296                 if (error)
2297                         return (error);
2298                 ifp->if_metric = ifr->ifr_metric;
2299                 getmicrotime(&ifp->if_lastchange);
2300                 break;
2301
2302         case SIOCSIFPHYS:
2303                 error = priv_check(td, PRIV_NET_SETIFPHYS);
2304                 if (error)
2305                         return (error);
2306                 if (ifp->if_ioctl == NULL)
2307                         return (EOPNOTSUPP);
2308                 error = (*ifp->if_ioctl)(ifp, cmd, data);
2309                 if (error == 0)
2310                         getmicrotime(&ifp->if_lastchange);
2311                 break;
2312
2313         case SIOCSIFMTU:
2314         {
2315                 u_long oldmtu = ifp->if_mtu;
2316
2317                 error = priv_check(td, PRIV_NET_SETIFMTU);
2318                 if (error)
2319                         return (error);
2320                 if (ifr->ifr_mtu < IF_MINMTU || ifr->ifr_mtu > IF_MAXMTU)
2321                         return (EINVAL);
2322                 if (ifp->if_ioctl == NULL)
2323                         return (EOPNOTSUPP);
2324                 error = (*ifp->if_ioctl)(ifp, cmd, data);
2325                 if (error == 0) {
2326                         getmicrotime(&ifp->if_lastchange);
2327                         rt_ifmsg(ifp);
2328                 }
2329                 /*
2330                  * If the link MTU changed, do network layer specific procedure.
2331                  */
2332                 if (ifp->if_mtu != oldmtu) {
2333 #ifdef INET6
2334                         nd6_setmtu(ifp);
2335 #endif
2336                 }
2337                 break;
2338         }
2339
2340         case SIOCADDMULTI:
2341         case SIOCDELMULTI:
2342                 if (cmd == SIOCADDMULTI)
2343                         error = priv_check(td, PRIV_NET_ADDMULTI);
2344                 else
2345                         error = priv_check(td, PRIV_NET_DELMULTI);
2346                 if (error)
2347                         return (error);
2348
2349                 /* Don't allow group membership on non-multicast interfaces. */
2350                 if ((ifp->if_flags & IFF_MULTICAST) == 0)
2351                         return (EOPNOTSUPP);
2352
2353                 /* Don't let users screw up protocols' entries. */
2354                 if (ifr->ifr_addr.sa_family != AF_LINK)
2355                         return (EINVAL);
2356
2357                 if (cmd == SIOCADDMULTI) {
2358                         struct ifmultiaddr *ifma;
2359
2360                         /*
2361                          * Userland is only permitted to join groups once
2362                          * via the if_addmulti() KPI, because it cannot hold
2363                          * struct ifmultiaddr * between calls. It may also
2364                          * lose a race while we check if the membership
2365                          * already exists.
2366                          */
2367                         IF_ADDR_LOCK(ifp);
2368                         ifma = if_findmulti(ifp, &ifr->ifr_addr);
2369                         IF_ADDR_UNLOCK(ifp);
2370                         if (ifma != NULL)
2371                                 error = EADDRINUSE;
2372                         else
2373                                 error = if_addmulti(ifp, &ifr->ifr_addr, &ifma);
2374                 } else {
2375                         error = if_delmulti(ifp, &ifr->ifr_addr);
2376                 }
2377                 if (error == 0)
2378                         getmicrotime(&ifp->if_lastchange);
2379                 break;
2380
2381         case SIOCSIFPHYADDR:
2382         case SIOCDIFPHYADDR:
2383 #ifdef INET6
2384         case SIOCSIFPHYADDR_IN6:
2385 #endif
2386         case SIOCSLIFPHYADDR:
2387         case SIOCSIFMEDIA:
2388         case SIOCSIFGENERIC:
2389                 error = priv_check(td, PRIV_NET_HWIOCTL);
2390                 if (error)
2391                         return (error);
2392                 if (ifp->if_ioctl == NULL)
2393                         return (EOPNOTSUPP);
2394                 error = (*ifp->if_ioctl)(ifp, cmd, data);
2395                 if (error == 0)
2396                         getmicrotime(&ifp->if_lastchange);
2397                 break;
2398
2399         case SIOCGIFSTATUS:
2400                 ifs = (struct ifstat *)data;
2401                 ifs->ascii[0] = '\0';
2402
2403         case SIOCGIFPSRCADDR:
2404         case SIOCGIFPDSTADDR:
2405         case SIOCGLIFPHYADDR:
2406         case SIOCGIFMEDIA:
2407         case SIOCGIFGENERIC:
2408                 if (ifp->if_ioctl == NULL)
2409                         return (EOPNOTSUPP);
2410                 error = (*ifp->if_ioctl)(ifp, cmd, data);
2411                 break;
2412
2413         case SIOCSIFLLADDR:
2414                 error = priv_check(td, PRIV_NET_SETLLADDR);
2415                 if (error)
2416                         return (error);
2417                 error = if_setlladdr(ifp,
2418                     ifr->ifr_addr.sa_data, ifr->ifr_addr.sa_len);
2419                 EVENTHANDLER_INVOKE(iflladdr_event, ifp);
2420                 break;
2421
2422         case SIOCAIFGROUP:
2423         {
2424                 struct ifgroupreq *ifgr = (struct ifgroupreq *)ifr;
2425
2426                 error = priv_check(td, PRIV_NET_ADDIFGROUP);
2427                 if (error)
2428                         return (error);
2429                 if ((error = if_addgroup(ifp, ifgr->ifgr_group)))
2430                         return (error);
2431                 break;
2432         }
2433
2434         case SIOCGIFGROUP:
2435                 if ((error = if_getgroup((struct ifgroupreq *)ifr, ifp)))
2436                         return (error);
2437                 break;
2438
2439         case SIOCDIFGROUP:
2440         {
2441                 struct ifgroupreq *ifgr = (struct ifgroupreq *)ifr;
2442
2443                 error = priv_check(td, PRIV_NET_DELIFGROUP);
2444                 if (error)
2445                         return (error);
2446                 if ((error = if_delgroup(ifp, ifgr->ifgr_group)))
2447                         return (error);
2448                 break;
2449         }
2450
2451         default:
2452                 error = ENOIOCTL;
2453                 break;
2454         }
2455         return (error);
2456 }
2457
2458 /*
2459  * Interface ioctls.
2460  */
2461 int
2462 ifioctl(struct socket *so, u_long cmd, caddr_t data, struct thread *td)
2463 {
2464         struct ifnet *ifp;
2465         struct ifreq *ifr;
2466         int error;
2467         int oif_flags;
2468
2469         switch (cmd) {
2470         case SIOCGIFCONF:
2471         case OSIOCGIFCONF:
2472 #ifdef __amd64__
2473         case SIOCGIFCONF32:
2474 #endif
2475                 return (ifconf(cmd, data));
2476         }
2477         ifr = (struct ifreq *)data;
2478
2479         switch (cmd) {
2480 #ifdef VIMAGE
2481         case SIOCSIFRVNET:
2482                 error = priv_check(td, PRIV_NET_SETIFVNET);
2483                 if (error)
2484                         return (error);
2485                 return (if_vmove_reclaim(td, ifr->ifr_name, ifr->ifr_jid));
2486 #endif
2487         case SIOCIFCREATE:
2488         case SIOCIFCREATE2:
2489                 error = priv_check(td, PRIV_NET_IFCREATE);
2490                 if (error)
2491                         return (error);
2492                 return (if_clone_create(ifr->ifr_name, sizeof(ifr->ifr_name),
2493                         cmd == SIOCIFCREATE2 ? ifr->ifr_data : NULL));
2494         case SIOCIFDESTROY:
2495                 error = priv_check(td, PRIV_NET_IFDESTROY);
2496                 if (error)
2497                         return (error);
2498                 return if_clone_destroy(ifr->ifr_name);
2499
2500         case SIOCIFGCLONERS:
2501                 return (if_clone_list((struct if_clonereq *)data));
2502         case SIOCGIFGMEMB:
2503                 return (if_getgroupmembers((struct ifgroupreq *)data));
2504         }
2505
2506         ifp = ifunit_ref(ifr->ifr_name);
2507         if (ifp == NULL)
2508                 return (ENXIO);
2509
2510         error = ifhwioctl(cmd, ifp, data, td);
2511         if (error != ENOIOCTL) {
2512                 if_rele(ifp);
2513                 return (error);
2514         }
2515
2516         oif_flags = ifp->if_flags;
2517         if (so->so_proto == NULL) {
2518                 if_rele(ifp);
2519                 return (EOPNOTSUPP);
2520         }
2521 #ifndef COMPAT_43
2522         error = ((*so->so_proto->pr_usrreqs->pru_control)(so, cmd,
2523                                                                  data,
2524                                                                  ifp, td));
2525         if (error == EOPNOTSUPP && ifp != NULL && ifp->if_ioctl != NULL)
2526                 error = (*ifp->if_ioctl)(ifp, cmd, data);
2527 #else
2528         {
2529                 u_long ocmd = cmd;
2530
2531                 switch (cmd) {
2532
2533                 case SIOCSIFDSTADDR:
2534                 case SIOCSIFADDR:
2535                 case SIOCSIFBRDADDR:
2536                 case SIOCSIFNETMASK:
2537 #if BYTE_ORDER != BIG_ENDIAN
2538                         if (ifr->ifr_addr.sa_family == 0 &&
2539                             ifr->ifr_addr.sa_len < 16) {
2540                                 ifr->ifr_addr.sa_family = ifr->ifr_addr.sa_len;
2541                                 ifr->ifr_addr.sa_len = 16;
2542                         }
2543 #else
2544                         if (ifr->ifr_addr.sa_len == 0)
2545                                 ifr->ifr_addr.sa_len = 16;
2546 #endif
2547                         break;
2548
2549                 case OSIOCGIFADDR:
2550                         cmd = SIOCGIFADDR;
2551                         break;
2552
2553                 case OSIOCGIFDSTADDR:
2554                         cmd = SIOCGIFDSTADDR;
2555                         break;
2556
2557                 case OSIOCGIFBRDADDR:
2558                         cmd = SIOCGIFBRDADDR;
2559                         break;
2560
2561                 case OSIOCGIFNETMASK:
2562                         cmd = SIOCGIFNETMASK;
2563                 }
2564                 error =  ((*so->so_proto->pr_usrreqs->pru_control)(so,
2565                                                                    cmd,
2566                                                                    data,
2567                                                                    ifp, td));
2568                 if (error == EOPNOTSUPP && ifp != NULL &&
2569                     ifp->if_ioctl != NULL)
2570                         error = (*ifp->if_ioctl)(ifp, cmd, data);
2571                 switch (ocmd) {
2572
2573                 case OSIOCGIFADDR:
2574                 case OSIOCGIFDSTADDR:
2575                 case OSIOCGIFBRDADDR:
2576                 case OSIOCGIFNETMASK:
2577                         *(u_short *)&ifr->ifr_addr = ifr->ifr_addr.sa_family;
2578
2579                 }
2580         }
2581 #endif /* COMPAT_43 */
2582
2583         if ((oif_flags ^ ifp->if_flags) & IFF_UP) {
2584 #ifdef INET6
2585                 if (ifp->if_flags & IFF_UP) {
2586                         int s = splimp();
2587                         in6_if_up(ifp);
2588                         splx(s);
2589                 }
2590 #endif
2591         }
2592         if_rele(ifp);
2593         return (error);
2594 }
2595
2596 /*
2597  * The code common to handling reference counted flags,
2598  * e.g., in ifpromisc() and if_allmulti().
2599  * The "pflag" argument can specify a permanent mode flag to check,
2600  * such as IFF_PPROMISC for promiscuous mode; should be 0 if none.
2601  *
2602  * Only to be used on stack-owned flags, not driver-owned flags.
2603  */
2604 static int
2605 if_setflag(struct ifnet *ifp, int flag, int pflag, int *refcount, int onswitch)
2606 {
2607         struct ifreq ifr;
2608         int error;
2609         int oldflags, oldcount;
2610
2611         /* Sanity checks to catch programming errors */
2612         KASSERT((flag & (IFF_DRV_OACTIVE|IFF_DRV_RUNNING)) == 0,
2613             ("%s: setting driver-owned flag %d", __func__, flag));
2614
2615         if (onswitch)
2616                 KASSERT(*refcount >= 0,
2617                     ("%s: increment negative refcount %d for flag %d",
2618                     __func__, *refcount, flag));
2619         else
2620                 KASSERT(*refcount > 0,
2621                     ("%s: decrement non-positive refcount %d for flag %d",
2622                     __func__, *refcount, flag));
2623
2624         /* In case this mode is permanent, just touch refcount */
2625         if (ifp->if_flags & pflag) {
2626                 *refcount += onswitch ? 1 : -1;
2627                 return (0);
2628         }
2629
2630         /* Save ifnet parameters for if_ioctl() may fail */
2631         oldcount = *refcount;
2632         oldflags = ifp->if_flags;
2633         
2634         /*
2635          * See if we aren't the only and touching refcount is enough.
2636          * Actually toggle interface flag if we are the first or last.
2637          */
2638         if (onswitch) {
2639                 if ((*refcount)++)
2640                         return (0);
2641                 ifp->if_flags |= flag;
2642         } else {
2643                 if (--(*refcount))
2644                         return (0);
2645                 ifp->if_flags &= ~flag;
2646         }
2647
2648         /* Call down the driver since we've changed interface flags */
2649         if (ifp->if_ioctl == NULL) {
2650                 error = EOPNOTSUPP;
2651                 goto recover;
2652         }
2653         ifr.ifr_flags = ifp->if_flags & 0xffff;
2654         ifr.ifr_flagshigh = ifp->if_flags >> 16;
2655         error = (*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
2656         if (error)
2657                 goto recover;
2658         /* Notify userland that interface flags have changed */
2659         rt_ifmsg(ifp);
2660         return (0);
2661
2662 recover:
2663         /* Recover after driver error */
2664         *refcount = oldcount;
2665         ifp->if_flags = oldflags;
2666         return (error);
2667 }
2668
2669 /*
2670  * Set/clear promiscuous mode on interface ifp based on the truth value
2671  * of pswitch.  The calls are reference counted so that only the first
2672  * "on" request actually has an effect, as does the final "off" request.
2673  * Results are undefined if the "off" and "on" requests are not matched.
2674  */
2675 int
2676 ifpromisc(struct ifnet *ifp, int pswitch)
2677 {
2678         int error;
2679         int oldflags = ifp->if_flags;
2680
2681         error = if_setflag(ifp, IFF_PROMISC, IFF_PPROMISC,
2682                            &ifp->if_pcount, pswitch);
2683         /* If promiscuous mode status has changed, log a message */
2684         if (error == 0 && ((ifp->if_flags ^ oldflags) & IFF_PROMISC))
2685                 log(LOG_INFO, "%s: promiscuous mode %s\n",
2686                     ifp->if_xname,
2687                     (ifp->if_flags & IFF_PROMISC) ? "enabled" : "disabled");
2688         return (error);
2689 }
2690
2691 /*
2692  * Return interface configuration
2693  * of system.  List may be used
2694  * in later ioctl's (above) to get
2695  * other information.
2696  */
2697 /*ARGSUSED*/
2698 static int
2699 ifconf(u_long cmd, caddr_t data)
2700 {
2701         struct ifconf *ifc = (struct ifconf *)data;
2702 #ifdef __amd64__
2703         struct ifconf32 *ifc32 = (struct ifconf32 *)data;
2704         struct ifconf ifc_swab;
2705 #endif
2706         struct ifnet *ifp;
2707         struct ifaddr *ifa;
2708         struct ifreq ifr;
2709         struct sbuf *sb;
2710         int error, full = 0, valid_len, max_len;
2711
2712 #ifdef __amd64__
2713         if (cmd == SIOCGIFCONF32) {
2714                 ifc_swab.ifc_len = ifc32->ifc_len;
2715                 ifc_swab.ifc_buf = (caddr_t)(uintptr_t)ifc32->ifc_buf;
2716                 ifc = &ifc_swab;
2717         }
2718 #endif
2719         /* Limit initial buffer size to MAXPHYS to avoid DoS from userspace. */
2720         max_len = MAXPHYS - 1;
2721
2722         /* Prevent hostile input from being able to crash the system */
2723         if (ifc->ifc_len <= 0)
2724                 return (EINVAL);
2725
2726 again:
2727         if (ifc->ifc_len <= max_len) {
2728                 max_len = ifc->ifc_len;
2729                 full = 1;
2730         }
2731         sb = sbuf_new(NULL, NULL, max_len + 1, SBUF_FIXEDLEN);
2732         max_len = 0;
2733         valid_len = 0;
2734
2735         IFNET_RLOCK();
2736         TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2737                 int addrs;
2738
2739                 /*
2740                  * Zero the ifr_name buffer to make sure we don't
2741                  * disclose the contents of the stack.
2742                  */
2743                 memset(ifr.ifr_name, 0, sizeof(ifr.ifr_name));
2744
2745                 if (strlcpy(ifr.ifr_name, ifp->if_xname, sizeof(ifr.ifr_name))
2746                     >= sizeof(ifr.ifr_name)) {
2747                         sbuf_delete(sb);
2748                         IFNET_RUNLOCK();
2749                         return (ENAMETOOLONG);
2750                 }
2751
2752                 addrs = 0;
2753                 IF_ADDR_LOCK(ifp);
2754                 TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
2755                         struct sockaddr *sa = ifa->ifa_addr;
2756
2757                         if (prison_if(curthread->td_ucred, sa) != 0)
2758                                 continue;
2759                         addrs++;
2760 #ifdef COMPAT_43
2761                         if (cmd == OSIOCGIFCONF) {
2762                                 struct osockaddr *osa =
2763                                          (struct osockaddr *)&ifr.ifr_addr;
2764                                 ifr.ifr_addr = *sa;
2765                                 osa->sa_family = sa->sa_family;
2766                                 sbuf_bcat(sb, &ifr, sizeof(ifr));
2767                                 max_len += sizeof(ifr);
2768                         } else
2769 #endif
2770                         if (sa->sa_len <= sizeof(*sa)) {
2771                                 ifr.ifr_addr = *sa;
2772                                 sbuf_bcat(sb, &ifr, sizeof(ifr));
2773                                 max_len += sizeof(ifr);
2774                         } else {
2775                                 sbuf_bcat(sb, &ifr,
2776                                     offsetof(struct ifreq, ifr_addr));
2777                                 max_len += offsetof(struct ifreq, ifr_addr);
2778                                 sbuf_bcat(sb, sa, sa->sa_len);
2779                                 max_len += sa->sa_len;
2780                         }
2781
2782                         if (!sbuf_overflowed(sb))
2783                                 valid_len = sbuf_len(sb);
2784                 }
2785                 IF_ADDR_UNLOCK(ifp);
2786                 if (addrs == 0) {
2787                         bzero((caddr_t)&ifr.ifr_addr, sizeof(ifr.ifr_addr));
2788                         sbuf_bcat(sb, &ifr, sizeof(ifr));
2789                         max_len += sizeof(ifr);
2790
2791                         if (!sbuf_overflowed(sb))
2792                                 valid_len = sbuf_len(sb);
2793                 }
2794         }
2795         IFNET_RUNLOCK();
2796
2797         /*
2798          * If we didn't allocate enough space (uncommon), try again.  If
2799          * we have already allocated as much space as we are allowed,
2800          * return what we've got.
2801          */
2802         if (valid_len != max_len && !full) {
2803                 sbuf_delete(sb);
2804                 goto again;
2805         }
2806
2807         ifc->ifc_len = valid_len;
2808 #ifdef __amd64__
2809         if (cmd == SIOCGIFCONF32)
2810                 ifc32->ifc_len = valid_len;
2811 #endif
2812         sbuf_finish(sb);
2813         error = copyout(sbuf_data(sb), ifc->ifc_req, ifc->ifc_len);
2814         sbuf_delete(sb);
2815         return (error);
2816 }
2817
2818 /*
2819  * Just like ifpromisc(), but for all-multicast-reception mode.
2820  */
2821 int
2822 if_allmulti(struct ifnet *ifp, int onswitch)
2823 {
2824
2825         return (if_setflag(ifp, IFF_ALLMULTI, 0, &ifp->if_amcount, onswitch));
2826 }
2827
2828 struct ifmultiaddr *
2829 if_findmulti(struct ifnet *ifp, struct sockaddr *sa)
2830 {
2831         struct ifmultiaddr *ifma;
2832
2833         IF_ADDR_LOCK_ASSERT(ifp);
2834
2835         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2836                 if (sa->sa_family == AF_LINK) {
2837                         if (sa_dl_equal(ifma->ifma_addr, sa))
2838                                 break;
2839                 } else {
2840                         if (sa_equal(ifma->ifma_addr, sa))
2841                                 break;
2842                 }
2843         }
2844
2845         return ifma;
2846 }
2847
2848 /*
2849  * Allocate a new ifmultiaddr and initialize based on passed arguments.  We
2850  * make copies of passed sockaddrs.  The ifmultiaddr will not be added to
2851  * the ifnet multicast address list here, so the caller must do that and
2852  * other setup work (such as notifying the device driver).  The reference
2853  * count is initialized to 1.
2854  */
2855 static struct ifmultiaddr *
2856 if_allocmulti(struct ifnet *ifp, struct sockaddr *sa, struct sockaddr *llsa,
2857     int mflags)
2858 {
2859         struct ifmultiaddr *ifma;
2860         struct sockaddr *dupsa;
2861
2862         ifma = malloc(sizeof *ifma, M_IFMADDR, mflags |
2863             M_ZERO);
2864         if (ifma == NULL)
2865                 return (NULL);
2866
2867         dupsa = malloc(sa->sa_len, M_IFMADDR, mflags);
2868         if (dupsa == NULL) {
2869                 free(ifma, M_IFMADDR);
2870                 return (NULL);
2871         }
2872         bcopy(sa, dupsa, sa->sa_len);
2873         ifma->ifma_addr = dupsa;
2874
2875         ifma->ifma_ifp = ifp;
2876         ifma->ifma_refcount = 1;
2877         ifma->ifma_protospec = NULL;
2878
2879         if (llsa == NULL) {
2880                 ifma->ifma_lladdr = NULL;
2881                 return (ifma);
2882         }
2883
2884         dupsa = malloc(llsa->sa_len, M_IFMADDR, mflags);
2885         if (dupsa == NULL) {
2886                 free(ifma->ifma_addr, M_IFMADDR);
2887                 free(ifma, M_IFMADDR);
2888                 return (NULL);
2889         }
2890         bcopy(llsa, dupsa, llsa->sa_len);
2891         ifma->ifma_lladdr = dupsa;
2892
2893         return (ifma);
2894 }
2895
2896 /*
2897  * if_freemulti: free ifmultiaddr structure and possibly attached related
2898  * addresses.  The caller is responsible for implementing reference
2899  * counting, notifying the driver, handling routing messages, and releasing
2900  * any dependent link layer state.
2901  */
2902 static void
2903 if_freemulti(struct ifmultiaddr *ifma)
2904 {
2905
2906         KASSERT(ifma->ifma_refcount == 0, ("if_freemulti: refcount %d",
2907             ifma->ifma_refcount));
2908         KASSERT(ifma->ifma_protospec == NULL,
2909             ("if_freemulti: protospec not NULL"));
2910
2911         if (ifma->ifma_lladdr != NULL)
2912                 free(ifma->ifma_lladdr, M_IFMADDR);
2913         free(ifma->ifma_addr, M_IFMADDR);
2914         free(ifma, M_IFMADDR);
2915 }
2916
2917 /*
2918  * Register an additional multicast address with a network interface.
2919  *
2920  * - If the address is already present, bump the reference count on the
2921  *   address and return.
2922  * - If the address is not link-layer, look up a link layer address.
2923  * - Allocate address structures for one or both addresses, and attach to the
2924  *   multicast address list on the interface.  If automatically adding a link
2925  *   layer address, the protocol address will own a reference to the link
2926  *   layer address, to be freed when it is freed.
2927  * - Notify the network device driver of an addition to the multicast address
2928  *   list.
2929  *
2930  * 'sa' points to caller-owned memory with the desired multicast address.
2931  *
2932  * 'retifma' will be used to return a pointer to the resulting multicast
2933  * address reference, if desired.
2934  */
2935 int
2936 if_addmulti(struct ifnet *ifp, struct sockaddr *sa,
2937     struct ifmultiaddr **retifma)
2938 {
2939         struct ifmultiaddr *ifma, *ll_ifma;
2940         struct sockaddr *llsa;
2941         int error;
2942
2943         /*
2944          * If the address is already present, return a new reference to it;
2945          * otherwise, allocate storage and set up a new address.
2946          */
2947         IF_ADDR_LOCK(ifp);
2948         ifma = if_findmulti(ifp, sa);
2949         if (ifma != NULL) {
2950                 ifma->ifma_refcount++;
2951                 if (retifma != NULL)
2952                         *retifma = ifma;
2953                 IF_ADDR_UNLOCK(ifp);
2954                 return (0);
2955         }
2956
2957         /*
2958          * The address isn't already present; resolve the protocol address
2959          * into a link layer address, and then look that up, bump its
2960          * refcount or allocate an ifma for that also.  If 'llsa' was
2961          * returned, we will need to free it later.
2962          */
2963         llsa = NULL;
2964         ll_ifma = NULL;
2965         if (ifp->if_resolvemulti != NULL) {
2966                 error = ifp->if_resolvemulti(ifp, &llsa, sa);
2967                 if (error)
2968                         goto unlock_out;
2969         }
2970
2971         /*
2972          * Allocate the new address.  Don't hook it up yet, as we may also
2973          * need to allocate a link layer multicast address.
2974          */
2975         ifma = if_allocmulti(ifp, sa, llsa, M_NOWAIT);
2976         if (ifma == NULL) {
2977                 error = ENOMEM;
2978                 goto free_llsa_out;
2979         }
2980
2981         /*
2982          * If a link layer address is found, we'll need to see if it's
2983          * already present in the address list, or allocate is as well.
2984          * When this block finishes, the link layer address will be on the
2985          * list.
2986          */
2987         if (llsa != NULL) {
2988                 ll_ifma = if_findmulti(ifp, llsa);
2989                 if (ll_ifma == NULL) {
2990                         ll_ifma = if_allocmulti(ifp, llsa, NULL, M_NOWAIT);
2991                         if (ll_ifma == NULL) {
2992                                 --ifma->ifma_refcount;
2993                                 if_freemulti(ifma);
2994                                 error = ENOMEM;
2995                                 goto free_llsa_out;
2996                         }
2997                         TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ll_ifma,
2998                             ifma_link);
2999                 } else
3000                         ll_ifma->ifma_refcount++;
3001                 ifma->ifma_llifma = ll_ifma;
3002         }
3003
3004         /*
3005          * We now have a new multicast address, ifma, and possibly a new or
3006          * referenced link layer address.  Add the primary address to the
3007          * ifnet address list.
3008          */
3009         TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ifma, ifma_link);
3010
3011         if (retifma != NULL)
3012                 *retifma = ifma;
3013
3014         /*
3015          * Must generate the message while holding the lock so that 'ifma'
3016          * pointer is still valid.
3017          */
3018         rt_newmaddrmsg(RTM_NEWMADDR, ifma);
3019         IF_ADDR_UNLOCK(ifp);
3020
3021         /*
3022          * We are certain we have added something, so call down to the
3023          * interface to let them know about it.
3024          */
3025         if (ifp->if_ioctl != NULL) {
3026                 (void) (*ifp->if_ioctl)(ifp, SIOCADDMULTI, 0);
3027         }
3028
3029         if (llsa != NULL)
3030                 free(llsa, M_IFMADDR);
3031
3032         return (0);
3033
3034 free_llsa_out:
3035         if (llsa != NULL)
3036                 free(llsa, M_IFMADDR);
3037
3038 unlock_out:
3039         IF_ADDR_UNLOCK(ifp);
3040         return (error);
3041 }
3042
3043 /*
3044  * Delete a multicast group membership by network-layer group address.
3045  *
3046  * Returns ENOENT if the entry could not be found. If ifp no longer
3047  * exists, results are undefined. This entry point should only be used
3048  * from subsystems which do appropriate locking to hold ifp for the
3049  * duration of the call.
3050  * Network-layer protocol domains must use if_delmulti_ifma().
3051  */
3052 int
3053 if_delmulti(struct ifnet *ifp, struct sockaddr *sa)
3054 {
3055         struct ifmultiaddr *ifma;
3056         int lastref;
3057 #ifdef INVARIANTS
3058         struct ifnet *oifp;
3059
3060         IFNET_RLOCK_NOSLEEP();
3061         TAILQ_FOREACH(oifp, &V_ifnet, if_link)
3062                 if (ifp == oifp)
3063                         break;
3064         if (ifp != oifp)
3065                 ifp = NULL;
3066         IFNET_RUNLOCK_NOSLEEP();
3067
3068         KASSERT(ifp != NULL, ("%s: ifnet went away", __func__));
3069 #endif
3070         if (ifp == NULL)
3071                 return (ENOENT);
3072
3073         IF_ADDR_LOCK(ifp);
3074         lastref = 0;
3075         ifma = if_findmulti(ifp, sa);
3076         if (ifma != NULL)
3077                 lastref = if_delmulti_locked(ifp, ifma, 0);
3078         IF_ADDR_UNLOCK(ifp);
3079
3080         if (ifma == NULL)
3081                 return (ENOENT);
3082
3083         if (lastref && ifp->if_ioctl != NULL) {
3084                 (void)(*ifp->if_ioctl)(ifp, SIOCDELMULTI, 0);
3085         }
3086
3087         return (0);
3088 }
3089
3090 /*
3091  * Delete all multicast group membership for an interface.
3092  * Should be used to quickly flush all multicast filters.
3093  */
3094 void
3095 if_delallmulti(struct ifnet *ifp)
3096 {
3097         struct ifmultiaddr *ifma;
3098         struct ifmultiaddr *next;
3099
3100         IF_ADDR_LOCK(ifp);
3101         TAILQ_FOREACH_SAFE(ifma, &ifp->if_multiaddrs, ifma_link, next)
3102                 if_delmulti_locked(ifp, ifma, 0);
3103         IF_ADDR_UNLOCK(ifp);
3104 }
3105
3106 /*
3107  * Delete a multicast group membership by group membership pointer.
3108  * Network-layer protocol domains must use this routine.
3109  *
3110  * It is safe to call this routine if the ifp disappeared.
3111  */
3112 void
3113 if_delmulti_ifma(struct ifmultiaddr *ifma)
3114 {
3115         struct ifnet *ifp;
3116         int lastref;
3117
3118         ifp = ifma->ifma_ifp;
3119 #ifdef DIAGNOSTIC
3120         if (ifp == NULL) {
3121                 printf("%s: ifma_ifp seems to be detached\n", __func__);
3122         } else {
3123                 struct ifnet *oifp;
3124
3125                 IFNET_RLOCK_NOSLEEP();
3126                 TAILQ_FOREACH(oifp, &V_ifnet, if_link)
3127                         if (ifp == oifp)
3128                                 break;
3129                 if (ifp != oifp) {
3130                         printf("%s: ifnet %p disappeared\n", __func__, ifp);
3131                         ifp = NULL;
3132                 }
3133                 IFNET_RUNLOCK_NOSLEEP();
3134         }
3135 #endif
3136         /*
3137          * If and only if the ifnet instance exists: Acquire the address lock.
3138          */
3139         if (ifp != NULL)
3140                 IF_ADDR_LOCK(ifp);
3141
3142         lastref = if_delmulti_locked(ifp, ifma, 0);
3143
3144         if (ifp != NULL) {
3145                 /*
3146                  * If and only if the ifnet instance exists:
3147                  *  Release the address lock.
3148                  *  If the group was left: update the hardware hash filter.
3149                  */
3150                 IF_ADDR_UNLOCK(ifp);
3151                 if (lastref && ifp->if_ioctl != NULL) {
3152                         (void)(*ifp->if_ioctl)(ifp, SIOCDELMULTI, 0);
3153                 }
3154         }
3155 }
3156
3157 /*
3158  * Perform deletion of network-layer and/or link-layer multicast address.
3159  *
3160  * Return 0 if the reference count was decremented.
3161  * Return 1 if the final reference was released, indicating that the
3162  * hardware hash filter should be reprogrammed.
3163  */
3164 static int
3165 if_delmulti_locked(struct ifnet *ifp, struct ifmultiaddr *ifma, int detaching)
3166 {
3167         struct ifmultiaddr *ll_ifma;
3168
3169         if (ifp != NULL && ifma->ifma_ifp != NULL) {
3170                 KASSERT(ifma->ifma_ifp == ifp,
3171                     ("%s: inconsistent ifp %p", __func__, ifp));
3172                 IF_ADDR_LOCK_ASSERT(ifp);
3173         }
3174
3175         ifp = ifma->ifma_ifp;
3176
3177         /*
3178          * If the ifnet is detaching, null out references to ifnet,
3179          * so that upper protocol layers will notice, and not attempt
3180          * to obtain locks for an ifnet which no longer exists. The
3181          * routing socket announcement must happen before the ifnet
3182          * instance is detached from the system.
3183          */
3184         if (detaching) {
3185 #ifdef DIAGNOSTIC
3186                 printf("%s: detaching ifnet instance %p\n", __func__, ifp);
3187 #endif
3188                 /*
3189                  * ifp may already be nulled out if we are being reentered
3190                  * to delete the ll_ifma.
3191                  */
3192                 if (ifp != NULL) {
3193                         rt_newmaddrmsg(RTM_DELMADDR, ifma);
3194                         ifma->ifma_ifp = NULL;
3195                 }
3196         }
3197
3198         if (--ifma->ifma_refcount > 0)
3199                 return 0;
3200
3201         /*
3202          * If this ifma is a network-layer ifma, a link-layer ifma may
3203          * have been associated with it. Release it first if so.
3204          */
3205         ll_ifma = ifma->ifma_llifma;
3206         if (ll_ifma != NULL) {
3207                 KASSERT(ifma->ifma_lladdr != NULL,
3208                     ("%s: llifma w/o lladdr", __func__));
3209                 if (detaching)
3210                         ll_ifma->ifma_ifp = NULL;       /* XXX */
3211                 if (--ll_ifma->ifma_refcount == 0) {
3212                         if (ifp != NULL) {
3213                                 TAILQ_REMOVE(&ifp->if_multiaddrs, ll_ifma,
3214                                     ifma_link);
3215                         }
3216                         if_freemulti(ll_ifma);
3217                 }
3218         }
3219
3220         if (ifp != NULL)
3221                 TAILQ_REMOVE(&ifp->if_multiaddrs, ifma, ifma_link);
3222
3223         if_freemulti(ifma);
3224
3225         /*
3226          * The last reference to this instance of struct ifmultiaddr
3227          * was released; the hardware should be notified of this change.
3228          */
3229         return 1;
3230 }
3231
3232 /*
3233  * Set the link layer address on an interface.
3234  *
3235  * At this time we only support certain types of interfaces,
3236  * and we don't allow the length of the address to change.
3237  */
3238 int
3239 if_setlladdr(struct ifnet *ifp, const u_char *lladdr, int len)
3240 {
3241         struct sockaddr_dl *sdl;
3242         struct ifaddr *ifa;
3243         struct ifreq ifr;
3244
3245         IF_ADDR_LOCK(ifp);
3246         ifa = ifp->if_addr;
3247         if (ifa == NULL) {
3248                 IF_ADDR_UNLOCK(ifp);
3249                 return (EINVAL);
3250         }
3251         ifa_ref(ifa);
3252         IF_ADDR_UNLOCK(ifp);
3253         sdl = (struct sockaddr_dl *)ifa->ifa_addr;
3254         if (sdl == NULL) {
3255                 ifa_free(ifa);
3256                 return (EINVAL);
3257         }
3258         if (len != sdl->sdl_alen) {     /* don't allow length to change */
3259                 ifa_free(ifa);
3260                 return (EINVAL);
3261         }
3262         switch (ifp->if_type) {
3263         case IFT_ETHER:
3264         case IFT_FDDI:
3265         case IFT_XETHER:
3266         case IFT_ISO88025:
3267         case IFT_L2VLAN:
3268         case IFT_BRIDGE:
3269         case IFT_ARCNET:
3270         case IFT_IEEE8023ADLAG:
3271         case IFT_IEEE80211:
3272                 bcopy(lladdr, LLADDR(sdl), len);
3273                 ifa_free(ifa);
3274                 break;
3275         default:
3276                 ifa_free(ifa);
3277                 return (ENODEV);
3278         }
3279
3280         /*
3281          * If the interface is already up, we need
3282          * to re-init it in order to reprogram its
3283          * address filter.
3284          */
3285         if ((ifp->if_flags & IFF_UP) != 0) {
3286                 if (ifp->if_ioctl) {
3287                         ifp->if_flags &= ~IFF_UP;
3288                         ifr.ifr_flags = ifp->if_flags & 0xffff;
3289                         ifr.ifr_flagshigh = ifp->if_flags >> 16;
3290                         (*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
3291                         ifp->if_flags |= IFF_UP;
3292                         ifr.ifr_flags = ifp->if_flags & 0xffff;
3293                         ifr.ifr_flagshigh = ifp->if_flags >> 16;
3294                         (*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
3295                 }
3296 #ifdef INET
3297                 /*
3298                  * Also send gratuitous ARPs to notify other nodes about
3299                  * the address change.
3300                  */
3301                 TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
3302                         if (ifa->ifa_addr->sa_family == AF_INET)
3303                                 arp_ifinit(ifp, ifa);
3304                 }
3305 #endif
3306         }
3307         return (0);
3308 }
3309
3310 /*
3311  * The name argument must be a pointer to storage which will last as
3312  * long as the interface does.  For physical devices, the result of
3313  * device_get_name(dev) is a good choice and for pseudo-devices a
3314  * static string works well.
3315  */
3316 void
3317 if_initname(struct ifnet *ifp, const char *name, int unit)
3318 {
3319         ifp->if_dname = name;
3320         ifp->if_dunit = unit;
3321         if (unit != IF_DUNIT_NONE)
3322                 snprintf(ifp->if_xname, IFNAMSIZ, "%s%d", name, unit);
3323         else
3324                 strlcpy(ifp->if_xname, name, IFNAMSIZ);
3325 }
3326
3327 int
3328 if_printf(struct ifnet *ifp, const char * fmt, ...)
3329 {
3330         va_list ap;
3331         int retval;
3332
3333         retval = printf("%s: ", ifp->if_xname);
3334         va_start(ap, fmt);
3335         retval += vprintf(fmt, ap);
3336         va_end(ap);
3337         return (retval);
3338 }
3339
3340 void
3341 if_start(struct ifnet *ifp)
3342 {
3343
3344         (*(ifp)->if_start)(ifp);
3345 }
3346
3347 /*
3348  * Backwards compatibility interface for drivers 
3349  * that have not implemented it
3350  */
3351 static int
3352 if_transmit(struct ifnet *ifp, struct mbuf *m)
3353 {
3354         int error;
3355
3356         IFQ_HANDOFF(ifp, m, error);
3357         return (error);
3358 }
3359
3360 int
3361 if_handoff(struct ifqueue *ifq, struct mbuf *m, struct ifnet *ifp, int adjust)
3362 {
3363         int active = 0;
3364
3365         IF_LOCK(ifq);
3366         if (_IF_QFULL(ifq)) {
3367                 _IF_DROP(ifq);
3368                 IF_UNLOCK(ifq);
3369                 m_freem(m);
3370                 return (0);
3371         }
3372         if (ifp != NULL) {
3373                 ifp->if_obytes += m->m_pkthdr.len + adjust;
3374                 if (m->m_flags & (M_BCAST|M_MCAST))
3375                         ifp->if_omcasts++;
3376                 active = ifp->if_drv_flags & IFF_DRV_OACTIVE;
3377         }
3378         _IF_ENQUEUE(ifq, m);
3379         IF_UNLOCK(ifq);
3380         if (ifp != NULL && !active)
3381                 (*(ifp)->if_start)(ifp);
3382         return (1);
3383 }
3384
3385 void
3386 if_register_com_alloc(u_char type,
3387     if_com_alloc_t *a, if_com_free_t *f)
3388 {
3389         
3390         KASSERT(if_com_alloc[type] == NULL,
3391             ("if_register_com_alloc: %d already registered", type));
3392         KASSERT(if_com_free[type] == NULL,
3393             ("if_register_com_alloc: %d free already registered", type));
3394
3395         if_com_alloc[type] = a;
3396         if_com_free[type] = f;
3397 }
3398
3399 void
3400 if_deregister_com_alloc(u_char type)
3401 {
3402         
3403         KASSERT(if_com_alloc[type] != NULL,
3404             ("if_deregister_com_alloc: %d not registered", type));
3405         KASSERT(if_com_free[type] != NULL,
3406             ("if_deregister_com_alloc: %d free not registered", type));
3407         if_com_alloc[type] = NULL;
3408         if_com_free[type] = NULL;
3409 }
3410
3411 #ifdef DDB
3412 static void
3413 if_show_ifnet(struct ifnet *ifp)
3414 {
3415
3416         if (ifp == NULL)
3417                 return;
3418         db_printf("%s:\n", ifp->if_xname);
3419 #define IF_DB_PRINTF(f, e)      db_printf("   %s = " f "\n", #e, ifp->e);
3420         IF_DB_PRINTF("%s", if_dname);
3421         IF_DB_PRINTF("%d", if_dunit);
3422         IF_DB_PRINTF("%s", if_description);
3423         IF_DB_PRINTF("%u", if_index);
3424         IF_DB_PRINTF("%u", if_refcount);
3425         IF_DB_PRINTF("%p", if_softc);
3426         IF_DB_PRINTF("%p", if_l2com);
3427         IF_DB_PRINTF("%p", if_vnet);
3428         IF_DB_PRINTF("%p", if_home_vnet);
3429         IF_DB_PRINTF("%p", if_addr);
3430         IF_DB_PRINTF("%p", if_llsoftc);
3431         IF_DB_PRINTF("%p", if_label);
3432         IF_DB_PRINTF("%u", if_pcount);
3433         IF_DB_PRINTF("0x%08x", if_flags);
3434         IF_DB_PRINTF("0x%08x", if_drv_flags);
3435         IF_DB_PRINTF("0x%08x", if_capabilities);
3436         IF_DB_PRINTF("0x%08x", if_capenable);
3437         IF_DB_PRINTF("%p", if_snd.ifq_head);
3438         IF_DB_PRINTF("%p", if_snd.ifq_tail);
3439         IF_DB_PRINTF("%d", if_snd.ifq_len);
3440         IF_DB_PRINTF("%d", if_snd.ifq_maxlen);
3441         IF_DB_PRINTF("%d", if_snd.ifq_drops);
3442         IF_DB_PRINTF("%p", if_snd.ifq_drv_head);
3443         IF_DB_PRINTF("%p", if_snd.ifq_drv_tail);
3444         IF_DB_PRINTF("%d", if_snd.ifq_drv_len);
3445         IF_DB_PRINTF("%d", if_snd.ifq_drv_maxlen);
3446         IF_DB_PRINTF("%d", if_snd.altq_type);
3447         IF_DB_PRINTF("%x", if_snd.altq_flags);
3448 #undef IF_DB_PRINTF
3449 }
3450
3451 DB_SHOW_COMMAND(ifnet, db_show_ifnet)
3452 {
3453
3454         if (!have_addr) {
3455                 db_printf("usage: show ifnet <struct ifnet *>\n");
3456                 return;
3457         }
3458
3459         if_show_ifnet((struct ifnet *)addr);
3460 }
3461
3462 DB_SHOW_ALL_COMMAND(ifnets, db_show_all_ifnets)
3463 {
3464         VNET_ITERATOR_DECL(vnet_iter);
3465         struct ifnet *ifp;
3466         u_short idx;
3467
3468         VNET_FOREACH(vnet_iter) {
3469                 CURVNET_SET_QUIET(vnet_iter);
3470 #ifdef VIMAGE
3471                 db_printf("vnet=%p\n", curvnet);
3472 #endif
3473                 for (idx = 1; idx <= V_if_index; idx++) {
3474                         ifp = V_ifindex_table[idx].ife_ifnet;
3475                         if (ifp == NULL)
3476                                 continue;
3477                         db_printf( "%20s ifp=%p\n", ifp->if_xname, ifp);
3478                         if (db_pager_quit)
3479                                 break;
3480                 }
3481                 CURVNET_RESTORE();
3482         }
3483 }
3484 #endif