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