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