Move poll_each_burst adjustment out of hot code path.
[dragonfly.git] / sys / kern / kern_poll.c
1 /*-
2  * Copyright (c) 2001-2002 Luigi Rizzo
3  *
4  * Supported by: the Xorp Project (www.xorp.org)
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  *
27  * $FreeBSD: src/sys/kern/kern_poll.c,v 1.2.2.4 2002/06/27 23:26:33 luigi Exp $
28  * $DragonFly: src/sys/kern/kern_poll.c,v 1.40 2007/10/01 10:03:49 sephe Exp $
29  */
30
31 #include "opt_polling.h"
32
33 #include <sys/param.h>
34 #include <sys/kernel.h>
35 #include <sys/socket.h>                 /* needed by net/if.h           */
36 #include <sys/sysctl.h>
37
38 #include <sys/thread2.h>
39 #include <sys/msgport2.h>
40
41 #include <net/if.h>                     /* for IFF_* flags              */
42 #include <net/netmsg2.h>
43
44 /*
45  * Polling support for [network] device drivers.
46  *
47  * Drivers which support this feature try to register with the
48  * polling code.
49  *
50  * If registration is successful, the driver must disable interrupts,
51  * and further I/O is performed through the handler, which is invoked
52  * (at least once per clock tick) with 3 arguments: the "arg" passed at
53  * register time (a struct ifnet pointer), a command, and a "count" limit.
54  *
55  * The command can be one of the following:
56  *  POLL_ONLY: quick move of "count" packets from input/output queues.
57  *  POLL_AND_CHECK_STATUS: as above, plus check status registers or do
58  *      other more expensive operations. This command is issued periodically
59  *      but less frequently than POLL_ONLY.
60  *  POLL_DEREGISTER: deregister and return to interrupt mode.
61  *  POLL_REGISTER: register and disable interrupts
62  *
63  * The first two commands are only issued if the interface is marked as
64  * 'IFF_UP, IFF_RUNNING and IFF_POLLING', the last two only if IFF_RUNNING
65  * is set.
66  *
67  * The count limit specifies how much work the handler can do during the
68  * call -- typically this is the number of packets to be received, or
69  * transmitted, etc. (drivers are free to interpret this number, as long
70  * as the max time spent in the function grows roughly linearly with the
71  * count).
72  *
73  * Deregistration can be requested by the driver itself (typically in the
74  * *_stop() routine), or by the polling code, by invoking the handler.
75  *
76  * Polling can be enabled or disabled on particular CPU_X with the sysctl
77  * variable kern.polling.X.enable (default is 1, enabled)
78  *
79  * A second variable controls the sharing of CPU between polling/kernel
80  * network processing, and other activities (typically userlevel tasks):
81  * kern.polling.X.user_frac (between 0 and 100, default 50) sets the share
82  * of CPU allocated to user tasks. CPU is allocated proportionally to the
83  * shares, by dynamically adjusting the "count" (poll_burst).
84  *
85  * Other parameters can should be left to their default values.
86  * The following constraints hold
87  *
88  *      1 <= poll_burst <= poll_burst_max
89  *      1 <= poll_each_burst <= poll_burst_max
90  *      MIN_POLL_BURST_MAX <= poll_burst_max <= MAX_POLL_BURST_MAX
91  */
92
93 #define MIN_POLL_BURST_MAX      10
94 #define MAX_POLL_BURST_MAX      1000
95
96 #ifndef DEVICE_POLLING_FREQ_MAX
97 #define DEVICE_POLLING_FREQ_MAX         30000
98 #endif
99 #define DEVICE_POLLING_FREQ_DEFAULT     2000
100
101 #define POLL_LIST_LEN  128
102 struct pollrec {
103         struct ifnet    *ifp;
104 };
105
106 #define POLLCTX_MAX     32
107
108 struct pollctx {
109         struct sysctl_ctx_list  poll_sysctl_ctx;
110         struct sysctl_oid       *poll_sysctl_tree;
111
112         uint32_t                poll_burst;
113         uint32_t                poll_each_burst;
114         uint32_t                poll_burst_max;
115         uint32_t                user_frac;
116         int                     reg_frac_count;
117         uint32_t                reg_frac;
118         uint32_t                short_ticks;
119         uint32_t                lost_polls;
120         uint32_t                pending_polls;
121         int                     residual_burst;
122         uint32_t                phase;
123         uint32_t                suspect;
124         uint32_t                stalled;
125         struct timeval          poll_start_t;
126         struct timeval          prev_t;
127
128         uint32_t                poll_handlers; /* next free entry in pr[]. */
129         struct pollrec          pr[POLL_LIST_LEN];
130
131         int                     poll_cpuid;
132         struct systimer         pollclock;
133         int                     polling_enabled;
134         int                     pollhz;
135
136         struct netmsg           poll_netmsg;
137         struct netmsg           poll_more_netmsg;
138 };
139
140 static struct pollctx   *poll_context[POLLCTX_MAX];
141
142 SYSCTL_NODE(_kern, OID_AUTO, polling, CTLFLAG_RW, 0,
143         "Device polling parameters");
144
145 static int      poll_defcpu = -1;
146 SYSCTL_INT(_kern_polling, OID_AUTO, defcpu, CTLFLAG_RD,
147         &poll_defcpu, 0, "default CPU to run device polling");
148
149 static uint32_t poll_cpumask0 = 0xffffffff;
150 TUNABLE_INT("kern.polling.cpumask", (int *)&poll_cpumask0);
151
152 static uint32_t poll_cpumask;
153 SYSCTL_INT(_kern_polling, OID_AUTO, cpumask, CTLFLAG_RD,
154         &poll_cpumask, 0, "CPUs that can run device polling");
155
156 static int      polling_enabled = 1;    /* global polling enable */
157 TUNABLE_INT("kern.polling.enable", &polling_enabled);
158
159 static int      pollhz = DEVICE_POLLING_FREQ_DEFAULT;
160 TUNABLE_INT("kern.polling.pollhz", &pollhz);
161
162 /* Netisr handlers */
163 static void     netisr_poll(struct netmsg *);
164 static void     netisr_pollmore(struct netmsg *);
165 static void     poll_register(struct netmsg *);
166 static void     poll_deregister(struct netmsg *);
167 static void     poll_sysctl_pollhz(struct netmsg *);
168 static void     poll_sysctl_polling(struct netmsg *);
169 static void     poll_sysctl_regfrac(struct netmsg *);
170 static void     poll_sysctl_burstmax(struct netmsg *);
171 static void     poll_sysctl_eachburst(struct netmsg *);
172
173 /* Systimer handler */
174 static void     pollclock(systimer_t, struct intrframe *);
175
176 /* Sysctl handlers */
177 static int      sysctl_pollhz(SYSCTL_HANDLER_ARGS);
178 static int      sysctl_polling(SYSCTL_HANDLER_ARGS);
179 static int      sysctl_regfrac(SYSCTL_HANDLER_ARGS);
180 static int      sysctl_burstmax(SYSCTL_HANDLER_ARGS);
181 static int      sysctl_eachburst(SYSCTL_HANDLER_ARGS);
182 static void     poll_add_sysctl(struct sysctl_ctx_list *,
183                                 struct sysctl_oid_list *, struct pollctx *);
184
185 static void     schedpoll_oncpu(struct pollctx *, struct netmsg *, netisr_fn_t);
186
187 void            init_device_poll_pcpu(int);     /* per-cpu init routine */
188
189 /*
190  * Initialize per-cpu polling(4) context.  Called from kern_clock.c:
191  */
192 void
193 init_device_poll_pcpu(int cpuid)
194 {
195         struct pollctx *pctx;
196         char cpuid_str[3];
197
198         if (cpuid >= POLLCTX_MAX)
199                 return;
200
201         if (((1 << cpuid) & poll_cpumask0) == 0)
202                 return;
203
204         poll_cpumask |= (1 << cpuid);
205
206         pctx = kmalloc(sizeof(*pctx), M_DEVBUF, M_WAITOK | M_ZERO);
207
208         pctx->poll_burst = 5;
209         pctx->poll_each_burst = 5;
210         pctx->poll_burst_max = 150; /* good for 100Mbit net and HZ=1000 */
211         pctx->user_frac = 50;
212         pctx->reg_frac = 20;
213         pctx->polling_enabled = polling_enabled;
214         pctx->pollhz = pollhz;
215         pctx->poll_cpuid = cpuid;
216         netmsg_init(&pctx->poll_netmsg, &netisr_adone_rport, 0, NULL);
217         netmsg_init(&pctx->poll_more_netmsg, &netisr_adone_rport, 0, NULL);
218
219         KASSERT(cpuid < POLLCTX_MAX, ("cpu id must < %d", cpuid));
220         poll_context[cpuid] = pctx;
221
222         if (poll_defcpu < 0) {
223                 poll_defcpu = cpuid;
224
225                 /*
226                  * Initialize global sysctl nodes, for compat
227                  */
228                 poll_add_sysctl(NULL, SYSCTL_STATIC_CHILDREN(_kern_polling),
229                                 pctx);
230         }
231
232         /*
233          * Initialize per-cpu sysctl nodes
234          */
235         ksnprintf(cpuid_str, sizeof(cpuid_str), "%d", pctx->poll_cpuid);
236
237         sysctl_ctx_init(&pctx->poll_sysctl_ctx);
238         pctx->poll_sysctl_tree = SYSCTL_ADD_NODE(&pctx->poll_sysctl_ctx,
239                                  SYSCTL_STATIC_CHILDREN(_kern_polling),
240                                  OID_AUTO, cpuid_str, CTLFLAG_RD, 0, "");
241         poll_add_sysctl(&pctx->poll_sysctl_ctx,
242                         SYSCTL_CHILDREN(pctx->poll_sysctl_tree), pctx);
243
244         /*
245          * Initialize systimer
246          */
247         systimer_init_periodic_nq(&pctx->pollclock, pollclock, pctx, 1);
248 }
249
250 static __inline void
251 schedpoll(struct pollctx *pctx)
252 {
253         schedpoll_oncpu(pctx, &pctx->poll_netmsg, netisr_poll);
254 }
255
256 static __inline void
257 schedpollmore(struct pollctx *pctx)
258 {
259         schedpoll_oncpu(pctx, &pctx->poll_more_netmsg, netisr_pollmore);
260 }
261
262 /*
263  * Set the polling frequency
264  */
265 static int
266 sysctl_pollhz(SYSCTL_HANDLER_ARGS)
267 {
268         struct pollctx *pctx = arg1;
269         struct netmsg msg;
270         lwkt_port_t port;
271         int error, phz;
272
273         phz = pctx->pollhz;
274         error = sysctl_handle_int(oidp, &phz, 0, req);
275         if (error || req->newptr == NULL)
276                 return error;
277         if (phz <= 0)
278                 return EINVAL;
279         else if (phz > DEVICE_POLLING_FREQ_MAX)
280                 phz = DEVICE_POLLING_FREQ_MAX;
281
282         netmsg_init(&msg, &curthread->td_msgport, 0, poll_sysctl_pollhz);
283         msg.nm_lmsg.u.ms_result = phz;
284
285         port = cpu_portfn(pctx->poll_cpuid);
286         lwkt_domsg(port, &msg.nm_lmsg, 0);
287         return 0;
288 }
289
290 /*
291  * Master enable.
292  */
293 static int
294 sysctl_polling(SYSCTL_HANDLER_ARGS)
295 {
296         struct pollctx *pctx = arg1;
297         struct netmsg msg;
298         lwkt_port_t port;
299         int error, enabled;
300
301         enabled = pctx->polling_enabled;
302         error = sysctl_handle_int(oidp, &enabled, 0, req);
303         if (error || req->newptr == NULL)
304                 return error;
305
306         netmsg_init(&msg, &curthread->td_msgport, 0, poll_sysctl_polling);
307         msg.nm_lmsg.u.ms_result = enabled;
308
309         port = cpu_portfn(pctx->poll_cpuid);
310         lwkt_domsg(port, &msg.nm_lmsg, 0);
311         return 0;
312 }
313
314 static int
315 sysctl_regfrac(SYSCTL_HANDLER_ARGS)
316 {
317         struct pollctx *pctx = arg1;
318         struct netmsg msg;
319         lwkt_port_t port;
320         uint32_t reg_frac;
321         int error;
322
323         reg_frac = pctx->reg_frac;
324         error = sysctl_handle_int(oidp, &reg_frac, 0, req);
325         if (error || req->newptr == NULL)
326                 return error;
327
328         netmsg_init(&msg, &curthread->td_msgport, 0, poll_sysctl_regfrac);
329         msg.nm_lmsg.u.ms_result = reg_frac;
330
331         port = cpu_portfn(pctx->poll_cpuid);
332         lwkt_domsg(port, &msg.nm_lmsg, 0);
333         return 0;
334 }
335
336 static int
337 sysctl_burstmax(SYSCTL_HANDLER_ARGS)
338 {
339         struct pollctx *pctx = arg1;
340         struct netmsg msg;
341         lwkt_port_t port;
342         uint32_t burst_max;
343         int error;
344
345         burst_max = pctx->poll_burst_max;
346         error = sysctl_handle_int(oidp, &burst_max, 0, req);
347         if (error || req->newptr == NULL)
348                 return error;
349         if (burst_max < MIN_POLL_BURST_MAX)
350                 burst_max = MIN_POLL_BURST_MAX;
351         else if (burst_max > MAX_POLL_BURST_MAX)
352                 burst_max = MAX_POLL_BURST_MAX;
353
354         netmsg_init(&msg, &curthread->td_msgport, 0, poll_sysctl_burstmax);
355         msg.nm_lmsg.u.ms_result = burst_max;
356
357         port = cpu_portfn(pctx->poll_cpuid);
358         lwkt_domsg(port, &msg.nm_lmsg, 0);
359         return 0;
360 }
361
362 static int
363 sysctl_eachburst(SYSCTL_HANDLER_ARGS)
364 {
365         struct pollctx *pctx = arg1;
366         struct netmsg msg;
367         lwkt_port_t port;
368         uint32_t each_burst;
369         int error;
370
371         each_burst = pctx->poll_each_burst;
372         error = sysctl_handle_int(oidp, &each_burst, 0, req);
373         if (error || req->newptr == NULL)
374                 return error;
375
376         netmsg_init(&msg, &curthread->td_msgport, 0, poll_sysctl_eachburst);
377         msg.nm_lmsg.u.ms_result = each_burst;
378
379         port = cpu_portfn(pctx->poll_cpuid);
380         lwkt_domsg(port, &msg.nm_lmsg, 0);
381         return 0;
382 }
383
384 /*
385  * Hook from polling systimer. Tries to schedule a netisr, but keeps
386  * track of lost ticks due to the previous handler taking too long.
387  * Normally, this should not happen, because polling handler should
388  * run for a short time. However, in some cases (e.g. when there are
389  * changes in link status etc.) the drivers take a very long time
390  * (even in the order of milliseconds) to reset and reconfigure the
391  * device, causing apparent lost polls.
392  *
393  * The first part of the code is just for debugging purposes, and tries
394  * to count how often hardclock ticks are shorter than they should,
395  * meaning either stray interrupts or delayed events.
396  *
397  * WARNING! called from fastint or IPI, the MP lock might not be held.
398  */
399 static void
400 pollclock(systimer_t info, struct intrframe *frame __unused)
401 {
402         struct pollctx *pctx = info->data;
403         struct timeval t;
404         int delta;
405
406         if (pctx->poll_handlers == 0)
407                 return;
408
409         microuptime(&t);
410         delta = (t.tv_usec - pctx->prev_t.tv_usec) +
411                 (t.tv_sec - pctx->prev_t.tv_sec)*1000000;
412         if (delta * pctx->pollhz < 500000)
413                 pctx->short_ticks++;
414         else
415                 pctx->prev_t = t;
416
417         if (pctx->pending_polls > 100) {
418                 /*
419                  * Too much, assume it has stalled (not always true
420                  * see comment above).
421                  */
422                 pctx->stalled++;
423                 pctx->pending_polls = 0;
424                 pctx->phase = 0;
425         }
426
427         if (pctx->phase <= 2) {
428                 if (pctx->phase != 0)
429                         pctx->suspect++;
430                 pctx->phase = 1;
431                 schedpoll(pctx);
432                 pctx->phase = 2;
433         }
434         if (pctx->pending_polls++ > 0)
435                 pctx->lost_polls++;
436 }
437
438 /*
439  * netisr_pollmore is called after other netisr's, possibly scheduling
440  * another NETISR_POLL call, or adapting the burst size for the next cycle.
441  *
442  * It is very bad to fetch large bursts of packets from a single card at once,
443  * because the burst could take a long time to be completely processed, or
444  * could saturate the intermediate queue (ipintrq or similar) leading to
445  * losses or unfairness. To reduce the problem, and also to account better for
446  * time spent in network-related processing, we split the burst in smaller
447  * chunks of fixed size, giving control to the other netisr's between chunks.
448  * This helps in improving the fairness, reducing livelock (because we
449  * emulate more closely the "process to completion" that we have with
450  * fastforwarding) and accounting for the work performed in low level
451  * handling and forwarding.
452  */
453
454 /* ARGSUSED */
455 static void
456 netisr_pollmore(struct netmsg *msg)
457 {
458         struct pollctx *pctx;
459         struct timeval t;
460         int kern_load, cpuid;
461
462         cpuid = mycpu->gd_cpuid;
463         KKASSERT(cpuid < POLLCTX_MAX);
464
465         pctx = poll_context[cpuid];
466         KKASSERT(pctx != NULL);
467         KKASSERT(pctx->poll_cpuid == cpuid);
468         KKASSERT(pctx == msg->nm_lmsg.u.ms_resultp);
469
470         lwkt_replymsg(&msg->nm_lmsg, 0);
471
472         pctx->phase = 5;
473         if (pctx->residual_burst > 0) {
474                 schedpoll(pctx);
475                 /* will run immediately on return, followed by netisrs */
476                 return;
477         }
478         /* here we can account time spent in netisr's in this tick */
479         microuptime(&t);
480         kern_load = (t.tv_usec - pctx->poll_start_t.tv_usec) +
481                 (t.tv_sec - pctx->poll_start_t.tv_sec)*1000000; /* us */
482         kern_load = (kern_load * pctx->pollhz) / 10000;         /* 0..100 */
483         if (kern_load > (100 - pctx->user_frac)) { /* try decrease ticks */
484                 if (pctx->poll_burst > 1)
485                         pctx->poll_burst--;
486         } else {
487                 if (pctx->poll_burst < pctx->poll_burst_max)
488                         pctx->poll_burst++;
489         }
490
491         pctx->pending_polls--;
492         if (pctx->pending_polls == 0) { /* we are done */
493                 pctx->phase = 0;
494         } else {
495                 /*
496                  * Last cycle was long and caused us to miss one or more
497                  * hardclock ticks. Restart processing again, but slightly
498                  * reduce the burst size to prevent that this happens again.
499                  */
500                 pctx->poll_burst -= (pctx->poll_burst / 8);
501                 if (pctx->poll_burst < 1)
502                         pctx->poll_burst = 1;
503                 schedpoll(pctx);
504                 pctx->phase = 6;
505         }
506 }
507
508 /*
509  * netisr_poll is scheduled by schedpoll when appropriate, typically once
510  * per polling systimer tick.
511  *
512  * Note that the message is replied immediately in order to allow a new
513  * ISR to be scheduled in the handler.
514  *
515  * XXX each registration should indicate whether it needs a critical
516  * section to operate.
517  */
518 /* ARGSUSED */
519 static void
520 netisr_poll(struct netmsg *msg)
521 {
522         struct pollctx *pctx;
523         int i, cycles, cpuid;
524         enum poll_cmd arg = POLL_ONLY;
525
526         cpuid = mycpu->gd_cpuid;
527         KKASSERT(cpuid < POLLCTX_MAX);
528
529         pctx = poll_context[cpuid];
530         KKASSERT(pctx != NULL);
531         KKASSERT(pctx->poll_cpuid == cpuid);
532         KKASSERT(pctx == msg->nm_lmsg.u.ms_resultp);
533
534         lwkt_replymsg(&msg->nm_lmsg, 0);
535
536         pctx->phase = 3;
537         if (pctx->residual_burst == 0) { /* first call in this tick */
538                 microuptime(&pctx->poll_start_t);
539
540                 if (pctx->reg_frac_count-- == 0) {
541                         arg = POLL_AND_CHECK_STATUS;
542                         pctx->reg_frac_count = pctx->reg_frac - 1;
543                 }
544
545                 pctx->residual_burst = pctx->poll_burst;
546         }
547         cycles = (pctx->residual_burst < pctx->poll_each_burst) ?
548                 pctx->residual_burst : pctx->poll_each_burst;
549         pctx->residual_burst -= cycles;
550
551         if (pctx->polling_enabled) {
552                 for (i = 0 ; i < pctx->poll_handlers ; i++) {
553                         struct ifnet *ifp = pctx->pr[i].ifp;
554
555                         if (!lwkt_serialize_try(ifp->if_serializer))
556                                 continue;
557
558                         if ((ifp->if_flags & (IFF_UP|IFF_RUNNING|IFF_POLLING))
559                             == (IFF_UP|IFF_RUNNING|IFF_POLLING))
560                                 ifp->if_poll(ifp, arg, cycles);
561
562                         lwkt_serialize_exit(ifp->if_serializer);
563                 }
564         } else {        /* unregister */
565                 for (i = 0 ; i < pctx->poll_handlers ; i++) {
566                         struct ifnet *ifp = pctx->pr[i].ifp;
567
568                         lwkt_serialize_enter(ifp->if_serializer);
569
570                         if ((ifp->if_flags & IFF_POLLING) == 0) {
571                                 KKASSERT(ifp->if_poll_cpuid < 0);
572                                 lwkt_serialize_exit(ifp->if_serializer);
573                                 continue;
574                         }
575                         ifp->if_flags &= ~IFF_POLLING;
576                         ifp->if_poll_cpuid = -1;
577
578                         /*
579                          * Only call the interface deregistration
580                          * function if the interface is still 
581                          * running.
582                          */
583                         if (ifp->if_flags & IFF_RUNNING)
584                                 ifp->if_poll(ifp, POLL_DEREGISTER, 1);
585
586                         lwkt_serialize_exit(ifp->if_serializer);
587                 }
588                 pctx->residual_burst = 0;
589                 pctx->poll_handlers = 0;
590         }
591         schedpollmore(pctx);
592         pctx->phase = 4;
593 }
594
595 static void
596 poll_register(struct netmsg *msg)
597 {
598         struct ifnet *ifp = msg->nm_lmsg.u.ms_resultp;
599         struct pollctx *pctx;
600         int rc, cpuid;
601
602         cpuid = mycpu->gd_cpuid;
603         KKASSERT(cpuid < POLLCTX_MAX);
604
605         pctx = poll_context[cpuid];
606         KKASSERT(pctx != NULL);
607         KKASSERT(pctx->poll_cpuid == cpuid);
608
609         if (pctx->polling_enabled == 0) {
610                 /* Polling disabled, cannot register */
611                 rc = EOPNOTSUPP;
612                 goto back;
613         }
614
615         /*
616          * Check if there is room.
617          */
618         if (pctx->poll_handlers >= POLL_LIST_LEN) {
619                 /*
620                  * List full, cannot register more entries.
621                  * This should never happen; if it does, it is probably a
622                  * broken driver trying to register multiple times. Checking
623                  * this at runtime is expensive, and won't solve the problem
624                  * anyways, so just report a few times and then give up.
625                  */
626                 static int verbose = 10;        /* XXX */
627                 if (verbose >0) {
628                         kprintf("poll handlers list full, "
629                                 "maybe a broken driver ?\n");
630                         verbose--;
631                 }
632                 rc = ENOMEM;
633         } else {
634                 pctx->pr[pctx->poll_handlers].ifp = ifp;
635                 pctx->poll_handlers++;
636                 rc = 0;
637
638                 if (pctx->poll_handlers == 1) {
639                         KKASSERT(pctx->polling_enabled);
640                         systimer_adjust_periodic(&pctx->pollclock,
641                                                  pctx->pollhz);
642                 }
643         }
644 back:
645         lwkt_replymsg(&msg->nm_lmsg, rc);
646 }
647
648 /*
649  * Try to register routine for polling. Returns 1 if successful
650  * (and polling should be enabled), 0 otherwise.
651  *
652  * Called from mainline code only, not called from an interrupt.
653  */
654 int
655 ether_poll_register(struct ifnet *ifp)
656 {
657         if (poll_defcpu < 0)
658                 return 0;
659         KKASSERT(poll_defcpu < POLLCTX_MAX);
660
661         return ether_pollcpu_register(ifp, poll_defcpu);
662 }
663
664 int
665 ether_pollcpu_register(struct ifnet *ifp, int cpuid)
666 {
667         struct netmsg msg;
668         lwkt_port_t port;
669         int rc;
670
671         if (ifp->if_poll == NULL) {
672                 /* Device does not support polling */
673                 return 0;
674         }
675
676         if (cpuid < 0 || cpuid >= POLLCTX_MAX)
677                 return 0;
678
679         if (((1 << cpuid) & poll_cpumask) == 0) {
680                 /* Polling is not supported on 'cpuid' */
681                 return 0;
682         }
683         KKASSERT(poll_context[cpuid] != NULL);
684
685         /*
686          * Attempt to register.  Interlock with IFF_POLLING.
687          */
688         crit_enter();   /* XXX MP - not mp safe */
689
690         lwkt_serialize_enter(ifp->if_serializer);
691         if (ifp->if_flags & IFF_POLLING) {
692                 /* Already polling */
693                 KKASSERT(ifp->if_poll_cpuid >= 0);
694                 lwkt_serialize_exit(ifp->if_serializer);
695                 crit_exit();
696                 return 0;
697         }
698         KKASSERT(ifp->if_poll_cpuid < 0);
699         ifp->if_flags |= IFF_POLLING;
700         ifp->if_poll_cpuid = cpuid;
701         if (ifp->if_flags & IFF_RUNNING)
702                 ifp->if_poll(ifp, POLL_REGISTER, 0);
703         lwkt_serialize_exit(ifp->if_serializer);
704
705         netmsg_init(&msg, &curthread->td_msgport, 0, poll_register);
706         msg.nm_lmsg.u.ms_resultp = ifp;
707
708         port = cpu_portfn(cpuid);
709         lwkt_domsg(port, &msg.nm_lmsg, 0);
710
711         if (msg.nm_lmsg.ms_error) {
712                 lwkt_serialize_enter(ifp->if_serializer);
713                 ifp->if_flags &= ~IFF_POLLING;
714                 ifp->if_poll_cpuid = -1;
715                 if (ifp->if_flags & IFF_RUNNING)
716                         ifp->if_poll(ifp, POLL_DEREGISTER, 0);
717                 lwkt_serialize_exit(ifp->if_serializer);
718                 rc = 0;
719         } else {
720                 rc = 1;
721         }
722
723         crit_exit();
724         return rc;
725 }
726
727 static void
728 poll_deregister(struct netmsg *msg)
729 {
730         struct ifnet *ifp = msg->nm_lmsg.u.ms_resultp;
731         struct pollctx *pctx;
732         int rc, i, cpuid;
733
734         cpuid = mycpu->gd_cpuid;
735         KKASSERT(cpuid < POLLCTX_MAX);
736
737         pctx = poll_context[cpuid];
738         KKASSERT(pctx != NULL);
739         KKASSERT(pctx->poll_cpuid == cpuid);
740
741         for (i = 0 ; i < pctx->poll_handlers ; i++) {
742                 if (pctx->pr[i].ifp == ifp) /* Found it */
743                         break;
744         }
745         if (i == pctx->poll_handlers) {
746                 kprintf("ether_poll_deregister: ifp not found!!!\n");
747                 rc = ENOENT;
748         } else {
749                 pctx->poll_handlers--;
750                 if (i < pctx->poll_handlers) {
751                         /* Last entry replaces this one. */
752                         pctx->pr[i].ifp = pctx->pr[pctx->poll_handlers].ifp;
753                 }
754
755                 if (pctx->poll_handlers == 0)
756                         systimer_adjust_periodic(&pctx->pollclock, 1);
757                 rc = 0;
758         }
759         lwkt_replymsg(&msg->nm_lmsg, rc);
760 }
761
762 /*
763  * Remove interface from the polling list.  Occurs when polling is turned
764  * off.  Called from mainline code only, not called from an interrupt.
765  */
766 int
767 ether_poll_deregister(struct ifnet *ifp)
768 {
769         struct netmsg msg;
770         lwkt_port_t port;
771         int rc, cpuid;
772
773         KKASSERT(ifp != NULL);
774
775         if (ifp->if_poll == NULL)
776                 return 0;
777
778         crit_enter();
779
780         lwkt_serialize_enter(ifp->if_serializer);
781         if ((ifp->if_flags & IFF_POLLING) == 0) {
782                 KKASSERT(ifp->if_poll_cpuid < 0);
783                 lwkt_serialize_exit(ifp->if_serializer);
784                 crit_exit();
785                 return 0;
786         }
787
788         cpuid = ifp->if_poll_cpuid;
789         KKASSERT(cpuid >= 0);
790         KKASSERT(poll_context[cpuid] != NULL);
791
792         ifp->if_flags &= ~IFF_POLLING;
793         ifp->if_poll_cpuid = -1;
794         lwkt_serialize_exit(ifp->if_serializer);
795
796         netmsg_init(&msg, &curthread->td_msgport, 0, poll_deregister);
797         msg.nm_lmsg.u.ms_resultp = ifp;
798
799         port = cpu_portfn(cpuid);
800         lwkt_domsg(port, &msg.nm_lmsg, 0);
801
802         if (!msg.nm_lmsg.ms_error) {
803                 lwkt_serialize_enter(ifp->if_serializer);
804                 if (ifp->if_flags & IFF_RUNNING)
805                         ifp->if_poll(ifp, POLL_DEREGISTER, 1);
806                 lwkt_serialize_exit(ifp->if_serializer);
807                 rc = 1;
808         } else {
809                 rc = 0;
810         }
811
812         crit_exit();
813         return rc;
814 }
815
816 static void
817 poll_add_sysctl(struct sysctl_ctx_list *ctx, struct sysctl_oid_list *parent,
818                 struct pollctx *pctx)
819 {
820         SYSCTL_ADD_PROC(ctx, parent, OID_AUTO, "enable",
821                         CTLTYPE_INT | CTLFLAG_RW, pctx, 0, sysctl_polling,
822                         "I", "Polling enabled");
823
824         SYSCTL_ADD_PROC(ctx, parent, OID_AUTO, "pollhz",
825                         CTLTYPE_INT | CTLFLAG_RW, pctx, 0, sysctl_pollhz,
826                         "I", "Device polling frequency");
827
828         SYSCTL_ADD_PROC(ctx, parent, OID_AUTO, "reg_frac",
829                         CTLTYPE_UINT | CTLFLAG_RW, pctx, 0, sysctl_regfrac,
830                         "IU", "Every this many cycles poll register");
831
832         SYSCTL_ADD_PROC(ctx, parent, OID_AUTO, "burst_max",
833                         CTLTYPE_UINT | CTLFLAG_RW, pctx, 0, sysctl_burstmax,
834                         "IU", "Max Polling burst size");
835
836         SYSCTL_ADD_PROC(ctx, parent, OID_AUTO, "each_burst",
837                         CTLTYPE_UINT | CTLFLAG_RW, pctx, 0, sysctl_eachburst,
838                         "IU", "Max size of each burst");
839
840         SYSCTL_ADD_UINT(ctx, parent, OID_AUTO, "phase", CTLFLAG_RD,
841                         &pctx->phase, 0, "Polling phase");
842
843         SYSCTL_ADD_UINT(ctx, parent, OID_AUTO, "suspect", CTLFLAG_RW,
844                         &pctx->suspect, 0, "suspect event");
845
846         SYSCTL_ADD_UINT(ctx, parent, OID_AUTO, "stalled", CTLFLAG_RW,
847                         &pctx->stalled, 0, "potential stalls");
848
849         SYSCTL_ADD_UINT(ctx, parent, OID_AUTO, "burst", CTLFLAG_RD,
850                         &pctx->poll_burst, 0, "Current polling burst size");
851
852         SYSCTL_ADD_UINT(ctx, parent, OID_AUTO, "user_frac", CTLFLAG_RW,
853                         &pctx->user_frac, 0,
854                         "Desired user fraction of cpu time");
855
856         SYSCTL_ADD_UINT(ctx, parent, OID_AUTO, "short_ticks", CTLFLAG_RW,
857                         &pctx->short_ticks, 0,
858                         "Hardclock ticks shorter than they should be");
859
860         SYSCTL_ADD_UINT(ctx, parent, OID_AUTO, "lost_polls", CTLFLAG_RW,
861                         &pctx->lost_polls, 0,
862                         "How many times we would have lost a poll tick");
863
864         SYSCTL_ADD_UINT(ctx, parent, OID_AUTO, "pending_polls", CTLFLAG_RD,
865                         &pctx->pending_polls, 0, "Do we need to poll again");
866
867         SYSCTL_ADD_INT(ctx, parent, OID_AUTO, "residual_burst", CTLFLAG_RD,
868                        &pctx->residual_burst, 0,
869                        "# of residual cycles in burst");
870
871         SYSCTL_ADD_UINT(ctx, parent, OID_AUTO, "handlers", CTLFLAG_RD,
872                         &pctx->poll_handlers, 0,
873                         "Number of registered poll handlers");
874 }
875
876 static void
877 schedpoll_oncpu(struct pollctx *pctx, struct netmsg *msg, netisr_fn_t handler)
878 {
879         if (msg->nm_lmsg.ms_flags & MSGF_DONE) {
880                 lwkt_port_t port;
881
882                 netmsg_init(msg, &netisr_adone_rport, 0, handler);
883 #ifdef INVARIANTS
884                 msg->nm_lmsg.u.ms_resultp = pctx;
885 #endif
886                 port = cpu_portfn(mycpu->gd_cpuid);
887                 lwkt_sendmsg(port, &msg->nm_lmsg);
888         }
889 }
890
891 static void
892 poll_sysctl_pollhz(struct netmsg *msg)
893 {
894         struct pollctx *pctx;
895         int cpuid;
896
897         cpuid = mycpu->gd_cpuid;
898         KKASSERT(cpuid < POLLCTX_MAX);
899
900         pctx = poll_context[cpuid];
901         KKASSERT(pctx != NULL);
902         KKASSERT(pctx->poll_cpuid == cpuid);
903
904         /*
905          * If polling is disabled or there is no device registered,
906          * don't adjust polling systimer frequency.
907          * Polling systimer frequency will be adjusted once polling
908          * is enabled and there are registered devices.
909          */
910         pctx->pollhz = msg->nm_lmsg.u.ms_result;
911         if (pctx->polling_enabled && pctx->poll_handlers)
912                 systimer_adjust_periodic(&pctx->pollclock, pctx->pollhz);
913
914         /*
915          * Make sure that reg_frac and reg_frac_count are within valid range.
916          */
917         if (pctx->reg_frac > pctx->pollhz) {
918                 pctx->reg_frac = pctx->pollhz;
919                 if (pctx->reg_frac_count > pctx->reg_frac)
920                         pctx->reg_frac_count = pctx->reg_frac - 1;
921         }
922
923         lwkt_replymsg(&msg->nm_lmsg, 0);
924 }
925
926 static void
927 poll_sysctl_polling(struct netmsg *msg)
928 {
929         struct pollctx *pctx;
930         int cpuid;
931
932         cpuid = mycpu->gd_cpuid;
933         KKASSERT(cpuid < POLLCTX_MAX);
934
935         pctx = poll_context[cpuid];
936         KKASSERT(pctx != NULL);
937         KKASSERT(pctx->poll_cpuid == cpuid);
938
939         /*
940          * If polling is disabled or there is no device registered,
941          * cut the polling systimer frequency to 1hz.
942          */
943         pctx->polling_enabled = msg->nm_lmsg.u.ms_result;
944         if (pctx->polling_enabled && pctx->poll_handlers)
945                 systimer_adjust_periodic(&pctx->pollclock, pctx->pollhz);
946         else
947                 systimer_adjust_periodic(&pctx->pollclock, 1);
948         lwkt_replymsg(&msg->nm_lmsg, 0);
949 }
950
951 static void
952 poll_sysctl_regfrac(struct netmsg *msg)
953 {
954         struct pollctx *pctx;
955         uint32_t reg_frac;
956         int cpuid;
957
958         cpuid = mycpu->gd_cpuid;
959         KKASSERT(cpuid < POLLCTX_MAX);
960
961         pctx = poll_context[cpuid];
962         KKASSERT(pctx != NULL);
963         KKASSERT(pctx->poll_cpuid == cpuid);
964
965         reg_frac = msg->nm_lmsg.u.ms_result;
966         if (reg_frac > pctx->pollhz)
967                 reg_frac = pctx->pollhz;
968         else if (reg_frac < 1)
969                 reg_frac = 1;
970
971         pctx->reg_frac = reg_frac;
972         if (pctx->reg_frac_count > pctx->reg_frac)
973                 pctx->reg_frac_count = pctx->reg_frac - 1;
974
975         lwkt_replymsg(&msg->nm_lmsg, 0);
976 }
977
978 static void
979 poll_sysctl_burstmax(struct netmsg *msg)
980 {
981         struct pollctx *pctx;
982         int cpuid;
983
984         cpuid = mycpu->gd_cpuid;
985         KKASSERT(cpuid < POLLCTX_MAX);
986
987         pctx = poll_context[cpuid];
988         KKASSERT(pctx != NULL);
989         KKASSERT(pctx->poll_cpuid == cpuid);
990
991         pctx->poll_burst_max = msg->nm_lmsg.u.ms_result;
992         if (pctx->poll_each_burst > pctx->poll_burst_max)
993                 pctx->poll_each_burst = pctx->poll_burst_max;
994         if (pctx->poll_burst > pctx->poll_burst_max)
995                 pctx->poll_burst = pctx->poll_burst_max;
996         if (pctx->residual_burst > pctx->poll_burst_max)
997                 pctx->residual_burst = pctx->poll_burst_max;
998
999         lwkt_replymsg(&msg->nm_lmsg, 0);
1000 }
1001
1002 static void
1003 poll_sysctl_eachburst(struct netmsg *msg)
1004 {
1005         struct pollctx *pctx;
1006         uint32_t each_burst;
1007         int cpuid;
1008
1009         cpuid = mycpu->gd_cpuid;
1010         KKASSERT(cpuid < POLLCTX_MAX);
1011
1012         pctx = poll_context[cpuid];
1013         KKASSERT(pctx != NULL);
1014         KKASSERT(pctx->poll_cpuid == cpuid);
1015
1016         each_burst = msg->nm_lmsg.u.ms_result;
1017         if (each_burst > pctx->poll_burst_max)
1018                 each_burst = pctx->poll_burst_max;
1019         else if (each_burst < 1)
1020                 each_burst = 1;
1021         pctx->poll_each_burst = each_burst;
1022
1023         lwkt_replymsg(&msg->nm_lmsg, 0);
1024 }