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