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