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