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