- Move poll_burst_max adjustment out of hot code path.
[games.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.39 2007/10/01 09:37:30 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
172 /* Systimer handler */
173 static void     pollclock(systimer_t, struct intrframe *);
174
175 /* Sysctl handlers */
176 static int      sysctl_pollhz(SYSCTL_HANDLER_ARGS);
177 static int      sysctl_polling(SYSCTL_HANDLER_ARGS);
178 static int      sysctl_regfrac(SYSCTL_HANDLER_ARGS);
179 static int      sysctl_burstmax(SYSCTL_HANDLER_ARGS);
180 static void     poll_add_sysctl(struct sysctl_ctx_list *,
181                                 struct sysctl_oid_list *, struct pollctx *);
182
183 static void     schedpoll_oncpu(struct pollctx *, struct netmsg *, netisr_fn_t);
184
185 void            init_device_poll_pcpu(int);     /* per-cpu init routine */
186
187 /*
188  * Initialize per-cpu polling(4) context.  Called from kern_clock.c:
189  */
190 void
191 init_device_poll_pcpu(int cpuid)
192 {
193         struct pollctx *pctx;
194         char cpuid_str[3];
195
196         if (cpuid >= POLLCTX_MAX)
197                 return;
198
199         if (((1 << cpuid) & poll_cpumask0) == 0)
200                 return;
201
202         poll_cpumask |= (1 << cpuid);
203
204         pctx = kmalloc(sizeof(*pctx), M_DEVBUF, M_WAITOK | M_ZERO);
205
206         pctx->poll_burst = 5;
207         pctx->poll_each_burst = 5;
208         pctx->poll_burst_max = 150; /* good for 100Mbit net and HZ=1000 */
209         pctx->user_frac = 50;
210         pctx->reg_frac = 20;
211         pctx->polling_enabled = polling_enabled;
212         pctx->pollhz = pollhz;
213         pctx->poll_cpuid = cpuid;
214         netmsg_init(&pctx->poll_netmsg, &netisr_adone_rport, 0, NULL);
215         netmsg_init(&pctx->poll_more_netmsg, &netisr_adone_rport, 0, NULL);
216
217         KASSERT(cpuid < POLLCTX_MAX, ("cpu id must < %d", cpuid));
218         poll_context[cpuid] = pctx;
219
220         if (poll_defcpu < 0) {
221                 poll_defcpu = cpuid;
222
223                 /*
224                  * Initialize global sysctl nodes, for compat
225                  */
226                 poll_add_sysctl(NULL, SYSCTL_STATIC_CHILDREN(_kern_polling),
227                                 pctx);
228         }
229
230         /*
231          * Initialize per-cpu sysctl nodes
232          */
233         ksnprintf(cpuid_str, sizeof(cpuid_str), "%d", pctx->poll_cpuid);
234
235         sysctl_ctx_init(&pctx->poll_sysctl_ctx);
236         pctx->poll_sysctl_tree = SYSCTL_ADD_NODE(&pctx->poll_sysctl_ctx,
237                                  SYSCTL_STATIC_CHILDREN(_kern_polling),
238                                  OID_AUTO, cpuid_str, CTLFLAG_RD, 0, "");
239         poll_add_sysctl(&pctx->poll_sysctl_ctx,
240                         SYSCTL_CHILDREN(pctx->poll_sysctl_tree), pctx);
241
242         /*
243          * Initialize systimer
244          */
245         systimer_init_periodic_nq(&pctx->pollclock, pollclock, pctx, 1);
246 }
247
248 static __inline void
249 schedpoll(struct pollctx *pctx)
250 {
251         schedpoll_oncpu(pctx, &pctx->poll_netmsg, netisr_poll);
252 }
253
254 static __inline void
255 schedpollmore(struct pollctx *pctx)
256 {
257         schedpoll_oncpu(pctx, &pctx->poll_more_netmsg, netisr_pollmore);
258 }
259
260 /*
261  * Set the polling frequency
262  */
263 static int
264 sysctl_pollhz(SYSCTL_HANDLER_ARGS)
265 {
266         struct pollctx *pctx = arg1;
267         struct netmsg msg;
268         lwkt_port_t port;
269         int error, phz;
270
271         phz = pctx->pollhz;
272         error = sysctl_handle_int(oidp, &phz, 0, req);
273         if (error || req->newptr == NULL)
274                 return error;
275         if (phz <= 0)
276                 return EINVAL;
277         else if (phz > DEVICE_POLLING_FREQ_MAX)
278                 phz = DEVICE_POLLING_FREQ_MAX;
279
280         netmsg_init(&msg, &curthread->td_msgport, 0, poll_sysctl_pollhz);
281         msg.nm_lmsg.u.ms_result = phz;
282
283         port = cpu_portfn(pctx->poll_cpuid);
284         lwkt_domsg(port, &msg.nm_lmsg, 0);
285         return 0;
286 }
287
288 /*
289  * Master enable.
290  */
291 static int
292 sysctl_polling(SYSCTL_HANDLER_ARGS)
293 {
294         struct pollctx *pctx = arg1;
295         struct netmsg msg;
296         lwkt_port_t port;
297         int error, enabled;
298
299         enabled = pctx->polling_enabled;
300         error = sysctl_handle_int(oidp, &enabled, 0, req);
301         if (error || req->newptr == NULL)
302                 return error;
303
304         netmsg_init(&msg, &curthread->td_msgport, 0, poll_sysctl_polling);
305         msg.nm_lmsg.u.ms_result = enabled;
306
307         port = cpu_portfn(pctx->poll_cpuid);
308         lwkt_domsg(port, &msg.nm_lmsg, 0);
309         return 0;
310 }
311
312 static int
313 sysctl_regfrac(SYSCTL_HANDLER_ARGS)
314 {
315         struct pollctx *pctx = arg1;
316         struct netmsg msg;
317         lwkt_port_t port;
318         uint32_t reg_frac;
319         int error;
320
321         reg_frac = pctx->reg_frac;
322         error = sysctl_handle_int(oidp, &reg_frac, 0, req);
323         if (error || req->newptr == NULL)
324                 return error;
325
326         netmsg_init(&msg, &curthread->td_msgport, 0, poll_sysctl_regfrac);
327         msg.nm_lmsg.u.ms_result = reg_frac;
328
329         port = cpu_portfn(pctx->poll_cpuid);
330         lwkt_domsg(port, &msg.nm_lmsg, 0);
331         return 0;
332 }
333
334 static int
335 sysctl_burstmax(SYSCTL_HANDLER_ARGS)
336 {
337         struct pollctx *pctx = arg1;
338         struct netmsg msg;
339         lwkt_port_t port;
340         uint32_t burst_max;
341         int error;
342
343         burst_max = pctx->poll_burst_max;
344         error = sysctl_handle_int(oidp, &burst_max, 0, req);
345         if (error || req->newptr == NULL)
346                 return error;
347         if (burst_max < MIN_POLL_BURST_MAX)
348                 burst_max = MIN_POLL_BURST_MAX;
349         else if (burst_max > MAX_POLL_BURST_MAX)
350                 burst_max = MAX_POLL_BURST_MAX;
351
352         netmsg_init(&msg, &curthread->td_msgport, 0, poll_sysctl_burstmax);
353         msg.nm_lmsg.u.ms_result = burst_max;
354
355         port = cpu_portfn(pctx->poll_cpuid);
356         lwkt_domsg(port, &msg.nm_lmsg, 0);
357         return 0;
358 }
359
360 /*
361  * Hook from polling systimer. Tries to schedule a netisr, but keeps
362  * track of lost ticks due to the previous handler taking too long.
363  * Normally, this should not happen, because polling handler should
364  * run for a short time. However, in some cases (e.g. when there are
365  * changes in link status etc.) the drivers take a very long time
366  * (even in the order of milliseconds) to reset and reconfigure the
367  * device, causing apparent lost polls.
368  *
369  * The first part of the code is just for debugging purposes, and tries
370  * to count how often hardclock ticks are shorter than they should,
371  * meaning either stray interrupts or delayed events.
372  *
373  * WARNING! called from fastint or IPI, the MP lock might not be held.
374  */
375 static void
376 pollclock(systimer_t info, struct intrframe *frame __unused)
377 {
378         struct pollctx *pctx = info->data;
379         struct timeval t;
380         int delta;
381
382         if (pctx->poll_handlers == 0)
383                 return;
384
385         microuptime(&t);
386         delta = (t.tv_usec - pctx->prev_t.tv_usec) +
387                 (t.tv_sec - pctx->prev_t.tv_sec)*1000000;
388         if (delta * pctx->pollhz < 500000)
389                 pctx->short_ticks++;
390         else
391                 pctx->prev_t = t;
392
393         if (pctx->pending_polls > 100) {
394                 /*
395                  * Too much, assume it has stalled (not always true
396                  * see comment above).
397                  */
398                 pctx->stalled++;
399                 pctx->pending_polls = 0;
400                 pctx->phase = 0;
401         }
402
403         if (pctx->phase <= 2) {
404                 if (pctx->phase != 0)
405                         pctx->suspect++;
406                 pctx->phase = 1;
407                 schedpoll(pctx);
408                 pctx->phase = 2;
409         }
410         if (pctx->pending_polls++ > 0)
411                 pctx->lost_polls++;
412 }
413
414 /*
415  * netisr_pollmore is called after other netisr's, possibly scheduling
416  * another NETISR_POLL call, or adapting the burst size for the next cycle.
417  *
418  * It is very bad to fetch large bursts of packets from a single card at once,
419  * because the burst could take a long time to be completely processed, or
420  * could saturate the intermediate queue (ipintrq or similar) leading to
421  * losses or unfairness. To reduce the problem, and also to account better for
422  * time spent in network-related processing, we split the burst in smaller
423  * chunks of fixed size, giving control to the other netisr's between chunks.
424  * This helps in improving the fairness, reducing livelock (because we
425  * emulate more closely the "process to completion" that we have with
426  * fastforwarding) and accounting for the work performed in low level
427  * handling and forwarding.
428  */
429
430 /* ARGSUSED */
431 static void
432 netisr_pollmore(struct netmsg *msg)
433 {
434         struct pollctx *pctx;
435         struct timeval t;
436         int kern_load, cpuid;
437
438         cpuid = mycpu->gd_cpuid;
439         KKASSERT(cpuid < POLLCTX_MAX);
440
441         pctx = poll_context[cpuid];
442         KKASSERT(pctx != NULL);
443         KKASSERT(pctx->poll_cpuid == cpuid);
444         KKASSERT(pctx == msg->nm_lmsg.u.ms_resultp);
445
446         lwkt_replymsg(&msg->nm_lmsg, 0);
447
448         pctx->phase = 5;
449         if (pctx->residual_burst > 0) {
450                 schedpoll(pctx);
451                 /* will run immediately on return, followed by netisrs */
452                 return;
453         }
454         /* here we can account time spent in netisr's in this tick */
455         microuptime(&t);
456         kern_load = (t.tv_usec - pctx->poll_start_t.tv_usec) +
457                 (t.tv_sec - pctx->poll_start_t.tv_sec)*1000000; /* us */
458         kern_load = (kern_load * pctx->pollhz) / 10000;         /* 0..100 */
459         if (kern_load > (100 - pctx->user_frac)) { /* try decrease ticks */
460                 if (pctx->poll_burst > 1)
461                         pctx->poll_burst--;
462         } else {
463                 if (pctx->poll_burst < pctx->poll_burst_max)
464                         pctx->poll_burst++;
465         }
466
467         pctx->pending_polls--;
468         if (pctx->pending_polls == 0) { /* we are done */
469                 pctx->phase = 0;
470         } else {
471                 /*
472                  * Last cycle was long and caused us to miss one or more
473                  * hardclock ticks. Restart processing again, but slightly
474                  * reduce the burst size to prevent that this happens again.
475                  */
476                 pctx->poll_burst -= (pctx->poll_burst / 8);
477                 if (pctx->poll_burst < 1)
478                         pctx->poll_burst = 1;
479                 schedpoll(pctx);
480                 pctx->phase = 6;
481         }
482 }
483
484 /*
485  * netisr_poll is scheduled by schedpoll when appropriate, typically once
486  * per polling systimer tick.
487  *
488  * Note that the message is replied immediately in order to allow a new
489  * ISR to be scheduled in the handler.
490  *
491  * XXX each registration should indicate whether it needs a critical
492  * section to operate.
493  */
494 /* ARGSUSED */
495 static void
496 netisr_poll(struct netmsg *msg)
497 {
498         struct pollctx *pctx;
499         int i, cycles, cpuid;
500         enum poll_cmd arg = POLL_ONLY;
501
502         cpuid = mycpu->gd_cpuid;
503         KKASSERT(cpuid < POLLCTX_MAX);
504
505         pctx = poll_context[cpuid];
506         KKASSERT(pctx != NULL);
507         KKASSERT(pctx->poll_cpuid == cpuid);
508         KKASSERT(pctx == msg->nm_lmsg.u.ms_resultp);
509
510         lwkt_replymsg(&msg->nm_lmsg, 0);
511
512         pctx->phase = 3;
513         if (pctx->residual_burst == 0) { /* first call in this tick */
514                 microuptime(&pctx->poll_start_t);
515                 /*
516                  * Check that paremeters are consistent with runtime
517                  * variables. Some of these tests could be done at sysctl
518                  * time, but the savings would be very limited because we
519                  * still have to check against reg_frac_count and
520                  * poll_each_burst. So, instead of writing separate sysctl
521                  * handlers, we do all here.
522                  */
523
524                 if (pctx->reg_frac_count-- == 0) {
525                         arg = POLL_AND_CHECK_STATUS;
526                         pctx->reg_frac_count = pctx->reg_frac - 1;
527                 }
528
529                 if (pctx->poll_each_burst < 1)
530                         pctx->poll_each_burst = 1;
531                 else if (pctx->poll_each_burst > pctx->poll_burst_max)
532                         pctx->poll_each_burst = pctx->poll_burst_max;
533
534                 pctx->residual_burst = pctx->poll_burst;
535         }
536         cycles = (pctx->residual_burst < pctx->poll_each_burst) ?
537                 pctx->residual_burst : pctx->poll_each_burst;
538         pctx->residual_burst -= cycles;
539
540         if (pctx->polling_enabled) {
541                 for (i = 0 ; i < pctx->poll_handlers ; i++) {
542                         struct ifnet *ifp = pctx->pr[i].ifp;
543
544                         if (!lwkt_serialize_try(ifp->if_serializer))
545                                 continue;
546
547                         if ((ifp->if_flags & (IFF_UP|IFF_RUNNING|IFF_POLLING))
548                             == (IFF_UP|IFF_RUNNING|IFF_POLLING))
549                                 ifp->if_poll(ifp, arg, cycles);
550
551                         lwkt_serialize_exit(ifp->if_serializer);
552                 }
553         } else {        /* unregister */
554                 for (i = 0 ; i < pctx->poll_handlers ; i++) {
555                         struct ifnet *ifp = pctx->pr[i].ifp;
556
557                         lwkt_serialize_enter(ifp->if_serializer);
558
559                         if ((ifp->if_flags & IFF_POLLING) == 0) {
560                                 KKASSERT(ifp->if_poll_cpuid < 0);
561                                 lwkt_serialize_exit(ifp->if_serializer);
562                                 continue;
563                         }
564                         ifp->if_flags &= ~IFF_POLLING;
565                         ifp->if_poll_cpuid = -1;
566
567                         /*
568                          * Only call the interface deregistration
569                          * function if the interface is still 
570                          * running.
571                          */
572                         if (ifp->if_flags & IFF_RUNNING)
573                                 ifp->if_poll(ifp, POLL_DEREGISTER, 1);
574
575                         lwkt_serialize_exit(ifp->if_serializer);
576                 }
577                 pctx->residual_burst = 0;
578                 pctx->poll_handlers = 0;
579         }
580         schedpollmore(pctx);
581         pctx->phase = 4;
582 }
583
584 static void
585 poll_register(struct netmsg *msg)
586 {
587         struct ifnet *ifp = msg->nm_lmsg.u.ms_resultp;
588         struct pollctx *pctx;
589         int rc, cpuid;
590
591         cpuid = mycpu->gd_cpuid;
592         KKASSERT(cpuid < POLLCTX_MAX);
593
594         pctx = poll_context[cpuid];
595         KKASSERT(pctx != NULL);
596         KKASSERT(pctx->poll_cpuid == cpuid);
597
598         if (pctx->polling_enabled == 0) {
599                 /* Polling disabled, cannot register */
600                 rc = EOPNOTSUPP;
601                 goto back;
602         }
603
604         /*
605          * Check if there is room.
606          */
607         if (pctx->poll_handlers >= POLL_LIST_LEN) {
608                 /*
609                  * List full, cannot register more entries.
610                  * This should never happen; if it does, it is probably a
611                  * broken driver trying to register multiple times. Checking
612                  * this at runtime is expensive, and won't solve the problem
613                  * anyways, so just report a few times and then give up.
614                  */
615                 static int verbose = 10;        /* XXX */
616                 if (verbose >0) {
617                         kprintf("poll handlers list full, "
618                                 "maybe a broken driver ?\n");
619                         verbose--;
620                 }
621                 rc = ENOMEM;
622         } else {
623                 pctx->pr[pctx->poll_handlers].ifp = ifp;
624                 pctx->poll_handlers++;
625                 rc = 0;
626
627                 if (pctx->poll_handlers == 1) {
628                         KKASSERT(pctx->polling_enabled);
629                         systimer_adjust_periodic(&pctx->pollclock,
630                                                  pctx->pollhz);
631                 }
632         }
633 back:
634         lwkt_replymsg(&msg->nm_lmsg, rc);
635 }
636
637 /*
638  * Try to register routine for polling. Returns 1 if successful
639  * (and polling should be enabled), 0 otherwise.
640  *
641  * Called from mainline code only, not called from an interrupt.
642  */
643 int
644 ether_poll_register(struct ifnet *ifp)
645 {
646         if (poll_defcpu < 0)
647                 return 0;
648         KKASSERT(poll_defcpu < POLLCTX_MAX);
649
650         return ether_pollcpu_register(ifp, poll_defcpu);
651 }
652
653 int
654 ether_pollcpu_register(struct ifnet *ifp, int cpuid)
655 {
656         struct netmsg msg;
657         lwkt_port_t port;
658         int rc;
659
660         if (ifp->if_poll == NULL) {
661                 /* Device does not support polling */
662                 return 0;
663         }
664
665         if (cpuid < 0 || cpuid >= POLLCTX_MAX)
666                 return 0;
667
668         if (((1 << cpuid) & poll_cpumask) == 0) {
669                 /* Polling is not supported on 'cpuid' */
670                 return 0;
671         }
672         KKASSERT(poll_context[cpuid] != NULL);
673
674         /*
675          * Attempt to register.  Interlock with IFF_POLLING.
676          */
677         crit_enter();   /* XXX MP - not mp safe */
678
679         lwkt_serialize_enter(ifp->if_serializer);
680         if (ifp->if_flags & IFF_POLLING) {
681                 /* Already polling */
682                 KKASSERT(ifp->if_poll_cpuid >= 0);
683                 lwkt_serialize_exit(ifp->if_serializer);
684                 crit_exit();
685                 return 0;
686         }
687         KKASSERT(ifp->if_poll_cpuid < 0);
688         ifp->if_flags |= IFF_POLLING;
689         ifp->if_poll_cpuid = cpuid;
690         if (ifp->if_flags & IFF_RUNNING)
691                 ifp->if_poll(ifp, POLL_REGISTER, 0);
692         lwkt_serialize_exit(ifp->if_serializer);
693
694         netmsg_init(&msg, &curthread->td_msgport, 0, poll_register);
695         msg.nm_lmsg.u.ms_resultp = ifp;
696
697         port = cpu_portfn(cpuid);
698         lwkt_domsg(port, &msg.nm_lmsg, 0);
699
700         if (msg.nm_lmsg.ms_error) {
701                 lwkt_serialize_enter(ifp->if_serializer);
702                 ifp->if_flags &= ~IFF_POLLING;
703                 ifp->if_poll_cpuid = -1;
704                 if (ifp->if_flags & IFF_RUNNING)
705                         ifp->if_poll(ifp, POLL_DEREGISTER, 0);
706                 lwkt_serialize_exit(ifp->if_serializer);
707                 rc = 0;
708         } else {
709                 rc = 1;
710         }
711
712         crit_exit();
713         return rc;
714 }
715
716 static void
717 poll_deregister(struct netmsg *msg)
718 {
719         struct ifnet *ifp = msg->nm_lmsg.u.ms_resultp;
720         struct pollctx *pctx;
721         int rc, i, cpuid;
722
723         cpuid = mycpu->gd_cpuid;
724         KKASSERT(cpuid < POLLCTX_MAX);
725
726         pctx = poll_context[cpuid];
727         KKASSERT(pctx != NULL);
728         KKASSERT(pctx->poll_cpuid == cpuid);
729
730         for (i = 0 ; i < pctx->poll_handlers ; i++) {
731                 if (pctx->pr[i].ifp == ifp) /* Found it */
732                         break;
733         }
734         if (i == pctx->poll_handlers) {
735                 kprintf("ether_poll_deregister: ifp not found!!!\n");
736                 rc = ENOENT;
737         } else {
738                 pctx->poll_handlers--;
739                 if (i < pctx->poll_handlers) {
740                         /* Last entry replaces this one. */
741                         pctx->pr[i].ifp = pctx->pr[pctx->poll_handlers].ifp;
742                 }
743
744                 if (pctx->poll_handlers == 0)
745                         systimer_adjust_periodic(&pctx->pollclock, 1);
746                 rc = 0;
747         }
748         lwkt_replymsg(&msg->nm_lmsg, rc);
749 }
750
751 /*
752  * Remove interface from the polling list.  Occurs when polling is turned
753  * off.  Called from mainline code only, not called from an interrupt.
754  */
755 int
756 ether_poll_deregister(struct ifnet *ifp)
757 {
758         struct netmsg msg;
759         lwkt_port_t port;
760         int rc, cpuid;
761
762         KKASSERT(ifp != NULL);
763
764         if (ifp->if_poll == NULL)
765                 return 0;
766
767         crit_enter();
768
769         lwkt_serialize_enter(ifp->if_serializer);
770         if ((ifp->if_flags & IFF_POLLING) == 0) {
771                 KKASSERT(ifp->if_poll_cpuid < 0);
772                 lwkt_serialize_exit(ifp->if_serializer);
773                 crit_exit();
774                 return 0;
775         }
776
777         cpuid = ifp->if_poll_cpuid;
778         KKASSERT(cpuid >= 0);
779         KKASSERT(poll_context[cpuid] != NULL);
780
781         ifp->if_flags &= ~IFF_POLLING;
782         ifp->if_poll_cpuid = -1;
783         lwkt_serialize_exit(ifp->if_serializer);
784
785         netmsg_init(&msg, &curthread->td_msgport, 0, poll_deregister);
786         msg.nm_lmsg.u.ms_resultp = ifp;
787
788         port = cpu_portfn(cpuid);
789         lwkt_domsg(port, &msg.nm_lmsg, 0);
790
791         if (!msg.nm_lmsg.ms_error) {
792                 lwkt_serialize_enter(ifp->if_serializer);
793                 if (ifp->if_flags & IFF_RUNNING)
794                         ifp->if_poll(ifp, POLL_DEREGISTER, 1);
795                 lwkt_serialize_exit(ifp->if_serializer);
796                 rc = 1;
797         } else {
798                 rc = 0;
799         }
800
801         crit_exit();
802         return rc;
803 }
804
805 static void
806 poll_add_sysctl(struct sysctl_ctx_list *ctx, struct sysctl_oid_list *parent,
807                 struct pollctx *pctx)
808 {
809         SYSCTL_ADD_PROC(ctx, parent, OID_AUTO, "enable",
810                         CTLTYPE_INT | CTLFLAG_RW, pctx, 0, sysctl_polling,
811                         "I", "Polling enabled");
812
813         SYSCTL_ADD_PROC(ctx, parent, OID_AUTO, "pollhz",
814                         CTLTYPE_INT | CTLFLAG_RW, pctx, 0, sysctl_pollhz,
815                         "I", "Device polling frequency");
816
817         SYSCTL_ADD_PROC(ctx, parent, OID_AUTO, "reg_frac",
818                         CTLTYPE_UINT | CTLFLAG_RW, pctx, 0, sysctl_regfrac,
819                         "IU", "Every this many cycles poll register");
820
821         SYSCTL_ADD_PROC(ctx, parent, OID_AUTO, "burst_max",
822                         CTLTYPE_UINT | CTLFLAG_RW, pctx, 0, sysctl_burstmax,
823                         "IU", "Max Polling burst size");
824
825         SYSCTL_ADD_UINT(ctx, parent, OID_AUTO, "phase", CTLFLAG_RD,
826                         &pctx->phase, 0, "Polling phase");
827
828         SYSCTL_ADD_UINT(ctx, parent, OID_AUTO, "suspect", CTLFLAG_RW,
829                         &pctx->suspect, 0, "suspect event");
830
831         SYSCTL_ADD_UINT(ctx, parent, OID_AUTO, "stalled", CTLFLAG_RW,
832                         &pctx->stalled, 0, "potential stalls");
833
834         SYSCTL_ADD_UINT(ctx, parent, OID_AUTO, "burst", CTLFLAG_RD,
835                         &pctx->poll_burst, 0, "Current polling burst size");
836
837         SYSCTL_ADD_UINT(ctx, parent, OID_AUTO, "each_burst", CTLFLAG_RW,
838                         &pctx->poll_each_burst, 0, "Max size of each burst");
839
840         SYSCTL_ADD_UINT(ctx, parent, OID_AUTO, "user_frac", CTLFLAG_RW,
841                         &pctx->user_frac, 0,
842                         "Desired user fraction of cpu time");
843
844         SYSCTL_ADD_UINT(ctx, parent, OID_AUTO, "short_ticks", CTLFLAG_RW,
845                         &pctx->short_ticks, 0,
846                         "Hardclock ticks shorter than they should be");
847
848         SYSCTL_ADD_UINT(ctx, parent, OID_AUTO, "lost_polls", CTLFLAG_RW,
849                         &pctx->lost_polls, 0,
850                         "How many times we would have lost a poll tick");
851
852         SYSCTL_ADD_UINT(ctx, parent, OID_AUTO, "pending_polls", CTLFLAG_RD,
853                         &pctx->pending_polls, 0, "Do we need to poll again");
854
855         SYSCTL_ADD_INT(ctx, parent, OID_AUTO, "residual_burst", CTLFLAG_RD,
856                        &pctx->residual_burst, 0,
857                        "# of residual cycles in burst");
858
859         SYSCTL_ADD_UINT(ctx, parent, OID_AUTO, "handlers", CTLFLAG_RD,
860                         &pctx->poll_handlers, 0,
861                         "Number of registered poll handlers");
862 }
863
864 static void
865 schedpoll_oncpu(struct pollctx *pctx, struct netmsg *msg, netisr_fn_t handler)
866 {
867         if (msg->nm_lmsg.ms_flags & MSGF_DONE) {
868                 lwkt_port_t port;
869
870                 netmsg_init(msg, &netisr_adone_rport, 0, handler);
871 #ifdef INVARIANTS
872                 msg->nm_lmsg.u.ms_resultp = pctx;
873 #endif
874                 port = cpu_portfn(mycpu->gd_cpuid);
875                 lwkt_sendmsg(port, &msg->nm_lmsg);
876         }
877 }
878
879 static void
880 poll_sysctl_pollhz(struct netmsg *msg)
881 {
882         struct pollctx *pctx;
883         int cpuid;
884
885         cpuid = mycpu->gd_cpuid;
886         KKASSERT(cpuid < POLLCTX_MAX);
887
888         pctx = poll_context[cpuid];
889         KKASSERT(pctx != NULL);
890         KKASSERT(pctx->poll_cpuid == cpuid);
891
892         /*
893          * If polling is disabled or there is no device registered,
894          * don't adjust polling systimer frequency.
895          * Polling systimer frequency will be adjusted once polling
896          * is enabled and there are registered devices.
897          */
898         pctx->pollhz = msg->nm_lmsg.u.ms_result;
899         if (pctx->polling_enabled && pctx->poll_handlers)
900                 systimer_adjust_periodic(&pctx->pollclock, pctx->pollhz);
901
902         /*
903          * Make sure that reg_frac and reg_frac_count are within valid range.
904          */
905         if (pctx->reg_frac > pctx->pollhz) {
906                 pctx->reg_frac = pctx->pollhz;
907                 if (pctx->reg_frac_count > pctx->reg_frac)
908                         pctx->reg_frac_count = pctx->reg_frac - 1;
909         }
910
911         lwkt_replymsg(&msg->nm_lmsg, 0);
912 }
913
914 static void
915 poll_sysctl_polling(struct netmsg *msg)
916 {
917         struct pollctx *pctx;
918         int cpuid;
919
920         cpuid = mycpu->gd_cpuid;
921         KKASSERT(cpuid < POLLCTX_MAX);
922
923         pctx = poll_context[cpuid];
924         KKASSERT(pctx != NULL);
925         KKASSERT(pctx->poll_cpuid == cpuid);
926
927         /*
928          * If polling is disabled or there is no device registered,
929          * cut the polling systimer frequency to 1hz.
930          */
931         pctx->polling_enabled = msg->nm_lmsg.u.ms_result;
932         if (pctx->polling_enabled && pctx->poll_handlers)
933                 systimer_adjust_periodic(&pctx->pollclock, pctx->pollhz);
934         else
935                 systimer_adjust_periodic(&pctx->pollclock, 1);
936         lwkt_replymsg(&msg->nm_lmsg, 0);
937 }
938
939 static void
940 poll_sysctl_regfrac(struct netmsg *msg)
941 {
942         struct pollctx *pctx;
943         uint32_t reg_frac;
944         int cpuid;
945
946         cpuid = mycpu->gd_cpuid;
947         KKASSERT(cpuid < POLLCTX_MAX);
948
949         pctx = poll_context[cpuid];
950         KKASSERT(pctx != NULL);
951         KKASSERT(pctx->poll_cpuid == cpuid);
952
953         reg_frac = msg->nm_lmsg.u.ms_result;
954         if (reg_frac > pctx->pollhz)
955                 reg_frac = pctx->pollhz;
956         else if (reg_frac < 1)
957                 reg_frac = 1;
958
959         pctx->reg_frac = reg_frac;
960         if (pctx->reg_frac_count > pctx->reg_frac)
961                 pctx->reg_frac_count = pctx->reg_frac - 1;
962
963         lwkt_replymsg(&msg->nm_lmsg, 0);
964 }
965
966 static void
967 poll_sysctl_burstmax(struct netmsg *msg)
968 {
969         struct pollctx *pctx;
970         int cpuid;
971
972         cpuid = mycpu->gd_cpuid;
973         KKASSERT(cpuid < POLLCTX_MAX);
974
975         pctx = poll_context[cpuid];
976         KKASSERT(pctx != NULL);
977         KKASSERT(pctx->poll_cpuid == cpuid);
978
979         pctx->poll_burst_max = msg->nm_lmsg.u.ms_result;
980         if (pctx->poll_each_burst > pctx->poll_burst_max)
981                 pctx->poll_each_burst = pctx->poll_burst_max;
982         if (pctx->poll_burst > pctx->poll_burst_max)
983                 pctx->poll_burst = pctx->poll_burst_max;
984         if (pctx->residual_burst > pctx->poll_burst_max)
985                 pctx->residual_burst = pctx->poll_burst_max;
986
987         lwkt_replymsg(&msg->nm_lmsg, 0);
988 }