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