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