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