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