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