]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/net/if.c
Protect link layer network interface multicast address list manipulation
[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/mac.h>
43 #include <sys/malloc.h>
44 #include <sys/sbuf.h>
45 #include <sys/bus.h>
46 #include <sys/mbuf.h>
47 #include <sys/systm.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_arp.h>
63 #include <net/if_clone.h>
64 #include <net/if_dl.h>
65 #include <net/if_types.h>
66 #include <net/if_var.h>
67 #include <net/radix.h>
68 #include <net/route.h>
69
70 #if defined(INET) || defined(INET6)
71 /*XXX*/
72 #include <netinet/in.h>
73 #include <netinet/in_var.h>
74 #ifdef INET6
75 #include <netinet6/in6_var.h>
76 #include <netinet6/in6_ifattach.h>
77 #endif
78 #endif
79 #ifdef INET
80 #include <netinet/if_ether.h>
81 #endif
82 #ifdef DEV_CARP
83 #include <netinet/ip_carp.h>
84 #endif
85
86 SYSCTL_NODE(_net, PF_LINK, link, CTLFLAG_RW, 0, "Link layers");
87 SYSCTL_NODE(_net_link, 0, generic, CTLFLAG_RW, 0, "Generic link-management");
88
89 /* Log link state change events */
90 static int log_link_state_change = 1;
91
92 SYSCTL_INT(_net_link, OID_AUTO, log_link_state_change, CTLFLAG_RW,
93         &log_link_state_change, 0,
94         "log interface link state change events");
95
96 void    (*bstp_linkstate_p)(struct ifnet *ifp, int state);
97 void    (*ng_ether_link_state_p)(struct ifnet *ifp, int state);
98
99 struct mbuf *(*tbr_dequeue_ptr)(struct ifaltq *, int) = NULL;
100
101 static void     if_attachdomain(void *);
102 static void     if_attachdomain1(struct ifnet *);
103 static int      ifconf(u_long, caddr_t);
104 static void     if_grow(void);
105 static void     if_init(void *);
106 static void     if_check(void *);
107 static int      if_findindex(struct ifnet *);
108 static void     if_qflush(struct ifaltq *);
109 static void     if_route(struct ifnet *, int flag, int fam);
110 static int      if_setflag(struct ifnet *, int, int, int *, int);
111 static void     if_slowtimo(void *);
112 static void     if_unroute(struct ifnet *, int flag, int fam);
113 static void     link_rtrequest(int, struct rtentry *, struct rt_addrinfo *);
114 static int      if_rtdel(struct radix_node *, void *);
115 static int      ifhwioctl(u_long, struct ifnet *, caddr_t, struct thread *);
116 static void     if_start_deferred(void *context, int pending);
117 static void     do_link_state_change(void *, int);
118 #ifdef INET6
119 /*
120  * XXX: declare here to avoid to include many inet6 related files..
121  * should be more generalized?
122  */
123 extern void     nd6_setmtu(struct ifnet *);
124 #endif
125
126 int     if_index = 0;
127 struct  ifindex_entry *ifindex_table = NULL;
128 int     ifqmaxlen = IFQ_MAXLEN;
129 struct  ifnethead ifnet;        /* depend on static init XXX */
130 struct  mtx ifnet_lock;
131 static  if_com_alloc_t *if_com_alloc[256];
132 static  if_com_free_t *if_com_free[256];
133
134 static int      if_indexlim = 8;
135 static struct   knlist ifklist;
136
137 static void     filt_netdetach(struct knote *kn);
138 static int      filt_netdev(struct knote *kn, long hint);
139
140 static struct filterops netdev_filtops =
141     { 1, NULL, filt_netdetach, filt_netdev };
142
143 /*
144  * System initialization
145  */
146 SYSINIT(interfaces, SI_SUB_INIT_IF, SI_ORDER_FIRST, if_init, NULL)
147 SYSINIT(interface_check, SI_SUB_PROTO_IF, SI_ORDER_FIRST, if_check, NULL)
148
149 MALLOC_DEFINE(M_IFNET, "ifnet", "interface internals");
150 MALLOC_DEFINE(M_IFADDR, "ifaddr", "interface address");
151 MALLOC_DEFINE(M_IFMADDR, "ether_multi", "link-level multicast address");
152
153 static d_open_t         netopen;
154 static d_close_t        netclose;
155 static d_ioctl_t        netioctl;
156 static d_kqfilter_t     netkqfilter;
157
158 static struct cdevsw net_cdevsw = {
159         .d_version =    D_VERSION,
160         .d_flags =      D_NEEDGIANT,
161         .d_open =       netopen,
162         .d_close =      netclose,
163         .d_ioctl =      netioctl,
164         .d_name =       "net",
165         .d_kqfilter =   netkqfilter,
166 };
167
168 static int
169 netopen(struct cdev *dev, int flag, int mode, struct thread *td)
170 {
171         return (0);
172 }
173
174 static int
175 netclose(struct cdev *dev, int flags, int fmt, struct thread *td)
176 {
177         return (0);
178 }
179
180 static int
181 netioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
182 {
183         struct ifnet *ifp;
184         int error, idx;
185
186         /* only support interface specific ioctls */
187         if (IOCGROUP(cmd) != 'i')
188                 return (EOPNOTSUPP);
189         idx = minor(dev);
190         if (idx == 0) {
191                 /*
192                  * special network device, not interface.
193                  */
194                 if (cmd == SIOCGIFCONF)
195                         return (ifconf(cmd, data));     /* XXX remove cmd */
196                 return (EOPNOTSUPP);
197         }
198
199         ifp = ifnet_byindex(idx);
200         if (ifp == NULL)
201                 return (ENXIO);
202
203         error = ifhwioctl(cmd, ifp, data, td);
204         if (error == ENOIOCTL)
205                 error = EOPNOTSUPP;
206         return (error);
207 }
208
209 static int
210 netkqfilter(struct cdev *dev, struct knote *kn)
211 {
212         struct knlist *klist;
213         struct ifnet *ifp;
214         int idx;
215
216         switch (kn->kn_filter) {
217         case EVFILT_NETDEV:
218                 kn->kn_fop = &netdev_filtops;
219                 break;
220         default:
221                 return (1);
222         }
223
224         idx = minor(dev);
225         if (idx == 0) {
226                 klist = &ifklist;
227         } else {
228                 ifp = ifnet_byindex(idx);
229                 if (ifp == NULL)
230                         return (1);
231                 klist = &ifp->if_klist;
232         }
233
234         kn->kn_hook = (caddr_t)klist;
235
236         knlist_add(klist, kn, 0);
237
238         return (0);
239 }
240
241 static void
242 filt_netdetach(struct knote *kn)
243 {
244         struct knlist *klist = (struct knlist *)kn->kn_hook;
245
246         knlist_remove(klist, kn, 0);
247 }
248
249 static int
250 filt_netdev(struct knote *kn, long hint)
251 {
252         struct knlist *klist = (struct knlist *)kn->kn_hook;
253
254         /*
255          * Currently NOTE_EXIT is abused to indicate device detach.
256          */
257         if (hint == NOTE_EXIT) {
258                 kn->kn_data = NOTE_LINKINV;
259                 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
260                 knlist_remove_inevent(klist, kn);
261                 return (1);
262         }
263         if (hint != 0)
264                 kn->kn_data = hint;                     /* current status */
265         if (kn->kn_sfflags & hint)
266                 kn->kn_fflags |= hint;
267         return (kn->kn_fflags != 0);
268 }
269
270 /*
271  * Network interface utility routines.
272  *
273  * Routines with ifa_ifwith* names take sockaddr *'s as
274  * parameters.
275  */
276 /* ARGSUSED*/
277 static void
278 if_init(void *dummy __unused)
279 {
280
281         IFNET_LOCK_INIT();
282         TAILQ_INIT(&ifnet);
283         knlist_init(&ifklist, NULL, NULL, NULL, NULL);
284         if_grow();                              /* create initial table */
285         ifdev_byindex(0) = make_dev(&net_cdevsw, 0,
286             UID_ROOT, GID_WHEEL, 0600, "network");
287         if_clone_init();
288 }
289
290 static void
291 if_grow(void)
292 {
293         u_int n;
294         struct ifindex_entry *e;
295
296         if_indexlim <<= 1;
297         n = if_indexlim * sizeof(*e);
298         e = malloc(n, M_IFNET, M_WAITOK | M_ZERO);
299         if (ifindex_table != NULL) {
300                 memcpy((caddr_t)e, (caddr_t)ifindex_table, n/2);
301                 free((caddr_t)ifindex_table, M_IFNET);
302         }
303         ifindex_table = e;
304 }
305
306 /* ARGSUSED*/
307 static void
308 if_check(void *dummy __unused)
309 {
310         struct ifnet *ifp;
311         int s;
312
313         s = splimp();
314         IFNET_RLOCK();  /* could sleep on rare error; mostly okay XXX */
315         TAILQ_FOREACH(ifp, &ifnet, if_link) {
316                 if (ifp->if_snd.ifq_maxlen == 0) {
317                         if_printf(ifp, "XXX: driver didn't set ifq_maxlen\n");
318                         ifp->if_snd.ifq_maxlen = ifqmaxlen;
319                 }
320                 if (!mtx_initialized(&ifp->if_snd.ifq_mtx)) {
321                         if_printf(ifp,
322                             "XXX: driver didn't initialize queue mtx\n");
323                         mtx_init(&ifp->if_snd.ifq_mtx, "unknown",
324                             MTX_NETWORK_LOCK, MTX_DEF);
325                 }
326         }
327         IFNET_RUNLOCK();
328         splx(s);
329         if_slowtimo(0);
330 }
331
332 /* XXX: should be locked. */
333 static int
334 if_findindex(struct ifnet *ifp)
335 {
336         int i, unit;
337         char eaddr[18], devname[32];
338         const char *name, *p;
339
340         switch (ifp->if_type) {
341         case IFT_ETHER:                 /* these types use struct arpcom */
342         case IFT_FDDI:
343         case IFT_XETHER:
344         case IFT_ISO88025:
345         case IFT_L2VLAN:
346         case IFT_BRIDGE:
347                 snprintf(eaddr, 18, "%6D", IFP2ENADDR(ifp), ":");
348                 break;
349         default:
350                 eaddr[0] = '\0';
351                 break;
352         }
353         strlcpy(devname, ifp->if_xname, sizeof(devname));
354         name = net_cdevsw.d_name;
355         i = 0;
356         while ((resource_find_dev(&i, name, &unit, NULL, NULL)) == 0) {
357                 if (resource_string_value(name, unit, "ether", &p) == 0)
358                         if (strcmp(p, eaddr) == 0)
359                                 goto found;
360                 if (resource_string_value(name, unit, "dev", &p) == 0)
361                         if (strcmp(p, devname) == 0)
362                                 goto found;
363         }
364         unit = 0;
365 found:
366         if (unit != 0) {
367                 if (ifaddr_byindex(unit) == NULL)
368                         return (unit);
369                 printf("%s%d in use, cannot hardwire it to %s.\n",
370                     name, unit, devname);
371         }
372         for (unit = 1; ; unit++) {
373                 if (unit <= if_index && ifaddr_byindex(unit) != NULL)
374                         continue;
375                 if (resource_string_value(name, unit, "ether", &p) == 0 ||
376                     resource_string_value(name, unit, "dev", &p) == 0)
377                         continue;
378                 break;
379         }
380         return (unit);
381 }
382
383 /*
384  * Allocate a struct ifnet and in index for an interface.
385  */
386 struct ifnet*
387 if_alloc(u_char type)
388 {
389         struct ifnet *ifp;
390
391         ifp = malloc(sizeof(struct ifnet), M_IFNET, M_WAITOK|M_ZERO);
392
393         /* XXX: This should fail if if_index is too big */
394         ifp->if_index = if_findindex(ifp);
395         if (ifp->if_index > if_index)
396                 if_index = ifp->if_index;
397         if (if_index >= if_indexlim)
398                 if_grow();
399
400         ifnet_byindex(ifp->if_index) = ifp;
401
402         ifp->if_type = type;
403
404         if (if_com_alloc[type] != NULL) {
405                 ifp->if_l2com = if_com_alloc[type](type, ifp);
406                 if (ifp->if_l2com == NULL) {
407                         free(ifp, M_IFNET);
408                         return (NULL);
409                 }
410         }
411
412         return (ifp);
413 }
414
415 void
416 if_free(struct ifnet *ifp)
417 {
418
419         if_free_type(ifp, ifp->if_type);
420
421         IF_ADDR_LOCK_DESTROY(ifp);
422 }
423
424 void
425 if_free_type(struct ifnet *ifp, u_char type)
426 {
427
428         if (ifp != ifnet_byindex(ifp->if_index)) {
429                 if_printf(ifp, "%s: value was not if_alloced, skipping\n",
430                     __func__);
431                 return;
432         }
433
434         ifnet_byindex(ifp->if_index) = NULL;
435
436         /* XXX: should be locked with if_findindex() */
437         while (if_index > 0 && ifaddr_byindex(if_index) == NULL)
438                 if_index--;
439
440         if (if_com_free[type] != NULL)
441                 if_com_free[type](ifp->if_l2com, type);
442
443         free(ifp, M_IFNET);
444 };
445
446 /*
447  * Attach an interface to the
448  * list of "active" interfaces.
449  */
450 void
451 if_attach(struct ifnet *ifp)
452 {
453         unsigned socksize, ifasize;
454         int namelen, masklen;
455         struct sockaddr_dl *sdl;
456         struct ifaddr *ifa;
457
458         if (ifp->if_index == 0 || ifp != ifnet_byindex(ifp->if_index))
459                 panic ("%s: BUG: if_attach called without if_alloc'd input()\n",
460                     ifp->if_xname);
461
462         TASK_INIT(&ifp->if_starttask, 0, if_start_deferred, ifp);
463         TASK_INIT(&ifp->if_linktask, 0, do_link_state_change, ifp);
464         IF_AFDATA_LOCK_INIT(ifp);
465         IF_ADDR_LOCK_INIT(ifp);
466         ifp->if_afdata_initialized = 0;
467         IFNET_WLOCK();
468         TAILQ_INSERT_TAIL(&ifnet, ifp, if_link);
469         IFNET_WUNLOCK();
470         /*
471          * XXX -
472          * The old code would work if the interface passed a pre-existing
473          * chain of ifaddrs to this code.  We don't trust our callers to
474          * properly initialize the tailq, however, so we no longer allow
475          * this unlikely case.
476          */
477         TAILQ_INIT(&ifp->if_addrhead);
478         TAILQ_INIT(&ifp->if_prefixhead);
479         TAILQ_INIT(&ifp->if_multiaddrs);
480         knlist_init(&ifp->if_klist, NULL, NULL, NULL, NULL);
481         getmicrotime(&ifp->if_lastchange);
482         ifp->if_data.ifi_epoch = time_uptime;
483         ifp->if_data.ifi_datalen = sizeof(struct if_data);
484
485 #ifdef MAC
486         mac_init_ifnet(ifp);
487         mac_create_ifnet(ifp);
488 #endif
489
490         ifdev_byindex(ifp->if_index) = make_dev(&net_cdevsw,
491             unit2minor(ifp->if_index),
492             UID_ROOT, GID_WHEEL, 0600, "%s/%s",
493             net_cdevsw.d_name, ifp->if_xname);
494         make_dev_alias(ifdev_byindex(ifp->if_index), "%s%d",
495             net_cdevsw.d_name, ifp->if_index);
496
497         mtx_init(&ifp->if_snd.ifq_mtx, ifp->if_xname, "if send queue", MTX_DEF);
498
499         /*
500          * create a Link Level name for this device
501          */
502         namelen = strlen(ifp->if_xname);
503         /*
504          * Always save enough space for any possiable name so we can do
505          * a rename in place later.
506          */
507         masklen = offsetof(struct sockaddr_dl, sdl_data[0]) + IFNAMSIZ;
508         socksize = masklen + ifp->if_addrlen;
509         if (socksize < sizeof(*sdl))
510                 socksize = sizeof(*sdl);
511         socksize = roundup2(socksize, sizeof(long));
512         ifasize = sizeof(*ifa) + 2 * socksize;
513         ifa = malloc(ifasize, M_IFADDR, M_WAITOK | M_ZERO);
514         IFA_LOCK_INIT(ifa);
515         sdl = (struct sockaddr_dl *)(ifa + 1);
516         sdl->sdl_len = socksize;
517         sdl->sdl_family = AF_LINK;
518         bcopy(ifp->if_xname, sdl->sdl_data, namelen);
519         sdl->sdl_nlen = namelen;
520         sdl->sdl_index = ifp->if_index;
521         sdl->sdl_type = ifp->if_type;
522         ifaddr_byindex(ifp->if_index) = ifa;
523         ifa->ifa_ifp = ifp;
524         ifa->ifa_rtrequest = link_rtrequest;
525         ifa->ifa_addr = (struct sockaddr *)sdl;
526         sdl = (struct sockaddr_dl *)(socksize + (caddr_t)sdl);
527         ifa->ifa_netmask = (struct sockaddr *)sdl;
528         sdl->sdl_len = masklen;
529         while (namelen != 0)
530                 sdl->sdl_data[--namelen] = 0xff;
531         ifa->ifa_refcnt = 1;
532         TAILQ_INSERT_HEAD(&ifp->if_addrhead, ifa, ifa_link);
533         ifp->if_broadcastaddr = NULL; /* reliably crash if used uninitialized */
534         ifp->if_snd.altq_type = 0;
535         ifp->if_snd.altq_disc = NULL;
536         ifp->if_snd.altq_flags &= ALTQF_CANTCHANGE;
537         ifp->if_snd.altq_tbr  = NULL;
538         ifp->if_snd.altq_ifp  = ifp;
539
540         if (domain_init_status >= 2)
541                 if_attachdomain1(ifp);
542
543         EVENTHANDLER_INVOKE(ifnet_arrival_event, ifp);
544
545         /* Announce the interface. */
546         rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
547 }
548
549 static void
550 if_attachdomain(void *dummy)
551 {
552         struct ifnet *ifp;
553         int s;
554
555         s = splnet();
556         TAILQ_FOREACH(ifp, &ifnet, if_link)
557                 if_attachdomain1(ifp);
558         splx(s);
559 }
560 SYSINIT(domainifattach, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_SECOND,
561     if_attachdomain, NULL);
562
563 static void
564 if_attachdomain1(struct ifnet *ifp)
565 {
566         struct domain *dp;
567         int s;
568
569         s = splnet();
570
571         /*
572          * Since dp->dom_ifattach calls malloc() with M_WAITOK, we
573          * cannot lock ifp->if_afdata initialization, entirely.
574          */
575         if (IF_AFDATA_TRYLOCK(ifp) == 0) {
576                 splx(s);
577                 return;
578         }
579         if (ifp->if_afdata_initialized >= domain_init_status) {
580                 IF_AFDATA_UNLOCK(ifp);
581                 splx(s);
582                 printf("if_attachdomain called more than once on %s\n",
583                     ifp->if_xname);
584                 return;
585         }
586         ifp->if_afdata_initialized = domain_init_status;
587         IF_AFDATA_UNLOCK(ifp);
588
589         /* address family dependent data region */
590         bzero(ifp->if_afdata, sizeof(ifp->if_afdata));
591         for (dp = domains; dp; dp = dp->dom_next) {
592                 if (dp->dom_ifattach)
593                         ifp->if_afdata[dp->dom_family] =
594                             (*dp->dom_ifattach)(ifp);
595         }
596
597         splx(s);
598 }
599
600 /*
601  * Remove any network addresses from an interface.
602  */
603
604 void
605 if_purgeaddrs(struct ifnet *ifp)
606 {
607         struct ifaddr *ifa, *next;
608
609         TAILQ_FOREACH_SAFE(ifa, &ifp->if_addrhead, ifa_link, next) {
610
611                 if (ifa->ifa_addr->sa_family == AF_LINK)
612                         continue;
613 #ifdef INET
614                 /* XXX: Ugly!! ad hoc just for INET */
615                 if (ifa->ifa_addr && ifa->ifa_addr->sa_family == AF_INET) {
616                         struct ifaliasreq ifr;
617
618                         bzero(&ifr, sizeof(ifr));
619                         ifr.ifra_addr = *ifa->ifa_addr;
620                         if (ifa->ifa_dstaddr)
621                                 ifr.ifra_broadaddr = *ifa->ifa_dstaddr;
622                         if (in_control(NULL, SIOCDIFADDR, (caddr_t)&ifr, ifp,
623                             NULL) == 0)
624                                 continue;
625                 }
626 #endif /* INET */
627 #ifdef INET6
628                 if (ifa->ifa_addr && ifa->ifa_addr->sa_family == AF_INET6) {
629                         in6_purgeaddr(ifa);
630                         /* ifp_addrhead is already updated */
631                         continue;
632                 }
633 #endif /* INET6 */
634                 TAILQ_REMOVE(&ifp->if_addrhead, ifa, ifa_link);
635                 IFAFREE(ifa);
636         }
637 }
638
639 /*
640  * Detach an interface, removing it from the
641  * list of "active" interfaces and freeing the struct ifnet.
642  */
643 void
644 if_detach(struct ifnet *ifp)
645 {
646         struct ifaddr *ifa;
647         struct radix_node_head  *rnh;
648         int s;
649         int i;
650         struct domain *dp;
651         struct ifnet *iter;
652         int found;
653
654         /*
655          * Remove/wait for pending events.
656          */
657         taskqueue_drain(taskqueue_swi, &ifp->if_linktask);
658
659 #ifdef DEV_CARP
660         /* Maybe hook to the generalized departure handler above?!? */
661         if (ifp->if_carp)
662                 carp_ifdetach(ifp);
663 #endif
664
665         /*
666          * Remove routes and flush queues.
667          */
668         s = splnet();
669         if_down(ifp);
670 #ifdef ALTQ
671         if (ALTQ_IS_ENABLED(&ifp->if_snd))
672                 altq_disable(&ifp->if_snd);
673         if (ALTQ_IS_ATTACHED(&ifp->if_snd))
674                 altq_detach(&ifp->if_snd);
675 #endif
676
677         if_purgeaddrs(ifp);
678
679 #ifdef INET6
680         /*
681          * Remove all IPv6 kernel structs related to ifp.  This should be done
682          * before removing routing entries below, since IPv6 interface direct
683          * routes are expected to be removed by the IPv6-specific kernel API.
684          * Otherwise, the kernel will detect some inconsistency and bark it.
685          */
686         in6_ifdetach(ifp);
687 #endif
688         /*
689          * Remove address from ifindex_table[] and maybe decrement if_index.
690          * Clean up all addresses.
691          */
692         ifaddr_byindex(ifp->if_index) = NULL;
693         destroy_dev(ifdev_byindex(ifp->if_index));
694         ifdev_byindex(ifp->if_index) = NULL;
695
696         /* We can now free link ifaddr. */
697         if (!TAILQ_EMPTY(&ifp->if_addrhead)) {
698                 ifa = TAILQ_FIRST(&ifp->if_addrhead);
699                 TAILQ_REMOVE(&ifp->if_addrhead, ifa, ifa_link);
700                 IFAFREE(ifa);
701         }
702
703         /*
704          * Delete all remaining routes using this interface
705          * Unfortuneatly the only way to do this is to slog through
706          * the entire routing table looking for routes which point
707          * to this interface...oh well...
708          */
709         for (i = 1; i <= AF_MAX; i++) {
710                 if ((rnh = rt_tables[i]) == NULL)
711                         continue;
712                 RADIX_NODE_HEAD_LOCK(rnh);
713                 (void) rnh->rnh_walktree(rnh, if_rtdel, ifp);
714                 RADIX_NODE_HEAD_UNLOCK(rnh);
715         }
716
717         /* Announce that the interface is gone. */
718         rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
719         EVENTHANDLER_INVOKE(ifnet_departure_event, ifp);
720
721         IF_AFDATA_LOCK(ifp);
722         for (dp = domains; dp; dp = dp->dom_next) {
723                 if (dp->dom_ifdetach && ifp->if_afdata[dp->dom_family])
724                         (*dp->dom_ifdetach)(ifp,
725                             ifp->if_afdata[dp->dom_family]);
726         }
727         IF_AFDATA_UNLOCK(ifp);
728
729 #ifdef MAC
730         mac_destroy_ifnet(ifp);
731 #endif /* MAC */
732         KNOTE_UNLOCKED(&ifp->if_klist, NOTE_EXIT);
733         knlist_clear(&ifp->if_klist, 0);
734         knlist_destroy(&ifp->if_klist);
735         IFNET_WLOCK();
736         found = 0;
737         TAILQ_FOREACH(iter, &ifnet, if_link)
738                 if (iter == ifp) {
739                         found = 1;
740                         break;
741                 }
742         if (found)
743                 TAILQ_REMOVE(&ifnet, ifp, if_link);
744         IFNET_WUNLOCK();
745         mtx_destroy(&ifp->if_snd.ifq_mtx);
746         IF_AFDATA_DESTROY(ifp);
747         splx(s);
748 }
749
750 /*
751  * Delete Routes for a Network Interface
752  *
753  * Called for each routing entry via the rnh->rnh_walktree() call above
754  * to delete all route entries referencing a detaching network interface.
755  *
756  * Arguments:
757  *      rn      pointer to node in the routing table
758  *      arg     argument passed to rnh->rnh_walktree() - detaching interface
759  *
760  * Returns:
761  *      0       successful
762  *      errno   failed - reason indicated
763  *
764  */
765 static int
766 if_rtdel(struct radix_node *rn, void *arg)
767 {
768         struct rtentry  *rt = (struct rtentry *)rn;
769         struct ifnet    *ifp = arg;
770         int             err;
771
772         if (rt->rt_ifp == ifp) {
773
774                 /*
775                  * Protect (sorta) against walktree recursion problems
776                  * with cloned routes
777                  */
778                 if ((rt->rt_flags & RTF_UP) == 0)
779                         return (0);
780
781                 err = rtrequest(RTM_DELETE, rt_key(rt), rt->rt_gateway,
782                                 rt_mask(rt), rt->rt_flags,
783                                 (struct rtentry **) NULL);
784                 if (err) {
785                         log(LOG_WARNING, "if_rtdel: error %d\n", err);
786                 }
787         }
788
789         return (0);
790 }
791
792 #define sa_equal(a1, a2)        (bcmp((a1), (a2), ((a1))->sa_len) == 0)
793
794 /*
795  * Locate an interface based on a complete address.
796  */
797 /*ARGSUSED*/
798 struct ifaddr *
799 ifa_ifwithaddr(struct sockaddr *addr)
800 {
801         struct ifnet *ifp;
802         struct ifaddr *ifa;
803
804         IFNET_RLOCK();
805         TAILQ_FOREACH(ifp, &ifnet, if_link)
806                 TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
807                         if (ifa->ifa_addr->sa_family != addr->sa_family)
808                                 continue;
809                         if (sa_equal(addr, ifa->ifa_addr))
810                                 goto done;
811                         /* IP6 doesn't have broadcast */
812                         if ((ifp->if_flags & IFF_BROADCAST) &&
813                             ifa->ifa_broadaddr &&
814                             ifa->ifa_broadaddr->sa_len != 0 &&
815                             sa_equal(ifa->ifa_broadaddr, addr))
816                                 goto done;
817                 }
818         ifa = NULL;
819 done:
820         IFNET_RUNLOCK();
821         return (ifa);
822 }
823
824 /*
825  * Locate the point to point interface with a given destination address.
826  */
827 /*ARGSUSED*/
828 struct ifaddr *
829 ifa_ifwithdstaddr(struct sockaddr *addr)
830 {
831         struct ifnet *ifp;
832         struct ifaddr *ifa;
833
834         IFNET_RLOCK();
835         TAILQ_FOREACH(ifp, &ifnet, if_link) {
836                 if ((ifp->if_flags & IFF_POINTOPOINT) == 0)
837                         continue;
838                 TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
839                         if (ifa->ifa_addr->sa_family != addr->sa_family)
840                                 continue;
841                         if (ifa->ifa_dstaddr &&
842                             sa_equal(addr, ifa->ifa_dstaddr))
843                                 goto done;
844                 }
845         }
846         ifa = NULL;
847 done:
848         IFNET_RUNLOCK();
849         return (ifa);
850 }
851
852 /*
853  * Find an interface on a specific network.  If many, choice
854  * is most specific found.
855  */
856 struct ifaddr *
857 ifa_ifwithnet(struct sockaddr *addr)
858 {
859         struct ifnet *ifp;
860         struct ifaddr *ifa;
861         struct ifaddr *ifa_maybe = (struct ifaddr *) 0;
862         u_int af = addr->sa_family;
863         char *addr_data = addr->sa_data, *cplim;
864
865         /*
866          * AF_LINK addresses can be looked up directly by their index number,
867          * so do that if we can.
868          */
869         if (af == AF_LINK) {
870             struct sockaddr_dl *sdl = (struct sockaddr_dl *)addr;
871             if (sdl->sdl_index && sdl->sdl_index <= if_index)
872                 return (ifaddr_byindex(sdl->sdl_index));
873         }
874
875         /*
876          * Scan though each interface, looking for ones that have
877          * addresses in this address family.
878          */
879         IFNET_RLOCK();
880         TAILQ_FOREACH(ifp, &ifnet, if_link) {
881                 TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
882                         char *cp, *cp2, *cp3;
883
884                         if (ifa->ifa_addr->sa_family != af)
885 next:                           continue;
886                         if (af == AF_INET && ifp->if_flags & IFF_POINTOPOINT) {
887                                 /*
888                                  * This is a bit broken as it doesn't
889                                  * take into account that the remote end may
890                                  * be a single node in the network we are
891                                  * looking for.
892                                  * The trouble is that we don't know the
893                                  * netmask for the remote end.
894                                  */
895                                 if (ifa->ifa_dstaddr != 0 &&
896                                     sa_equal(addr, ifa->ifa_dstaddr))
897                                         goto done;
898                         } else {
899                                 /*
900                                  * if we have a special address handler,
901                                  * then use it instead of the generic one.
902                                  */
903                                 if (ifa->ifa_claim_addr) {
904                                         if ((*ifa->ifa_claim_addr)(ifa, addr))
905                                                 goto done;
906                                         continue;
907                                 }
908
909                                 /*
910                                  * Scan all the bits in the ifa's address.
911                                  * If a bit dissagrees with what we are
912                                  * looking for, mask it with the netmask
913                                  * to see if it really matters.
914                                  * (A byte at a time)
915                                  */
916                                 if (ifa->ifa_netmask == 0)
917                                         continue;
918                                 cp = addr_data;
919                                 cp2 = ifa->ifa_addr->sa_data;
920                                 cp3 = ifa->ifa_netmask->sa_data;
921                                 cplim = ifa->ifa_netmask->sa_len
922                                         + (char *)ifa->ifa_netmask;
923                                 while (cp3 < cplim)
924                                         if ((*cp++ ^ *cp2++) & *cp3++)
925                                                 goto next; /* next address! */
926                                 /*
927                                  * If the netmask of what we just found
928                                  * is more specific than what we had before
929                                  * (if we had one) then remember the new one
930                                  * before continuing to search
931                                  * for an even better one.
932                                  */
933                                 if (ifa_maybe == 0 ||
934                                     rn_refines((caddr_t)ifa->ifa_netmask,
935                                     (caddr_t)ifa_maybe->ifa_netmask))
936                                         ifa_maybe = ifa;
937                         }
938                 }
939         }
940         ifa = ifa_maybe;
941 done:
942         IFNET_RUNLOCK();
943         return (ifa);
944 }
945
946 /*
947  * Find an interface address specific to an interface best matching
948  * a given address.
949  */
950 struct ifaddr *
951 ifaof_ifpforaddr(struct sockaddr *addr, struct ifnet *ifp)
952 {
953         struct ifaddr *ifa;
954         char *cp, *cp2, *cp3;
955         char *cplim;
956         struct ifaddr *ifa_maybe = 0;
957         u_int af = addr->sa_family;
958
959         if (af >= AF_MAX)
960                 return (0);
961         TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
962                 if (ifa->ifa_addr->sa_family != af)
963                         continue;
964                 if (ifa_maybe == 0)
965                         ifa_maybe = ifa;
966                 if (ifa->ifa_netmask == 0) {
967                         if (sa_equal(addr, ifa->ifa_addr) ||
968                             (ifa->ifa_dstaddr &&
969                             sa_equal(addr, ifa->ifa_dstaddr)))
970                                 goto done;
971                         continue;
972                 }
973                 if (ifp->if_flags & IFF_POINTOPOINT) {
974                         if (sa_equal(addr, ifa->ifa_dstaddr))
975                                 goto done;
976                 } else {
977                         cp = addr->sa_data;
978                         cp2 = ifa->ifa_addr->sa_data;
979                         cp3 = ifa->ifa_netmask->sa_data;
980                         cplim = ifa->ifa_netmask->sa_len + (char *)ifa->ifa_netmask;
981                         for (; cp3 < cplim; cp3++)
982                                 if ((*cp++ ^ *cp2++) & *cp3)
983                                         break;
984                         if (cp3 == cplim)
985                                 goto done;
986                 }
987         }
988         ifa = ifa_maybe;
989 done:
990         return (ifa);
991 }
992
993 #include <net/route.h>
994
995 /*
996  * Default action when installing a route with a Link Level gateway.
997  * Lookup an appropriate real ifa to point to.
998  * This should be moved to /sys/net/link.c eventually.
999  */
1000 static void
1001 link_rtrequest(int cmd, struct rtentry *rt, struct rt_addrinfo *info)
1002 {
1003         struct ifaddr *ifa, *oifa;
1004         struct sockaddr *dst;
1005         struct ifnet *ifp;
1006
1007         RT_LOCK_ASSERT(rt);
1008
1009         if (cmd != RTM_ADD || ((ifa = rt->rt_ifa) == 0) ||
1010             ((ifp = ifa->ifa_ifp) == 0) || ((dst = rt_key(rt)) == 0))
1011                 return;
1012         ifa = ifaof_ifpforaddr(dst, ifp);
1013         if (ifa) {
1014                 IFAREF(ifa);            /* XXX */
1015                 oifa = rt->rt_ifa;
1016                 rt->rt_ifa = ifa;
1017                 IFAFREE(oifa);
1018                 if (ifa->ifa_rtrequest && ifa->ifa_rtrequest != link_rtrequest)
1019                         ifa->ifa_rtrequest(cmd, rt, info);
1020         }
1021 }
1022
1023 /*
1024  * Mark an interface down and notify protocols of
1025  * the transition.
1026  * NOTE: must be called at splnet or eqivalent.
1027  */
1028 static void
1029 if_unroute(struct ifnet *ifp, int flag, int fam)
1030 {
1031         struct ifaddr *ifa;
1032
1033         ifp->if_flags &= ~flag;
1034         getmicrotime(&ifp->if_lastchange);
1035         TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
1036                 if (fam == PF_UNSPEC || (fam == ifa->ifa_addr->sa_family))
1037                         pfctlinput(PRC_IFDOWN, ifa->ifa_addr);
1038         if_qflush(&ifp->if_snd);
1039 #ifdef DEV_CARP
1040         if (ifp->if_carp)
1041                 carp_carpdev_state(ifp->if_carp);
1042 #endif
1043         rt_ifmsg(ifp);
1044 }
1045
1046 /*
1047  * Mark an interface up and notify protocols of
1048  * the transition.
1049  * NOTE: must be called at splnet or eqivalent.
1050  */
1051 static void
1052 if_route(struct ifnet *ifp, int flag, int fam)
1053 {
1054         struct ifaddr *ifa;
1055
1056         ifp->if_flags |= flag;
1057         getmicrotime(&ifp->if_lastchange);
1058         TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
1059                 if (fam == PF_UNSPEC || (fam == ifa->ifa_addr->sa_family))
1060                         pfctlinput(PRC_IFUP, ifa->ifa_addr);
1061 #ifdef DEV_CARP
1062         if (ifp->if_carp)
1063                 carp_carpdev_state(ifp->if_carp);
1064 #endif
1065         rt_ifmsg(ifp);
1066 #ifdef INET6
1067         in6_if_up(ifp);
1068 #endif
1069 }
1070
1071 void    (*vlan_link_state_p)(struct ifnet *, int);      /* XXX: private from if_vlan */
1072
1073 /*
1074  * Handle a change in the interface link state. To avoid LORs
1075  * between driver lock and upper layer locks, as well as possible
1076  * recursions, we post event to taskqueue, and all job
1077  * is done in static do_link_state_change().
1078  */
1079 void
1080 if_link_state_change(struct ifnet *ifp, int link_state)
1081 {
1082         /* Return if state hasn't changed. */
1083         if (ifp->if_link_state == link_state)
1084                 return;
1085
1086         ifp->if_link_state = link_state;
1087
1088         taskqueue_enqueue(taskqueue_swi, &ifp->if_linktask);
1089 }
1090
1091 static void
1092 do_link_state_change(void *arg, int pending)
1093 {
1094         struct ifnet *ifp = (struct ifnet *)arg;
1095         int link_state = ifp->if_link_state;
1096         int link;
1097
1098         /* Notify that the link state has changed. */
1099         rt_ifmsg(ifp);
1100         if (link_state == LINK_STATE_UP)
1101                 link = NOTE_LINKUP;
1102         else if (link_state == LINK_STATE_DOWN)
1103                 link = NOTE_LINKDOWN;
1104         else
1105                 link = NOTE_LINKINV;
1106         KNOTE_UNLOCKED(&ifp->if_klist, link);
1107         if (ifp->if_nvlans != 0)
1108                 (*vlan_link_state_p)(ifp, link);
1109
1110         if ((ifp->if_type == IFT_ETHER || ifp->if_type == IFT_L2VLAN) &&
1111             IFP2AC(ifp)->ac_netgraph != NULL)
1112                 (*ng_ether_link_state_p)(ifp, link_state);
1113 #ifdef DEV_CARP
1114         if (ifp->if_carp)
1115                 carp_carpdev_state(ifp->if_carp);
1116 #endif
1117         if (ifp->if_bridge) {
1118                 KASSERT(bstp_linkstate_p != NULL,("if_bridge bstp not loaded!"));
1119                 (*bstp_linkstate_p)(ifp, link_state);
1120         }
1121
1122         devctl_notify("IFNET", ifp->if_xname,
1123             (link_state == LINK_STATE_UP) ? "LINK_UP" : "LINK_DOWN", NULL);
1124         if (pending > 1)
1125                 if_printf(ifp, "%d link states coalesced\n", pending);
1126         if (log_link_state_change)
1127                 log(LOG_NOTICE, "%s: link state changed to %s\n", ifp->if_xname,
1128                     (link_state == LINK_STATE_UP) ? "UP" : "DOWN" );
1129 }
1130
1131 /*
1132  * Mark an interface down and notify protocols of
1133  * the transition.
1134  * NOTE: must be called at splnet or eqivalent.
1135  */
1136 void
1137 if_down(struct ifnet *ifp)
1138 {
1139
1140         if_unroute(ifp, IFF_UP, AF_UNSPEC);
1141 }
1142
1143 /*
1144  * Mark an interface up and notify protocols of
1145  * the transition.
1146  * NOTE: must be called at splnet or eqivalent.
1147  */
1148 void
1149 if_up(struct ifnet *ifp)
1150 {
1151
1152         if_route(ifp, IFF_UP, AF_UNSPEC);
1153 }
1154
1155 /*
1156  * Flush an interface queue.
1157  */
1158 static void
1159 if_qflush(struct ifaltq *ifq)
1160 {
1161         struct mbuf *m, *n;
1162
1163         IFQ_LOCK(ifq);
1164 #ifdef ALTQ
1165         if (ALTQ_IS_ENABLED(ifq))
1166                 ALTQ_PURGE(ifq);
1167 #endif
1168         n = ifq->ifq_head;
1169         while ((m = n) != 0) {
1170                 n = m->m_act;
1171                 m_freem(m);
1172         }
1173         ifq->ifq_head = 0;
1174         ifq->ifq_tail = 0;
1175         ifq->ifq_len = 0;
1176         IFQ_UNLOCK(ifq);
1177 }
1178
1179 /*
1180  * Handle interface watchdog timer routines.  Called
1181  * from softclock, we decrement timers (if set) and
1182  * call the appropriate interface routine on expiration.
1183  *
1184  * XXXRW: Note that because timeouts run with Giant, if_watchdog() is called
1185  * holding Giant.  If we switch to an MPSAFE callout, we likely need to grab
1186  * Giant before entering if_watchdog() on an IFF_NEEDSGIANT interface.
1187  */
1188 static void
1189 if_slowtimo(void *arg)
1190 {
1191         struct ifnet *ifp;
1192         int s = splimp();
1193
1194         IFNET_RLOCK();
1195         TAILQ_FOREACH(ifp, &ifnet, if_link) {
1196                 if (ifp->if_timer == 0 || --ifp->if_timer)
1197                         continue;
1198                 if (ifp->if_watchdog)
1199                         (*ifp->if_watchdog)(ifp);
1200         }
1201         IFNET_RUNLOCK();
1202         splx(s);
1203         timeout(if_slowtimo, (void *)0, hz / IFNET_SLOWHZ);
1204 }
1205
1206 /*
1207  * Map interface name to
1208  * interface structure pointer.
1209  */
1210 struct ifnet *
1211 ifunit(const char *name)
1212 {
1213         struct ifnet *ifp;
1214
1215         IFNET_RLOCK();
1216         TAILQ_FOREACH(ifp, &ifnet, if_link) {
1217                 if (strncmp(name, ifp->if_xname, IFNAMSIZ) == 0)
1218                         break;
1219         }
1220         IFNET_RUNLOCK();
1221         return (ifp);
1222 }
1223
1224 /*
1225  * Hardware specific interface ioctls.
1226  */
1227 static int
1228 ifhwioctl(u_long cmd, struct ifnet *ifp, caddr_t data, struct thread *td)
1229 {
1230         struct ifreq *ifr;
1231         struct ifstat *ifs;
1232         int error = 0;
1233         int new_flags;
1234         size_t namelen, onamelen;
1235         char new_name[IFNAMSIZ];
1236         struct ifaddr *ifa;
1237         struct sockaddr_dl *sdl;
1238
1239         ifr = (struct ifreq *)data;
1240         switch (cmd) {
1241         case SIOCGIFINDEX:
1242                 ifr->ifr_index = ifp->if_index;
1243                 break;
1244
1245         case SIOCGIFFLAGS:
1246                 ifr->ifr_flags = ifp->if_flags & 0xffff;
1247                 ifr->ifr_flagshigh = ifp->if_flags >> 16;
1248                 break;
1249
1250         case SIOCGIFCAP:
1251                 ifr->ifr_reqcap = ifp->if_capabilities;
1252                 ifr->ifr_curcap = ifp->if_capenable;
1253                 break;
1254
1255 #ifdef MAC
1256         case SIOCGIFMAC:
1257                 error = mac_ioctl_ifnet_get(td->td_ucred, ifr, ifp);
1258                 break;
1259 #endif
1260
1261         case SIOCGIFMETRIC:
1262                 ifr->ifr_metric = ifp->if_metric;
1263                 break;
1264
1265         case SIOCGIFMTU:
1266                 ifr->ifr_mtu = ifp->if_mtu;
1267                 break;
1268
1269         case SIOCGIFPHYS:
1270                 ifr->ifr_phys = ifp->if_physical;
1271                 break;
1272
1273         case SIOCSIFFLAGS:
1274                 error = suser(td);
1275                 if (error)
1276                         return (error);
1277                 new_flags = (ifr->ifr_flags & 0xffff) |
1278                     (ifr->ifr_flagshigh << 16);
1279                 if (ifp->if_flags & IFF_SMART) {
1280                         /* Smart drivers twiddle their own routes */
1281                 } else if (ifp->if_flags & IFF_UP &&
1282                     (new_flags & IFF_UP) == 0) {
1283                         int s = splimp();
1284                         if_down(ifp);
1285                         splx(s);
1286                 } else if (new_flags & IFF_UP &&
1287                     (ifp->if_flags & IFF_UP) == 0) {
1288                         int s = splimp();
1289                         if_up(ifp);
1290                         splx(s);
1291                 }
1292                 ifp->if_flags = (ifp->if_flags & IFF_CANTCHANGE) |
1293                         (new_flags &~ IFF_CANTCHANGE);
1294                 if (new_flags & IFF_PPROMISC) {
1295                         /* Permanently promiscuous mode requested */
1296                         ifp->if_flags |= IFF_PROMISC;
1297                 } else if (ifp->if_pcount == 0) {
1298                         ifp->if_flags &= ~IFF_PROMISC;
1299                 }
1300                 if (ifp->if_ioctl) {
1301                         IFF_LOCKGIANT(ifp);
1302                         (void) (*ifp->if_ioctl)(ifp, cmd, data);
1303                         IFF_UNLOCKGIANT(ifp);
1304                 }
1305                 getmicrotime(&ifp->if_lastchange);
1306                 break;
1307
1308         case SIOCSIFCAP:
1309                 error = suser(td);
1310                 if (error)
1311                         return (error);
1312                 if (ifp->if_ioctl == NULL)
1313                         return (EOPNOTSUPP);
1314                 if (ifr->ifr_reqcap & ~ifp->if_capabilities)
1315                         return (EINVAL);
1316                 IFF_LOCKGIANT(ifp);
1317                 error = (*ifp->if_ioctl)(ifp, cmd, data);
1318                 IFF_UNLOCKGIANT(ifp);
1319                 if (error == 0)
1320                         getmicrotime(&ifp->if_lastchange);
1321                 break;
1322
1323 #ifdef MAC
1324         case SIOCSIFMAC:
1325                 error = mac_ioctl_ifnet_set(td->td_ucred, ifr, ifp);
1326                 break;
1327 #endif
1328
1329         case SIOCSIFNAME:
1330                 error = suser(td);
1331                 if (error != 0)
1332                         return (error);
1333                 error = copyinstr(ifr->ifr_data, new_name, IFNAMSIZ, NULL);
1334                 if (error != 0)
1335                         return (error);
1336                 if (new_name[0] == '\0')
1337                         return (EINVAL);
1338                 if (ifunit(new_name) != NULL)
1339                         return (EEXIST);
1340                 
1341                 /* Announce the departure of the interface. */
1342                 rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
1343                 EVENTHANDLER_INVOKE(ifnet_departure_event, ifp);
1344
1345                 log(LOG_INFO, "%s: changing name to '%s'\n",
1346                     ifp->if_xname, new_name);
1347
1348                 strlcpy(ifp->if_xname, new_name, sizeof(ifp->if_xname));
1349                 ifa = ifaddr_byindex(ifp->if_index);
1350                 IFA_LOCK(ifa);
1351                 sdl = (struct sockaddr_dl *)ifa->ifa_addr;
1352                 namelen = strlen(new_name);
1353                 onamelen = sdl->sdl_nlen;
1354                 /*
1355                  * Move the address if needed.  This is safe because we
1356                  * allocate space for a name of length IFNAMSIZ when we
1357                  * create this in if_attach().
1358                  */
1359                 if (namelen != onamelen) {
1360                         bcopy(sdl->sdl_data + onamelen,
1361                             sdl->sdl_data + namelen, sdl->sdl_alen);
1362                 }
1363                 bcopy(new_name, sdl->sdl_data, namelen);
1364                 sdl->sdl_nlen = namelen;
1365                 sdl = (struct sockaddr_dl *)ifa->ifa_netmask;
1366                 bzero(sdl->sdl_data, onamelen);
1367                 while (namelen != 0)
1368                         sdl->sdl_data[--namelen] = 0xff;
1369                 IFA_UNLOCK(ifa);
1370
1371                 EVENTHANDLER_INVOKE(ifnet_arrival_event, ifp);
1372                 /* Announce the return of the interface. */
1373                 rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
1374                 break;
1375
1376         case SIOCSIFMETRIC:
1377                 error = suser(td);
1378                 if (error)
1379                         return (error);
1380                 ifp->if_metric = ifr->ifr_metric;
1381                 getmicrotime(&ifp->if_lastchange);
1382                 break;
1383
1384         case SIOCSIFPHYS:
1385                 error = suser(td);
1386                 if (error)
1387                         return (error);
1388                 if (ifp->if_ioctl == NULL)
1389                         return (EOPNOTSUPP);
1390                 IFF_LOCKGIANT(ifp);
1391                 error = (*ifp->if_ioctl)(ifp, cmd, data);
1392                 IFF_UNLOCKGIANT(ifp);
1393                 if (error == 0)
1394                         getmicrotime(&ifp->if_lastchange);
1395                 break;
1396
1397         case SIOCSIFMTU:
1398         {
1399                 u_long oldmtu = ifp->if_mtu;
1400
1401                 error = suser(td);
1402                 if (error)
1403                         return (error);
1404                 if (ifr->ifr_mtu < IF_MINMTU || ifr->ifr_mtu > IF_MAXMTU)
1405                         return (EINVAL);
1406                 if (ifp->if_ioctl == NULL)
1407                         return (EOPNOTSUPP);
1408                 IFF_LOCKGIANT(ifp);
1409                 error = (*ifp->if_ioctl)(ifp, cmd, data);
1410                 IFF_UNLOCKGIANT(ifp);
1411                 if (error == 0) {
1412                         getmicrotime(&ifp->if_lastchange);
1413                         rt_ifmsg(ifp);
1414                 }
1415                 /*
1416                  * If the link MTU changed, do network layer specific procedure.
1417                  */
1418                 if (ifp->if_mtu != oldmtu) {
1419 #ifdef INET6
1420                         nd6_setmtu(ifp);
1421 #endif
1422                 }
1423                 break;
1424         }
1425
1426         case SIOCADDMULTI:
1427         case SIOCDELMULTI:
1428                 error = suser(td);
1429                 if (error)
1430                         return (error);
1431
1432                 /* Don't allow group membership on non-multicast interfaces. */
1433                 if ((ifp->if_flags & IFF_MULTICAST) == 0)
1434                         return (EOPNOTSUPP);
1435
1436                 /* Don't let users screw up protocols' entries. */
1437                 if (ifr->ifr_addr.sa_family != AF_LINK)
1438                         return (EINVAL);
1439
1440                 if (cmd == SIOCADDMULTI) {
1441                         struct ifmultiaddr *ifma;
1442                         error = if_addmulti(ifp, &ifr->ifr_addr, &ifma);
1443                 } else {
1444                         error = if_delmulti(ifp, &ifr->ifr_addr);
1445                 }
1446                 if (error == 0)
1447                         getmicrotime(&ifp->if_lastchange);
1448                 break;
1449
1450         case SIOCSIFPHYADDR:
1451         case SIOCDIFPHYADDR:
1452 #ifdef INET6
1453         case SIOCSIFPHYADDR_IN6:
1454 #endif
1455         case SIOCSLIFPHYADDR:
1456         case SIOCSIFMEDIA:
1457         case SIOCSIFGENERIC:
1458                 error = suser(td);
1459                 if (error)
1460                         return (error);
1461                 if (ifp->if_ioctl == NULL)
1462                         return (EOPNOTSUPP);
1463                 IFF_LOCKGIANT(ifp);
1464                 error = (*ifp->if_ioctl)(ifp, cmd, data);
1465                 IFF_UNLOCKGIANT(ifp);
1466                 if (error == 0)
1467                         getmicrotime(&ifp->if_lastchange);
1468                 break;
1469
1470         case SIOCGIFSTATUS:
1471                 ifs = (struct ifstat *)data;
1472                 ifs->ascii[0] = '\0';
1473
1474         case SIOCGIFPSRCADDR:
1475         case SIOCGIFPDSTADDR:
1476         case SIOCGLIFPHYADDR:
1477         case SIOCGIFMEDIA:
1478         case SIOCGIFGENERIC:
1479                 if (ifp->if_ioctl == NULL)
1480                         return (EOPNOTSUPP);
1481                 IFF_LOCKGIANT(ifp);
1482                 error = (*ifp->if_ioctl)(ifp, cmd, data);
1483                 IFF_UNLOCKGIANT(ifp);
1484                 break;
1485
1486         case SIOCSIFLLADDR:
1487                 error = suser(td);
1488                 if (error)
1489                         return (error);
1490                 error = if_setlladdr(ifp,
1491                     ifr->ifr_addr.sa_data, ifr->ifr_addr.sa_len);
1492                 break;
1493
1494         default:
1495                 error = ENOIOCTL;
1496                 break;
1497         }
1498         return (error);
1499 }
1500
1501 /*
1502  * Interface ioctls.
1503  */
1504 int
1505 ifioctl(struct socket *so, u_long cmd, caddr_t data, struct thread *td)
1506 {
1507         struct ifnet *ifp;
1508         struct ifreq *ifr;
1509         int error;
1510         int oif_flags;
1511
1512         switch (cmd) {
1513         case SIOCGIFCONF:
1514         case OSIOCGIFCONF:
1515                 return (ifconf(cmd, data));
1516         }
1517         ifr = (struct ifreq *)data;
1518
1519         switch (cmd) {
1520         case SIOCIFCREATE:
1521         case SIOCIFDESTROY:
1522                 if ((error = suser(td)) != 0)
1523                         return (error);
1524                 return ((cmd == SIOCIFCREATE) ?
1525                         if_clone_create(ifr->ifr_name, sizeof(ifr->ifr_name)) :
1526                         if_clone_destroy(ifr->ifr_name));
1527
1528         case SIOCIFGCLONERS:
1529                 return (if_clone_list((struct if_clonereq *)data));
1530         }
1531
1532         ifp = ifunit(ifr->ifr_name);
1533         if (ifp == 0)
1534                 return (ENXIO);
1535
1536         error = ifhwioctl(cmd, ifp, data, td);
1537         if (error != ENOIOCTL)
1538                 return (error);
1539
1540         oif_flags = ifp->if_flags;
1541         if (so->so_proto == 0)
1542                 return (EOPNOTSUPP);
1543 #ifndef COMPAT_43
1544         error = ((*so->so_proto->pr_usrreqs->pru_control)(so, cmd,
1545                                                                  data,
1546                                                                  ifp, td));
1547 #else
1548         {
1549                 int ocmd = cmd;
1550
1551                 switch (cmd) {
1552
1553                 case SIOCSIFDSTADDR:
1554                 case SIOCSIFADDR:
1555                 case SIOCSIFBRDADDR:
1556                 case SIOCSIFNETMASK:
1557 #if BYTE_ORDER != BIG_ENDIAN
1558                         if (ifr->ifr_addr.sa_family == 0 &&
1559                             ifr->ifr_addr.sa_len < 16) {
1560                                 ifr->ifr_addr.sa_family = ifr->ifr_addr.sa_len;
1561                                 ifr->ifr_addr.sa_len = 16;
1562                         }
1563 #else
1564                         if (ifr->ifr_addr.sa_len == 0)
1565                                 ifr->ifr_addr.sa_len = 16;
1566 #endif
1567                         break;
1568
1569                 case OSIOCGIFADDR:
1570                         cmd = SIOCGIFADDR;
1571                         break;
1572
1573                 case OSIOCGIFDSTADDR:
1574                         cmd = SIOCGIFDSTADDR;
1575                         break;
1576
1577                 case OSIOCGIFBRDADDR:
1578                         cmd = SIOCGIFBRDADDR;
1579                         break;
1580
1581                 case OSIOCGIFNETMASK:
1582                         cmd = SIOCGIFNETMASK;
1583                 }
1584                 error =  ((*so->so_proto->pr_usrreqs->pru_control)(so,
1585                                                                    cmd,
1586                                                                    data,
1587                                                                    ifp, td));
1588                 switch (ocmd) {
1589
1590                 case OSIOCGIFADDR:
1591                 case OSIOCGIFDSTADDR:
1592                 case OSIOCGIFBRDADDR:
1593                 case OSIOCGIFNETMASK:
1594                         *(u_short *)&ifr->ifr_addr = ifr->ifr_addr.sa_family;
1595
1596                 }
1597         }
1598 #endif /* COMPAT_43 */
1599
1600         if ((oif_flags ^ ifp->if_flags) & IFF_UP) {
1601 #ifdef INET6
1602                 DELAY(100);/* XXX: temporary workaround for fxp issue*/
1603                 if (ifp->if_flags & IFF_UP) {
1604                         int s = splimp();
1605                         in6_if_up(ifp);
1606                         splx(s);
1607                 }
1608 #endif
1609         }
1610         return (error);
1611 }
1612
1613 /*
1614  * The code common to hadling reference counted flags,
1615  * e.g., in ifpromisc() and if_allmulti().
1616  * The "pflag" argument can specify a permanent mode flag,
1617  * such as IFF_PPROMISC for promiscuous mode; should be 0 if none.
1618  */
1619 static int
1620 if_setflag(struct ifnet *ifp, int flag, int pflag, int *refcount, int onswitch)
1621 {
1622         struct ifreq ifr;
1623         int error;
1624         int oldflags, oldcount;
1625
1626         /* Sanity checks to catch programming errors */
1627         if (onswitch) {
1628                 if (*refcount < 0) {
1629                         if_printf(ifp,
1630                             "refusing to increment negative refcount %d "
1631                             "for interface flag %d\n", *refcount, flag);
1632                         return (EINVAL);
1633                 }
1634         } else {
1635                 if (*refcount <= 0) {
1636                         if_printf(ifp,
1637                             "refusing to decrement non-positive refcount %d"
1638                             "for interface flag %d\n", *refcount, flag);
1639                         return (EINVAL);
1640                 }
1641         }
1642
1643         /* In case this mode is permanent, just touch refcount */
1644         if (ifp->if_flags & pflag) {
1645                 *refcount += onswitch ? 1 : -1;
1646                 return (0);
1647         }
1648
1649         /* Save ifnet parameters for if_ioctl() may fail */
1650         oldcount = *refcount;
1651         oldflags = ifp->if_flags;
1652         
1653         /*
1654          * See if we aren't the only and touching refcount is enough.
1655          * Actually toggle interface flag if we are the first or last.
1656          */
1657         if (onswitch) {
1658                 if ((*refcount)++)
1659                         return (0);
1660                 ifp->if_flags |= flag;
1661         } else {
1662                 if (--(*refcount))
1663                         return (0);
1664                 ifp->if_flags &= ~flag;
1665         }
1666
1667         /* Call down the driver since we've changed interface flags */
1668         if (ifp->if_ioctl == NULL) {
1669                 error = EOPNOTSUPP;
1670                 goto recover;
1671         }
1672         ifr.ifr_flags = ifp->if_flags & 0xffff;
1673         ifr.ifr_flagshigh = ifp->if_flags >> 16;
1674         IFF_LOCKGIANT(ifp);
1675         error = (*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
1676         IFF_UNLOCKGIANT(ifp);
1677         if (error)
1678                 goto recover;
1679         /* Notify userland that interface flags have changed */
1680         rt_ifmsg(ifp);
1681         return (0);
1682
1683 recover:
1684         /* Recover after driver error */
1685         *refcount = oldcount;
1686         ifp->if_flags = oldflags;
1687         return (error);
1688 }
1689
1690 /*
1691  * Set/clear promiscuous mode on interface ifp based on the truth value
1692  * of pswitch.  The calls are reference counted so that only the first
1693  * "on" request actually has an effect, as does the final "off" request.
1694  * Results are undefined if the "off" and "on" requests are not matched.
1695  */
1696 int
1697 ifpromisc(struct ifnet *ifp, int pswitch)
1698 {
1699         int error;
1700         int oldflags = ifp->if_flags;
1701
1702         error = if_setflag(ifp, IFF_PROMISC, IFF_PPROMISC,
1703                            &ifp->if_pcount, pswitch);
1704         /* If promiscuous mode status has changed, log a message */
1705         if (error == 0 && ((ifp->if_flags ^ oldflags) & IFF_PROMISC))
1706                 log(LOG_INFO, "%s: promiscuous mode %s\n",
1707                     ifp->if_xname,
1708                     (ifp->if_flags & IFF_PROMISC) ? "enabled" : "disabled");
1709         return (error);
1710 }
1711
1712 /*
1713  * Return interface configuration
1714  * of system.  List may be used
1715  * in later ioctl's (above) to get
1716  * other information.
1717  */
1718 /*ARGSUSED*/
1719 static int
1720 ifconf(u_long cmd, caddr_t data)
1721 {
1722         struct ifconf *ifc = (struct ifconf *)data;
1723         struct ifnet *ifp;
1724         struct ifaddr *ifa;
1725         struct ifreq ifr;
1726         struct sbuf *sb;
1727         int error, full = 0, valid_len, max_len;
1728
1729         /* Limit initial buffer size to MAXPHYS to avoid DoS from userspace. */
1730         max_len = MAXPHYS - 1;
1731
1732         /* Prevent hostile input from being able to crash the system */
1733         if (ifc->ifc_len <= 0)
1734                 return (EINVAL);
1735
1736 again:
1737         if (ifc->ifc_len <= max_len) {
1738                 max_len = ifc->ifc_len;
1739                 full = 1;
1740         }
1741         sb = sbuf_new(NULL, NULL, max_len + 1, SBUF_FIXEDLEN);
1742         max_len = 0;
1743         valid_len = 0;
1744
1745         IFNET_RLOCK();          /* could sleep XXX */
1746         TAILQ_FOREACH(ifp, &ifnet, if_link) {
1747                 int addrs;
1748
1749                 /*
1750                  * Zero the ifr_name buffer to make sure we don't
1751                  * disclose the contents of the stack.
1752                  */
1753                 memset(ifr.ifr_name, 0, sizeof(ifr.ifr_name));
1754
1755                 if (strlcpy(ifr.ifr_name, ifp->if_xname, sizeof(ifr.ifr_name))
1756                     >= sizeof(ifr.ifr_name))
1757                         return (ENAMETOOLONG);
1758
1759                 addrs = 0;
1760                 TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1761                         struct sockaddr *sa = ifa->ifa_addr;
1762
1763                         if (jailed(curthread->td_ucred) &&
1764                             prison_if(curthread->td_ucred, sa))
1765                                 continue;
1766                         addrs++;
1767 #ifdef COMPAT_43
1768                         if (cmd == OSIOCGIFCONF) {
1769                                 struct osockaddr *osa =
1770                                          (struct osockaddr *)&ifr.ifr_addr;
1771                                 ifr.ifr_addr = *sa;
1772                                 osa->sa_family = sa->sa_family;
1773                                 sbuf_bcat(sb, &ifr, sizeof(ifr));
1774                                 max_len += sizeof(ifr);
1775                         } else
1776 #endif
1777                         if (sa->sa_len <= sizeof(*sa)) {
1778                                 ifr.ifr_addr = *sa;
1779                                 sbuf_bcat(sb, &ifr, sizeof(ifr));
1780                                 max_len += sizeof(ifr);
1781                         } else {
1782                                 sbuf_bcat(sb, &ifr,
1783                                     offsetof(struct ifreq, ifr_addr));
1784                                 max_len += offsetof(struct ifreq, ifr_addr);
1785                                 sbuf_bcat(sb, sa, sa->sa_len);
1786                                 max_len += sa->sa_len;
1787                         }
1788
1789                         if (!sbuf_overflowed(sb))
1790                                 valid_len = sbuf_len(sb);
1791                 }
1792                 if (addrs == 0) {
1793                         bzero((caddr_t)&ifr.ifr_addr, sizeof(ifr.ifr_addr));
1794                         sbuf_bcat(sb, &ifr, sizeof(ifr));
1795                         max_len += sizeof(ifr);
1796
1797                         if (!sbuf_overflowed(sb))
1798                                 valid_len = sbuf_len(sb);
1799                 }
1800         }
1801         IFNET_RUNLOCK();
1802
1803         /*
1804          * If we didn't allocate enough space (uncommon), try again.  If
1805          * we have already allocated as much space as we are allowed,
1806          * return what we've got.
1807          */
1808         if (valid_len != max_len && !full) {
1809                 sbuf_delete(sb);
1810                 goto again;
1811         }
1812
1813         ifc->ifc_len = valid_len;
1814         sbuf_finish(sb);
1815         error = copyout(sbuf_data(sb), ifc->ifc_req, ifc->ifc_len);
1816         sbuf_delete(sb);
1817         return (error);
1818 }
1819
1820 /*
1821  * Just like ifpromisc(), but for all-multicast-reception mode.
1822  */
1823 int
1824 if_allmulti(struct ifnet *ifp, int onswitch)
1825 {
1826
1827         return (if_setflag(ifp, IFF_ALLMULTI, 0, &ifp->if_amcount, onswitch));
1828 }
1829
1830 static struct ifmultiaddr *
1831 if_findmulti(struct ifnet *ifp, struct sockaddr *sa)
1832 {
1833         struct ifmultiaddr *ifma;
1834
1835         IF_ADDR_LOCK_ASSERT(ifp);
1836
1837         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
1838                 if (sa_equal(ifma->ifma_addr, sa))
1839                         break;
1840         }
1841
1842         return ifma;
1843 }
1844
1845 /*
1846  * Allocate a new ifmultiaddr and initialize based on passed arguments.  We
1847  * make copies of passed sockaddrs.  The ifmultiaddr will not be added to
1848  * the ifnet multicast address list here, so the caller must do that and
1849  * other setup work (such as notifying the device driver).  The reference
1850  * count is initialized to 1.
1851  */
1852 static struct ifmultiaddr *
1853 if_allocmulti(struct ifnet *ifp, struct sockaddr *sa, struct sockaddr *llsa,
1854     int mflags)
1855 {
1856         struct ifmultiaddr *ifma;
1857         struct sockaddr *dupsa;
1858
1859         MALLOC(ifma, struct ifmultiaddr *, sizeof *ifma, M_IFMADDR, mflags |
1860             M_ZERO);
1861         if (ifma == NULL)
1862                 return (NULL);
1863
1864         MALLOC(dupsa, struct sockaddr *, sa->sa_len, M_IFMADDR, mflags);
1865         if (dupsa == NULL) {
1866                 FREE(ifma, M_IFMADDR);
1867                 return (NULL);
1868         }
1869         bcopy(sa, dupsa, sa->sa_len);
1870         ifma->ifma_addr = dupsa;
1871
1872         ifma->ifma_ifp = ifp;
1873         ifma->ifma_refcount = 1;
1874         ifma->ifma_protospec = NULL;
1875
1876         if (llsa == NULL) {
1877                 ifma->ifma_lladdr = NULL;
1878                 return (ifma);
1879         }
1880
1881         MALLOC(dupsa, struct sockaddr *, llsa->sa_len, M_IFMADDR, mflags);
1882         if (dupsa == NULL) {
1883                 FREE(ifma->ifma_addr, M_IFMADDR);
1884                 FREE(ifma, M_IFMADDR);
1885                 return (NULL);
1886         }
1887         bcopy(llsa, dupsa, llsa->sa_len);
1888         ifma->ifma_lladdr = dupsa;
1889
1890         return (ifma);
1891 }
1892
1893 /*
1894  * if_freemulti: free ifmultiaddr structure and possibly attached related
1895  * addresses.  The caller is responsible for implementing reference
1896  * counting, notifying the driver, handling routing messages, and releasing
1897  * any dependent link layer state.
1898  */
1899 static void
1900 if_freemulti(struct ifmultiaddr *ifma)
1901 {
1902
1903         KASSERT(ifma->ifma_refcount == 1, ("if_freemulti: refcount %d",
1904             ifma->ifma_refcount));
1905         KASSERT(ifma->ifma_protospec == NULL,
1906             ("if_freemulti: protospec not NULL"));
1907
1908         if (ifma->ifma_lladdr != NULL)
1909                 FREE(ifma->ifma_lladdr, M_IFMADDR);
1910         FREE(ifma->ifma_addr, M_IFMADDR);
1911         FREE(ifma, M_IFMADDR);
1912 }
1913
1914 /*
1915  * Register an additional multicast address with a network interface.
1916  *
1917  * - If the address is already present, bump the reference count on the
1918  *   address and return.
1919  * - If the address is not link-layer, look up a link layer address.
1920  * - Allocate address structures for one or both addresses, and attach to the
1921  *   multicast address list on the interface.  If automatically adding a link
1922  *   layer address, the protocol address will own a reference to the link
1923  *   layer address, to be freed when it is freed.
1924  * - Notify the network device driver of an addition to the multicast address
1925  *   list.
1926  *
1927  * 'sa' points to caller-owned memory with the desired multicast address.
1928  *
1929  * 'retifma' will be used to return a pointer to the resulting multicast
1930  * address reference, if desired.
1931  */
1932 int
1933 if_addmulti(struct ifnet *ifp, struct sockaddr *sa,
1934     struct ifmultiaddr **retifma)
1935 {
1936         struct ifmultiaddr *ifma, *ll_ifma;
1937         struct sockaddr *llsa;
1938         int error;
1939
1940         /*
1941          * If the address is already present, return a new reference to it;
1942          * otherwise, allocate storage and set up a new address.
1943          */
1944         IF_ADDR_LOCK(ifp);
1945         ifma = if_findmulti(ifp, sa);
1946         if (ifma != NULL) {
1947                 ifma->ifma_refcount++;
1948                 if (retifma != NULL)
1949                         *retifma = ifma;
1950                 IF_ADDR_UNLOCK(ifp);
1951                 return (0);
1952         }
1953
1954         /*
1955          * The address isn't already present; resolve the protocol address
1956          * into a link layer address, and then look that up, bump its
1957          * refcount or allocate an ifma for that also.  If 'llsa' was
1958          * returned, we will need to free it later.
1959          */
1960         llsa = NULL;
1961         ll_ifma = NULL;
1962         if (ifp->if_resolvemulti != NULL) {
1963                 error = ifp->if_resolvemulti(ifp, &llsa, sa);
1964                 if (error)
1965                         goto unlock_out;
1966         }
1967
1968         /*
1969          * Allocate the new address.  Don't hook it up yet, as we may also
1970          * need to allocate a link layer multicast address.
1971          */
1972         ifma = if_allocmulti(ifp, sa, llsa, M_NOWAIT);
1973         if (ifma == NULL) {
1974                 error = ENOMEM;
1975                 goto free_llsa_out;
1976         }
1977
1978         /*
1979          * If a link layer address is found, we'll need to see if it's
1980          * already present in the address list, or allocate is as well.
1981          * When this block finishes, the link layer address will be on the
1982          * list.
1983          */
1984         if (llsa != NULL) {
1985                 ll_ifma = if_findmulti(ifp, llsa);
1986                 if (ll_ifma == NULL) {
1987                         ll_ifma = if_allocmulti(ifp, llsa, NULL, M_NOWAIT);
1988                         if (ll_ifma == NULL) {
1989                                 if_freemulti(ifma);
1990                                 error = ENOMEM;
1991                                 goto free_llsa_out;
1992                         }
1993                         TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ll_ifma,
1994                             ifma_link);
1995                 } else
1996                         ll_ifma->ifma_refcount++;
1997         }
1998
1999         /*
2000          * We now have a new multicast address, ifma, and possibly a new or
2001          * referenced link layer address.  Add the primary address to the
2002          * ifnet address list.
2003          */
2004         TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ifma, ifma_link);
2005
2006         if (retifma != NULL)
2007                 *retifma = ifma;
2008
2009         /*
2010          * Must generate the message while holding the lock so that 'ifma'
2011          * pointer is still valid.
2012          *
2013          * XXXRW: How come we don't announce ll_ifma?
2014          */
2015         rt_newmaddrmsg(RTM_NEWMADDR, ifma);
2016         IF_ADDR_UNLOCK(ifp);
2017
2018         /*
2019          * We are certain we have added something, so call down to the
2020          * interface to let them know about it.
2021          */
2022         if (ifp->if_ioctl != NULL) {
2023                 IFF_LOCKGIANT(ifp);
2024                 (void) (*ifp->if_ioctl)(ifp, SIOCADDMULTI, 0);
2025                 IFF_UNLOCKGIANT(ifp);
2026         }
2027
2028         if (llsa != NULL)
2029                 FREE(llsa, M_IFMADDR);
2030
2031         return (0);
2032
2033 free_llsa_out:
2034         if (llsa != NULL)
2035                 FREE(llsa, M_IFMADDR);
2036
2037 unlock_out:
2038         IF_ADDR_UNLOCK(ifp);
2039         return (error);
2040 }
2041
2042 /*
2043  * Remove a reference to a multicast address on this interface.  Yell
2044  * if the request does not match an existing membership.
2045  */
2046 int
2047 if_delmulti(struct ifnet *ifp, struct sockaddr *sa)
2048 {
2049         struct ifmultiaddr *ifma, *ll_ifma;
2050
2051         IF_ADDR_LOCK(ifp);
2052         ifma = if_findmulti(ifp, sa);
2053         if (ifma == NULL) {
2054                 IF_ADDR_UNLOCK(ifp);
2055                 return ENOENT;
2056         }
2057
2058         if (ifma->ifma_refcount > 1) {
2059                 ifma->ifma_refcount--;
2060                 IF_ADDR_UNLOCK(ifp);
2061                 return 0;
2062         }
2063
2064         sa = ifma->ifma_lladdr;
2065         if (sa != NULL)
2066                 ll_ifma = if_findmulti(ifp, sa);
2067         else
2068                 ll_ifma = NULL;
2069
2070         /*
2071          * XXXRW: How come we don't announce ll_ifma?
2072          */
2073         rt_newmaddrmsg(RTM_DELMADDR, ifma);
2074
2075         TAILQ_REMOVE(&ifp->if_multiaddrs, ifma, ifma_link);
2076         if_freemulti(ifma);
2077
2078         if (ll_ifma != NULL) {
2079                 if (ll_ifma->ifma_refcount == 1) {
2080                         TAILQ_REMOVE(&ifp->if_multiaddrs, ll_ifma, ifma_link);
2081                         if_freemulti(ll_ifma);
2082                 } else
2083                         ll_ifma->ifma_refcount--;
2084         }
2085         IF_ADDR_UNLOCK(ifp);
2086
2087         /*
2088          * Make sure the interface driver is notified
2089          * in the case of a link layer mcast group being left.
2090          */
2091         if (ifp->if_ioctl) {
2092                 IFF_LOCKGIANT(ifp);
2093                 (void) (*ifp->if_ioctl)(ifp, SIOCDELMULTI, 0);
2094                 IFF_UNLOCKGIANT(ifp);
2095         }
2096
2097         return 0;
2098 }
2099
2100 /*
2101  * Set the link layer address on an interface.
2102  *
2103  * At this time we only support certain types of interfaces,
2104  * and we don't allow the length of the address to change.
2105  */
2106 int
2107 if_setlladdr(struct ifnet *ifp, const u_char *lladdr, int len)
2108 {
2109         struct sockaddr_dl *sdl;
2110         struct ifaddr *ifa;
2111         struct ifreq ifr;
2112
2113         ifa = ifaddr_byindex(ifp->if_index);
2114         if (ifa == NULL)
2115                 return (EINVAL);
2116         sdl = (struct sockaddr_dl *)ifa->ifa_addr;
2117         if (sdl == NULL)
2118                 return (EINVAL);
2119         if (len != sdl->sdl_alen)       /* don't allow length to change */
2120                 return (EINVAL);
2121         switch (ifp->if_type) {
2122         case IFT_ETHER:                 /* these types use struct arpcom */
2123         case IFT_FDDI:
2124         case IFT_XETHER:
2125         case IFT_ISO88025:
2126         case IFT_L2VLAN:
2127         case IFT_BRIDGE:
2128                 bcopy(lladdr, IFP2ENADDR(ifp), len);
2129                 /*
2130                  * XXX We also need to store the lladdr in LLADDR(sdl),
2131                  * which is done below. This is a pain because we must
2132                  * remember to keep the info in sync.
2133                  */
2134                 /* FALLTHROUGH */
2135         case IFT_ARCNET:
2136                 bcopy(lladdr, LLADDR(sdl), len);
2137                 break;
2138         default:
2139                 return (ENODEV);
2140         }
2141         /*
2142          * If the interface is already up, we need
2143          * to re-init it in order to reprogram its
2144          * address filter.
2145          */
2146         if ((ifp->if_flags & IFF_UP) != 0) {
2147                 if (ifp->if_ioctl) {
2148                         IFF_LOCKGIANT(ifp);
2149                         ifp->if_flags &= ~IFF_UP;
2150                         ifr.ifr_flags = ifp->if_flags & 0xffff;
2151                         ifr.ifr_flagshigh = ifp->if_flags >> 16;
2152                         (*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
2153                         ifp->if_flags |= IFF_UP;
2154                         ifr.ifr_flags = ifp->if_flags & 0xffff;
2155                         ifr.ifr_flagshigh = ifp->if_flags >> 16;
2156                         (*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
2157                         IFF_UNLOCKGIANT(ifp);
2158                 }
2159 #ifdef INET
2160                 /*
2161                  * Also send gratuitous ARPs to notify other nodes about
2162                  * the address change.
2163                  */
2164                 TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
2165                         if (ifa->ifa_addr != NULL &&
2166                             ifa->ifa_addr->sa_family == AF_INET)
2167                                 arp_ifinit(ifp, ifa);
2168                 }
2169 #endif
2170         }
2171         return (0);
2172 }
2173
2174 /*
2175  * The name argument must be a pointer to storage which will last as
2176  * long as the interface does.  For physical devices, the result of
2177  * device_get_name(dev) is a good choice and for pseudo-devices a
2178  * static string works well.
2179  */
2180 void
2181 if_initname(struct ifnet *ifp, const char *name, int unit)
2182 {
2183         ifp->if_dname = name;
2184         ifp->if_dunit = unit;
2185         if (unit != IF_DUNIT_NONE)
2186                 snprintf(ifp->if_xname, IFNAMSIZ, "%s%d", name, unit);
2187         else
2188                 strlcpy(ifp->if_xname, name, IFNAMSIZ);
2189 }
2190
2191 int
2192 if_printf(struct ifnet *ifp, const char * fmt, ...)
2193 {
2194         va_list ap;
2195         int retval;
2196
2197         retval = printf("%s: ", ifp->if_xname);
2198         va_start(ap, fmt);
2199         retval += vprintf(fmt, ap);
2200         va_end(ap);
2201         return (retval);
2202 }
2203
2204 /*
2205  * When an interface is marked IFF_NEEDSGIANT, its if_start() routine cannot
2206  * be called without Giant.  However, we often can't acquire the Giant lock
2207  * at those points; instead, we run it via a task queue that holds Giant via
2208  * if_start_deferred.
2209  *
2210  * XXXRW: We need to make sure that the ifnet isn't fully detached until any
2211  * outstanding if_start_deferred() tasks that will run after the free.  This
2212  * probably means waiting in if_detach().
2213  */
2214 void
2215 if_start(struct ifnet *ifp)
2216 {
2217
2218         NET_ASSERT_GIANT();
2219
2220         if ((ifp->if_flags & IFF_NEEDSGIANT) != 0 && debug_mpsafenet != 0) {
2221                 if (mtx_owned(&Giant))
2222                         (*(ifp)->if_start)(ifp);
2223                 else
2224                         taskqueue_enqueue(taskqueue_swi_giant,
2225                             &ifp->if_starttask);
2226         } else
2227                 (*(ifp)->if_start)(ifp);
2228 }
2229
2230 static void
2231 if_start_deferred(void *context, int pending)
2232 {
2233         struct ifnet *ifp;
2234
2235         /*
2236          * This code must be entered with Giant, and should never run if
2237          * we're not running with debug.mpsafenet.
2238          */
2239         KASSERT(debug_mpsafenet != 0, ("if_start_deferred: debug.mpsafenet"));
2240         GIANT_REQUIRED;
2241
2242         ifp = context;
2243         (ifp->if_start)(ifp);
2244 }
2245
2246 int
2247 if_handoff(struct ifqueue *ifq, struct mbuf *m, struct ifnet *ifp, int adjust)
2248 {
2249         int active = 0;
2250
2251         IF_LOCK(ifq);
2252         if (_IF_QFULL(ifq)) {
2253                 _IF_DROP(ifq);
2254                 IF_UNLOCK(ifq);
2255                 m_freem(m);
2256                 return (0);
2257         }
2258         if (ifp != NULL) {
2259                 ifp->if_obytes += m->m_pkthdr.len + adjust;
2260                 if (m->m_flags & (M_BCAST|M_MCAST))
2261                         ifp->if_omcasts++;
2262                 active = ifp->if_flags & IFF_OACTIVE;
2263         }
2264         _IF_ENQUEUE(ifq, m);
2265         IF_UNLOCK(ifq);
2266         if (ifp != NULL && !active)
2267                 if_start(ifp);
2268         return (1);
2269 }
2270
2271 void
2272 if_register_com_alloc(u_char type,
2273     if_com_alloc_t *a, if_com_free_t *f)
2274 {
2275         
2276         KASSERT(if_com_alloc[type] == NULL,
2277             ("if_register_com_alloc: %d already registered", type));
2278         KASSERT(if_com_free[type] == NULL,
2279             ("if_register_com_alloc: %d free already registered", type));
2280
2281         if_com_alloc[type] = a;
2282         if_com_free[type] = f;
2283 }
2284
2285 void
2286 if_deregister_com_alloc(u_char type)
2287 {
2288         
2289         KASSERT(if_com_alloc[type] == NULL,
2290             ("if_deregister_com_alloc: %d not registered", type));
2291         KASSERT(if_com_free[type] == NULL,
2292             ("if_deregister_com_alloc: %d free not registered", type));
2293         if_com_alloc[type] = NULL;
2294         if_com_free[type] = NULL;
2295 }