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