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