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