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