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