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