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