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