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