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