]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/net/if.c
bridge: epoch-ification
[FreeBSD/FreeBSD.git] / sys / net / if.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1980, 1986, 1993
5  *      The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *      @(#)if.c        8.5 (Berkeley) 1/9/95
32  * $FreeBSD$
33  */
34
35 #include "opt_bpf.h"
36 #include "opt_inet6.h"
37 #include "opt_inet.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/epoch.h>
46 #include <sys/mbuf.h>
47 #include <sys/systm.h>
48 #include <sys/priv.h>
49 #include <sys/proc.h>
50 #include <sys/socket.h>
51 #include <sys/socketvar.h>
52 #include <sys/protosw.h>
53 #include <sys/kernel.h>
54 #include <sys/lock.h>
55 #include <sys/refcount.h>
56 #include <sys/module.h>
57 #include <sys/rwlock.h>
58 #include <sys/sockio.h>
59 #include <sys/syslog.h>
60 #include <sys/sysctl.h>
61 #include <sys/sysent.h>
62 #include <sys/taskqueue.h>
63 #include <sys/domain.h>
64 #include <sys/jail.h>
65 #include <sys/priv.h>
66 #include <sys/sched.h>
67 #include <sys/smp.h>
68
69 #include <machine/stdarg.h>
70 #include <vm/uma.h>
71
72 #include <net/bpf.h>
73 #include <net/ethernet.h>
74 #include <net/if.h>
75 #include <net/if_arp.h>
76 #include <net/if_clone.h>
77 #include <net/if_dl.h>
78 #include <net/if_types.h>
79 #include <net/if_var.h>
80 #include <net/if_media.h>
81 #include <net/if_vlan_var.h>
82 #include <net/radix.h>
83 #include <net/route.h>
84 #include <net/vnet.h>
85
86 #if defined(INET) || defined(INET6)
87 #include <net/ethernet.h>
88 #include <netinet/in.h>
89 #include <netinet/in_var.h>
90 #include <netinet/ip.h>
91 #include <netinet/ip_carp.h>
92 #ifdef INET
93 #include <netinet/if_ether.h>
94 #include <netinet/netdump/netdump.h>
95 #endif /* INET */
96 #ifdef INET6
97 #include <netinet6/in6_var.h>
98 #include <netinet6/in6_ifattach.h>
99 #endif /* INET6 */
100 #endif /* INET || INET6 */
101
102 #include <security/mac/mac_framework.h>
103
104 /*
105  * Consumers of struct ifreq such as tcpdump assume no pad between ifr_name
106  * and ifr_ifru when it is used in SIOCGIFCONF.
107  */
108 _Static_assert(sizeof(((struct ifreq *)0)->ifr_name) ==
109     offsetof(struct ifreq, ifr_ifru), "gap between ifr_name and ifr_ifru");
110
111 __read_mostly epoch_t net_epoch_preempt;
112 __read_mostly epoch_t net_epoch;
113 #ifdef COMPAT_FREEBSD32
114 #include <sys/mount.h>
115 #include <compat/freebsd32/freebsd32.h>
116
117 struct ifreq_buffer32 {
118         uint32_t        length;         /* (size_t) */
119         uint32_t        buffer;         /* (void *) */
120 };
121
122 /*
123  * Interface request structure used for socket
124  * ioctl's.  All interface ioctl's must have parameter
125  * definitions which begin with ifr_name.  The
126  * remainder may be interface specific.
127  */
128 struct ifreq32 {
129         char    ifr_name[IFNAMSIZ];             /* if name, e.g. "en0" */
130         union {
131                 struct sockaddr ifru_addr;
132                 struct sockaddr ifru_dstaddr;
133                 struct sockaddr ifru_broadaddr;
134                 struct ifreq_buffer32 ifru_buffer;
135                 short           ifru_flags[2];
136                 short           ifru_index;
137                 int             ifru_jid;
138                 int             ifru_metric;
139                 int             ifru_mtu;
140                 int             ifru_phys;
141                 int             ifru_media;
142                 uint32_t        ifru_data;
143                 int             ifru_cap[2];
144                 u_int           ifru_fib;
145                 u_char          ifru_vlan_pcp;
146         } ifr_ifru;
147 };
148 CTASSERT(sizeof(struct ifreq) == sizeof(struct ifreq32));
149 CTASSERT(__offsetof(struct ifreq, ifr_ifru) ==
150     __offsetof(struct ifreq32, ifr_ifru));
151
152 struct ifgroupreq32 {
153         char    ifgr_name[IFNAMSIZ];
154         u_int   ifgr_len;
155         union {
156                 char            ifgru_group[IFNAMSIZ];
157                 uint32_t        ifgru_groups;
158         } ifgr_ifgru;
159 };
160
161 struct ifmediareq32 {
162         char            ifm_name[IFNAMSIZ];
163         int             ifm_current;
164         int             ifm_mask;
165         int             ifm_status;
166         int             ifm_active;
167         int             ifm_count;
168         uint32_t        ifm_ulist;      /* (int *) */
169 };
170 #define SIOCGIFMEDIA32  _IOC_NEWTYPE(SIOCGIFMEDIA, struct ifmediareq32)
171 #define SIOCGIFXMEDIA32 _IOC_NEWTYPE(SIOCGIFXMEDIA, struct ifmediareq32)
172
173 #define _CASE_IOC_IFGROUPREQ_32(cmd)                            \
174     _IOC_NEWTYPE((cmd), struct ifgroupreq32): case
175 #else /* !COMPAT_FREEBSD32 */
176 #define _CASE_IOC_IFGROUPREQ_32(cmd)
177 #endif /* !COMPAT_FREEBSD32 */
178
179 #define CASE_IOC_IFGROUPREQ(cmd)        \
180     _CASE_IOC_IFGROUPREQ_32(cmd)        \
181     (cmd)
182
183 union ifreq_union {
184         struct ifreq    ifr;
185 #ifdef COMPAT_FREEBSD32
186         struct ifreq32  ifr32;
187 #endif
188 };
189
190 union ifgroupreq_union {
191         struct ifgroupreq ifgr;
192 #ifdef COMPAT_FREEBSD32
193         struct ifgroupreq32 ifgr32;
194 #endif
195 };
196
197 SYSCTL_NODE(_net, PF_LINK, link, CTLFLAG_RW, 0, "Link layers");
198 SYSCTL_NODE(_net_link, 0, generic, CTLFLAG_RW, 0, "Generic link-management");
199
200 SYSCTL_INT(_net_link, OID_AUTO, ifqmaxlen, CTLFLAG_RDTUN,
201     &ifqmaxlen, 0, "max send queue size");
202
203 /* Log link state change events */
204 static int log_link_state_change = 1;
205
206 SYSCTL_INT(_net_link, OID_AUTO, log_link_state_change, CTLFLAG_RW,
207         &log_link_state_change, 0,
208         "log interface link state change events");
209
210 /* Log promiscuous mode change events */
211 static int log_promisc_mode_change = 1;
212
213 SYSCTL_INT(_net_link, OID_AUTO, log_promisc_mode_change, CTLFLAG_RDTUN,
214         &log_promisc_mode_change, 1,
215         "log promiscuous mode change events");
216
217 /* Interface description */
218 static unsigned int ifdescr_maxlen = 1024;
219 SYSCTL_UINT(_net, OID_AUTO, ifdescr_maxlen, CTLFLAG_RW,
220         &ifdescr_maxlen, 0,
221         "administrative maximum length for interface description");
222
223 static MALLOC_DEFINE(M_IFDESCR, "ifdescr", "ifnet descriptions");
224
225 /* global sx for non-critical path ifdescr */
226 static struct sx ifdescr_sx;
227 SX_SYSINIT(ifdescr_sx, &ifdescr_sx, "ifnet descr");
228
229 void    (*ng_ether_link_state_p)(struct ifnet *ifp, int state);
230 void    (*lagg_linkstate_p)(struct ifnet *ifp, int state);
231 /* These are external hooks for CARP. */
232 void    (*carp_linkstate_p)(struct ifnet *ifp);
233 void    (*carp_demote_adj_p)(int, char *);
234 int     (*carp_master_p)(struct ifaddr *);
235 #if defined(INET) || defined(INET6)
236 int     (*carp_forus_p)(struct ifnet *ifp, u_char *dhost);
237 int     (*carp_output_p)(struct ifnet *ifp, struct mbuf *m,
238     const struct sockaddr *sa);
239 int     (*carp_ioctl_p)(struct ifreq *, u_long, struct thread *);   
240 int     (*carp_attach_p)(struct ifaddr *, int);
241 void    (*carp_detach_p)(struct ifaddr *, bool);
242 #endif
243 #ifdef INET
244 int     (*carp_iamatch_p)(struct ifaddr *, uint8_t **);
245 #endif
246 #ifdef INET6
247 struct ifaddr *(*carp_iamatch6_p)(struct ifnet *ifp, struct in6_addr *taddr6);
248 caddr_t (*carp_macmatch6_p)(struct ifnet *ifp, struct mbuf *m,
249     const struct in6_addr *taddr);
250 #endif
251
252 struct mbuf *(*tbr_dequeue_ptr)(struct ifaltq *, int) = NULL;
253
254 /*
255  * XXX: Style; these should be sorted alphabetically, and unprototyped
256  * static functions should be prototyped. Currently they are sorted by
257  * declaration order.
258  */
259 static void     if_attachdomain(void *);
260 static void     if_attachdomain1(struct ifnet *);
261 static int      ifconf(u_long, caddr_t);
262 static void     *if_grow(void);
263 static void     if_input_default(struct ifnet *, struct mbuf *);
264 static int      if_requestencap_default(struct ifnet *, struct if_encap_req *);
265 static void     if_route(struct ifnet *, int flag, int fam);
266 static int      if_setflag(struct ifnet *, int, int, int *, int);
267 static int      if_transmit(struct ifnet *ifp, struct mbuf *m);
268 static void     if_unroute(struct ifnet *, int flag, int fam);
269 static void     link_rtrequest(int, struct rtentry *, struct rt_addrinfo *);
270 static int      if_delmulti_locked(struct ifnet *, struct ifmultiaddr *, int);
271 static void     do_link_state_change(void *, int);
272 static int      if_getgroup(struct ifgroupreq *, struct ifnet *);
273 static int      if_getgroupmembers(struct ifgroupreq *);
274 static void     if_delgroups(struct ifnet *);
275 static void     if_attach_internal(struct ifnet *, int, struct if_clone *);
276 static int      if_detach_internal(struct ifnet *, int, struct if_clone **);
277 #ifdef VIMAGE
278 static void     if_vmove(struct ifnet *, struct vnet *);
279 #endif
280
281 #ifdef INET6
282 /*
283  * XXX: declare here to avoid to include many inet6 related files..
284  * should be more generalized?
285  */
286 extern void     nd6_setmtu(struct ifnet *);
287 #endif
288
289 /* ipsec helper hooks */
290 VNET_DEFINE(struct hhook_head *, ipsec_hhh_in[HHOOK_IPSEC_COUNT]);
291 VNET_DEFINE(struct hhook_head *, ipsec_hhh_out[HHOOK_IPSEC_COUNT]);
292
293 VNET_DEFINE(int, if_index);
294 int     ifqmaxlen = IFQ_MAXLEN;
295 VNET_DEFINE(struct ifnethead, ifnet);   /* depend on static init XXX */
296 VNET_DEFINE(struct ifgrouphead, ifg_head);
297
298 VNET_DEFINE_STATIC(int, if_indexlim) = 8;
299
300 /* Table of ifnet by index. */
301 VNET_DEFINE(struct ifnet **, ifindex_table);
302
303 #define V_if_indexlim           VNET(if_indexlim)
304 #define V_ifindex_table         VNET(ifindex_table)
305
306 /*
307  * The global network interface list (V_ifnet) and related state (such as
308  * if_index, if_indexlim, and ifindex_table) are protected by an sxlock and
309  * an rwlock.  Either may be acquired shared to stablize the list, but both
310  * must be acquired writable to modify the list.  This model allows us to
311  * both stablize the interface list during interrupt thread processing, but
312  * also to stablize it over long-running ioctls, without introducing priority
313  * inversions and deadlocks.
314  */
315 struct rwlock ifnet_rwlock;
316 RW_SYSINIT_FLAGS(ifnet_rw, &ifnet_rwlock, "ifnet_rw", RW_RECURSE);
317 struct sx ifnet_sxlock;
318 SX_SYSINIT_FLAGS(ifnet_sx, &ifnet_sxlock, "ifnet_sx", SX_RECURSE);
319
320 /*
321  * The allocation of network interfaces is a rather non-atomic affair; we
322  * need to select an index before we are ready to expose the interface for
323  * use, so will use this pointer value to indicate reservation.
324  */
325 #define IFNET_HOLD      (void *)(uintptr_t)(-1)
326
327 static  if_com_alloc_t *if_com_alloc[256];
328 static  if_com_free_t *if_com_free[256];
329
330 static MALLOC_DEFINE(M_IFNET, "ifnet", "interface internals");
331 MALLOC_DEFINE(M_IFADDR, "ifaddr", "interface address");
332 MALLOC_DEFINE(M_IFMADDR, "ether_multi", "link-level multicast address");
333
334 struct ifnet *
335 ifnet_byindex_locked(u_short idx)
336 {
337
338         if (idx > V_if_index)
339                 return (NULL);
340         if (V_ifindex_table[idx] == IFNET_HOLD)
341                 return (NULL);
342         return (V_ifindex_table[idx]);
343 }
344
345 struct ifnet *
346 ifnet_byindex(u_short idx)
347 {
348         struct ifnet *ifp;
349
350         ifp = ifnet_byindex_locked(idx);
351         return (ifp);
352 }
353
354 struct ifnet *
355 ifnet_byindex_ref(u_short idx)
356 {
357         struct ifnet *ifp;
358
359         IFNET_RLOCK_NOSLEEP();
360         ifp = ifnet_byindex_locked(idx);
361         if (ifp == NULL || (ifp->if_flags & IFF_DYING)) {
362                 IFNET_RUNLOCK_NOSLEEP();
363                 return (NULL);
364         }
365         if_ref(ifp);
366         IFNET_RUNLOCK_NOSLEEP();
367         return (ifp);
368 }
369
370 /*
371  * Allocate an ifindex array entry; return 0 on success or an error on
372  * failure.
373  */
374 static u_short
375 ifindex_alloc(void **old)
376 {
377         u_short idx;
378
379         IFNET_WLOCK_ASSERT();
380         /*
381          * Try to find an empty slot below V_if_index.  If we fail, take the
382          * next slot.
383          */
384         for (idx = 1; idx <= V_if_index; idx++) {
385                 if (V_ifindex_table[idx] == NULL)
386                         break;
387         }
388
389         /* Catch if_index overflow. */
390         if (idx >= V_if_indexlim) {
391                 *old = if_grow();
392                 return (USHRT_MAX);
393         }
394         if (idx > V_if_index)
395                 V_if_index = idx;
396         return (idx);
397 }
398
399 static void
400 ifindex_free_locked(u_short idx)
401 {
402
403         IFNET_WLOCK_ASSERT();
404
405         V_ifindex_table[idx] = NULL;
406         while (V_if_index > 0 &&
407             V_ifindex_table[V_if_index] == NULL)
408                 V_if_index--;
409 }
410
411 static void
412 ifindex_free(u_short idx)
413 {
414
415         IFNET_WLOCK();
416         ifindex_free_locked(idx);
417         IFNET_WUNLOCK();
418 }
419
420 static void
421 ifnet_setbyindex(u_short idx, struct ifnet *ifp)
422 {
423
424         V_ifindex_table[idx] = ifp;
425 }
426
427 struct ifaddr *
428 ifaddr_byindex(u_short idx)
429 {
430         struct ifnet *ifp;
431         struct ifaddr *ifa = NULL;
432
433         IFNET_RLOCK_NOSLEEP();
434         ifp = ifnet_byindex_locked(idx);
435         if (ifp != NULL && (ifa = ifp->if_addr) != NULL)
436                 ifa_ref(ifa);
437         IFNET_RUNLOCK_NOSLEEP();
438         return (ifa);
439 }
440
441 /*
442  * Network interface utility routines.
443  *
444  * Routines with ifa_ifwith* names take sockaddr *'s as
445  * parameters.
446  */
447
448 static void
449 vnet_if_init(const void *unused __unused)
450 {
451         void *old;
452
453         CK_STAILQ_INIT(&V_ifnet);
454         CK_STAILQ_INIT(&V_ifg_head);
455         IFNET_WLOCK();
456         old = if_grow();                                /* create initial table */
457         IFNET_WUNLOCK();
458         epoch_wait_preempt(net_epoch_preempt);
459         free(old, M_IFNET);
460         vnet_if_clone_init();
461 }
462 VNET_SYSINIT(vnet_if_init, SI_SUB_INIT_IF, SI_ORDER_SECOND, vnet_if_init,
463     NULL);
464
465 #ifdef VIMAGE
466 static void
467 vnet_if_uninit(const void *unused __unused)
468 {
469
470         VNET_ASSERT(CK_STAILQ_EMPTY(&V_ifnet), ("%s:%d tailq &V_ifnet=%p "
471             "not empty", __func__, __LINE__, &V_ifnet));
472         VNET_ASSERT(CK_STAILQ_EMPTY(&V_ifg_head), ("%s:%d tailq &V_ifg_head=%p "
473             "not empty", __func__, __LINE__, &V_ifg_head));
474
475         free((caddr_t)V_ifindex_table, M_IFNET);
476 }
477 VNET_SYSUNINIT(vnet_if_uninit, SI_SUB_INIT_IF, SI_ORDER_FIRST,
478     vnet_if_uninit, NULL);
479
480 static void
481 vnet_if_return(const void *unused __unused)
482 {
483         struct ifnet *ifp, *nifp;
484
485         /* Return all inherited interfaces to their parent vnets. */
486         CK_STAILQ_FOREACH_SAFE(ifp, &V_ifnet, if_link, nifp) {
487                 if (ifp->if_home_vnet != ifp->if_vnet)
488                         if_vmove(ifp, ifp->if_home_vnet);
489         }
490 }
491 VNET_SYSUNINIT(vnet_if_return, SI_SUB_VNET_DONE, SI_ORDER_ANY,
492     vnet_if_return, NULL);
493 #endif
494
495
496 static void *
497 if_grow(void)
498 {
499         int oldlim;
500         u_int n;
501         struct ifnet **e;
502         void *old;
503
504         old = NULL;
505         IFNET_WLOCK_ASSERT();
506         oldlim = V_if_indexlim;
507         IFNET_WUNLOCK();
508         n = (oldlim << 1) * sizeof(*e);
509         e = malloc(n, M_IFNET, M_WAITOK | M_ZERO);
510         IFNET_WLOCK();
511         if (V_if_indexlim != oldlim) {
512                 free(e, M_IFNET);
513                 return (NULL);
514         }
515         if (V_ifindex_table != NULL) {
516                 memcpy((caddr_t)e, (caddr_t)V_ifindex_table, n/2);
517                 old = V_ifindex_table;
518         }
519         V_if_indexlim <<= 1;
520         V_ifindex_table = e;
521         return (old);
522 }
523
524 /*
525  * Allocate a struct ifnet and an index for an interface.  A layer 2
526  * common structure will also be allocated if an allocation routine is
527  * registered for the passed type.
528  */
529 struct ifnet *
530 if_alloc(u_char type)
531 {
532         struct ifnet *ifp;
533         u_short idx;
534         void *old;
535
536         ifp = malloc(sizeof(struct ifnet), M_IFNET, M_WAITOK|M_ZERO);
537  restart:
538         IFNET_WLOCK();
539         idx = ifindex_alloc(&old);
540         if (__predict_false(idx == USHRT_MAX)) {
541                 IFNET_WUNLOCK();
542                 epoch_wait_preempt(net_epoch_preempt);
543                 free(old, M_IFNET);
544                 goto restart;
545         }
546         ifnet_setbyindex(idx, IFNET_HOLD);
547         IFNET_WUNLOCK();
548         ifp->if_index = idx;
549         ifp->if_type = type;
550         ifp->if_alloctype = type;
551 #ifdef VIMAGE
552         ifp->if_vnet = curvnet;
553 #endif
554         if (if_com_alloc[type] != NULL) {
555                 ifp->if_l2com = if_com_alloc[type](type, ifp);
556                 if (ifp->if_l2com == NULL) {
557                         free(ifp, M_IFNET);
558                         ifindex_free(idx);
559                         return (NULL);
560                 }
561         }
562
563         IF_ADDR_LOCK_INIT(ifp);
564         TASK_INIT(&ifp->if_linktask, 0, do_link_state_change, ifp);
565         ifp->if_afdata_initialized = 0;
566         IF_AFDATA_LOCK_INIT(ifp);
567         CK_STAILQ_INIT(&ifp->if_addrhead);
568         CK_STAILQ_INIT(&ifp->if_multiaddrs);
569         CK_STAILQ_INIT(&ifp->if_groups);
570 #ifdef MAC
571         mac_ifnet_init(ifp);
572 #endif
573         ifq_init(&ifp->if_snd, ifp);
574
575         refcount_init(&ifp->if_refcount, 1);    /* Index reference. */
576         for (int i = 0; i < IFCOUNTERS; i++)
577                 ifp->if_counters[i] = counter_u64_alloc(M_WAITOK);
578         ifp->if_get_counter = if_get_counter_default;
579         ifp->if_pcp = IFNET_PCP_NONE;
580         ifnet_setbyindex(ifp->if_index, ifp);
581         return (ifp);
582 }
583
584 /*
585  * Do the actual work of freeing a struct ifnet, and layer 2 common
586  * structure.  This call is made when the last reference to an
587  * interface is released.
588  */
589 static void
590 if_free_internal(struct ifnet *ifp)
591 {
592
593         KASSERT((ifp->if_flags & IFF_DYING),
594             ("if_free_internal: interface not dying"));
595
596         if (if_com_free[ifp->if_alloctype] != NULL)
597                 if_com_free[ifp->if_alloctype](ifp->if_l2com,
598                     ifp->if_alloctype);
599
600 #ifdef MAC
601         mac_ifnet_destroy(ifp);
602 #endif /* MAC */
603         IF_AFDATA_DESTROY(ifp);
604         IF_ADDR_LOCK_DESTROY(ifp);
605         ifq_delete(&ifp->if_snd);
606
607         for (int i = 0; i < IFCOUNTERS; i++)
608                 counter_u64_free(ifp->if_counters[i]);
609
610         free(ifp->if_description, M_IFDESCR);
611         free(ifp->if_hw_addr, M_IFADDR);
612         free(ifp, M_IFNET);
613 }
614
615 static void
616 if_destroy(epoch_context_t ctx)
617 {
618         struct ifnet *ifp;
619
620         ifp = __containerof(ctx, struct ifnet, if_epoch_ctx);
621         if_free_internal(ifp);
622 }
623
624 /*
625  * Deregister an interface and free the associated storage.
626  */
627 void
628 if_free(struct ifnet *ifp)
629 {
630
631         ifp->if_flags |= IFF_DYING;                     /* XXX: Locking */
632
633         CURVNET_SET_QUIET(ifp->if_vnet);
634         IFNET_WLOCK();
635         KASSERT(ifp == ifnet_byindex_locked(ifp->if_index),
636             ("%s: freeing unallocated ifnet", ifp->if_xname));
637
638         ifindex_free_locked(ifp->if_index);
639         IFNET_WUNLOCK();
640
641         if (refcount_release(&ifp->if_refcount))
642                 epoch_call(net_epoch_preempt, &ifp->if_epoch_ctx, if_destroy);
643         CURVNET_RESTORE();
644 }
645
646 /*
647  * Interfaces to keep an ifnet type-stable despite the possibility of the
648  * driver calling if_free().  If there are additional references, we defer
649  * freeing the underlying data structure.
650  */
651 void
652 if_ref(struct ifnet *ifp)
653 {
654
655         /* We don't assert the ifnet list lock here, but arguably should. */
656         refcount_acquire(&ifp->if_refcount);
657 }
658
659 void
660 if_rele(struct ifnet *ifp)
661 {
662
663         if (!refcount_release(&ifp->if_refcount))
664                 return;
665         epoch_call(net_epoch_preempt, &ifp->if_epoch_ctx, if_destroy);
666 }
667
668 void
669 ifq_init(struct ifaltq *ifq, struct ifnet *ifp)
670 {
671         
672         mtx_init(&ifq->ifq_mtx, ifp->if_xname, "if send queue", MTX_DEF);
673
674         if (ifq->ifq_maxlen == 0) 
675                 ifq->ifq_maxlen = ifqmaxlen;
676
677         ifq->altq_type = 0;
678         ifq->altq_disc = NULL;
679         ifq->altq_flags &= ALTQF_CANTCHANGE;
680         ifq->altq_tbr  = NULL;
681         ifq->altq_ifp  = ifp;
682 }
683
684 void
685 ifq_delete(struct ifaltq *ifq)
686 {
687         mtx_destroy(&ifq->ifq_mtx);
688 }
689
690 /*
691  * Perform generic interface initialization tasks and attach the interface
692  * to the list of "active" interfaces.  If vmove flag is set on entry
693  * to if_attach_internal(), perform only a limited subset of initialization
694  * tasks, given that we are moving from one vnet to another an ifnet which
695  * has already been fully initialized.
696  *
697  * Note that if_detach_internal() removes group membership unconditionally
698  * even when vmove flag is set, and if_attach_internal() adds only IFG_ALL.
699  * Thus, when if_vmove() is applied to a cloned interface, group membership
700  * is lost while a cloned one always joins a group whose name is
701  * ifc->ifc_name.  To recover this after if_detach_internal() and
702  * if_attach_internal(), the cloner should be specified to
703  * if_attach_internal() via ifc.  If it is non-NULL, if_attach_internal()
704  * attempts to join a group whose name is ifc->ifc_name.
705  *
706  * XXX:
707  *  - The decision to return void and thus require this function to
708  *    succeed is questionable.
709  *  - We should probably do more sanity checking.  For instance we don't
710  *    do anything to insure if_xname is unique or non-empty.
711  */
712 void
713 if_attach(struct ifnet *ifp)
714 {
715
716         if_attach_internal(ifp, 0, NULL);
717 }
718
719 /*
720  * Compute the least common TSO limit.
721  */
722 void
723 if_hw_tsomax_common(if_t ifp, struct ifnet_hw_tsomax *pmax)
724 {
725         /*
726          * 1) If there is no limit currently, take the limit from
727          * the network adapter.
728          *
729          * 2) If the network adapter has a limit below the current
730          * limit, apply it.
731          */
732         if (pmax->tsomaxbytes == 0 || (ifp->if_hw_tsomax != 0 &&
733             ifp->if_hw_tsomax < pmax->tsomaxbytes)) {
734                 pmax->tsomaxbytes = ifp->if_hw_tsomax;
735         }
736         if (pmax->tsomaxsegcount == 0 || (ifp->if_hw_tsomaxsegcount != 0 &&
737             ifp->if_hw_tsomaxsegcount < pmax->tsomaxsegcount)) {
738                 pmax->tsomaxsegcount = ifp->if_hw_tsomaxsegcount;
739         }
740         if (pmax->tsomaxsegsize == 0 || (ifp->if_hw_tsomaxsegsize != 0 &&
741             ifp->if_hw_tsomaxsegsize < pmax->tsomaxsegsize)) {
742                 pmax->tsomaxsegsize = ifp->if_hw_tsomaxsegsize;
743         }
744 }
745
746 /*
747  * Update TSO limit of a network adapter.
748  *
749  * Returns zero if no change. Else non-zero.
750  */
751 int
752 if_hw_tsomax_update(if_t ifp, struct ifnet_hw_tsomax *pmax)
753 {
754         int retval = 0;
755         if (ifp->if_hw_tsomax != pmax->tsomaxbytes) {
756                 ifp->if_hw_tsomax = pmax->tsomaxbytes;
757                 retval++;
758         }
759         if (ifp->if_hw_tsomaxsegsize != pmax->tsomaxsegsize) {
760                 ifp->if_hw_tsomaxsegsize = pmax->tsomaxsegsize;
761                 retval++;
762         }
763         if (ifp->if_hw_tsomaxsegcount != pmax->tsomaxsegcount) {
764                 ifp->if_hw_tsomaxsegcount = pmax->tsomaxsegcount;
765                 retval++;
766         }
767         return (retval);
768 }
769
770 static void
771 if_attach_internal(struct ifnet *ifp, int vmove, struct if_clone *ifc)
772 {
773         unsigned socksize, ifasize;
774         int namelen, masklen;
775         struct sockaddr_dl *sdl;
776         struct ifaddr *ifa;
777
778         if (ifp->if_index == 0 || ifp != ifnet_byindex(ifp->if_index))
779                 panic ("%s: BUG: if_attach called without if_alloc'd input()\n",
780                     ifp->if_xname);
781
782 #ifdef VIMAGE
783         ifp->if_vnet = curvnet;
784         if (ifp->if_home_vnet == NULL)
785                 ifp->if_home_vnet = curvnet;
786 #endif
787
788         if_addgroup(ifp, IFG_ALL);
789
790         /* Restore group membership for cloned interfaces. */
791         if (vmove && ifc != NULL)
792                 if_clone_addgroup(ifp, ifc);
793
794         getmicrotime(&ifp->if_lastchange);
795         ifp->if_epoch = time_uptime;
796
797         KASSERT((ifp->if_transmit == NULL && ifp->if_qflush == NULL) ||
798             (ifp->if_transmit != NULL && ifp->if_qflush != NULL),
799             ("transmit and qflush must both either be set or both be NULL"));
800         if (ifp->if_transmit == NULL) {
801                 ifp->if_transmit = if_transmit;
802                 ifp->if_qflush = if_qflush;
803         }
804         if (ifp->if_input == NULL)
805                 ifp->if_input = if_input_default;
806
807         if (ifp->if_requestencap == NULL)
808                 ifp->if_requestencap = if_requestencap_default;
809
810         if (!vmove) {
811 #ifdef MAC
812                 mac_ifnet_create(ifp);
813 #endif
814
815                 /*
816                  * Create a Link Level name for this device.
817                  */
818                 namelen = strlen(ifp->if_xname);
819                 /*
820                  * Always save enough space for any possiable name so we
821                  * can do a rename in place later.
822                  */
823                 masklen = offsetof(struct sockaddr_dl, sdl_data[0]) + IFNAMSIZ;
824                 socksize = masklen + ifp->if_addrlen;
825                 if (socksize < sizeof(*sdl))
826                         socksize = sizeof(*sdl);
827                 socksize = roundup2(socksize, sizeof(long));
828                 ifasize = sizeof(*ifa) + 2 * socksize;
829                 ifa = ifa_alloc(ifasize, M_WAITOK);
830                 sdl = (struct sockaddr_dl *)(ifa + 1);
831                 sdl->sdl_len = socksize;
832                 sdl->sdl_family = AF_LINK;
833                 bcopy(ifp->if_xname, sdl->sdl_data, namelen);
834                 sdl->sdl_nlen = namelen;
835                 sdl->sdl_index = ifp->if_index;
836                 sdl->sdl_type = ifp->if_type;
837                 ifp->if_addr = ifa;
838                 ifa->ifa_ifp = ifp;
839                 ifa->ifa_rtrequest = link_rtrequest;
840                 ifa->ifa_addr = (struct sockaddr *)sdl;
841                 sdl = (struct sockaddr_dl *)(socksize + (caddr_t)sdl);
842                 ifa->ifa_netmask = (struct sockaddr *)sdl;
843                 sdl->sdl_len = masklen;
844                 while (namelen != 0)
845                         sdl->sdl_data[--namelen] = 0xff;
846                 CK_STAILQ_INSERT_HEAD(&ifp->if_addrhead, ifa, ifa_link);
847                 /* Reliably crash if used uninitialized. */
848                 ifp->if_broadcastaddr = NULL;
849
850                 if (ifp->if_type == IFT_ETHER) {
851                         ifp->if_hw_addr = malloc(ifp->if_addrlen, M_IFADDR,
852                             M_WAITOK | M_ZERO);
853                 }
854
855 #if defined(INET) || defined(INET6)
856                 /* Use defaults for TSO, if nothing is set */
857                 if (ifp->if_hw_tsomax == 0 &&
858                     ifp->if_hw_tsomaxsegcount == 0 &&
859                     ifp->if_hw_tsomaxsegsize == 0) {
860                         /*
861                          * The TSO defaults needs to be such that an
862                          * NFS mbuf list of 35 mbufs totalling just
863                          * below 64K works and that a chain of mbufs
864                          * can be defragged into at most 32 segments:
865                          */
866                         ifp->if_hw_tsomax = min(IP_MAXPACKET, (32 * MCLBYTES) -
867                             (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN));
868                         ifp->if_hw_tsomaxsegcount = 35;
869                         ifp->if_hw_tsomaxsegsize = 2048;        /* 2K */
870
871                         /* XXX some drivers set IFCAP_TSO after ethernet attach */
872                         if (ifp->if_capabilities & IFCAP_TSO) {
873                                 if_printf(ifp, "Using defaults for TSO: %u/%u/%u\n",
874                                     ifp->if_hw_tsomax,
875                                     ifp->if_hw_tsomaxsegcount,
876                                     ifp->if_hw_tsomaxsegsize);
877                         }
878                 }
879 #endif
880         }
881 #ifdef VIMAGE
882         else {
883                 /*
884                  * Update the interface index in the link layer address
885                  * of the interface.
886                  */
887                 for (ifa = ifp->if_addr; ifa != NULL;
888                     ifa = CK_STAILQ_NEXT(ifa, ifa_link)) {
889                         if (ifa->ifa_addr->sa_family == AF_LINK) {
890                                 sdl = (struct sockaddr_dl *)ifa->ifa_addr;
891                                 sdl->sdl_index = ifp->if_index;
892                         }
893                 }
894         }
895 #endif
896
897         IFNET_WLOCK();
898         CK_STAILQ_INSERT_TAIL(&V_ifnet, ifp, if_link);
899 #ifdef VIMAGE
900         curvnet->vnet_ifcnt++;
901 #endif
902         IFNET_WUNLOCK();
903
904         if (domain_init_status >= 2)
905                 if_attachdomain1(ifp);
906
907         EVENTHANDLER_INVOKE(ifnet_arrival_event, ifp);
908         if (IS_DEFAULT_VNET(curvnet))
909                 devctl_notify("IFNET", ifp->if_xname, "ATTACH", NULL);
910
911         /* Announce the interface. */
912         rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
913 }
914
915 static void
916 if_epochalloc(void *dummy __unused)
917 {
918
919         net_epoch_preempt = epoch_alloc(EPOCH_PREEMPT);
920         net_epoch = epoch_alloc(0);
921 }
922 SYSINIT(ifepochalloc, SI_SUB_TASKQ + 1, SI_ORDER_ANY,
923     if_epochalloc, NULL);
924
925 static void
926 if_attachdomain(void *dummy)
927 {
928         struct ifnet *ifp;
929
930         CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link)
931                 if_attachdomain1(ifp);
932 }
933 SYSINIT(domainifattach, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_SECOND,
934     if_attachdomain, NULL);
935
936 static void
937 if_attachdomain1(struct ifnet *ifp)
938 {
939         struct domain *dp;
940
941         /*
942          * Since dp->dom_ifattach calls malloc() with M_WAITOK, we
943          * cannot lock ifp->if_afdata initialization, entirely.
944          */
945         IF_AFDATA_LOCK(ifp);
946         if (ifp->if_afdata_initialized >= domain_init_status) {
947                 IF_AFDATA_UNLOCK(ifp);
948                 log(LOG_WARNING, "%s called more than once on %s\n",
949                     __func__, ifp->if_xname);
950                 return;
951         }
952         ifp->if_afdata_initialized = domain_init_status;
953         IF_AFDATA_UNLOCK(ifp);
954
955         /* address family dependent data region */
956         bzero(ifp->if_afdata, sizeof(ifp->if_afdata));
957         for (dp = domains; dp; dp = dp->dom_next) {
958                 if (dp->dom_ifattach)
959                         ifp->if_afdata[dp->dom_family] =
960                             (*dp->dom_ifattach)(ifp);
961         }
962 }
963
964 /*
965  * Remove any unicast or broadcast network addresses from an interface.
966  */
967 void
968 if_purgeaddrs(struct ifnet *ifp)
969 {
970         struct ifaddr *ifa;
971
972         while (1) {
973                 NET_EPOCH_ENTER();
974                 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
975                         if (ifa->ifa_addr->sa_family != AF_LINK)
976                                 break;
977                 }
978                 NET_EPOCH_EXIT();
979
980                 if (ifa == NULL)
981                         break;
982 #ifdef INET
983                 /* XXX: Ugly!! ad hoc just for INET */
984                 if (ifa->ifa_addr->sa_family == AF_INET) {
985                         struct ifaliasreq ifr;
986
987                         bzero(&ifr, sizeof(ifr));
988                         ifr.ifra_addr = *ifa->ifa_addr;
989                         if (ifa->ifa_dstaddr)
990                                 ifr.ifra_broadaddr = *ifa->ifa_dstaddr;
991                         if (in_control(NULL, SIOCDIFADDR, (caddr_t)&ifr, ifp,
992                             NULL) == 0)
993                                 continue;
994                 }
995 #endif /* INET */
996 #ifdef INET6
997                 if (ifa->ifa_addr->sa_family == AF_INET6) {
998                         in6_purgeaddr(ifa);
999                         /* ifp_addrhead is already updated */
1000                         continue;
1001                 }
1002 #endif /* INET6 */
1003                 IF_ADDR_WLOCK(ifp);
1004                 CK_STAILQ_REMOVE(&ifp->if_addrhead, ifa, ifaddr, ifa_link);
1005                 IF_ADDR_WUNLOCK(ifp);
1006                 ifa_free(ifa);
1007         }
1008 }
1009
1010 /*
1011  * Remove any multicast network addresses from an interface when an ifnet
1012  * is going away.
1013  */
1014 static void
1015 if_purgemaddrs(struct ifnet *ifp)
1016 {
1017         struct ifmultiaddr *ifma;
1018
1019         IF_ADDR_WLOCK(ifp);
1020         while (!CK_STAILQ_EMPTY(&ifp->if_multiaddrs)) {
1021                 ifma = CK_STAILQ_FIRST(&ifp->if_multiaddrs);
1022                 CK_STAILQ_REMOVE(&ifp->if_multiaddrs, ifma, ifmultiaddr, ifma_link);
1023                 if_delmulti_locked(ifp, ifma, 1);
1024         }
1025         IF_ADDR_WUNLOCK(ifp);
1026 }
1027
1028 /*
1029  * Detach an interface, removing it from the list of "active" interfaces.
1030  * If vmove flag is set on entry to if_detach_internal(), perform only a
1031  * limited subset of cleanup tasks, given that we are moving an ifnet from
1032  * one vnet to another, where it must be fully operational.
1033  *
1034  * XXXRW: There are some significant questions about event ordering, and
1035  * how to prevent things from starting to use the interface during detach.
1036  */
1037 void
1038 if_detach(struct ifnet *ifp)
1039 {
1040
1041         CURVNET_SET_QUIET(ifp->if_vnet);
1042         if_detach_internal(ifp, 0, NULL);
1043         CURVNET_RESTORE();
1044 }
1045
1046 /*
1047  * The vmove flag, if set, indicates that we are called from a callpath
1048  * that is moving an interface to a different vnet instance.
1049  *
1050  * The shutdown flag, if set, indicates that we are called in the
1051  * process of shutting down a vnet instance.  Currently only the
1052  * vnet_if_return SYSUNINIT function sets it.  Note: we can be called
1053  * on a vnet instance shutdown without this flag being set, e.g., when
1054  * the cloned interfaces are destoyed as first thing of teardown.
1055  */
1056 static int
1057 if_detach_internal(struct ifnet *ifp, int vmove, struct if_clone **ifcp)
1058 {
1059         struct ifaddr *ifa;
1060         int i;
1061         struct domain *dp;
1062         struct ifnet *iter;
1063         int found = 0;
1064 #ifdef VIMAGE
1065         int shutdown;
1066
1067         shutdown = (ifp->if_vnet->vnet_state > SI_SUB_VNET &&
1068                  ifp->if_vnet->vnet_state < SI_SUB_VNET_DONE) ? 1 : 0;
1069 #endif
1070         IFNET_WLOCK();
1071         CK_STAILQ_FOREACH(iter, &V_ifnet, if_link)
1072                 if (iter == ifp) {
1073                         CK_STAILQ_REMOVE(&V_ifnet, ifp, ifnet, if_link);
1074                         if (!vmove)
1075                                 ifp->if_flags |= IFF_DYING;
1076                         found = 1;
1077                         break;
1078                 }
1079         IFNET_WUNLOCK();
1080         if (!found) {
1081                 /*
1082                  * While we would want to panic here, we cannot
1083                  * guarantee that the interface is indeed still on
1084                  * the list given we don't hold locks all the way.
1085                  */
1086                 return (ENOENT);
1087 #if 0
1088                 if (vmove)
1089                         panic("%s: ifp=%p not on the ifnet tailq %p",
1090                             __func__, ifp, &V_ifnet);
1091                 else
1092                         return; /* XXX this should panic as well? */
1093 #endif
1094         }
1095
1096         /*
1097          * At this point we know the interface still was on the ifnet list
1098          * and we removed it so we are in a stable state.
1099          */
1100 #ifdef VIMAGE
1101         curvnet->vnet_ifcnt--;
1102 #endif
1103         epoch_wait_preempt(net_epoch_preempt);
1104
1105         /*
1106          * Ensure all pending EPOCH(9) callbacks have been executed. This
1107          * fixes issues about late destruction of multicast options
1108          * which lead to leave group calls, which in turn access the
1109          * belonging ifnet structure:
1110          */
1111         epoch_drain_callbacks(net_epoch_preempt);
1112
1113         /*
1114          * In any case (destroy or vmove) detach us from the groups
1115          * and remove/wait for pending events on the taskq.
1116          * XXX-BZ in theory an interface could still enqueue a taskq change?
1117          */
1118         if_delgroups(ifp);
1119
1120         taskqueue_drain(taskqueue_swi, &ifp->if_linktask);
1121
1122         /*
1123          * Check if this is a cloned interface or not. Must do even if
1124          * shutting down as a if_vmove_reclaim() would move the ifp and
1125          * the if_clone_addgroup() will have a corrupted string overwise
1126          * from a gibberish pointer.
1127          */
1128         if (vmove && ifcp != NULL)
1129                 *ifcp = if_clone_findifc(ifp);
1130
1131         if_down(ifp);
1132
1133 #ifdef VIMAGE
1134         /*
1135          * On VNET shutdown abort here as the stack teardown will do all
1136          * the work top-down for us.
1137          */
1138         if (shutdown) {
1139                 /* Give interface users the chance to clean up. */
1140                 EVENTHANDLER_INVOKE(ifnet_departure_event, ifp);
1141
1142                 /*
1143                  * In case of a vmove we are done here without error.
1144                  * If we would signal an error it would lead to the same
1145                  * abort as if we did not find the ifnet anymore.
1146                  * if_detach() calls us in void context and does not care
1147                  * about an early abort notification, so life is splendid :)
1148                  */
1149                 goto finish_vnet_shutdown;
1150         }
1151 #endif
1152
1153         /*
1154          * At this point we are not tearing down a VNET and are either
1155          * going to destroy or vmove the interface and have to cleanup
1156          * accordingly.
1157          */
1158
1159         /*
1160          * Remove routes and flush queues.
1161          */
1162 #ifdef ALTQ
1163         if (ALTQ_IS_ENABLED(&ifp->if_snd))
1164                 altq_disable(&ifp->if_snd);
1165         if (ALTQ_IS_ATTACHED(&ifp->if_snd))
1166                 altq_detach(&ifp->if_snd);
1167 #endif
1168
1169         if_purgeaddrs(ifp);
1170
1171 #ifdef INET
1172         in_ifdetach(ifp);
1173 #endif
1174
1175 #ifdef INET6
1176         /*
1177          * Remove all IPv6 kernel structs related to ifp.  This should be done
1178          * before removing routing entries below, since IPv6 interface direct
1179          * routes are expected to be removed by the IPv6-specific kernel API.
1180          * Otherwise, the kernel will detect some inconsistency and bark it.
1181          */
1182         in6_ifdetach(ifp);
1183 #endif
1184         if_purgemaddrs(ifp);
1185
1186         /* Announce that the interface is gone. */
1187         rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
1188         EVENTHANDLER_INVOKE(ifnet_departure_event, ifp);
1189         if (IS_DEFAULT_VNET(curvnet))
1190                 devctl_notify("IFNET", ifp->if_xname, "DETACH", NULL);
1191
1192         if (!vmove) {
1193                 /*
1194                  * Prevent further calls into the device driver via ifnet.
1195                  */
1196                 if_dead(ifp);
1197
1198                 /*
1199                  * Clean up all addresses.
1200                  */
1201                 IF_ADDR_WLOCK(ifp);
1202                 if (!CK_STAILQ_EMPTY(&ifp->if_addrhead)) {
1203                         ifa = CK_STAILQ_FIRST(&ifp->if_addrhead);
1204                         CK_STAILQ_REMOVE(&ifp->if_addrhead, ifa, ifaddr, ifa_link);
1205                         IF_ADDR_WUNLOCK(ifp);
1206                         ifa_free(ifa);
1207                 } else
1208                         IF_ADDR_WUNLOCK(ifp);
1209         }
1210
1211         rt_flushifroutes(ifp);
1212
1213 #ifdef VIMAGE
1214 finish_vnet_shutdown:
1215 #endif
1216         /*
1217          * We cannot hold the lock over dom_ifdetach calls as they might
1218          * sleep, for example trying to drain a callout, thus open up the
1219          * theoretical race with re-attaching.
1220          */
1221         IF_AFDATA_LOCK(ifp);
1222         i = ifp->if_afdata_initialized;
1223         ifp->if_afdata_initialized = 0;
1224         IF_AFDATA_UNLOCK(ifp);
1225         for (dp = domains; i > 0 && dp; dp = dp->dom_next) {
1226                 if (dp->dom_ifdetach && ifp->if_afdata[dp->dom_family]) {
1227                         (*dp->dom_ifdetach)(ifp,
1228                             ifp->if_afdata[dp->dom_family]);
1229                         ifp->if_afdata[dp->dom_family] = NULL;
1230                 }
1231         }
1232
1233         return (0);
1234 }
1235
1236 #ifdef VIMAGE
1237 /*
1238  * if_vmove() performs a limited version of if_detach() in current
1239  * vnet and if_attach()es the ifnet to the vnet specified as 2nd arg.
1240  * An attempt is made to shrink if_index in current vnet, find an
1241  * unused if_index in target vnet and calls if_grow() if necessary,
1242  * and finally find an unused if_xname for the target vnet.
1243  */
1244 static void
1245 if_vmove(struct ifnet *ifp, struct vnet *new_vnet)
1246 {
1247         struct if_clone *ifc;
1248 #ifdef DEV_BPF
1249         u_int bif_dlt, bif_hdrlen;
1250 #endif
1251         void *old;
1252         int rc;
1253
1254 #ifdef DEV_BPF
1255         /*
1256          * if_detach_internal() will call the eventhandler to notify
1257          * interface departure.  That will detach if_bpf.  We need to
1258          * safe the dlt and hdrlen so we can re-attach it later.
1259          */
1260         bpf_get_bp_params(ifp->if_bpf, &bif_dlt, &bif_hdrlen);
1261 #endif
1262
1263         /*
1264          * Detach from current vnet, but preserve LLADDR info, do not
1265          * mark as dead etc. so that the ifnet can be reattached later.
1266          * If we cannot find it, we lost the race to someone else.
1267          */
1268         rc = if_detach_internal(ifp, 1, &ifc);
1269         if (rc != 0)
1270                 return;
1271
1272         /*
1273          * Unlink the ifnet from ifindex_table[] in current vnet, and shrink
1274          * the if_index for that vnet if possible.
1275          *
1276          * NOTE: IFNET_WLOCK/IFNET_WUNLOCK() are assumed to be unvirtualized,
1277          * or we'd lock on one vnet and unlock on another.
1278          */
1279         IFNET_WLOCK();
1280         ifindex_free_locked(ifp->if_index);
1281         IFNET_WUNLOCK();
1282
1283         /* Don't re-attach DYING interfaces. */
1284         if (ifp->if_flags & IFF_DYING)
1285                 return;
1286
1287         /*
1288          * Perform interface-specific reassignment tasks, if provided by
1289          * the driver.
1290          */
1291         if (ifp->if_reassign != NULL)
1292                 ifp->if_reassign(ifp, new_vnet, NULL);
1293
1294         /*
1295          * Switch to the context of the target vnet.
1296          */
1297         CURVNET_SET_QUIET(new_vnet);
1298  restart:
1299         IFNET_WLOCK();
1300         ifp->if_index = ifindex_alloc(&old);
1301         if (__predict_false(ifp->if_index == USHRT_MAX)) {
1302                 IFNET_WUNLOCK();
1303                 epoch_wait_preempt(net_epoch_preempt);
1304                 free(old, M_IFNET);
1305                 goto restart;
1306         }
1307         ifnet_setbyindex(ifp->if_index, ifp);
1308         IFNET_WUNLOCK();
1309
1310         if_attach_internal(ifp, 1, ifc);
1311
1312 #ifdef DEV_BPF
1313         if (ifp->if_bpf == NULL)
1314                 bpfattach(ifp, bif_dlt, bif_hdrlen);
1315 #endif
1316
1317         CURVNET_RESTORE();
1318 }
1319
1320 /*
1321  * Move an ifnet to or from another child prison/vnet, specified by the jail id.
1322  */
1323 static int
1324 if_vmove_loan(struct thread *td, struct ifnet *ifp, char *ifname, int jid)
1325 {
1326         struct prison *pr;
1327         struct ifnet *difp;
1328         int shutdown;
1329
1330         /* Try to find the prison within our visibility. */
1331         sx_slock(&allprison_lock);
1332         pr = prison_find_child(td->td_ucred->cr_prison, jid);
1333         sx_sunlock(&allprison_lock);
1334         if (pr == NULL)
1335                 return (ENXIO);
1336         prison_hold_locked(pr);
1337         mtx_unlock(&pr->pr_mtx);
1338
1339         /* Do not try to move the iface from and to the same prison. */
1340         if (pr->pr_vnet == ifp->if_vnet) {
1341                 prison_free(pr);
1342                 return (EEXIST);
1343         }
1344
1345         /* Make sure the named iface does not exists in the dst. prison/vnet. */
1346         /* XXX Lock interfaces to avoid races. */
1347         CURVNET_SET_QUIET(pr->pr_vnet);
1348         difp = ifunit(ifname);
1349         if (difp != NULL) {
1350                 CURVNET_RESTORE();
1351                 prison_free(pr);
1352                 return (EEXIST);
1353         }
1354
1355         /* Make sure the VNET is stable. */
1356         shutdown = (ifp->if_vnet->vnet_state > SI_SUB_VNET &&
1357                  ifp->if_vnet->vnet_state < SI_SUB_VNET_DONE) ? 1 : 0;
1358         if (shutdown) {
1359                 CURVNET_RESTORE();
1360                 prison_free(pr);
1361                 return (EBUSY);
1362         }
1363         CURVNET_RESTORE();
1364
1365         /* Move the interface into the child jail/vnet. */
1366         if_vmove(ifp, pr->pr_vnet);
1367
1368         /* Report the new if_xname back to the userland. */
1369         sprintf(ifname, "%s", ifp->if_xname);
1370
1371         prison_free(pr);
1372         return (0);
1373 }
1374
1375 static int
1376 if_vmove_reclaim(struct thread *td, char *ifname, int jid)
1377 {
1378         struct prison *pr;
1379         struct vnet *vnet_dst;
1380         struct ifnet *ifp;
1381         int shutdown;
1382
1383         /* Try to find the prison within our visibility. */
1384         sx_slock(&allprison_lock);
1385         pr = prison_find_child(td->td_ucred->cr_prison, jid);
1386         sx_sunlock(&allprison_lock);
1387         if (pr == NULL)
1388                 return (ENXIO);
1389         prison_hold_locked(pr);
1390         mtx_unlock(&pr->pr_mtx);
1391
1392         /* Make sure the named iface exists in the source prison/vnet. */
1393         CURVNET_SET(pr->pr_vnet);
1394         ifp = ifunit(ifname);           /* XXX Lock to avoid races. */
1395         if (ifp == NULL) {
1396                 CURVNET_RESTORE();
1397                 prison_free(pr);
1398                 return (ENXIO);
1399         }
1400
1401         /* Do not try to move the iface from and to the same prison. */
1402         vnet_dst = TD_TO_VNET(td);
1403         if (vnet_dst == ifp->if_vnet) {
1404                 CURVNET_RESTORE();
1405                 prison_free(pr);
1406                 return (EEXIST);
1407         }
1408
1409         /* Make sure the VNET is stable. */
1410         shutdown = (ifp->if_vnet->vnet_state > SI_SUB_VNET &&
1411                  ifp->if_vnet->vnet_state < SI_SUB_VNET_DONE) ? 1 : 0;
1412         if (shutdown) {
1413                 CURVNET_RESTORE();
1414                 prison_free(pr);
1415                 return (EBUSY);
1416         }
1417
1418         /* Get interface back from child jail/vnet. */
1419         if_vmove(ifp, vnet_dst);
1420         CURVNET_RESTORE();
1421
1422         /* Report the new if_xname back to the userland. */
1423         sprintf(ifname, "%s", ifp->if_xname);
1424
1425         prison_free(pr);
1426         return (0);
1427 }
1428 #endif /* VIMAGE */
1429
1430 /*
1431  * Add a group to an interface
1432  */
1433 int
1434 if_addgroup(struct ifnet *ifp, const char *groupname)
1435 {
1436         struct ifg_list         *ifgl;
1437         struct ifg_group        *ifg = NULL;
1438         struct ifg_member       *ifgm;
1439         int                      new = 0;
1440
1441         if (groupname[0] && groupname[strlen(groupname) - 1] >= '0' &&
1442             groupname[strlen(groupname) - 1] <= '9')
1443                 return (EINVAL);
1444
1445         IFNET_WLOCK();
1446         CK_STAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
1447                 if (!strcmp(ifgl->ifgl_group->ifg_group, groupname)) {
1448                         IFNET_WUNLOCK();
1449                         return (EEXIST);
1450                 }
1451
1452         if ((ifgl = malloc(sizeof(*ifgl), M_TEMP, M_NOWAIT)) == NULL) {
1453                 IFNET_WUNLOCK();
1454                 return (ENOMEM);
1455         }
1456
1457         if ((ifgm = malloc(sizeof(*ifgm), M_TEMP, M_NOWAIT)) == NULL) {
1458                 free(ifgl, M_TEMP);
1459                 IFNET_WUNLOCK();
1460                 return (ENOMEM);
1461         }
1462
1463         CK_STAILQ_FOREACH(ifg, &V_ifg_head, ifg_next)
1464                 if (!strcmp(ifg->ifg_group, groupname))
1465                         break;
1466
1467         if (ifg == NULL) {
1468                 if ((ifg = malloc(sizeof(*ifg), M_TEMP, M_NOWAIT)) == NULL) {
1469                         free(ifgl, M_TEMP);
1470                         free(ifgm, M_TEMP);
1471                         IFNET_WUNLOCK();
1472                         return (ENOMEM);
1473                 }
1474                 strlcpy(ifg->ifg_group, groupname, sizeof(ifg->ifg_group));
1475                 ifg->ifg_refcnt = 0;
1476                 CK_STAILQ_INIT(&ifg->ifg_members);
1477                 CK_STAILQ_INSERT_TAIL(&V_ifg_head, ifg, ifg_next);
1478                 new = 1;
1479         }
1480
1481         ifg->ifg_refcnt++;
1482         ifgl->ifgl_group = ifg;
1483         ifgm->ifgm_ifp = ifp;
1484
1485         IF_ADDR_WLOCK(ifp);
1486         CK_STAILQ_INSERT_TAIL(&ifg->ifg_members, ifgm, ifgm_next);
1487         CK_STAILQ_INSERT_TAIL(&ifp->if_groups, ifgl, ifgl_next);
1488         IF_ADDR_WUNLOCK(ifp);
1489
1490         IFNET_WUNLOCK();
1491
1492         if (new)
1493                 EVENTHANDLER_INVOKE(group_attach_event, ifg);
1494         EVENTHANDLER_INVOKE(group_change_event, groupname);
1495
1496         return (0);
1497 }
1498
1499 /*
1500  * Helper function to remove a group out of an interface.  Expects the global
1501  * ifnet lock to be write-locked, and drops it before returning.
1502  */
1503 static void
1504 _if_delgroup_locked(struct ifnet *ifp, struct ifg_list *ifgl,
1505     const char *groupname)
1506 {
1507         struct ifg_member *ifgm;
1508         bool freeifgl;
1509
1510         IFNET_WLOCK_ASSERT();
1511
1512         IF_ADDR_WLOCK(ifp);
1513         CK_STAILQ_REMOVE(&ifp->if_groups, ifgl, ifg_list, ifgl_next);
1514         IF_ADDR_WUNLOCK(ifp);
1515
1516         CK_STAILQ_FOREACH(ifgm, &ifgl->ifgl_group->ifg_members, ifgm_next) {
1517                 if (ifgm->ifgm_ifp == ifp) {
1518                         CK_STAILQ_REMOVE(&ifgl->ifgl_group->ifg_members, ifgm,
1519                             ifg_member, ifgm_next);
1520                         break;
1521                 }
1522         }
1523
1524         if (--ifgl->ifgl_group->ifg_refcnt == 0) {
1525                 CK_STAILQ_REMOVE(&V_ifg_head, ifgl->ifgl_group, ifg_group,
1526                     ifg_next);
1527                 freeifgl = true;
1528         } else {
1529                 freeifgl = false;
1530         }
1531         IFNET_WUNLOCK();
1532
1533         epoch_wait_preempt(net_epoch_preempt);
1534         if (freeifgl) {
1535                 EVENTHANDLER_INVOKE(group_detach_event, ifgl->ifgl_group);
1536                 free(ifgl->ifgl_group, M_TEMP);
1537         }
1538         free(ifgm, M_TEMP);
1539         free(ifgl, M_TEMP);
1540
1541         EVENTHANDLER_INVOKE(group_change_event, groupname);
1542 }
1543
1544 /*
1545  * Remove a group from an interface
1546  */
1547 int
1548 if_delgroup(struct ifnet *ifp, const char *groupname)
1549 {
1550         struct ifg_list *ifgl;
1551
1552         IFNET_WLOCK();
1553         CK_STAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
1554                 if (strcmp(ifgl->ifgl_group->ifg_group, groupname) == 0)
1555                         break;
1556         if (ifgl == NULL) {
1557                 IFNET_WUNLOCK();
1558                 return (ENOENT);
1559         }
1560
1561         _if_delgroup_locked(ifp, ifgl, groupname);
1562
1563         return (0);
1564 }
1565
1566 /*
1567  * Remove an interface from all groups
1568  */
1569 static void
1570 if_delgroups(struct ifnet *ifp)
1571 {
1572         struct ifg_list *ifgl;
1573         char groupname[IFNAMSIZ];
1574
1575         IFNET_WLOCK();
1576         while ((ifgl = CK_STAILQ_FIRST(&ifp->if_groups)) != NULL) {
1577                 strlcpy(groupname, ifgl->ifgl_group->ifg_group, IFNAMSIZ);
1578                 _if_delgroup_locked(ifp, ifgl, groupname);
1579                 IFNET_WLOCK();
1580         }
1581         IFNET_WUNLOCK();
1582 }
1583
1584 static char *
1585 ifgr_group_get(void *ifgrp)
1586 {
1587         union ifgroupreq_union *ifgrup;
1588
1589         ifgrup = ifgrp;
1590 #ifdef COMPAT_FREEBSD32
1591         if (SV_CURPROC_FLAG(SV_ILP32))
1592                 return (&ifgrup->ifgr32.ifgr_ifgru.ifgru_group[0]);
1593 #endif
1594         return (&ifgrup->ifgr.ifgr_ifgru.ifgru_group[0]);
1595 }
1596
1597 static struct ifg_req *
1598 ifgr_groups_get(void *ifgrp)
1599 {
1600         union ifgroupreq_union *ifgrup;
1601
1602         ifgrup = ifgrp;
1603 #ifdef COMPAT_FREEBSD32
1604         if (SV_CURPROC_FLAG(SV_ILP32))
1605                 return ((struct ifg_req *)(uintptr_t)
1606                     ifgrup->ifgr32.ifgr_ifgru.ifgru_groups);
1607 #endif
1608         return (ifgrup->ifgr.ifgr_ifgru.ifgru_groups);
1609 }
1610
1611 /*
1612  * Stores all groups from an interface in memory pointed to by ifgr.
1613  */
1614 static int
1615 if_getgroup(struct ifgroupreq *ifgr, struct ifnet *ifp)
1616 {
1617         int                      len, error;
1618         struct ifg_list         *ifgl;
1619         struct ifg_req           ifgrq, *ifgp;
1620
1621         if (ifgr->ifgr_len == 0) {
1622                 IF_ADDR_RLOCK(ifp);
1623                 CK_STAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
1624                         ifgr->ifgr_len += sizeof(struct ifg_req);
1625                 IF_ADDR_RUNLOCK(ifp);
1626                 return (0);
1627         }
1628
1629         len = ifgr->ifgr_len;
1630         ifgp = ifgr_groups_get(ifgr);
1631         /* XXX: wire */
1632         IF_ADDR_RLOCK(ifp);
1633         CK_STAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next) {
1634                 if (len < sizeof(ifgrq)) {
1635                         IF_ADDR_RUNLOCK(ifp);
1636                         return (EINVAL);
1637                 }
1638                 bzero(&ifgrq, sizeof ifgrq);
1639                 strlcpy(ifgrq.ifgrq_group, ifgl->ifgl_group->ifg_group,
1640                     sizeof(ifgrq.ifgrq_group));
1641                 if ((error = copyout(&ifgrq, ifgp, sizeof(struct ifg_req)))) {
1642                         IF_ADDR_RUNLOCK(ifp);
1643                         return (error);
1644                 }
1645                 len -= sizeof(ifgrq);
1646                 ifgp++;
1647         }
1648         IF_ADDR_RUNLOCK(ifp);
1649
1650         return (0);
1651 }
1652
1653 /*
1654  * Stores all members of a group in memory pointed to by igfr
1655  */
1656 static int
1657 if_getgroupmembers(struct ifgroupreq *ifgr)
1658 {
1659         struct ifg_group        *ifg;
1660         struct ifg_member       *ifgm;
1661         struct ifg_req           ifgrq, *ifgp;
1662         int                      len, error;
1663
1664         IFNET_RLOCK();
1665         CK_STAILQ_FOREACH(ifg, &V_ifg_head, ifg_next)
1666                 if (strcmp(ifg->ifg_group, ifgr->ifgr_name) == 0)
1667                         break;
1668         if (ifg == NULL) {
1669                 IFNET_RUNLOCK();
1670                 return (ENOENT);
1671         }
1672
1673         if (ifgr->ifgr_len == 0) {
1674                 CK_STAILQ_FOREACH(ifgm, &ifg->ifg_members, ifgm_next)
1675                         ifgr->ifgr_len += sizeof(ifgrq);
1676                 IFNET_RUNLOCK();
1677                 return (0);
1678         }
1679
1680         len = ifgr->ifgr_len;
1681         ifgp = ifgr_groups_get(ifgr);
1682         CK_STAILQ_FOREACH(ifgm, &ifg->ifg_members, ifgm_next) {
1683                 if (len < sizeof(ifgrq)) {
1684                         IFNET_RUNLOCK();
1685                         return (EINVAL);
1686                 }
1687                 bzero(&ifgrq, sizeof ifgrq);
1688                 strlcpy(ifgrq.ifgrq_member, ifgm->ifgm_ifp->if_xname,
1689                     sizeof(ifgrq.ifgrq_member));
1690                 if ((error = copyout(&ifgrq, ifgp, sizeof(struct ifg_req)))) {
1691                         IFNET_RUNLOCK();
1692                         return (error);
1693                 }
1694                 len -= sizeof(ifgrq);
1695                 ifgp++;
1696         }
1697         IFNET_RUNLOCK();
1698
1699         return (0);
1700 }
1701
1702 /*
1703  * Return counter values from counter(9)s stored in ifnet.
1704  */
1705 uint64_t
1706 if_get_counter_default(struct ifnet *ifp, ift_counter cnt)
1707 {
1708
1709         KASSERT(cnt < IFCOUNTERS, ("%s: invalid cnt %d", __func__, cnt));
1710
1711         return (counter_u64_fetch(ifp->if_counters[cnt]));
1712 }
1713
1714 /*
1715  * Increase an ifnet counter. Usually used for counters shared
1716  * between the stack and a driver, but function supports them all.
1717  */
1718 void
1719 if_inc_counter(struct ifnet *ifp, ift_counter cnt, int64_t inc)
1720 {
1721
1722         KASSERT(cnt < IFCOUNTERS, ("%s: invalid cnt %d", __func__, cnt));
1723
1724         counter_u64_add(ifp->if_counters[cnt], inc);
1725 }
1726
1727 /*
1728  * Copy data from ifnet to userland API structure if_data.
1729  */
1730 void
1731 if_data_copy(struct ifnet *ifp, struct if_data *ifd)
1732 {
1733
1734         ifd->ifi_type = ifp->if_type;
1735         ifd->ifi_physical = 0;
1736         ifd->ifi_addrlen = ifp->if_addrlen;
1737         ifd->ifi_hdrlen = ifp->if_hdrlen;
1738         ifd->ifi_link_state = ifp->if_link_state;
1739         ifd->ifi_vhid = 0;
1740         ifd->ifi_datalen = sizeof(struct if_data);
1741         ifd->ifi_mtu = ifp->if_mtu;
1742         ifd->ifi_metric = ifp->if_metric;
1743         ifd->ifi_baudrate = ifp->if_baudrate;
1744         ifd->ifi_hwassist = ifp->if_hwassist;
1745         ifd->ifi_epoch = ifp->if_epoch;
1746         ifd->ifi_lastchange = ifp->if_lastchange;
1747
1748         ifd->ifi_ipackets = ifp->if_get_counter(ifp, IFCOUNTER_IPACKETS);
1749         ifd->ifi_ierrors = ifp->if_get_counter(ifp, IFCOUNTER_IERRORS);
1750         ifd->ifi_opackets = ifp->if_get_counter(ifp, IFCOUNTER_OPACKETS);
1751         ifd->ifi_oerrors = ifp->if_get_counter(ifp, IFCOUNTER_OERRORS);
1752         ifd->ifi_collisions = ifp->if_get_counter(ifp, IFCOUNTER_COLLISIONS);
1753         ifd->ifi_ibytes = ifp->if_get_counter(ifp, IFCOUNTER_IBYTES);
1754         ifd->ifi_obytes = ifp->if_get_counter(ifp, IFCOUNTER_OBYTES);
1755         ifd->ifi_imcasts = ifp->if_get_counter(ifp, IFCOUNTER_IMCASTS);
1756         ifd->ifi_omcasts = ifp->if_get_counter(ifp, IFCOUNTER_OMCASTS);
1757         ifd->ifi_iqdrops = ifp->if_get_counter(ifp, IFCOUNTER_IQDROPS);
1758         ifd->ifi_oqdrops = ifp->if_get_counter(ifp, IFCOUNTER_OQDROPS);
1759         ifd->ifi_noproto = ifp->if_get_counter(ifp, IFCOUNTER_NOPROTO);
1760 }
1761
1762 struct ifnet_read_lock {
1763         struct mtx mtx; /* lock protecting tracker below */
1764         struct epoch_tracker et;
1765 };
1766
1767 DPCPU_DEFINE_STATIC(struct ifnet_read_lock, ifnet_addr_read_lock);
1768 DPCPU_DEFINE_STATIC(struct ifnet_read_lock, ifnet_maddr_read_lock);
1769
1770 static void
1771 ifnet_read_lock_init(void __unused *arg)
1772 {
1773         struct ifnet_read_lock *pifrl;
1774         int cpu;
1775
1776         CPU_FOREACH(cpu) {
1777                 pifrl = DPCPU_ID_PTR(cpu, ifnet_addr_read_lock);
1778                 mtx_init(&pifrl->mtx, "ifnet_addr_read_lock", NULL, MTX_DEF);
1779
1780                 pifrl = DPCPU_ID_PTR(cpu, ifnet_maddr_read_lock);
1781                 mtx_init(&pifrl->mtx, "ifnet_maddr_read_lock", NULL, MTX_DEF);
1782         }
1783 }
1784 SYSINIT(ifnet_read_lock_init, SI_SUB_CPU + 1, SI_ORDER_FIRST, &ifnet_read_lock_init, NULL);
1785
1786 /*
1787  * Wrapper functions for struct ifnet address list locking macros.  These are
1788  * used by kernel modules to avoid encoding programming interface or binary
1789  * interface assumptions that may be violated when kernel-internal locking
1790  * approaches change.
1791  */
1792 void
1793 if_addr_rlock(struct ifnet *ifp)
1794 {
1795         struct ifnet_read_lock *pifrl;
1796
1797         sched_pin();
1798         pifrl = DPCPU_PTR(ifnet_addr_read_lock);
1799         mtx_lock(&pifrl->mtx);
1800         epoch_enter_preempt(net_epoch_preempt, &pifrl->et);
1801 }
1802
1803 void
1804 if_addr_runlock(struct ifnet *ifp)
1805 {
1806         struct ifnet_read_lock *pifrl;
1807
1808         pifrl = DPCPU_PTR(ifnet_addr_read_lock);
1809
1810         epoch_exit_preempt(net_epoch_preempt, &pifrl->et);
1811         mtx_unlock(&pifrl->mtx);
1812         sched_unpin();
1813 }
1814
1815 void
1816 if_maddr_rlock(if_t ifp)
1817 {
1818         struct ifnet_read_lock *pifrl;
1819
1820         sched_pin();
1821         pifrl = DPCPU_PTR(ifnet_maddr_read_lock);
1822         mtx_lock(&pifrl->mtx);
1823         epoch_enter_preempt(net_epoch_preempt, &pifrl->et);
1824 }
1825
1826 void
1827 if_maddr_runlock(if_t ifp)
1828 {
1829         struct ifnet_read_lock *pifrl;
1830
1831         pifrl = DPCPU_PTR(ifnet_maddr_read_lock);
1832
1833         epoch_exit_preempt(net_epoch_preempt, &pifrl->et);
1834         mtx_unlock(&pifrl->mtx);
1835         sched_unpin();
1836 }
1837
1838 /*
1839  * Initialization, destruction and refcounting functions for ifaddrs.
1840  */
1841 struct ifaddr *
1842 ifa_alloc(size_t size, int flags)
1843 {
1844         struct ifaddr *ifa;
1845
1846         KASSERT(size >= sizeof(struct ifaddr),
1847             ("%s: invalid size %zu", __func__, size));
1848
1849         ifa = malloc(size, M_IFADDR, M_ZERO | flags);
1850         if (ifa == NULL)
1851                 return (NULL);
1852
1853         if ((ifa->ifa_opackets = counter_u64_alloc(flags)) == NULL)
1854                 goto fail;
1855         if ((ifa->ifa_ipackets = counter_u64_alloc(flags)) == NULL)
1856                 goto fail;
1857         if ((ifa->ifa_obytes = counter_u64_alloc(flags)) == NULL)
1858                 goto fail;
1859         if ((ifa->ifa_ibytes = counter_u64_alloc(flags)) == NULL)
1860                 goto fail;
1861
1862         refcount_init(&ifa->ifa_refcnt, 1);
1863
1864         return (ifa);
1865
1866 fail:
1867         /* free(NULL) is okay */
1868         counter_u64_free(ifa->ifa_opackets);
1869         counter_u64_free(ifa->ifa_ipackets);
1870         counter_u64_free(ifa->ifa_obytes);
1871         counter_u64_free(ifa->ifa_ibytes);
1872         free(ifa, M_IFADDR);
1873
1874         return (NULL);
1875 }
1876
1877 void
1878 ifa_ref(struct ifaddr *ifa)
1879 {
1880
1881         refcount_acquire(&ifa->ifa_refcnt);
1882 }
1883
1884 static void
1885 ifa_destroy(epoch_context_t ctx)
1886 {
1887         struct ifaddr *ifa;
1888
1889         ifa = __containerof(ctx, struct ifaddr, ifa_epoch_ctx);
1890         counter_u64_free(ifa->ifa_opackets);
1891         counter_u64_free(ifa->ifa_ipackets);
1892         counter_u64_free(ifa->ifa_obytes);
1893         counter_u64_free(ifa->ifa_ibytes);
1894         free(ifa, M_IFADDR);
1895 }
1896
1897 void
1898 ifa_free(struct ifaddr *ifa)
1899 {
1900
1901         if (refcount_release(&ifa->ifa_refcnt))
1902                 epoch_call(net_epoch_preempt, &ifa->ifa_epoch_ctx, ifa_destroy);
1903 }
1904
1905
1906 static int
1907 ifa_maintain_loopback_route(int cmd, const char *otype, struct ifaddr *ifa,
1908     struct sockaddr *ia)
1909 {
1910         int error;
1911         struct rt_addrinfo info;
1912         struct sockaddr_dl null_sdl;
1913         struct ifnet *ifp;
1914
1915         ifp = ifa->ifa_ifp;
1916
1917         bzero(&info, sizeof(info));
1918         if (cmd != RTM_DELETE)
1919                 info.rti_ifp = V_loif;
1920         info.rti_flags = ifa->ifa_flags | RTF_HOST | RTF_STATIC | RTF_PINNED;
1921         info.rti_info[RTAX_DST] = ia;
1922         info.rti_info[RTAX_GATEWAY] = (struct sockaddr *)&null_sdl;
1923         link_init_sdl(ifp, (struct sockaddr *)&null_sdl, ifp->if_type);
1924
1925         error = rtrequest1_fib(cmd, &info, NULL, ifp->if_fib);
1926
1927         if (error == 0 ||
1928             (cmd == RTM_ADD && error == EEXIST) ||
1929             (cmd == RTM_DELETE && (error == ENOENT || error == ESRCH)))
1930                 return (error);
1931
1932         log(LOG_DEBUG, "%s: %s failed for interface %s: %u\n",
1933                 __func__, otype, if_name(ifp), error);
1934
1935         return (error);
1936 }
1937
1938 int
1939 ifa_add_loopback_route(struct ifaddr *ifa, struct sockaddr *ia)
1940 {
1941
1942         return (ifa_maintain_loopback_route(RTM_ADD, "insertion", ifa, ia));
1943 }
1944
1945 int
1946 ifa_del_loopback_route(struct ifaddr *ifa, struct sockaddr *ia)
1947 {
1948
1949         return (ifa_maintain_loopback_route(RTM_DELETE, "deletion", ifa, ia));
1950 }
1951
1952 int
1953 ifa_switch_loopback_route(struct ifaddr *ifa, struct sockaddr *ia)
1954 {
1955
1956         return (ifa_maintain_loopback_route(RTM_CHANGE, "switch", ifa, ia));
1957 }
1958
1959 /*
1960  * XXX: Because sockaddr_dl has deeper structure than the sockaddr
1961  * structs used to represent other address families, it is necessary
1962  * to perform a different comparison.
1963  */
1964
1965 #define sa_dl_equal(a1, a2)     \
1966         ((((const struct sockaddr_dl *)(a1))->sdl_len ==                \
1967          ((const struct sockaddr_dl *)(a2))->sdl_len) &&                \
1968          (bcmp(CLLADDR((const struct sockaddr_dl *)(a1)),               \
1969                CLLADDR((const struct sockaddr_dl *)(a2)),               \
1970                ((const struct sockaddr_dl *)(a1))->sdl_alen) == 0))
1971
1972 /*
1973  * Locate an interface based on a complete address.
1974  */
1975 /*ARGSUSED*/
1976 struct ifaddr *
1977 ifa_ifwithaddr(const struct sockaddr *addr)
1978 {
1979         struct ifnet *ifp;
1980         struct ifaddr *ifa;
1981
1982         MPASS(in_epoch(net_epoch_preempt));
1983         CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
1984                 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1985                         if (ifa->ifa_addr->sa_family != addr->sa_family)
1986                                 continue;
1987                         if (sa_equal(addr, ifa->ifa_addr)) {
1988                                 goto done;
1989                         }
1990                         /* IP6 doesn't have broadcast */
1991                         if ((ifp->if_flags & IFF_BROADCAST) &&
1992                             ifa->ifa_broadaddr &&
1993                             ifa->ifa_broadaddr->sa_len != 0 &&
1994                             sa_equal(ifa->ifa_broadaddr, addr)) {
1995                                 goto done;
1996                         }
1997                 }
1998         }
1999         ifa = NULL;
2000 done:
2001         return (ifa);
2002 }
2003
2004 int
2005 ifa_ifwithaddr_check(const struct sockaddr *addr)
2006 {
2007         int rc;
2008
2009         NET_EPOCH_ENTER();
2010         rc = (ifa_ifwithaddr(addr) != NULL);
2011         NET_EPOCH_EXIT();
2012         return (rc);
2013 }
2014
2015 /*
2016  * Locate an interface based on the broadcast address.
2017  */
2018 /* ARGSUSED */
2019 struct ifaddr *
2020 ifa_ifwithbroadaddr(const struct sockaddr *addr, int fibnum)
2021 {
2022         struct ifnet *ifp;
2023         struct ifaddr *ifa;
2024
2025         MPASS(in_epoch(net_epoch_preempt));
2026         CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2027                 if ((fibnum != RT_ALL_FIBS) && (ifp->if_fib != fibnum))
2028                         continue;
2029                 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
2030                         if (ifa->ifa_addr->sa_family != addr->sa_family)
2031                                 continue;
2032                         if ((ifp->if_flags & IFF_BROADCAST) &&
2033                             ifa->ifa_broadaddr &&
2034                             ifa->ifa_broadaddr->sa_len != 0 &&
2035                             sa_equal(ifa->ifa_broadaddr, addr)) {
2036                                 goto done;
2037                         }
2038                 }
2039         }
2040         ifa = NULL;
2041 done:
2042         return (ifa);
2043 }
2044
2045 /*
2046  * Locate the point to point interface with a given destination address.
2047  */
2048 /*ARGSUSED*/
2049 struct ifaddr *
2050 ifa_ifwithdstaddr(const struct sockaddr *addr, int fibnum)
2051 {
2052         struct ifnet *ifp;
2053         struct ifaddr *ifa;
2054
2055         MPASS(in_epoch(net_epoch_preempt));
2056         CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2057                 if ((ifp->if_flags & IFF_POINTOPOINT) == 0)
2058                         continue;
2059                 if ((fibnum != RT_ALL_FIBS) && (ifp->if_fib != fibnum))
2060                         continue;
2061                 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
2062                         if (ifa->ifa_addr->sa_family != addr->sa_family)
2063                                 continue;
2064                         if (ifa->ifa_dstaddr != NULL &&
2065                             sa_equal(addr, ifa->ifa_dstaddr)) {
2066                                 goto done;
2067                         }
2068                 }
2069         }
2070         ifa = NULL;
2071 done:
2072         return (ifa);
2073 }
2074
2075 /*
2076  * Find an interface on a specific network.  If many, choice
2077  * is most specific found.
2078  */
2079 struct ifaddr *
2080 ifa_ifwithnet(const struct sockaddr *addr, int ignore_ptp, int fibnum)
2081 {
2082         struct ifnet *ifp;
2083         struct ifaddr *ifa;
2084         struct ifaddr *ifa_maybe = NULL;
2085         u_int af = addr->sa_family;
2086         const char *addr_data = addr->sa_data, *cplim;
2087
2088         MPASS(in_epoch(net_epoch_preempt));
2089         /*
2090          * AF_LINK addresses can be looked up directly by their index number,
2091          * so do that if we can.
2092          */
2093         if (af == AF_LINK) {
2094             const struct sockaddr_dl *sdl = (const struct sockaddr_dl *)addr;
2095             if (sdl->sdl_index && sdl->sdl_index <= V_if_index)
2096                 return (ifaddr_byindex(sdl->sdl_index));
2097         }
2098
2099         /*
2100          * Scan though each interface, looking for ones that have addresses
2101          * in this address family and the requested fib.  Maintain a reference
2102          * on ifa_maybe once we find one, as we release the IF_ADDR_RLOCK() that
2103          * kept it stable when we move onto the next interface.
2104          */
2105         CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2106                 if ((fibnum != RT_ALL_FIBS) && (ifp->if_fib != fibnum))
2107                         continue;
2108                 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
2109                         const char *cp, *cp2, *cp3;
2110
2111                         if (ifa->ifa_addr->sa_family != af)
2112 next:                           continue;
2113                         if (af == AF_INET && 
2114                             ifp->if_flags & IFF_POINTOPOINT && !ignore_ptp) {
2115                                 /*
2116                                  * This is a bit broken as it doesn't
2117                                  * take into account that the remote end may
2118                                  * be a single node in the network we are
2119                                  * looking for.
2120                                  * The trouble is that we don't know the
2121                                  * netmask for the remote end.
2122                                  */
2123                                 if (ifa->ifa_dstaddr != NULL &&
2124                                     sa_equal(addr, ifa->ifa_dstaddr)) {
2125                                         goto done;
2126                                 }
2127                         } else {
2128                                 /*
2129                                  * Scan all the bits in the ifa's address.
2130                                  * If a bit dissagrees with what we are
2131                                  * looking for, mask it with the netmask
2132                                  * to see if it really matters.
2133                                  * (A byte at a time)
2134                                  */
2135                                 if (ifa->ifa_netmask == 0)
2136                                         continue;
2137                                 cp = addr_data;
2138                                 cp2 = ifa->ifa_addr->sa_data;
2139                                 cp3 = ifa->ifa_netmask->sa_data;
2140                                 cplim = ifa->ifa_netmask->sa_len
2141                                         + (char *)ifa->ifa_netmask;
2142                                 while (cp3 < cplim)
2143                                         if ((*cp++ ^ *cp2++) & *cp3++)
2144                                                 goto next; /* next address! */
2145                                 /*
2146                                  * If the netmask of what we just found
2147                                  * is more specific than what we had before
2148                                  * (if we had one), or if the virtual status
2149                                  * of new prefix is better than of the old one,
2150                                  * then remember the new one before continuing
2151                                  * to search for an even better one.
2152                                  */
2153                                 if (ifa_maybe == NULL ||
2154                                     ifa_preferred(ifa_maybe, ifa) ||
2155                                     rn_refines((caddr_t)ifa->ifa_netmask,
2156                                     (caddr_t)ifa_maybe->ifa_netmask)) {
2157                                         ifa_maybe = ifa;
2158                                 }
2159                         }
2160                 }
2161         }
2162         ifa = ifa_maybe;
2163         ifa_maybe = NULL;
2164 done:
2165         return (ifa);
2166 }
2167
2168 /*
2169  * Find an interface address specific to an interface best matching
2170  * a given address.
2171  */
2172 struct ifaddr *
2173 ifaof_ifpforaddr(const struct sockaddr *addr, struct ifnet *ifp)
2174 {
2175         struct ifaddr *ifa;
2176         const char *cp, *cp2, *cp3;
2177         char *cplim;
2178         struct ifaddr *ifa_maybe = NULL;
2179         u_int af = addr->sa_family;
2180
2181         if (af >= AF_MAX)
2182                 return (NULL);
2183
2184         MPASS(in_epoch(net_epoch_preempt));
2185         CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
2186                 if (ifa->ifa_addr->sa_family != af)
2187                         continue;
2188                 if (ifa_maybe == NULL)
2189                         ifa_maybe = ifa;
2190                 if (ifa->ifa_netmask == 0) {
2191                         if (sa_equal(addr, ifa->ifa_addr) ||
2192                             (ifa->ifa_dstaddr &&
2193                             sa_equal(addr, ifa->ifa_dstaddr)))
2194                                 goto done;
2195                         continue;
2196                 }
2197                 if (ifp->if_flags & IFF_POINTOPOINT) {
2198                         if (sa_equal(addr, ifa->ifa_dstaddr))
2199                                 goto done;
2200                 } else {
2201                         cp = addr->sa_data;
2202                         cp2 = ifa->ifa_addr->sa_data;
2203                         cp3 = ifa->ifa_netmask->sa_data;
2204                         cplim = ifa->ifa_netmask->sa_len + (char *)ifa->ifa_netmask;
2205                         for (; cp3 < cplim; cp3++)
2206                                 if ((*cp++ ^ *cp2++) & *cp3)
2207                                         break;
2208                         if (cp3 == cplim)
2209                                 goto done;
2210                 }
2211         }
2212         ifa = ifa_maybe;
2213 done:
2214         return (ifa);
2215 }
2216
2217 /*
2218  * See whether new ifa is better than current one:
2219  * 1) A non-virtual one is preferred over virtual.
2220  * 2) A virtual in master state preferred over any other state.
2221  *
2222  * Used in several address selecting functions.
2223  */
2224 int
2225 ifa_preferred(struct ifaddr *cur, struct ifaddr *next)
2226 {
2227
2228         return (cur->ifa_carp && (!next->ifa_carp ||
2229             ((*carp_master_p)(next) && !(*carp_master_p)(cur))));
2230 }
2231
2232 #include <net/if_llatbl.h>
2233
2234 /*
2235  * Default action when installing a route with a Link Level gateway.
2236  * Lookup an appropriate real ifa to point to.
2237  * This should be moved to /sys/net/link.c eventually.
2238  */
2239 static void
2240 link_rtrequest(int cmd, struct rtentry *rt, struct rt_addrinfo *info)
2241 {
2242         struct ifaddr *ifa, *oifa;
2243         struct sockaddr *dst;
2244         struct ifnet *ifp;
2245
2246         if (cmd != RTM_ADD || ((ifa = rt->rt_ifa) == NULL) ||
2247             ((ifp = ifa->ifa_ifp) == NULL) || ((dst = rt_key(rt)) == NULL))
2248                 return;
2249         NET_EPOCH_ENTER();
2250         ifa = ifaof_ifpforaddr(dst, ifp);
2251         if (ifa) {
2252                 oifa = rt->rt_ifa;
2253                 if (oifa != ifa) {
2254                         ifa_free(oifa);
2255                         ifa_ref(ifa);
2256                 }
2257                 rt->rt_ifa = ifa;
2258                 if (ifa->ifa_rtrequest && ifa->ifa_rtrequest != link_rtrequest)
2259                         ifa->ifa_rtrequest(cmd, rt, info);
2260         }
2261         NET_EPOCH_EXIT();
2262 }
2263
2264 struct sockaddr_dl *
2265 link_alloc_sdl(size_t size, int flags)
2266 {
2267
2268         return (malloc(size, M_TEMP, flags));
2269 }
2270
2271 void
2272 link_free_sdl(struct sockaddr *sa)
2273 {
2274         free(sa, M_TEMP);
2275 }
2276
2277 /*
2278  * Fills in given sdl with interface basic info.
2279  * Returns pointer to filled sdl.
2280  */
2281 struct sockaddr_dl *
2282 link_init_sdl(struct ifnet *ifp, struct sockaddr *paddr, u_char iftype)
2283 {
2284         struct sockaddr_dl *sdl;
2285
2286         sdl = (struct sockaddr_dl *)paddr;
2287         memset(sdl, 0, sizeof(struct sockaddr_dl));
2288         sdl->sdl_len = sizeof(struct sockaddr_dl);
2289         sdl->sdl_family = AF_LINK;
2290         sdl->sdl_index = ifp->if_index;
2291         sdl->sdl_type = iftype;
2292
2293         return (sdl);
2294 }
2295
2296 /*
2297  * Mark an interface down and notify protocols of
2298  * the transition.
2299  */
2300 static void
2301 if_unroute(struct ifnet *ifp, int flag, int fam)
2302 {
2303         struct ifaddr *ifa;
2304
2305         KASSERT(flag == IFF_UP, ("if_unroute: flag != IFF_UP"));
2306
2307         ifp->if_flags &= ~flag;
2308         getmicrotime(&ifp->if_lastchange);
2309         CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
2310                 if (fam == PF_UNSPEC || (fam == ifa->ifa_addr->sa_family))
2311                         pfctlinput(PRC_IFDOWN, ifa->ifa_addr);
2312         ifp->if_qflush(ifp);
2313
2314         if (ifp->if_carp)
2315                 (*carp_linkstate_p)(ifp);
2316         rt_ifmsg(ifp);
2317 }
2318
2319 /*
2320  * Mark an interface up and notify protocols of
2321  * the transition.
2322  */
2323 static void
2324 if_route(struct ifnet *ifp, int flag, int fam)
2325 {
2326         struct ifaddr *ifa;
2327
2328         KASSERT(flag == IFF_UP, ("if_route: flag != IFF_UP"));
2329
2330         ifp->if_flags |= flag;
2331         getmicrotime(&ifp->if_lastchange);
2332         CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
2333                 if (fam == PF_UNSPEC || (fam == ifa->ifa_addr->sa_family))
2334                         pfctlinput(PRC_IFUP, ifa->ifa_addr);
2335         if (ifp->if_carp)
2336                 (*carp_linkstate_p)(ifp);
2337         rt_ifmsg(ifp);
2338 #ifdef INET6
2339         in6_if_up(ifp);
2340 #endif
2341 }
2342
2343 void    (*vlan_link_state_p)(struct ifnet *);   /* XXX: private from if_vlan */
2344 void    (*vlan_trunk_cap_p)(struct ifnet *);            /* XXX: private from if_vlan */
2345 struct ifnet *(*vlan_trunkdev_p)(struct ifnet *);
2346 struct  ifnet *(*vlan_devat_p)(struct ifnet *, uint16_t);
2347 int     (*vlan_tag_p)(struct ifnet *, uint16_t *);
2348 int     (*vlan_pcp_p)(struct ifnet *, uint16_t *);
2349 int     (*vlan_setcookie_p)(struct ifnet *, void *);
2350 void    *(*vlan_cookie_p)(struct ifnet *);
2351
2352 /*
2353  * Handle a change in the interface link state. To avoid LORs
2354  * between driver lock and upper layer locks, as well as possible
2355  * recursions, we post event to taskqueue, and all job
2356  * is done in static do_link_state_change().
2357  */
2358 void
2359 if_link_state_change(struct ifnet *ifp, int link_state)
2360 {
2361         /* Return if state hasn't changed. */
2362         if (ifp->if_link_state == link_state)
2363                 return;
2364
2365         ifp->if_link_state = link_state;
2366
2367         taskqueue_enqueue(taskqueue_swi, &ifp->if_linktask);
2368 }
2369
2370 static void
2371 do_link_state_change(void *arg, int pending)
2372 {
2373         struct ifnet *ifp = (struct ifnet *)arg;
2374         int link_state = ifp->if_link_state;
2375         CURVNET_SET(ifp->if_vnet);
2376
2377         /* Notify that the link state has changed. */
2378         rt_ifmsg(ifp);
2379         if (ifp->if_vlantrunk != NULL)
2380                 (*vlan_link_state_p)(ifp);
2381
2382         if ((ifp->if_type == IFT_ETHER || ifp->if_type == IFT_L2VLAN) &&
2383             ifp->if_l2com != NULL)
2384                 (*ng_ether_link_state_p)(ifp, link_state);
2385         if (ifp->if_carp)
2386                 (*carp_linkstate_p)(ifp);
2387         if (ifp->if_bridge)
2388                 ifp->if_bridge_linkstate(ifp);
2389         if (ifp->if_lagg)
2390                 (*lagg_linkstate_p)(ifp, link_state);
2391
2392         if (IS_DEFAULT_VNET(curvnet))
2393                 devctl_notify("IFNET", ifp->if_xname,
2394                     (link_state == LINK_STATE_UP) ? "LINK_UP" : "LINK_DOWN",
2395                     NULL);
2396         if (pending > 1)
2397                 if_printf(ifp, "%d link states coalesced\n", pending);
2398         if (log_link_state_change)
2399                 if_printf(ifp, "link state changed to %s\n",
2400                     (link_state == LINK_STATE_UP) ? "UP" : "DOWN" );
2401         EVENTHANDLER_INVOKE(ifnet_link_event, ifp, link_state);
2402         CURVNET_RESTORE();
2403 }
2404
2405 /*
2406  * Mark an interface down and notify protocols of
2407  * the transition.
2408  */
2409 void
2410 if_down(struct ifnet *ifp)
2411 {
2412
2413         EVENTHANDLER_INVOKE(ifnet_event, ifp, IFNET_EVENT_DOWN);
2414         if_unroute(ifp, IFF_UP, AF_UNSPEC);
2415 }
2416
2417 /*
2418  * Mark an interface up and notify protocols of
2419  * the transition.
2420  */
2421 void
2422 if_up(struct ifnet *ifp)
2423 {
2424
2425         if_route(ifp, IFF_UP, AF_UNSPEC);
2426         EVENTHANDLER_INVOKE(ifnet_event, ifp, IFNET_EVENT_UP);
2427 }
2428
2429 /*
2430  * Flush an interface queue.
2431  */
2432 void
2433 if_qflush(struct ifnet *ifp)
2434 {
2435         struct mbuf *m, *n;
2436         struct ifaltq *ifq;
2437         
2438         ifq = &ifp->if_snd;
2439         IFQ_LOCK(ifq);
2440 #ifdef ALTQ
2441         if (ALTQ_IS_ENABLED(ifq))
2442                 ALTQ_PURGE(ifq);
2443 #endif
2444         n = ifq->ifq_head;
2445         while ((m = n) != NULL) {
2446                 n = m->m_nextpkt;
2447                 m_freem(m);
2448         }
2449         ifq->ifq_head = 0;
2450         ifq->ifq_tail = 0;
2451         ifq->ifq_len = 0;
2452         IFQ_UNLOCK(ifq);
2453 }
2454
2455 /*
2456  * Map interface name to interface structure pointer, with or without
2457  * returning a reference.
2458  */
2459 struct ifnet *
2460 ifunit_ref(const char *name)
2461 {
2462         struct ifnet *ifp;
2463
2464         IFNET_RLOCK_NOSLEEP();
2465         CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2466                 if (strncmp(name, ifp->if_xname, IFNAMSIZ) == 0 &&
2467                     !(ifp->if_flags & IFF_DYING))
2468                         break;
2469         }
2470         if (ifp != NULL)
2471                 if_ref(ifp);
2472         IFNET_RUNLOCK_NOSLEEP();
2473         return (ifp);
2474 }
2475
2476 struct ifnet *
2477 ifunit(const char *name)
2478 {
2479         struct ifnet *ifp;
2480
2481         IFNET_RLOCK_NOSLEEP();
2482         CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2483                 if (strncmp(name, ifp->if_xname, IFNAMSIZ) == 0)
2484                         break;
2485         }
2486         IFNET_RUNLOCK_NOSLEEP();
2487         return (ifp);
2488 }
2489
2490 void *
2491 ifr_buffer_get_buffer(void *data)
2492 {
2493         union ifreq_union *ifrup;
2494
2495         ifrup = data;
2496 #ifdef COMPAT_FREEBSD32
2497         if (SV_CURPROC_FLAG(SV_ILP32))
2498                 return ((void *)(uintptr_t)
2499                     ifrup->ifr32.ifr_ifru.ifru_buffer.buffer);
2500 #endif
2501         return (ifrup->ifr.ifr_ifru.ifru_buffer.buffer);
2502 }
2503
2504 static void
2505 ifr_buffer_set_buffer_null(void *data)
2506 {
2507         union ifreq_union *ifrup;
2508
2509         ifrup = data;
2510 #ifdef COMPAT_FREEBSD32
2511         if (SV_CURPROC_FLAG(SV_ILP32))
2512                 ifrup->ifr32.ifr_ifru.ifru_buffer.buffer = 0;
2513         else
2514 #endif
2515                 ifrup->ifr.ifr_ifru.ifru_buffer.buffer = NULL;
2516 }
2517
2518 size_t
2519 ifr_buffer_get_length(void *data)
2520 {
2521         union ifreq_union *ifrup;
2522
2523         ifrup = data;
2524 #ifdef COMPAT_FREEBSD32
2525         if (SV_CURPROC_FLAG(SV_ILP32))
2526                 return (ifrup->ifr32.ifr_ifru.ifru_buffer.length);
2527 #endif
2528         return (ifrup->ifr.ifr_ifru.ifru_buffer.length);
2529 }
2530
2531 static void
2532 ifr_buffer_set_length(void *data, size_t len)
2533 {
2534         union ifreq_union *ifrup;
2535
2536         ifrup = data;
2537 #ifdef COMPAT_FREEBSD32
2538         if (SV_CURPROC_FLAG(SV_ILP32))
2539                 ifrup->ifr32.ifr_ifru.ifru_buffer.length = len;
2540         else
2541 #endif
2542                 ifrup->ifr.ifr_ifru.ifru_buffer.length = len;
2543 }
2544
2545 void *
2546 ifr_data_get_ptr(void *ifrp)
2547 {
2548         union ifreq_union *ifrup;
2549
2550         ifrup = ifrp;
2551 #ifdef COMPAT_FREEBSD32
2552         if (SV_CURPROC_FLAG(SV_ILP32))
2553                 return ((void *)(uintptr_t)
2554                     ifrup->ifr32.ifr_ifru.ifru_data);
2555 #endif
2556                 return (ifrup->ifr.ifr_ifru.ifru_data);
2557 }
2558
2559 /*
2560  * Hardware specific interface ioctls.
2561  */
2562 int
2563 ifhwioctl(u_long cmd, struct ifnet *ifp, caddr_t data, struct thread *td)
2564 {
2565         struct ifreq *ifr;
2566         int error = 0, do_ifup = 0;
2567         int new_flags, temp_flags;
2568         size_t namelen, onamelen;
2569         size_t descrlen;
2570         char *descrbuf, *odescrbuf;
2571         char new_name[IFNAMSIZ];
2572         struct ifaddr *ifa;
2573         struct sockaddr_dl *sdl;
2574
2575         ifr = (struct ifreq *)data;
2576         switch (cmd) {
2577         case SIOCGIFINDEX:
2578                 ifr->ifr_index = ifp->if_index;
2579                 break;
2580
2581         case SIOCGIFFLAGS:
2582                 temp_flags = ifp->if_flags | ifp->if_drv_flags;
2583                 ifr->ifr_flags = temp_flags & 0xffff;
2584                 ifr->ifr_flagshigh = temp_flags >> 16;
2585                 break;
2586
2587         case SIOCGIFCAP:
2588                 ifr->ifr_reqcap = ifp->if_capabilities;
2589                 ifr->ifr_curcap = ifp->if_capenable;
2590                 break;
2591
2592 #ifdef MAC
2593         case SIOCGIFMAC:
2594                 error = mac_ifnet_ioctl_get(td->td_ucred, ifr, ifp);
2595                 break;
2596 #endif
2597
2598         case SIOCGIFMETRIC:
2599                 ifr->ifr_metric = ifp->if_metric;
2600                 break;
2601
2602         case SIOCGIFMTU:
2603                 ifr->ifr_mtu = ifp->if_mtu;
2604                 break;
2605
2606         case SIOCGIFPHYS:
2607                 /* XXXGL: did this ever worked? */
2608                 ifr->ifr_phys = 0;
2609                 break;
2610
2611         case SIOCGIFDESCR:
2612                 error = 0;
2613                 sx_slock(&ifdescr_sx);
2614                 if (ifp->if_description == NULL)
2615                         error = ENOMSG;
2616                 else {
2617                         /* space for terminating nul */
2618                         descrlen = strlen(ifp->if_description) + 1;
2619                         if (ifr_buffer_get_length(ifr) < descrlen)
2620                                 ifr_buffer_set_buffer_null(ifr);
2621                         else
2622                                 error = copyout(ifp->if_description,
2623                                     ifr_buffer_get_buffer(ifr), descrlen);
2624                         ifr_buffer_set_length(ifr, descrlen);
2625                 }
2626                 sx_sunlock(&ifdescr_sx);
2627                 break;
2628
2629         case SIOCSIFDESCR:
2630                 error = priv_check(td, PRIV_NET_SETIFDESCR);
2631                 if (error)
2632                         return (error);
2633
2634                 /*
2635                  * Copy only (length-1) bytes to make sure that
2636                  * if_description is always nul terminated.  The
2637                  * length parameter is supposed to count the
2638                  * terminating nul in.
2639                  */
2640                 if (ifr_buffer_get_length(ifr) > ifdescr_maxlen)
2641                         return (ENAMETOOLONG);
2642                 else if (ifr_buffer_get_length(ifr) == 0)
2643                         descrbuf = NULL;
2644                 else {
2645                         descrbuf = malloc(ifr_buffer_get_length(ifr),
2646                             M_IFDESCR, M_WAITOK | M_ZERO);
2647                         error = copyin(ifr_buffer_get_buffer(ifr), descrbuf,
2648                             ifr_buffer_get_length(ifr) - 1);
2649                         if (error) {
2650                                 free(descrbuf, M_IFDESCR);
2651                                 break;
2652                         }
2653                 }
2654
2655                 sx_xlock(&ifdescr_sx);
2656                 odescrbuf = ifp->if_description;
2657                 ifp->if_description = descrbuf;
2658                 sx_xunlock(&ifdescr_sx);
2659
2660                 getmicrotime(&ifp->if_lastchange);
2661                 free(odescrbuf, M_IFDESCR);
2662                 break;
2663
2664         case SIOCGIFFIB:
2665                 ifr->ifr_fib = ifp->if_fib;
2666                 break;
2667
2668         case SIOCSIFFIB:
2669                 error = priv_check(td, PRIV_NET_SETIFFIB);
2670                 if (error)
2671                         return (error);
2672                 if (ifr->ifr_fib >= rt_numfibs)
2673                         return (EINVAL);
2674
2675                 ifp->if_fib = ifr->ifr_fib;
2676                 break;
2677
2678         case SIOCSIFFLAGS:
2679                 error = priv_check(td, PRIV_NET_SETIFFLAGS);
2680                 if (error)
2681                         return (error);
2682                 /*
2683                  * Currently, no driver owned flags pass the IFF_CANTCHANGE
2684                  * check, so we don't need special handling here yet.
2685                  */
2686                 new_flags = (ifr->ifr_flags & 0xffff) |
2687                     (ifr->ifr_flagshigh << 16);
2688                 if (ifp->if_flags & IFF_UP &&
2689                     (new_flags & IFF_UP) == 0) {
2690                         if_down(ifp);
2691                 } else if (new_flags & IFF_UP &&
2692                     (ifp->if_flags & IFF_UP) == 0) {
2693                         do_ifup = 1;
2694                 }
2695                 /* See if permanently promiscuous mode bit is about to flip */
2696                 if ((ifp->if_flags ^ new_flags) & IFF_PPROMISC) {
2697                         if (new_flags & IFF_PPROMISC)
2698                                 ifp->if_flags |= IFF_PROMISC;
2699                         else if (ifp->if_pcount == 0)
2700                                 ifp->if_flags &= ~IFF_PROMISC;
2701                         if (log_promisc_mode_change)
2702                                 if_printf(ifp, "permanently promiscuous mode %s\n",
2703                                     ((new_flags & IFF_PPROMISC) ?
2704                                      "enabled" : "disabled"));
2705                 }
2706                 ifp->if_flags = (ifp->if_flags & IFF_CANTCHANGE) |
2707                         (new_flags &~ IFF_CANTCHANGE);
2708                 if (ifp->if_ioctl) {
2709                         (void) (*ifp->if_ioctl)(ifp, cmd, data);
2710                 }
2711                 if (do_ifup)
2712                         if_up(ifp);
2713                 getmicrotime(&ifp->if_lastchange);
2714                 break;
2715
2716         case SIOCSIFCAP:
2717                 error = priv_check(td, PRIV_NET_SETIFCAP);
2718                 if (error)
2719                         return (error);
2720                 if (ifp->if_ioctl == NULL)
2721                         return (EOPNOTSUPP);
2722                 if (ifr->ifr_reqcap & ~ifp->if_capabilities)
2723                         return (EINVAL);
2724                 error = (*ifp->if_ioctl)(ifp, cmd, data);
2725                 if (error == 0)
2726                         getmicrotime(&ifp->if_lastchange);
2727                 break;
2728
2729 #ifdef MAC
2730         case SIOCSIFMAC:
2731                 error = mac_ifnet_ioctl_set(td->td_ucred, ifr, ifp);
2732                 break;
2733 #endif
2734
2735         case SIOCSIFNAME:
2736                 error = priv_check(td, PRIV_NET_SETIFNAME);
2737                 if (error)
2738                         return (error);
2739                 error = copyinstr(ifr_data_get_ptr(ifr), new_name, IFNAMSIZ,
2740                     NULL);
2741                 if (error != 0)
2742                         return (error);
2743                 if (new_name[0] == '\0')
2744                         return (EINVAL);
2745                 if (new_name[IFNAMSIZ-1] != '\0') {
2746                         new_name[IFNAMSIZ-1] = '\0';
2747                         if (strlen(new_name) == IFNAMSIZ-1)
2748                                 return (EINVAL);
2749                 }
2750                 if (strcmp(new_name, ifp->if_xname) == 0)
2751                         break;
2752                 if (ifunit(new_name) != NULL)
2753                         return (EEXIST);
2754
2755                 /*
2756                  * XXX: Locking.  Nothing else seems to lock if_flags,
2757                  * and there are numerous other races with the
2758                  * ifunit() checks not being atomic with namespace
2759                  * changes (renames, vmoves, if_attach, etc).
2760                  */
2761                 ifp->if_flags |= IFF_RENAMING;
2762                 
2763                 /* Announce the departure of the interface. */
2764                 rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
2765                 EVENTHANDLER_INVOKE(ifnet_departure_event, ifp);
2766
2767                 if_printf(ifp, "changing name to '%s'\n", new_name);
2768
2769                 IF_ADDR_WLOCK(ifp);
2770                 strlcpy(ifp->if_xname, new_name, sizeof(ifp->if_xname));
2771                 ifa = ifp->if_addr;
2772                 sdl = (struct sockaddr_dl *)ifa->ifa_addr;
2773                 namelen = strlen(new_name);
2774                 onamelen = sdl->sdl_nlen;
2775                 /*
2776                  * Move the address if needed.  This is safe because we
2777                  * allocate space for a name of length IFNAMSIZ when we
2778                  * create this in if_attach().
2779                  */
2780                 if (namelen != onamelen) {
2781                         bcopy(sdl->sdl_data + onamelen,
2782                             sdl->sdl_data + namelen, sdl->sdl_alen);
2783                 }
2784                 bcopy(new_name, sdl->sdl_data, namelen);
2785                 sdl->sdl_nlen = namelen;
2786                 sdl = (struct sockaddr_dl *)ifa->ifa_netmask;
2787                 bzero(sdl->sdl_data, onamelen);
2788                 while (namelen != 0)
2789                         sdl->sdl_data[--namelen] = 0xff;
2790                 IF_ADDR_WUNLOCK(ifp);
2791
2792                 EVENTHANDLER_INVOKE(ifnet_arrival_event, ifp);
2793                 /* Announce the return of the interface. */
2794                 rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
2795
2796                 ifp->if_flags &= ~IFF_RENAMING;
2797                 break;
2798
2799 #ifdef VIMAGE
2800         case SIOCSIFVNET:
2801                 error = priv_check(td, PRIV_NET_SETIFVNET);
2802                 if (error)
2803                         return (error);
2804                 error = if_vmove_loan(td, ifp, ifr->ifr_name, ifr->ifr_jid);
2805                 break;
2806 #endif
2807
2808         case SIOCSIFMETRIC:
2809                 error = priv_check(td, PRIV_NET_SETIFMETRIC);
2810                 if (error)
2811                         return (error);
2812                 ifp->if_metric = ifr->ifr_metric;
2813                 getmicrotime(&ifp->if_lastchange);
2814                 break;
2815
2816         case SIOCSIFPHYS:
2817                 error = priv_check(td, PRIV_NET_SETIFPHYS);
2818                 if (error)
2819                         return (error);
2820                 if (ifp->if_ioctl == NULL)
2821                         return (EOPNOTSUPP);
2822                 error = (*ifp->if_ioctl)(ifp, cmd, data);
2823                 if (error == 0)
2824                         getmicrotime(&ifp->if_lastchange);
2825                 break;
2826
2827         case SIOCSIFMTU:
2828         {
2829                 u_long oldmtu = ifp->if_mtu;
2830
2831                 error = priv_check(td, PRIV_NET_SETIFMTU);
2832                 if (error)
2833                         return (error);
2834                 if (ifr->ifr_mtu < IF_MINMTU || ifr->ifr_mtu > IF_MAXMTU)
2835                         return (EINVAL);
2836                 if (ifp->if_ioctl == NULL)
2837                         return (EOPNOTSUPP);
2838                 error = (*ifp->if_ioctl)(ifp, cmd, data);
2839                 if (error == 0) {
2840                         getmicrotime(&ifp->if_lastchange);
2841                         rt_ifmsg(ifp);
2842 #ifdef INET
2843                         NETDUMP_REINIT(ifp);
2844 #endif
2845                 }
2846                 /*
2847                  * If the link MTU changed, do network layer specific procedure.
2848                  */
2849                 if (ifp->if_mtu != oldmtu) {
2850 #ifdef INET6
2851                         nd6_setmtu(ifp);
2852 #endif
2853                         rt_updatemtu(ifp);
2854                 }
2855                 break;
2856         }
2857
2858         case SIOCADDMULTI:
2859         case SIOCDELMULTI:
2860                 if (cmd == SIOCADDMULTI)
2861                         error = priv_check(td, PRIV_NET_ADDMULTI);
2862                 else
2863                         error = priv_check(td, PRIV_NET_DELMULTI);
2864                 if (error)
2865                         return (error);
2866
2867                 /* Don't allow group membership on non-multicast interfaces. */
2868                 if ((ifp->if_flags & IFF_MULTICAST) == 0)
2869                         return (EOPNOTSUPP);
2870
2871                 /* Don't let users screw up protocols' entries. */
2872                 if (ifr->ifr_addr.sa_family != AF_LINK)
2873                         return (EINVAL);
2874
2875                 if (cmd == SIOCADDMULTI) {
2876                         struct ifmultiaddr *ifma;
2877
2878                         /*
2879                          * Userland is only permitted to join groups once
2880                          * via the if_addmulti() KPI, because it cannot hold
2881                          * struct ifmultiaddr * between calls. It may also
2882                          * lose a race while we check if the membership
2883                          * already exists.
2884                          */
2885                         IF_ADDR_RLOCK(ifp);
2886                         ifma = if_findmulti(ifp, &ifr->ifr_addr);
2887                         IF_ADDR_RUNLOCK(ifp);
2888                         if (ifma != NULL)
2889                                 error = EADDRINUSE;
2890                         else
2891                                 error = if_addmulti(ifp, &ifr->ifr_addr, &ifma);
2892                 } else {
2893                         error = if_delmulti(ifp, &ifr->ifr_addr);
2894                 }
2895                 if (error == 0)
2896                         getmicrotime(&ifp->if_lastchange);
2897                 break;
2898
2899         case SIOCSIFPHYADDR:
2900         case SIOCDIFPHYADDR:
2901 #ifdef INET6
2902         case SIOCSIFPHYADDR_IN6:
2903 #endif
2904         case SIOCSIFMEDIA:
2905         case SIOCSIFGENERIC:
2906                 error = priv_check(td, PRIV_NET_HWIOCTL);
2907                 if (error)
2908                         return (error);
2909                 if (ifp->if_ioctl == NULL)
2910                         return (EOPNOTSUPP);
2911                 error = (*ifp->if_ioctl)(ifp, cmd, data);
2912                 if (error == 0)
2913                         getmicrotime(&ifp->if_lastchange);
2914                 break;
2915
2916         case SIOCGIFSTATUS:
2917         case SIOCGIFPSRCADDR:
2918         case SIOCGIFPDSTADDR:
2919         case SIOCGIFMEDIA:
2920         case SIOCGIFXMEDIA:
2921         case SIOCGIFGENERIC:
2922         case SIOCGIFRSSKEY:
2923         case SIOCGIFRSSHASH:
2924         case SIOCGIFDOWNREASON:
2925                 if (ifp->if_ioctl == NULL)
2926                         return (EOPNOTSUPP);
2927                 error = (*ifp->if_ioctl)(ifp, cmd, data);
2928                 break;
2929
2930         case SIOCSIFLLADDR:
2931                 error = priv_check(td, PRIV_NET_SETLLADDR);
2932                 if (error)
2933                         return (error);
2934                 error = if_setlladdr(ifp,
2935                     ifr->ifr_addr.sa_data, ifr->ifr_addr.sa_len);
2936                 break;
2937
2938         case SIOCGHWADDR:
2939                 error = if_gethwaddr(ifp, ifr);
2940                 break;
2941
2942         case CASE_IOC_IFGROUPREQ(SIOCAIFGROUP):
2943                 error = priv_check(td, PRIV_NET_ADDIFGROUP);
2944                 if (error)
2945                         return (error);
2946                 if ((error = if_addgroup(ifp,
2947                     ifgr_group_get((struct ifgroupreq *)data))))
2948                         return (error);
2949                 break;
2950
2951         case CASE_IOC_IFGROUPREQ(SIOCGIFGROUP):
2952                 if ((error = if_getgroup((struct ifgroupreq *)data, ifp)))
2953                         return (error);
2954                 break;
2955
2956         case CASE_IOC_IFGROUPREQ(SIOCDIFGROUP):
2957                 error = priv_check(td, PRIV_NET_DELIFGROUP);
2958                 if (error)
2959                         return (error);
2960                 if ((error = if_delgroup(ifp,
2961                     ifgr_group_get((struct ifgroupreq *)data))))
2962                         return (error);
2963                 break;
2964
2965         default:
2966                 error = ENOIOCTL;
2967                 break;
2968         }
2969         return (error);
2970 }
2971
2972 #ifdef COMPAT_FREEBSD32
2973 struct ifconf32 {
2974         int32_t ifc_len;
2975         union {
2976                 uint32_t        ifcu_buf;
2977                 uint32_t        ifcu_req;
2978         } ifc_ifcu;
2979 };
2980 #define SIOCGIFCONF32   _IOWR('i', 36, struct ifconf32)
2981 #endif
2982
2983 #ifdef COMPAT_FREEBSD32
2984 static void
2985 ifmr_init(struct ifmediareq *ifmr, caddr_t data)
2986 {
2987         struct ifmediareq32 *ifmr32;
2988
2989         ifmr32 = (struct ifmediareq32 *)data;
2990         memcpy(ifmr->ifm_name, ifmr32->ifm_name,
2991             sizeof(ifmr->ifm_name));
2992         ifmr->ifm_current = ifmr32->ifm_current;
2993         ifmr->ifm_mask = ifmr32->ifm_mask;
2994         ifmr->ifm_status = ifmr32->ifm_status;
2995         ifmr->ifm_active = ifmr32->ifm_active;
2996         ifmr->ifm_count = ifmr32->ifm_count;
2997         ifmr->ifm_ulist = (int *)(uintptr_t)ifmr32->ifm_ulist;
2998 }
2999
3000 static void
3001 ifmr_update(const struct ifmediareq *ifmr, caddr_t data)
3002 {
3003         struct ifmediareq32 *ifmr32;
3004
3005         ifmr32 = (struct ifmediareq32 *)data;
3006         ifmr32->ifm_current = ifmr->ifm_current;
3007         ifmr32->ifm_mask = ifmr->ifm_mask;
3008         ifmr32->ifm_status = ifmr->ifm_status;
3009         ifmr32->ifm_active = ifmr->ifm_active;
3010         ifmr32->ifm_count = ifmr->ifm_count;
3011 }
3012 #endif
3013
3014 /*
3015  * Interface ioctls.
3016  */
3017 int
3018 ifioctl(struct socket *so, u_long cmd, caddr_t data, struct thread *td)
3019 {
3020 #ifdef COMPAT_FREEBSD32
3021         caddr_t saved_data = NULL;
3022         struct ifmediareq ifmr;
3023         struct ifmediareq *ifmrp;
3024 #endif
3025         struct ifnet *ifp;
3026         struct ifreq *ifr;
3027         int error;
3028         int oif_flags;
3029 #ifdef VIMAGE
3030         int shutdown;
3031 #endif
3032
3033         CURVNET_SET(so->so_vnet);
3034 #ifdef VIMAGE
3035         /* Make sure the VNET is stable. */
3036         shutdown = (so->so_vnet->vnet_state > SI_SUB_VNET &&
3037                  so->so_vnet->vnet_state < SI_SUB_VNET_DONE) ? 1 : 0;
3038         if (shutdown) {
3039                 CURVNET_RESTORE();
3040                 return (EBUSY);
3041         }
3042 #endif
3043
3044
3045         switch (cmd) {
3046         case SIOCGIFCONF:
3047                 error = ifconf(cmd, data);
3048                 CURVNET_RESTORE();
3049                 return (error);
3050
3051 #ifdef COMPAT_FREEBSD32
3052         case SIOCGIFCONF32:
3053                 {
3054                         struct ifconf32 *ifc32;
3055                         struct ifconf ifc;
3056
3057                         ifc32 = (struct ifconf32 *)data;
3058                         ifc.ifc_len = ifc32->ifc_len;
3059                         ifc.ifc_buf = PTRIN(ifc32->ifc_buf);
3060
3061                         error = ifconf(SIOCGIFCONF, (void *)&ifc);
3062                         CURVNET_RESTORE();
3063                         if (error == 0)
3064                                 ifc32->ifc_len = ifc.ifc_len;
3065                         return (error);
3066                 }
3067 #endif
3068         }
3069
3070 #ifdef COMPAT_FREEBSD32
3071         ifmrp = NULL;
3072         switch (cmd) {
3073         case SIOCGIFMEDIA32:
3074         case SIOCGIFXMEDIA32:
3075                 ifmrp = &ifmr;
3076                 ifmr_init(ifmrp, data);
3077                 cmd = _IOC_NEWTYPE(cmd, struct ifmediareq);
3078                 saved_data = data;
3079                 data = (caddr_t)ifmrp;
3080         }
3081 #endif
3082
3083         ifr = (struct ifreq *)data;
3084         switch (cmd) {
3085 #ifdef VIMAGE
3086         case SIOCSIFRVNET:
3087                 error = priv_check(td, PRIV_NET_SETIFVNET);
3088                 if (error == 0)
3089                         error = if_vmove_reclaim(td, ifr->ifr_name,
3090                             ifr->ifr_jid);
3091                 goto out_noref;
3092 #endif
3093         case SIOCIFCREATE:
3094         case SIOCIFCREATE2:
3095                 error = priv_check(td, PRIV_NET_IFCREATE);
3096                 if (error == 0)
3097                         error = if_clone_create(ifr->ifr_name,
3098                             sizeof(ifr->ifr_name), cmd == SIOCIFCREATE2 ?
3099                             ifr_data_get_ptr(ifr) : NULL);
3100                 goto out_noref;
3101         case SIOCIFDESTROY:
3102                 error = priv_check(td, PRIV_NET_IFDESTROY);
3103                 if (error == 0)
3104                         error = if_clone_destroy(ifr->ifr_name);
3105                 goto out_noref;
3106
3107         case SIOCIFGCLONERS:
3108                 error = if_clone_list((struct if_clonereq *)data);
3109                 goto out_noref;
3110
3111         case CASE_IOC_IFGROUPREQ(SIOCGIFGMEMB):
3112                 error = if_getgroupmembers((struct ifgroupreq *)data);
3113                 goto out_noref;
3114
3115 #if defined(INET) || defined(INET6)
3116         case SIOCSVH:
3117         case SIOCGVH:
3118                 if (carp_ioctl_p == NULL)
3119                         error = EPROTONOSUPPORT;
3120                 else
3121                         error = (*carp_ioctl_p)(ifr, cmd, td);
3122                 goto out_noref;
3123 #endif
3124         }
3125
3126         ifp = ifunit_ref(ifr->ifr_name);
3127         if (ifp == NULL) {
3128                 error = ENXIO;
3129                 goto out_noref;
3130         }
3131
3132         error = ifhwioctl(cmd, ifp, data, td);
3133         if (error != ENOIOCTL)
3134                 goto out_ref;
3135
3136         oif_flags = ifp->if_flags;
3137         if (so->so_proto == NULL) {
3138                 error = EOPNOTSUPP;
3139                 goto out_ref;
3140         }
3141
3142         /*
3143          * Pass the request on to the socket control method, and if the
3144          * latter returns EOPNOTSUPP, directly to the interface.
3145          *
3146          * Make an exception for the legacy SIOCSIF* requests.  Drivers
3147          * trust SIOCSIFADDR et al to come from an already privileged
3148          * layer, and do not perform any credentials checks or input
3149          * validation.
3150          */
3151         error = ((*so->so_proto->pr_usrreqs->pru_control)(so, cmd, data,
3152             ifp, td));
3153         if (error == EOPNOTSUPP && ifp != NULL && ifp->if_ioctl != NULL &&
3154             cmd != SIOCSIFADDR && cmd != SIOCSIFBRDADDR &&
3155             cmd != SIOCSIFDSTADDR && cmd != SIOCSIFNETMASK)
3156                 error = (*ifp->if_ioctl)(ifp, cmd, data);
3157
3158         if ((oif_flags ^ ifp->if_flags) & IFF_UP) {
3159 #ifdef INET6
3160                 if (ifp->if_flags & IFF_UP)
3161                         in6_if_up(ifp);
3162 #endif
3163         }
3164
3165 out_ref:
3166         if_rele(ifp);
3167 out_noref:
3168 #ifdef COMPAT_FREEBSD32
3169         if (ifmrp != NULL) {
3170                 KASSERT((cmd == SIOCGIFMEDIA || cmd == SIOCGIFXMEDIA),
3171                     ("ifmrp non-NULL, but cmd is not an ifmedia req 0x%lx",
3172                      cmd));
3173                 data = saved_data;
3174                 ifmr_update(ifmrp, data);
3175         }
3176 #endif
3177         CURVNET_RESTORE();
3178         return (error);
3179 }
3180
3181 /*
3182  * The code common to handling reference counted flags,
3183  * e.g., in ifpromisc() and if_allmulti().
3184  * The "pflag" argument can specify a permanent mode flag to check,
3185  * such as IFF_PPROMISC for promiscuous mode; should be 0 if none.
3186  *
3187  * Only to be used on stack-owned flags, not driver-owned flags.
3188  */
3189 static int
3190 if_setflag(struct ifnet *ifp, int flag, int pflag, int *refcount, int onswitch)
3191 {
3192         struct ifreq ifr;
3193         int error;
3194         int oldflags, oldcount;
3195
3196         /* Sanity checks to catch programming errors */
3197         KASSERT((flag & (IFF_DRV_OACTIVE|IFF_DRV_RUNNING)) == 0,
3198             ("%s: setting driver-owned flag %d", __func__, flag));
3199
3200         if (onswitch)
3201                 KASSERT(*refcount >= 0,
3202                     ("%s: increment negative refcount %d for flag %d",
3203                     __func__, *refcount, flag));
3204         else
3205                 KASSERT(*refcount > 0,
3206                     ("%s: decrement non-positive refcount %d for flag %d",
3207                     __func__, *refcount, flag));
3208
3209         /* In case this mode is permanent, just touch refcount */
3210         if (ifp->if_flags & pflag) {
3211                 *refcount += onswitch ? 1 : -1;
3212                 return (0);
3213         }
3214
3215         /* Save ifnet parameters for if_ioctl() may fail */
3216         oldcount = *refcount;
3217         oldflags = ifp->if_flags;
3218         
3219         /*
3220          * See if we aren't the only and touching refcount is enough.
3221          * Actually toggle interface flag if we are the first or last.
3222          */
3223         if (onswitch) {
3224                 if ((*refcount)++)
3225                         return (0);
3226                 ifp->if_flags |= flag;
3227         } else {
3228                 if (--(*refcount))
3229                         return (0);
3230                 ifp->if_flags &= ~flag;
3231         }
3232
3233         /* Call down the driver since we've changed interface flags */
3234         if (ifp->if_ioctl == NULL) {
3235                 error = EOPNOTSUPP;
3236                 goto recover;
3237         }
3238         ifr.ifr_flags = ifp->if_flags & 0xffff;
3239         ifr.ifr_flagshigh = ifp->if_flags >> 16;
3240         error = (*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
3241         if (error)
3242                 goto recover;
3243         /* Notify userland that interface flags have changed */
3244         rt_ifmsg(ifp);
3245         return (0);
3246
3247 recover:
3248         /* Recover after driver error */
3249         *refcount = oldcount;
3250         ifp->if_flags = oldflags;
3251         return (error);
3252 }
3253
3254 /*
3255  * Set/clear promiscuous mode on interface ifp based on the truth value
3256  * of pswitch.  The calls are reference counted so that only the first
3257  * "on" request actually has an effect, as does the final "off" request.
3258  * Results are undefined if the "off" and "on" requests are not matched.
3259  */
3260 int
3261 ifpromisc(struct ifnet *ifp, int pswitch)
3262 {
3263         int error;
3264         int oldflags = ifp->if_flags;
3265
3266         error = if_setflag(ifp, IFF_PROMISC, IFF_PPROMISC,
3267                            &ifp->if_pcount, pswitch);
3268         /* If promiscuous mode status has changed, log a message */
3269         if (error == 0 && ((ifp->if_flags ^ oldflags) & IFF_PROMISC) &&
3270             log_promisc_mode_change)
3271                 if_printf(ifp, "promiscuous mode %s\n",
3272                     (ifp->if_flags & IFF_PROMISC) ? "enabled" : "disabled");
3273         return (error);
3274 }
3275
3276 /*
3277  * Return interface configuration
3278  * of system.  List may be used
3279  * in later ioctl's (above) to get
3280  * other information.
3281  */
3282 /*ARGSUSED*/
3283 static int
3284 ifconf(u_long cmd, caddr_t data)
3285 {
3286         struct ifconf *ifc = (struct ifconf *)data;
3287         struct ifnet *ifp;
3288         struct ifaddr *ifa;
3289         struct ifreq ifr;
3290         struct sbuf *sb;
3291         int error, full = 0, valid_len, max_len;
3292
3293         /* Limit initial buffer size to MAXPHYS to avoid DoS from userspace. */
3294         max_len = MAXPHYS - 1;
3295
3296         /* Prevent hostile input from being able to crash the system */
3297         if (ifc->ifc_len <= 0)
3298                 return (EINVAL);
3299
3300 again:
3301         if (ifc->ifc_len <= max_len) {
3302                 max_len = ifc->ifc_len;
3303                 full = 1;
3304         }
3305         sb = sbuf_new(NULL, NULL, max_len + 1, SBUF_FIXEDLEN);
3306         max_len = 0;
3307         valid_len = 0;
3308
3309         IFNET_RLOCK();
3310         CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
3311                 int addrs;
3312
3313                 /*
3314                  * Zero the ifr to make sure we don't disclose the contents
3315                  * of the stack.
3316                  */
3317                 memset(&ifr, 0, sizeof(ifr));
3318
3319                 if (strlcpy(ifr.ifr_name, ifp->if_xname, sizeof(ifr.ifr_name))
3320                     >= sizeof(ifr.ifr_name)) {
3321                         sbuf_delete(sb);
3322                         IFNET_RUNLOCK();
3323                         return (ENAMETOOLONG);
3324                 }
3325
3326                 addrs = 0;
3327                 IF_ADDR_RLOCK(ifp);
3328                 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
3329                         struct sockaddr *sa = ifa->ifa_addr;
3330
3331                         if (prison_if(curthread->td_ucred, sa) != 0)
3332                                 continue;
3333                         addrs++;
3334                         if (sa->sa_len <= sizeof(*sa)) {
3335                                 if (sa->sa_len < sizeof(*sa)) {
3336                                         memset(&ifr.ifr_ifru.ifru_addr, 0,
3337                                             sizeof(ifr.ifr_ifru.ifru_addr));
3338                                         memcpy(&ifr.ifr_ifru.ifru_addr, sa,
3339                                             sa->sa_len);
3340                                 } else
3341                                         ifr.ifr_ifru.ifru_addr = *sa;
3342                                 sbuf_bcat(sb, &ifr, sizeof(ifr));
3343                                 max_len += sizeof(ifr);
3344                         } else {
3345                                 sbuf_bcat(sb, &ifr,
3346                                     offsetof(struct ifreq, ifr_addr));
3347                                 max_len += offsetof(struct ifreq, ifr_addr);
3348                                 sbuf_bcat(sb, sa, sa->sa_len);
3349                                 max_len += sa->sa_len;
3350                         }
3351
3352                         if (sbuf_error(sb) == 0)
3353                                 valid_len = sbuf_len(sb);
3354                 }
3355                 IF_ADDR_RUNLOCK(ifp);
3356                 if (addrs == 0) {
3357                         sbuf_bcat(sb, &ifr, sizeof(ifr));
3358                         max_len += sizeof(ifr);
3359
3360                         if (sbuf_error(sb) == 0)
3361                                 valid_len = sbuf_len(sb);
3362                 }
3363         }
3364         IFNET_RUNLOCK();
3365
3366         /*
3367          * If we didn't allocate enough space (uncommon), try again.  If
3368          * we have already allocated as much space as we are allowed,
3369          * return what we've got.
3370          */
3371         if (valid_len != max_len && !full) {
3372                 sbuf_delete(sb);
3373                 goto again;
3374         }
3375
3376         ifc->ifc_len = valid_len;
3377         sbuf_finish(sb);
3378         error = copyout(sbuf_data(sb), ifc->ifc_req, ifc->ifc_len);
3379         sbuf_delete(sb);
3380         return (error);
3381 }
3382
3383 /*
3384  * Just like ifpromisc(), but for all-multicast-reception mode.
3385  */
3386 int
3387 if_allmulti(struct ifnet *ifp, int onswitch)
3388 {
3389
3390         return (if_setflag(ifp, IFF_ALLMULTI, 0, &ifp->if_amcount, onswitch));
3391 }
3392
3393 struct ifmultiaddr *
3394 if_findmulti(struct ifnet *ifp, const struct sockaddr *sa)
3395 {
3396         struct ifmultiaddr *ifma;
3397
3398         IF_ADDR_LOCK_ASSERT(ifp);
3399
3400         CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
3401                 if (sa->sa_family == AF_LINK) {
3402                         if (sa_dl_equal(ifma->ifma_addr, sa))
3403                                 break;
3404                 } else {
3405                         if (sa_equal(ifma->ifma_addr, sa))
3406                                 break;
3407                 }
3408         }
3409
3410         return ifma;
3411 }
3412
3413 /*
3414  * Allocate a new ifmultiaddr and initialize based on passed arguments.  We
3415  * make copies of passed sockaddrs.  The ifmultiaddr will not be added to
3416  * the ifnet multicast address list here, so the caller must do that and
3417  * other setup work (such as notifying the device driver).  The reference
3418  * count is initialized to 1.
3419  */
3420 static struct ifmultiaddr *
3421 if_allocmulti(struct ifnet *ifp, struct sockaddr *sa, struct sockaddr *llsa,
3422     int mflags)
3423 {
3424         struct ifmultiaddr *ifma;
3425         struct sockaddr *dupsa;
3426
3427         ifma = malloc(sizeof *ifma, M_IFMADDR, mflags |
3428             M_ZERO);
3429         if (ifma == NULL)
3430                 return (NULL);
3431
3432         dupsa = malloc(sa->sa_len, M_IFMADDR, mflags);
3433         if (dupsa == NULL) {
3434                 free(ifma, M_IFMADDR);
3435                 return (NULL);
3436         }
3437         bcopy(sa, dupsa, sa->sa_len);
3438         ifma->ifma_addr = dupsa;
3439
3440         ifma->ifma_ifp = ifp;
3441         ifma->ifma_refcount = 1;
3442         ifma->ifma_protospec = NULL;
3443
3444         if (llsa == NULL) {
3445                 ifma->ifma_lladdr = NULL;
3446                 return (ifma);
3447         }
3448
3449         dupsa = malloc(llsa->sa_len, M_IFMADDR, mflags);
3450         if (dupsa == NULL) {
3451                 free(ifma->ifma_addr, M_IFMADDR);
3452                 free(ifma, M_IFMADDR);
3453                 return (NULL);
3454         }
3455         bcopy(llsa, dupsa, llsa->sa_len);
3456         ifma->ifma_lladdr = dupsa;
3457
3458         return (ifma);
3459 }
3460
3461 /*
3462  * if_freemulti: free ifmultiaddr structure and possibly attached related
3463  * addresses.  The caller is responsible for implementing reference
3464  * counting, notifying the driver, handling routing messages, and releasing
3465  * any dependent link layer state.
3466  */
3467 #ifdef MCAST_VERBOSE
3468 extern void kdb_backtrace(void);
3469 #endif
3470 static void
3471 if_freemulti_internal(struct ifmultiaddr *ifma)
3472 {
3473
3474         KASSERT(ifma->ifma_refcount == 0, ("if_freemulti: refcount %d",
3475             ifma->ifma_refcount));
3476
3477         if (ifma->ifma_lladdr != NULL)
3478                 free(ifma->ifma_lladdr, M_IFMADDR);
3479 #ifdef MCAST_VERBOSE
3480         kdb_backtrace();
3481         printf("%s freeing ifma: %p\n", __func__, ifma);
3482 #endif
3483         free(ifma->ifma_addr, M_IFMADDR);
3484         free(ifma, M_IFMADDR);
3485 }
3486
3487 static void
3488 if_destroymulti(epoch_context_t ctx)
3489 {
3490         struct ifmultiaddr *ifma;
3491
3492         ifma = __containerof(ctx, struct ifmultiaddr, ifma_epoch_ctx);
3493         if_freemulti_internal(ifma);
3494 }
3495
3496 void
3497 if_freemulti(struct ifmultiaddr *ifma)
3498 {
3499         KASSERT(ifma->ifma_refcount == 0, ("if_freemulti_epoch: refcount %d",
3500             ifma->ifma_refcount));
3501
3502         epoch_call(net_epoch_preempt, &ifma->ifma_epoch_ctx, if_destroymulti);
3503 }
3504
3505
3506 /*
3507  * Register an additional multicast address with a network interface.
3508  *
3509  * - If the address is already present, bump the reference count on the
3510  *   address and return.
3511  * - If the address is not link-layer, look up a link layer address.
3512  * - Allocate address structures for one or both addresses, and attach to the
3513  *   multicast address list on the interface.  If automatically adding a link
3514  *   layer address, the protocol address will own a reference to the link
3515  *   layer address, to be freed when it is freed.
3516  * - Notify the network device driver of an addition to the multicast address
3517  *   list.
3518  *
3519  * 'sa' points to caller-owned memory with the desired multicast address.
3520  *
3521  * 'retifma' will be used to return a pointer to the resulting multicast
3522  * address reference, if desired.
3523  */
3524 int
3525 if_addmulti(struct ifnet *ifp, struct sockaddr *sa,
3526     struct ifmultiaddr **retifma)
3527 {
3528         struct ifmultiaddr *ifma, *ll_ifma;
3529         struct sockaddr *llsa;
3530         struct sockaddr_dl sdl;
3531         int error;
3532
3533 #ifdef INET
3534         IN_MULTI_LIST_UNLOCK_ASSERT();
3535 #endif
3536 #ifdef INET6
3537         IN6_MULTI_LIST_UNLOCK_ASSERT();
3538 #endif
3539         /*
3540          * If the address is already present, return a new reference to it;
3541          * otherwise, allocate storage and set up a new address.
3542          */
3543         IF_ADDR_WLOCK(ifp);
3544         ifma = if_findmulti(ifp, sa);
3545         if (ifma != NULL) {
3546                 ifma->ifma_refcount++;
3547                 if (retifma != NULL)
3548                         *retifma = ifma;
3549                 IF_ADDR_WUNLOCK(ifp);
3550                 return (0);
3551         }
3552
3553         /*
3554          * The address isn't already present; resolve the protocol address
3555          * into a link layer address, and then look that up, bump its
3556          * refcount or allocate an ifma for that also.
3557          * Most link layer resolving functions returns address data which
3558          * fits inside default sockaddr_dl structure. However callback
3559          * can allocate another sockaddr structure, in that case we need to
3560          * free it later.
3561          */
3562         llsa = NULL;
3563         ll_ifma = NULL;
3564         if (ifp->if_resolvemulti != NULL) {
3565                 /* Provide called function with buffer size information */
3566                 sdl.sdl_len = sizeof(sdl);
3567                 llsa = (struct sockaddr *)&sdl;
3568                 error = ifp->if_resolvemulti(ifp, &llsa, sa);
3569                 if (error)
3570                         goto unlock_out;
3571         }
3572
3573         /*
3574          * Allocate the new address.  Don't hook it up yet, as we may also
3575          * need to allocate a link layer multicast address.
3576          */
3577         ifma = if_allocmulti(ifp, sa, llsa, M_NOWAIT);
3578         if (ifma == NULL) {
3579                 error = ENOMEM;
3580                 goto free_llsa_out;
3581         }
3582
3583         /*
3584          * If a link layer address is found, we'll need to see if it's
3585          * already present in the address list, or allocate is as well.
3586          * When this block finishes, the link layer address will be on the
3587          * list.
3588          */
3589         if (llsa != NULL) {
3590                 ll_ifma = if_findmulti(ifp, llsa);
3591                 if (ll_ifma == NULL) {
3592                         ll_ifma = if_allocmulti(ifp, llsa, NULL, M_NOWAIT);
3593                         if (ll_ifma == NULL) {
3594                                 --ifma->ifma_refcount;
3595                                 if_freemulti(ifma);
3596                                 error = ENOMEM;
3597                                 goto free_llsa_out;
3598                         }
3599                         ll_ifma->ifma_flags |= IFMA_F_ENQUEUED;
3600                         CK_STAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ll_ifma,
3601                             ifma_link);
3602                 } else
3603                         ll_ifma->ifma_refcount++;
3604                 ifma->ifma_llifma = ll_ifma;
3605         }
3606
3607         /*
3608          * We now have a new multicast address, ifma, and possibly a new or
3609          * referenced link layer address.  Add the primary address to the
3610          * ifnet address list.
3611          */
3612         ifma->ifma_flags |= IFMA_F_ENQUEUED;
3613         CK_STAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ifma, ifma_link);
3614
3615         if (retifma != NULL)
3616                 *retifma = ifma;
3617
3618         /*
3619          * Must generate the message while holding the lock so that 'ifma'
3620          * pointer is still valid.
3621          */
3622         rt_newmaddrmsg(RTM_NEWMADDR, ifma);
3623         IF_ADDR_WUNLOCK(ifp);
3624
3625         /*
3626          * We are certain we have added something, so call down to the
3627          * interface to let them know about it.
3628          */
3629         if (ifp->if_ioctl != NULL) {
3630                 (void) (*ifp->if_ioctl)(ifp, SIOCADDMULTI, 0);
3631         }
3632
3633         if ((llsa != NULL) && (llsa != (struct sockaddr *)&sdl))
3634                 link_free_sdl(llsa);
3635
3636         return (0);
3637
3638 free_llsa_out:
3639         if ((llsa != NULL) && (llsa != (struct sockaddr *)&sdl))
3640                 link_free_sdl(llsa);
3641
3642 unlock_out:
3643         IF_ADDR_WUNLOCK(ifp);
3644         return (error);
3645 }
3646
3647 /*
3648  * Delete a multicast group membership by network-layer group address.
3649  *
3650  * Returns ENOENT if the entry could not be found. If ifp no longer
3651  * exists, results are undefined. This entry point should only be used
3652  * from subsystems which do appropriate locking to hold ifp for the
3653  * duration of the call.
3654  * Network-layer protocol domains must use if_delmulti_ifma().
3655  */
3656 int
3657 if_delmulti(struct ifnet *ifp, struct sockaddr *sa)
3658 {
3659         struct ifmultiaddr *ifma;
3660         int lastref;
3661 #ifdef INVARIANTS
3662         struct ifnet *oifp;
3663
3664         IFNET_RLOCK_NOSLEEP();
3665         CK_STAILQ_FOREACH(oifp, &V_ifnet, if_link)
3666                 if (ifp == oifp)
3667                         break;
3668         if (ifp != oifp)
3669                 ifp = NULL;
3670         IFNET_RUNLOCK_NOSLEEP();
3671
3672         KASSERT(ifp != NULL, ("%s: ifnet went away", __func__));
3673 #endif
3674         if (ifp == NULL)
3675                 return (ENOENT);
3676
3677         IF_ADDR_WLOCK(ifp);
3678         lastref = 0;
3679         ifma = if_findmulti(ifp, sa);
3680         if (ifma != NULL)
3681                 lastref = if_delmulti_locked(ifp, ifma, 0);
3682         IF_ADDR_WUNLOCK(ifp);
3683
3684         if (ifma == NULL)
3685                 return (ENOENT);
3686
3687         if (lastref && ifp->if_ioctl != NULL) {
3688                 (void)(*ifp->if_ioctl)(ifp, SIOCDELMULTI, 0);
3689         }
3690
3691         return (0);
3692 }
3693
3694 /*
3695  * Delete all multicast group membership for an interface.
3696  * Should be used to quickly flush all multicast filters.
3697  */
3698 void
3699 if_delallmulti(struct ifnet *ifp)
3700 {
3701         struct ifmultiaddr *ifma;
3702         struct ifmultiaddr *next;
3703
3704         IF_ADDR_WLOCK(ifp);
3705         CK_STAILQ_FOREACH_SAFE(ifma, &ifp->if_multiaddrs, ifma_link, next)
3706                 if_delmulti_locked(ifp, ifma, 0);
3707         IF_ADDR_WUNLOCK(ifp);
3708 }
3709
3710 void
3711 if_delmulti_ifma(struct ifmultiaddr *ifma)
3712 {
3713         if_delmulti_ifma_flags(ifma, 0);
3714 }
3715
3716 /*
3717  * Delete a multicast group membership by group membership pointer.
3718  * Network-layer protocol domains must use this routine.
3719  *
3720  * It is safe to call this routine if the ifp disappeared.
3721  */
3722 void
3723 if_delmulti_ifma_flags(struct ifmultiaddr *ifma, int flags)
3724 {
3725         struct ifnet *ifp;
3726         int lastref;
3727         MCDPRINTF("%s freeing ifma: %p\n", __func__, ifma);
3728 #ifdef INET
3729         IN_MULTI_LIST_UNLOCK_ASSERT();
3730 #endif
3731         ifp = ifma->ifma_ifp;
3732 #ifdef DIAGNOSTIC
3733         if (ifp == NULL) {
3734                 printf("%s: ifma_ifp seems to be detached\n", __func__);
3735         } else {
3736                 struct ifnet *oifp;
3737
3738                 IFNET_RLOCK_NOSLEEP();
3739                 CK_STAILQ_FOREACH(oifp, &V_ifnet, if_link)
3740                         if (ifp == oifp)
3741                                 break;
3742                 if (ifp != oifp)
3743                         ifp = NULL;
3744                 IFNET_RUNLOCK_NOSLEEP();
3745         }
3746 #endif
3747         /*
3748          * If and only if the ifnet instance exists: Acquire the address lock.
3749          */
3750         if (ifp != NULL)
3751                 IF_ADDR_WLOCK(ifp);
3752
3753         lastref = if_delmulti_locked(ifp, ifma, flags);
3754
3755         if (ifp != NULL) {
3756                 /*
3757                  * If and only if the ifnet instance exists:
3758                  *  Release the address lock.
3759                  *  If the group was left: update the hardware hash filter.
3760                  */
3761                 IF_ADDR_WUNLOCK(ifp);
3762                 if (lastref && ifp->if_ioctl != NULL) {
3763                         (void)(*ifp->if_ioctl)(ifp, SIOCDELMULTI, 0);
3764                 }
3765         }
3766 }
3767
3768 /*
3769  * Perform deletion of network-layer and/or link-layer multicast address.
3770  *
3771  * Return 0 if the reference count was decremented.
3772  * Return 1 if the final reference was released, indicating that the
3773  * hardware hash filter should be reprogrammed.
3774  */
3775 static int
3776 if_delmulti_locked(struct ifnet *ifp, struct ifmultiaddr *ifma, int detaching)
3777 {
3778         struct ifmultiaddr *ll_ifma;
3779
3780         if (ifp != NULL && ifma->ifma_ifp != NULL) {
3781                 KASSERT(ifma->ifma_ifp == ifp,
3782                     ("%s: inconsistent ifp %p", __func__, ifp));
3783                 IF_ADDR_WLOCK_ASSERT(ifp);
3784         }
3785
3786         ifp = ifma->ifma_ifp;
3787         MCDPRINTF("%s freeing %p from %s \n", __func__, ifma, ifp ? ifp->if_xname : "");
3788
3789         /*
3790          * If the ifnet is detaching, null out references to ifnet,
3791          * so that upper protocol layers will notice, and not attempt
3792          * to obtain locks for an ifnet which no longer exists. The
3793          * routing socket announcement must happen before the ifnet
3794          * instance is detached from the system.
3795          */
3796         if (detaching) {
3797 #ifdef DIAGNOSTIC
3798                 printf("%s: detaching ifnet instance %p\n", __func__, ifp);
3799 #endif
3800                 /*
3801                  * ifp may already be nulled out if we are being reentered
3802                  * to delete the ll_ifma.
3803                  */
3804                 if (ifp != NULL) {
3805                         rt_newmaddrmsg(RTM_DELMADDR, ifma);
3806                         ifma->ifma_ifp = NULL;
3807                 }
3808         }
3809
3810         if (--ifma->ifma_refcount > 0)
3811                 return 0;
3812
3813         if (ifp != NULL && detaching == 0 && (ifma->ifma_flags & IFMA_F_ENQUEUED)) {
3814                 CK_STAILQ_REMOVE(&ifp->if_multiaddrs, ifma, ifmultiaddr, ifma_link);
3815                 ifma->ifma_flags &= ~IFMA_F_ENQUEUED;
3816         }
3817         /*
3818          * If this ifma is a network-layer ifma, a link-layer ifma may
3819          * have been associated with it. Release it first if so.
3820          */
3821         ll_ifma = ifma->ifma_llifma;
3822         if (ll_ifma != NULL) {
3823                 KASSERT(ifma->ifma_lladdr != NULL,
3824                     ("%s: llifma w/o lladdr", __func__));
3825                 if (detaching)
3826                         ll_ifma->ifma_ifp = NULL;       /* XXX */
3827                 if (--ll_ifma->ifma_refcount == 0) {
3828                         if (ifp != NULL) {
3829                                 if (ll_ifma->ifma_flags & IFMA_F_ENQUEUED) {
3830                                         CK_STAILQ_REMOVE(&ifp->if_multiaddrs, ll_ifma, ifmultiaddr,
3831                                                 ifma_link);
3832                                         ll_ifma->ifma_flags &= ~IFMA_F_ENQUEUED;
3833                                 }
3834                         }
3835                         if_freemulti(ll_ifma);
3836                 }
3837         }
3838 #ifdef INVARIANTS
3839         if (ifp) {
3840                 struct ifmultiaddr *ifmatmp;
3841
3842                 CK_STAILQ_FOREACH(ifmatmp, &ifp->if_multiaddrs, ifma_link)
3843                         MPASS(ifma != ifmatmp);
3844         }
3845 #endif
3846         if_freemulti(ifma);
3847         /*
3848          * The last reference to this instance of struct ifmultiaddr
3849          * was released; the hardware should be notified of this change.
3850          */
3851         return 1;
3852 }
3853
3854 /*
3855  * Set the link layer address on an interface.
3856  *
3857  * At this time we only support certain types of interfaces,
3858  * and we don't allow the length of the address to change.
3859  *
3860  * Set noinline to be dtrace-friendly
3861  */
3862 __noinline int
3863 if_setlladdr(struct ifnet *ifp, const u_char *lladdr, int len)
3864 {
3865         struct sockaddr_dl *sdl;
3866         struct ifaddr *ifa;
3867         struct ifreq ifr;
3868         int rc;
3869
3870         rc = 0;
3871         NET_EPOCH_ENTER();
3872         ifa = ifp->if_addr;
3873         if (ifa == NULL) {
3874                 rc = EINVAL;
3875                 goto out;
3876         }
3877
3878         sdl = (struct sockaddr_dl *)ifa->ifa_addr;
3879         if (sdl == NULL) {
3880                 rc = EINVAL;
3881                 goto out;
3882         }
3883         if (len != sdl->sdl_alen) {     /* don't allow length to change */
3884                 rc = EINVAL;
3885                 goto out;
3886         }
3887         switch (ifp->if_type) {
3888         case IFT_ETHER:
3889         case IFT_XETHER:
3890         case IFT_L2VLAN:
3891         case IFT_BRIDGE:
3892         case IFT_IEEE8023ADLAG:
3893                 bcopy(lladdr, LLADDR(sdl), len);
3894                 break;
3895         default:
3896                 rc = ENODEV;
3897                 goto out;
3898         }
3899
3900         /*
3901          * If the interface is already up, we need
3902          * to re-init it in order to reprogram its
3903          * address filter.
3904          */
3905         NET_EPOCH_EXIT();
3906         if ((ifp->if_flags & IFF_UP) != 0) {
3907                 if (ifp->if_ioctl) {
3908                         ifp->if_flags &= ~IFF_UP;
3909                         ifr.ifr_flags = ifp->if_flags & 0xffff;
3910                         ifr.ifr_flagshigh = ifp->if_flags >> 16;
3911                         (*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
3912                         ifp->if_flags |= IFF_UP;
3913                         ifr.ifr_flags = ifp->if_flags & 0xffff;
3914                         ifr.ifr_flagshigh = ifp->if_flags >> 16;
3915                         (*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
3916                 }
3917         }
3918         EVENTHANDLER_INVOKE(iflladdr_event, ifp);
3919         return (0);
3920  out:
3921         NET_EPOCH_EXIT();
3922         return (rc);
3923 }
3924
3925 /*
3926  * Compat function for handling basic encapsulation requests.
3927  * Not converted stacks (FDDI, IB, ..) supports traditional
3928  * output model: ARP (and other similar L2 protocols) are handled
3929  * inside output routine, arpresolve/nd6_resolve() returns MAC
3930  * address instead of full prepend.
3931  *
3932  * This function creates calculated header==MAC for IPv4/IPv6 and
3933  * returns EAFNOSUPPORT (which is then handled in ARP code) for other
3934  * address families.
3935  */
3936 static int
3937 if_requestencap_default(struct ifnet *ifp, struct if_encap_req *req)
3938 {
3939
3940         if (req->rtype != IFENCAP_LL)
3941                 return (EOPNOTSUPP);
3942
3943         if (req->bufsize < req->lladdr_len)
3944                 return (ENOMEM);
3945
3946         switch (req->family) {
3947         case AF_INET:
3948         case AF_INET6:
3949                 break;
3950         default:
3951                 return (EAFNOSUPPORT);
3952         }
3953
3954         /* Copy lladdr to storage as is */
3955         memmove(req->buf, req->lladdr, req->lladdr_len);
3956         req->bufsize = req->lladdr_len;
3957         req->lladdr_off = 0;
3958
3959         return (0);
3960 }
3961
3962 /*
3963  * Tunnel interfaces can nest, also they may cause infinite recursion
3964  * calls when misconfigured. We'll prevent this by detecting loops.
3965  * High nesting level may cause stack exhaustion. We'll prevent this
3966  * by introducing upper limit.
3967  *
3968  * Return 0, if tunnel nesting count is equal or less than limit.
3969  */
3970 int
3971 if_tunnel_check_nesting(struct ifnet *ifp, struct mbuf *m, uint32_t cookie,
3972     int limit)
3973 {
3974         struct m_tag *mtag;
3975         int count;
3976
3977         count = 1;
3978         mtag = NULL;
3979         while ((mtag = m_tag_locate(m, cookie, 0, mtag)) != NULL) {
3980                 if (*(struct ifnet **)(mtag + 1) == ifp) {
3981                         log(LOG_NOTICE, "%s: loop detected\n", if_name(ifp));
3982                         return (EIO);
3983                 }
3984                 count++;
3985         }
3986         if (count > limit) {
3987                 log(LOG_NOTICE,
3988                     "%s: if_output recursively called too many times(%d)\n",
3989                     if_name(ifp), count);
3990                 return (EIO);
3991         }
3992         mtag = m_tag_alloc(cookie, 0, sizeof(struct ifnet *), M_NOWAIT);
3993         if (mtag == NULL)
3994                 return (ENOMEM);
3995         *(struct ifnet **)(mtag + 1) = ifp;
3996         m_tag_prepend(m, mtag);
3997         return (0);
3998 }
3999
4000 /*
4001  * Get the link layer address that was read from the hardware at attach.
4002  *
4003  * This is only set by Ethernet NICs (IFT_ETHER), but laggX interfaces re-type
4004  * their component interfaces as IFT_IEEE8023ADLAG.
4005  */
4006 int
4007 if_gethwaddr(struct ifnet *ifp, struct ifreq *ifr)
4008 {
4009
4010         if (ifp->if_hw_addr == NULL)
4011                 return (ENODEV);
4012
4013         switch (ifp->if_type) {
4014         case IFT_ETHER:
4015         case IFT_IEEE8023ADLAG:
4016                 bcopy(ifp->if_hw_addr, ifr->ifr_addr.sa_data, ifp->if_addrlen);
4017                 return (0);
4018         default:
4019                 return (ENODEV);
4020         }
4021 }
4022
4023 /*
4024  * The name argument must be a pointer to storage which will last as
4025  * long as the interface does.  For physical devices, the result of
4026  * device_get_name(dev) is a good choice and for pseudo-devices a
4027  * static string works well.
4028  */
4029 void
4030 if_initname(struct ifnet *ifp, const char *name, int unit)
4031 {
4032         ifp->if_dname = name;
4033         ifp->if_dunit = unit;
4034         if (unit != IF_DUNIT_NONE)
4035                 snprintf(ifp->if_xname, IFNAMSIZ, "%s%d", name, unit);
4036         else
4037                 strlcpy(ifp->if_xname, name, IFNAMSIZ);
4038 }
4039
4040 int
4041 if_printf(struct ifnet *ifp, const char *fmt, ...)
4042 {
4043         char if_fmt[256];
4044         va_list ap;
4045
4046         snprintf(if_fmt, sizeof(if_fmt), "%s: %s", ifp->if_xname, fmt);
4047         va_start(ap, fmt);
4048         vlog(LOG_INFO, if_fmt, ap);
4049         va_end(ap);
4050         return (0);
4051 }
4052
4053 void
4054 if_start(struct ifnet *ifp)
4055 {
4056
4057         (*(ifp)->if_start)(ifp);
4058 }
4059
4060 /*
4061  * Backwards compatibility interface for drivers 
4062  * that have not implemented it
4063  */
4064 static int
4065 if_transmit(struct ifnet *ifp, struct mbuf *m)
4066 {
4067         int error;
4068
4069         IFQ_HANDOFF(ifp, m, error);
4070         return (error);
4071 }
4072
4073 static void
4074 if_input_default(struct ifnet *ifp __unused, struct mbuf *m)
4075 {
4076
4077         m_freem(m);
4078 }
4079
4080 int
4081 if_handoff(struct ifqueue *ifq, struct mbuf *m, struct ifnet *ifp, int adjust)
4082 {
4083         int active = 0;
4084
4085         IF_LOCK(ifq);
4086         if (_IF_QFULL(ifq)) {
4087                 IF_UNLOCK(ifq);
4088                 if_inc_counter(ifp, IFCOUNTER_OQDROPS, 1);
4089                 m_freem(m);
4090                 return (0);
4091         }
4092         if (ifp != NULL) {
4093                 if_inc_counter(ifp, IFCOUNTER_OBYTES, m->m_pkthdr.len + adjust);
4094                 if (m->m_flags & (M_BCAST|M_MCAST))
4095                         if_inc_counter(ifp, IFCOUNTER_OMCASTS, 1);
4096                 active = ifp->if_drv_flags & IFF_DRV_OACTIVE;
4097         }
4098         _IF_ENQUEUE(ifq, m);
4099         IF_UNLOCK(ifq);
4100         if (ifp != NULL && !active)
4101                 (*(ifp)->if_start)(ifp);
4102         return (1);
4103 }
4104
4105 void
4106 if_register_com_alloc(u_char type,
4107     if_com_alloc_t *a, if_com_free_t *f)
4108 {
4109         
4110         KASSERT(if_com_alloc[type] == NULL,
4111             ("if_register_com_alloc: %d already registered", type));
4112         KASSERT(if_com_free[type] == NULL,
4113             ("if_register_com_alloc: %d free already registered", type));
4114
4115         if_com_alloc[type] = a;
4116         if_com_free[type] = f;
4117 }
4118
4119 void
4120 if_deregister_com_alloc(u_char type)
4121 {
4122         
4123         KASSERT(if_com_alloc[type] != NULL,
4124             ("if_deregister_com_alloc: %d not registered", type));
4125         KASSERT(if_com_free[type] != NULL,
4126             ("if_deregister_com_alloc: %d free not registered", type));
4127         if_com_alloc[type] = NULL;
4128         if_com_free[type] = NULL;
4129 }
4130
4131 /* API for driver access to network stack owned ifnet.*/
4132 uint64_t
4133 if_setbaudrate(struct ifnet *ifp, uint64_t baudrate)
4134 {
4135         uint64_t oldbrate;
4136
4137         oldbrate = ifp->if_baudrate;
4138         ifp->if_baudrate = baudrate;
4139         return (oldbrate);
4140 }
4141
4142 uint64_t
4143 if_getbaudrate(if_t ifp)
4144 {
4145
4146         return (((struct ifnet *)ifp)->if_baudrate);
4147 }
4148
4149 int
4150 if_setcapabilities(if_t ifp, int capabilities)
4151 {
4152         ((struct ifnet *)ifp)->if_capabilities = capabilities;
4153         return (0);
4154 }
4155
4156 int
4157 if_setcapabilitiesbit(if_t ifp, int setbit, int clearbit)
4158 {
4159         ((struct ifnet *)ifp)->if_capabilities |= setbit;
4160         ((struct ifnet *)ifp)->if_capabilities &= ~clearbit;
4161
4162         return (0);
4163 }
4164
4165 int
4166 if_getcapabilities(if_t ifp)
4167 {
4168         return ((struct ifnet *)ifp)->if_capabilities;
4169 }
4170
4171 int 
4172 if_setcapenable(if_t ifp, int capabilities)
4173 {
4174         ((struct ifnet *)ifp)->if_capenable = capabilities;
4175         return (0);
4176 }
4177
4178 int 
4179 if_setcapenablebit(if_t ifp, int setcap, int clearcap)
4180 {
4181         if(setcap) 
4182                 ((struct ifnet *)ifp)->if_capenable |= setcap;
4183         if(clearcap)
4184                 ((struct ifnet *)ifp)->if_capenable &= ~clearcap;
4185
4186         return (0);
4187 }
4188
4189 const char *
4190 if_getdname(if_t ifp)
4191 {
4192         return ((struct ifnet *)ifp)->if_dname;
4193 }
4194
4195 int 
4196 if_togglecapenable(if_t ifp, int togglecap)
4197 {
4198         ((struct ifnet *)ifp)->if_capenable ^= togglecap;
4199         return (0);
4200 }
4201
4202 int
4203 if_getcapenable(if_t ifp)
4204 {
4205         return ((struct ifnet *)ifp)->if_capenable;
4206 }
4207
4208 /*
4209  * This is largely undesirable because it ties ifnet to a device, but does
4210  * provide flexiblity for an embedded product vendor. Should be used with
4211  * the understanding that it violates the interface boundaries, and should be
4212  * a last resort only.
4213  */
4214 int
4215 if_setdev(if_t ifp, void *dev)
4216 {
4217         return (0);
4218 }
4219
4220 int
4221 if_setdrvflagbits(if_t ifp, int set_flags, int clear_flags)
4222 {
4223         ((struct ifnet *)ifp)->if_drv_flags |= set_flags;
4224         ((struct ifnet *)ifp)->if_drv_flags &= ~clear_flags;
4225
4226         return (0);
4227 }
4228
4229 int
4230 if_getdrvflags(if_t ifp)
4231 {
4232         return ((struct ifnet *)ifp)->if_drv_flags;
4233 }
4234  
4235 int
4236 if_setdrvflags(if_t ifp, int flags)
4237 {
4238         ((struct ifnet *)ifp)->if_drv_flags = flags;
4239         return (0);
4240 }
4241
4242
4243 int
4244 if_setflags(if_t ifp, int flags)
4245 {
4246         ((struct ifnet *)ifp)->if_flags = flags;
4247         return (0);
4248 }
4249
4250 int
4251 if_setflagbits(if_t ifp, int set, int clear)
4252 {
4253         ((struct ifnet *)ifp)->if_flags |= set;
4254         ((struct ifnet *)ifp)->if_flags &= ~clear;
4255
4256         return (0);
4257 }
4258
4259 int
4260 if_getflags(if_t ifp)
4261 {
4262         return ((struct ifnet *)ifp)->if_flags;
4263 }
4264
4265 int
4266 if_clearhwassist(if_t ifp)
4267 {
4268         ((struct ifnet *)ifp)->if_hwassist = 0;
4269         return (0);
4270 }
4271
4272 int
4273 if_sethwassistbits(if_t ifp, int toset, int toclear)
4274 {
4275         ((struct ifnet *)ifp)->if_hwassist |= toset;
4276         ((struct ifnet *)ifp)->if_hwassist &= ~toclear;
4277
4278         return (0);
4279 }
4280
4281 int
4282 if_sethwassist(if_t ifp, int hwassist_bit)
4283 {
4284         ((struct ifnet *)ifp)->if_hwassist = hwassist_bit;
4285         return (0);
4286 }
4287
4288 int
4289 if_gethwassist(if_t ifp)
4290 {
4291         return ((struct ifnet *)ifp)->if_hwassist;
4292 }
4293
4294 int
4295 if_setmtu(if_t ifp, int mtu)
4296 {
4297         ((struct ifnet *)ifp)->if_mtu = mtu;
4298         return (0);
4299 }
4300
4301 int
4302 if_getmtu(if_t ifp)
4303 {
4304         return ((struct ifnet *)ifp)->if_mtu;
4305 }
4306
4307 int
4308 if_getmtu_family(if_t ifp, int family)
4309 {
4310         struct domain *dp;
4311
4312         for (dp = domains; dp; dp = dp->dom_next) {
4313                 if (dp->dom_family == family && dp->dom_ifmtu != NULL)
4314                         return (dp->dom_ifmtu((struct ifnet *)ifp));
4315         }
4316
4317         return (((struct ifnet *)ifp)->if_mtu);
4318 }
4319
4320 /*
4321  * Methods for drivers to access interface unicast and multicast
4322  * link level addresses.  Driver shall not know 'struct ifaddr' neither
4323  * 'struct ifmultiaddr'.
4324  */
4325 u_int
4326 if_foreach_lladdr(if_t ifp, iflladdr_cb_t cb, void *cb_arg)
4327 {
4328         struct ifaddr *ifa;
4329         u_int count;
4330
4331         MPASS(cb);
4332
4333         count = 0;
4334         IF_ADDR_RLOCK(ifp);
4335         CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
4336                 if (ifa->ifa_addr->sa_family != AF_LINK)
4337                         continue;
4338                 count += (*cb)(cb_arg, (struct sockaddr_dl *)ifa->ifa_addr,
4339                     count);
4340         }
4341         IF_ADDR_RUNLOCK(ifp);
4342
4343         return (count);
4344 }
4345
4346 u_int
4347 if_foreach_llmaddr(if_t ifp, iflladdr_cb_t cb, void *cb_arg)
4348 {
4349         struct ifmultiaddr *ifma;
4350         u_int count;
4351
4352         MPASS(cb);
4353
4354         count = 0;
4355         IF_ADDR_RLOCK(ifp);
4356         CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
4357                 if (ifma->ifma_addr->sa_family != AF_LINK)
4358                         continue;
4359                 count += (*cb)(cb_arg, (struct sockaddr_dl *)ifma->ifma_addr,
4360                     count);
4361         }
4362         IF_ADDR_RUNLOCK(ifp);
4363
4364         return (count);
4365 }
4366
4367 int
4368 if_setsoftc(if_t ifp, void *softc)
4369 {
4370         ((struct ifnet *)ifp)->if_softc = softc;
4371         return (0);
4372 }
4373
4374 void *
4375 if_getsoftc(if_t ifp)
4376 {
4377         return ((struct ifnet *)ifp)->if_softc;
4378 }
4379
4380 void 
4381 if_setrcvif(struct mbuf *m, if_t ifp)
4382 {
4383         m->m_pkthdr.rcvif = (struct ifnet *)ifp;
4384 }
4385
4386 void 
4387 if_setvtag(struct mbuf *m, uint16_t tag)
4388 {
4389         m->m_pkthdr.ether_vtag = tag;   
4390 }
4391
4392 uint16_t
4393 if_getvtag(struct mbuf *m)
4394 {
4395
4396         return (m->m_pkthdr.ether_vtag);
4397 }
4398
4399 int
4400 if_sendq_empty(if_t ifp)
4401 {
4402         return IFQ_DRV_IS_EMPTY(&((struct ifnet *)ifp)->if_snd);
4403 }
4404
4405 struct ifaddr *
4406 if_getifaddr(if_t ifp)
4407 {
4408         return ((struct ifnet *)ifp)->if_addr;
4409 }
4410
4411 int
4412 if_getamcount(if_t ifp)
4413 {
4414         return ((struct ifnet *)ifp)->if_amcount;
4415 }
4416
4417
4418 int
4419 if_setsendqready(if_t ifp)
4420 {
4421         IFQ_SET_READY(&((struct ifnet *)ifp)->if_snd);
4422         return (0);
4423 }
4424
4425 int
4426 if_setsendqlen(if_t ifp, int tx_desc_count)
4427 {
4428         IFQ_SET_MAXLEN(&((struct ifnet *)ifp)->if_snd, tx_desc_count);
4429         ((struct ifnet *)ifp)->if_snd.ifq_drv_maxlen = tx_desc_count;
4430
4431         return (0);
4432 }
4433
4434 int
4435 if_vlantrunkinuse(if_t ifp)
4436 {
4437         return ((struct ifnet *)ifp)->if_vlantrunk != NULL?1:0;
4438 }
4439
4440 int
4441 if_input(if_t ifp, struct mbuf* sendmp)
4442 {
4443         (*((struct ifnet *)ifp)->if_input)((struct ifnet *)ifp, sendmp);
4444         return (0);
4445
4446 }
4447
4448 /* XXX */
4449 #ifndef ETH_ADDR_LEN
4450 #define ETH_ADDR_LEN 6
4451 #endif
4452
4453 int 
4454 if_setupmultiaddr(if_t ifp, void *mta, int *cnt, int max)
4455 {
4456         struct ifmultiaddr *ifma;
4457         uint8_t *lmta = (uint8_t *)mta;
4458         int mcnt = 0;
4459
4460         CK_STAILQ_FOREACH(ifma, &((struct ifnet *)ifp)->if_multiaddrs, ifma_link) {
4461                 if (ifma->ifma_addr->sa_family != AF_LINK)
4462                         continue;
4463
4464                 if (mcnt == max)
4465                         break;
4466
4467                 bcopy(LLADDR((struct sockaddr_dl *)ifma->ifma_addr),
4468                     &lmta[mcnt * ETH_ADDR_LEN], ETH_ADDR_LEN);
4469                 mcnt++;
4470         }
4471         *cnt = mcnt;
4472
4473         return (0);
4474 }
4475
4476 int
4477 if_multiaddr_array(if_t ifp, void *mta, int *cnt, int max)
4478 {
4479         int error;
4480
4481         if_maddr_rlock(ifp);
4482         error = if_setupmultiaddr(ifp, mta, cnt, max);
4483         if_maddr_runlock(ifp);
4484         return (error);
4485 }
4486
4487 int
4488 if_multiaddr_count(if_t ifp, int max)
4489 {
4490         struct ifmultiaddr *ifma;
4491         int count;
4492
4493         count = 0;
4494         if_maddr_rlock(ifp);
4495         CK_STAILQ_FOREACH(ifma, &((struct ifnet *)ifp)->if_multiaddrs, ifma_link) {
4496                 if (ifma->ifma_addr->sa_family != AF_LINK)
4497                         continue;
4498                 count++;
4499                 if (count == max)
4500                         break;
4501         }
4502         if_maddr_runlock(ifp);
4503         return (count);
4504 }
4505
4506 int
4507 if_multi_apply(struct ifnet *ifp, int (*filter)(void *, struct ifmultiaddr *, int), void *arg)
4508 {
4509         struct ifmultiaddr *ifma;
4510         int cnt = 0;
4511
4512         if_maddr_rlock(ifp);
4513         CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link)
4514                 cnt += filter(arg, ifma, cnt);
4515         if_maddr_runlock(ifp);
4516         return (cnt);
4517 }
4518
4519 struct mbuf *
4520 if_dequeue(if_t ifp)
4521 {
4522         struct mbuf *m;
4523         IFQ_DRV_DEQUEUE(&((struct ifnet *)ifp)->if_snd, m);
4524
4525         return (m);
4526 }
4527
4528 int
4529 if_sendq_prepend(if_t ifp, struct mbuf *m)
4530 {
4531         IFQ_DRV_PREPEND(&((struct ifnet *)ifp)->if_snd, m);
4532         return (0);
4533 }
4534
4535 int
4536 if_setifheaderlen(if_t ifp, int len)
4537 {
4538         ((struct ifnet *)ifp)->if_hdrlen = len;
4539         return (0);
4540 }
4541
4542 caddr_t
4543 if_getlladdr(if_t ifp)
4544 {
4545         return (IF_LLADDR((struct ifnet *)ifp));
4546 }
4547
4548 void *
4549 if_gethandle(u_char type)
4550 {
4551         return (if_alloc(type));
4552 }
4553
4554 void
4555 if_bpfmtap(if_t ifh, struct mbuf *m)
4556 {
4557         struct ifnet *ifp = (struct ifnet *)ifh;
4558
4559         BPF_MTAP(ifp, m);
4560 }
4561
4562 void
4563 if_etherbpfmtap(if_t ifh, struct mbuf *m)
4564 {
4565         struct ifnet *ifp = (struct ifnet *)ifh;
4566
4567         ETHER_BPF_MTAP(ifp, m);
4568 }
4569
4570 void
4571 if_vlancap(if_t ifh)
4572 {
4573         struct ifnet *ifp = (struct ifnet *)ifh;
4574         VLAN_CAPABILITIES(ifp);
4575 }
4576
4577 int
4578 if_sethwtsomax(if_t ifp, u_int if_hw_tsomax)
4579 {
4580
4581         ((struct ifnet *)ifp)->if_hw_tsomax = if_hw_tsomax;
4582         return (0);
4583 }
4584
4585 int
4586 if_sethwtsomaxsegcount(if_t ifp, u_int if_hw_tsomaxsegcount)
4587 {
4588
4589         ((struct ifnet *)ifp)->if_hw_tsomaxsegcount = if_hw_tsomaxsegcount;
4590         return (0);
4591 }
4592
4593 int
4594 if_sethwtsomaxsegsize(if_t ifp, u_int if_hw_tsomaxsegsize)
4595 {
4596
4597         ((struct ifnet *)ifp)->if_hw_tsomaxsegsize = if_hw_tsomaxsegsize;
4598         return (0);
4599 }
4600
4601 u_int
4602 if_gethwtsomax(if_t ifp)
4603 {
4604
4605         return (((struct ifnet *)ifp)->if_hw_tsomax);
4606 }
4607
4608 u_int
4609 if_gethwtsomaxsegcount(if_t ifp)
4610 {
4611
4612         return (((struct ifnet *)ifp)->if_hw_tsomaxsegcount);
4613 }
4614
4615 u_int
4616 if_gethwtsomaxsegsize(if_t ifp)
4617 {
4618
4619         return (((struct ifnet *)ifp)->if_hw_tsomaxsegsize);
4620 }
4621
4622 void
4623 if_setinitfn(if_t ifp, void (*init_fn)(void *))
4624 {
4625         ((struct ifnet *)ifp)->if_init = init_fn;
4626 }
4627
4628 void
4629 if_setioctlfn(if_t ifp, int (*ioctl_fn)(if_t, u_long, caddr_t))
4630 {
4631         ((struct ifnet *)ifp)->if_ioctl = (void *)ioctl_fn;
4632 }
4633
4634 void
4635 if_setstartfn(if_t ifp, void (*start_fn)(if_t))
4636 {
4637         ((struct ifnet *)ifp)->if_start = (void *)start_fn;
4638 }
4639
4640 void
4641 if_settransmitfn(if_t ifp, if_transmit_fn_t start_fn)
4642 {
4643         ((struct ifnet *)ifp)->if_transmit = start_fn;
4644 }
4645
4646 void if_setqflushfn(if_t ifp, if_qflush_fn_t flush_fn)
4647 {
4648         ((struct ifnet *)ifp)->if_qflush = flush_fn;
4649         
4650 }
4651
4652 void
4653 if_setgetcounterfn(if_t ifp, if_get_counter_t fn)
4654 {
4655
4656         ifp->if_get_counter = fn;
4657 }
4658
4659 /* Revisit these - These are inline functions originally. */
4660 int
4661 drbr_inuse_drv(if_t ifh, struct buf_ring *br)
4662 {
4663         return drbr_inuse(ifh, br);
4664 }
4665
4666 struct mbuf*
4667 drbr_dequeue_drv(if_t ifh, struct buf_ring *br)
4668 {
4669         return drbr_dequeue(ifh, br);
4670 }
4671
4672 int
4673 drbr_needs_enqueue_drv(if_t ifh, struct buf_ring *br)
4674 {
4675         return drbr_needs_enqueue(ifh, br);
4676 }
4677
4678 int
4679 drbr_enqueue_drv(if_t ifh, struct buf_ring *br, struct mbuf *m)
4680 {
4681         return drbr_enqueue(ifh, br, m);
4682
4683 }