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