kern_poll.c revision 90550
11541Srgrimes/*-
21541Srgrimes * Copyright (c) 2001-2002 Luigi Rizzo
31541Srgrimes *
41541Srgrimes * Supported by: the Xorp Project (www.xorp.org)
51541Srgrimes *
61541Srgrimes * Redistribution and use in source and binary forms, with or without
71541Srgrimes * modification, are permitted provided that the following conditions
81541Srgrimes * are met:
91541Srgrimes * 1. Redistributions of source code must retain the above copyright
101541Srgrimes *    notice, this list of conditions and the following disclaimer.
111541Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
121541Srgrimes *    notice, this list of conditions and the following disclaimer in the
131541Srgrimes *    documentation and/or other materials provided with the distribution.
141541Srgrimes *
151541Srgrimes * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
161541Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
171541Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
181541Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
191541Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
201541Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
211541Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
221541Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
231541Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
241541Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
251541Srgrimes * SUCH DAMAGE.
261541Srgrimes *
271541Srgrimes * $FreeBSD: head/sys/kern/kern_poll.c 90550 2002-02-11 23:56:18Z luigi $
281541Srgrimes */
291541Srgrimes
301541Srgrimes#include <sys/param.h>
311541Srgrimes#include <sys/systm.h>
321541Srgrimes#include <sys/kernel.h>
331541Srgrimes#include <sys/socket.h>			/* needed by net/if.h		*/
34116189Sobrien#include <sys/sysctl.h>
35116189Sobrien
36116189Sobrien#include <net/if.h>			/* for IFF_* flags		*/
3718207Sbde#include <net/netisr.h>			/* for NETISR_POLL		*/
381541Srgrimes
391541Srgrimes#include <sys/proc.h>
401541Srgrimes#include <sys/resourcevar.h>
411541Srgrimes#include <sys/kthread.h>
421541Srgrimes
431541Srgrimes#ifdef SMP
441541Srgrimes#error DEVICE_POLLING is not compatible with SMP
451541Srgrimes#endif
461541Srgrimes
471541Srgrimesstatic void netisr_poll(void);		/* the two netisr handlers      */
481541Srgrimesvoid netisr_pollmore(void);
491541Srgrimes
501541Srgrimesvoid init_device_poll(void);		/* init routine			*/
51void hardclock_device_poll(void);	/* hook from hardclock		*/
52void ether_poll(int);			/* polling while in trap	*/
53
54/*
55 * Polling support for [network] device drivers.
56 *
57 * Drivers which support this feature try to register with the
58 * polling code.
59 *
60 * If registration is successful, the driver must disable interrupts,
61 * and further I/O is performed through the handler, which is invoked
62 * (at least once per clock tick) with 3 arguments: the "arg" passed at
63 * register time (a struct ifnet pointer), a command, and a "count" limit.
64 *
65 * The command can be one of the following:
66 *  POLL_ONLY: quick move of "count" packets from input/output queues.
67 *  POLL_AND_CHECK_STATUS: as above, plus check status registers or do
68 *	other more expensive operations. This command is issued periodically
69 *	but less frequently than POLL_ONLY.
70 *  POLL_DEREGISTER: deregister and return to interrupt mode.
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 *	0 <= poll_in_trap <= poll_each_burst
98 *	MIN_POLL_BURST_MAX <= poll_burst_max <= MAX_POLL_BURST_MAX
99 */
100
101#define MIN_POLL_BURST_MAX	10
102#define MAX_POLL_BURST_MAX	1000
103
104SYSCTL_NODE(_kern, OID_AUTO, polling, CTLFLAG_RW, 0,
105	"Device polling parameters");
106
107static u_int32_t poll_burst = 5;
108SYSCTL_UINT(_kern_polling, OID_AUTO, burst, CTLFLAG_RW,
109	&poll_burst, 0, "Current polling burst size");
110
111static u_int32_t poll_each_burst = 5;
112SYSCTL_UINT(_kern_polling, OID_AUTO, each_burst, CTLFLAG_RW,
113	&poll_each_burst, 0, "Max size of each burst");
114
115static u_int32_t poll_burst_max = 150;	/* good for 100Mbit net and HZ=1000 */
116SYSCTL_UINT(_kern_polling, OID_AUTO, burst_max, CTLFLAG_RW,
117	&poll_burst_max, 0, "Max Polling burst size");
118
119static u_int32_t poll_in_idle_loop=1;	/* do we poll in idle loop ? */
120SYSCTL_UINT(_kern_polling, OID_AUTO, idle_poll, CTLFLAG_RW,
121	&poll_in_idle_loop, 0, "Enable device polling in idle loop");
122
123u_int32_t poll_in_trap;			/* used in trap.c */
124SYSCTL_UINT(_kern_polling, OID_AUTO, poll_in_trap, CTLFLAG_RW,
125	&poll_in_trap, 0, "Poll burst size during a trap");
126
127static u_int32_t user_frac = 50;
128SYSCTL_UINT(_kern_polling, OID_AUTO, user_frac, CTLFLAG_RW,
129	&user_frac, 0, "Desired user fraction of cpu time");
130
131static u_int32_t reg_frac = 20 ;
132SYSCTL_UINT(_kern_polling, OID_AUTO, reg_frac, CTLFLAG_RW,
133	&reg_frac, 0, "Every this many cycles poll register");
134
135static u_int32_t short_ticks;
136SYSCTL_UINT(_kern_polling, OID_AUTO, short_ticks, CTLFLAG_RW,
137	&short_ticks, 0, "Hardclock ticks shorter than they should be");
138
139static u_int32_t lost_polls;
140SYSCTL_UINT(_kern_polling, OID_AUTO, lost_polls, CTLFLAG_RW,
141	&lost_polls, 0, "How many times we would have lost a poll tick");
142
143static u_int32_t pending_polls;
144SYSCTL_UINT(_kern_polling, OID_AUTO, pending_polls, CTLFLAG_RW,
145	&pending_polls, 0, "Do we need to poll again");
146
147static int residual_burst = 0;
148SYSCTL_INT(_kern_polling, OID_AUTO, residual_burst, CTLFLAG_RW,
149	&residual_burst, 0, "# of residual cycles in burst");
150
151static u_int32_t poll_handlers; /* next free entry in pr[]. */
152SYSCTL_UINT(_kern_polling, OID_AUTO, handlers, CTLFLAG_RD,
153	&poll_handlers, 0, "Number of registered poll handlers");
154
155static int polling = 0;		/* global polling enable */
156SYSCTL_UINT(_kern_polling, OID_AUTO, enable, CTLFLAG_RW,
157	&polling, 0, "Polling enabled");
158
159static volatile u_int32_t phase;
160SYSCTL_UINT(_kern_polling, OID_AUTO, phase, CTLFLAG_RW,
161	&phase, 0, "Polling phase");
162
163static u_int32_t suspect;
164SYSCTL_UINT(_kern_polling, OID_AUTO, suspect, CTLFLAG_RW,
165	&suspect, 0, "suspect event");
166
167static volatile u_int32_t stalled;
168SYSCTL_UINT(_kern_polling, OID_AUTO, stalled, CTLFLAG_RW,
169	&stalled, 0, "potential stalls");
170
171static u_int32_t idlepoll_sleeping; /* idlepoll is sleeping */
172SYSCTL_UINT(_kern_polling, OID_AUTO, idlepoll_sleeping, CTLFLAG_RD,
173	&idlepoll_sleeping, 0, "idlepoll is sleeping");
174
175
176#define POLL_LIST_LEN  128
177struct pollrec {
178	poll_handler_t	*handler;
179	struct ifnet	*ifp;
180};
181
182static struct pollrec pr[POLL_LIST_LEN];
183
184/*
185 * register relevant netisr. Called from kern_clock.c:
186 */
187void
188init_device_poll(void)
189{
190	register_netisr(NETISR_POLL, netisr_poll);
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 * The first part of the code is just for debugging purposes, and tries
197 * to count how often hardclock ticks are shorter than they should,
198 * meaning either stray interrupts or delayed events.
199 */
200void
201hardclock_device_poll(void)
202{
203	static struct timeval prev_t, t;
204	int delta;
205
206	if (poll_handlers == 0)
207		return;
208
209	microuptime(&t);
210	delta = (t.tv_usec - prev_t.tv_usec) +
211		(t.tv_sec - prev_t.tv_sec)*1000000;
212	if (delta * hz < 500000)
213		short_ticks++;
214	else
215		prev_t = t;
216
217	if (pending_polls > 100) {
218		/* too much, assume it has stalled */
219		stalled++;
220		printf("poll stalled [%d] in phase %d\n",
221			stalled, phase);
222		pending_polls = 0;
223		phase = 0;
224	}
225
226	if (phase <= 2) {
227		if (phase != 0)
228			suspect++;
229		phase = 1;
230		schednetisr(NETISR_POLL);
231		phase = 2;
232	}
233	if (pending_polls++ > 0)
234		lost_polls++;
235}
236
237/*
238 * ether_poll is called from the idle loop or from the trap handler.
239 */
240void
241ether_poll(int count)
242{
243	int i;
244
245	mtx_lock(&Giant);
246
247	if (count > poll_each_burst)
248		count = poll_each_burst;
249	for (i = 0 ; i < poll_handlers ; i++)
250		if (pr[i].handler && (IFF_UP|IFF_RUNNING) ==
251		    (pr[i].ifp->if_flags & (IFF_UP|IFF_RUNNING)) )
252			pr[i].handler(pr[i].ifp, 0, count); /* quick check */
253	mtx_unlock(&Giant);
254}
255
256/*
257 * netisr_pollmore is called after other netisr's, possibly scheduling
258 * another NETISR_POLL call, or adapting the burst size for the next cycle.
259 *
260 * It is very bad to fetch large bursts of packets from a single card at once,
261 * because the burst could take a long time to be completely processed, or
262 * could saturate the intermediate queue (ipintrq or similar) leading to
263 * losses or unfairness. To reduce the problem, and also to account better for
264 * time spent in network-related processing, we split the burst in smaller
265 * chunks of fixed size, giving control to the other netisr's between chunks.
266 * This helps in improving the fairness, reducing livelock (because we
267 * emulate more closely the "process to completion" that we have with
268 * fastforwarding) and accounting for the work performed in low level
269 * handling and forwarding.
270 */
271
272static struct timeval poll_start_t;
273
274void
275netisr_pollmore()
276{
277	struct timeval t;
278	int kern_load;
279	/* XXX run at splhigh() or equivalent */
280
281	phase = 5;
282	if (residual_burst > 0) {
283		schednetisr(NETISR_POLL);
284		/* will run immediately on return, followed by netisrs */
285		return ;
286	}
287	/* here we can account time spent in netisr's in this tick */
288	microuptime(&t);
289	kern_load = (t.tv_usec - poll_start_t.tv_usec) +
290		(t.tv_sec - poll_start_t.tv_sec)*1000000;	/* us */
291	kern_load = (kern_load * hz) / 10000;			/* 0..100 */
292	if (kern_load > (100 - user_frac)) { /* try decrease ticks */
293		if (poll_burst > 1)
294			poll_burst--;
295	} else {
296		if (poll_burst < poll_burst_max)
297			poll_burst++;
298	}
299
300	pending_polls--;
301	if (pending_polls == 0) /* we are done */
302		phase = 0;
303	else {
304		/*
305		 * Last cycle was long and caused us to miss one or more
306		 * hardclock ticks. Restart processing again, but slightly
307		 * reduce the burst size to prevent that this happens again.
308		 */
309		poll_burst -= (poll_burst / 8);
310		if (poll_burst < 1)
311			poll_burst = 1;
312		schednetisr(NETISR_POLL);
313		phase = 6;
314	}
315}
316
317/*
318 * netisr_poll is scheduled by schednetisr when appropriate, typically once
319 * per tick. It is called at splnet() so first thing to do is to upgrade to
320 * splimp(), and call all registered handlers.
321 */
322static void
323netisr_poll(void)
324{
325	static int reg_frac_count;
326	int i, cycles;
327	enum poll_cmd arg = POLL_ONLY;
328	mtx_lock(&Giant);
329
330	phase = 3;
331	if (residual_burst == 0) { /* first call in this tick */
332		microuptime(&poll_start_t);
333		/*
334		 * Check that paremeters are consistent with runtime
335		 * variables. Some of these tests could be done at sysctl
336		 * time, but the savings would be very limited because we
337		 * still have to check against reg_frac_count and
338		 * poll_each_burst. So, instead of writing separate sysctl
339		 * handlers, we do all here.
340		 */
341
342		if (reg_frac > hz)
343			reg_frac = hz;
344		else if (reg_frac < 1)
345			reg_frac = 1;
346		if (reg_frac_count > reg_frac)
347			reg_frac_count = reg_frac - 1;
348		if (reg_frac_count-- == 0) {
349			arg = POLL_AND_CHECK_STATUS;
350			reg_frac_count = reg_frac - 1;
351		}
352		if (poll_burst_max < MIN_POLL_BURST_MAX)
353			poll_burst_max = MIN_POLL_BURST_MAX;
354		else if (poll_burst_max > MAX_POLL_BURST_MAX)
355			poll_burst_max = MAX_POLL_BURST_MAX;
356
357		if (poll_each_burst < 1)
358			poll_each_burst = 1;
359		else if (poll_each_burst > poll_burst_max)
360			poll_each_burst = poll_burst_max;
361
362		residual_burst = poll_burst;
363	}
364	cycles = (residual_burst < poll_each_burst) ?
365		residual_burst : poll_each_burst;
366	residual_burst -= cycles;
367
368	if (polling) {
369		for (i = 0 ; i < poll_handlers ; i++)
370			if (pr[i].handler && (IFF_UP|IFF_RUNNING) ==
371			    (pr[i].ifp->if_flags & (IFF_UP|IFF_RUNNING)) )
372				pr[i].handler(pr[i].ifp, arg, cycles);
373	} else {	/* unregister */
374		for (i = 0 ; i < poll_handlers ; i++) {
375			if (pr[i].handler &&
376			    pr[i].ifp->if_flags & IFF_RUNNING) {
377				pr[i].ifp->if_ipending &= ~IFF_POLLING;
378				pr[i].handler(pr[i].ifp, POLL_DEREGISTER, 1);
379			}
380			pr[i].handler=NULL;
381		}
382		residual_burst = 0;
383		poll_handlers = 0;
384	}
385	/* on -stable, schednetisr(NETISR_POLLMORE); */
386	phase = 4;
387	mtx_unlock(&Giant);
388}
389
390/*
391 * Try to register routine for polling. Returns 1 if successful
392 * (and polling should be enabled), 0 otherwise.
393 * A device is not supposed to register itself multiple times.
394 *
395 * This is called from within the *_intr() functions, so we do not need
396 * further locking.
397 */
398int
399ether_poll_register(poll_handler_t *h, struct ifnet *ifp)
400{
401	int s;
402
403	if (polling == 0) /* polling disabled, cannot register */
404		return 0;
405	if (h == NULL || ifp == NULL)		/* bad arguments	*/
406		return 0;
407	if ( !(ifp->if_flags & IFF_UP) )	/* must be up		*/
408		return 0;
409	if (ifp->if_ipending & IFF_POLLING)	/* already polling	*/
410		return 0;
411
412	s = splhigh();
413	if (poll_handlers >= POLL_LIST_LEN) {
414		/*
415		 * List full, cannot register more entries.
416		 * This should never happen; if it does, it is probably a
417		 * broken driver trying to register multiple times. Checking
418		 * this at runtime is expensive, and won't solve the problem
419		 * anyways, so just report a few times and then give up.
420		 */
421		static int verbose = 10 ;
422		splx(s);
423		if (verbose >0) {
424			printf("poll handlers list full, "
425				"maybe a broken driver ?\n");
426			verbose--;
427		}
428		return 0; /* no polling for you */
429	}
430
431	pr[poll_handlers].handler = h;
432	pr[poll_handlers].ifp = ifp;
433	poll_handlers++;
434	ifp->if_ipending |= IFF_POLLING;
435	splx(s);
436	if (idlepoll_sleeping)
437		wakeup(&idlepoll_sleeping);
438	return 1; /* polling enabled in next call */
439}
440
441/*
442 * Remove interface from the polling list. Normally called by *_stop().
443 * It is not an error to call it with IFF_POLLING clear, the call is
444 * sufficiently rare to be preferable to save the space for the extra
445 * test in each driver in exchange of one additional function call.
446 */
447int
448ether_poll_deregister(struct ifnet *ifp)
449{
450	int i;
451
452	mtx_lock(&Giant);
453	if ( !ifp || !(ifp->if_ipending & IFF_POLLING) ) {
454		mtx_unlock(&Giant);
455		return 0;
456	}
457	for (i = 0 ; i < poll_handlers ; i++)
458		if (pr[i].ifp == ifp) /* found it */
459			break;
460	ifp->if_ipending &= ~IFF_POLLING; /* found or not... */
461	if (i == poll_handlers) {
462		mtx_unlock(&Giant);
463		printf("ether_poll_deregister: ifp not found!!!\n");
464		return 0;
465	}
466	poll_handlers--;
467	if (i < poll_handlers) { /* Last entry replaces this one. */
468		pr[i].handler = pr[poll_handlers].handler;
469		pr[i].ifp = pr[poll_handlers].ifp;
470	}
471	mtx_unlock(&Giant);
472	return 1;
473}
474
475static void
476poll_idle(void)
477{
478	struct thread *td = curthread;
479	struct rtprio rtp;
480	int pri;
481
482	rtp.prio = RTP_PRIO_MAX;	/* lowest priority */
483	rtp.type = RTP_PRIO_IDLE;
484	mtx_lock_spin(&sched_lock);
485	rtp_to_pri(&rtp, &td->td_ksegrp->kg_pri);
486	pri = td->td_priority;
487	mtx_unlock_spin(&sched_lock);
488
489	for (;;) {
490		if (poll_in_idle_loop && poll_handlers > 0) {
491			idlepoll_sleeping = 0;
492			mtx_lock(&Giant);
493			ether_poll(poll_each_burst);
494			mtx_unlock(&Giant);
495			mtx_assert(&Giant, MA_NOTOWNED);
496			mtx_lock_spin(&sched_lock);
497			setrunqueue(td);
498			td->td_proc->p_stats->p_ru.ru_nvcsw++;
499			mi_switch();
500			mtx_unlock_spin(&sched_lock);
501		} else {
502			idlepoll_sleeping = 1;
503			tsleep(&idlepoll_sleeping, pri, "pollid", hz * 3);
504		}
505	}
506}
507
508static struct proc *idlepoll;
509static struct kproc_desc idlepoll_kp = {
510	 "idlepoll",
511	 poll_idle,
512	 &idlepoll
513};
514SYSINIT(idlepoll, SI_SUB_KTHREAD_VM, SI_ORDER_ANY, kproc_start, &idlepoll_kp)
515