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