__P(); not anymore in this directory
[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.4 2003/07/22 22:10:51 dillon Exp $
29  */
30
31 #include <sys/param.h>
32 #include <sys/systm.h>
33 #include <sys/kernel.h>
34 #include <sys/socket.h>                 /* needed by net/if.h           */
35 #include <sys/sysctl.h>
36
37 #include <i386/include/md_var.h>        /* for vm_page_zero_idle()      */
38 #include <net/if.h>                     /* for IFF_* flags              */
39 #include <net/netisr.h>                 /* for NETISR_POLL              */
40
41 #ifdef SMP
42 #include "opt_lint.h"
43 #ifndef COMPILING_LINT
44 #error DEVICE_POLLING is not compatible with SMP
45 #endif
46 #endif
47
48 static void netisr_poll(void);          /* the two netisr handlers      */
49 static void netisr_pollmore(void);
50
51 void init_device_poll(void);            /* init routine                 */
52 void hardclock_device_poll(void);       /* hook from hardclock          */
53 void ether_poll(int);                   /* polling while in trap        */
54 int idle_poll(void);                    /* poll while in idle loop      */
55
56 /*
57  * Polling support for [network] device drivers.
58  *
59  * Drivers which support this feature try to register with the
60  * polling code.
61  *
62  * If registration is successful, the driver must disable interrupts,
63  * and further I/O is performed through the handler, which is invoked
64  * (at least once per clock tick) with 3 arguments: the "arg" passed at
65  * register time (a struct ifnet pointer), a command, and a "count" limit.
66  *
67  * The command can be one of the following:
68  *  POLL_ONLY: quick move of "count" packets from input/output queues.
69  *  POLL_AND_CHECK_STATUS: as above, plus check status registers or do
70  *      other more expensive operations. This command is issued periodically
71  *      but less frequently than POLL_ONLY.
72  *  POLL_DEREGISTER: deregister and return to interrupt mode.
73  *
74  * The first two commands are only issued if the interface is marked as
75  * 'IFF_UP and IFF_RUNNING', the last one only if IFF_RUNNING is set.
76  *
77  * The count limit specifies how much work the handler can do during the
78  * call -- typically this is the number of packets to be received, or
79  * transmitted, etc. (drivers are free to interpret this number, as long
80  * as the max time spent in the function grows roughly linearly with the
81  * count).
82  *
83  * Deregistration can be requested by the driver itself (typically in the
84  * *_stop() routine), or by the polling code, by invoking the handler.
85  *
86  * Polling can be globally enabled or disabled with the sysctl variable
87  * kern.polling.enable (default is 0, disabled)
88  *
89  * A second variable controls the sharing of CPU between polling/kernel
90  * network processing, and other activities (typically userlevel tasks):
91  * kern.polling.user_frac (between 0 and 100, default 50) sets the share
92  * of CPU allocated to user tasks. CPU is allocated proportionally to the
93  * shares, by dynamically adjusting the "count" (poll_burst).
94  *
95  * Other parameters can should be left to their default values.
96  * The following constraints hold
97  *
98  *      1 <= poll_each_burst <= poll_burst <= poll_burst_max
99  *      0 <= poll_in_trap <= poll_each_burst
100  *      MIN_POLL_BURST_MAX <= poll_burst_max <= MAX_POLL_BURST_MAX
101  */
102
103 #define MIN_POLL_BURST_MAX      10
104 #define MAX_POLL_BURST_MAX      1000
105
106 SYSCTL_NODE(_kern, OID_AUTO, polling, CTLFLAG_RW, 0,
107         "Device polling parameters");
108
109 static u_int32_t poll_burst = 5;
110 SYSCTL_UINT(_kern_polling, OID_AUTO, burst, CTLFLAG_RW,
111         &poll_burst, 0, "Current polling burst size");
112
113 static u_int32_t poll_each_burst = 5;
114 SYSCTL_UINT(_kern_polling, OID_AUTO, each_burst, CTLFLAG_RW,
115         &poll_each_burst, 0, "Max size of each burst");
116
117 static u_int32_t poll_burst_max = 150;  /* good for 100Mbit net and HZ=1000 */
118 SYSCTL_UINT(_kern_polling, OID_AUTO, burst_max, CTLFLAG_RW,
119         &poll_burst_max, 0, "Max Polling burst size");
120
121 static u_int32_t poll_in_idle_loop=1;           /* do we poll in idle loop ? */
122 SYSCTL_UINT(_kern_polling, OID_AUTO, idle_poll, CTLFLAG_RW,
123         &poll_in_idle_loop, 0, "Enable device polling in idle loop");
124
125 u_int32_t poll_in_trap;                 /* used in trap.c */
126 SYSCTL_UINT(_kern_polling, OID_AUTO, poll_in_trap, CTLFLAG_RW,
127         &poll_in_trap, 0, "Poll burst size during a trap");
128
129 static u_int32_t user_frac = 50;
130 SYSCTL_UINT(_kern_polling, OID_AUTO, user_frac, CTLFLAG_RW,
131         &user_frac, 0, "Desired user fraction of cpu time");
132
133 static u_int32_t reg_frac = 20 ;
134 SYSCTL_UINT(_kern_polling, OID_AUTO, reg_frac, CTLFLAG_RW,
135         &reg_frac, 0, "Every this many cycles poll register");
136
137 static u_int32_t short_ticks;
138 SYSCTL_UINT(_kern_polling, OID_AUTO, short_ticks, CTLFLAG_RW,
139         &short_ticks, 0, "Hardclock ticks shorter than they should be");
140
141 static u_int32_t lost_polls;
142 SYSCTL_UINT(_kern_polling, OID_AUTO, lost_polls, CTLFLAG_RW,
143         &lost_polls, 0, "How many times we would have lost a poll tick");
144
145 static u_int32_t pending_polls;
146 SYSCTL_UINT(_kern_polling, OID_AUTO, pending_polls, CTLFLAG_RW,
147         &pending_polls, 0, "Do we need to poll again");
148
149 static int residual_burst = 0;
150 SYSCTL_INT(_kern_polling, OID_AUTO, residual_burst, CTLFLAG_RW,
151         &residual_burst, 0, "# of residual cycles in burst");
152
153 static u_int32_t poll_handlers; /* next free entry in pr[]. */
154 SYSCTL_UINT(_kern_polling, OID_AUTO, handlers, CTLFLAG_RD,
155         &poll_handlers, 0, "Number of registered poll handlers");
156
157 static int polling = 0;         /* global polling enable */
158 SYSCTL_UINT(_kern_polling, OID_AUTO, enable, CTLFLAG_RW,
159         &polling, 0, "Polling enabled");
160
161 static u_int32_t phase;
162 SYSCTL_UINT(_kern_polling, OID_AUTO, phase, CTLFLAG_RW,
163         &phase, 0, "Polling phase");
164
165 static u_int32_t suspect;
166 SYSCTL_UINT(_kern_polling, OID_AUTO, suspect, CTLFLAG_RW,
167         &suspect, 0, "suspect event");
168
169 static u_int32_t stalled;
170 SYSCTL_UINT(_kern_polling, OID_AUTO, stalled, CTLFLAG_RW,
171         &stalled, 0, "potential stalls");
172
173
174 #define POLL_LIST_LEN  128
175 struct pollrec {
176         poll_handler_t  *handler;
177         struct ifnet    *ifp;
178 };
179
180 static struct pollrec pr[POLL_LIST_LEN];
181
182 /*
183  * register relevant netisr. Called from kern_clock.c:
184  */
185 void
186 init_device_poll(void)
187 {
188         register_netisr(NETISR_POLL, netisr_poll);
189         register_netisr(NETISR_POLLMORE, netisr_pollmore);
190 }
191
192 /*
193  * Hook from hardclock. Tries to schedule a netisr, but keeps track
194  * of lost ticks due to the previous handler taking too long.
195  * Normally, this should not happen, because polling handler should
196  * run for a short time. However, in some cases (e.g. when there are
197  * changes in link status etc.) the drivers take a very long time
198  * (even in the order of milliseconds) to reset and reconfigure the
199  * device, causing apparent lost polls.
200  *
201  * The first part of the code is just for debugging purposes, and tries
202  * to count how often hardclock ticks are shorter than they should,
203  * meaning either stray interrupts or delayed events.
204  */
205 void
206 hardclock_device_poll(void)
207 {
208         static struct timeval prev_t, t;
209         int delta;
210
211         if (poll_handlers == 0)
212                 return;
213
214         microuptime(&t);
215         delta = (t.tv_usec - prev_t.tv_usec) +
216                 (t.tv_sec - prev_t.tv_sec)*1000000;
217         if (delta * hz < 500000)
218                 short_ticks++;
219         else
220                 prev_t = t;
221
222         if (pending_polls > 100) {
223                 /*
224                  * Too much, assume it has stalled (not always true
225                  * see comment above).
226                  */
227                 stalled++;
228                 pending_polls = 0;
229                 phase = 0;
230         }
231
232         if (phase <= 2) {
233                 if (phase != 0)
234                         suspect++;
235                 phase = 1;
236                 schednetisr(NETISR_POLL);
237                 phase = 2;
238         }
239         if (pending_polls++ > 0)
240                 lost_polls++;
241 }
242
243 /*
244  * ether_poll is called from the idle loop or from the trap handler.
245  */
246 void
247 ether_poll(int count)
248 {
249         int i;
250         int s = splimp();
251
252         if (count > poll_each_burst)
253                 count = poll_each_burst;
254         for (i = 0 ; i < poll_handlers ; i++)
255                 if (pr[i].handler && (IFF_UP|IFF_RUNNING) ==
256                     (pr[i].ifp->if_flags & (IFF_UP|IFF_RUNNING)) )
257                         pr[i].handler(pr[i].ifp, 0, count); /* quick check */
258         splx(s);
259 }
260
261 /*
262  * idle_poll is replaces the body of the idle loop when DEVICE_POLLING
263  * is used.  YYY not currently implemented.
264  */
265 int
266 idle_poll(void)
267 {
268         if (poll_in_idle_loop && poll_handlers > 0) {
269                 int s = splimp();
270                 cpu_enable_intr();
271                 ether_poll(poll_each_burst);
272                 cpu_disable_intr();
273                 splx(s);
274                 vm_page_zero_idle();
275                 return 1;
276         } else
277                 return vm_page_zero_idle();
278 }
279
280 /*
281  * netisr_pollmore is called after other netisr's, possibly scheduling
282  * another NETISR_POLL call, or adapting the burst size for the next cycle.
283  *
284  * It is very bad to fetch large bursts of packets from a single card at once,
285  * because the burst could take a long time to be completely processed, or
286  * could saturate the intermediate queue (ipintrq or similar) leading to
287  * losses or unfairness. To reduce the problem, and also to account better for
288  * time spent in network-related processing, we split the burst in smaller
289  * chunks of fixed size, giving control to the other netisr's between chunks.
290  * This helps in improving the fairness, reducing livelock (because we
291  * emulate more closely the "process to completion" that we have with
292  * fastforwarding) and accounting for the work performed in low level
293  * handling and forwarding.
294  */
295
296
297 static struct timeval poll_start_t;
298
299 static void
300 netisr_pollmore()
301 {
302         struct timeval t;
303         int kern_load;
304         int s = splhigh();
305
306         phase = 5;
307         if (residual_burst > 0) {
308                 schednetisr(NETISR_POLL);
309                 /* will run immediately on return, followed by netisrs */
310                 splx(s);
311                 return ;
312         }
313         /* here we can account time spent in netisr's in this tick */
314         microuptime(&t);
315         kern_load = (t.tv_usec - poll_start_t.tv_usec) +
316                 (t.tv_sec - poll_start_t.tv_sec)*1000000;       /* us */
317         kern_load = (kern_load * hz) / 10000;                   /* 0..100 */
318         if (kern_load > (100 - user_frac)) { /* try decrease ticks */
319                 if (poll_burst > 1)
320                         poll_burst--;
321         } else {
322                 if (poll_burst < poll_burst_max)
323                         poll_burst++;
324         }
325
326         pending_polls--;
327         if (pending_polls == 0) /* we are done */
328                 phase = 0;
329         else {
330                 /*
331                  * Last cycle was long and caused us to miss one or more
332                  * hardclock ticks. Restart processing again, but slightly
333                  * reduce the burst size to prevent that this happens again.
334                  */
335                 poll_burst -= (poll_burst / 8);
336                 if (poll_burst < 1)
337                         poll_burst = 1;
338                 schednetisr(NETISR_POLL);
339                 phase = 6;
340         }
341         splx(s);
342 }
343
344 /*
345  * netisr_poll is scheduled by schednetisr when appropriate, typically once
346  * per tick. It is called at splnet() so first thing to do is to upgrade to
347  * splimp(), and call all registered handlers.
348  */
349 static void
350 netisr_poll(void)
351 {
352         static int reg_frac_count;
353         int i, cycles;
354         enum poll_cmd arg = POLL_ONLY;
355         int s=splimp();
356
357         phase = 3;
358         if (residual_burst == 0) { /* first call in this tick */
359                 microuptime(&poll_start_t);
360                 /*
361                  * Check that paremeters are consistent with runtime
362                  * variables. Some of these tests could be done at sysctl
363                  * time, but the savings would be very limited because we
364                  * still have to check against reg_frac_count and
365                  * poll_each_burst. So, instead of writing separate sysctl
366                  * handlers, we do all here.
367                  */
368
369                 if (reg_frac > hz)
370                         reg_frac = hz;
371                 else if (reg_frac < 1)
372                         reg_frac = 1;
373                 if (reg_frac_count > reg_frac)
374                         reg_frac_count = reg_frac - 1;
375                 if (reg_frac_count-- == 0) {
376                         arg = POLL_AND_CHECK_STATUS;
377                         reg_frac_count = reg_frac - 1;
378                 }
379                 if (poll_burst_max < MIN_POLL_BURST_MAX)
380                         poll_burst_max = MIN_POLL_BURST_MAX;
381                 else if (poll_burst_max > MAX_POLL_BURST_MAX)
382                         poll_burst_max = MAX_POLL_BURST_MAX;
383
384                 if (poll_each_burst < 1)
385                         poll_each_burst = 1;
386                 else if (poll_each_burst > poll_burst_max)
387                         poll_each_burst = poll_burst_max;
388
389                 residual_burst = poll_burst;
390         }
391         cycles = (residual_burst < poll_each_burst) ?
392                 residual_burst : poll_each_burst;
393         residual_burst -= cycles;
394
395         if (polling) {
396                 for (i = 0 ; i < poll_handlers ; i++)
397                         if (pr[i].handler && (IFF_UP|IFF_RUNNING) ==
398                             (pr[i].ifp->if_flags & (IFF_UP|IFF_RUNNING)) )
399                                 pr[i].handler(pr[i].ifp, arg, cycles);
400         } else {        /* unregister */
401                 for (i = 0 ; i < poll_handlers ; i++) {
402                         if (pr[i].handler &&
403                             pr[i].ifp->if_flags & IFF_RUNNING) {
404                                 pr[i].ifp->if_ipending &= ~IFF_POLLING;
405                                 pr[i].handler(pr[i].ifp, POLL_DEREGISTER, 1);
406                         }
407                         pr[i].handler=NULL;
408                 }
409                 residual_burst = 0;
410                 poll_handlers = 0;
411         }
412         schednetisr(NETISR_POLLMORE);
413         phase = 4;
414         splx(s);
415 }
416
417 /*
418  * Try to register routine for polling. Returns 1 if successful
419  * (and polling should be enabled), 0 otherwise.
420  * A device is not supposed to register itself multiple times.
421  *
422  * This is called from within the *_intr() functions, so we do not need
423  * further locking.
424  */
425 int
426 ether_poll_register(poll_handler_t *h, struct ifnet *ifp)
427 {
428         int s;
429
430         if (polling == 0) /* polling disabled, cannot register */
431                 return 0;
432         if (h == NULL || ifp == NULL)           /* bad arguments        */
433                 return 0;
434         if ( !(ifp->if_flags & IFF_UP) )        /* must be up           */
435                 return 0;
436         if (ifp->if_ipending & IFF_POLLING)     /* already polling      */
437                 return 0;
438
439         s = splhigh();
440         if (poll_handlers >= POLL_LIST_LEN) {
441                 /*
442                  * List full, cannot register more entries.
443                  * This should never happen; if it does, it is probably a
444                  * broken driver trying to register multiple times. Checking
445                  * this at runtime is expensive, and won't solve the problem
446                  * anyways, so just report a few times and then give up.
447                  */
448                 static int verbose = 10 ;
449                 splx(s);
450                 if (verbose >0) {
451                         printf("poll handlers list full, "
452                                 "maybe a broken driver ?\n");
453                         verbose--;
454                 }
455                 return 0; /* no polling for you */
456         }
457
458         pr[poll_handlers].handler = h;
459         pr[poll_handlers].ifp = ifp;
460         poll_handlers++;
461         ifp->if_ipending |= IFF_POLLING;
462         splx(s);
463         return 1; /* polling enabled in next call */
464 }
465
466 /*
467  * Remove interface from the polling list. Normally called by *_stop().
468  * It is not an error to call it with IFF_POLLING clear, the call is
469  * sufficiently rare to be preferable to save the space for the extra
470  * test in each driver in exchange of one additional function call.
471  */
472 int
473 ether_poll_deregister(struct ifnet *ifp)
474 {
475         int i;
476         int s = splimp();
477         
478         if ( !ifp || !(ifp->if_ipending & IFF_POLLING) ) {
479                 splx(s);
480                 return 0;
481         }
482         for (i = 0 ; i < poll_handlers ; i++)
483                 if (pr[i].ifp == ifp) /* found it */
484                         break;
485         ifp->if_ipending &= ~IFF_POLLING; /* found or not... */
486         if (i == poll_handlers) {
487                 splx(s);
488                 printf("ether_poll_deregister: ifp not found!!!\n");
489                 return 0;
490         }
491         poll_handlers--;
492         if (i < poll_handlers) { /* Last entry replaces this one. */
493                 pr[i].handler = pr[poll_handlers].handler;
494                 pr[i].ifp = pr[poll_handlers].ifp;
495         }
496         splx(s);
497         return 1;
498 }