source: rtems-libbsd/freebsd/sys/net/if.c @ 3d1e767

55-freebsd-126-freebsd-12freebsd-9.3
Last change on this file since 3d1e767 was 3d1e767, checked in by Sebastian Huber <sebastian.huber@…>, on 04/27/16 at 08:25:22

Directly use <sys/types.h> provided by Newlib

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