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