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