Merge branch 'master' of ssh://crater.dragonflybsd.org/repository/git/dragonfly
[dragonfly.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  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *      @(#)if.c        8.3 (Berkeley) 1/4/94
34  * $FreeBSD: src/sys/net/if.c,v 1.185 2004/03/13 02:35:03 brooks Exp $
35  * $DragonFly: src/sys/net/if.c,v 1.84 2008/11/15 11:58:16 sephe Exp $
36  */
37
38 #include "opt_compat.h"
39 #include "opt_inet6.h"
40 #include "opt_inet.h"
41 #include "opt_polling.h"
42 #include "opt_ifpoll.h"
43
44 #include <sys/param.h>
45 #include <sys/malloc.h>
46 #include <sys/mbuf.h>
47 #include <sys/systm.h>
48 #include <sys/proc.h>
49 #include <sys/priv.h>
50 #include <sys/protosw.h>
51 #include <sys/socket.h>
52 #include <sys/socketvar.h>
53 #include <sys/socketops.h>
54 #include <sys/protosw.h>
55 #include <sys/kernel.h>
56 #include <sys/ktr.h>
57 #include <sys/sockio.h>
58 #include <sys/syslog.h>
59 #include <sys/sysctl.h>
60 #include <sys/domain.h>
61 #include <sys/thread.h>
62 #include <sys/thread2.h>
63 #include <sys/serialize.h>
64 #include <sys/msgport2.h>
65 #include <sys/bus.h>
66
67 #include <net/if.h>
68 #include <net/if_arp.h>
69 #include <net/if_dl.h>
70 #include <net/if_types.h>
71 #include <net/if_var.h>
72 #include <net/ifq_var.h>
73 #include <net/radix.h>
74 #include <net/route.h>
75 #include <net/if_clone.h>
76 #include <net/netisr.h>
77 #include <net/netmsg2.h>
78
79 #include <machine/atomic.h>
80 #include <machine/stdarg.h>
81 #include <machine/smp.h>
82
83 #if defined(INET) || defined(INET6)
84 /*XXX*/
85 #include <netinet/in.h>
86 #include <netinet/in_var.h>
87 #include <netinet/if_ether.h>
88 #ifdef INET6
89 #include <netinet6/in6_var.h>
90 #include <netinet6/in6_ifattach.h>
91 #endif
92 #endif
93
94 #if defined(COMPAT_43)
95 #include <emulation/43bsd/43bsd_socket.h>
96 #endif /* COMPAT_43 */
97
98 struct netmsg_ifaddr {
99         struct netmsg   netmsg;
100         struct ifaddr   *ifa;
101         struct ifnet    *ifp;
102         int             tail;
103 };
104
105 /*
106  * System initialization
107  */
108 static void     if_attachdomain(void *);
109 static void     if_attachdomain1(struct ifnet *);
110 static int      ifconf(u_long, caddr_t, struct ucred *);
111 static void     ifinit(void *);
112 static void     ifnetinit(void *);
113 static void     if_slowtimo(void *);
114 static void     link_rtrequest(int, struct rtentry *, struct rt_addrinfo *);
115 static int      if_rtdel(struct radix_node *, void *);
116
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 SYSCTL_NODE(_net, PF_LINK, link, CTLFLAG_RW, 0, "Link layers");
126 SYSCTL_NODE(_net_link, 0, generic, CTLFLAG_RW, 0, "Generic link-management");
127
128 SYSINIT(interfaces, SI_SUB_PROTO_IF, SI_ORDER_FIRST, ifinit, NULL)
129 /* Must be after netisr_init */
130 SYSINIT(ifnet, SI_SUB_PRE_DRIVERS, SI_ORDER_SECOND, ifnetinit, NULL)
131
132 static  if_com_alloc_t *if_com_alloc[256];
133 static  if_com_free_t *if_com_free[256];
134
135 MALLOC_DEFINE(M_IFADDR, "ifaddr", "interface address");
136 MALLOC_DEFINE(M_IFMADDR, "ether_multi", "link-level multicast address");
137 MALLOC_DEFINE(M_IFNET, "ifnet", "interface structure");
138
139 int                     ifqmaxlen = IFQ_MAXLEN;
140 struct ifnethead        ifnet = TAILQ_HEAD_INITIALIZER(ifnet);
141
142 /* In ifq_dispatch(), try to do direct ifnet.if_start first */
143 static int              ifq_dispatch_schedonly = 0;
144 SYSCTL_INT(_net_link_generic, OID_AUTO, ifq_dispatch_schedonly, CTLFLAG_RW,
145            &ifq_dispatch_schedonly, 0, "");
146
147 /* In ifq_dispatch(), schedule ifnet.if_start without checking ifnet.if_snd */
148 static int              ifq_dispatch_schednochk = 0;
149 SYSCTL_INT(_net_link_generic, OID_AUTO, ifq_dispatch_schednochk, CTLFLAG_RW,
150            &ifq_dispatch_schednochk, 0, "");
151
152 /* In if_devstart(), try to do direct ifnet.if_start first */
153 static int              if_devstart_schedonly = 0;
154 SYSCTL_INT(_net_link_generic, OID_AUTO, if_devstart_schedonly, CTLFLAG_RW,
155            &if_devstart_schedonly, 0, "");
156
157 /* In if_devstart(), schedule ifnet.if_start without checking ifnet.if_snd */
158 static int              if_devstart_schednochk = 0;
159 SYSCTL_INT(_net_link_generic, OID_AUTO, if_devstart_schednochk, CTLFLAG_RW,
160            &if_devstart_schednochk, 0, "");
161
162 #ifdef SMP
163 /* Schedule ifnet.if_start on the current CPU */
164 static int              if_start_oncpu_sched = 0;
165 SYSCTL_INT(_net_link_generic, OID_AUTO, if_start_oncpu_sched, CTLFLAG_RW,
166            &if_start_oncpu_sched, 0, "");
167 #endif
168
169 struct callout          if_slowtimo_timer;
170
171 int                     if_index = 0;
172 struct ifnet            **ifindex2ifnet = NULL;
173 static struct thread    ifnet_threads[MAXCPU];
174
175 #define IFQ_KTR_STRING          "ifq=%p"
176 #define IFQ_KTR_ARG_SIZE        (sizeof(void *))
177 #ifndef KTR_IFQ
178 #define KTR_IFQ                 KTR_ALL
179 #endif
180 KTR_INFO_MASTER(ifq);
181 KTR_INFO(KTR_IFQ, ifq, enqueue, 0, IFQ_KTR_STRING, IFQ_KTR_ARG_SIZE);
182 KTR_INFO(KTR_IFQ, ifq, dequeue, 1, IFQ_KTR_STRING, IFQ_KTR_ARG_SIZE);
183 #define logifq(name, arg)       KTR_LOG(ifq_ ## name, arg)
184
185 #define IF_START_KTR_STRING     "ifp=%p"
186 #define IF_START_KTR_ARG_SIZE   (sizeof(void *))
187 #ifndef KTR_IF_START
188 #define KTR_IF_START            KTR_ALL
189 #endif
190 KTR_INFO_MASTER(if_start);
191 KTR_INFO(KTR_IF_START, if_start, run, 0,
192          IF_START_KTR_STRING, IF_START_KTR_ARG_SIZE);
193 KTR_INFO(KTR_IF_START, if_start, sched, 1,
194          IF_START_KTR_STRING, IF_START_KTR_ARG_SIZE);
195 KTR_INFO(KTR_IF_START, if_start, avoid, 2,
196          IF_START_KTR_STRING, IF_START_KTR_ARG_SIZE);
197 KTR_INFO(KTR_IF_START, if_start, contend_sched, 3,
198          IF_START_KTR_STRING, IF_START_KTR_ARG_SIZE);
199 #ifdef SMP
200 KTR_INFO(KTR_IF_START, if_start, chase_sched, 4,
201          IF_START_KTR_STRING, IF_START_KTR_ARG_SIZE);
202 #endif
203 #define logifstart(name, arg)   KTR_LOG(if_start_ ## name, arg)
204
205 TAILQ_HEAD(, ifg_group) ifg_head;
206
207 /*
208  * Network interface utility routines.
209  *
210  * Routines with ifa_ifwith* names take sockaddr *'s as
211  * parameters.
212  */
213 /* ARGSUSED*/
214 void
215 ifinit(void *dummy)
216 {
217         struct ifnet *ifp;
218
219         callout_init(&if_slowtimo_timer);
220
221         crit_enter();
222         TAILQ_FOREACH(ifp, &ifnet, if_link) {
223                 if (ifp->if_snd.ifq_maxlen == 0) {
224                         if_printf(ifp, "XXX: driver didn't set ifq_maxlen\n");
225                         ifp->if_snd.ifq_maxlen = ifqmaxlen;
226                 }
227         }
228         crit_exit();
229
230         if_slowtimo(0);
231 }
232
233 static int
234 if_start_cpuid(struct ifnet *ifp)
235 {
236         return ifp->if_cpuid;
237 }
238
239 #ifdef DEVICE_POLLING
240 static int
241 if_start_cpuid_poll(struct ifnet *ifp)
242 {
243         int poll_cpuid = ifp->if_poll_cpuid;
244
245         if (poll_cpuid >= 0)
246                 return poll_cpuid;
247         else
248                 return ifp->if_cpuid;
249 }
250 #endif
251
252 static void
253 if_start_ipifunc(void *arg)
254 {
255         struct ifnet *ifp = arg;
256         struct lwkt_msg *lmsg = &ifp->if_start_nmsg[mycpuid].nm_lmsg;
257
258         crit_enter();
259         if (lmsg->ms_flags & MSGF_DONE)
260                 lwkt_sendmsg(ifnet_portfn(mycpuid), lmsg);
261         crit_exit();
262 }
263
264 /*
265  * Schedule ifnet.if_start on ifnet's CPU
266  */
267 static void
268 if_start_schedule(struct ifnet *ifp)
269 {
270 #ifdef SMP
271         int cpu;
272
273         if (if_start_oncpu_sched)
274                 cpu = mycpuid;
275         else
276                 cpu = ifp->if_start_cpuid(ifp);
277
278         if (cpu != mycpuid)
279                 lwkt_send_ipiq(globaldata_find(cpu), if_start_ipifunc, ifp);
280         else
281 #endif
282         if_start_ipifunc(ifp);
283 }
284
285 /*
286  * NOTE:
287  * This function will release ifnet.if_start interlock,
288  * if ifnet.if_start does not need to be scheduled
289  */
290 static __inline int
291 if_start_need_schedule(struct ifaltq *ifq, int running)
292 {
293         if (!running || ifq_is_empty(ifq)
294 #ifdef ALTQ
295             || ifq->altq_tbr != NULL
296 #endif
297         ) {
298                 ALTQ_LOCK(ifq);
299                 /*
300                  * ifnet.if_start interlock is released, if:
301                  * 1) Hardware can not take any packets, due to
302                  *    o  interface is marked down
303                  *    o  hardware queue is full (IFF_OACTIVE)
304                  *    Under the second situation, hardware interrupt
305                  *    or polling(4) will call/schedule ifnet.if_start
306                  *    when hardware queue is ready
307                  * 2) There is not packet in the ifnet.if_snd.
308                  *    Further ifq_dispatch or ifq_handoff will call/
309                  *    schedule ifnet.if_start
310                  * 3) TBR is used and it does not allow further
311                  *    dequeueing.
312                  *    TBR callout will call ifnet.if_start
313                  */
314                 if (!running || !ifq_data_ready(ifq)) {
315                         ifq->altq_started = 0;
316                         ALTQ_UNLOCK(ifq);
317                         return 0;
318                 }
319                 ALTQ_UNLOCK(ifq);
320         }
321         return 1;
322 }
323
324 static void
325 if_start_dispatch(struct netmsg *nmsg)
326 {
327         struct lwkt_msg *lmsg = &nmsg->nm_lmsg;
328         struct ifnet *ifp = lmsg->u.ms_resultp;
329         struct ifaltq *ifq = &ifp->if_snd;
330         int running = 0;
331
332         crit_enter();
333         lwkt_replymsg(lmsg, 0); /* reply ASAP */
334         crit_exit();
335
336 #ifdef SMP
337         if (!if_start_oncpu_sched && mycpuid != ifp->if_start_cpuid(ifp)) {
338                 /*
339                  * If the ifnet is still up, we need to
340                  * chase its CPU change.
341                  */
342                 if (ifp->if_flags & IFF_UP) {
343                         logifstart(chase_sched, ifp);
344                         if_start_schedule(ifp);
345                         return;
346                 } else {
347                         goto check;
348                 }
349         }
350 #endif
351
352         if (ifp->if_flags & IFF_UP) {
353                 ifnet_serialize_tx(ifp); /* XXX try? */
354                 if ((ifp->if_flags & IFF_OACTIVE) == 0) {
355                         logifstart(run, ifp);
356                         ifp->if_start(ifp);
357                         if ((ifp->if_flags &
358                         (IFF_OACTIVE | IFF_RUNNING)) == IFF_RUNNING)
359                                 running = 1;
360                 }
361                 ifnet_deserialize_tx(ifp);
362         }
363 #ifdef SMP
364 check:
365 #endif
366         if (if_start_need_schedule(ifq, running)) {
367                 crit_enter();
368                 if (lmsg->ms_flags & MSGF_DONE) { /* XXX necessary? */
369                         logifstart(sched, ifp);
370                         lwkt_sendmsg(ifnet_portfn(mycpuid), lmsg);
371                 }
372                 crit_exit();
373         }
374 }
375
376 /* Device driver ifnet.if_start helper function */
377 void
378 if_devstart(struct ifnet *ifp)
379 {
380         struct ifaltq *ifq = &ifp->if_snd;
381         int running = 0;
382
383         ASSERT_IFNET_SERIALIZED_TX(ifp);
384
385         ALTQ_LOCK(ifq);
386         if (ifq->altq_started || !ifq_data_ready(ifq)) {
387                 logifstart(avoid, ifp);
388                 ALTQ_UNLOCK(ifq);
389                 return;
390         }
391         ifq->altq_started = 1;
392         ALTQ_UNLOCK(ifq);
393
394         if (if_devstart_schedonly) {
395                 /*
396                  * Always schedule ifnet.if_start on ifnet's CPU,
397                  * short circuit the rest of this function.
398                  */
399                 logifstart(sched, ifp);
400                 if_start_schedule(ifp);
401                 return;
402         }
403
404         logifstart(run, ifp);
405         ifp->if_start(ifp);
406
407         if ((ifp->if_flags & (IFF_OACTIVE | IFF_RUNNING)) == IFF_RUNNING)
408                 running = 1;
409
410         if (if_devstart_schednochk || if_start_need_schedule(ifq, running)) {
411                 /*
412                  * More data need to be transmitted, ifnet.if_start is
413                  * scheduled on ifnet's CPU, and we keep going.
414                  * NOTE: ifnet.if_start interlock is not released.
415                  */
416                 logifstart(sched, ifp);
417                 if_start_schedule(ifp);
418         }
419 }
420
421 static void
422 if_default_serialize(struct ifnet *ifp, enum ifnet_serialize slz __unused)
423 {
424         lwkt_serialize_enter(ifp->if_serializer);
425 }
426
427 static void
428 if_default_deserialize(struct ifnet *ifp, enum ifnet_serialize slz __unused)
429 {
430         lwkt_serialize_exit(ifp->if_serializer);
431 }
432
433 static int
434 if_default_tryserialize(struct ifnet *ifp, enum ifnet_serialize slz __unused)
435 {
436         return lwkt_serialize_try(ifp->if_serializer);
437 }
438
439 #ifdef INVARIANTS
440 static void
441 if_default_serialize_assert(struct ifnet *ifp,
442                             enum ifnet_serialize slz __unused,
443                             boolean_t serialized)
444 {
445         if (serialized)
446                 ASSERT_SERIALIZED(ifp->if_serializer);
447         else
448                 ASSERT_NOT_SERIALIZED(ifp->if_serializer);
449 }
450 #endif
451
452 /*
453  * Attach an interface to the list of "active" interfaces.
454  *
455  * The serializer is optional.  If non-NULL access to the interface
456  * may be MPSAFE.
457  */
458 void
459 if_attach(struct ifnet *ifp, lwkt_serialize_t serializer)
460 {
461         unsigned socksize, ifasize;
462         int namelen, masklen;
463         struct sockaddr_dl *sdl;
464         struct ifaddr *ifa;
465         struct ifaltq *ifq;
466         int i;
467
468         static int if_indexlim = 8;
469
470         if (ifp->if_serialize != NULL) {
471                 KASSERT(ifp->if_deserialize != NULL &&
472                         ifp->if_tryserialize != NULL &&
473                         ifp->if_serialize_assert != NULL,
474                         ("serialize functions are partially setup\n"));
475
476                 /*
477                  * If the device supplies serialize functions,
478                  * then clear if_serializer to catch any invalid
479                  * usage of this field.
480                  */
481                 KASSERT(serializer == NULL,
482                         ("both serialize functions and default serializer "
483                          "are supplied\n"));
484                 ifp->if_serializer = NULL;
485         } else {
486                 KASSERT(ifp->if_deserialize == NULL &&
487                         ifp->if_tryserialize == NULL &&
488                         ifp->if_serialize_assert == NULL,
489                         ("serialize functions are partially setup\n"));
490                 ifp->if_serialize = if_default_serialize;
491                 ifp->if_deserialize = if_default_deserialize;
492                 ifp->if_tryserialize = if_default_tryserialize;
493 #ifdef INVARIANTS
494                 ifp->if_serialize_assert = if_default_serialize_assert;
495 #endif
496
497                 /*
498                  * The serializer can be passed in from the device,
499                  * allowing the same serializer to be used for both
500                  * the interrupt interlock and the device queue.
501                  * If not specified, the netif structure will use an
502                  * embedded serializer.
503                  */
504                 if (serializer == NULL) {
505                         serializer = &ifp->if_default_serializer;
506                         lwkt_serialize_init(serializer);
507                 }
508                 ifp->if_serializer = serializer;
509         }
510
511         ifp->if_start_cpuid = if_start_cpuid;
512         ifp->if_cpuid = 0;
513
514 #ifdef DEVICE_POLLING
515         /* Device is not in polling mode by default */
516         ifp->if_poll_cpuid = -1;
517         if (ifp->if_poll != NULL)
518                 ifp->if_start_cpuid = if_start_cpuid_poll;
519 #endif
520
521         ifp->if_start_nmsg = kmalloc(ncpus * sizeof(struct netmsg),
522                                      M_LWKTMSG, M_WAITOK);
523         for (i = 0; i < ncpus; ++i) {
524                 netmsg_init(&ifp->if_start_nmsg[i], NULL, &netisr_adone_rport,
525                             0, if_start_dispatch);
526                 ifp->if_start_nmsg[i].nm_lmsg.u.ms_resultp = ifp;
527         }
528
529         TAILQ_INSERT_TAIL(&ifnet, ifp, if_link);
530         ifp->if_index = ++if_index;
531
532         /*
533          * XXX -
534          * The old code would work if the interface passed a pre-existing
535          * chain of ifaddrs to this code.  We don't trust our callers to
536          * properly initialize the tailq, however, so we no longer allow
537          * this unlikely case.
538          */
539         ifp->if_addrheads = kmalloc(ncpus * sizeof(struct ifaddrhead),
540                                     M_IFADDR, M_WAITOK | M_ZERO);
541         for (i = 0; i < ncpus; ++i)
542                 TAILQ_INIT(&ifp->if_addrheads[i]);
543
544         TAILQ_INIT(&ifp->if_prefixhead);
545         TAILQ_INIT(&ifp->if_multiaddrs);
546         getmicrotime(&ifp->if_lastchange);
547         if (ifindex2ifnet == NULL || if_index >= if_indexlim) {
548                 unsigned int n;
549                 struct ifnet **q;
550
551                 if_indexlim <<= 1;
552
553                 /* grow ifindex2ifnet */
554                 n = if_indexlim * sizeof(*q);
555                 q = kmalloc(n, M_IFADDR, M_WAITOK | M_ZERO);
556                 if (ifindex2ifnet) {
557                         bcopy(ifindex2ifnet, q, n/2);
558                         kfree(ifindex2ifnet, M_IFADDR);
559                 }
560                 ifindex2ifnet = q;
561         }
562
563         ifindex2ifnet[if_index] = ifp;
564
565         /*
566          * create a Link Level name for this device
567          */
568         namelen = strlen(ifp->if_xname);
569 #define _offsetof(t, m) ((int)((caddr_t)&((t *)0)->m))
570         masklen = _offsetof(struct sockaddr_dl, sdl_data[0]) + namelen;
571         socksize = masklen + ifp->if_addrlen;
572 #define ROUNDUP(a) (1 + (((a) - 1) | (sizeof(long) - 1)))
573         if (socksize < sizeof(*sdl))
574                 socksize = sizeof(*sdl);
575         socksize = ROUNDUP(socksize);
576         ifasize = sizeof(struct ifaddr) + 2 * socksize;
577         ifa = ifa_create(ifasize, M_WAITOK);
578         sdl = (struct sockaddr_dl *)(ifa + 1);
579         sdl->sdl_len = socksize;
580         sdl->sdl_family = AF_LINK;
581         bcopy(ifp->if_xname, sdl->sdl_data, namelen);
582         sdl->sdl_nlen = namelen;
583         sdl->sdl_index = ifp->if_index;
584         sdl->sdl_type = ifp->if_type;
585         ifp->if_lladdr = ifa;
586         ifa->ifa_ifp = ifp;
587         ifa->ifa_rtrequest = link_rtrequest;
588         ifa->ifa_addr = (struct sockaddr *)sdl;
589         sdl = (struct sockaddr_dl *)(socksize + (caddr_t)sdl);
590         ifa->ifa_netmask = (struct sockaddr *)sdl;
591         sdl->sdl_len = masklen;
592         while (namelen != 0)
593                 sdl->sdl_data[--namelen] = 0xff;
594         ifa_iflink(ifa, ifp, 0 /* Insert head */);
595
596         EVENTHANDLER_INVOKE(ifnet_attach_event, ifp);
597         devctl_notify("IFNET", ifp->if_xname, "ATTACH", NULL);
598
599         ifq = &ifp->if_snd;
600         ifq->altq_type = 0;
601         ifq->altq_disc = NULL;
602         ifq->altq_flags &= ALTQF_CANTCHANGE;
603         ifq->altq_tbr = NULL;
604         ifq->altq_ifp = ifp;
605         ifq->altq_started = 0;
606         ifq->altq_prepended = NULL;
607         ALTQ_LOCK_INIT(ifq);
608         ifq_set_classic(ifq);
609
610         if (!SLIST_EMPTY(&domains))
611                 if_attachdomain1(ifp);
612
613         /* Announce the interface. */
614         rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
615 }
616
617 static void
618 if_attachdomain(void *dummy)
619 {
620         struct ifnet *ifp;
621
622         crit_enter();
623         TAILQ_FOREACH(ifp, &ifnet, if_list)
624                 if_attachdomain1(ifp);
625         crit_exit();
626 }
627 SYSINIT(domainifattach, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_FIRST,
628         if_attachdomain, NULL);
629
630 static void
631 if_attachdomain1(struct ifnet *ifp)
632 {
633         struct domain *dp;
634
635         crit_enter();
636
637         /* address family dependent data region */
638         bzero(ifp->if_afdata, sizeof(ifp->if_afdata));
639         SLIST_FOREACH(dp, &domains, dom_next)
640                 if (dp->dom_ifattach)
641                         ifp->if_afdata[dp->dom_family] =
642                                 (*dp->dom_ifattach)(ifp);
643         crit_exit();
644 }
645
646 /*
647  * Purge all addresses whose type is _not_ AF_LINK
648  */
649 void
650 if_purgeaddrs_nolink(struct ifnet *ifp)
651 {
652         struct ifaddr_container *ifac, *next;
653
654         TAILQ_FOREACH_MUTABLE(ifac, &ifp->if_addrheads[mycpuid],
655                               ifa_link, next) {
656                 struct ifaddr *ifa = ifac->ifa;
657
658                 /* Leave link ifaddr as it is */
659                 if (ifa->ifa_addr->sa_family == AF_LINK)
660                         continue;
661 #ifdef INET
662                 /* XXX: Ugly!! ad hoc just for INET */
663                 if (ifa->ifa_addr && ifa->ifa_addr->sa_family == AF_INET) {
664                         struct ifaliasreq ifr;
665 #ifdef IFADDR_DEBUG_VERBOSE
666                         int i;
667
668                         kprintf("purge in4 addr %p: ", ifa);
669                         for (i = 0; i < ncpus; ++i)
670                                 kprintf("%d ", ifa->ifa_containers[i].ifa_refcnt);
671                         kprintf("\n");
672 #endif
673
674                         bzero(&ifr, sizeof ifr);
675                         ifr.ifra_addr = *ifa->ifa_addr;
676                         if (ifa->ifa_dstaddr)
677                                 ifr.ifra_broadaddr = *ifa->ifa_dstaddr;
678                         if (in_control(NULL, SIOCDIFADDR, (caddr_t)&ifr, ifp,
679                                        NULL) == 0)
680                                 continue;
681                 }
682 #endif /* INET */
683 #ifdef INET6
684                 if (ifa->ifa_addr && ifa->ifa_addr->sa_family == AF_INET6) {
685 #ifdef IFADDR_DEBUG_VERBOSE
686                         int i;
687
688                         kprintf("purge in6 addr %p: ", ifa);
689                         for (i = 0; i < ncpus; ++i)
690                                 kprintf("%d ", ifa->ifa_containers[i].ifa_refcnt);
691                         kprintf("\n");
692 #endif
693
694                         in6_purgeaddr(ifa);
695                         /* ifp_addrhead is already updated */
696                         continue;
697                 }
698 #endif /* INET6 */
699                 ifa_ifunlink(ifa, ifp);
700                 ifa_destroy(ifa);
701         }
702 }
703
704 /*
705  * Detach an interface, removing it from the
706  * list of "active" interfaces.
707  */
708 void
709 if_detach(struct ifnet *ifp)
710 {
711         struct radix_node_head  *rnh;
712         int i;
713         int cpu, origcpu;
714         struct domain *dp;
715
716         EVENTHANDLER_INVOKE(ifnet_detach_event, ifp);
717
718         /*
719          * Remove routes and flush queues.
720          */
721         crit_enter();
722 #ifdef DEVICE_POLLING
723         if (ifp->if_flags & IFF_POLLING)
724                 ether_poll_deregister(ifp);
725 #endif
726 #ifdef IFPOLL_ENABLE
727         if (ifp->if_flags & IFF_NPOLLING)
728                 ifpoll_deregister(ifp);
729 #endif
730         if_down(ifp);
731
732 #ifdef ALTQ
733         if (ifq_is_enabled(&ifp->if_snd))
734                 altq_disable(&ifp->if_snd);
735         if (ifq_is_attached(&ifp->if_snd))
736                 altq_detach(&ifp->if_snd);
737 #endif
738
739         /*
740          * Clean up all addresses.
741          */
742         ifp->if_lladdr = NULL;
743
744         if_purgeaddrs_nolink(ifp);
745         if (!TAILQ_EMPTY(&ifp->if_addrheads[mycpuid])) {
746                 struct ifaddr *ifa;
747
748                 ifa = TAILQ_FIRST(&ifp->if_addrheads[mycpuid])->ifa;
749                 KASSERT(ifa->ifa_addr->sa_family == AF_LINK,
750                         ("non-link ifaddr is left on if_addrheads"));
751
752                 ifa_ifunlink(ifa, ifp);
753                 ifa_destroy(ifa);
754                 KASSERT(TAILQ_EMPTY(&ifp->if_addrheads[mycpuid]),
755                         ("there are still ifaddrs left on if_addrheads"));
756         }
757
758 #ifdef INET
759         /*
760          * Remove all IPv4 kernel structures related to ifp.
761          */
762         in_ifdetach(ifp);
763 #endif
764
765 #ifdef INET6
766         /*
767          * Remove all IPv6 kernel structs related to ifp.  This should be done
768          * before removing routing entries below, since IPv6 interface direct
769          * routes are expected to be removed by the IPv6-specific kernel API.
770          * Otherwise, the kernel will detect some inconsistency and bark it.
771          */
772         in6_ifdetach(ifp);
773 #endif
774
775         /*
776          * Delete all remaining routes using this interface
777          * Unfortuneatly the only way to do this is to slog through
778          * the entire routing table looking for routes which point
779          * to this interface...oh well...
780          */
781         origcpu = mycpuid;
782         for (cpu = 0; cpu < ncpus2; cpu++) {
783                 lwkt_migratecpu(cpu);
784                 for (i = 1; i <= AF_MAX; i++) {
785                         if ((rnh = rt_tables[cpu][i]) == NULL)
786                                 continue;
787                         rnh->rnh_walktree(rnh, if_rtdel, ifp);
788                 }
789         }
790         lwkt_migratecpu(origcpu);
791
792         /* Announce that the interface is gone. */
793         rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
794         devctl_notify("IFNET", ifp->if_xname, "DETACH", NULL);
795
796         SLIST_FOREACH(dp, &domains, dom_next)
797                 if (dp->dom_ifdetach && ifp->if_afdata[dp->dom_family])
798                         (*dp->dom_ifdetach)(ifp,
799                                 ifp->if_afdata[dp->dom_family]);
800
801         /*
802          * Remove interface from ifindex2ifp[] and maybe decrement if_index.
803          */
804         ifindex2ifnet[ifp->if_index] = NULL;
805         while (if_index > 0 && ifindex2ifnet[if_index] == NULL)
806                 if_index--;
807
808         TAILQ_REMOVE(&ifnet, ifp, if_link);
809         kfree(ifp->if_addrheads, M_IFADDR);
810         kfree(ifp->if_start_nmsg, M_LWKTMSG);
811         crit_exit();
812 }
813
814 /*
815  * Create interface group without members
816  */
817 struct ifg_group *
818 if_creategroup(const char *groupname)
819 {
820         struct ifg_group        *ifg = NULL;
821
822         if ((ifg = (struct ifg_group *)kmalloc(sizeof(struct ifg_group),
823             M_TEMP, M_NOWAIT)) == NULL)
824                 return (NULL);
825
826         strlcpy(ifg->ifg_group, groupname, sizeof(ifg->ifg_group));
827         ifg->ifg_refcnt = 0;
828         ifg->ifg_carp_demoted = 0;
829         TAILQ_INIT(&ifg->ifg_members);
830 #if NPF > 0
831         pfi_attach_ifgroup(ifg);
832 #endif
833         TAILQ_INSERT_TAIL(&ifg_head, ifg, ifg_next);
834
835         return (ifg);
836 }
837
838 /*
839  * Add a group to an interface
840  */
841 int
842 if_addgroup(struct ifnet *ifp, const char *groupname)
843 {
844         struct ifg_list         *ifgl;
845         struct ifg_group        *ifg = NULL;
846         struct ifg_member       *ifgm;
847
848         if (groupname[0] && groupname[strlen(groupname) - 1] >= '0' &&
849             groupname[strlen(groupname) - 1] <= '9')
850                 return (EINVAL);
851
852         TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
853                 if (!strcmp(ifgl->ifgl_group->ifg_group, groupname))
854                         return (EEXIST);
855
856         if ((ifgl = kmalloc(sizeof(*ifgl), M_TEMP, M_NOWAIT)) == NULL)
857                 return (ENOMEM);
858
859         if ((ifgm = kmalloc(sizeof(*ifgm), M_TEMP, M_NOWAIT)) == NULL) {
860                 kfree(ifgl, M_TEMP);
861                 return (ENOMEM);
862         }
863
864         TAILQ_FOREACH(ifg, &ifg_head, ifg_next)
865                 if (!strcmp(ifg->ifg_group, groupname))
866                         break;
867
868         if (ifg == NULL && (ifg = if_creategroup(groupname)) == NULL) {
869                 kfree(ifgl, M_TEMP);
870                 kfree(ifgm, M_TEMP);
871                 return (ENOMEM);
872         }
873
874         ifg->ifg_refcnt++;
875         ifgl->ifgl_group = ifg;
876         ifgm->ifgm_ifp = ifp;
877
878         TAILQ_INSERT_TAIL(&ifg->ifg_members, ifgm, ifgm_next);
879         TAILQ_INSERT_TAIL(&ifp->if_groups, ifgl, ifgl_next);
880
881 #if NPF > 0
882         pfi_group_change(groupname);
883 #endif
884
885         return (0);
886 }
887
888 /*
889  * Remove a group from an interface
890  */
891 int
892 if_delgroup(struct ifnet *ifp, const char *groupname)
893 {
894         struct ifg_list         *ifgl;
895         struct ifg_member       *ifgm;
896
897         TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
898                 if (!strcmp(ifgl->ifgl_group->ifg_group, groupname))
899                         break;
900         if (ifgl == NULL)
901                 return (ENOENT);
902
903         TAILQ_REMOVE(&ifp->if_groups, ifgl, ifgl_next);
904
905         TAILQ_FOREACH(ifgm, &ifgl->ifgl_group->ifg_members, ifgm_next)
906                 if (ifgm->ifgm_ifp == ifp)
907                         break;
908
909         if (ifgm != NULL) {
910                 TAILQ_REMOVE(&ifgl->ifgl_group->ifg_members, ifgm, ifgm_next);
911                 kfree(ifgm, M_TEMP);
912         }
913
914         if (--ifgl->ifgl_group->ifg_refcnt == 0) {
915                 TAILQ_REMOVE(&ifg_head, ifgl->ifgl_group, ifg_next);
916 #if NPF > 0
917                 pfi_detach_ifgroup(ifgl->ifgl_group);
918 #endif
919                 kfree(ifgl->ifgl_group, M_TEMP);
920         }
921
922         kfree(ifgl, M_TEMP);
923
924 #if NPF > 0
925         pfi_group_change(groupname);
926 #endif
927
928         return (0);
929 }
930
931 /*
932  * Stores all groups from an interface in memory pointed
933  * to by data
934  */
935 int
936 if_getgroup(caddr_t data, struct ifnet *ifp)
937 {
938         int                      len, error;
939         struct ifg_list         *ifgl;
940         struct ifg_req           ifgrq, *ifgp;
941         struct ifgroupreq       *ifgr = (struct ifgroupreq *)data;
942
943         if (ifgr->ifgr_len == 0) {
944                 TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
945                         ifgr->ifgr_len += sizeof(struct ifg_req);
946                 return (0);
947         }
948
949         len = ifgr->ifgr_len;
950         ifgp = ifgr->ifgr_groups;
951         TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next) {
952                 if (len < sizeof(ifgrq))
953                         return (EINVAL);
954                 bzero(&ifgrq, sizeof ifgrq);
955                 strlcpy(ifgrq.ifgrq_group, ifgl->ifgl_group->ifg_group,
956                     sizeof(ifgrq.ifgrq_group));
957                 if ((error = copyout((caddr_t)&ifgrq, (caddr_t)ifgp,
958                     sizeof(struct ifg_req))))
959                         return (error);
960                 len -= sizeof(ifgrq);
961                 ifgp++;
962         }
963
964         return (0);
965 }
966
967 /*
968  * Stores all members of a group in memory pointed to by data
969  */
970 int
971 if_getgroupmembers(caddr_t data)
972 {
973         struct ifgroupreq       *ifgr = (struct ifgroupreq *)data;
974         struct ifg_group        *ifg;
975         struct ifg_member       *ifgm;
976         struct ifg_req           ifgrq, *ifgp;
977         int                      len, error;
978
979         TAILQ_FOREACH(ifg, &ifg_head, ifg_next)
980                 if (!strcmp(ifg->ifg_group, ifgr->ifgr_name))
981                         break;
982         if (ifg == NULL)
983                 return (ENOENT);
984
985         if (ifgr->ifgr_len == 0) {
986                 TAILQ_FOREACH(ifgm, &ifg->ifg_members, ifgm_next)
987                         ifgr->ifgr_len += sizeof(ifgrq);
988                 return (0);
989         }
990
991         len = ifgr->ifgr_len;
992         ifgp = ifgr->ifgr_groups;
993         TAILQ_FOREACH(ifgm, &ifg->ifg_members, ifgm_next) {
994                 if (len < sizeof(ifgrq))
995                         return (EINVAL);
996                 bzero(&ifgrq, sizeof ifgrq);
997                 strlcpy(ifgrq.ifgrq_member, ifgm->ifgm_ifp->if_xname,
998                     sizeof(ifgrq.ifgrq_member));
999                 if ((error = copyout((caddr_t)&ifgrq, (caddr_t)ifgp,
1000                     sizeof(struct ifg_req))))
1001                         return (error);
1002                 len -= sizeof(ifgrq);
1003                 ifgp++;
1004         }
1005
1006         return (0);
1007 }
1008
1009 /*
1010  * Delete Routes for a Network Interface
1011  *
1012  * Called for each routing entry via the rnh->rnh_walktree() call above
1013  * to delete all route entries referencing a detaching network interface.
1014  *
1015  * Arguments:
1016  *      rn      pointer to node in the routing table
1017  *      arg     argument passed to rnh->rnh_walktree() - detaching interface
1018  *
1019  * Returns:
1020  *      0       successful
1021  *      errno   failed - reason indicated
1022  *
1023  */
1024 static int
1025 if_rtdel(struct radix_node *rn, void *arg)
1026 {
1027         struct rtentry  *rt = (struct rtentry *)rn;
1028         struct ifnet    *ifp = arg;
1029         int             err;
1030
1031         if (rt->rt_ifp == ifp) {
1032
1033                 /*
1034                  * Protect (sorta) against walktree recursion problems
1035                  * with cloned routes
1036                  */
1037                 if (!(rt->rt_flags & RTF_UP))
1038                         return (0);
1039
1040                 err = rtrequest(RTM_DELETE, rt_key(rt), rt->rt_gateway,
1041                                 rt_mask(rt), rt->rt_flags,
1042                                 NULL);
1043                 if (err) {
1044                         log(LOG_WARNING, "if_rtdel: error %d\n", err);
1045                 }
1046         }
1047
1048         return (0);
1049 }
1050
1051 /*
1052  * Locate an interface based on a complete address.
1053  */
1054 struct ifaddr *
1055 ifa_ifwithaddr(struct sockaddr *addr)
1056 {
1057         struct ifnet *ifp;
1058
1059         TAILQ_FOREACH(ifp, &ifnet, if_link) {
1060                 struct ifaddr_container *ifac;
1061
1062                 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1063                         struct ifaddr *ifa = ifac->ifa;
1064
1065                         if (ifa->ifa_addr->sa_family != addr->sa_family)
1066                                 continue;
1067                         if (sa_equal(addr, ifa->ifa_addr))
1068                                 return (ifa);
1069                         if ((ifp->if_flags & IFF_BROADCAST) &&
1070                             ifa->ifa_broadaddr &&
1071                             /* IPv6 doesn't have broadcast */
1072                             ifa->ifa_broadaddr->sa_len != 0 &&
1073                             sa_equal(ifa->ifa_broadaddr, addr))
1074                                 return (ifa);
1075                 }
1076         }
1077         return (NULL);
1078 }
1079 /*
1080  * Locate the point to point interface with a given destination address.
1081  */
1082 struct ifaddr *
1083 ifa_ifwithdstaddr(struct sockaddr *addr)
1084 {
1085         struct ifnet *ifp;
1086
1087         TAILQ_FOREACH(ifp, &ifnet, if_link) {
1088                 struct ifaddr_container *ifac;
1089
1090                 if (!(ifp->if_flags & IFF_POINTOPOINT))
1091                         continue;
1092
1093                 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1094                         struct ifaddr *ifa = ifac->ifa;
1095
1096                         if (ifa->ifa_addr->sa_family != addr->sa_family)
1097                                 continue;
1098                         if (ifa->ifa_dstaddr &&
1099                             sa_equal(addr, ifa->ifa_dstaddr))
1100                                 return (ifa);
1101                 }
1102         }
1103         return (NULL);
1104 }
1105
1106 /*
1107  * Find an interface on a specific network.  If many, choice
1108  * is most specific found.
1109  */
1110 struct ifaddr *
1111 ifa_ifwithnet(struct sockaddr *addr)
1112 {
1113         struct ifnet *ifp;
1114         struct ifaddr *ifa_maybe = NULL;
1115         u_int af = addr->sa_family;
1116         char *addr_data = addr->sa_data, *cplim;
1117
1118         /*
1119          * AF_LINK addresses can be looked up directly by their index number,
1120          * so do that if we can.
1121          */
1122         if (af == AF_LINK) {
1123                 struct sockaddr_dl *sdl = (struct sockaddr_dl *)addr;
1124
1125                 if (sdl->sdl_index && sdl->sdl_index <= if_index)
1126                         return (ifindex2ifnet[sdl->sdl_index]->if_lladdr);
1127         }
1128
1129         /*
1130          * Scan though each interface, looking for ones that have
1131          * addresses in this address family.
1132          */
1133         TAILQ_FOREACH(ifp, &ifnet, if_link) {
1134                 struct ifaddr_container *ifac;
1135
1136                 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1137                         struct ifaddr *ifa = ifac->ifa;
1138                         char *cp, *cp2, *cp3;
1139
1140                         if (ifa->ifa_addr->sa_family != af)
1141 next:                           continue;
1142                         if (af == AF_INET && ifp->if_flags & IFF_POINTOPOINT) {
1143                                 /*
1144                                  * This is a bit broken as it doesn't
1145                                  * take into account that the remote end may
1146                                  * be a single node in the network we are
1147                                  * looking for.
1148                                  * The trouble is that we don't know the
1149                                  * netmask for the remote end.
1150                                  */
1151                                 if (ifa->ifa_dstaddr != NULL &&
1152                                     sa_equal(addr, ifa->ifa_dstaddr))
1153                                         return (ifa);
1154                         } else {
1155                                 /*
1156                                  * if we have a special address handler,
1157                                  * then use it instead of the generic one.
1158                                  */
1159                                 if (ifa->ifa_claim_addr) {
1160                                         if ((*ifa->ifa_claim_addr)(ifa, addr)) {
1161                                                 return (ifa);
1162                                         } else {
1163                                                 continue;
1164                                         }
1165                                 }
1166
1167                                 /*
1168                                  * Scan all the bits in the ifa's address.
1169                                  * If a bit dissagrees with what we are
1170                                  * looking for, mask it with the netmask
1171                                  * to see if it really matters.
1172                                  * (A byte at a time)
1173                                  */
1174                                 if (ifa->ifa_netmask == 0)
1175                                         continue;
1176                                 cp = addr_data;
1177                                 cp2 = ifa->ifa_addr->sa_data;
1178                                 cp3 = ifa->ifa_netmask->sa_data;
1179                                 cplim = ifa->ifa_netmask->sa_len +
1180                                         (char *)ifa->ifa_netmask;
1181                                 while (cp3 < cplim)
1182                                         if ((*cp++ ^ *cp2++) & *cp3++)
1183                                                 goto next; /* next address! */
1184                                 /*
1185                                  * If the netmask of what we just found
1186                                  * is more specific than what we had before
1187                                  * (if we had one) then remember the new one
1188                                  * before continuing to search
1189                                  * for an even better one.
1190                                  */
1191                                 if (ifa_maybe == 0 ||
1192                                     rn_refines((char *)ifa->ifa_netmask,
1193                                                (char *)ifa_maybe->ifa_netmask))
1194                                         ifa_maybe = ifa;
1195                         }
1196                 }
1197         }
1198         return (ifa_maybe);
1199 }
1200
1201 /*
1202  * Find an interface address specific to an interface best matching
1203  * a given address.
1204  */
1205 struct ifaddr *
1206 ifaof_ifpforaddr(struct sockaddr *addr, struct ifnet *ifp)
1207 {
1208         struct ifaddr_container *ifac;
1209         char *cp, *cp2, *cp3;
1210         char *cplim;
1211         struct ifaddr *ifa_maybe = 0;
1212         u_int af = addr->sa_family;
1213
1214         if (af >= AF_MAX)
1215                 return (0);
1216         TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1217                 struct ifaddr *ifa = ifac->ifa;
1218
1219                 if (ifa->ifa_addr->sa_family != af)
1220                         continue;
1221                 if (ifa_maybe == 0)
1222                         ifa_maybe = ifa;
1223                 if (ifa->ifa_netmask == NULL) {
1224                         if (sa_equal(addr, ifa->ifa_addr) ||
1225                             (ifa->ifa_dstaddr != NULL &&
1226                              sa_equal(addr, ifa->ifa_dstaddr)))
1227                                 return (ifa);
1228                         continue;
1229                 }
1230                 if (ifp->if_flags & IFF_POINTOPOINT) {
1231                         if (sa_equal(addr, ifa->ifa_dstaddr))
1232                                 return (ifa);
1233                 } else {
1234                         cp = addr->sa_data;
1235                         cp2 = ifa->ifa_addr->sa_data;
1236                         cp3 = ifa->ifa_netmask->sa_data;
1237                         cplim = ifa->ifa_netmask->sa_len + (char *)ifa->ifa_netmask;
1238                         for (; cp3 < cplim; cp3++)
1239                                 if ((*cp++ ^ *cp2++) & *cp3)
1240                                         break;
1241                         if (cp3 == cplim)
1242                                 return (ifa);
1243                 }
1244         }
1245         return (ifa_maybe);
1246 }
1247
1248 /*
1249  * Default action when installing a route with a Link Level gateway.
1250  * Lookup an appropriate real ifa to point to.
1251  * This should be moved to /sys/net/link.c eventually.
1252  */
1253 static void
1254 link_rtrequest(int cmd, struct rtentry *rt, struct rt_addrinfo *info)
1255 {
1256         struct ifaddr *ifa;
1257         struct sockaddr *dst;
1258         struct ifnet *ifp;
1259
1260         if (cmd != RTM_ADD || (ifa = rt->rt_ifa) == NULL ||
1261             (ifp = ifa->ifa_ifp) == NULL || (dst = rt_key(rt)) == NULL)
1262                 return;
1263         ifa = ifaof_ifpforaddr(dst, ifp);
1264         if (ifa != NULL) {
1265                 IFAFREE(rt->rt_ifa);
1266                 IFAREF(ifa);
1267                 rt->rt_ifa = ifa;
1268                 if (ifa->ifa_rtrequest && ifa->ifa_rtrequest != link_rtrequest)
1269                         ifa->ifa_rtrequest(cmd, rt, info);
1270         }
1271 }
1272
1273 /*
1274  * Mark an interface down and notify protocols of
1275  * the transition.
1276  * NOTE: must be called at splnet or eqivalent.
1277  */
1278 void
1279 if_unroute(struct ifnet *ifp, int flag, int fam)
1280 {
1281         struct ifaddr_container *ifac;
1282
1283         ifp->if_flags &= ~flag;
1284         getmicrotime(&ifp->if_lastchange);
1285         TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1286                 struct ifaddr *ifa = ifac->ifa;
1287
1288                 if (fam == PF_UNSPEC || (fam == ifa->ifa_addr->sa_family))
1289                         kpfctlinput(PRC_IFDOWN, ifa->ifa_addr);
1290         }
1291         ifq_purge(&ifp->if_snd);
1292         rt_ifmsg(ifp);
1293 }
1294
1295 /*
1296  * Mark an interface up and notify protocols of
1297  * the transition.
1298  * NOTE: must be called at splnet or eqivalent.
1299  */
1300 void
1301 if_route(struct ifnet *ifp, int flag, int fam)
1302 {
1303         struct ifaddr_container *ifac;
1304
1305         ifq_purge(&ifp->if_snd);
1306         ifp->if_flags |= flag;
1307         getmicrotime(&ifp->if_lastchange);
1308         TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1309                 struct ifaddr *ifa = ifac->ifa;
1310
1311                 if (fam == PF_UNSPEC || (fam == ifa->ifa_addr->sa_family))
1312                         kpfctlinput(PRC_IFUP, ifa->ifa_addr);
1313         }
1314         rt_ifmsg(ifp);
1315 #ifdef INET6
1316         in6_if_up(ifp);
1317 #endif
1318 }
1319
1320 /*
1321  * Mark an interface down and notify protocols of the transition.  An
1322  * interface going down is also considered to be a synchronizing event.
1323  * We must ensure that all packet processing related to the interface
1324  * has completed before we return so e.g. the caller can free the ifnet
1325  * structure that the mbufs may be referencing.
1326  *
1327  * NOTE: must be called at splnet or eqivalent.
1328  */
1329 void
1330 if_down(struct ifnet *ifp)
1331 {
1332         if_unroute(ifp, IFF_UP, AF_UNSPEC);
1333         netmsg_service_sync();
1334 }
1335
1336 /*
1337  * Mark an interface up and notify protocols of
1338  * the transition.
1339  * NOTE: must be called at splnet or eqivalent.
1340  */
1341 void
1342 if_up(struct ifnet *ifp)
1343 {
1344         if_route(ifp, IFF_UP, AF_UNSPEC);
1345 }
1346
1347 /*
1348  * Process a link state change.
1349  * NOTE: must be called at splsoftnet or equivalent.
1350  */
1351 void
1352 if_link_state_change(struct ifnet *ifp)
1353 {
1354         int link_state = ifp->if_link_state;
1355
1356         rt_ifmsg(ifp);
1357         devctl_notify("IFNET", ifp->if_xname,
1358             (link_state == LINK_STATE_UP) ? "LINK_UP" : "LINK_DOWN", NULL);
1359 }
1360
1361 /*
1362  * Handle interface watchdog timer routines.  Called
1363  * from softclock, we decrement timers (if set) and
1364  * call the appropriate interface routine on expiration.
1365  */
1366 static void
1367 if_slowtimo(void *arg)
1368 {
1369         struct ifnet *ifp;
1370
1371         crit_enter();
1372
1373         TAILQ_FOREACH(ifp, &ifnet, if_link) {
1374                 if (ifp->if_timer == 0 || --ifp->if_timer)
1375                         continue;
1376                 if (ifp->if_watchdog) {
1377                         if (ifnet_tryserialize_all(ifp)) {
1378                                 (*ifp->if_watchdog)(ifp);
1379                                 ifnet_deserialize_all(ifp);
1380                         } else {
1381                                 /* try again next timeout */
1382                                 ++ifp->if_timer;
1383                         }
1384                 }
1385         }
1386
1387         crit_exit();
1388
1389         callout_reset(&if_slowtimo_timer, hz / IFNET_SLOWHZ, if_slowtimo, NULL);
1390 }
1391
1392 /*
1393  * Map interface name to
1394  * interface structure pointer.
1395  */
1396 struct ifnet *
1397 ifunit(const char *name)
1398 {
1399         struct ifnet *ifp;
1400
1401         /*
1402          * Search all the interfaces for this name/number
1403          */
1404
1405         TAILQ_FOREACH(ifp, &ifnet, if_link) {
1406                 if (strncmp(ifp->if_xname, name, IFNAMSIZ) == 0)
1407                         break;
1408         }
1409         return (ifp);
1410 }
1411
1412
1413 /*
1414  * Map interface name in a sockaddr_dl to
1415  * interface structure pointer.
1416  */
1417 struct ifnet *
1418 if_withname(struct sockaddr *sa)
1419 {
1420         char ifname[IFNAMSIZ+1];
1421         struct sockaddr_dl *sdl = (struct sockaddr_dl *)sa;
1422
1423         if ( (sa->sa_family != AF_LINK) || (sdl->sdl_nlen == 0) ||
1424              (sdl->sdl_nlen > IFNAMSIZ) )
1425                 return NULL;
1426
1427         /*
1428          * ifunit wants a null-terminated name.  It may not be null-terminated
1429          * in the sockaddr.  We don't want to change the caller's sockaddr,
1430          * and there might not be room to put the trailing null anyway, so we
1431          * make a local copy that we know we can null terminate safely.
1432          */
1433
1434         bcopy(sdl->sdl_data, ifname, sdl->sdl_nlen);
1435         ifname[sdl->sdl_nlen] = '\0';
1436         return ifunit(ifname);
1437 }
1438
1439
1440 /*
1441  * Interface ioctls.
1442  */
1443 int
1444 ifioctl(struct socket *so, u_long cmd, caddr_t data, struct ucred *cred)
1445 {
1446         struct ifnet *ifp;
1447         struct ifreq *ifr;
1448         struct ifstat *ifs;
1449         int error;
1450         short oif_flags;
1451         int new_flags;
1452         size_t namelen, onamelen;
1453         char new_name[IFNAMSIZ];
1454         struct ifaddr *ifa;
1455         struct sockaddr_dl *sdl;
1456
1457         switch (cmd) {
1458
1459         case SIOCGIFCONF:
1460         case OSIOCGIFCONF:
1461                 return (ifconf(cmd, data, cred));
1462         }
1463         ifr = (struct ifreq *)data;
1464
1465         switch (cmd) {
1466         case SIOCIFCREATE:
1467         case SIOCIFCREATE2:
1468                 if ((error = priv_check_cred(cred, PRIV_ROOT, 0)) != 0)
1469                         return (error);
1470                 return (if_clone_create(ifr->ifr_name, sizeof(ifr->ifr_name),
1471                         cmd == SIOCIFCREATE2 ? ifr->ifr_data : NULL));
1472         case SIOCIFDESTROY:
1473                 if ((error = priv_check_cred(cred, PRIV_ROOT, 0)) != 0)
1474                         return (error);
1475                 return (if_clone_destroy(ifr->ifr_name));
1476
1477         case SIOCIFGCLONERS:
1478                 return (if_clone_list((struct if_clonereq *)data));
1479         }
1480
1481         ifp = ifunit(ifr->ifr_name);
1482         if (ifp == 0)
1483                 return (ENXIO);
1484         switch (cmd) {
1485
1486         case SIOCGIFINDEX:
1487                 ifr->ifr_index = ifp->if_index;
1488                 break;
1489
1490         case SIOCGIFFLAGS:
1491                 ifr->ifr_flags = ifp->if_flags;
1492                 ifr->ifr_flagshigh = ifp->if_flags >> 16;
1493                 break;
1494
1495         case SIOCGIFCAP:
1496                 ifr->ifr_reqcap = ifp->if_capabilities;
1497                 ifr->ifr_curcap = ifp->if_capenable;
1498                 break;
1499
1500         case SIOCGIFMETRIC:
1501                 ifr->ifr_metric = ifp->if_metric;
1502                 break;
1503
1504         case SIOCGIFMTU:
1505                 ifr->ifr_mtu = ifp->if_mtu;
1506                 break;
1507
1508         case SIOCGIFDATA:
1509                 error = copyout((caddr_t)&ifp->if_data, ifr->ifr_data,
1510                     sizeof(ifp->if_data));
1511                 break;
1512
1513
1514         case SIOCGIFPHYS:
1515                 ifr->ifr_phys = ifp->if_physical;
1516                 break;
1517
1518         case SIOCGIFPOLLCPU:
1519 #ifdef DEVICE_POLLING
1520                 ifr->ifr_pollcpu = ifp->if_poll_cpuid;
1521 #else
1522                 ifr->ifr_pollcpu = -1;
1523 #endif
1524                 break;
1525
1526         case SIOCSIFPOLLCPU:
1527 #ifdef DEVICE_POLLING
1528                 if ((ifp->if_flags & IFF_POLLING) == 0)
1529                         ether_pollcpu_register(ifp, ifr->ifr_pollcpu);
1530 #endif
1531                 break;
1532
1533         case SIOCSIFFLAGS:
1534                 error = priv_check_cred(cred, PRIV_ROOT, 0);
1535                 if (error)
1536                         return (error);
1537                 new_flags = (ifr->ifr_flags & 0xffff) |
1538                     (ifr->ifr_flagshigh << 16);
1539                 if (ifp->if_flags & IFF_SMART) {
1540                         /* Smart drivers twiddle their own routes */
1541                 } else if (ifp->if_flags & IFF_UP &&
1542                     (new_flags & IFF_UP) == 0) {
1543                         crit_enter();
1544                         if_down(ifp);
1545                         crit_exit();
1546                 } else if (new_flags & IFF_UP &&
1547                     (ifp->if_flags & IFF_UP) == 0) {
1548                         crit_enter();
1549                         if_up(ifp);
1550                         crit_exit();
1551                 }
1552
1553 #ifdef DEVICE_POLLING
1554                 if ((new_flags ^ ifp->if_flags) & IFF_POLLING) {
1555                         if (new_flags & IFF_POLLING) {
1556                                 ether_poll_register(ifp);
1557                         } else {
1558                                 ether_poll_deregister(ifp);
1559                         }
1560                 }
1561 #endif
1562 #ifdef IFPOLL_ENABLE
1563                 if ((new_flags ^ ifp->if_flags) & IFF_NPOLLING) {
1564                         if (new_flags & IFF_NPOLLING)
1565                                 ifpoll_register(ifp);
1566                         else
1567                                 ifpoll_deregister(ifp);
1568                 }
1569 #endif
1570
1571                 ifp->if_flags = (ifp->if_flags & IFF_CANTCHANGE) |
1572                         (new_flags &~ IFF_CANTCHANGE);
1573                 if (new_flags & IFF_PPROMISC) {
1574                         /* Permanently promiscuous mode requested */
1575                         ifp->if_flags |= IFF_PROMISC;
1576                 } else if (ifp->if_pcount == 0) {
1577                         ifp->if_flags &= ~IFF_PROMISC;
1578                 }
1579                 if (ifp->if_ioctl) {
1580                         ifnet_serialize_all(ifp);
1581                         ifp->if_ioctl(ifp, cmd, data, cred);
1582                         ifnet_deserialize_all(ifp);
1583                 }
1584                 getmicrotime(&ifp->if_lastchange);
1585                 break;
1586
1587         case SIOCSIFCAP:
1588                 error = priv_check_cred(cred, PRIV_ROOT, 0);
1589                 if (error)
1590                         return (error);
1591                 if (ifr->ifr_reqcap & ~ifp->if_capabilities)
1592                         return (EINVAL);
1593                 ifnet_serialize_all(ifp);
1594                 ifp->if_ioctl(ifp, cmd, data, cred);
1595                 ifnet_deserialize_all(ifp);
1596                 break;
1597
1598         case SIOCSIFNAME:
1599                 error = priv_check_cred(cred, PRIV_ROOT, 0);
1600                 if (error != 0)
1601                         return (error);
1602                 error = copyinstr(ifr->ifr_data, new_name, IFNAMSIZ, NULL);
1603                 if (error != 0)
1604                         return (error);
1605                 if (new_name[0] == '\0')
1606                         return (EINVAL);
1607                 if (ifunit(new_name) != NULL)
1608                         return (EEXIST);
1609
1610                 EVENTHANDLER_INVOKE(ifnet_detach_event, ifp);
1611
1612                 /* Announce the departure of the interface. */
1613                 rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
1614
1615                 strlcpy(ifp->if_xname, new_name, sizeof(ifp->if_xname));
1616                 ifa = TAILQ_FIRST(&ifp->if_addrheads[mycpuid])->ifa;
1617                 /* XXX IFA_LOCK(ifa); */
1618                 sdl = (struct sockaddr_dl *)ifa->ifa_addr;
1619                 namelen = strlen(new_name);
1620                 onamelen = sdl->sdl_nlen;
1621                 /*
1622                  * Move the address if needed.  This is safe because we
1623                  * allocate space for a name of length IFNAMSIZ when we
1624                  * create this in if_attach().
1625                  */
1626                 if (namelen != onamelen) {
1627                         bcopy(sdl->sdl_data + onamelen,
1628                             sdl->sdl_data + namelen, sdl->sdl_alen);
1629                 }
1630                 bcopy(new_name, sdl->sdl_data, namelen);
1631                 sdl->sdl_nlen = namelen;
1632                 sdl = (struct sockaddr_dl *)ifa->ifa_netmask;
1633                 bzero(sdl->sdl_data, onamelen);
1634                 while (namelen != 0)
1635                         sdl->sdl_data[--namelen] = 0xff;
1636                 /* XXX IFA_UNLOCK(ifa) */
1637
1638                 EVENTHANDLER_INVOKE(ifnet_attach_event, ifp);
1639
1640                 /* Announce the return of the interface. */
1641                 rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
1642                 break;
1643
1644         case SIOCSIFMETRIC:
1645                 error = priv_check_cred(cred, PRIV_ROOT, 0);
1646                 if (error)
1647                         return (error);
1648                 ifp->if_metric = ifr->ifr_metric;
1649                 getmicrotime(&ifp->if_lastchange);
1650                 break;
1651
1652         case SIOCSIFPHYS:
1653                 error = priv_check_cred(cred, PRIV_ROOT, 0);
1654                 if (error)
1655                         return error;
1656                 if (!ifp->if_ioctl)
1657                         return EOPNOTSUPP;
1658                 ifnet_serialize_all(ifp);
1659                 error = ifp->if_ioctl(ifp, cmd, data, cred);
1660                 ifnet_deserialize_all(ifp);
1661                 if (error == 0)
1662                         getmicrotime(&ifp->if_lastchange);
1663                 return (error);
1664
1665         case SIOCSIFMTU:
1666         {
1667                 u_long oldmtu = ifp->if_mtu;
1668
1669                 error = priv_check_cred(cred, PRIV_ROOT, 0);
1670                 if (error)
1671                         return (error);
1672                 if (ifp->if_ioctl == NULL)
1673                         return (EOPNOTSUPP);
1674                 if (ifr->ifr_mtu < IF_MINMTU || ifr->ifr_mtu > IF_MAXMTU)
1675                         return (EINVAL);
1676                 ifnet_serialize_all(ifp);
1677                 error = ifp->if_ioctl(ifp, cmd, data, cred);
1678                 ifnet_deserialize_all(ifp);
1679                 if (error == 0) {
1680                         getmicrotime(&ifp->if_lastchange);
1681                         rt_ifmsg(ifp);
1682                 }
1683                 /*
1684                  * If the link MTU changed, do network layer specific procedure.
1685                  */
1686                 if (ifp->if_mtu != oldmtu) {
1687 #ifdef INET6
1688                         nd6_setmtu(ifp);
1689 #endif
1690                 }
1691                 return (error);
1692         }
1693
1694         case SIOCADDMULTI:
1695         case SIOCDELMULTI:
1696                 error = priv_check_cred(cred, PRIV_ROOT, 0);
1697                 if (error)
1698                         return (error);
1699
1700                 /* Don't allow group membership on non-multicast interfaces. */
1701                 if ((ifp->if_flags & IFF_MULTICAST) == 0)
1702                         return EOPNOTSUPP;
1703
1704                 /* Don't let users screw up protocols' entries. */
1705                 if (ifr->ifr_addr.sa_family != AF_LINK)
1706                         return EINVAL;
1707
1708                 if (cmd == SIOCADDMULTI) {
1709                         struct ifmultiaddr *ifma;
1710                         error = if_addmulti(ifp, &ifr->ifr_addr, &ifma);
1711                 } else {
1712                         error = if_delmulti(ifp, &ifr->ifr_addr);
1713                 }
1714                 if (error == 0)
1715                         getmicrotime(&ifp->if_lastchange);
1716                 return error;
1717
1718         case SIOCSIFPHYADDR:
1719         case SIOCDIFPHYADDR:
1720 #ifdef INET6
1721         case SIOCSIFPHYADDR_IN6:
1722 #endif
1723         case SIOCSLIFPHYADDR:
1724         case SIOCSIFMEDIA:
1725         case SIOCSIFGENERIC:
1726                 error = priv_check_cred(cred, PRIV_ROOT, 0);
1727                 if (error)
1728                         return (error);
1729                 if (ifp->if_ioctl == 0)
1730                         return (EOPNOTSUPP);
1731                 ifnet_serialize_all(ifp);
1732                 error = ifp->if_ioctl(ifp, cmd, data, cred);
1733                 ifnet_deserialize_all(ifp);
1734                 if (error == 0)
1735                         getmicrotime(&ifp->if_lastchange);
1736                 return error;
1737
1738         case SIOCGIFSTATUS:
1739                 ifs = (struct ifstat *)data;
1740                 ifs->ascii[0] = '\0';
1741
1742         case SIOCGIFPSRCADDR:
1743         case SIOCGIFPDSTADDR:
1744         case SIOCGLIFPHYADDR:
1745         case SIOCGIFMEDIA:
1746         case SIOCGIFGENERIC:
1747                 if (ifp->if_ioctl == NULL)
1748                         return (EOPNOTSUPP);
1749                 ifnet_serialize_all(ifp);
1750                 error = ifp->if_ioctl(ifp, cmd, data, cred);
1751                 ifnet_deserialize_all(ifp);
1752                 return (error);
1753
1754         case SIOCSIFLLADDR:
1755                 error = priv_check_cred(cred, PRIV_ROOT, 0);
1756                 if (error)
1757                         return (error);
1758                 error = if_setlladdr(ifp,
1759                     ifr->ifr_addr.sa_data, ifr->ifr_addr.sa_len);
1760                 EVENTHANDLER_INVOKE(iflladdr_event, ifp);
1761                 return (error);
1762
1763         default:
1764                 oif_flags = ifp->if_flags;
1765                 if (so->so_proto == 0)
1766                         return (EOPNOTSUPP);
1767 #ifndef COMPAT_43
1768                 error = so_pru_control(so, cmd, data, ifp);
1769 #else
1770             {
1771                 int ocmd = cmd;
1772
1773                 switch (cmd) {
1774
1775                 case SIOCSIFDSTADDR:
1776                 case SIOCSIFADDR:
1777                 case SIOCSIFBRDADDR:
1778                 case SIOCSIFNETMASK:
1779 #if BYTE_ORDER != BIG_ENDIAN
1780                         if (ifr->ifr_addr.sa_family == 0 &&
1781                             ifr->ifr_addr.sa_len < 16) {
1782                                 ifr->ifr_addr.sa_family = ifr->ifr_addr.sa_len;
1783                                 ifr->ifr_addr.sa_len = 16;
1784                         }
1785 #else
1786                         if (ifr->ifr_addr.sa_len == 0)
1787                                 ifr->ifr_addr.sa_len = 16;
1788 #endif
1789                         break;
1790
1791                 case OSIOCGIFADDR:
1792                         cmd = SIOCGIFADDR;
1793                         break;
1794
1795                 case OSIOCGIFDSTADDR:
1796                         cmd = SIOCGIFDSTADDR;
1797                         break;
1798
1799                 case OSIOCGIFBRDADDR:
1800                         cmd = SIOCGIFBRDADDR;
1801                         break;
1802
1803                 case OSIOCGIFNETMASK:
1804                         cmd = SIOCGIFNETMASK;
1805                 }
1806                 error =  so_pru_control(so, cmd, data, ifp);
1807                 switch (ocmd) {
1808
1809                 case OSIOCGIFADDR:
1810                 case OSIOCGIFDSTADDR:
1811                 case OSIOCGIFBRDADDR:
1812                 case OSIOCGIFNETMASK:
1813                         *(u_short *)&ifr->ifr_addr = ifr->ifr_addr.sa_family;
1814
1815                 }
1816             }
1817 #endif /* COMPAT_43 */
1818
1819                 if ((oif_flags ^ ifp->if_flags) & IFF_UP) {
1820 #ifdef INET6
1821                         DELAY(100);/* XXX: temporary workaround for fxp issue*/
1822                         if (ifp->if_flags & IFF_UP) {
1823                                 crit_enter();
1824                                 in6_if_up(ifp);
1825                                 crit_exit();
1826                         }
1827 #endif
1828                 }
1829                 return (error);
1830
1831         }
1832         return (0);
1833 }
1834
1835 /*
1836  * Set/clear promiscuous mode on interface ifp based on the truth value
1837  * of pswitch.  The calls are reference counted so that only the first
1838  * "on" request actually has an effect, as does the final "off" request.
1839  * Results are undefined if the "off" and "on" requests are not matched.
1840  */
1841 int
1842 ifpromisc(struct ifnet *ifp, int pswitch)
1843 {
1844         struct ifreq ifr;
1845         int error;
1846         int oldflags;
1847
1848         oldflags = ifp->if_flags;
1849         if (ifp->if_flags & IFF_PPROMISC) {
1850                 /* Do nothing if device is in permanently promiscuous mode */
1851                 ifp->if_pcount += pswitch ? 1 : -1;
1852                 return (0);
1853         }
1854         if (pswitch) {
1855                 /*
1856                  * If the device is not configured up, we cannot put it in
1857                  * promiscuous mode.
1858                  */
1859                 if ((ifp->if_flags & IFF_UP) == 0)
1860                         return (ENETDOWN);
1861                 if (ifp->if_pcount++ != 0)
1862                         return (0);
1863                 ifp->if_flags |= IFF_PROMISC;
1864                 log(LOG_INFO, "%s: promiscuous mode enabled\n",
1865                     ifp->if_xname);
1866         } else {
1867                 if (--ifp->if_pcount > 0)
1868                         return (0);
1869                 ifp->if_flags &= ~IFF_PROMISC;
1870                 log(LOG_INFO, "%s: promiscuous mode disabled\n",
1871                     ifp->if_xname);
1872         }
1873         ifr.ifr_flags = ifp->if_flags;
1874         ifr.ifr_flagshigh = ifp->if_flags >> 16;
1875         ifnet_serialize_all(ifp);
1876         error = ifp->if_ioctl(ifp, SIOCSIFFLAGS, (caddr_t)&ifr, NULL);
1877         ifnet_deserialize_all(ifp);
1878         if (error == 0)
1879                 rt_ifmsg(ifp);
1880         else
1881                 ifp->if_flags = oldflags;
1882         return error;
1883 }
1884
1885 /*
1886  * Return interface configuration
1887  * of system.  List may be used
1888  * in later ioctl's (above) to get
1889  * other information.
1890  */
1891 static int
1892 ifconf(u_long cmd, caddr_t data, struct ucred *cred)
1893 {
1894         struct ifconf *ifc = (struct ifconf *)data;
1895         struct ifnet *ifp;
1896         struct sockaddr *sa;
1897         struct ifreq ifr, *ifrp;
1898         int space = ifc->ifc_len, error = 0;
1899
1900         ifrp = ifc->ifc_req;
1901         TAILQ_FOREACH(ifp, &ifnet, if_link) {
1902                 struct ifaddr_container *ifac;
1903                 int addrs;
1904
1905                 if (space <= sizeof ifr)
1906                         break;
1907
1908                 /*
1909                  * Zero the stack declared structure first to prevent
1910                  * memory disclosure.
1911                  */
1912                 bzero(&ifr, sizeof(ifr));
1913                 if (strlcpy(ifr.ifr_name, ifp->if_xname, sizeof(ifr.ifr_name))
1914                     >= sizeof(ifr.ifr_name)) {
1915                         error = ENAMETOOLONG;
1916                         break;
1917                 }
1918
1919                 addrs = 0;
1920                 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1921                         struct ifaddr *ifa = ifac->ifa;
1922
1923                         if (space <= sizeof ifr)
1924                                 break;
1925                         sa = ifa->ifa_addr;
1926                         if (cred->cr_prison &&
1927                             prison_if(cred, sa))
1928                                 continue;
1929                         addrs++;
1930 #ifdef COMPAT_43
1931                         if (cmd == OSIOCGIFCONF) {
1932                                 struct osockaddr *osa =
1933                                          (struct osockaddr *)&ifr.ifr_addr;
1934                                 ifr.ifr_addr = *sa;
1935                                 osa->sa_family = sa->sa_family;
1936                                 error = copyout(&ifr, ifrp, sizeof ifr);
1937                                 ifrp++;
1938                         } else
1939 #endif
1940                         if (sa->sa_len <= sizeof(*sa)) {
1941                                 ifr.ifr_addr = *sa;
1942                                 error = copyout(&ifr, ifrp, sizeof ifr);
1943                                 ifrp++;
1944                         } else {
1945                                 if (space < (sizeof ifr) + sa->sa_len -
1946                                             sizeof(*sa))
1947                                         break;
1948                                 space -= sa->sa_len - sizeof(*sa);
1949                                 error = copyout(&ifr, ifrp,
1950                                                 sizeof ifr.ifr_name);
1951                                 if (error == 0)
1952                                         error = copyout(sa, &ifrp->ifr_addr,
1953                                                         sa->sa_len);
1954                                 ifrp = (struct ifreq *)
1955                                         (sa->sa_len + (caddr_t)&ifrp->ifr_addr);
1956                         }
1957                         if (error)
1958                                 break;
1959                         space -= sizeof ifr;
1960                 }
1961                 if (error)
1962                         break;
1963                 if (!addrs) {
1964                         bzero(&ifr.ifr_addr, sizeof ifr.ifr_addr);
1965                         error = copyout(&ifr, ifrp, sizeof ifr);
1966                         if (error)
1967                                 break;
1968                         space -= sizeof ifr;
1969                         ifrp++;
1970                 }
1971         }
1972         ifc->ifc_len -= space;
1973         return (error);
1974 }
1975
1976 /*
1977  * Just like if_promisc(), but for all-multicast-reception mode.
1978  */
1979 int
1980 if_allmulti(struct ifnet *ifp, int onswitch)
1981 {
1982         int error = 0;
1983         struct ifreq ifr;
1984
1985         crit_enter();
1986
1987         if (onswitch) {
1988                 if (ifp->if_amcount++ == 0) {
1989                         ifp->if_flags |= IFF_ALLMULTI;
1990                         ifr.ifr_flags = ifp->if_flags;
1991                         ifr.ifr_flagshigh = ifp->if_flags >> 16;
1992                         ifnet_serialize_all(ifp);
1993                         error = ifp->if_ioctl(ifp, SIOCSIFFLAGS, (caddr_t)&ifr,
1994                                               NULL);
1995                         ifnet_deserialize_all(ifp);
1996                 }
1997         } else {
1998                 if (ifp->if_amcount > 1) {
1999                         ifp->if_amcount--;
2000                 } else {
2001                         ifp->if_amcount = 0;
2002                         ifp->if_flags &= ~IFF_ALLMULTI;
2003                         ifr.ifr_flags = ifp->if_flags;
2004                         ifr.ifr_flagshigh = ifp->if_flags >> 16;
2005                         ifnet_serialize_all(ifp);
2006                         error = ifp->if_ioctl(ifp, SIOCSIFFLAGS, (caddr_t)&ifr,
2007                                               NULL);
2008                         ifnet_deserialize_all(ifp);
2009                 }
2010         }
2011
2012         crit_exit();
2013
2014         if (error == 0)
2015                 rt_ifmsg(ifp);
2016         return error;
2017 }
2018
2019 /*
2020  * Add a multicast listenership to the interface in question.
2021  * The link layer provides a routine which converts
2022  */
2023 int
2024 if_addmulti(
2025         struct ifnet *ifp,      /* interface to manipulate */
2026         struct sockaddr *sa,    /* address to add */
2027         struct ifmultiaddr **retifma)
2028 {
2029         struct sockaddr *llsa, *dupsa;
2030         int error;
2031         struct ifmultiaddr *ifma;
2032
2033         /*
2034          * If the matching multicast address already exists
2035          * then don't add a new one, just add a reference
2036          */
2037         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2038                 if (sa_equal(sa, ifma->ifma_addr)) {
2039                         ifma->ifma_refcount++;
2040                         if (retifma)
2041                                 *retifma = ifma;
2042                         return 0;
2043                 }
2044         }
2045
2046         /*
2047          * Give the link layer a chance to accept/reject it, and also
2048          * find out which AF_LINK address this maps to, if it isn't one
2049          * already.
2050          */
2051         if (ifp->if_resolvemulti) {
2052                 ifnet_serialize_all(ifp);
2053                 error = ifp->if_resolvemulti(ifp, &llsa, sa);
2054                 ifnet_deserialize_all(ifp);
2055                 if (error) 
2056                         return error;
2057         } else {
2058                 llsa = 0;
2059         }
2060
2061         MALLOC(ifma, struct ifmultiaddr *, sizeof *ifma, M_IFMADDR, M_WAITOK);
2062         MALLOC(dupsa, struct sockaddr *, sa->sa_len, M_IFMADDR, M_WAITOK);
2063         bcopy(sa, dupsa, sa->sa_len);
2064
2065         ifma->ifma_addr = dupsa;
2066         ifma->ifma_lladdr = llsa;
2067         ifma->ifma_ifp = ifp;
2068         ifma->ifma_refcount = 1;
2069         ifma->ifma_protospec = 0;
2070         rt_newmaddrmsg(RTM_NEWMADDR, ifma);
2071
2072         /*
2073          * Some network interfaces can scan the address list at
2074          * interrupt time; lock them out.
2075          */
2076         crit_enter();
2077         TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ifma, ifma_link);
2078         crit_exit();
2079         if (retifma)
2080                 *retifma = ifma;
2081
2082         if (llsa != 0) {
2083                 TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2084                         if (sa_equal(ifma->ifma_addr, llsa))
2085                                 break;
2086                 }
2087                 if (ifma) {
2088                         ifma->ifma_refcount++;
2089                 } else {
2090                         MALLOC(ifma, struct ifmultiaddr *, sizeof *ifma,
2091                                M_IFMADDR, M_WAITOK);
2092                         MALLOC(dupsa, struct sockaddr *, llsa->sa_len,
2093                                M_IFMADDR, M_WAITOK);
2094                         bcopy(llsa, dupsa, llsa->sa_len);
2095                         ifma->ifma_addr = dupsa;
2096                         ifma->ifma_ifp = ifp;
2097                         ifma->ifma_refcount = 1;
2098                         crit_enter();
2099                         TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ifma, ifma_link);
2100                         crit_exit();
2101                 }
2102         }
2103         /*
2104          * We are certain we have added something, so call down to the
2105          * interface to let them know about it.
2106          */
2107         crit_enter();
2108         ifnet_serialize_all(ifp);
2109         if (ifp->if_ioctl)
2110                 ifp->if_ioctl(ifp, SIOCADDMULTI, 0, NULL);
2111         ifnet_deserialize_all(ifp);
2112         crit_exit();
2113
2114         return 0;
2115 }
2116
2117 /*
2118  * Remove a reference to a multicast address on this interface.  Yell
2119  * if the request does not match an existing membership.
2120  */
2121 int
2122 if_delmulti(struct ifnet *ifp, struct sockaddr *sa)
2123 {
2124         struct ifmultiaddr *ifma;
2125
2126         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link)
2127                 if (sa_equal(sa, ifma->ifma_addr))
2128                         break;
2129         if (ifma == 0)
2130                 return ENOENT;
2131
2132         if (ifma->ifma_refcount > 1) {
2133                 ifma->ifma_refcount--;
2134                 return 0;
2135         }
2136
2137         rt_newmaddrmsg(RTM_DELMADDR, ifma);
2138         sa = ifma->ifma_lladdr;
2139         crit_enter();
2140         TAILQ_REMOVE(&ifp->if_multiaddrs, ifma, ifma_link);
2141         /*
2142          * Make sure the interface driver is notified
2143          * in the case of a link layer mcast group being left.
2144          */
2145         if (ifma->ifma_addr->sa_family == AF_LINK && sa == 0) {
2146                 ifnet_serialize_all(ifp);
2147                 ifp->if_ioctl(ifp, SIOCDELMULTI, 0, NULL);
2148                 ifnet_deserialize_all(ifp);
2149         }
2150         crit_exit();
2151         kfree(ifma->ifma_addr, M_IFMADDR);
2152         kfree(ifma, M_IFMADDR);
2153         if (sa == 0)
2154                 return 0;
2155
2156         /*
2157          * Now look for the link-layer address which corresponds to
2158          * this network address.  It had been squirreled away in
2159          * ifma->ifma_lladdr for this purpose (so we don't have
2160          * to call ifp->if_resolvemulti() again), and we saved that
2161          * value in sa above.  If some nasty deleted the
2162          * link-layer address out from underneath us, we can deal because
2163          * the address we stored was is not the same as the one which was
2164          * in the record for the link-layer address.  (So we don't complain
2165          * in that case.)
2166          */
2167         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link)
2168                 if (sa_equal(sa, ifma->ifma_addr))
2169                         break;
2170         if (ifma == 0)
2171                 return 0;
2172
2173         if (ifma->ifma_refcount > 1) {
2174                 ifma->ifma_refcount--;
2175                 return 0;
2176         }
2177
2178         crit_enter();
2179         ifnet_serialize_all(ifp);
2180         TAILQ_REMOVE(&ifp->if_multiaddrs, ifma, ifma_link);
2181         ifp->if_ioctl(ifp, SIOCDELMULTI, 0, NULL);
2182         ifnet_deserialize_all(ifp);
2183         crit_exit();
2184         kfree(ifma->ifma_addr, M_IFMADDR);
2185         kfree(sa, M_IFMADDR);
2186         kfree(ifma, M_IFMADDR);
2187
2188         return 0;
2189 }
2190
2191 /*
2192  * Delete all multicast group membership for an interface.
2193  * Should be used to quickly flush all multicast filters.
2194  */
2195 void
2196 if_delallmulti(struct ifnet *ifp)
2197 {
2198         struct ifmultiaddr *ifma;
2199         struct ifmultiaddr *next;
2200
2201         TAILQ_FOREACH_MUTABLE(ifma, &ifp->if_multiaddrs, ifma_link, next)
2202                 if_delmulti(ifp, ifma->ifma_addr);
2203 }
2204
2205
2206 /*
2207  * Set the link layer address on an interface.
2208  *
2209  * At this time we only support certain types of interfaces,
2210  * and we don't allow the length of the address to change.
2211  */
2212 int
2213 if_setlladdr(struct ifnet *ifp, const u_char *lladdr, int len)
2214 {
2215         struct sockaddr_dl *sdl;
2216         struct ifreq ifr;
2217
2218         sdl = IF_LLSOCKADDR(ifp);
2219         if (sdl == NULL)
2220                 return (EINVAL);
2221         if (len != sdl->sdl_alen)       /* don't allow length to change */
2222                 return (EINVAL);
2223         switch (ifp->if_type) {
2224         case IFT_ETHER:                 /* these types use struct arpcom */
2225         case IFT_XETHER:
2226         case IFT_L2VLAN:
2227                 bcopy(lladdr, ((struct arpcom *)ifp->if_softc)->ac_enaddr, len);
2228                 bcopy(lladdr, LLADDR(sdl), len);
2229                 break;
2230         default:
2231                 return (ENODEV);
2232         }
2233         /*
2234          * If the interface is already up, we need
2235          * to re-init it in order to reprogram its
2236          * address filter.
2237          */
2238         ifnet_serialize_all(ifp);
2239         if ((ifp->if_flags & IFF_UP) != 0) {
2240                 struct ifaddr_container *ifac;
2241
2242                 ifp->if_flags &= ~IFF_UP;
2243                 ifr.ifr_flags = ifp->if_flags;
2244                 ifr.ifr_flagshigh = ifp->if_flags >> 16;
2245                 ifp->if_ioctl(ifp, SIOCSIFFLAGS, (caddr_t)&ifr,
2246                               NULL);
2247                 ifp->if_flags |= IFF_UP;
2248                 ifr.ifr_flags = ifp->if_flags;
2249                 ifr.ifr_flagshigh = ifp->if_flags >> 16;
2250                 ifp->if_ioctl(ifp, SIOCSIFFLAGS, (caddr_t)&ifr,
2251                                  NULL);
2252 #ifdef INET
2253                 /*
2254                  * Also send gratuitous ARPs to notify other nodes about
2255                  * the address change.
2256                  */
2257                 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
2258                         struct ifaddr *ifa = ifac->ifa;
2259
2260                         if (ifa->ifa_addr != NULL &&
2261                             ifa->ifa_addr->sa_family == AF_INET)
2262                                 arp_ifinit(ifp, ifa);
2263                 }
2264 #endif
2265         }
2266         ifnet_deserialize_all(ifp);
2267         return (0);
2268 }
2269
2270 struct ifmultiaddr *
2271 ifmaof_ifpforaddr(struct sockaddr *sa, struct ifnet *ifp)
2272 {
2273         struct ifmultiaddr *ifma;
2274
2275         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link)
2276                 if (sa_equal(ifma->ifma_addr, sa))
2277                         break;
2278
2279         return ifma;
2280 }
2281
2282 /*
2283  * This function locates the first real ethernet MAC from a network
2284  * card and loads it into node, returning 0 on success or ENOENT if
2285  * no suitable interfaces were found.  It is used by the uuid code to
2286  * generate a unique 6-byte number.
2287  */
2288 int
2289 if_getanyethermac(uint16_t *node, int minlen)
2290 {
2291         struct ifnet *ifp;
2292         struct sockaddr_dl *sdl;
2293
2294         TAILQ_FOREACH(ifp, &ifnet, if_link) {
2295                 if (ifp->if_type != IFT_ETHER)
2296                         continue;
2297                 sdl = IF_LLSOCKADDR(ifp);
2298                 if (sdl->sdl_alen < minlen)
2299                         continue;
2300                 bcopy(((struct arpcom *)ifp->if_softc)->ac_enaddr, node,
2301                       minlen);
2302                 return(0);
2303         }
2304         return (ENOENT);
2305 }
2306
2307 /*
2308  * The name argument must be a pointer to storage which will last as
2309  * long as the interface does.  For physical devices, the result of
2310  * device_get_name(dev) is a good choice and for pseudo-devices a
2311  * static string works well.
2312  */
2313 void
2314 if_initname(struct ifnet *ifp, const char *name, int unit)
2315 {
2316         ifp->if_dname = name;
2317         ifp->if_dunit = unit;
2318         if (unit != IF_DUNIT_NONE)
2319                 ksnprintf(ifp->if_xname, IFNAMSIZ, "%s%d", name, unit);
2320         else
2321                 strlcpy(ifp->if_xname, name, IFNAMSIZ);
2322 }
2323
2324 int
2325 if_printf(struct ifnet *ifp, const char *fmt, ...)
2326 {
2327         __va_list ap;
2328         int retval;
2329
2330         retval = kprintf("%s: ", ifp->if_xname);
2331         __va_start(ap, fmt);
2332         retval += kvprintf(fmt, ap);
2333         __va_end(ap);
2334         return (retval);
2335 }
2336
2337 struct ifnet *
2338 if_alloc(uint8_t type)
2339 {
2340         struct ifnet *ifp;
2341         size_t size;
2342
2343         /*
2344          * XXX temporary hack until arpcom is setup in if_l2com
2345          */
2346         if (type == IFT_ETHER)
2347                 size = sizeof(struct arpcom);
2348         else
2349                 size = sizeof(struct ifnet);
2350
2351         ifp = kmalloc(size, M_IFNET, M_WAITOK|M_ZERO);
2352
2353         ifp->if_type = type;
2354
2355         if (if_com_alloc[type] != NULL) {
2356                 ifp->if_l2com = if_com_alloc[type](type, ifp);
2357                 if (ifp->if_l2com == NULL) {
2358                         kfree(ifp, M_IFNET);
2359                         return (NULL);
2360                 }
2361         }
2362         return (ifp);
2363 }
2364
2365 void
2366 if_free(struct ifnet *ifp)
2367 {
2368         kfree(ifp, M_IFNET);
2369 }
2370
2371 void
2372 ifq_set_classic(struct ifaltq *ifq)
2373 {
2374         ifq->altq_enqueue = ifq_classic_enqueue;
2375         ifq->altq_dequeue = ifq_classic_dequeue;
2376         ifq->altq_request = ifq_classic_request;
2377 }
2378
2379 int
2380 ifq_classic_enqueue(struct ifaltq *ifq, struct mbuf *m,
2381                     struct altq_pktattr *pa __unused)
2382 {
2383         logifq(enqueue, ifq);
2384         if (IF_QFULL(ifq)) {
2385                 m_freem(m);
2386                 return(ENOBUFS);
2387         } else {
2388                 IF_ENQUEUE(ifq, m);
2389                 return(0);
2390         }       
2391 }
2392
2393 struct mbuf *
2394 ifq_classic_dequeue(struct ifaltq *ifq, struct mbuf *mpolled, int op)
2395 {
2396         struct mbuf *m;
2397
2398         switch (op) {
2399         case ALTDQ_POLL:
2400                 IF_POLL(ifq, m);
2401                 break;
2402         case ALTDQ_REMOVE:
2403                 logifq(dequeue, ifq);
2404                 IF_DEQUEUE(ifq, m);
2405                 break;
2406         default:
2407                 panic("unsupported ALTQ dequeue op: %d", op);
2408         }
2409         KKASSERT(mpolled == NULL || mpolled == m);
2410         return(m);
2411 }
2412
2413 int
2414 ifq_classic_request(struct ifaltq *ifq, int req, void *arg)
2415 {
2416         switch (req) {
2417         case ALTRQ_PURGE:
2418                 IF_DRAIN(ifq);
2419                 break;
2420         default:
2421                 panic("unsupported ALTQ request: %d", req);
2422         }
2423         return(0);
2424 }
2425
2426 int
2427 ifq_dispatch(struct ifnet *ifp, struct mbuf *m, struct altq_pktattr *pa)
2428 {
2429         struct ifaltq *ifq = &ifp->if_snd;
2430         int running = 0, error, start = 0;
2431
2432         ASSERT_IFNET_NOT_SERIALIZED_TX(ifp);
2433
2434         ALTQ_LOCK(ifq);
2435         error = ifq_enqueue_locked(ifq, m, pa);
2436         if (error) {
2437                 ALTQ_UNLOCK(ifq);
2438                 return error;
2439         }
2440         if (!ifq->altq_started) {
2441                 /*
2442                  * Hold the interlock of ifnet.if_start
2443                  */
2444                 ifq->altq_started = 1;
2445                 start = 1;
2446         }
2447         ALTQ_UNLOCK(ifq);
2448
2449         ifp->if_obytes += m->m_pkthdr.len;
2450         if (m->m_flags & M_MCAST)
2451                 ifp->if_omcasts++;
2452
2453         if (!start) {
2454                 logifstart(avoid, ifp);
2455                 return 0;
2456         }
2457
2458         if (ifq_dispatch_schedonly) {
2459                 /*
2460                  * Always schedule ifnet.if_start on ifnet's CPU,
2461                  * short circuit the rest of this function.
2462                  */
2463                 logifstart(sched, ifp);
2464                 if_start_schedule(ifp);
2465                 return 0;
2466         }
2467
2468         /*
2469          * Try to do direct ifnet.if_start first, if there is
2470          * contention on ifnet's serializer, ifnet.if_start will
2471          * be scheduled on ifnet's CPU.
2472          */
2473         if (!ifnet_tryserialize_tx(ifp)) {
2474                 /*
2475                  * ifnet serializer contention happened,
2476                  * ifnet.if_start is scheduled on ifnet's
2477                  * CPU, and we keep going.
2478                  */
2479                 logifstart(contend_sched, ifp);
2480                 if_start_schedule(ifp);
2481                 return 0;
2482         }
2483
2484         if ((ifp->if_flags & IFF_OACTIVE) == 0) {
2485                 logifstart(run, ifp);
2486                 ifp->if_start(ifp);
2487                 if ((ifp->if_flags &
2488                      (IFF_OACTIVE | IFF_RUNNING)) == IFF_RUNNING)
2489                         running = 1;
2490         }
2491
2492         ifnet_deserialize_tx(ifp);
2493
2494         if (ifq_dispatch_schednochk || if_start_need_schedule(ifq, running)) {
2495                 /*
2496                  * More data need to be transmitted, ifnet.if_start is
2497                  * scheduled on ifnet's CPU, and we keep going.
2498                  * NOTE: ifnet.if_start interlock is not released.
2499                  */
2500                 logifstart(sched, ifp);
2501                 if_start_schedule(ifp);
2502         }
2503         return 0;
2504 }
2505
2506 void *
2507 ifa_create(int size, int flags)
2508 {
2509         struct ifaddr *ifa;
2510         int i;
2511
2512         KASSERT(size >= sizeof(*ifa), ("ifaddr size too small\n"));
2513
2514         ifa = kmalloc(size, M_IFADDR, flags | M_ZERO);
2515         if (ifa == NULL)
2516                 return NULL;
2517
2518         ifa->ifa_containers = kmalloc(ncpus * sizeof(struct ifaddr_container),
2519                                       M_IFADDR, M_WAITOK | M_ZERO);
2520         ifa->ifa_ncnt = ncpus;
2521         for (i = 0; i < ncpus; ++i) {
2522                 struct ifaddr_container *ifac = &ifa->ifa_containers[i];
2523
2524                 ifac->ifa_magic = IFA_CONTAINER_MAGIC;
2525                 ifac->ifa = ifa;
2526                 ifac->ifa_refcnt = 1;
2527         }
2528 #ifdef IFADDR_DEBUG
2529         kprintf("alloc ifa %p %d\n", ifa, size);
2530 #endif
2531         return ifa;
2532 }
2533
2534 void
2535 ifac_free(struct ifaddr_container *ifac, int cpu_id)
2536 {
2537         struct ifaddr *ifa = ifac->ifa;
2538
2539         KKASSERT(ifac->ifa_magic == IFA_CONTAINER_MAGIC);
2540         KKASSERT(ifac->ifa_refcnt == 0);
2541         KASSERT(ifac->ifa_listmask == 0,
2542                 ("ifa is still on %#x lists\n", ifac->ifa_listmask));
2543
2544         ifac->ifa_magic = IFA_CONTAINER_DEAD;
2545
2546 #ifdef IFADDR_DEBUG_VERBOSE
2547         kprintf("try free ifa %p cpu_id %d\n", ifac->ifa, cpu_id);
2548 #endif
2549
2550         KASSERT(ifa->ifa_ncnt > 0 && ifa->ifa_ncnt <= ncpus,
2551                 ("invalid # of ifac, %d\n", ifa->ifa_ncnt));
2552         if (atomic_fetchadd_int(&ifa->ifa_ncnt, -1) == 1) {
2553 #ifdef IFADDR_DEBUG
2554                 kprintf("free ifa %p\n", ifa);
2555 #endif
2556                 kfree(ifa->ifa_containers, M_IFADDR);
2557                 kfree(ifa, M_IFADDR);
2558         }
2559 }
2560
2561 static void
2562 ifa_iflink_dispatch(struct netmsg *nmsg)
2563 {
2564         struct netmsg_ifaddr *msg = (struct netmsg_ifaddr *)nmsg;
2565         struct ifaddr *ifa = msg->ifa;
2566         struct ifnet *ifp = msg->ifp;
2567         int cpu = mycpuid;
2568         struct ifaddr_container *ifac;
2569
2570         crit_enter();
2571
2572         ifac = &ifa->ifa_containers[cpu];
2573         ASSERT_IFAC_VALID(ifac);
2574         KASSERT((ifac->ifa_listmask & IFA_LIST_IFADDRHEAD) == 0,
2575                 ("ifaddr is on if_addrheads\n"));
2576
2577         ifac->ifa_listmask |= IFA_LIST_IFADDRHEAD;
2578         if (msg->tail)
2579                 TAILQ_INSERT_TAIL(&ifp->if_addrheads[cpu], ifac, ifa_link);
2580         else
2581                 TAILQ_INSERT_HEAD(&ifp->if_addrheads[cpu], ifac, ifa_link);
2582
2583         crit_exit();
2584
2585         ifa_forwardmsg(&nmsg->nm_lmsg, cpu + 1);
2586 }
2587
2588 void
2589 ifa_iflink(struct ifaddr *ifa, struct ifnet *ifp, int tail)
2590 {
2591         struct netmsg_ifaddr msg;
2592
2593         netmsg_init(&msg.netmsg, NULL, &curthread->td_msgport,
2594                     0, ifa_iflink_dispatch);
2595         msg.ifa = ifa;
2596         msg.ifp = ifp;
2597         msg.tail = tail;
2598
2599         ifa_domsg(&msg.netmsg.nm_lmsg, 0);
2600 }
2601
2602 static void
2603 ifa_ifunlink_dispatch(struct netmsg *nmsg)
2604 {
2605         struct netmsg_ifaddr *msg = (struct netmsg_ifaddr *)nmsg;
2606         struct ifaddr *ifa = msg->ifa;
2607         struct ifnet *ifp = msg->ifp;
2608         int cpu = mycpuid;
2609         struct ifaddr_container *ifac;
2610
2611         crit_enter();
2612
2613         ifac = &ifa->ifa_containers[cpu];
2614         ASSERT_IFAC_VALID(ifac);
2615         KASSERT(ifac->ifa_listmask & IFA_LIST_IFADDRHEAD,
2616                 ("ifaddr is not on if_addrhead\n"));
2617
2618         TAILQ_REMOVE(&ifp->if_addrheads[cpu], ifac, ifa_link);
2619         ifac->ifa_listmask &= ~IFA_LIST_IFADDRHEAD;
2620
2621         crit_exit();
2622
2623         ifa_forwardmsg(&nmsg->nm_lmsg, cpu + 1);
2624 }
2625
2626 void
2627 ifa_ifunlink(struct ifaddr *ifa, struct ifnet *ifp)
2628 {
2629         struct netmsg_ifaddr msg;
2630
2631         netmsg_init(&msg.netmsg, NULL, &curthread->td_msgport,
2632                     0, ifa_ifunlink_dispatch);
2633         msg.ifa = ifa;
2634         msg.ifp = ifp;
2635
2636         ifa_domsg(&msg.netmsg.nm_lmsg, 0);
2637 }
2638
2639 static void
2640 ifa_destroy_dispatch(struct netmsg *nmsg)
2641 {
2642         struct netmsg_ifaddr *msg = (struct netmsg_ifaddr *)nmsg;
2643
2644         IFAFREE(msg->ifa);
2645         ifa_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
2646 }
2647
2648 void
2649 ifa_destroy(struct ifaddr *ifa)
2650 {
2651         struct netmsg_ifaddr msg;
2652
2653         netmsg_init(&msg.netmsg, NULL, &curthread->td_msgport,
2654                     0, ifa_destroy_dispatch);
2655         msg.ifa = ifa;
2656
2657         ifa_domsg(&msg.netmsg.nm_lmsg, 0);
2658 }
2659
2660 struct lwkt_port *
2661 ifnet_portfn(int cpu)
2662 {
2663         return &ifnet_threads[cpu].td_msgport;
2664 }
2665
2666 void
2667 ifnet_forwardmsg(struct lwkt_msg *lmsg, int next_cpu)
2668 {
2669         KKASSERT(next_cpu > mycpuid && next_cpu <= ncpus);
2670
2671         if (next_cpu < ncpus)
2672                 lwkt_forwardmsg(ifnet_portfn(next_cpu), lmsg);
2673         else
2674                 lwkt_replymsg(lmsg, 0);
2675 }
2676
2677 int
2678 ifnet_domsg(struct lwkt_msg *lmsg, int cpu)
2679 {
2680         KKASSERT(cpu < ncpus);
2681         return lwkt_domsg(ifnet_portfn(cpu), lmsg, 0);
2682 }
2683
2684 void
2685 ifnet_sendmsg(struct lwkt_msg *lmsg, int cpu)
2686 {
2687         KKASSERT(cpu < ncpus);
2688         lwkt_sendmsg(ifnet_portfn(cpu), lmsg);
2689 }
2690
2691 /*
2692  * Generic netmsg service loop.  Some protocols may roll their own but all
2693  * must do the basic command dispatch function call done here.
2694  */
2695 static void
2696 ifnet_service_loop(void *arg __unused)
2697 {
2698         struct netmsg *msg;
2699
2700         while ((msg = lwkt_waitport(&curthread->td_msgport, 0))) {
2701                 KASSERT(msg->nm_dispatch, ("ifnet_service: badmsg"));
2702                 msg->nm_dispatch(msg);
2703         }
2704 }
2705
2706 static void
2707 ifnetinit(void *dummy __unused)
2708 {
2709         int i;
2710
2711         for (i = 0; i < ncpus; ++i) {
2712                 struct thread *thr = &ifnet_threads[i];
2713
2714                 lwkt_create(ifnet_service_loop, NULL, NULL,
2715                             thr, TDF_STOPREQ, i, "ifnet %d", i);
2716                 netmsg_service_port_init(&thr->td_msgport);
2717                 lwkt_schedule(thr);
2718         }
2719 }
2720
2721 struct ifnet *
2722 ifnet_byindex(unsigned short idx)
2723 {
2724         if (idx > if_index)
2725                 return NULL;
2726         return ifindex2ifnet[idx];
2727 }
2728
2729 struct ifaddr *
2730 ifaddr_byindex(unsigned short idx)
2731 {
2732         struct ifnet *ifp;
2733
2734         ifp = ifnet_byindex(idx);
2735         if (!ifp)
2736                 return NULL;
2737         return TAILQ_FIRST(&ifp->if_addrheads[mycpuid])->ifa;
2738 }
2739
2740 void
2741 if_register_com_alloc(u_char type,
2742     if_com_alloc_t *a, if_com_free_t *f)
2743 {
2744
2745         KASSERT(if_com_alloc[type] == NULL,
2746             ("if_register_com_alloc: %d already registered", type));
2747         KASSERT(if_com_free[type] == NULL,
2748             ("if_register_com_alloc: %d free already registered", type));
2749
2750         if_com_alloc[type] = a;
2751         if_com_free[type] = f;
2752 }
2753
2754 void
2755 if_deregister_com_alloc(u_char type)
2756 {
2757
2758         KASSERT(if_com_alloc[type] != NULL,
2759             ("if_deregister_com_alloc: %d not registered", type));
2760         KASSERT(if_com_free[type] != NULL,
2761             ("if_deregister_com_alloc: %d free not registered", type));
2762         if_com_alloc[type] = NULL;
2763         if_com_free[type] = NULL;
2764 }