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