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