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