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