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