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