]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/net/if.c
Change the initialization methodology for global variables scheduled
[FreeBSD/FreeBSD.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 #include "opt_mac.h"
37 #include "opt_carp.h"
38
39 #include <sys/param.h>
40 #include <sys/types.h>
41 #include <sys/conf.h>
42 #include <sys/malloc.h>
43 #include <sys/sbuf.h>
44 #include <sys/bus.h>
45 #include <sys/mbuf.h>
46 #include <sys/systm.h>
47 #include <sys/priv.h>
48 #include <sys/proc.h>
49 #include <sys/socket.h>
50 #include <sys/socketvar.h>
51 #include <sys/protosw.h>
52 #include <sys/kernel.h>
53 #include <sys/sockio.h>
54 #include <sys/syslog.h>
55 #include <sys/sysctl.h>
56 #include <sys/taskqueue.h>
57 #include <sys/domain.h>
58 #include <sys/jail.h>
59 #include <sys/vimage.h>
60 #include <machine/stdarg.h>
61
62 #include <net/if.h>
63 #include <net/if_arp.h>
64 #include <net/if_clone.h>
65 #include <net/if_dl.h>
66 #include <net/if_types.h>
67 #include <net/if_var.h>
68 #include <net/radix.h>
69 #include <net/route.h>
70
71 #if defined(INET) || defined(INET6)
72 /*XXX*/
73 #include <netinet/in.h>
74 #include <netinet/in_var.h>
75 #ifdef INET6
76 #include <netinet6/in6_var.h>
77 #include <netinet6/in6_ifattach.h>
78 #endif
79 #endif
80 #ifdef INET
81 #include <netinet/if_ether.h>
82 #endif
83 #ifdef DEV_CARP
84 #include <netinet/ip_carp.h>
85 #endif
86
87 #include <security/mac/mac_framework.h>
88
89 SYSCTL_NODE(_net, PF_LINK, link, CTLFLAG_RW, 0, "Link layers");
90 SYSCTL_NODE(_net_link, 0, generic, CTLFLAG_RW, 0, "Generic link-management");
91
92 /* Log link state change events */
93 static int log_link_state_change = 1;
94
95 SYSCTL_INT(_net_link, OID_AUTO, log_link_state_change, CTLFLAG_RW,
96         &log_link_state_change, 0,
97         "log interface link state change events");
98
99 void    (*bstp_linkstate_p)(struct ifnet *ifp, int state);
100 void    (*ng_ether_link_state_p)(struct ifnet *ifp, int state);
101 void    (*lagg_linkstate_p)(struct ifnet *ifp, int state);
102
103 struct mbuf *(*tbr_dequeue_ptr)(struct ifaltq *, int) = NULL;
104
105 /*
106  * XXX: Style; these should be sorted alphabetically, and unprototyped
107  * static functions should be prototyped. Currently they are sorted by
108  * declaration order.
109  */
110 static void     if_attachdomain(void *);
111 static void     if_attachdomain1(struct ifnet *);
112 static int      ifconf(u_long, caddr_t);
113 static void     if_freemulti(struct ifmultiaddr *);
114 static void     if_grow(void);
115 static void     if_init(void *);
116 static void     if_qflush(struct ifaltq *);
117 static void     if_route(struct ifnet *, int flag, int fam);
118 static int      if_setflag(struct ifnet *, int, int, int *, int);
119 static void     if_slowtimo(void *);
120 static void     if_unroute(struct ifnet *, int flag, int fam);
121 static void     link_rtrequest(int, struct rtentry *, struct rt_addrinfo *);
122 static int      if_rtdel(struct radix_node *, void *);
123 static int      ifhwioctl(u_long, struct ifnet *, caddr_t, struct thread *);
124 static int      if_delmulti_locked(struct ifnet *, struct ifmultiaddr *, int);
125 static void     if_start_deferred(void *context, int pending);
126 static void     do_link_state_change(void *, int);
127 static int      if_getgroup(struct ifgroupreq *, struct ifnet *);
128 static int      if_getgroupmembers(struct ifgroupreq *);
129 #ifdef INET6
130 /*
131  * XXX: declare here to avoid to include many inet6 related files..
132  * should be more generalized?
133  */
134 extern void     nd6_setmtu(struct ifnet *);
135 #endif
136
137 #ifdef VIMAGE_GLOBALS
138 struct  ifnethead ifnet;        /* depend on static init XXX */
139 struct  ifgrouphead ifg_head;
140 int     if_index;
141 static  int if_indexlim;
142 /* Table of ifnet/cdev by index.  Locked with ifnet_lock. */
143 static struct ifindex_entry *ifindex_table;
144 static struct   knlist ifklist;
145 #endif
146
147 int     ifqmaxlen = IFQ_MAXLEN;
148 struct  mtx ifnet_lock;
149 static  if_com_alloc_t *if_com_alloc[256];
150 static  if_com_free_t *if_com_free[256];
151
152 static void     filt_netdetach(struct knote *kn);
153 static int      filt_netdev(struct knote *kn, long hint);
154
155 static struct filterops netdev_filtops =
156     { 1, NULL, filt_netdetach, filt_netdev };
157
158 /*
159  * System initialization
160  */
161 SYSINIT(interfaces, SI_SUB_INIT_IF, SI_ORDER_FIRST, if_init, NULL);
162 SYSINIT(interface_check, SI_SUB_PROTO_IF, SI_ORDER_FIRST, if_slowtimo, NULL);
163
164 MALLOC_DEFINE(M_IFNET, "ifnet", "interface internals");
165 MALLOC_DEFINE(M_IFADDR, "ifaddr", "interface address");
166 MALLOC_DEFINE(M_IFMADDR, "ether_multi", "link-level multicast address");
167
168 struct ifnet *
169 ifnet_byindex(u_short idx)
170 {
171         INIT_VNET_NET(curvnet);
172         struct ifnet *ifp;
173
174         IFNET_RLOCK();
175         ifp = V_ifindex_table[idx].ife_ifnet;
176         IFNET_RUNLOCK();
177         return (ifp);
178 }
179
180 static void
181 ifnet_setbyindex(u_short idx, struct ifnet *ifp)
182 {
183         INIT_VNET_NET(curvnet);
184
185         IFNET_WLOCK_ASSERT();
186
187         V_ifindex_table[idx].ife_ifnet = ifp;
188 }
189
190 struct ifaddr *
191 ifaddr_byindex(u_short idx)
192 {
193         INIT_VNET_NET(curvnet);
194         struct ifaddr *ifa;
195
196         IFNET_RLOCK();
197         ifa = ifnet_byindex(idx)->if_addr;
198         IFNET_RUNLOCK();
199         return (ifa);
200 }
201
202 struct cdev *
203 ifdev_byindex(u_short idx)
204 {
205         INIT_VNET_NET(curvnet);
206         struct cdev *cdev;
207
208         IFNET_RLOCK();
209         cdev = V_ifindex_table[idx].ife_dev;
210         IFNET_RUNLOCK();
211         return (cdev);
212 }
213
214 static void
215 ifdev_setbyindex(u_short idx, struct cdev *cdev)
216 {
217         INIT_VNET_NET(curvnet);
218
219         IFNET_WLOCK();
220         V_ifindex_table[idx].ife_dev = cdev;
221         IFNET_WUNLOCK();
222 }
223
224 static d_open_t         netopen;
225 static d_close_t        netclose;
226 static d_ioctl_t        netioctl;
227 static d_kqfilter_t     netkqfilter;
228
229 static struct cdevsw net_cdevsw = {
230         .d_version =    D_VERSION,
231         .d_flags =      D_NEEDGIANT,
232         .d_open =       netopen,
233         .d_close =      netclose,
234         .d_ioctl =      netioctl,
235         .d_name =       "net",
236         .d_kqfilter =   netkqfilter,
237 };
238
239 static int
240 netopen(struct cdev *dev, int flag, int mode, struct thread *td)
241 {
242         return (0);
243 }
244
245 static int
246 netclose(struct cdev *dev, int flags, int fmt, struct thread *td)
247 {
248         return (0);
249 }
250
251 static int
252 netioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
253 {
254         struct ifnet *ifp;
255         int error, idx;
256
257         /* only support interface specific ioctls */
258         if (IOCGROUP(cmd) != 'i')
259                 return (EOPNOTSUPP);
260         idx = dev2unit(dev);
261         if (idx == 0) {
262                 /*
263                  * special network device, not interface.
264                  */
265                 if (cmd == SIOCGIFCONF)
266                         return (ifconf(cmd, data));     /* XXX remove cmd */
267 #ifdef __amd64__
268                 if (cmd == SIOCGIFCONF32)
269                         return (ifconf(cmd, data));     /* XXX remove cmd */
270 #endif
271                 return (EOPNOTSUPP);
272         }
273
274         ifp = ifnet_byindex(idx);
275         if (ifp == NULL)
276                 return (ENXIO);
277
278         error = ifhwioctl(cmd, ifp, data, td);
279         if (error == ENOIOCTL)
280                 error = EOPNOTSUPP;
281         return (error);
282 }
283
284 static int
285 netkqfilter(struct cdev *dev, struct knote *kn)
286 {
287         INIT_VNET_NET(curvnet);
288         struct knlist *klist;
289         struct ifnet *ifp;
290         int idx;
291
292         switch (kn->kn_filter) {
293         case EVFILT_NETDEV:
294                 kn->kn_fop = &netdev_filtops;
295                 break;
296         default:
297                 return (EINVAL);
298         }
299
300         idx = dev2unit(dev);
301         if (idx == 0) {
302                 klist = &V_ifklist;
303         } else {
304                 ifp = ifnet_byindex(idx);
305                 if (ifp == NULL)
306                         return (1);
307                 klist = &ifp->if_klist;
308         }
309
310         kn->kn_hook = (caddr_t)klist;
311
312         knlist_add(klist, kn, 0);
313
314         return (0);
315 }
316
317 static void
318 filt_netdetach(struct knote *kn)
319 {
320         struct knlist *klist = (struct knlist *)kn->kn_hook;
321
322         knlist_remove(klist, kn, 0);
323 }
324
325 static int
326 filt_netdev(struct knote *kn, long hint)
327 {
328         struct knlist *klist = (struct knlist *)kn->kn_hook;
329
330         /*
331          * Currently NOTE_EXIT is abused to indicate device detach.
332          */
333         if (hint == NOTE_EXIT) {
334                 kn->kn_data = NOTE_LINKINV;
335                 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
336                 knlist_remove_inevent(klist, kn);
337                 return (1);
338         }
339         if (hint != 0)
340                 kn->kn_data = hint;                     /* current status */
341         if (kn->kn_sfflags & hint)
342                 kn->kn_fflags |= hint;
343         return (kn->kn_fflags != 0);
344 }
345
346 /*
347  * Network interface utility routines.
348  *
349  * Routines with ifa_ifwith* names take sockaddr *'s as
350  * parameters.
351  */
352
353 /* ARGSUSED*/
354 static void
355 if_init(void *dummy __unused)
356 {
357         INIT_VNET_NET(curvnet);
358
359         V_if_index = 0;
360         V_ifindex_table = NULL;
361         V_if_indexlim = 8;
362
363         IFNET_LOCK_INIT();
364         TAILQ_INIT(&V_ifnet);
365         TAILQ_INIT(&V_ifg_head);
366         knlist_init(&V_ifklist, NULL, NULL, NULL, NULL);
367         if_grow();                              /* create initial table */
368         ifdev_setbyindex(0, make_dev(&net_cdevsw, 0, UID_ROOT, GID_WHEEL,
369             0600, "network"));
370         if_clone_init();
371 }
372
373 static void
374 if_grow(void)
375 {
376         INIT_VNET_NET(curvnet);
377         u_int n;
378         struct ifindex_entry *e;
379
380         V_if_indexlim <<= 1;
381         n = V_if_indexlim * sizeof(*e);
382         e = malloc(n, M_IFNET, M_WAITOK | M_ZERO);
383         if (V_ifindex_table != NULL) {
384                 memcpy((caddr_t)e, (caddr_t)V_ifindex_table, n/2);
385                 free((caddr_t)V_ifindex_table, M_IFNET);
386         }
387         V_ifindex_table = e;
388 }
389
390 /*
391  * Allocate a struct ifnet and an index for an interface.  A layer 2
392  * common structure will also be allocated if an allocation routine is
393  * registered for the passed type.
394  */
395 struct ifnet*
396 if_alloc(u_char type)
397 {
398         INIT_VNET_NET(curvnet);
399         struct ifnet *ifp;
400
401         ifp = malloc(sizeof(struct ifnet), M_IFNET, M_WAITOK|M_ZERO);
402
403         /*
404          * Try to find an empty slot below if_index.  If we fail, take
405          * the next slot.
406          *
407          * XXX: should be locked!
408          */
409         for (ifp->if_index = 1; ifp->if_index <= V_if_index; ifp->if_index++) {
410                 if (ifnet_byindex(ifp->if_index) == NULL)
411                         break;
412         }
413         /* Catch if_index overflow. */
414         if (ifp->if_index < 1) {
415                 free(ifp, M_IFNET);
416                 return (NULL);
417         }
418         if (ifp->if_index > V_if_index)
419                 V_if_index = ifp->if_index;
420         if (V_if_index >= V_if_indexlim)
421                 if_grow();
422
423         ifp->if_type = type;
424
425         if (if_com_alloc[type] != NULL) {
426                 ifp->if_l2com = if_com_alloc[type](type, ifp);
427                 if (ifp->if_l2com == NULL) {
428                         free(ifp, M_IFNET);
429                         return (NULL);
430                 }
431         }
432         IFNET_WLOCK();
433         ifnet_setbyindex(ifp->if_index, ifp);
434         IFNET_WUNLOCK();
435         IF_ADDR_LOCK_INIT(ifp);
436
437         return (ifp);
438 }
439
440 /*
441  * Free the struct ifnet, the associated index, and the layer 2 common
442  * structure if needed.  All the work is done in if_free_type().
443  *
444  * Do not add code to this function!  Add it to if_free_type().
445  */
446 void
447 if_free(struct ifnet *ifp)
448 {
449
450         if_free_type(ifp, ifp->if_type);
451 }
452
453 /*
454  * Do the actual work of freeing a struct ifnet, associated index, and
455  * layer 2 common structure.  This version should only be called by
456  * intefaces that switch their type after calling if_alloc().
457  */
458 void
459 if_free_type(struct ifnet *ifp, u_char type)
460 {
461         INIT_VNET_NET(curvnet); /* ifp->if_vnet can be NULL here ! */
462
463         if (ifp != ifnet_byindex(ifp->if_index)) {
464                 if_printf(ifp, "%s: value was not if_alloced, skipping\n",
465                     __func__);
466                 return;
467         }
468
469         IFNET_WLOCK();
470         ifnet_setbyindex(ifp->if_index, NULL);
471
472         /* XXX: should be locked with if_findindex() */
473         while (V_if_index > 0 && ifnet_byindex(V_if_index) == NULL)
474                 V_if_index--;
475         IFNET_WUNLOCK();
476
477         if (if_com_free[type] != NULL)
478                 if_com_free[type](ifp->if_l2com, type);
479
480         IF_ADDR_LOCK_DESTROY(ifp);
481         free(ifp, M_IFNET);
482 };
483
484 /*
485  * Perform generic interface initalization tasks and attach the interface
486  * to the list of "active" interfaces.
487  *
488  * XXX:
489  *  - The decision to return void and thus require this function to
490  *    succeed is questionable.
491  *  - We do more initialization here then is probably a good idea.
492  *    Some of this should probably move to if_alloc().
493  *  - We should probably do more sanity checking.  For instance we don't
494  *    do anything to insure if_xname is unique or non-empty.
495  */
496 void
497 if_attach(struct ifnet *ifp)
498 {
499         INIT_VNET_NET(curvnet);
500         unsigned socksize, ifasize;
501         int namelen, masklen;
502         struct sockaddr_dl *sdl;
503         struct ifaddr *ifa;
504
505         if (ifp->if_index == 0 || ifp != ifnet_byindex(ifp->if_index))
506                 panic ("%s: BUG: if_attach called without if_alloc'd input()\n",
507                     ifp->if_xname);
508
509         TASK_INIT(&ifp->if_starttask, 0, if_start_deferred, ifp);
510         TASK_INIT(&ifp->if_linktask, 0, do_link_state_change, ifp);
511         IF_AFDATA_LOCK_INIT(ifp);
512         ifp->if_afdata_initialized = 0;
513
514         TAILQ_INIT(&ifp->if_addrhead);
515         TAILQ_INIT(&ifp->if_prefixhead);
516         TAILQ_INIT(&ifp->if_multiaddrs);
517         TAILQ_INIT(&ifp->if_groups);
518
519         if_addgroup(ifp, IFG_ALL);
520
521         knlist_init(&ifp->if_klist, NULL, NULL, NULL, NULL);
522         getmicrotime(&ifp->if_lastchange);
523         ifp->if_data.ifi_epoch = time_uptime;
524         ifp->if_data.ifi_datalen = sizeof(struct if_data);
525
526 #ifdef MAC
527         mac_ifnet_init(ifp);
528         mac_ifnet_create(ifp);
529 #endif
530
531         ifdev_setbyindex(ifp->if_index, make_dev(&net_cdevsw,
532             ifp->if_index, UID_ROOT, GID_WHEEL, 0600, "%s/%s",
533             net_cdevsw.d_name, ifp->if_xname));
534         make_dev_alias(ifdev_byindex(ifp->if_index), "%s%d",
535             net_cdevsw.d_name, ifp->if_index);
536
537         mtx_init(&ifp->if_snd.ifq_mtx, ifp->if_xname, "if send queue", MTX_DEF);
538
539         /*
540          * create a Link Level name for this device
541          */
542         namelen = strlen(ifp->if_xname);
543         /*
544          * Always save enough space for any possiable name so we can do
545          * a rename in place later.
546          */
547         masklen = offsetof(struct sockaddr_dl, sdl_data[0]) + IFNAMSIZ;
548         socksize = masklen + ifp->if_addrlen;
549         if (socksize < sizeof(*sdl))
550                 socksize = sizeof(*sdl);
551         socksize = roundup2(socksize, sizeof(long));
552         ifasize = sizeof(*ifa) + 2 * socksize;
553         ifa = malloc(ifasize, M_IFADDR, M_WAITOK | M_ZERO);
554         IFA_LOCK_INIT(ifa);
555         sdl = (struct sockaddr_dl *)(ifa + 1);
556         sdl->sdl_len = socksize;
557         sdl->sdl_family = AF_LINK;
558         bcopy(ifp->if_xname, sdl->sdl_data, namelen);
559         sdl->sdl_nlen = namelen;
560         sdl->sdl_index = ifp->if_index;
561         sdl->sdl_type = ifp->if_type;
562         ifp->if_addr = ifa;
563         ifa->ifa_ifp = ifp;
564         ifa->ifa_rtrequest = link_rtrequest;
565         ifa->ifa_addr = (struct sockaddr *)sdl;
566         sdl = (struct sockaddr_dl *)(socksize + (caddr_t)sdl);
567         ifa->ifa_netmask = (struct sockaddr *)sdl;
568         sdl->sdl_len = masklen;
569         while (namelen != 0)
570                 sdl->sdl_data[--namelen] = 0xff;
571         ifa->ifa_refcnt = 1;
572         TAILQ_INSERT_HEAD(&ifp->if_addrhead, ifa, ifa_link);
573         ifp->if_broadcastaddr = NULL; /* reliably crash if used uninitialized */
574
575         /*
576          * XXX: why do we warn about this? We're correcting it and most
577          * drivers just set the value the way we do.
578          */
579         if (ifp->if_snd.ifq_maxlen == 0) {
580                 if_printf(ifp, "XXX: driver didn't set ifq_maxlen\n");
581                 ifp->if_snd.ifq_maxlen = ifqmaxlen;
582         }
583         ifp->if_snd.altq_type = 0;
584         ifp->if_snd.altq_disc = NULL;
585         ifp->if_snd.altq_flags &= ALTQF_CANTCHANGE;
586         ifp->if_snd.altq_tbr  = NULL;
587         ifp->if_snd.altq_ifp  = ifp;
588
589         IFNET_WLOCK();
590         TAILQ_INSERT_TAIL(&V_ifnet, ifp, if_link);
591         IFNET_WUNLOCK();
592
593         if (domain_init_status >= 2)
594                 if_attachdomain1(ifp);
595
596         EVENTHANDLER_INVOKE(ifnet_arrival_event, ifp);
597         devctl_notify("IFNET", ifp->if_xname, "ATTACH", NULL);
598
599         /* Announce the interface. */
600         rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
601
602         if (ifp->if_watchdog != NULL)
603                 if_printf(ifp,
604                     "WARNING: using obsoleted if_watchdog interface\n");
605         if (ifp->if_flags & IFF_NEEDSGIANT)
606                 if_printf(ifp,
607                     "WARNING: using obsoleted IFF_NEEDSGIANT flag\n");
608 }
609
610 static void
611 if_attachdomain(void *dummy)
612 {
613         INIT_VNET_NET(curvnet);
614         struct ifnet *ifp;
615         int s;
616
617         s = splnet();
618         TAILQ_FOREACH(ifp, &V_ifnet, if_link)
619                 if_attachdomain1(ifp);
620         splx(s);
621 }
622 SYSINIT(domainifattach, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_SECOND,
623     if_attachdomain, NULL);
624
625 static void
626 if_attachdomain1(struct ifnet *ifp)
627 {
628         struct domain *dp;
629         int s;
630
631         s = splnet();
632
633         /*
634          * Since dp->dom_ifattach calls malloc() with M_WAITOK, we
635          * cannot lock ifp->if_afdata initialization, entirely.
636          */
637         if (IF_AFDATA_TRYLOCK(ifp) == 0) {
638                 splx(s);
639                 return;
640         }
641         if (ifp->if_afdata_initialized >= domain_init_status) {
642                 IF_AFDATA_UNLOCK(ifp);
643                 splx(s);
644                 printf("if_attachdomain called more than once on %s\n",
645                     ifp->if_xname);
646                 return;
647         }
648         ifp->if_afdata_initialized = domain_init_status;
649         IF_AFDATA_UNLOCK(ifp);
650
651         /* address family dependent data region */
652         bzero(ifp->if_afdata, sizeof(ifp->if_afdata));
653         for (dp = domains; dp; dp = dp->dom_next) {
654                 if (dp->dom_ifattach)
655                         ifp->if_afdata[dp->dom_family] =
656                             (*dp->dom_ifattach)(ifp);
657         }
658
659         splx(s);
660 }
661
662 /*
663  * Remove any unicast or broadcast network addresses from an interface.
664  */
665 void
666 if_purgeaddrs(struct ifnet *ifp)
667 {
668         struct ifaddr *ifa, *next;
669
670         TAILQ_FOREACH_SAFE(ifa, &ifp->if_addrhead, ifa_link, next) {
671                 if (ifa->ifa_addr->sa_family == AF_LINK)
672                         continue;
673 #ifdef INET
674                 /* XXX: Ugly!! ad hoc just for INET */
675                 if (ifa->ifa_addr->sa_family == AF_INET) {
676                         struct ifaliasreq ifr;
677
678                         bzero(&ifr, sizeof(ifr));
679                         ifr.ifra_addr = *ifa->ifa_addr;
680                         if (ifa->ifa_dstaddr)
681                                 ifr.ifra_broadaddr = *ifa->ifa_dstaddr;
682                         if (in_control(NULL, SIOCDIFADDR, (caddr_t)&ifr, ifp,
683                             NULL) == 0)
684                                 continue;
685                 }
686 #endif /* INET */
687 #ifdef INET6
688                 if (ifa->ifa_addr->sa_family == AF_INET6) {
689                         in6_purgeaddr(ifa);
690                         /* ifp_addrhead is already updated */
691                         continue;
692                 }
693 #endif /* INET6 */
694                 TAILQ_REMOVE(&ifp->if_addrhead, ifa, ifa_link);
695                 IFAFREE(ifa);
696         }
697 }
698
699 /*
700  * Remove any multicast network addresses from an interface.
701  */
702 void
703 if_purgemaddrs(struct ifnet *ifp)
704 {
705         struct ifmultiaddr *ifma;
706         struct ifmultiaddr *next;
707
708         IF_ADDR_LOCK(ifp);
709         TAILQ_FOREACH_SAFE(ifma, &ifp->if_multiaddrs, ifma_link, next)
710                 if_delmulti_locked(ifp, ifma, 1);
711         IF_ADDR_UNLOCK(ifp);
712 }
713
714 /*
715  * Detach an interface, removing it from the
716  * list of "active" interfaces.
717  *
718  * XXXRW: There are some significant questions about event ordering, and
719  * how to prevent things from starting to use the interface during detach.
720  */
721 void
722 if_detach(struct ifnet *ifp)
723 {
724         INIT_VNET_NET(ifp->if_vnet);
725         struct ifaddr *ifa;
726         struct radix_node_head  *rnh;
727         int s;
728         int i;
729         struct domain *dp;
730         struct ifnet *iter;
731         int found = 0;
732
733         IFNET_WLOCK();
734         TAILQ_FOREACH(iter, &V_ifnet, if_link)
735                 if (iter == ifp) {
736                         TAILQ_REMOVE(&V_ifnet, ifp, if_link);
737                         found = 1;
738                         break;
739                 }
740         IFNET_WUNLOCK();
741         if (!found)
742                 return;
743
744         /*
745          * Remove/wait for pending events.
746          */
747         taskqueue_drain(taskqueue_swi, &ifp->if_linktask);
748
749         /*
750          * Remove routes and flush queues.
751          */
752         s = splnet();
753         if_down(ifp);
754 #ifdef ALTQ
755         if (ALTQ_IS_ENABLED(&ifp->if_snd))
756                 altq_disable(&ifp->if_snd);
757         if (ALTQ_IS_ATTACHED(&ifp->if_snd))
758                 altq_detach(&ifp->if_snd);
759 #endif
760
761         if_purgeaddrs(ifp);
762
763 #ifdef INET
764         in_ifdetach(ifp);
765 #endif
766
767 #ifdef INET6
768         /*
769          * Remove all IPv6 kernel structs related to ifp.  This should be done
770          * before removing routing entries below, since IPv6 interface direct
771          * routes are expected to be removed by the IPv6-specific kernel API.
772          * Otherwise, the kernel will detect some inconsistency and bark it.
773          */
774         in6_ifdetach(ifp);
775 #endif
776         if_purgemaddrs(ifp);
777
778         /*
779          * Remove link ifaddr pointer and maybe decrement if_index.
780          * Clean up all addresses.
781          */
782         ifp->if_addr = NULL;
783         destroy_dev(ifdev_byindex(ifp->if_index));
784         ifdev_setbyindex(ifp->if_index, NULL);  
785
786         /* We can now free link ifaddr. */
787         if (!TAILQ_EMPTY(&ifp->if_addrhead)) {
788                 ifa = TAILQ_FIRST(&ifp->if_addrhead);
789                 TAILQ_REMOVE(&ifp->if_addrhead, ifa, ifa_link);
790                 IFAFREE(ifa);
791         }
792
793         /*
794          * Delete all remaining routes using this interface
795          * Unfortuneatly the only way to do this is to slog through
796          * the entire routing table looking for routes which point
797          * to this interface...oh well...
798          */
799         for (i = 1; i <= AF_MAX; i++) {
800             int j;
801             for (j = 0; j < rt_numfibs; j++) {
802                 if ((rnh = V_rt_tables[j][i]) == NULL)
803                         continue;
804                 RADIX_NODE_HEAD_LOCK(rnh);
805                 (void) rnh->rnh_walktree(rnh, if_rtdel, ifp);
806                 RADIX_NODE_HEAD_UNLOCK(rnh);
807             }
808         }
809
810         /* Announce that the interface is gone. */
811         rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
812         EVENTHANDLER_INVOKE(ifnet_departure_event, ifp);
813         devctl_notify("IFNET", ifp->if_xname, "DETACH", NULL);
814
815         IF_AFDATA_LOCK(ifp);
816         for (dp = domains; dp; dp = dp->dom_next) {
817                 if (dp->dom_ifdetach && ifp->if_afdata[dp->dom_family])
818                         (*dp->dom_ifdetach)(ifp,
819                             ifp->if_afdata[dp->dom_family]);
820         }
821         IF_AFDATA_UNLOCK(ifp);
822
823 #ifdef MAC
824         mac_ifnet_destroy(ifp);
825 #endif /* MAC */
826         KNOTE_UNLOCKED(&ifp->if_klist, NOTE_EXIT);
827         knlist_clear(&ifp->if_klist, 0);
828         knlist_destroy(&ifp->if_klist);
829         mtx_destroy(&ifp->if_snd.ifq_mtx);
830         IF_AFDATA_DESTROY(ifp);
831         splx(s);
832 }
833
834 /*
835  * Add a group to an interface
836  */
837 int
838 if_addgroup(struct ifnet *ifp, const char *groupname)
839 {
840         INIT_VNET_NET(ifp->if_vnet);
841         struct ifg_list         *ifgl;
842         struct ifg_group        *ifg = NULL;
843         struct ifg_member       *ifgm;
844
845         if (groupname[0] && groupname[strlen(groupname) - 1] >= '0' &&
846             groupname[strlen(groupname) - 1] <= '9')
847                 return (EINVAL);
848
849         IFNET_WLOCK();
850         TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
851                 if (!strcmp(ifgl->ifgl_group->ifg_group, groupname)) {
852                         IFNET_WUNLOCK();
853                         return (EEXIST);
854                 }
855
856         if ((ifgl = (struct ifg_list *)malloc(sizeof(struct ifg_list), M_TEMP,
857             M_NOWAIT)) == NULL) {
858                 IFNET_WUNLOCK();
859                 return (ENOMEM);
860         }
861
862         if ((ifgm = (struct ifg_member *)malloc(sizeof(struct ifg_member),
863             M_TEMP, M_NOWAIT)) == NULL) {
864                 free(ifgl, M_TEMP);
865                 IFNET_WUNLOCK();
866                 return (ENOMEM);
867         }
868
869         TAILQ_FOREACH(ifg, &V_ifg_head, ifg_next)
870                 if (!strcmp(ifg->ifg_group, groupname))
871                         break;
872
873         if (ifg == NULL) {
874                 if ((ifg = (struct ifg_group *)malloc(sizeof(struct ifg_group),
875                     M_TEMP, M_NOWAIT)) == NULL) {
876                         free(ifgl, M_TEMP);
877                         free(ifgm, M_TEMP);
878                         IFNET_WUNLOCK();
879                         return (ENOMEM);
880                 }
881                 strlcpy(ifg->ifg_group, groupname, sizeof(ifg->ifg_group));
882                 ifg->ifg_refcnt = 0;
883                 TAILQ_INIT(&ifg->ifg_members);
884                 EVENTHANDLER_INVOKE(group_attach_event, ifg);
885                 TAILQ_INSERT_TAIL(&V_ifg_head, ifg, ifg_next);
886         }
887
888         ifg->ifg_refcnt++;
889         ifgl->ifgl_group = ifg;
890         ifgm->ifgm_ifp = ifp;
891
892         IF_ADDR_LOCK(ifp);
893         TAILQ_INSERT_TAIL(&ifg->ifg_members, ifgm, ifgm_next);
894         TAILQ_INSERT_TAIL(&ifp->if_groups, ifgl, ifgl_next);
895         IF_ADDR_UNLOCK(ifp);
896
897         IFNET_WUNLOCK();
898
899         EVENTHANDLER_INVOKE(group_change_event, groupname);
900
901         return (0);
902 }
903
904 /*
905  * Remove a group from an interface
906  */
907 int
908 if_delgroup(struct ifnet *ifp, const char *groupname)
909 {
910         INIT_VNET_NET(ifp->if_vnet);
911         struct ifg_list         *ifgl;
912         struct ifg_member       *ifgm;
913
914         IFNET_WLOCK();
915         TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
916                 if (!strcmp(ifgl->ifgl_group->ifg_group, groupname))
917                         break;
918         if (ifgl == NULL) {
919                 IFNET_WUNLOCK();
920                 return (ENOENT);
921         }
922
923         IF_ADDR_LOCK(ifp);
924         TAILQ_REMOVE(&ifp->if_groups, ifgl, ifgl_next);
925         IF_ADDR_UNLOCK(ifp);
926
927         TAILQ_FOREACH(ifgm, &ifgl->ifgl_group->ifg_members, ifgm_next)
928                 if (ifgm->ifgm_ifp == ifp)
929                         break;
930
931         if (ifgm != NULL) {
932                 TAILQ_REMOVE(&ifgl->ifgl_group->ifg_members, ifgm, ifgm_next);
933                 free(ifgm, M_TEMP);
934         }
935
936         if (--ifgl->ifgl_group->ifg_refcnt == 0) {
937                 TAILQ_REMOVE(&V_ifg_head, ifgl->ifgl_group, ifg_next);
938                 EVENTHANDLER_INVOKE(group_detach_event, ifgl->ifgl_group);
939                 free(ifgl->ifgl_group, M_TEMP);
940         }
941         IFNET_WUNLOCK();
942
943         free(ifgl, M_TEMP);
944
945         EVENTHANDLER_INVOKE(group_change_event, groupname);
946
947         return (0);
948 }
949
950 /*
951  * Stores all groups from an interface in memory pointed
952  * to by data
953  */
954 static int
955 if_getgroup(struct ifgroupreq *data, struct ifnet *ifp)
956 {
957         int                      len, error;
958         struct ifg_list         *ifgl;
959         struct ifg_req           ifgrq, *ifgp;
960         struct ifgroupreq       *ifgr = data;
961
962         if (ifgr->ifgr_len == 0) {
963                 IF_ADDR_LOCK(ifp);
964                 TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
965                         ifgr->ifgr_len += sizeof(struct ifg_req);
966                 IF_ADDR_UNLOCK(ifp);
967                 return (0);
968         }
969
970         len = ifgr->ifgr_len;
971         ifgp = ifgr->ifgr_groups;
972         /* XXX: wire */
973         IF_ADDR_LOCK(ifp);
974         TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next) {
975                 if (len < sizeof(ifgrq)) {
976                         IF_ADDR_UNLOCK(ifp);
977                         return (EINVAL);
978                 }
979                 bzero(&ifgrq, sizeof ifgrq);
980                 strlcpy(ifgrq.ifgrq_group, ifgl->ifgl_group->ifg_group,
981                     sizeof(ifgrq.ifgrq_group));
982                 if ((error = copyout(&ifgrq, ifgp, sizeof(struct ifg_req)))) {
983                         IF_ADDR_UNLOCK(ifp);
984                         return (error);
985                 }
986                 len -= sizeof(ifgrq);
987                 ifgp++;
988         }
989         IF_ADDR_UNLOCK(ifp);
990
991         return (0);
992 }
993
994 /*
995  * Stores all members of a group in memory pointed to by data
996  */
997 static int
998 if_getgroupmembers(struct ifgroupreq *data)
999 {
1000         INIT_VNET_NET(curvnet);
1001         struct ifgroupreq       *ifgr = data;
1002         struct ifg_group        *ifg;
1003         struct ifg_member       *ifgm;
1004         struct ifg_req           ifgrq, *ifgp;
1005         int                      len, error;
1006
1007         IFNET_RLOCK();
1008         TAILQ_FOREACH(ifg, &V_ifg_head, ifg_next)
1009                 if (!strcmp(ifg->ifg_group, ifgr->ifgr_name))
1010                         break;
1011         if (ifg == NULL) {
1012                 IFNET_RUNLOCK();
1013                 return (ENOENT);
1014         }
1015
1016         if (ifgr->ifgr_len == 0) {
1017                 TAILQ_FOREACH(ifgm, &ifg->ifg_members, ifgm_next)
1018                         ifgr->ifgr_len += sizeof(ifgrq);
1019                 IFNET_RUNLOCK();
1020                 return (0);
1021         }
1022
1023         len = ifgr->ifgr_len;
1024         ifgp = ifgr->ifgr_groups;
1025         TAILQ_FOREACH(ifgm, &ifg->ifg_members, ifgm_next) {
1026                 if (len < sizeof(ifgrq)) {
1027                         IFNET_RUNLOCK();
1028                         return (EINVAL);
1029                 }
1030                 bzero(&ifgrq, sizeof ifgrq);
1031                 strlcpy(ifgrq.ifgrq_member, ifgm->ifgm_ifp->if_xname,
1032                     sizeof(ifgrq.ifgrq_member));
1033                 if ((error = copyout(&ifgrq, ifgp, sizeof(struct ifg_req)))) {
1034                         IFNET_RUNLOCK();
1035                         return (error);
1036                 }
1037                 len -= sizeof(ifgrq);
1038                 ifgp++;
1039         }
1040         IFNET_RUNLOCK();
1041
1042         return (0);
1043 }
1044
1045 /*
1046  * Delete Routes for a Network Interface
1047  *
1048  * Called for each routing entry via the rnh->rnh_walktree() call above
1049  * to delete all route entries referencing a detaching network interface.
1050  *
1051  * Arguments:
1052  *      rn      pointer to node in the routing table
1053  *      arg     argument passed to rnh->rnh_walktree() - detaching interface
1054  *
1055  * Returns:
1056  *      0       successful
1057  *      errno   failed - reason indicated
1058  *
1059  */
1060 static int
1061 if_rtdel(struct radix_node *rn, void *arg)
1062 {
1063         struct rtentry  *rt = (struct rtentry *)rn;
1064         struct ifnet    *ifp = arg;
1065         int             err;
1066
1067         if (rt->rt_ifp == ifp) {
1068
1069                 /*
1070                  * Protect (sorta) against walktree recursion problems
1071                  * with cloned routes
1072                  */
1073                 if ((rt->rt_flags & RTF_UP) == 0)
1074                         return (0);
1075
1076                 err = rtrequest_fib(RTM_DELETE, rt_key(rt), rt->rt_gateway,
1077                                 rt_mask(rt), rt->rt_flags,
1078                                 (struct rtentry **) NULL, rt->rt_fibnum);
1079                 if (err) {
1080                         log(LOG_WARNING, "if_rtdel: error %d\n", err);
1081                 }
1082         }
1083
1084         return (0);
1085 }
1086
1087 /*
1088  * XXX: Because sockaddr_dl has deeper structure than the sockaddr
1089  * structs used to represent other address families, it is necessary
1090  * to perform a different comparison.
1091  */
1092
1093 #define sa_equal(a1, a2)        \
1094         (bcmp((a1), (a2), ((a1))->sa_len) == 0)
1095
1096 #define sa_dl_equal(a1, a2)     \
1097         ((((struct sockaddr_dl *)(a1))->sdl_len ==                      \
1098          ((struct sockaddr_dl *)(a2))->sdl_len) &&                      \
1099          (bcmp(LLADDR((struct sockaddr_dl *)(a1)),                      \
1100                LLADDR((struct sockaddr_dl *)(a2)),                      \
1101                ((struct sockaddr_dl *)(a1))->sdl_alen) == 0))
1102
1103 /*
1104  * Locate an interface based on a complete address.
1105  */
1106 /*ARGSUSED*/
1107 struct ifaddr *
1108 ifa_ifwithaddr(struct sockaddr *addr)
1109 {
1110         INIT_VNET_NET(curvnet);
1111         struct ifnet *ifp;
1112         struct ifaddr *ifa;
1113
1114         IFNET_RLOCK();
1115         TAILQ_FOREACH(ifp, &V_ifnet, if_link)
1116                 TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1117                         if (ifa->ifa_addr->sa_family != addr->sa_family)
1118                                 continue;
1119                         if (sa_equal(addr, ifa->ifa_addr))
1120                                 goto done;
1121                         /* IP6 doesn't have broadcast */
1122                         if ((ifp->if_flags & IFF_BROADCAST) &&
1123                             ifa->ifa_broadaddr &&
1124                             ifa->ifa_broadaddr->sa_len != 0 &&
1125                             sa_equal(ifa->ifa_broadaddr, addr))
1126                                 goto done;
1127                 }
1128         ifa = NULL;
1129 done:
1130         IFNET_RUNLOCK();
1131         return (ifa);
1132 }
1133
1134 /*
1135  * Locate an interface based on the broadcast address.
1136  */
1137 /* ARGSUSED */
1138 struct ifaddr *
1139 ifa_ifwithbroadaddr(struct sockaddr *addr)
1140 {
1141         INIT_VNET_NET(curvnet);
1142         struct ifnet *ifp;
1143         struct ifaddr *ifa;
1144
1145         IFNET_RLOCK();
1146         TAILQ_FOREACH(ifp, &V_ifnet, if_link)
1147                 TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1148                         if (ifa->ifa_addr->sa_family != addr->sa_family)
1149                                 continue;
1150                         if ((ifp->if_flags & IFF_BROADCAST) &&
1151                             ifa->ifa_broadaddr &&
1152                             ifa->ifa_broadaddr->sa_len != 0 &&
1153                             sa_equal(ifa->ifa_broadaddr, addr))
1154                                 goto done;
1155                 }
1156         ifa = NULL;
1157 done:
1158         IFNET_RUNLOCK();
1159         return (ifa);
1160 }
1161
1162 /*
1163  * Locate the point to point interface with a given destination address.
1164  */
1165 /*ARGSUSED*/
1166 struct ifaddr *
1167 ifa_ifwithdstaddr(struct sockaddr *addr)
1168 {
1169         INIT_VNET_NET(curvnet);
1170         struct ifnet *ifp;
1171         struct ifaddr *ifa;
1172
1173         IFNET_RLOCK();
1174         TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
1175                 if ((ifp->if_flags & IFF_POINTOPOINT) == 0)
1176                         continue;
1177                 TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1178                         if (ifa->ifa_addr->sa_family != addr->sa_family)
1179                                 continue;
1180                         if (ifa->ifa_dstaddr != NULL &&
1181                             sa_equal(addr, ifa->ifa_dstaddr))
1182                                 goto done;
1183                 }
1184         }
1185         ifa = NULL;
1186 done:
1187         IFNET_RUNLOCK();
1188         return (ifa);
1189 }
1190
1191 /*
1192  * Find an interface on a specific network.  If many, choice
1193  * is most specific found.
1194  */
1195 struct ifaddr *
1196 ifa_ifwithnet(struct sockaddr *addr)
1197 {
1198         INIT_VNET_NET(curvnet);
1199         struct ifnet *ifp;
1200         struct ifaddr *ifa;
1201         struct ifaddr *ifa_maybe = (struct ifaddr *) 0;
1202         u_int af = addr->sa_family;
1203         char *addr_data = addr->sa_data, *cplim;
1204
1205         /*
1206          * AF_LINK addresses can be looked up directly by their index number,
1207          * so do that if we can.
1208          */
1209         if (af == AF_LINK) {
1210             struct sockaddr_dl *sdl = (struct sockaddr_dl *)addr;
1211             if (sdl->sdl_index && sdl->sdl_index <= V_if_index)
1212                 return (ifaddr_byindex(sdl->sdl_index));
1213         }
1214
1215         /*
1216          * Scan though each interface, looking for ones that have
1217          * addresses in this address family.
1218          */
1219         IFNET_RLOCK();
1220         TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
1221                 TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1222                         char *cp, *cp2, *cp3;
1223
1224                         if (ifa->ifa_addr->sa_family != af)
1225 next:                           continue;
1226                         if (af == AF_INET && ifp->if_flags & IFF_POINTOPOINT) {
1227                                 /*
1228                                  * This is a bit broken as it doesn't
1229                                  * take into account that the remote end may
1230                                  * be a single node in the network we are
1231                                  * looking for.
1232                                  * The trouble is that we don't know the
1233                                  * netmask for the remote end.
1234                                  */
1235                                 if (ifa->ifa_dstaddr != NULL &&
1236                                     sa_equal(addr, ifa->ifa_dstaddr))
1237                                         goto done;
1238                         } else {
1239                                 /*
1240                                  * if we have a special address handler,
1241                                  * then use it instead of the generic one.
1242                                  */
1243                                 if (ifa->ifa_claim_addr) {
1244                                         if ((*ifa->ifa_claim_addr)(ifa, addr))
1245                                                 goto done;
1246                                         continue;
1247                                 }
1248
1249                                 /*
1250                                  * Scan all the bits in the ifa's address.
1251                                  * If a bit dissagrees with what we are
1252                                  * looking for, mask it with the netmask
1253                                  * to see if it really matters.
1254                                  * (A byte at a time)
1255                                  */
1256                                 if (ifa->ifa_netmask == 0)
1257                                         continue;
1258                                 cp = addr_data;
1259                                 cp2 = ifa->ifa_addr->sa_data;
1260                                 cp3 = ifa->ifa_netmask->sa_data;
1261                                 cplim = ifa->ifa_netmask->sa_len
1262                                         + (char *)ifa->ifa_netmask;
1263                                 while (cp3 < cplim)
1264                                         if ((*cp++ ^ *cp2++) & *cp3++)
1265                                                 goto next; /* next address! */
1266                                 /*
1267                                  * If the netmask of what we just found
1268                                  * is more specific than what we had before
1269                                  * (if we had one) then remember the new one
1270                                  * before continuing to search
1271                                  * for an even better one.
1272                                  */
1273                                 if (ifa_maybe == 0 ||
1274                                     rn_refines((caddr_t)ifa->ifa_netmask,
1275                                     (caddr_t)ifa_maybe->ifa_netmask))
1276                                         ifa_maybe = ifa;
1277                         }
1278                 }
1279         }
1280         ifa = ifa_maybe;
1281 done:
1282         IFNET_RUNLOCK();
1283         return (ifa);
1284 }
1285
1286 /*
1287  * Find an interface address specific to an interface best matching
1288  * a given address.
1289  */
1290 struct ifaddr *
1291 ifaof_ifpforaddr(struct sockaddr *addr, struct ifnet *ifp)
1292 {
1293         struct ifaddr *ifa;
1294         char *cp, *cp2, *cp3;
1295         char *cplim;
1296         struct ifaddr *ifa_maybe = 0;
1297         u_int af = addr->sa_family;
1298
1299         if (af >= AF_MAX)
1300                 return (0);
1301         TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1302                 if (ifa->ifa_addr->sa_family != af)
1303                         continue;
1304                 if (ifa_maybe == 0)
1305                         ifa_maybe = ifa;
1306                 if (ifa->ifa_netmask == 0) {
1307                         if (sa_equal(addr, ifa->ifa_addr) ||
1308                             (ifa->ifa_dstaddr &&
1309                             sa_equal(addr, ifa->ifa_dstaddr)))
1310                                 goto done;
1311                         continue;
1312                 }
1313                 if (ifp->if_flags & IFF_POINTOPOINT) {
1314                         if (sa_equal(addr, ifa->ifa_dstaddr))
1315                                 goto done;
1316                 } else {
1317                         cp = addr->sa_data;
1318                         cp2 = ifa->ifa_addr->sa_data;
1319                         cp3 = ifa->ifa_netmask->sa_data;
1320                         cplim = ifa->ifa_netmask->sa_len + (char *)ifa->ifa_netmask;
1321                         for (; cp3 < cplim; cp3++)
1322                                 if ((*cp++ ^ *cp2++) & *cp3)
1323                                         break;
1324                         if (cp3 == cplim)
1325                                 goto done;
1326                 }
1327         }
1328         ifa = ifa_maybe;
1329 done:
1330         return (ifa);
1331 }
1332
1333 #include <net/route.h>
1334
1335 /*
1336  * Default action when installing a route with a Link Level gateway.
1337  * Lookup an appropriate real ifa to point to.
1338  * This should be moved to /sys/net/link.c eventually.
1339  */
1340 static void
1341 link_rtrequest(int cmd, struct rtentry *rt, struct rt_addrinfo *info)
1342 {
1343         struct ifaddr *ifa, *oifa;
1344         struct sockaddr *dst;
1345         struct ifnet *ifp;
1346
1347         RT_LOCK_ASSERT(rt);
1348
1349         if (cmd != RTM_ADD || ((ifa = rt->rt_ifa) == 0) ||
1350             ((ifp = ifa->ifa_ifp) == 0) || ((dst = rt_key(rt)) == 0))
1351                 return;
1352         ifa = ifaof_ifpforaddr(dst, ifp);
1353         if (ifa) {
1354                 IFAREF(ifa);            /* XXX */
1355                 oifa = rt->rt_ifa;
1356                 rt->rt_ifa = ifa;
1357                 IFAFREE(oifa);
1358                 if (ifa->ifa_rtrequest && ifa->ifa_rtrequest != link_rtrequest)
1359                         ifa->ifa_rtrequest(cmd, rt, info);
1360         }
1361 }
1362
1363 /*
1364  * Mark an interface down and notify protocols of
1365  * the transition.
1366  * NOTE: must be called at splnet or eqivalent.
1367  */
1368 static void
1369 if_unroute(struct ifnet *ifp, int flag, int fam)
1370 {
1371         struct ifaddr *ifa;
1372
1373         KASSERT(flag == IFF_UP, ("if_unroute: flag != IFF_UP"));
1374
1375         ifp->if_flags &= ~flag;
1376         getmicrotime(&ifp->if_lastchange);
1377         TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
1378                 if (fam == PF_UNSPEC || (fam == ifa->ifa_addr->sa_family))
1379                         pfctlinput(PRC_IFDOWN, ifa->ifa_addr);
1380         if_qflush(&ifp->if_snd);
1381 #ifdef DEV_CARP
1382         if (ifp->if_carp)
1383                 carp_carpdev_state(ifp->if_carp);
1384 #endif
1385         rt_ifmsg(ifp);
1386 }
1387
1388 /*
1389  * Mark an interface up and notify protocols of
1390  * the transition.
1391  * NOTE: must be called at splnet or eqivalent.
1392  */
1393 static void
1394 if_route(struct ifnet *ifp, int flag, int fam)
1395 {
1396         struct ifaddr *ifa;
1397
1398         KASSERT(flag == IFF_UP, ("if_route: flag != IFF_UP"));
1399
1400         ifp->if_flags |= flag;
1401         getmicrotime(&ifp->if_lastchange);
1402         TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
1403                 if (fam == PF_UNSPEC || (fam == ifa->ifa_addr->sa_family))
1404                         pfctlinput(PRC_IFUP, ifa->ifa_addr);
1405 #ifdef DEV_CARP
1406         if (ifp->if_carp)
1407                 carp_carpdev_state(ifp->if_carp);
1408 #endif
1409         rt_ifmsg(ifp);
1410 #ifdef INET6
1411         in6_if_up(ifp);
1412 #endif
1413 }
1414
1415 void    (*vlan_link_state_p)(struct ifnet *, int);      /* XXX: private from if_vlan */
1416 void    (*vlan_trunk_cap_p)(struct ifnet *);            /* XXX: private from if_vlan */
1417
1418 /*
1419  * Handle a change in the interface link state. To avoid LORs
1420  * between driver lock and upper layer locks, as well as possible
1421  * recursions, we post event to taskqueue, and all job
1422  * is done in static do_link_state_change().
1423  */
1424 void
1425 if_link_state_change(struct ifnet *ifp, int link_state)
1426 {
1427         /* Return if state hasn't changed. */
1428         if (ifp->if_link_state == link_state)
1429                 return;
1430
1431         ifp->if_link_state = link_state;
1432
1433         taskqueue_enqueue(taskqueue_swi, &ifp->if_linktask);
1434 }
1435
1436 static void
1437 do_link_state_change(void *arg, int pending)
1438 {
1439         struct ifnet *ifp = (struct ifnet *)arg;
1440         int link_state = ifp->if_link_state;
1441         int link;
1442         CURVNET_SET(ifp->if_vnet);
1443
1444         /* Notify that the link state has changed. */
1445         rt_ifmsg(ifp);
1446         if (link_state == LINK_STATE_UP)
1447                 link = NOTE_LINKUP;
1448         else if (link_state == LINK_STATE_DOWN)
1449                 link = NOTE_LINKDOWN;
1450         else
1451                 link = NOTE_LINKINV;
1452         KNOTE_UNLOCKED(&ifp->if_klist, link);
1453         if (ifp->if_vlantrunk != NULL)
1454                 (*vlan_link_state_p)(ifp, link);
1455
1456         if ((ifp->if_type == IFT_ETHER || ifp->if_type == IFT_L2VLAN) &&
1457             IFP2AC(ifp)->ac_netgraph != NULL)
1458                 (*ng_ether_link_state_p)(ifp, link_state);
1459 #ifdef DEV_CARP
1460         if (ifp->if_carp)
1461                 carp_carpdev_state(ifp->if_carp);
1462 #endif
1463         if (ifp->if_bridge) {
1464                 KASSERT(bstp_linkstate_p != NULL,("if_bridge bstp not loaded!"));
1465                 (*bstp_linkstate_p)(ifp, link_state);
1466         }
1467         if (ifp->if_lagg) {
1468                 KASSERT(lagg_linkstate_p != NULL,("if_lagg not loaded!"));
1469                 (*lagg_linkstate_p)(ifp, link_state);
1470         }
1471
1472         devctl_notify("IFNET", ifp->if_xname,
1473             (link_state == LINK_STATE_UP) ? "LINK_UP" : "LINK_DOWN", NULL);
1474         if (pending > 1)
1475                 if_printf(ifp, "%d link states coalesced\n", pending);
1476         if (log_link_state_change)
1477                 log(LOG_NOTICE, "%s: link state changed to %s\n", ifp->if_xname,
1478                     (link_state == LINK_STATE_UP) ? "UP" : "DOWN" );
1479         CURVNET_RESTORE();
1480 }
1481
1482 /*
1483  * Mark an interface down and notify protocols of
1484  * the transition.
1485  * NOTE: must be called at splnet or eqivalent.
1486  */
1487 void
1488 if_down(struct ifnet *ifp)
1489 {
1490
1491         if_unroute(ifp, IFF_UP, AF_UNSPEC);
1492 }
1493
1494 /*
1495  * Mark an interface up and notify protocols of
1496  * the transition.
1497  * NOTE: must be called at splnet or eqivalent.
1498  */
1499 void
1500 if_up(struct ifnet *ifp)
1501 {
1502
1503         if_route(ifp, IFF_UP, AF_UNSPEC);
1504 }
1505
1506 /*
1507  * Flush an interface queue.
1508  */
1509 static void
1510 if_qflush(struct ifaltq *ifq)
1511 {
1512         struct mbuf *m, *n;
1513
1514         IFQ_LOCK(ifq);
1515 #ifdef ALTQ
1516         if (ALTQ_IS_ENABLED(ifq))
1517                 ALTQ_PURGE(ifq);
1518 #endif
1519         n = ifq->ifq_head;
1520         while ((m = n) != 0) {
1521                 n = m->m_act;
1522                 m_freem(m);
1523         }
1524         ifq->ifq_head = 0;
1525         ifq->ifq_tail = 0;
1526         ifq->ifq_len = 0;
1527         IFQ_UNLOCK(ifq);
1528 }
1529
1530 /*
1531  * Handle interface watchdog timer routines.  Called
1532  * from softclock, we decrement timers (if set) and
1533  * call the appropriate interface routine on expiration.
1534  *
1535  * XXXRW: Note that because timeouts run with Giant, if_watchdog() is called
1536  * holding Giant.  If we switch to an MPSAFE callout, we likely need to grab
1537  * Giant before entering if_watchdog() on an IFF_NEEDSGIANT interface.
1538  */
1539 static void
1540 if_slowtimo(void *arg)
1541 {
1542         VNET_ITERATOR_DECL(vnet_iter);
1543         struct ifnet *ifp;
1544         int s = splimp();
1545
1546         IFNET_RLOCK();
1547         VNET_LIST_RLOCK();
1548         VNET_FOREACH(vnet_iter) {
1549                 CURVNET_SET(vnet_iter);
1550                 INIT_VNET_NET(vnet_iter);
1551                 TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
1552                         if (ifp->if_timer == 0 || --ifp->if_timer)
1553                                 continue;
1554                         if (ifp->if_watchdog)
1555                                 (*ifp->if_watchdog)(ifp);
1556                 }
1557                 CURVNET_RESTORE();
1558         }
1559         VNET_LIST_RUNLOCK();
1560         IFNET_RUNLOCK();
1561         splx(s);
1562         timeout(if_slowtimo, (void *)0, hz / IFNET_SLOWHZ);
1563 }
1564
1565 /*
1566  * Map interface name to
1567  * interface structure pointer.
1568  */
1569 struct ifnet *
1570 ifunit(const char *name)
1571 {
1572         INIT_VNET_NET(curvnet);
1573         struct ifnet *ifp;
1574
1575         IFNET_RLOCK();
1576         TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
1577                 if (strncmp(name, ifp->if_xname, IFNAMSIZ) == 0)
1578                         break;
1579         }
1580         IFNET_RUNLOCK();
1581         return (ifp);
1582 }
1583
1584 /*
1585  * Hardware specific interface ioctls.
1586  */
1587 static int
1588 ifhwioctl(u_long cmd, struct ifnet *ifp, caddr_t data, struct thread *td)
1589 {
1590         struct ifreq *ifr;
1591         struct ifstat *ifs;
1592         int error = 0;
1593         int new_flags, temp_flags;
1594         size_t namelen, onamelen;
1595         char new_name[IFNAMSIZ];
1596         struct ifaddr *ifa;
1597         struct sockaddr_dl *sdl;
1598
1599         ifr = (struct ifreq *)data;
1600         switch (cmd) {
1601         case SIOCGIFINDEX:
1602                 ifr->ifr_index = ifp->if_index;
1603                 break;
1604
1605         case SIOCGIFFLAGS:
1606                 temp_flags = ifp->if_flags | ifp->if_drv_flags;
1607                 ifr->ifr_flags = temp_flags & 0xffff;
1608                 ifr->ifr_flagshigh = temp_flags >> 16;
1609                 break;
1610
1611         case SIOCGIFCAP:
1612                 ifr->ifr_reqcap = ifp->if_capabilities;
1613                 ifr->ifr_curcap = ifp->if_capenable;
1614                 break;
1615
1616 #ifdef MAC
1617         case SIOCGIFMAC:
1618                 error = mac_ifnet_ioctl_get(td->td_ucred, ifr, ifp);
1619                 break;
1620 #endif
1621
1622         case SIOCGIFMETRIC:
1623                 ifr->ifr_metric = ifp->if_metric;
1624                 break;
1625
1626         case SIOCGIFMTU:
1627                 ifr->ifr_mtu = ifp->if_mtu;
1628                 break;
1629
1630         case SIOCGIFPHYS:
1631                 ifr->ifr_phys = ifp->if_physical;
1632                 break;
1633
1634         case SIOCSIFFLAGS:
1635                 error = priv_check(td, PRIV_NET_SETIFFLAGS);
1636                 if (error)
1637                         return (error);
1638                 /*
1639                  * Currently, no driver owned flags pass the IFF_CANTCHANGE
1640                  * check, so we don't need special handling here yet.
1641                  */
1642                 new_flags = (ifr->ifr_flags & 0xffff) |
1643                     (ifr->ifr_flagshigh << 16);
1644                 if (ifp->if_flags & IFF_SMART) {
1645                         /* Smart drivers twiddle their own routes */
1646                 } else if (ifp->if_flags & IFF_UP &&
1647                     (new_flags & IFF_UP) == 0) {
1648                         int s = splimp();
1649                         if_down(ifp);
1650                         splx(s);
1651                 } else if (new_flags & IFF_UP &&
1652                     (ifp->if_flags & IFF_UP) == 0) {
1653                         int s = splimp();
1654                         if_up(ifp);
1655                         splx(s);
1656                 }
1657                 /* See if permanently promiscuous mode bit is about to flip */
1658                 if ((ifp->if_flags ^ new_flags) & IFF_PPROMISC) {
1659                         if (new_flags & IFF_PPROMISC)
1660                                 ifp->if_flags |= IFF_PROMISC;
1661                         else if (ifp->if_pcount == 0)
1662                                 ifp->if_flags &= ~IFF_PROMISC;
1663                         log(LOG_INFO, "%s: permanently promiscuous mode %s\n",
1664                             ifp->if_xname,
1665                             (new_flags & IFF_PPROMISC) ? "enabled" : "disabled");
1666                 }
1667                 ifp->if_flags = (ifp->if_flags & IFF_CANTCHANGE) |
1668                         (new_flags &~ IFF_CANTCHANGE);
1669                 if (ifp->if_ioctl) {
1670                         IFF_LOCKGIANT(ifp);
1671                         (void) (*ifp->if_ioctl)(ifp, cmd, data);
1672                         IFF_UNLOCKGIANT(ifp);
1673                 }
1674                 getmicrotime(&ifp->if_lastchange);
1675                 break;
1676
1677         case SIOCSIFCAP:
1678                 error = priv_check(td, PRIV_NET_SETIFCAP);
1679                 if (error)
1680                         return (error);
1681                 if (ifp->if_ioctl == NULL)
1682                         return (EOPNOTSUPP);
1683                 if (ifr->ifr_reqcap & ~ifp->if_capabilities)
1684                         return (EINVAL);
1685                 IFF_LOCKGIANT(ifp);
1686                 error = (*ifp->if_ioctl)(ifp, cmd, data);
1687                 IFF_UNLOCKGIANT(ifp);
1688                 if (error == 0)
1689                         getmicrotime(&ifp->if_lastchange);
1690                 break;
1691
1692 #ifdef MAC
1693         case SIOCSIFMAC:
1694                 error = mac_ifnet_ioctl_set(td->td_ucred, ifr, ifp);
1695                 break;
1696 #endif
1697
1698         case SIOCSIFNAME:
1699                 error = priv_check(td, PRIV_NET_SETIFNAME);
1700                 if (error)
1701                         return (error);
1702                 error = copyinstr(ifr->ifr_data, new_name, IFNAMSIZ, NULL);
1703                 if (error != 0)
1704                         return (error);
1705                 if (new_name[0] == '\0')
1706                         return (EINVAL);
1707                 if (ifunit(new_name) != NULL)
1708                         return (EEXIST);
1709                 
1710                 /* Announce the departure of the interface. */
1711                 rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
1712                 EVENTHANDLER_INVOKE(ifnet_departure_event, ifp);
1713
1714                 log(LOG_INFO, "%s: changing name to '%s'\n",
1715                     ifp->if_xname, new_name);
1716
1717                 strlcpy(ifp->if_xname, new_name, sizeof(ifp->if_xname));
1718                 ifa = ifp->if_addr;
1719                 IFA_LOCK(ifa);
1720                 sdl = (struct sockaddr_dl *)ifa->ifa_addr;
1721                 namelen = strlen(new_name);
1722                 onamelen = sdl->sdl_nlen;
1723                 /*
1724                  * Move the address if needed.  This is safe because we
1725                  * allocate space for a name of length IFNAMSIZ when we
1726                  * create this in if_attach().
1727                  */
1728                 if (namelen != onamelen) {
1729                         bcopy(sdl->sdl_data + onamelen,
1730                             sdl->sdl_data + namelen, sdl->sdl_alen);
1731                 }
1732                 bcopy(new_name, sdl->sdl_data, namelen);
1733                 sdl->sdl_nlen = namelen;
1734                 sdl = (struct sockaddr_dl *)ifa->ifa_netmask;
1735                 bzero(sdl->sdl_data, onamelen);
1736                 while (namelen != 0)
1737                         sdl->sdl_data[--namelen] = 0xff;
1738                 IFA_UNLOCK(ifa);
1739
1740                 EVENTHANDLER_INVOKE(ifnet_arrival_event, ifp);
1741                 /* Announce the return of the interface. */
1742                 rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
1743                 break;
1744
1745         case SIOCSIFMETRIC:
1746                 error = priv_check(td, PRIV_NET_SETIFMETRIC);
1747                 if (error)
1748                         return (error);
1749                 ifp->if_metric = ifr->ifr_metric;
1750                 getmicrotime(&ifp->if_lastchange);
1751                 break;
1752
1753         case SIOCSIFPHYS:
1754                 error = priv_check(td, PRIV_NET_SETIFPHYS);
1755                 if (error)
1756                         return (error);
1757                 if (ifp->if_ioctl == NULL)
1758                         return (EOPNOTSUPP);
1759                 IFF_LOCKGIANT(ifp);
1760                 error = (*ifp->if_ioctl)(ifp, cmd, data);
1761                 IFF_UNLOCKGIANT(ifp);
1762                 if (error == 0)
1763                         getmicrotime(&ifp->if_lastchange);
1764                 break;
1765
1766         case SIOCSIFMTU:
1767         {
1768                 u_long oldmtu = ifp->if_mtu;
1769
1770                 error = priv_check(td, PRIV_NET_SETIFMTU);
1771                 if (error)
1772                         return (error);
1773                 if (ifr->ifr_mtu < IF_MINMTU || ifr->ifr_mtu > IF_MAXMTU)
1774                         return (EINVAL);
1775                 if (ifp->if_ioctl == NULL)
1776                         return (EOPNOTSUPP);
1777                 IFF_LOCKGIANT(ifp);
1778                 error = (*ifp->if_ioctl)(ifp, cmd, data);
1779                 IFF_UNLOCKGIANT(ifp);
1780                 if (error == 0) {
1781                         getmicrotime(&ifp->if_lastchange);
1782                         rt_ifmsg(ifp);
1783                 }
1784                 /*
1785                  * If the link MTU changed, do network layer specific procedure.
1786                  */
1787                 if (ifp->if_mtu != oldmtu) {
1788 #ifdef INET6
1789                         nd6_setmtu(ifp);
1790 #endif
1791                 }
1792                 break;
1793         }
1794
1795         case SIOCADDMULTI:
1796         case SIOCDELMULTI:
1797                 if (cmd == SIOCADDMULTI)
1798                         error = priv_check(td, PRIV_NET_ADDMULTI);
1799                 else
1800                         error = priv_check(td, PRIV_NET_DELMULTI);
1801                 if (error)
1802                         return (error);
1803
1804                 /* Don't allow group membership on non-multicast interfaces. */
1805                 if ((ifp->if_flags & IFF_MULTICAST) == 0)
1806                         return (EOPNOTSUPP);
1807
1808                 /* Don't let users screw up protocols' entries. */
1809                 if (ifr->ifr_addr.sa_family != AF_LINK)
1810                         return (EINVAL);
1811
1812                 if (cmd == SIOCADDMULTI) {
1813                         struct ifmultiaddr *ifma;
1814
1815                         /*
1816                          * Userland is only permitted to join groups once
1817                          * via the if_addmulti() KPI, because it cannot hold
1818                          * struct ifmultiaddr * between calls. It may also
1819                          * lose a race while we check if the membership
1820                          * already exists.
1821                          */
1822                         IF_ADDR_LOCK(ifp);
1823                         ifma = if_findmulti(ifp, &ifr->ifr_addr);
1824                         IF_ADDR_UNLOCK(ifp);
1825                         if (ifma != NULL)
1826                                 error = EADDRINUSE;
1827                         else
1828                                 error = if_addmulti(ifp, &ifr->ifr_addr, &ifma);
1829                 } else {
1830                         error = if_delmulti(ifp, &ifr->ifr_addr);
1831                 }
1832                 if (error == 0)
1833                         getmicrotime(&ifp->if_lastchange);
1834                 break;
1835
1836         case SIOCSIFPHYADDR:
1837         case SIOCDIFPHYADDR:
1838 #ifdef INET6
1839         case SIOCSIFPHYADDR_IN6:
1840 #endif
1841         case SIOCSLIFPHYADDR:
1842         case SIOCSIFMEDIA:
1843         case SIOCSIFGENERIC:
1844                 error = priv_check(td, PRIV_NET_HWIOCTL);
1845                 if (error)
1846                         return (error);
1847                 if (ifp->if_ioctl == NULL)
1848                         return (EOPNOTSUPP);
1849                 IFF_LOCKGIANT(ifp);
1850                 error = (*ifp->if_ioctl)(ifp, cmd, data);
1851                 IFF_UNLOCKGIANT(ifp);
1852                 if (error == 0)
1853                         getmicrotime(&ifp->if_lastchange);
1854                 break;
1855
1856         case SIOCGIFSTATUS:
1857                 ifs = (struct ifstat *)data;
1858                 ifs->ascii[0] = '\0';
1859
1860         case SIOCGIFPSRCADDR:
1861         case SIOCGIFPDSTADDR:
1862         case SIOCGLIFPHYADDR:
1863         case SIOCGIFMEDIA:
1864         case SIOCGIFGENERIC:
1865                 if (ifp->if_ioctl == NULL)
1866                         return (EOPNOTSUPP);
1867                 IFF_LOCKGIANT(ifp);
1868                 error = (*ifp->if_ioctl)(ifp, cmd, data);
1869                 IFF_UNLOCKGIANT(ifp);
1870                 break;
1871
1872         case SIOCSIFLLADDR:
1873                 error = priv_check(td, PRIV_NET_SETLLADDR);
1874                 if (error)
1875                         return (error);
1876                 error = if_setlladdr(ifp,
1877                     ifr->ifr_addr.sa_data, ifr->ifr_addr.sa_len);
1878                 break;
1879
1880         case SIOCAIFGROUP:
1881         {
1882                 struct ifgroupreq *ifgr = (struct ifgroupreq *)ifr;
1883
1884                 error = priv_check(td, PRIV_NET_ADDIFGROUP);
1885                 if (error)
1886                         return (error);
1887                 if ((error = if_addgroup(ifp, ifgr->ifgr_group)))
1888                         return (error);
1889                 break;
1890         }
1891
1892         case SIOCGIFGROUP:
1893                 if ((error = if_getgroup((struct ifgroupreq *)ifr, ifp)))
1894                         return (error);
1895                 break;
1896
1897         case SIOCDIFGROUP:
1898         {
1899                 struct ifgroupreq *ifgr = (struct ifgroupreq *)ifr;
1900
1901                 error = priv_check(td, PRIV_NET_DELIFGROUP);
1902                 if (error)
1903                         return (error);
1904                 if ((error = if_delgroup(ifp, ifgr->ifgr_group)))
1905                         return (error);
1906                 break;
1907         }
1908
1909         default:
1910                 error = ENOIOCTL;
1911                 break;
1912         }
1913         return (error);
1914 }
1915
1916 /*
1917  * Interface ioctls.
1918  */
1919 int
1920 ifioctl(struct socket *so, u_long cmd, caddr_t data, struct thread *td)
1921 {
1922         struct ifnet *ifp;
1923         struct ifreq *ifr;
1924         int error;
1925         int oif_flags;
1926
1927         switch (cmd) {
1928         case SIOCGIFCONF:
1929         case OSIOCGIFCONF:
1930 #ifdef __amd64__
1931         case SIOCGIFCONF32:
1932 #endif
1933                 return (ifconf(cmd, data));
1934         }
1935         ifr = (struct ifreq *)data;
1936
1937         switch (cmd) {
1938         case SIOCIFCREATE:
1939         case SIOCIFCREATE2:
1940                 error = priv_check(td, PRIV_NET_IFCREATE);
1941                 if (error)
1942                         return (error);
1943                 return (if_clone_create(ifr->ifr_name, sizeof(ifr->ifr_name),
1944                         cmd == SIOCIFCREATE2 ? ifr->ifr_data : NULL));
1945         case SIOCIFDESTROY:
1946                 error = priv_check(td, PRIV_NET_IFDESTROY);
1947                 if (error)
1948                         return (error);
1949                 return if_clone_destroy(ifr->ifr_name);
1950
1951         case SIOCIFGCLONERS:
1952                 return (if_clone_list((struct if_clonereq *)data));
1953         case SIOCGIFGMEMB:
1954                 return (if_getgroupmembers((struct ifgroupreq *)data));
1955         }
1956
1957         ifp = ifunit(ifr->ifr_name);
1958         if (ifp == 0)
1959                 return (ENXIO);
1960
1961         error = ifhwioctl(cmd, ifp, data, td);
1962         if (error != ENOIOCTL)
1963                 return (error);
1964
1965         oif_flags = ifp->if_flags;
1966         if (so->so_proto == 0)
1967                 return (EOPNOTSUPP);
1968 #ifndef COMPAT_43
1969         error = ((*so->so_proto->pr_usrreqs->pru_control)(so, cmd,
1970                                                                  data,
1971                                                                  ifp, td));
1972 #else
1973         {
1974                 int ocmd = cmd;
1975
1976                 switch (cmd) {
1977
1978                 case SIOCSIFDSTADDR:
1979                 case SIOCSIFADDR:
1980                 case SIOCSIFBRDADDR:
1981                 case SIOCSIFNETMASK:
1982 #if BYTE_ORDER != BIG_ENDIAN
1983                         if (ifr->ifr_addr.sa_family == 0 &&
1984                             ifr->ifr_addr.sa_len < 16) {
1985                                 ifr->ifr_addr.sa_family = ifr->ifr_addr.sa_len;
1986                                 ifr->ifr_addr.sa_len = 16;
1987                         }
1988 #else
1989                         if (ifr->ifr_addr.sa_len == 0)
1990                                 ifr->ifr_addr.sa_len = 16;
1991 #endif
1992                         break;
1993
1994                 case OSIOCGIFADDR:
1995                         cmd = SIOCGIFADDR;
1996                         break;
1997
1998                 case OSIOCGIFDSTADDR:
1999                         cmd = SIOCGIFDSTADDR;
2000                         break;
2001
2002                 case OSIOCGIFBRDADDR:
2003                         cmd = SIOCGIFBRDADDR;
2004                         break;
2005
2006                 case OSIOCGIFNETMASK:
2007                         cmd = SIOCGIFNETMASK;
2008                 }
2009                 error =  ((*so->so_proto->pr_usrreqs->pru_control)(so,
2010                                                                    cmd,
2011                                                                    data,
2012                                                                    ifp, td));
2013                 switch (ocmd) {
2014
2015                 case OSIOCGIFADDR:
2016                 case OSIOCGIFDSTADDR:
2017                 case OSIOCGIFBRDADDR:
2018                 case OSIOCGIFNETMASK:
2019                         *(u_short *)&ifr->ifr_addr = ifr->ifr_addr.sa_family;
2020
2021                 }
2022         }
2023 #endif /* COMPAT_43 */
2024
2025         if ((oif_flags ^ ifp->if_flags) & IFF_UP) {
2026 #ifdef INET6
2027                 DELAY(100);/* XXX: temporary workaround for fxp issue*/
2028                 if (ifp->if_flags & IFF_UP) {
2029                         int s = splimp();
2030                         in6_if_up(ifp);
2031                         splx(s);
2032                 }
2033 #endif
2034         }
2035         return (error);
2036 }
2037
2038 /*
2039  * The code common to handling reference counted flags,
2040  * e.g., in ifpromisc() and if_allmulti().
2041  * The "pflag" argument can specify a permanent mode flag to check,
2042  * such as IFF_PPROMISC for promiscuous mode; should be 0 if none.
2043  *
2044  * Only to be used on stack-owned flags, not driver-owned flags.
2045  */
2046 static int
2047 if_setflag(struct ifnet *ifp, int flag, int pflag, int *refcount, int onswitch)
2048 {
2049         struct ifreq ifr;
2050         int error;
2051         int oldflags, oldcount;
2052
2053         /* Sanity checks to catch programming errors */
2054         KASSERT((flag & (IFF_DRV_OACTIVE|IFF_DRV_RUNNING)) == 0,
2055             ("%s: setting driver-owned flag %d", __func__, flag));
2056
2057         if (onswitch)
2058                 KASSERT(*refcount >= 0,
2059                     ("%s: increment negative refcount %d for flag %d",
2060                     __func__, *refcount, flag));
2061         else
2062                 KASSERT(*refcount > 0,
2063                     ("%s: decrement non-positive refcount %d for flag %d",
2064                     __func__, *refcount, flag));
2065
2066         /* In case this mode is permanent, just touch refcount */
2067         if (ifp->if_flags & pflag) {
2068                 *refcount += onswitch ? 1 : -1;
2069                 return (0);
2070         }
2071
2072         /* Save ifnet parameters for if_ioctl() may fail */
2073         oldcount = *refcount;
2074         oldflags = ifp->if_flags;
2075         
2076         /*
2077          * See if we aren't the only and touching refcount is enough.
2078          * Actually toggle interface flag if we are the first or last.
2079          */
2080         if (onswitch) {
2081                 if ((*refcount)++)
2082                         return (0);
2083                 ifp->if_flags |= flag;
2084         } else {
2085                 if (--(*refcount))
2086                         return (0);
2087                 ifp->if_flags &= ~flag;
2088         }
2089
2090         /* Call down the driver since we've changed interface flags */
2091         if (ifp->if_ioctl == NULL) {
2092                 error = EOPNOTSUPP;
2093                 goto recover;
2094         }
2095         ifr.ifr_flags = ifp->if_flags & 0xffff;
2096         ifr.ifr_flagshigh = ifp->if_flags >> 16;
2097         IFF_LOCKGIANT(ifp);
2098         error = (*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
2099         IFF_UNLOCKGIANT(ifp);
2100         if (error)
2101                 goto recover;
2102         /* Notify userland that interface flags have changed */
2103         rt_ifmsg(ifp);
2104         return (0);
2105
2106 recover:
2107         /* Recover after driver error */
2108         *refcount = oldcount;
2109         ifp->if_flags = oldflags;
2110         return (error);
2111 }
2112
2113 /*
2114  * Set/clear promiscuous mode on interface ifp based on the truth value
2115  * of pswitch.  The calls are reference counted so that only the first
2116  * "on" request actually has an effect, as does the final "off" request.
2117  * Results are undefined if the "off" and "on" requests are not matched.
2118  */
2119 int
2120 ifpromisc(struct ifnet *ifp, int pswitch)
2121 {
2122         int error;
2123         int oldflags = ifp->if_flags;
2124
2125         error = if_setflag(ifp, IFF_PROMISC, IFF_PPROMISC,
2126                            &ifp->if_pcount, pswitch);
2127         /* If promiscuous mode status has changed, log a message */
2128         if (error == 0 && ((ifp->if_flags ^ oldflags) & IFF_PROMISC))
2129                 log(LOG_INFO, "%s: promiscuous mode %s\n",
2130                     ifp->if_xname,
2131                     (ifp->if_flags & IFF_PROMISC) ? "enabled" : "disabled");
2132         return (error);
2133 }
2134
2135 /*
2136  * Return interface configuration
2137  * of system.  List may be used
2138  * in later ioctl's (above) to get
2139  * other information.
2140  */
2141 /*ARGSUSED*/
2142 static int
2143 ifconf(u_long cmd, caddr_t data)
2144 {
2145         INIT_VNET_NET(curvnet);
2146         struct ifconf *ifc = (struct ifconf *)data;
2147 #ifdef __amd64__
2148         struct ifconf32 *ifc32 = (struct ifconf32 *)data;
2149         struct ifconf ifc_swab;
2150 #endif
2151         struct ifnet *ifp;
2152         struct ifaddr *ifa;
2153         struct ifreq ifr;
2154         struct sbuf *sb;
2155         int error, full = 0, valid_len, max_len;
2156
2157 #ifdef __amd64__
2158         if (cmd == SIOCGIFCONF32) {
2159                 ifc_swab.ifc_len = ifc32->ifc_len;
2160                 ifc_swab.ifc_buf = (caddr_t)(uintptr_t)ifc32->ifc_buf;
2161                 ifc = &ifc_swab;
2162         }
2163 #endif
2164         /* Limit initial buffer size to MAXPHYS to avoid DoS from userspace. */
2165         max_len = MAXPHYS - 1;
2166
2167         /* Prevent hostile input from being able to crash the system */
2168         if (ifc->ifc_len <= 0)
2169                 return (EINVAL);
2170
2171 again:
2172         if (ifc->ifc_len <= max_len) {
2173                 max_len = ifc->ifc_len;
2174                 full = 1;
2175         }
2176         sb = sbuf_new(NULL, NULL, max_len + 1, SBUF_FIXEDLEN);
2177         max_len = 0;
2178         valid_len = 0;
2179
2180         IFNET_RLOCK();          /* could sleep XXX */
2181         TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2182                 int addrs;
2183
2184                 /*
2185                  * Zero the ifr_name buffer to make sure we don't
2186                  * disclose the contents of the stack.
2187                  */
2188                 memset(ifr.ifr_name, 0, sizeof(ifr.ifr_name));
2189
2190                 if (strlcpy(ifr.ifr_name, ifp->if_xname, sizeof(ifr.ifr_name))
2191                     >= sizeof(ifr.ifr_name)) {
2192                         sbuf_delete(sb);
2193                         IFNET_RUNLOCK();
2194                         return (ENAMETOOLONG);
2195                 }
2196
2197                 addrs = 0;
2198                 TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
2199                         struct sockaddr *sa = ifa->ifa_addr;
2200
2201                         if (jailed(curthread->td_ucred) &&
2202                             prison_if(curthread->td_ucred, sa))
2203                                 continue;
2204                         addrs++;
2205 #ifdef COMPAT_43
2206                         if (cmd == OSIOCGIFCONF) {
2207                                 struct osockaddr *osa =
2208                                          (struct osockaddr *)&ifr.ifr_addr;
2209                                 ifr.ifr_addr = *sa;
2210                                 osa->sa_family = sa->sa_family;
2211                                 sbuf_bcat(sb, &ifr, sizeof(ifr));
2212                                 max_len += sizeof(ifr);
2213                         } else
2214 #endif
2215                         if (sa->sa_len <= sizeof(*sa)) {
2216                                 ifr.ifr_addr = *sa;
2217                                 sbuf_bcat(sb, &ifr, sizeof(ifr));
2218                                 max_len += sizeof(ifr);
2219                         } else {
2220                                 sbuf_bcat(sb, &ifr,
2221                                     offsetof(struct ifreq, ifr_addr));
2222                                 max_len += offsetof(struct ifreq, ifr_addr);
2223                                 sbuf_bcat(sb, sa, sa->sa_len);
2224                                 max_len += sa->sa_len;
2225                         }
2226
2227                         if (!sbuf_overflowed(sb))
2228                                 valid_len = sbuf_len(sb);
2229                 }
2230                 if (addrs == 0) {
2231                         bzero((caddr_t)&ifr.ifr_addr, sizeof(ifr.ifr_addr));
2232                         sbuf_bcat(sb, &ifr, sizeof(ifr));
2233                         max_len += sizeof(ifr);
2234
2235                         if (!sbuf_overflowed(sb))
2236                                 valid_len = sbuf_len(sb);
2237                 }
2238         }
2239         IFNET_RUNLOCK();
2240
2241         /*
2242          * If we didn't allocate enough space (uncommon), try again.  If
2243          * we have already allocated as much space as we are allowed,
2244          * return what we've got.
2245          */
2246         if (valid_len != max_len && !full) {
2247                 sbuf_delete(sb);
2248                 goto again;
2249         }
2250
2251         ifc->ifc_len = valid_len;
2252 #ifdef __amd64__
2253         if (cmd == SIOCGIFCONF32)
2254                 ifc32->ifc_len = valid_len;
2255 #endif
2256         sbuf_finish(sb);
2257         error = copyout(sbuf_data(sb), ifc->ifc_req, ifc->ifc_len);
2258         sbuf_delete(sb);
2259         return (error);
2260 }
2261
2262 /*
2263  * Just like ifpromisc(), but for all-multicast-reception mode.
2264  */
2265 int
2266 if_allmulti(struct ifnet *ifp, int onswitch)
2267 {
2268
2269         return (if_setflag(ifp, IFF_ALLMULTI, 0, &ifp->if_amcount, onswitch));
2270 }
2271
2272 struct ifmultiaddr *
2273 if_findmulti(struct ifnet *ifp, struct sockaddr *sa)
2274 {
2275         struct ifmultiaddr *ifma;
2276
2277         IF_ADDR_LOCK_ASSERT(ifp);
2278
2279         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2280                 if (sa->sa_family == AF_LINK) {
2281                         if (sa_dl_equal(ifma->ifma_addr, sa))
2282                                 break;
2283                 } else {
2284                         if (sa_equal(ifma->ifma_addr, sa))
2285                                 break;
2286                 }
2287         }
2288
2289         return ifma;
2290 }
2291
2292 /*
2293  * Allocate a new ifmultiaddr and initialize based on passed arguments.  We
2294  * make copies of passed sockaddrs.  The ifmultiaddr will not be added to
2295  * the ifnet multicast address list here, so the caller must do that and
2296  * other setup work (such as notifying the device driver).  The reference
2297  * count is initialized to 1.
2298  */
2299 static struct ifmultiaddr *
2300 if_allocmulti(struct ifnet *ifp, struct sockaddr *sa, struct sockaddr *llsa,
2301     int mflags)
2302 {
2303         struct ifmultiaddr *ifma;
2304         struct sockaddr *dupsa;
2305
2306         ifma = malloc(sizeof *ifma, M_IFMADDR, mflags |
2307             M_ZERO);
2308         if (ifma == NULL)
2309                 return (NULL);
2310
2311         dupsa = malloc(sa->sa_len, M_IFMADDR, mflags);
2312         if (dupsa == NULL) {
2313                 free(ifma, M_IFMADDR);
2314                 return (NULL);
2315         }
2316         bcopy(sa, dupsa, sa->sa_len);
2317         ifma->ifma_addr = dupsa;
2318
2319         ifma->ifma_ifp = ifp;
2320         ifma->ifma_refcount = 1;
2321         ifma->ifma_protospec = NULL;
2322
2323         if (llsa == NULL) {
2324                 ifma->ifma_lladdr = NULL;
2325                 return (ifma);
2326         }
2327
2328         dupsa = malloc(llsa->sa_len, M_IFMADDR, mflags);
2329         if (dupsa == NULL) {
2330                 free(ifma->ifma_addr, M_IFMADDR);
2331                 free(ifma, M_IFMADDR);
2332                 return (NULL);
2333         }
2334         bcopy(llsa, dupsa, llsa->sa_len);
2335         ifma->ifma_lladdr = dupsa;
2336
2337         return (ifma);
2338 }
2339
2340 /*
2341  * if_freemulti: free ifmultiaddr structure and possibly attached related
2342  * addresses.  The caller is responsible for implementing reference
2343  * counting, notifying the driver, handling routing messages, and releasing
2344  * any dependent link layer state.
2345  */
2346 static void
2347 if_freemulti(struct ifmultiaddr *ifma)
2348 {
2349
2350         KASSERT(ifma->ifma_refcount == 0, ("if_freemulti: refcount %d",
2351             ifma->ifma_refcount));
2352         KASSERT(ifma->ifma_protospec == NULL,
2353             ("if_freemulti: protospec not NULL"));
2354
2355         if (ifma->ifma_lladdr != NULL)
2356                 free(ifma->ifma_lladdr, M_IFMADDR);
2357         free(ifma->ifma_addr, M_IFMADDR);
2358         free(ifma, M_IFMADDR);
2359 }
2360
2361 /*
2362  * Register an additional multicast address with a network interface.
2363  *
2364  * - If the address is already present, bump the reference count on the
2365  *   address and return.
2366  * - If the address is not link-layer, look up a link layer address.
2367  * - Allocate address structures for one or both addresses, and attach to the
2368  *   multicast address list on the interface.  If automatically adding a link
2369  *   layer address, the protocol address will own a reference to the link
2370  *   layer address, to be freed when it is freed.
2371  * - Notify the network device driver of an addition to the multicast address
2372  *   list.
2373  *
2374  * 'sa' points to caller-owned memory with the desired multicast address.
2375  *
2376  * 'retifma' will be used to return a pointer to the resulting multicast
2377  * address reference, if desired.
2378  */
2379 int
2380 if_addmulti(struct ifnet *ifp, struct sockaddr *sa,
2381     struct ifmultiaddr **retifma)
2382 {
2383         struct ifmultiaddr *ifma, *ll_ifma;
2384         struct sockaddr *llsa;
2385         int error;
2386
2387         /*
2388          * If the address is already present, return a new reference to it;
2389          * otherwise, allocate storage and set up a new address.
2390          */
2391         IF_ADDR_LOCK(ifp);
2392         ifma = if_findmulti(ifp, sa);
2393         if (ifma != NULL) {
2394                 ifma->ifma_refcount++;
2395                 if (retifma != NULL)
2396                         *retifma = ifma;
2397                 IF_ADDR_UNLOCK(ifp);
2398                 return (0);
2399         }
2400
2401         /*
2402          * The address isn't already present; resolve the protocol address
2403          * into a link layer address, and then look that up, bump its
2404          * refcount or allocate an ifma for that also.  If 'llsa' was
2405          * returned, we will need to free it later.
2406          */
2407         llsa = NULL;
2408         ll_ifma = NULL;
2409         if (ifp->if_resolvemulti != NULL) {
2410                 error = ifp->if_resolvemulti(ifp, &llsa, sa);
2411                 if (error)
2412                         goto unlock_out;
2413         }
2414
2415         /*
2416          * Allocate the new address.  Don't hook it up yet, as we may also
2417          * need to allocate a link layer multicast address.
2418          */
2419         ifma = if_allocmulti(ifp, sa, llsa, M_NOWAIT);
2420         if (ifma == NULL) {
2421                 error = ENOMEM;
2422                 goto free_llsa_out;
2423         }
2424
2425         /*
2426          * If a link layer address is found, we'll need to see if it's
2427          * already present in the address list, or allocate is as well.
2428          * When this block finishes, the link layer address will be on the
2429          * list.
2430          */
2431         if (llsa != NULL) {
2432                 ll_ifma = if_findmulti(ifp, llsa);
2433                 if (ll_ifma == NULL) {
2434                         ll_ifma = if_allocmulti(ifp, llsa, NULL, M_NOWAIT);
2435                         if (ll_ifma == NULL) {
2436                                 --ifma->ifma_refcount;
2437                                 if_freemulti(ifma);
2438                                 error = ENOMEM;
2439                                 goto free_llsa_out;
2440                         }
2441                         TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ll_ifma,
2442                             ifma_link);
2443                 } else
2444                         ll_ifma->ifma_refcount++;
2445                 ifma->ifma_llifma = ll_ifma;
2446         }
2447
2448         /*
2449          * We now have a new multicast address, ifma, and possibly a new or
2450          * referenced link layer address.  Add the primary address to the
2451          * ifnet address list.
2452          */
2453         TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ifma, ifma_link);
2454
2455         if (retifma != NULL)
2456                 *retifma = ifma;
2457
2458         /*
2459          * Must generate the message while holding the lock so that 'ifma'
2460          * pointer is still valid.
2461          */
2462         rt_newmaddrmsg(RTM_NEWMADDR, ifma);
2463         IF_ADDR_UNLOCK(ifp);
2464
2465         /*
2466          * We are certain we have added something, so call down to the
2467          * interface to let them know about it.
2468          */
2469         if (ifp->if_ioctl != NULL) {
2470                 IFF_LOCKGIANT(ifp);
2471                 (void) (*ifp->if_ioctl)(ifp, SIOCADDMULTI, 0);
2472                 IFF_UNLOCKGIANT(ifp);
2473         }
2474
2475         if (llsa != NULL)
2476                 free(llsa, M_IFMADDR);
2477
2478         return (0);
2479
2480 free_llsa_out:
2481         if (llsa != NULL)
2482                 free(llsa, M_IFMADDR);
2483
2484 unlock_out:
2485         IF_ADDR_UNLOCK(ifp);
2486         return (error);
2487 }
2488
2489 /*
2490  * Delete a multicast group membership by network-layer group address.
2491  *
2492  * Returns ENOENT if the entry could not be found. If ifp no longer
2493  * exists, results are undefined. This entry point should only be used
2494  * from subsystems which do appropriate locking to hold ifp for the
2495  * duration of the call.
2496  * Network-layer protocol domains must use if_delmulti_ifma().
2497  */
2498 int
2499 if_delmulti(struct ifnet *ifp, struct sockaddr *sa)
2500 {
2501         struct ifmultiaddr *ifma;
2502         int lastref;
2503 #ifdef INVARIANTS
2504         struct ifnet *oifp;
2505         INIT_VNET_NET(ifp->if_vnet);
2506
2507         IFNET_RLOCK();
2508         TAILQ_FOREACH(oifp, &V_ifnet, if_link)
2509                 if (ifp == oifp)
2510                         break;
2511         if (ifp != oifp)
2512                 ifp = NULL;
2513         IFNET_RUNLOCK();
2514
2515         KASSERT(ifp != NULL, ("%s: ifnet went away", __func__));
2516 #endif
2517         if (ifp == NULL)
2518                 return (ENOENT);
2519
2520         IF_ADDR_LOCK(ifp);
2521         lastref = 0;
2522         ifma = if_findmulti(ifp, sa);
2523         if (ifma != NULL)
2524                 lastref = if_delmulti_locked(ifp, ifma, 0);
2525         IF_ADDR_UNLOCK(ifp);
2526
2527         if (ifma == NULL)
2528                 return (ENOENT);
2529
2530         if (lastref && ifp->if_ioctl != NULL) {
2531                 IFF_LOCKGIANT(ifp);
2532                 (void)(*ifp->if_ioctl)(ifp, SIOCDELMULTI, 0);
2533                 IFF_UNLOCKGIANT(ifp);
2534         }
2535
2536         return (0);
2537 }
2538
2539 /*
2540  * Delete a multicast group membership by group membership pointer.
2541  * Network-layer protocol domains must use this routine.
2542  *
2543  * It is safe to call this routine if the ifp disappeared. Callers should
2544  * hold IFF_LOCKGIANT() to avoid a LOR in case the hardware needs to be
2545  * reconfigured.
2546  */
2547 void
2548 if_delmulti_ifma(struct ifmultiaddr *ifma)
2549 {
2550 #ifdef DIAGNOSTIC
2551         INIT_VNET_NET(curvnet);
2552 #endif
2553         struct ifnet *ifp;
2554         int lastref;
2555
2556         ifp = ifma->ifma_ifp;
2557 #ifdef DIAGNOSTIC
2558         if (ifp == NULL) {
2559                 printf("%s: ifma_ifp seems to be detached\n", __func__);
2560         } else {
2561                 struct ifnet *oifp;
2562
2563                 IFNET_RLOCK();
2564                 TAILQ_FOREACH(oifp, &V_ifnet, if_link)
2565                         if (ifp == oifp)
2566                                 break;
2567                 if (ifp != oifp) {
2568                         printf("%s: ifnet %p disappeared\n", __func__, ifp);
2569                         ifp = NULL;
2570                 }
2571                 IFNET_RUNLOCK();
2572         }
2573 #endif
2574         /*
2575          * If and only if the ifnet instance exists: Acquire the address lock.
2576          */
2577         if (ifp != NULL)
2578                 IF_ADDR_LOCK(ifp);
2579
2580         lastref = if_delmulti_locked(ifp, ifma, 0);
2581
2582         if (ifp != NULL) {
2583                 /*
2584                  * If and only if the ifnet instance exists:
2585                  *  Release the address lock.
2586                  *  If the group was left: update the hardware hash filter.
2587                  */
2588                 IF_ADDR_UNLOCK(ifp);
2589                 if (lastref && ifp->if_ioctl != NULL) {
2590                         IFF_LOCKGIANT(ifp);
2591                         (void)(*ifp->if_ioctl)(ifp, SIOCDELMULTI, 0);
2592                         IFF_UNLOCKGIANT(ifp);
2593                 }
2594         }
2595 }
2596
2597 /*
2598  * Perform deletion of network-layer and/or link-layer multicast address.
2599  *
2600  * Return 0 if the reference count was decremented.
2601  * Return 1 if the final reference was released, indicating that the
2602  * hardware hash filter should be reprogrammed.
2603  */
2604 static int
2605 if_delmulti_locked(struct ifnet *ifp, struct ifmultiaddr *ifma, int detaching)
2606 {
2607         struct ifmultiaddr *ll_ifma;
2608
2609         if (ifp != NULL && ifma->ifma_ifp != NULL) {
2610                 KASSERT(ifma->ifma_ifp == ifp,
2611                     ("%s: inconsistent ifp %p", __func__, ifp));
2612                 IF_ADDR_LOCK_ASSERT(ifp);
2613         }
2614
2615         ifp = ifma->ifma_ifp;
2616
2617         /*
2618          * If the ifnet is detaching, null out references to ifnet,
2619          * so that upper protocol layers will notice, and not attempt
2620          * to obtain locks for an ifnet which no longer exists. The
2621          * routing socket announcement must happen before the ifnet
2622          * instance is detached from the system.
2623          */
2624         if (detaching) {
2625 #ifdef DIAGNOSTIC
2626                 printf("%s: detaching ifnet instance %p\n", __func__, ifp);
2627 #endif
2628                 /*
2629                  * ifp may already be nulled out if we are being reentered
2630                  * to delete the ll_ifma.
2631                  */
2632                 if (ifp != NULL) {
2633                         rt_newmaddrmsg(RTM_DELMADDR, ifma);
2634                         ifma->ifma_ifp = NULL;
2635                 }
2636         }
2637
2638         if (--ifma->ifma_refcount > 0)
2639                 return 0;
2640
2641         /*
2642          * If this ifma is a network-layer ifma, a link-layer ifma may
2643          * have been associated with it. Release it first if so.
2644          */
2645         ll_ifma = ifma->ifma_llifma;
2646         if (ll_ifma != NULL) {
2647                 KASSERT(ifma->ifma_lladdr != NULL,
2648                     ("%s: llifma w/o lladdr", __func__));
2649                 if (detaching)
2650                         ll_ifma->ifma_ifp = NULL;       /* XXX */
2651                 if (--ll_ifma->ifma_refcount == 0) {
2652                         if (ifp != NULL) {
2653                                 TAILQ_REMOVE(&ifp->if_multiaddrs, ll_ifma,
2654                                     ifma_link);
2655                         }
2656                         if_freemulti(ll_ifma);
2657                 }
2658         }
2659
2660         if (ifp != NULL)
2661                 TAILQ_REMOVE(&ifp->if_multiaddrs, ifma, ifma_link);
2662
2663         if_freemulti(ifma);
2664
2665         /*
2666          * The last reference to this instance of struct ifmultiaddr
2667          * was released; the hardware should be notified of this change.
2668          */
2669         return 1;
2670 }
2671
2672 /*
2673  * Set the link layer address on an interface.
2674  *
2675  * At this time we only support certain types of interfaces,
2676  * and we don't allow the length of the address to change.
2677  */
2678 int
2679 if_setlladdr(struct ifnet *ifp, const u_char *lladdr, int len)
2680 {
2681         struct sockaddr_dl *sdl;
2682         struct ifaddr *ifa;
2683         struct ifreq ifr;
2684
2685         ifa = ifp->if_addr;
2686         if (ifa == NULL)
2687                 return (EINVAL);
2688         sdl = (struct sockaddr_dl *)ifa->ifa_addr;
2689         if (sdl == NULL)
2690                 return (EINVAL);
2691         if (len != sdl->sdl_alen)       /* don't allow length to change */
2692                 return (EINVAL);
2693         switch (ifp->if_type) {
2694         case IFT_ETHER:
2695         case IFT_FDDI:
2696         case IFT_XETHER:
2697         case IFT_ISO88025:
2698         case IFT_L2VLAN:
2699         case IFT_BRIDGE:
2700         case IFT_ARCNET:
2701         case IFT_IEEE8023ADLAG:
2702                 bcopy(lladdr, LLADDR(sdl), len);
2703                 break;
2704         default:
2705                 return (ENODEV);
2706         }
2707         /*
2708          * If the interface is already up, we need
2709          * to re-init it in order to reprogram its
2710          * address filter.
2711          */
2712         if ((ifp->if_flags & IFF_UP) != 0) {
2713                 if (ifp->if_ioctl) {
2714                         IFF_LOCKGIANT(ifp);
2715                         ifp->if_flags &= ~IFF_UP;
2716                         ifr.ifr_flags = ifp->if_flags & 0xffff;
2717                         ifr.ifr_flagshigh = ifp->if_flags >> 16;
2718                         (*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
2719                         ifp->if_flags |= IFF_UP;
2720                         ifr.ifr_flags = ifp->if_flags & 0xffff;
2721                         ifr.ifr_flagshigh = ifp->if_flags >> 16;
2722                         (*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
2723                         IFF_UNLOCKGIANT(ifp);
2724                 }
2725 #ifdef INET
2726                 /*
2727                  * Also send gratuitous ARPs to notify other nodes about
2728                  * the address change.
2729                  */
2730                 TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
2731                         if (ifa->ifa_addr->sa_family == AF_INET)
2732                                 arp_ifinit(ifp, ifa);
2733                 }
2734 #endif
2735         }
2736         return (0);
2737 }
2738
2739 /*
2740  * The name argument must be a pointer to storage which will last as
2741  * long as the interface does.  For physical devices, the result of
2742  * device_get_name(dev) is a good choice and for pseudo-devices a
2743  * static string works well.
2744  */
2745 void
2746 if_initname(struct ifnet *ifp, const char *name, int unit)
2747 {
2748         ifp->if_dname = name;
2749         ifp->if_dunit = unit;
2750         if (unit != IF_DUNIT_NONE)
2751                 snprintf(ifp->if_xname, IFNAMSIZ, "%s%d", name, unit);
2752         else
2753                 strlcpy(ifp->if_xname, name, IFNAMSIZ);
2754 }
2755
2756 int
2757 if_printf(struct ifnet *ifp, const char * fmt, ...)
2758 {
2759         va_list ap;
2760         int retval;
2761
2762         retval = printf("%s: ", ifp->if_xname);
2763         va_start(ap, fmt);
2764         retval += vprintf(fmt, ap);
2765         va_end(ap);
2766         return (retval);
2767 }
2768
2769 /*
2770  * When an interface is marked IFF_NEEDSGIANT, its if_start() routine cannot
2771  * be called without Giant.  However, we often can't acquire the Giant lock
2772  * at those points; instead, we run it via a task queue that holds Giant via
2773  * if_start_deferred.
2774  *
2775  * XXXRW: We need to make sure that the ifnet isn't fully detached until any
2776  * outstanding if_start_deferred() tasks that will run after the free.  This
2777  * probably means waiting in if_detach().
2778  */
2779 void
2780 if_start(struct ifnet *ifp)
2781 {
2782
2783         if (ifp->if_flags & IFF_NEEDSGIANT) {
2784                 if (mtx_owned(&Giant))
2785                         (*(ifp)->if_start)(ifp);
2786                 else
2787                         taskqueue_enqueue(taskqueue_swi_giant,
2788                             &ifp->if_starttask);
2789         } else
2790                 (*(ifp)->if_start)(ifp);
2791 }
2792
2793 static void
2794 if_start_deferred(void *context, int pending)
2795 {
2796         struct ifnet *ifp;
2797
2798         GIANT_REQUIRED;
2799
2800         ifp = context;
2801         (ifp->if_start)(ifp);
2802 }
2803
2804 int
2805 if_handoff(struct ifqueue *ifq, struct mbuf *m, struct ifnet *ifp, int adjust)
2806 {
2807         int active = 0;
2808
2809         IF_LOCK(ifq);
2810         if (_IF_QFULL(ifq)) {
2811                 _IF_DROP(ifq);
2812                 IF_UNLOCK(ifq);
2813                 m_freem(m);
2814                 return (0);
2815         }
2816         if (ifp != NULL) {
2817                 ifp->if_obytes += m->m_pkthdr.len + adjust;
2818                 if (m->m_flags & (M_BCAST|M_MCAST))
2819                         ifp->if_omcasts++;
2820                 active = ifp->if_drv_flags & IFF_DRV_OACTIVE;
2821         }
2822         _IF_ENQUEUE(ifq, m);
2823         IF_UNLOCK(ifq);
2824         if (ifp != NULL && !active)
2825                 if_start(ifp);
2826         return (1);
2827 }
2828
2829 void
2830 if_register_com_alloc(u_char type,
2831     if_com_alloc_t *a, if_com_free_t *f)
2832 {
2833         
2834         KASSERT(if_com_alloc[type] == NULL,
2835             ("if_register_com_alloc: %d already registered", type));
2836         KASSERT(if_com_free[type] == NULL,
2837             ("if_register_com_alloc: %d free already registered", type));
2838
2839         if_com_alloc[type] = a;
2840         if_com_free[type] = f;
2841 }
2842
2843 void
2844 if_deregister_com_alloc(u_char type)
2845 {
2846         
2847         KASSERT(if_com_alloc[type] != NULL,
2848             ("if_deregister_com_alloc: %d not registered", type));
2849         KASSERT(if_com_free[type] != NULL,
2850             ("if_deregister_com_alloc: %d free not registered", type));
2851         if_com_alloc[type] = NULL;
2852         if_com_free[type] = NULL;
2853 }