xref: /freebsd/sys/kern/kern_poll.c (revision 5861f9665471e98e544f6fa3ce73c4912229ff82)
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 
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30 
31 #include "opt_device_polling.h"
32 
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/kernel.h>
36 #include <sys/kthread.h>
37 #include <sys/proc.h>
38 #include <sys/eventhandler.h>
39 #include <sys/resourcevar.h>
40 #include <sys/socket.h>			/* needed by net/if.h		*/
41 #include <sys/sockio.h>
42 #include <sys/sysctl.h>
43 #include <sys/syslog.h>
44 #include <sys/vimage.h>
45 
46 #include <net/if.h>			/* for IFF_* flags		*/
47 #include <net/netisr.h>			/* for NETISR_POLL		*/
48 #include <net/vnet.h>
49 
50 static int poll_switch(SYSCTL_HANDLER_ARGS);
51 
52 void hardclock_device_poll(void);	/* hook from hardclock		*/
53 
54 static struct mtx	poll_mtx;
55 
56 /*
57  * Polling support for [network] device drivers.
58  *
59  * Drivers which support this feature can register with the
60  * polling code.
61  *
62  * If registration is successful, the driver must disable interrupts,
63  * and further I/O is performed through the handler, which is invoked
64  * (at least once per clock tick) with 3 arguments: the "arg" passed at
65  * register time (a struct ifnet pointer), a command, and a "count" limit.
66  *
67  * The command can be one of the following:
68  *  POLL_ONLY: quick move of "count" packets from input/output queues.
69  *  POLL_AND_CHECK_STATUS: as above, plus check status registers or do
70  *	other more expensive operations. This command is issued periodically
71  *	but less frequently than POLL_ONLY.
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  * Polling is enabled and disabled via setting IFCAP_POLLING flag on
80  * the interface. The driver ioctl handler should register interface
81  * with polling and disable interrupts, if registration was successful.
82  *
83  * A second variable controls the sharing of CPU between polling/kernel
84  * network processing, and other activities (typically userlevel tasks):
85  * kern.polling.user_frac (between 0 and 100, default 50) sets the share
86  * of CPU allocated to user tasks. CPU is allocated proportionally to the
87  * shares, by dynamically adjusting the "count" (poll_burst).
88  *
89  * Other parameters can should be left to their default values.
90  * The following constraints hold
91  *
92  *	1 <= poll_each_burst <= poll_burst <= poll_burst_max
93  *	0 <= poll_each_burst
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 static uint32_t poll_burst = 5;
101 static uint32_t poll_burst_max = 150;	/* good for 100Mbit net and HZ=1000 */
102 static uint32_t poll_each_burst = 5;
103 
104 SYSCTL_NODE(_kern, OID_AUTO, polling, CTLFLAG_RW, 0,
105 	"Device polling parameters");
106 
107 SYSCTL_UINT(_kern_polling, OID_AUTO, burst, CTLFLAG_RD,
108 	&poll_burst, 0, "Current polling burst size");
109 
110 static int	netisr_poll_scheduled;
111 static int	netisr_pollmore_scheduled;
112 static int	poll_shutting_down;
113 
114 static int poll_burst_max_sysctl(SYSCTL_HANDLER_ARGS)
115 {
116 	uint32_t val = poll_burst_max;
117 	int error;
118 
119 	error = sysctl_handle_int(oidp, &val, 0, req);
120 	if (error || !req->newptr )
121 		return (error);
122 	if (val < MIN_POLL_BURST_MAX || val > MAX_POLL_BURST_MAX)
123 		return (EINVAL);
124 
125 	mtx_lock(&poll_mtx);
126 	poll_burst_max = val;
127 	if (poll_burst > poll_burst_max)
128 		poll_burst = poll_burst_max;
129 	if (poll_each_burst > poll_burst_max)
130 		poll_each_burst = MIN_POLL_BURST_MAX;
131 	mtx_unlock(&poll_mtx);
132 
133 	return (0);
134 }
135 SYSCTL_PROC(_kern_polling, OID_AUTO, burst_max, CTLTYPE_UINT | CTLFLAG_RW,
136 	0, sizeof(uint32_t), poll_burst_max_sysctl, "I", "Max Polling burst size");
137 
138 static int poll_each_burst_sysctl(SYSCTL_HANDLER_ARGS)
139 {
140 	uint32_t val = poll_each_burst;
141 	int error;
142 
143 	error = sysctl_handle_int(oidp, &val, 0, req);
144 	if (error || !req->newptr )
145 		return (error);
146 	if (val < 1)
147 		return (EINVAL);
148 
149 	mtx_lock(&poll_mtx);
150 	if (val > poll_burst_max) {
151 		mtx_unlock(&poll_mtx);
152 		return (EINVAL);
153 	}
154 	poll_each_burst = val;
155 	mtx_unlock(&poll_mtx);
156 
157 	return (0);
158 }
159 SYSCTL_PROC(_kern_polling, OID_AUTO, each_burst, CTLTYPE_UINT | CTLFLAG_RW,
160 	0, sizeof(uint32_t), poll_each_burst_sysctl, "I",
161 	"Max size of each burst");
162 
163 static uint32_t poll_in_idle_loop=0;	/* do we poll in idle loop ? */
164 SYSCTL_UINT(_kern_polling, OID_AUTO, idle_poll, CTLFLAG_RW,
165 	&poll_in_idle_loop, 0, "Enable device polling in idle loop");
166 
167 static uint32_t user_frac = 50;
168 static int user_frac_sysctl(SYSCTL_HANDLER_ARGS)
169 {
170 	uint32_t val = user_frac;
171 	int error;
172 
173 	error = sysctl_handle_int(oidp, &val, 0, req);
174 	if (error || !req->newptr )
175 		return (error);
176 	if (val < 0 || val > 99)
177 		return (EINVAL);
178 
179 	mtx_lock(&poll_mtx);
180 	user_frac = val;
181 	mtx_unlock(&poll_mtx);
182 
183 	return (0);
184 }
185 SYSCTL_PROC(_kern_polling, OID_AUTO, user_frac, CTLTYPE_UINT | CTLFLAG_RW,
186 	0, sizeof(uint32_t), user_frac_sysctl, "I",
187 	"Desired user fraction of cpu time");
188 
189 static uint32_t reg_frac_count = 0;
190 static uint32_t reg_frac = 20 ;
191 static int reg_frac_sysctl(SYSCTL_HANDLER_ARGS)
192 {
193 	uint32_t val = reg_frac;
194 	int error;
195 
196 	error = sysctl_handle_int(oidp, &val, 0, req);
197 	if (error || !req->newptr )
198 		return (error);
199 	if (val < 1 || val > hz)
200 		return (EINVAL);
201 
202 	mtx_lock(&poll_mtx);
203 	reg_frac = val;
204 	if (reg_frac_count >= reg_frac)
205 		reg_frac_count = 0;
206 	mtx_unlock(&poll_mtx);
207 
208 	return (0);
209 }
210 SYSCTL_PROC(_kern_polling, OID_AUTO, reg_frac, CTLTYPE_UINT | CTLFLAG_RW,
211 	0, sizeof(uint32_t), reg_frac_sysctl, "I",
212 	"Every this many cycles check registers");
213 
214 static uint32_t short_ticks;
215 SYSCTL_UINT(_kern_polling, OID_AUTO, short_ticks, CTLFLAG_RD,
216 	&short_ticks, 0, "Hardclock ticks shorter than they should be");
217 
218 static uint32_t lost_polls;
219 SYSCTL_UINT(_kern_polling, OID_AUTO, lost_polls, CTLFLAG_RD,
220 	&lost_polls, 0, "How many times we would have lost a poll tick");
221 
222 static uint32_t pending_polls;
223 SYSCTL_UINT(_kern_polling, OID_AUTO, pending_polls, CTLFLAG_RD,
224 	&pending_polls, 0, "Do we need to poll again");
225 
226 static int residual_burst = 0;
227 SYSCTL_INT(_kern_polling, OID_AUTO, residual_burst, CTLFLAG_RD,
228 	&residual_burst, 0, "# of residual cycles in burst");
229 
230 static uint32_t poll_handlers; /* next free entry in pr[]. */
231 SYSCTL_UINT(_kern_polling, OID_AUTO, handlers, CTLFLAG_RD,
232 	&poll_handlers, 0, "Number of registered poll handlers");
233 
234 static int polling = 0;
235 SYSCTL_PROC(_kern_polling, OID_AUTO, enable, CTLTYPE_UINT | CTLFLAG_RW,
236 	0, sizeof(int), poll_switch, "I", "Switch polling for all interfaces");
237 
238 static uint32_t phase;
239 SYSCTL_UINT(_kern_polling, OID_AUTO, phase, CTLFLAG_RD,
240 	&phase, 0, "Polling phase");
241 
242 static uint32_t suspect;
243 SYSCTL_UINT(_kern_polling, OID_AUTO, suspect, CTLFLAG_RD,
244 	&suspect, 0, "suspect event");
245 
246 static uint32_t stalled;
247 SYSCTL_UINT(_kern_polling, OID_AUTO, stalled, CTLFLAG_RD,
248 	&stalled, 0, "potential stalls");
249 
250 static uint32_t idlepoll_sleeping; /* idlepoll is sleeping */
251 SYSCTL_UINT(_kern_polling, OID_AUTO, idlepoll_sleeping, CTLFLAG_RD,
252 	&idlepoll_sleeping, 0, "idlepoll is sleeping");
253 
254 
255 #define POLL_LIST_LEN  128
256 struct pollrec {
257 	poll_handler_t	*handler;
258 	struct ifnet	*ifp;
259 };
260 
261 static struct pollrec pr[POLL_LIST_LEN];
262 
263 static void
264 poll_shutdown(void *arg, int howto)
265 {
266 
267 	poll_shutting_down = 1;
268 }
269 
270 static void
271 init_device_poll(void)
272 {
273 
274 	mtx_init(&poll_mtx, "polling", NULL, MTX_DEF);
275 	EVENTHANDLER_REGISTER(shutdown_post_sync, poll_shutdown, NULL,
276 	    SHUTDOWN_PRI_LAST);
277 }
278 SYSINIT(device_poll, SI_SUB_CLOCKS, SI_ORDER_MIDDLE, init_device_poll, NULL);
279 
280 
281 /*
282  * Hook from hardclock. Tries to schedule a netisr, but keeps track
283  * of lost ticks due to the previous handler taking too long.
284  * Normally, this should not happen, because polling handler should
285  * run for a short time. However, in some cases (e.g. when there are
286  * changes in link status etc.) the drivers take a very long time
287  * (even in the order of milliseconds) to reset and reconfigure the
288  * device, causing apparent lost polls.
289  *
290  * The first part of the code is just for debugging purposes, and tries
291  * to count how often hardclock ticks are shorter than they should,
292  * meaning either stray interrupts or delayed events.
293  */
294 void
295 hardclock_device_poll(void)
296 {
297 	static struct timeval prev_t, t;
298 	int delta;
299 
300 	if (poll_handlers == 0 || poll_shutting_down)
301 		return;
302 
303 	microuptime(&t);
304 	delta = (t.tv_usec - prev_t.tv_usec) +
305 		(t.tv_sec - prev_t.tv_sec)*1000000;
306 	if (delta * hz < 500000)
307 		short_ticks++;
308 	else
309 		prev_t = t;
310 
311 	if (pending_polls > 100) {
312 		/*
313 		 * Too much, assume it has stalled (not always true
314 		 * see comment above).
315 		 */
316 		stalled++;
317 		pending_polls = 0;
318 		phase = 0;
319 	}
320 
321 	if (phase <= 2) {
322 		if (phase != 0)
323 			suspect++;
324 		phase = 1;
325 		netisr_poll_scheduled = 1;
326 		netisr_pollmore_scheduled = 1;
327 		netisr_sched_poll();
328 		phase = 2;
329 	}
330 	if (pending_polls++ > 0)
331 		lost_polls++;
332 }
333 
334 /*
335  * ether_poll is called from the idle loop.
336  */
337 static void
338 ether_poll(int count)
339 {
340 	int i;
341 
342 	mtx_lock(&poll_mtx);
343 
344 	if (count > poll_each_burst)
345 		count = poll_each_burst;
346 
347 	for (i = 0 ; i < poll_handlers ; i++)
348 		pr[i].handler(pr[i].ifp, POLL_ONLY, count);
349 
350 	mtx_unlock(&poll_mtx);
351 }
352 
353 /*
354  * netisr_pollmore is called after other netisr's, possibly scheduling
355  * another NETISR_POLL call, or adapting the burst size for the next cycle.
356  *
357  * It is very bad to fetch large bursts of packets from a single card at once,
358  * because the burst could take a long time to be completely processed, or
359  * could saturate the intermediate queue (ipintrq or similar) leading to
360  * losses or unfairness. To reduce the problem, and also to account better for
361  * time spent in network-related processing, we split the burst in smaller
362  * chunks of fixed size, giving control to the other netisr's between chunks.
363  * This helps in improving the fairness, reducing livelock (because we
364  * emulate more closely the "process to completion" that we have with
365  * fastforwarding) and accounting for the work performed in low level
366  * handling and forwarding.
367  */
368 
369 static struct timeval poll_start_t;
370 
371 void
372 netisr_pollmore()
373 {
374 	struct timeval t;
375 	int kern_load;
376 
377 	mtx_lock(&poll_mtx);
378 	if (!netisr_pollmore_scheduled) {
379 		mtx_unlock(&poll_mtx);
380 		return;
381 	}
382 	netisr_pollmore_scheduled = 0;
383 	phase = 5;
384 	if (residual_burst > 0) {
385 		netisr_poll_scheduled = 1;
386 		netisr_pollmore_scheduled = 1;
387 		netisr_sched_poll();
388 		mtx_unlock(&poll_mtx);
389 		/* will run immediately on return, followed by netisrs */
390 		return;
391 	}
392 	/* here we can account time spent in netisr's in this tick */
393 	microuptime(&t);
394 	kern_load = (t.tv_usec - poll_start_t.tv_usec) +
395 		(t.tv_sec - poll_start_t.tv_sec)*1000000;	/* us */
396 	kern_load = (kern_load * hz) / 10000;			/* 0..100 */
397 	if (kern_load > (100 - user_frac)) { /* try decrease ticks */
398 		if (poll_burst > 1)
399 			poll_burst--;
400 	} else {
401 		if (poll_burst < poll_burst_max)
402 			poll_burst++;
403 	}
404 
405 	pending_polls--;
406 	if (pending_polls == 0) /* we are done */
407 		phase = 0;
408 	else {
409 		/*
410 		 * Last cycle was long and caused us to miss one or more
411 		 * hardclock ticks. Restart processing again, but slightly
412 		 * reduce the burst size to prevent that this happens again.
413 		 */
414 		poll_burst -= (poll_burst / 8);
415 		if (poll_burst < 1)
416 			poll_burst = 1;
417 		netisr_poll_scheduled = 1;
418 		netisr_pollmore_scheduled = 1;
419 		netisr_sched_poll();
420 		phase = 6;
421 	}
422 	mtx_unlock(&poll_mtx);
423 }
424 
425 /*
426  * netisr_poll is typically scheduled once per tick.
427  */
428 void
429 netisr_poll(void)
430 {
431 	int i, cycles;
432 	enum poll_cmd arg = POLL_ONLY;
433 
434 	mtx_lock(&poll_mtx);
435 	if (!netisr_poll_scheduled) {
436 		mtx_unlock(&poll_mtx);
437 		return;
438 	}
439 	netisr_poll_scheduled = 0;
440 	phase = 3;
441 	if (residual_burst == 0) { /* first call in this tick */
442 		microuptime(&poll_start_t);
443 		if (++reg_frac_count == reg_frac) {
444 			arg = POLL_AND_CHECK_STATUS;
445 			reg_frac_count = 0;
446 		}
447 
448 		residual_burst = poll_burst;
449 	}
450 	cycles = (residual_burst < poll_each_burst) ?
451 		residual_burst : poll_each_burst;
452 	residual_burst -= cycles;
453 
454 	for (i = 0 ; i < poll_handlers ; i++)
455 		pr[i].handler(pr[i].ifp, arg, cycles);
456 
457 	phase = 4;
458 	mtx_unlock(&poll_mtx);
459 }
460 
461 /*
462  * Try to register routine for polling. Returns 0 if successful
463  * (and polling should be enabled), error code otherwise.
464  * A device is not supposed to register itself multiple times.
465  *
466  * This is called from within the *_ioctl() functions.
467  */
468 int
469 ether_poll_register(poll_handler_t *h, struct ifnet *ifp)
470 {
471 	int i;
472 
473 	KASSERT(h != NULL, ("%s: handler is NULL", __func__));
474 	KASSERT(ifp != NULL, ("%s: ifp is NULL", __func__));
475 
476 	mtx_lock(&poll_mtx);
477 	if (poll_handlers >= POLL_LIST_LEN) {
478 		/*
479 		 * List full, cannot register more entries.
480 		 * This should never happen; if it does, it is probably a
481 		 * broken driver trying to register multiple times. Checking
482 		 * this at runtime is expensive, and won't solve the problem
483 		 * anyways, so just report a few times and then give up.
484 		 */
485 		static int verbose = 10 ;
486 		if (verbose >0) {
487 			log(LOG_ERR, "poll handlers list full, "
488 			    "maybe a broken driver ?\n");
489 			verbose--;
490 		}
491 		mtx_unlock(&poll_mtx);
492 		return (ENOMEM); /* no polling for you */
493 	}
494 
495 	for (i = 0 ; i < poll_handlers ; i++)
496 		if (pr[i].ifp == ifp && pr[i].handler != NULL) {
497 			mtx_unlock(&poll_mtx);
498 			log(LOG_DEBUG, "ether_poll_register: %s: handler"
499 			    " already registered\n", ifp->if_xname);
500 			return (EEXIST);
501 		}
502 
503 	pr[poll_handlers].handler = h;
504 	pr[poll_handlers].ifp = ifp;
505 	poll_handlers++;
506 	mtx_unlock(&poll_mtx);
507 	if (idlepoll_sleeping)
508 		wakeup(&idlepoll_sleeping);
509 	return (0);
510 }
511 
512 /*
513  * Remove interface from the polling list. Called from *_ioctl(), too.
514  */
515 int
516 ether_poll_deregister(struct ifnet *ifp)
517 {
518 	int i;
519 
520 	KASSERT(ifp != NULL, ("%s: ifp is NULL", __func__));
521 
522 	mtx_lock(&poll_mtx);
523 
524 	for (i = 0 ; i < poll_handlers ; i++)
525 		if (pr[i].ifp == ifp) /* found it */
526 			break;
527 	if (i == poll_handlers) {
528 		log(LOG_DEBUG, "ether_poll_deregister: %s: not found!\n",
529 		    ifp->if_xname);
530 		mtx_unlock(&poll_mtx);
531 		return (ENOENT);
532 	}
533 	poll_handlers--;
534 	if (i < poll_handlers) { /* Last entry replaces this one. */
535 		pr[i].handler = pr[poll_handlers].handler;
536 		pr[i].ifp = pr[poll_handlers].ifp;
537 	}
538 	mtx_unlock(&poll_mtx);
539 	return (0);
540 }
541 
542 /*
543  * Legacy interface for turning polling on all interfaces at one time.
544  */
545 static int
546 poll_switch(SYSCTL_HANDLER_ARGS)
547 {
548 	INIT_VNET_NET(curvnet);
549 	struct ifnet *ifp;
550 	int error;
551 	int val = polling;
552 
553 	error = sysctl_handle_int(oidp, &val, 0, req);
554 	if (error || !req->newptr )
555 		return (error);
556 
557 	if (val == polling)
558 		return (0);
559 
560 	if (val < 0 || val > 1)
561 		return (EINVAL);
562 
563 	polling = val;
564 
565 	IFNET_RLOCK();
566 	TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
567 		if (ifp->if_capabilities & IFCAP_POLLING) {
568 			struct ifreq ifr;
569 
570 			if (val == 1)
571 				ifr.ifr_reqcap =
572 				    ifp->if_capenable | IFCAP_POLLING;
573 			else
574 				ifr.ifr_reqcap =
575 				    ifp->if_capenable & ~IFCAP_POLLING;
576 			(void) (*ifp->if_ioctl)(ifp, SIOCSIFCAP, (caddr_t)&ifr);
577 		}
578 	}
579 	IFNET_RUNLOCK();
580 
581 	log(LOG_ERR, "kern.polling.enable is deprecated. Use ifconfig(8)");
582 
583 	return (0);
584 }
585 
586 static void
587 poll_idle(void)
588 {
589 	struct thread *td = curthread;
590 	struct rtprio rtp;
591 
592 	rtp.prio = RTP_PRIO_MAX;	/* lowest priority */
593 	rtp.type = RTP_PRIO_IDLE;
594 	PROC_SLOCK(td->td_proc);
595 	rtp_to_pri(&rtp, td);
596 	PROC_SUNLOCK(td->td_proc);
597 
598 	for (;;) {
599 		if (poll_in_idle_loop && poll_handlers > 0) {
600 			idlepoll_sleeping = 0;
601 			ether_poll(poll_each_burst);
602 			thread_lock(td);
603 			mi_switch(SW_VOL, NULL);
604 			thread_unlock(td);
605 		} else {
606 			idlepoll_sleeping = 1;
607 			tsleep(&idlepoll_sleeping, 0, "pollid", hz * 3);
608 		}
609 	}
610 }
611 
612 static struct proc *idlepoll;
613 static struct kproc_desc idlepoll_kp = {
614 	 "idlepoll",
615 	 poll_idle,
616 	 &idlepoll
617 };
618 SYSINIT(idlepoll, SI_SUB_KTHREAD_VM, SI_ORDER_ANY, kproc_start,
619     &idlepoll_kp);
620