kernel: Use the system's offsetof() macro instead of cooking our own.
[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  */
36
37 #include "opt_compat.h"
38 #include "opt_inet6.h"
39 #include "opt_inet.h"
40 #include "opt_polling.h"
41 #include "opt_ifpoll.h"
42
43 #include <sys/param.h>
44 #include <sys/malloc.h>
45 #include <sys/mbuf.h>
46 #include <sys/systm.h>
47 #include <sys/proc.h>
48 #include <sys/priv.h>
49 #include <sys/protosw.h>
50 #include <sys/socket.h>
51 #include <sys/socketvar.h>
52 #include <sys/socketops.h>
53 #include <sys/protosw.h>
54 #include <sys/kernel.h>
55 #include <sys/ktr.h>
56 #include <sys/sockio.h>
57 #include <sys/syslog.h>
58 #include <sys/sysctl.h>
59 #include <sys/domain.h>
60 #include <sys/thread.h>
61 #include <sys/thread2.h>
62 #include <sys/serialize.h>
63 #include <sys/msgport2.h>
64 #include <sys/bus.h>
65
66 #include <net/if.h>
67 #include <net/if_arp.h>
68 #include <net/if_dl.h>
69 #include <net/if_types.h>
70 #include <net/if_var.h>
71 #include <net/ifq_var.h>
72 #include <net/radix.h>
73 #include <net/route.h>
74 #include <net/if_clone.h>
75 #include <net/netisr.h>
76 #include <net/netmsg2.h>
77
78 #include <machine/atomic.h>
79 #include <machine/stdarg.h>
80 #include <machine/smp.h>
81
82 #if defined(INET) || defined(INET6)
83 /*XXX*/
84 #include <netinet/in.h>
85 #include <netinet/in_var.h>
86 #include <netinet/if_ether.h>
87 #ifdef INET6
88 #include <netinet6/in6_var.h>
89 #include <netinet6/in6_ifattach.h>
90 #endif
91 #endif
92
93 #if defined(COMPAT_43)
94 #include <emulation/43bsd/43bsd_socket.h>
95 #endif /* COMPAT_43 */
96
97 struct netmsg_ifaddr {
98         struct netmsg_base base;
99         struct ifaddr   *ifa;
100         struct ifnet    *ifp;
101         int             tail;
102 };
103
104 /*
105  * System initialization
106  */
107 static void     if_attachdomain(void *);
108 static void     if_attachdomain1(struct ifnet *);
109 static int      ifconf(u_long, caddr_t, struct ucred *);
110 static void     ifinit(void *);
111 static void     ifnetinit(void *);
112 static void     if_slowtimo(void *);
113 static void     link_rtrequest(int, struct rtentry *, struct rt_addrinfo *);
114 static int      if_rtdel(struct radix_node *, void *);
115
116 #ifdef INET6
117 /*
118  * XXX: declare here to avoid to include many inet6 related files..
119  * should be more generalized?
120  */
121 extern void     nd6_setmtu(struct ifnet *);
122 #endif
123
124 SYSCTL_NODE(_net, PF_LINK, link, CTLFLAG_RW, 0, "Link layers");
125 SYSCTL_NODE(_net_link, 0, generic, CTLFLAG_RW, 0, "Generic link-management");
126
127 SYSINIT(interfaces, SI_SUB_PROTO_IF, SI_ORDER_FIRST, ifinit, NULL)
128 /* Must be after netisr_init */
129 SYSINIT(ifnet, SI_SUB_PRE_DRIVERS, SI_ORDER_SECOND, ifnetinit, NULL)
130
131 static  if_com_alloc_t *if_com_alloc[256];
132 static  if_com_free_t *if_com_free[256];
133
134 MALLOC_DEFINE(M_IFADDR, "ifaddr", "interface address");
135 MALLOC_DEFINE(M_IFMADDR, "ether_multi", "link-level multicast address");
136 MALLOC_DEFINE(M_IFNET, "ifnet", "interface structure");
137
138 int                     ifqmaxlen = IFQ_MAXLEN;
139 struct ifnethead        ifnet = TAILQ_HEAD_INITIALIZER(ifnet);
140
141 /* In ifq_dispatch(), try to do direct ifnet.if_start first */
142 static int              ifq_dispatch_schedonly = 0;
143 SYSCTL_INT(_net_link_generic, OID_AUTO, ifq_dispatch_schedonly, CTLFLAG_RW,
144            &ifq_dispatch_schedonly, 0, "");
145
146 /* In ifq_dispatch(), schedule ifnet.if_start without checking ifnet.if_snd */
147 static int              ifq_dispatch_schednochk = 0;
148 SYSCTL_INT(_net_link_generic, OID_AUTO, ifq_dispatch_schednochk, CTLFLAG_RW,
149            &ifq_dispatch_schednochk, 0, "");
150
151 /* In if_devstart(), try to do direct ifnet.if_start first */
152 static int              if_devstart_schedonly = 0;
153 SYSCTL_INT(_net_link_generic, OID_AUTO, if_devstart_schedonly, CTLFLAG_RW,
154            &if_devstart_schedonly, 0, "");
155
156 /* In if_devstart(), schedule ifnet.if_start without checking ifnet.if_snd */
157 static int              if_devstart_schednochk = 0;
158 SYSCTL_INT(_net_link_generic, OID_AUTO, if_devstart_schednochk, CTLFLAG_RW,
159            &if_devstart_schednochk, 0, "");
160
161 #ifdef SMP
162 /* Schedule ifnet.if_start on the current CPU */
163 static int              if_start_oncpu_sched = 0;
164 SYSCTL_INT(_net_link_generic, OID_AUTO, if_start_oncpu_sched, CTLFLAG_RW,
165            &if_start_oncpu_sched, 0, "");
166 #endif
167
168 struct callout          if_slowtimo_timer;
169
170 int                     if_index = 0;
171 struct ifnet            **ifindex2ifnet = NULL;
172 static struct thread    ifnet_threads[MAXCPU];
173
174 #define IFQ_KTR_STRING          "ifq=%p"
175 #define IFQ_KTR_ARG_SIZE        (sizeof(void *))
176 #ifndef KTR_IFQ
177 #define KTR_IFQ                 KTR_ALL
178 #endif
179 KTR_INFO_MASTER(ifq);
180 KTR_INFO(KTR_IFQ, ifq, enqueue, 0, IFQ_KTR_STRING, IFQ_KTR_ARG_SIZE);
181 KTR_INFO(KTR_IFQ, ifq, dequeue, 1, IFQ_KTR_STRING, IFQ_KTR_ARG_SIZE);
182 #define logifq(name, arg)       KTR_LOG(ifq_ ## name, arg)
183
184 #define IF_START_KTR_STRING     "ifp=%p"
185 #define IF_START_KTR_ARG_SIZE   (sizeof(void *))
186 #ifndef KTR_IF_START
187 #define KTR_IF_START            KTR_ALL
188 #endif
189 KTR_INFO_MASTER(if_start);
190 KTR_INFO(KTR_IF_START, if_start, run, 0,
191          IF_START_KTR_STRING, IF_START_KTR_ARG_SIZE);
192 KTR_INFO(KTR_IF_START, if_start, sched, 1,
193          IF_START_KTR_STRING, IF_START_KTR_ARG_SIZE);
194 KTR_INFO(KTR_IF_START, if_start, avoid, 2,
195          IF_START_KTR_STRING, IF_START_KTR_ARG_SIZE);
196 KTR_INFO(KTR_IF_START, if_start, contend_sched, 3,
197          IF_START_KTR_STRING, IF_START_KTR_ARG_SIZE);
198 #ifdef SMP
199 KTR_INFO(KTR_IF_START, if_start, chase_sched, 4,
200          IF_START_KTR_STRING, IF_START_KTR_ARG_SIZE);
201 #endif
202 #define logifstart(name, arg)   KTR_LOG(if_start_ ## name, arg)
203
204 TAILQ_HEAD(, ifg_group) ifg_head = TAILQ_HEAD_INITIALIZER(ifg_head);
205
206 /*
207  * Network interface utility routines.
208  *
209  * Routines with ifa_ifwith* names take sockaddr *'s as
210  * parameters.
211  */
212 /* ARGSUSED*/
213 void
214 ifinit(void *dummy)
215 {
216         struct ifnet *ifp;
217
218         callout_init(&if_slowtimo_timer);
219
220         crit_enter();
221         TAILQ_FOREACH(ifp, &ifnet, if_link) {
222                 if (ifp->if_snd.ifq_maxlen == 0) {
223                         if_printf(ifp, "XXX: driver didn't set ifq_maxlen\n");
224                         ifp->if_snd.ifq_maxlen = ifqmaxlen;
225                 }
226         }
227         crit_exit();
228
229         if_slowtimo(0);
230 }
231
232 static int
233 if_start_cpuid(struct ifnet *ifp)
234 {
235         return ifp->if_cpuid;
236 }
237
238 #ifdef DEVICE_POLLING
239 static int
240 if_start_cpuid_poll(struct ifnet *ifp)
241 {
242         int poll_cpuid = ifp->if_poll_cpuid;
243
244         if (poll_cpuid >= 0)
245                 return poll_cpuid;
246         else
247                 return ifp->if_cpuid;
248 }
249 #endif
250
251 static void
252 if_start_ipifunc(void *arg)
253 {
254         struct ifnet *ifp = arg;
255         struct lwkt_msg *lmsg = &ifp->if_start_nmsg[mycpuid].lmsg;
256
257         crit_enter();
258         if (lmsg->ms_flags & MSGF_DONE)
259                 lwkt_sendmsg(ifnet_portfn(mycpuid), lmsg);
260         crit_exit();
261 }
262
263 /*
264  * Schedule ifnet.if_start on ifnet's CPU
265  */
266 static void
267 if_start_schedule(struct ifnet *ifp)
268 {
269 #ifdef SMP
270         int cpu;
271
272         if (if_start_oncpu_sched)
273                 cpu = mycpuid;
274         else
275                 cpu = ifp->if_start_cpuid(ifp);
276
277         if (cpu != mycpuid)
278                 lwkt_send_ipiq(globaldata_find(cpu), if_start_ipifunc, ifp);
279         else
280 #endif
281         if_start_ipifunc(ifp);
282 }
283
284 /*
285  * NOTE:
286  * This function will release ifnet.if_start interlock,
287  * if ifnet.if_start does not need to be scheduled
288  */
289 static __inline int
290 if_start_need_schedule(struct ifaltq *ifq, int running)
291 {
292         if (!running || ifq_is_empty(ifq)
293 #ifdef ALTQ
294             || ifq->altq_tbr != NULL
295 #endif
296         ) {
297                 ALTQ_LOCK(ifq);
298                 /*
299                  * ifnet.if_start interlock is released, if:
300                  * 1) Hardware can not take any packets, due to
301                  *    o  interface is marked down
302                  *    o  hardware queue is full (IFF_OACTIVE)
303                  *    Under the second situation, hardware interrupt
304                  *    or polling(4) will call/schedule ifnet.if_start
305                  *    when hardware queue is ready
306                  * 2) There is not packet in the ifnet.if_snd.
307                  *    Further ifq_dispatch or ifq_handoff will call/
308                  *    schedule ifnet.if_start
309                  * 3) TBR is used and it does not allow further
310                  *    dequeueing.
311                  *    TBR callout will call ifnet.if_start
312                  */
313                 if (!running || !ifq_data_ready(ifq)) {
314                         ifq->altq_started = 0;
315                         ALTQ_UNLOCK(ifq);
316                         return 0;
317                 }
318                 ALTQ_UNLOCK(ifq);
319         }
320         return 1;
321 }
322
323 static void
324 if_start_dispatch(netmsg_t msg)
325 {
326         struct lwkt_msg *lmsg = &msg->base.lmsg;
327         struct ifnet *ifp = lmsg->u.ms_resultp;
328         struct ifaltq *ifq = &ifp->if_snd;
329         int running = 0;
330
331         crit_enter();
332         lwkt_replymsg(lmsg, 0); /* reply ASAP */
333         crit_exit();
334
335 #ifdef SMP
336         if (!if_start_oncpu_sched && mycpuid != ifp->if_start_cpuid(ifp)) {
337                 /*
338                  * If the ifnet is still up, we need to
339                  * chase its CPU change.
340                  */
341                 if (ifp->if_flags & IFF_UP) {
342                         logifstart(chase_sched, ifp);
343                         if_start_schedule(ifp);
344                         return;
345                 } else {
346                         goto check;
347                 }
348         }
349 #endif
350
351         if (ifp->if_flags & IFF_UP) {
352                 ifnet_serialize_tx(ifp); /* XXX try? */
353                 if ((ifp->if_flags & IFF_OACTIVE) == 0) {
354                         logifstart(run, ifp);
355                         ifp->if_start(ifp);
356                         if ((ifp->if_flags &
357                         (IFF_OACTIVE | IFF_RUNNING)) == IFF_RUNNING)
358                                 running = 1;
359                 }
360                 ifnet_deserialize_tx(ifp);
361         }
362 #ifdef SMP
363 check:
364 #endif
365         if (if_start_need_schedule(ifq, running)) {
366                 crit_enter();
367                 if (lmsg->ms_flags & MSGF_DONE) { /* XXX necessary? */
368                         logifstart(sched, ifp);
369                         lwkt_sendmsg(ifnet_portfn(mycpuid), lmsg);
370                 }
371                 crit_exit();
372         }
373 }
374
375 /* Device driver ifnet.if_start helper function */
376 void
377 if_devstart(struct ifnet *ifp)
378 {
379         struct ifaltq *ifq = &ifp->if_snd;
380         int running = 0;
381
382         ASSERT_IFNET_SERIALIZED_TX(ifp);
383
384         ALTQ_LOCK(ifq);
385         if (ifq->altq_started || !ifq_data_ready(ifq)) {
386                 logifstart(avoid, ifp);
387                 ALTQ_UNLOCK(ifq);
388                 return;
389         }
390         ifq->altq_started = 1;
391         ALTQ_UNLOCK(ifq);
392
393         if (if_devstart_schedonly) {
394                 /*
395                  * Always schedule ifnet.if_start on ifnet's CPU,
396                  * short circuit the rest of this function.
397                  */
398                 logifstart(sched, ifp);
399                 if_start_schedule(ifp);
400                 return;
401         }
402
403         logifstart(run, ifp);
404         ifp->if_start(ifp);
405
406         if ((ifp->if_flags & (IFF_OACTIVE | IFF_RUNNING)) == IFF_RUNNING)
407                 running = 1;
408
409         if (if_devstart_schednochk || if_start_need_schedule(ifq, running)) {
410                 /*
411                  * More data need to be transmitted, ifnet.if_start is
412                  * scheduled on ifnet's CPU, and we keep going.
413                  * NOTE: ifnet.if_start interlock is not released.
414                  */
415                 logifstart(sched, ifp);
416                 if_start_schedule(ifp);
417         }
418 }
419
420 static void
421 if_default_serialize(struct ifnet *ifp, enum ifnet_serialize slz __unused)
422 {
423         lwkt_serialize_enter(ifp->if_serializer);
424 }
425
426 static void
427 if_default_deserialize(struct ifnet *ifp, enum ifnet_serialize slz __unused)
428 {
429         lwkt_serialize_exit(ifp->if_serializer);
430 }
431
432 static int
433 if_default_tryserialize(struct ifnet *ifp, enum ifnet_serialize slz __unused)
434 {
435         return lwkt_serialize_try(ifp->if_serializer);
436 }
437
438 #ifdef INVARIANTS
439 static void
440 if_default_serialize_assert(struct ifnet *ifp,
441                             enum ifnet_serialize slz __unused,
442                             boolean_t serialized)
443 {
444         if (serialized)
445                 ASSERT_SERIALIZED(ifp->if_serializer);
446         else
447                 ASSERT_NOT_SERIALIZED(ifp->if_serializer);
448 }
449 #endif
450
451 /*
452  * Attach an interface to the list of "active" interfaces.
453  *
454  * The serializer is optional.  If non-NULL access to the interface
455  * may be MPSAFE.
456  */
457 void
458 if_attach(struct ifnet *ifp, lwkt_serialize_t serializer)
459 {
460         unsigned socksize, ifasize;
461         int namelen, masklen;
462         struct sockaddr_dl *sdl;
463         struct ifaddr *ifa;
464         struct ifaltq *ifq;
465         int i;
466
467         static int if_indexlim = 8;
468
469         if (ifp->if_serialize != NULL) {
470                 KASSERT(ifp->if_deserialize != NULL &&
471                         ifp->if_tryserialize != NULL &&
472                         ifp->if_serialize_assert != NULL,
473                         ("serialize functions are partially setup\n"));
474
475                 /*
476                  * If the device supplies serialize functions,
477                  * then clear if_serializer to catch any invalid
478                  * usage of this field.
479                  */
480                 KASSERT(serializer == NULL,
481                         ("both serialize functions and default serializer "
482                          "are supplied\n"));
483                 ifp->if_serializer = NULL;
484         } else {
485                 KASSERT(ifp->if_deserialize == NULL &&
486                         ifp->if_tryserialize == NULL &&
487                         ifp->if_serialize_assert == NULL,
488                         ("serialize functions are partially setup\n"));
489                 ifp->if_serialize = if_default_serialize;
490                 ifp->if_deserialize = if_default_deserialize;
491                 ifp->if_tryserialize = if_default_tryserialize;
492 #ifdef INVARIANTS
493                 ifp->if_serialize_assert = if_default_serialize_assert;
494 #endif
495
496                 /*
497                  * The serializer can be passed in from the device,
498                  * allowing the same serializer to be used for both
499                  * the interrupt interlock and the device queue.
500                  * If not specified, the netif structure will use an
501                  * embedded serializer.
502                  */
503                 if (serializer == NULL) {
504                         serializer = &ifp->if_default_serializer;
505                         lwkt_serialize_init(serializer);
506                 }
507                 ifp->if_serializer = serializer;
508         }
509
510         ifp->if_start_cpuid = if_start_cpuid;
511         ifp->if_cpuid = 0;
512
513 #ifdef DEVICE_POLLING
514         /* Device is not in polling mode by default */
515         ifp->if_poll_cpuid = -1;
516         if (ifp->if_poll != NULL)
517                 ifp->if_start_cpuid = if_start_cpuid_poll;
518 #endif
519
520         ifp->if_start_nmsg = kmalloc(ncpus * sizeof(*ifp->if_start_nmsg),
521                                      M_LWKTMSG, M_WAITOK);
522         for (i = 0; i < ncpus; ++i) {
523                 netmsg_init(&ifp->if_start_nmsg[i], NULL, &netisr_adone_rport,
524                             0, if_start_dispatch);
525                 ifp->if_start_nmsg[i].lmsg.u.ms_resultp = ifp;
526         }
527
528         TAILQ_INSERT_TAIL(&ifnet, ifp, if_link);
529         ifp->if_index = ++if_index;
530
531         /*
532          * XXX -
533          * The old code would work if the interface passed a pre-existing
534          * chain of ifaddrs to this code.  We don't trust our callers to
535          * properly initialize the tailq, however, so we no longer allow
536          * this unlikely case.
537          */
538         ifp->if_addrheads = kmalloc(ncpus * sizeof(struct ifaddrhead),
539                                     M_IFADDR, M_WAITOK | M_ZERO);
540         for (i = 0; i < ncpus; ++i)
541                 TAILQ_INIT(&ifp->if_addrheads[i]);
542
543         TAILQ_INIT(&ifp->if_prefixhead);
544         TAILQ_INIT(&ifp->if_multiaddrs);
545         TAILQ_INIT(&ifp->if_groups);
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         masklen = offsetof(struct sockaddr_dl, sdl_data[0]) + namelen;
570         socksize = masklen + ifp->if_addrlen;
571 #define ROUNDUP(a) (1 + (((a) - 1) | (sizeof(long) - 1)))
572         if (socksize < sizeof(*sdl))
573                 socksize = sizeof(*sdl);
574         socksize = ROUNDUP(socksize);
575 #undef ROUNDUP
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_direct(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
1807                 error = so_pru_control_direct(so, cmd, data, ifp);
1808
1809                 switch (ocmd) {
1810                 case OSIOCGIFADDR:
1811                 case OSIOCGIFDSTADDR:
1812                 case OSIOCGIFBRDADDR:
1813                 case OSIOCGIFNETMASK:
1814                         *(u_short *)&ifr->ifr_addr = ifr->ifr_addr.sa_family;
1815                         break;
1816                 }
1817             }
1818 #endif /* COMPAT_43 */
1819
1820                 if ((oif_flags ^ ifp->if_flags) & IFF_UP) {
1821 #ifdef INET6
1822                         DELAY(100);/* XXX: temporary workaround for fxp issue*/
1823                         if (ifp->if_flags & IFF_UP) {
1824                                 crit_enter();
1825                                 in6_if_up(ifp);
1826                                 crit_exit();
1827                         }
1828 #endif
1829                 }
1830                 return (error);
1831
1832         }
1833         return (0);
1834 }
1835
1836 /*
1837  * Set/clear promiscuous mode on interface ifp based on the truth value
1838  * of pswitch.  The calls are reference counted so that only the first
1839  * "on" request actually has an effect, as does the final "off" request.
1840  * Results are undefined if the "off" and "on" requests are not matched.
1841  */
1842 int
1843 ifpromisc(struct ifnet *ifp, int pswitch)
1844 {
1845         struct ifreq ifr;
1846         int error;
1847         int oldflags;
1848
1849         oldflags = ifp->if_flags;
1850         if (ifp->if_flags & IFF_PPROMISC) {
1851                 /* Do nothing if device is in permanently promiscuous mode */
1852                 ifp->if_pcount += pswitch ? 1 : -1;
1853                 return (0);
1854         }
1855         if (pswitch) {
1856                 /*
1857                  * If the device is not configured up, we cannot put it in
1858                  * promiscuous mode.
1859                  */
1860                 if ((ifp->if_flags & IFF_UP) == 0)
1861                         return (ENETDOWN);
1862                 if (ifp->if_pcount++ != 0)
1863                         return (0);
1864                 ifp->if_flags |= IFF_PROMISC;
1865                 log(LOG_INFO, "%s: promiscuous mode enabled\n",
1866                     ifp->if_xname);
1867         } else {
1868                 if (--ifp->if_pcount > 0)
1869                         return (0);
1870                 ifp->if_flags &= ~IFF_PROMISC;
1871                 log(LOG_INFO, "%s: promiscuous mode disabled\n",
1872                     ifp->if_xname);
1873         }
1874         ifr.ifr_flags = ifp->if_flags;
1875         ifr.ifr_flagshigh = ifp->if_flags >> 16;
1876         ifnet_serialize_all(ifp);
1877         error = ifp->if_ioctl(ifp, SIOCSIFFLAGS, (caddr_t)&ifr, NULL);
1878         ifnet_deserialize_all(ifp);
1879         if (error == 0)
1880                 rt_ifmsg(ifp);
1881         else
1882                 ifp->if_flags = oldflags;
1883         return error;
1884 }
1885
1886 /*
1887  * Return interface configuration
1888  * of system.  List may be used
1889  * in later ioctl's (above) to get
1890  * other information.
1891  */
1892 static int
1893 ifconf(u_long cmd, caddr_t data, struct ucred *cred)
1894 {
1895         struct ifconf *ifc = (struct ifconf *)data;
1896         struct ifnet *ifp;
1897         struct sockaddr *sa;
1898         struct ifreq ifr, *ifrp;
1899         int space = ifc->ifc_len, error = 0;
1900
1901         ifrp = ifc->ifc_req;
1902         TAILQ_FOREACH(ifp, &ifnet, if_link) {
1903                 struct ifaddr_container *ifac;
1904                 int addrs;
1905
1906                 if (space <= sizeof ifr)
1907                         break;
1908
1909                 /*
1910                  * Zero the stack declared structure first to prevent
1911                  * memory disclosure.
1912                  */
1913                 bzero(&ifr, sizeof(ifr));
1914                 if (strlcpy(ifr.ifr_name, ifp->if_xname, sizeof(ifr.ifr_name))
1915                     >= sizeof(ifr.ifr_name)) {
1916                         error = ENAMETOOLONG;
1917                         break;
1918                 }
1919
1920                 addrs = 0;
1921                 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1922                         struct ifaddr *ifa = ifac->ifa;
1923
1924                         if (space <= sizeof ifr)
1925                                 break;
1926                         sa = ifa->ifa_addr;
1927                         if (cred->cr_prison &&
1928                             prison_if(cred, sa))
1929                                 continue;
1930                         addrs++;
1931 #ifdef COMPAT_43
1932                         if (cmd == OSIOCGIFCONF) {
1933                                 struct osockaddr *osa =
1934                                          (struct osockaddr *)&ifr.ifr_addr;
1935                                 ifr.ifr_addr = *sa;
1936                                 osa->sa_family = sa->sa_family;
1937                                 error = copyout(&ifr, ifrp, sizeof ifr);
1938                                 ifrp++;
1939                         } else
1940 #endif
1941                         if (sa->sa_len <= sizeof(*sa)) {
1942                                 ifr.ifr_addr = *sa;
1943                                 error = copyout(&ifr, ifrp, sizeof ifr);
1944                                 ifrp++;
1945                         } else {
1946                                 if (space < (sizeof ifr) + sa->sa_len -
1947                                             sizeof(*sa))
1948                                         break;
1949                                 space -= sa->sa_len - sizeof(*sa);
1950                                 error = copyout(&ifr, ifrp,
1951                                                 sizeof ifr.ifr_name);
1952                                 if (error == 0)
1953                                         error = copyout(sa, &ifrp->ifr_addr,
1954                                                         sa->sa_len);
1955                                 ifrp = (struct ifreq *)
1956                                         (sa->sa_len + (caddr_t)&ifrp->ifr_addr);
1957                         }
1958                         if (error)
1959                                 break;
1960                         space -= sizeof ifr;
1961                 }
1962                 if (error)
1963                         break;
1964                 if (!addrs) {
1965                         bzero(&ifr.ifr_addr, sizeof ifr.ifr_addr);
1966                         error = copyout(&ifr, ifrp, sizeof ifr);
1967                         if (error)
1968                                 break;
1969                         space -= sizeof ifr;
1970                         ifrp++;
1971                 }
1972         }
1973         ifc->ifc_len -= space;
1974         return (error);
1975 }
1976
1977 /*
1978  * Just like if_promisc(), but for all-multicast-reception mode.
1979  */
1980 int
1981 if_allmulti(struct ifnet *ifp, int onswitch)
1982 {
1983         int error = 0;
1984         struct ifreq ifr;
1985
1986         crit_enter();
1987
1988         if (onswitch) {
1989                 if (ifp->if_amcount++ == 0) {
1990                         ifp->if_flags |= IFF_ALLMULTI;
1991                         ifr.ifr_flags = ifp->if_flags;
1992                         ifr.ifr_flagshigh = ifp->if_flags >> 16;
1993                         ifnet_serialize_all(ifp);
1994                         error = ifp->if_ioctl(ifp, SIOCSIFFLAGS, (caddr_t)&ifr,
1995                                               NULL);
1996                         ifnet_deserialize_all(ifp);
1997                 }
1998         } else {
1999                 if (ifp->if_amcount > 1) {
2000                         ifp->if_amcount--;
2001                 } else {
2002                         ifp->if_amcount = 0;
2003                         ifp->if_flags &= ~IFF_ALLMULTI;
2004                         ifr.ifr_flags = ifp->if_flags;
2005                         ifr.ifr_flagshigh = ifp->if_flags >> 16;
2006                         ifnet_serialize_all(ifp);
2007                         error = ifp->if_ioctl(ifp, SIOCSIFFLAGS, (caddr_t)&ifr,
2008                                               NULL);
2009                         ifnet_deserialize_all(ifp);
2010                 }
2011         }
2012
2013         crit_exit();
2014
2015         if (error == 0)
2016                 rt_ifmsg(ifp);
2017         return error;
2018 }
2019
2020 /*
2021  * Add a multicast listenership to the interface in question.
2022  * The link layer provides a routine which converts
2023  */
2024 int
2025 if_addmulti(
2026         struct ifnet *ifp,      /* interface to manipulate */
2027         struct sockaddr *sa,    /* address to add */
2028         struct ifmultiaddr **retifma)
2029 {
2030         struct sockaddr *llsa, *dupsa;
2031         int error;
2032         struct ifmultiaddr *ifma;
2033
2034         /*
2035          * If the matching multicast address already exists
2036          * then don't add a new one, just add a reference
2037          */
2038         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2039                 if (sa_equal(sa, ifma->ifma_addr)) {
2040                         ifma->ifma_refcount++;
2041                         if (retifma)
2042                                 *retifma = ifma;
2043                         return 0;
2044                 }
2045         }
2046
2047         /*
2048          * Give the link layer a chance to accept/reject it, and also
2049          * find out which AF_LINK address this maps to, if it isn't one
2050          * already.
2051          */
2052         if (ifp->if_resolvemulti) {
2053                 ifnet_serialize_all(ifp);
2054                 error = ifp->if_resolvemulti(ifp, &llsa, sa);
2055                 ifnet_deserialize_all(ifp);
2056                 if (error) 
2057                         return error;
2058         } else {
2059                 llsa = 0;
2060         }
2061
2062         MALLOC(ifma, struct ifmultiaddr *, sizeof *ifma, M_IFMADDR, M_WAITOK);
2063         MALLOC(dupsa, struct sockaddr *, sa->sa_len, M_IFMADDR, M_WAITOK);
2064         bcopy(sa, dupsa, sa->sa_len);
2065
2066         ifma->ifma_addr = dupsa;
2067         ifma->ifma_lladdr = llsa;
2068         ifma->ifma_ifp = ifp;
2069         ifma->ifma_refcount = 1;
2070         ifma->ifma_protospec = 0;
2071         rt_newmaddrmsg(RTM_NEWMADDR, ifma);
2072
2073         /*
2074          * Some network interfaces can scan the address list at
2075          * interrupt time; lock them out.
2076          */
2077         crit_enter();
2078         TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ifma, ifma_link);
2079         crit_exit();
2080         if (retifma)
2081                 *retifma = ifma;
2082
2083         if (llsa != 0) {
2084                 TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2085                         if (sa_equal(ifma->ifma_addr, llsa))
2086                                 break;
2087                 }
2088                 if (ifma) {
2089                         ifma->ifma_refcount++;
2090                 } else {
2091                         MALLOC(ifma, struct ifmultiaddr *, sizeof *ifma,
2092                                M_IFMADDR, M_WAITOK);
2093                         MALLOC(dupsa, struct sockaddr *, llsa->sa_len,
2094                                M_IFMADDR, M_WAITOK);
2095                         bcopy(llsa, dupsa, llsa->sa_len);
2096                         ifma->ifma_addr = dupsa;
2097                         ifma->ifma_ifp = ifp;
2098                         ifma->ifma_refcount = 1;
2099                         crit_enter();
2100                         TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ifma, ifma_link);
2101                         crit_exit();
2102                 }
2103         }
2104         /*
2105          * We are certain we have added something, so call down to the
2106          * interface to let them know about it.
2107          */
2108         crit_enter();
2109         ifnet_serialize_all(ifp);
2110         if (ifp->if_ioctl)
2111                 ifp->if_ioctl(ifp, SIOCADDMULTI, 0, NULL);
2112         ifnet_deserialize_all(ifp);
2113         crit_exit();
2114
2115         return 0;
2116 }
2117
2118 /*
2119  * Remove a reference to a multicast address on this interface.  Yell
2120  * if the request does not match an existing membership.
2121  */
2122 int
2123 if_delmulti(struct ifnet *ifp, struct sockaddr *sa)
2124 {
2125         struct ifmultiaddr *ifma;
2126
2127         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link)
2128                 if (sa_equal(sa, ifma->ifma_addr))
2129                         break;
2130         if (ifma == 0)
2131                 return ENOENT;
2132
2133         if (ifma->ifma_refcount > 1) {
2134                 ifma->ifma_refcount--;
2135                 return 0;
2136         }
2137
2138         rt_newmaddrmsg(RTM_DELMADDR, ifma);
2139         sa = ifma->ifma_lladdr;
2140         crit_enter();
2141         TAILQ_REMOVE(&ifp->if_multiaddrs, ifma, ifma_link);
2142         /*
2143          * Make sure the interface driver is notified
2144          * in the case of a link layer mcast group being left.
2145          */
2146         if (ifma->ifma_addr->sa_family == AF_LINK && sa == 0) {
2147                 ifnet_serialize_all(ifp);
2148                 ifp->if_ioctl(ifp, SIOCDELMULTI, 0, NULL);
2149                 ifnet_deserialize_all(ifp);
2150         }
2151         crit_exit();
2152         kfree(ifma->ifma_addr, M_IFMADDR);
2153         kfree(ifma, M_IFMADDR);
2154         if (sa == 0)
2155                 return 0;
2156
2157         /*
2158          * Now look for the link-layer address which corresponds to
2159          * this network address.  It had been squirreled away in
2160          * ifma->ifma_lladdr for this purpose (so we don't have
2161          * to call ifp->if_resolvemulti() again), and we saved that
2162          * value in sa above.  If some nasty deleted the
2163          * link-layer address out from underneath us, we can deal because
2164          * the address we stored was is not the same as the one which was
2165          * in the record for the link-layer address.  (So we don't complain
2166          * in that case.)
2167          */
2168         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link)
2169                 if (sa_equal(sa, ifma->ifma_addr))
2170                         break;
2171         if (ifma == 0)
2172                 return 0;
2173
2174         if (ifma->ifma_refcount > 1) {
2175                 ifma->ifma_refcount--;
2176                 return 0;
2177         }
2178
2179         crit_enter();
2180         ifnet_serialize_all(ifp);
2181         TAILQ_REMOVE(&ifp->if_multiaddrs, ifma, ifma_link);
2182         ifp->if_ioctl(ifp, SIOCDELMULTI, 0, NULL);
2183         ifnet_deserialize_all(ifp);
2184         crit_exit();
2185         kfree(ifma->ifma_addr, M_IFMADDR);
2186         kfree(sa, M_IFMADDR);
2187         kfree(ifma, M_IFMADDR);
2188
2189         return 0;
2190 }
2191
2192 /*
2193  * Delete all multicast group membership for an interface.
2194  * Should be used to quickly flush all multicast filters.
2195  */
2196 void
2197 if_delallmulti(struct ifnet *ifp)
2198 {
2199         struct ifmultiaddr *ifma;
2200         struct ifmultiaddr *next;
2201
2202         TAILQ_FOREACH_MUTABLE(ifma, &ifp->if_multiaddrs, ifma_link, next)
2203                 if_delmulti(ifp, ifma->ifma_addr);
2204 }
2205
2206
2207 /*
2208  * Set the link layer address on an interface.
2209  *
2210  * At this time we only support certain types of interfaces,
2211  * and we don't allow the length of the address to change.
2212  */
2213 int
2214 if_setlladdr(struct ifnet *ifp, const u_char *lladdr, int len)
2215 {
2216         struct sockaddr_dl *sdl;
2217         struct ifreq ifr;
2218
2219         sdl = IF_LLSOCKADDR(ifp);
2220         if (sdl == NULL)
2221                 return (EINVAL);
2222         if (len != sdl->sdl_alen)       /* don't allow length to change */
2223                 return (EINVAL);
2224         switch (ifp->if_type) {
2225         case IFT_ETHER:                 /* these types use struct arpcom */
2226         case IFT_XETHER:
2227         case IFT_L2VLAN:
2228                 bcopy(lladdr, ((struct arpcom *)ifp->if_softc)->ac_enaddr, len);
2229                 bcopy(lladdr, LLADDR(sdl), len);
2230                 break;
2231         default:
2232                 return (ENODEV);
2233         }
2234         /*
2235          * If the interface is already up, we need
2236          * to re-init it in order to reprogram its
2237          * address filter.
2238          */
2239         ifnet_serialize_all(ifp);
2240         if ((ifp->if_flags & IFF_UP) != 0) {
2241                 struct ifaddr_container *ifac;
2242
2243                 ifp->if_flags &= ~IFF_UP;
2244                 ifr.ifr_flags = ifp->if_flags;
2245                 ifr.ifr_flagshigh = ifp->if_flags >> 16;
2246                 ifp->if_ioctl(ifp, SIOCSIFFLAGS, (caddr_t)&ifr,
2247                               NULL);
2248                 ifp->if_flags |= IFF_UP;
2249                 ifr.ifr_flags = ifp->if_flags;
2250                 ifr.ifr_flagshigh = ifp->if_flags >> 16;
2251                 ifp->if_ioctl(ifp, SIOCSIFFLAGS, (caddr_t)&ifr,
2252                                  NULL);
2253 #ifdef INET
2254                 /*
2255                  * Also send gratuitous ARPs to notify other nodes about
2256                  * the address change.
2257                  */
2258                 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
2259                         struct ifaddr *ifa = ifac->ifa;
2260
2261                         if (ifa->ifa_addr != NULL &&
2262                             ifa->ifa_addr->sa_family == AF_INET)
2263                                 arp_ifinit(ifp, ifa);
2264                 }
2265 #endif
2266         }
2267         ifnet_deserialize_all(ifp);
2268         return (0);
2269 }
2270
2271 struct ifmultiaddr *
2272 ifmaof_ifpforaddr(struct sockaddr *sa, struct ifnet *ifp)
2273 {
2274         struct ifmultiaddr *ifma;
2275
2276         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link)
2277                 if (sa_equal(ifma->ifma_addr, sa))
2278                         break;
2279
2280         return ifma;
2281 }
2282
2283 /*
2284  * This function locates the first real ethernet MAC from a network
2285  * card and loads it into node, returning 0 on success or ENOENT if
2286  * no suitable interfaces were found.  It is used by the uuid code to
2287  * generate a unique 6-byte number.
2288  */
2289 int
2290 if_getanyethermac(uint16_t *node, int minlen)
2291 {
2292         struct ifnet *ifp;
2293         struct sockaddr_dl *sdl;
2294
2295         TAILQ_FOREACH(ifp, &ifnet, if_link) {
2296                 if (ifp->if_type != IFT_ETHER)
2297                         continue;
2298                 sdl = IF_LLSOCKADDR(ifp);
2299                 if (sdl->sdl_alen < minlen)
2300                         continue;
2301                 bcopy(((struct arpcom *)ifp->if_softc)->ac_enaddr, node,
2302                       minlen);
2303                 return(0);
2304         }
2305         return (ENOENT);
2306 }
2307
2308 /*
2309  * The name argument must be a pointer to storage which will last as
2310  * long as the interface does.  For physical devices, the result of
2311  * device_get_name(dev) is a good choice and for pseudo-devices a
2312  * static string works well.
2313  */
2314 void
2315 if_initname(struct ifnet *ifp, const char *name, int unit)
2316 {
2317         ifp->if_dname = name;
2318         ifp->if_dunit = unit;
2319         if (unit != IF_DUNIT_NONE)
2320                 ksnprintf(ifp->if_xname, IFNAMSIZ, "%s%d", name, unit);
2321         else
2322                 strlcpy(ifp->if_xname, name, IFNAMSIZ);
2323 }
2324
2325 int
2326 if_printf(struct ifnet *ifp, const char *fmt, ...)
2327 {
2328         __va_list ap;
2329         int retval;
2330
2331         retval = kprintf("%s: ", ifp->if_xname);
2332         __va_start(ap, fmt);
2333         retval += kvprintf(fmt, ap);
2334         __va_end(ap);
2335         return (retval);
2336 }
2337
2338 struct ifnet *
2339 if_alloc(uint8_t type)
2340 {
2341         struct ifnet *ifp;
2342         size_t size;
2343
2344         /*
2345          * XXX temporary hack until arpcom is setup in if_l2com
2346          */
2347         if (type == IFT_ETHER)
2348                 size = sizeof(struct arpcom);
2349         else
2350                 size = sizeof(struct ifnet);
2351
2352         ifp = kmalloc(size, M_IFNET, M_WAITOK|M_ZERO);
2353
2354         ifp->if_type = type;
2355
2356         if (if_com_alloc[type] != NULL) {
2357                 ifp->if_l2com = if_com_alloc[type](type, ifp);
2358                 if (ifp->if_l2com == NULL) {
2359                         kfree(ifp, M_IFNET);
2360                         return (NULL);
2361                 }
2362         }
2363         return (ifp);
2364 }
2365
2366 void
2367 if_free(struct ifnet *ifp)
2368 {
2369         kfree(ifp, M_IFNET);
2370 }
2371
2372 void
2373 ifq_set_classic(struct ifaltq *ifq)
2374 {
2375         ifq->altq_enqueue = ifq_classic_enqueue;
2376         ifq->altq_dequeue = ifq_classic_dequeue;
2377         ifq->altq_request = ifq_classic_request;
2378 }
2379
2380 int
2381 ifq_classic_enqueue(struct ifaltq *ifq, struct mbuf *m,
2382                     struct altq_pktattr *pa __unused)
2383 {
2384         logifq(enqueue, ifq);
2385         if (IF_QFULL(ifq)) {
2386                 m_freem(m);
2387                 return(ENOBUFS);
2388         } else {
2389                 IF_ENQUEUE(ifq, m);
2390                 return(0);
2391         }       
2392 }
2393
2394 struct mbuf *
2395 ifq_classic_dequeue(struct ifaltq *ifq, struct mbuf *mpolled, int op)
2396 {
2397         struct mbuf *m;
2398
2399         switch (op) {
2400         case ALTDQ_POLL:
2401                 IF_POLL(ifq, m);
2402                 break;
2403         case ALTDQ_REMOVE:
2404                 logifq(dequeue, ifq);
2405                 IF_DEQUEUE(ifq, m);
2406                 break;
2407         default:
2408                 panic("unsupported ALTQ dequeue op: %d", op);
2409         }
2410         KKASSERT(mpolled == NULL || mpolled == m);
2411         return(m);
2412 }
2413
2414 int
2415 ifq_classic_request(struct ifaltq *ifq, int req, void *arg)
2416 {
2417         switch (req) {
2418         case ALTRQ_PURGE:
2419                 IF_DRAIN(ifq);
2420                 break;
2421         default:
2422                 panic("unsupported ALTQ request: %d", req);
2423         }
2424         return(0);
2425 }
2426
2427 int
2428 ifq_dispatch(struct ifnet *ifp, struct mbuf *m, struct altq_pktattr *pa)
2429 {
2430         struct ifaltq *ifq = &ifp->if_snd;
2431         int running = 0, error, start = 0;
2432
2433         ASSERT_IFNET_NOT_SERIALIZED_TX(ifp);
2434
2435         ALTQ_LOCK(ifq);
2436         error = ifq_enqueue_locked(ifq, m, pa);
2437         if (error) {
2438                 ALTQ_UNLOCK(ifq);
2439                 return error;
2440         }
2441         if (!ifq->altq_started) {
2442                 /*
2443                  * Hold the interlock of ifnet.if_start
2444                  */
2445                 ifq->altq_started = 1;
2446                 start = 1;
2447         }
2448         ALTQ_UNLOCK(ifq);
2449
2450         ifp->if_obytes += m->m_pkthdr.len;
2451         if (m->m_flags & M_MCAST)
2452                 ifp->if_omcasts++;
2453
2454         if (!start) {
2455                 logifstart(avoid, ifp);
2456                 return 0;
2457         }
2458
2459         if (ifq_dispatch_schedonly) {
2460                 /*
2461                  * Always schedule ifnet.if_start on ifnet's CPU,
2462                  * short circuit the rest of this function.
2463                  */
2464                 logifstart(sched, ifp);
2465                 if_start_schedule(ifp);
2466                 return 0;
2467         }
2468
2469         /*
2470          * Try to do direct ifnet.if_start first, if there is
2471          * contention on ifnet's serializer, ifnet.if_start will
2472          * be scheduled on ifnet's CPU.
2473          */
2474         if (!ifnet_tryserialize_tx(ifp)) {
2475                 /*
2476                  * ifnet serializer contention happened,
2477                  * ifnet.if_start is scheduled on ifnet's
2478                  * CPU, and we keep going.
2479                  */
2480                 logifstart(contend_sched, ifp);
2481                 if_start_schedule(ifp);
2482                 return 0;
2483         }
2484
2485         if ((ifp->if_flags & IFF_OACTIVE) == 0) {
2486                 logifstart(run, ifp);
2487                 ifp->if_start(ifp);
2488                 if ((ifp->if_flags &
2489                      (IFF_OACTIVE | IFF_RUNNING)) == IFF_RUNNING)
2490                         running = 1;
2491         }
2492
2493         ifnet_deserialize_tx(ifp);
2494
2495         if (ifq_dispatch_schednochk || if_start_need_schedule(ifq, running)) {
2496                 /*
2497                  * More data need to be transmitted, ifnet.if_start is
2498                  * scheduled on ifnet's CPU, and we keep going.
2499                  * NOTE: ifnet.if_start interlock is not released.
2500                  */
2501                 logifstart(sched, ifp);
2502                 if_start_schedule(ifp);
2503         }
2504         return 0;
2505 }
2506
2507 void *
2508 ifa_create(int size, int flags)
2509 {
2510         struct ifaddr *ifa;
2511         int i;
2512
2513         KASSERT(size >= sizeof(*ifa), ("ifaddr size too small\n"));
2514
2515         ifa = kmalloc(size, M_IFADDR, flags | M_ZERO);
2516         if (ifa == NULL)
2517                 return NULL;
2518
2519         ifa->ifa_containers = kmalloc(ncpus * sizeof(struct ifaddr_container),
2520                                       M_IFADDR, M_WAITOK | M_ZERO);
2521         ifa->ifa_ncnt = ncpus;
2522         for (i = 0; i < ncpus; ++i) {
2523                 struct ifaddr_container *ifac = &ifa->ifa_containers[i];
2524
2525                 ifac->ifa_magic = IFA_CONTAINER_MAGIC;
2526                 ifac->ifa = ifa;
2527                 ifac->ifa_refcnt = 1;
2528         }
2529 #ifdef IFADDR_DEBUG
2530         kprintf("alloc ifa %p %d\n", ifa, size);
2531 #endif
2532         return ifa;
2533 }
2534
2535 void
2536 ifac_free(struct ifaddr_container *ifac, int cpu_id)
2537 {
2538         struct ifaddr *ifa = ifac->ifa;
2539
2540         KKASSERT(ifac->ifa_magic == IFA_CONTAINER_MAGIC);
2541         KKASSERT(ifac->ifa_refcnt == 0);
2542         KASSERT(ifac->ifa_listmask == 0,
2543                 ("ifa is still on %#x lists\n", ifac->ifa_listmask));
2544
2545         ifac->ifa_magic = IFA_CONTAINER_DEAD;
2546
2547 #ifdef IFADDR_DEBUG_VERBOSE
2548         kprintf("try free ifa %p cpu_id %d\n", ifac->ifa, cpu_id);
2549 #endif
2550
2551         KASSERT(ifa->ifa_ncnt > 0 && ifa->ifa_ncnt <= ncpus,
2552                 ("invalid # of ifac, %d\n", ifa->ifa_ncnt));
2553         if (atomic_fetchadd_int(&ifa->ifa_ncnt, -1) == 1) {
2554 #ifdef IFADDR_DEBUG
2555                 kprintf("free ifa %p\n", ifa);
2556 #endif
2557                 kfree(ifa->ifa_containers, M_IFADDR);
2558                 kfree(ifa, M_IFADDR);
2559         }
2560 }
2561
2562 static void
2563 ifa_iflink_dispatch(netmsg_t nmsg)
2564 {
2565         struct netmsg_ifaddr *msg = (struct netmsg_ifaddr *)nmsg;
2566         struct ifaddr *ifa = msg->ifa;
2567         struct ifnet *ifp = msg->ifp;
2568         int cpu = mycpuid;
2569         struct ifaddr_container *ifac;
2570
2571         crit_enter();
2572
2573         ifac = &ifa->ifa_containers[cpu];
2574         ASSERT_IFAC_VALID(ifac);
2575         KASSERT((ifac->ifa_listmask & IFA_LIST_IFADDRHEAD) == 0,
2576                 ("ifaddr is on if_addrheads\n"));
2577
2578         ifac->ifa_listmask |= IFA_LIST_IFADDRHEAD;
2579         if (msg->tail)
2580                 TAILQ_INSERT_TAIL(&ifp->if_addrheads[cpu], ifac, ifa_link);
2581         else
2582                 TAILQ_INSERT_HEAD(&ifp->if_addrheads[cpu], ifac, ifa_link);
2583
2584         crit_exit();
2585
2586         ifa_forwardmsg(&nmsg->lmsg, cpu + 1);
2587 }
2588
2589 void
2590 ifa_iflink(struct ifaddr *ifa, struct ifnet *ifp, int tail)
2591 {
2592         struct netmsg_ifaddr msg;
2593
2594         netmsg_init(&msg.base, NULL, &curthread->td_msgport,
2595                     0, ifa_iflink_dispatch);
2596         msg.ifa = ifa;
2597         msg.ifp = ifp;
2598         msg.tail = tail;
2599
2600         ifa_domsg(&msg.base.lmsg, 0);
2601 }
2602
2603 static void
2604 ifa_ifunlink_dispatch(netmsg_t nmsg)
2605 {
2606         struct netmsg_ifaddr *msg = (struct netmsg_ifaddr *)nmsg;
2607         struct ifaddr *ifa = msg->ifa;
2608         struct ifnet *ifp = msg->ifp;
2609         int cpu = mycpuid;
2610         struct ifaddr_container *ifac;
2611
2612         crit_enter();
2613
2614         ifac = &ifa->ifa_containers[cpu];
2615         ASSERT_IFAC_VALID(ifac);
2616         KASSERT(ifac->ifa_listmask & IFA_LIST_IFADDRHEAD,
2617                 ("ifaddr is not on if_addrhead\n"));
2618
2619         TAILQ_REMOVE(&ifp->if_addrheads[cpu], ifac, ifa_link);
2620         ifac->ifa_listmask &= ~IFA_LIST_IFADDRHEAD;
2621
2622         crit_exit();
2623
2624         ifa_forwardmsg(&nmsg->lmsg, cpu + 1);
2625 }
2626
2627 void
2628 ifa_ifunlink(struct ifaddr *ifa, struct ifnet *ifp)
2629 {
2630         struct netmsg_ifaddr msg;
2631
2632         netmsg_init(&msg.base, NULL, &curthread->td_msgport,
2633                     0, ifa_ifunlink_dispatch);
2634         msg.ifa = ifa;
2635         msg.ifp = ifp;
2636
2637         ifa_domsg(&msg.base.lmsg, 0);
2638 }
2639
2640 static void
2641 ifa_destroy_dispatch(netmsg_t nmsg)
2642 {
2643         struct netmsg_ifaddr *msg = (struct netmsg_ifaddr *)nmsg;
2644
2645         IFAFREE(msg->ifa);
2646         ifa_forwardmsg(&nmsg->lmsg, mycpuid + 1);
2647 }
2648
2649 void
2650 ifa_destroy(struct ifaddr *ifa)
2651 {
2652         struct netmsg_ifaddr msg;
2653
2654         netmsg_init(&msg.base, NULL, &curthread->td_msgport,
2655                     0, ifa_destroy_dispatch);
2656         msg.ifa = ifa;
2657
2658         ifa_domsg(&msg.base.lmsg, 0);
2659 }
2660
2661 struct lwkt_port *
2662 ifnet_portfn(int cpu)
2663 {
2664         return &ifnet_threads[cpu].td_msgport;
2665 }
2666
2667 void
2668 ifnet_forwardmsg(struct lwkt_msg *lmsg, int next_cpu)
2669 {
2670         KKASSERT(next_cpu > mycpuid && next_cpu <= ncpus);
2671
2672         if (next_cpu < ncpus)
2673                 lwkt_forwardmsg(ifnet_portfn(next_cpu), lmsg);
2674         else
2675                 lwkt_replymsg(lmsg, 0);
2676 }
2677
2678 int
2679 ifnet_domsg(struct lwkt_msg *lmsg, int cpu)
2680 {
2681         KKASSERT(cpu < ncpus);
2682         return lwkt_domsg(ifnet_portfn(cpu), lmsg, 0);
2683 }
2684
2685 void
2686 ifnet_sendmsg(struct lwkt_msg *lmsg, int cpu)
2687 {
2688         KKASSERT(cpu < ncpus);
2689         lwkt_sendmsg(ifnet_portfn(cpu), lmsg);
2690 }
2691
2692 /*
2693  * Generic netmsg service loop.  Some protocols may roll their own but all
2694  * must do the basic command dispatch function call done here.
2695  */
2696 static void
2697 ifnet_service_loop(void *arg __unused)
2698 {
2699         netmsg_t msg;
2700
2701         while ((msg = lwkt_waitport(&curthread->td_msgport, 0))) {
2702                 KASSERT(msg->base.nm_dispatch, ("ifnet_service: badmsg"));
2703                 msg->base.nm_dispatch(msg);
2704         }
2705 }
2706
2707 static void
2708 ifnetinit(void *dummy __unused)
2709 {
2710         int i;
2711
2712         for (i = 0; i < ncpus; ++i) {
2713                 struct thread *thr = &ifnet_threads[i];
2714
2715                 lwkt_create(ifnet_service_loop, NULL, NULL,
2716                             thr, TDF_STOPREQ, i, "ifnet %d", i);
2717                 netmsg_service_port_init(&thr->td_msgport);
2718                 lwkt_schedule(thr);
2719         }
2720 }
2721
2722 struct ifnet *
2723 ifnet_byindex(unsigned short idx)
2724 {
2725         if (idx > if_index)
2726                 return NULL;
2727         return ifindex2ifnet[idx];
2728 }
2729
2730 struct ifaddr *
2731 ifaddr_byindex(unsigned short idx)
2732 {
2733         struct ifnet *ifp;
2734
2735         ifp = ifnet_byindex(idx);
2736         if (!ifp)
2737                 return NULL;
2738         return TAILQ_FIRST(&ifp->if_addrheads[mycpuid])->ifa;
2739 }
2740
2741 void
2742 if_register_com_alloc(u_char type,
2743     if_com_alloc_t *a, if_com_free_t *f)
2744 {
2745
2746         KASSERT(if_com_alloc[type] == NULL,
2747             ("if_register_com_alloc: %d already registered", type));
2748         KASSERT(if_com_free[type] == NULL,
2749             ("if_register_com_alloc: %d free already registered", type));
2750
2751         if_com_alloc[type] = a;
2752         if_com_free[type] = f;
2753 }
2754
2755 void
2756 if_deregister_com_alloc(u_char type)
2757 {
2758
2759         KASSERT(if_com_alloc[type] != NULL,
2760             ("if_deregister_com_alloc: %d not registered", type));
2761         KASSERT(if_com_free[type] != NULL,
2762             ("if_deregister_com_alloc: %d free not registered", type));
2763         if_com_alloc[type] = NULL;
2764         if_com_free[type] = NULL;
2765 }