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