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