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