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