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