xref: /freebsd-13-stable/sys/kern/kern_poll.c (revision 3bc80996974a61a4223eae4c1ccd47b6ee32a48a)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2001-2002 Luigi Rizzo
5  *
6  * Supported by: the Xorp Project (www.xorp.org)
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
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/epoch.h>
39 #include <sys/eventhandler.h>
40 #include <sys/resourcevar.h>
41 #include <sys/socket.h>			/* needed by net/if.h		*/
42 #include <sys/sockio.h>
43 #include <sys/sysctl.h>
44 #include <sys/syslog.h>
45 
46 #include <net/if.h>
47 #include <net/if_var.h>
48 #include <net/netisr.h>			/* for NETISR_POLL		*/
49 #include <net/vnet.h>
50 
51 void hardclock_device_poll(void);	/* hook from hardclock		*/
52 
53 static struct mtx	poll_mtx;
54 
55 /*
56  * Polling support for [network] device drivers.
57  *
58  * Drivers which support this feature can register with the
59  * polling code.
60  *
61  * If registration is successful, the driver must disable interrupts,
62  * and further I/O is performed through the handler, which is invoked
63  * (at least once per clock tick) with 3 arguments: the "arg" passed at
64  * register time (a struct ifnet pointer), a command, and a "count" limit.
65  *
66  * The command can be one of the following:
67  *  POLL_ONLY: quick move of "count" packets from input/output queues.
68  *  POLL_AND_CHECK_STATUS: as above, plus check status registers or do
69  *	other more expensive operations. This command is issued periodically
70  *	but less frequently than POLL_ONLY.
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  * Polling is enabled and disabled via setting IFCAP_POLLING flag on
79  * the interface. The driver ioctl handler should register interface
80  * with polling and disable interrupts, if registration was successful.
81  *
82  * A second variable controls the sharing of CPU between polling/kernel
83  * network processing, and other activities (typically userlevel tasks):
84  * kern.polling.user_frac (between 0 and 100, default 50) sets the share
85  * of CPU allocated to user tasks. CPU is allocated proportionally to the
86  * shares, by dynamically adjusting the "count" (poll_burst).
87  *
88  * Other parameters can should be left to their default values.
89  * The following constraints hold
90  *
91  *	1 <= poll_each_burst <= poll_burst <= poll_burst_max
92  *	MIN_POLL_BURST_MAX <= poll_burst_max <= MAX_POLL_BURST_MAX
93  */
94 
95 #define MIN_POLL_BURST_MAX	10
96 #define MAX_POLL_BURST_MAX	20000
97 
98 static uint32_t poll_burst = 5;
99 static uint32_t poll_burst_max = 150;	/* good for 100Mbit net and HZ=1000 */
100 static uint32_t poll_each_burst = 5;
101 
102 static SYSCTL_NODE(_kern, OID_AUTO, polling, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
103     "Device polling parameters");
104 
105 SYSCTL_UINT(_kern_polling, OID_AUTO, burst, CTLFLAG_RD,
106 	&poll_burst, 0, "Current polling burst size");
107 
108 static int	netisr_poll_scheduled;
109 static int	netisr_pollmore_scheduled;
110 static int	poll_shutting_down;
111 
poll_burst_max_sysctl(SYSCTL_HANDLER_ARGS)112 static int poll_burst_max_sysctl(SYSCTL_HANDLER_ARGS)
113 {
114 	uint32_t val = poll_burst_max;
115 	int error;
116 
117 	error = sysctl_handle_int(oidp, &val, 0, req);
118 	if (error || !req->newptr )
119 		return (error);
120 	if (val < MIN_POLL_BURST_MAX || val > MAX_POLL_BURST_MAX)
121 		return (EINVAL);
122 
123 	mtx_lock(&poll_mtx);
124 	poll_burst_max = val;
125 	if (poll_burst > poll_burst_max)
126 		poll_burst = poll_burst_max;
127 	if (poll_each_burst > poll_burst_max)
128 		poll_each_burst = MIN_POLL_BURST_MAX;
129 	mtx_unlock(&poll_mtx);
130 
131 	return (0);
132 }
133 SYSCTL_PROC(_kern_polling, OID_AUTO, burst_max,
134     CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE, 0, sizeof(uint32_t),
135     poll_burst_max_sysctl, "I",
136     "Max Polling burst size");
137 
poll_each_burst_sysctl(SYSCTL_HANDLER_ARGS)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,
160     CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE, 0, sizeof(uint32_t),
161     poll_each_burst_sysctl, "I",
162     "Max size of each burst");
163 
164 static uint32_t poll_in_idle_loop=0;	/* do we poll in idle loop ? */
165 SYSCTL_UINT(_kern_polling, OID_AUTO, idle_poll, CTLFLAG_RW,
166 	&poll_in_idle_loop, 0, "Enable device polling in idle loop");
167 
168 static uint32_t user_frac = 50;
user_frac_sysctl(SYSCTL_HANDLER_ARGS)169 static int user_frac_sysctl(SYSCTL_HANDLER_ARGS)
170 {
171 	uint32_t val = user_frac;
172 	int error;
173 
174 	error = sysctl_handle_int(oidp, &val, 0, req);
175 	if (error || !req->newptr )
176 		return (error);
177 	if (val > 99)
178 		return (EINVAL);
179 
180 	mtx_lock(&poll_mtx);
181 	user_frac = val;
182 	mtx_unlock(&poll_mtx);
183 
184 	return (0);
185 }
186 SYSCTL_PROC(_kern_polling, OID_AUTO, user_frac,
187     CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE, 0, sizeof(uint32_t),
188     user_frac_sysctl, "I",
189     "Desired user fraction of cpu time");
190 
191 static uint32_t reg_frac_count = 0;
192 static uint32_t reg_frac = 20 ;
reg_frac_sysctl(SYSCTL_HANDLER_ARGS)193 static int reg_frac_sysctl(SYSCTL_HANDLER_ARGS)
194 {
195 	uint32_t val = reg_frac;
196 	int error;
197 
198 	error = sysctl_handle_int(oidp, &val, 0, req);
199 	if (error || !req->newptr )
200 		return (error);
201 	if (val < 1 || val > hz)
202 		return (EINVAL);
203 
204 	mtx_lock(&poll_mtx);
205 	reg_frac = val;
206 	if (reg_frac_count >= reg_frac)
207 		reg_frac_count = 0;
208 	mtx_unlock(&poll_mtx);
209 
210 	return (0);
211 }
212 SYSCTL_PROC(_kern_polling, OID_AUTO, reg_frac,
213     CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE, 0, sizeof(uint32_t),
214     reg_frac_sysctl, "I",
215     "Every this many cycles check registers");
216 
217 static uint32_t short_ticks;
218 SYSCTL_UINT(_kern_polling, OID_AUTO, short_ticks, CTLFLAG_RD,
219 	&short_ticks, 0, "Hardclock ticks shorter than they should be");
220 
221 static uint32_t lost_polls;
222 SYSCTL_UINT(_kern_polling, OID_AUTO, lost_polls, CTLFLAG_RD,
223 	&lost_polls, 0, "How many times we would have lost a poll tick");
224 
225 static uint32_t pending_polls;
226 SYSCTL_UINT(_kern_polling, OID_AUTO, pending_polls, CTLFLAG_RD,
227 	&pending_polls, 0, "Do we need to poll again");
228 
229 static int residual_burst = 0;
230 SYSCTL_INT(_kern_polling, OID_AUTO, residual_burst, CTLFLAG_RD,
231 	&residual_burst, 0, "# of residual cycles in burst");
232 
233 static uint32_t poll_handlers; /* next free entry in pr[]. */
234 SYSCTL_UINT(_kern_polling, OID_AUTO, handlers, CTLFLAG_RD,
235 	&poll_handlers, 0, "Number of registered poll handlers");
236 
237 static uint32_t phase;
238 SYSCTL_UINT(_kern_polling, OID_AUTO, phase, CTLFLAG_RD,
239 	&phase, 0, "Polling phase");
240 
241 static uint32_t suspect;
242 SYSCTL_UINT(_kern_polling, OID_AUTO, suspect, CTLFLAG_RD,
243 	&suspect, 0, "suspect event");
244 
245 static uint32_t stalled;
246 SYSCTL_UINT(_kern_polling, OID_AUTO, stalled, CTLFLAG_RD,
247 	&stalled, 0, "potential stalls");
248 
249 static uint32_t idlepoll_sleeping; /* idlepoll is sleeping */
250 SYSCTL_UINT(_kern_polling, OID_AUTO, idlepoll_sleeping, CTLFLAG_RD,
251 	&idlepoll_sleeping, 0, "idlepoll is sleeping");
252 
253 #define POLL_LIST_LEN  128
254 struct pollrec {
255 	poll_handler_t	*handler;
256 	struct ifnet	*ifp;
257 };
258 
259 static struct pollrec pr[POLL_LIST_LEN];
260 
261 static void
poll_shutdown(void * arg,int howto)262 poll_shutdown(void *arg, int howto)
263 {
264 
265 	poll_shutting_down = 1;
266 }
267 
268 static void
init_device_poll(void)269 init_device_poll(void)
270 {
271 
272 	mtx_init(&poll_mtx, "polling", NULL, MTX_DEF);
273 	EVENTHANDLER_REGISTER(shutdown_post_sync, poll_shutdown, NULL,
274 	    SHUTDOWN_PRI_LAST);
275 }
276 SYSINIT(device_poll, SI_SUB_SOFTINTR, SI_ORDER_MIDDLE, init_device_poll, NULL);
277 
278 /*
279  * Hook from hardclock. Tries to schedule a netisr, but keeps track
280  * of lost ticks due to the previous handler taking too long.
281  * Normally, this should not happen, because polling handler should
282  * run for a short time. However, in some cases (e.g. when there are
283  * changes in link status etc.) the drivers take a very long time
284  * (even in the order of milliseconds) to reset and reconfigure the
285  * device, causing apparent lost polls.
286  *
287  * The first part of the code is just for debugging purposes, and tries
288  * to count how often hardclock ticks are shorter than they should,
289  * meaning either stray interrupts or delayed events.
290  */
291 void
hardclock_device_poll(void)292 hardclock_device_poll(void)
293 {
294 	static struct timeval prev_t, t;
295 	int delta;
296 
297 	if (poll_handlers == 0 || poll_shutting_down)
298 		return;
299 
300 	microuptime(&t);
301 	delta = (t.tv_usec - prev_t.tv_usec) +
302 		(t.tv_sec - prev_t.tv_sec)*1000000;
303 	if (delta * hz < 500000)
304 		short_ticks++;
305 	else
306 		prev_t = t;
307 
308 	if (pending_polls > 100) {
309 		/*
310 		 * Too much, assume it has stalled (not always true
311 		 * see comment above).
312 		 */
313 		stalled++;
314 		pending_polls = 0;
315 		phase = 0;
316 	}
317 
318 	if (phase <= 2) {
319 		if (phase != 0)
320 			suspect++;
321 		phase = 1;
322 		netisr_poll_scheduled = 1;
323 		netisr_pollmore_scheduled = 1;
324 		netisr_sched_poll();
325 		phase = 2;
326 	}
327 	if (pending_polls++ > 0)
328 		lost_polls++;
329 }
330 
331 /*
332  * ether_poll is called from the idle loop.
333  */
334 static void
ether_poll(int count)335 ether_poll(int count)
336 {
337 	struct epoch_tracker et;
338 	int i;
339 
340 	mtx_lock(&poll_mtx);
341 
342 	if (count > poll_each_burst)
343 		count = poll_each_burst;
344 
345 	NET_EPOCH_ENTER(et);
346 	for (i = 0 ; i < poll_handlers ; i++)
347 		pr[i].handler(pr[i].ifp, POLL_ONLY, count);
348 	NET_EPOCH_EXIT(et);
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
netisr_pollmore(void)372 netisr_pollmore(void)
373 {
374 	struct timeval t;
375 	int kern_load;
376 
377 	if (poll_handlers == 0)
378 		return;
379 
380 	mtx_lock(&poll_mtx);
381 	if (!netisr_pollmore_scheduled) {
382 		mtx_unlock(&poll_mtx);
383 		return;
384 	}
385 	netisr_pollmore_scheduled = 0;
386 	phase = 5;
387 	if (residual_burst > 0) {
388 		netisr_poll_scheduled = 1;
389 		netisr_pollmore_scheduled = 1;
390 		netisr_sched_poll();
391 		mtx_unlock(&poll_mtx);
392 		/* will run immediately on return, followed by netisrs */
393 		return;
394 	}
395 	/* here we can account time spent in netisr's in this tick */
396 	microuptime(&t);
397 	kern_load = (t.tv_usec - poll_start_t.tv_usec) +
398 		(t.tv_sec - poll_start_t.tv_sec)*1000000;	/* us */
399 	kern_load = (kern_load * hz) / 10000;			/* 0..100 */
400 	if (kern_load > (100 - user_frac)) { /* try decrease ticks */
401 		if (poll_burst > 1)
402 			poll_burst--;
403 	} else {
404 		if (poll_burst < poll_burst_max)
405 			poll_burst++;
406 	}
407 
408 	pending_polls--;
409 	if (pending_polls == 0) /* we are done */
410 		phase = 0;
411 	else {
412 		/*
413 		 * Last cycle was long and caused us to miss one or more
414 		 * hardclock ticks. Restart processing again, but slightly
415 		 * reduce the burst size to prevent that this happens again.
416 		 */
417 		poll_burst -= (poll_burst / 8);
418 		if (poll_burst < 1)
419 			poll_burst = 1;
420 		netisr_poll_scheduled = 1;
421 		netisr_pollmore_scheduled = 1;
422 		netisr_sched_poll();
423 		phase = 6;
424 	}
425 	mtx_unlock(&poll_mtx);
426 }
427 
428 /*
429  * netisr_poll is typically scheduled once per tick.
430  */
431 void
netisr_poll(void)432 netisr_poll(void)
433 {
434 	int i, cycles;
435 	enum poll_cmd arg = POLL_ONLY;
436 
437 	NET_EPOCH_ASSERT();
438 
439 	if (poll_handlers == 0)
440 		return;
441 
442 	mtx_lock(&poll_mtx);
443 	if (!netisr_poll_scheduled) {
444 		mtx_unlock(&poll_mtx);
445 		return;
446 	}
447 	netisr_poll_scheduled = 0;
448 	phase = 3;
449 	if (residual_burst == 0) { /* first call in this tick */
450 		microuptime(&poll_start_t);
451 		if (++reg_frac_count == reg_frac) {
452 			arg = POLL_AND_CHECK_STATUS;
453 			reg_frac_count = 0;
454 		}
455 
456 		residual_burst = poll_burst;
457 	}
458 	cycles = (residual_burst < poll_each_burst) ?
459 		residual_burst : poll_each_burst;
460 	residual_burst -= cycles;
461 
462 	for (i = 0 ; i < poll_handlers ; i++)
463 		pr[i].handler(pr[i].ifp, arg, cycles);
464 
465 	phase = 4;
466 	mtx_unlock(&poll_mtx);
467 }
468 
469 /*
470  * Try to register routine for polling. Returns 0 if successful
471  * (and polling should be enabled), error code otherwise.
472  * A device is not supposed to register itself multiple times.
473  *
474  * This is called from within the *_ioctl() functions.
475  */
476 int
ether_poll_register(poll_handler_t * h,if_t ifp)477 ether_poll_register(poll_handler_t *h, if_t ifp)
478 {
479 	int i;
480 
481 	KASSERT(h != NULL, ("%s: handler is NULL", __func__));
482 	KASSERT(ifp != NULL, ("%s: ifp is NULL", __func__));
483 
484 	mtx_lock(&poll_mtx);
485 	if (poll_handlers >= POLL_LIST_LEN) {
486 		/*
487 		 * List full, cannot register more entries.
488 		 * This should never happen; if it does, it is probably a
489 		 * broken driver trying to register multiple times. Checking
490 		 * this at runtime is expensive, and won't solve the problem
491 		 * anyways, so just report a few times and then give up.
492 		 */
493 		static int verbose = 10 ;
494 		if (verbose >0) {
495 			log(LOG_ERR, "poll handlers list full, "
496 			    "maybe a broken driver ?\n");
497 			verbose--;
498 		}
499 		mtx_unlock(&poll_mtx);
500 		return (ENOMEM); /* no polling for you */
501 	}
502 
503 	for (i = 0 ; i < poll_handlers ; i++)
504 		if (pr[i].ifp == ifp && pr[i].handler != NULL) {
505 			mtx_unlock(&poll_mtx);
506 			log(LOG_DEBUG, "ether_poll_register: %s: handler"
507 			    " already registered\n", ifp->if_xname);
508 			return (EEXIST);
509 		}
510 
511 	pr[poll_handlers].handler = h;
512 	pr[poll_handlers].ifp = ifp;
513 	poll_handlers++;
514 	mtx_unlock(&poll_mtx);
515 	if (idlepoll_sleeping)
516 		wakeup(&idlepoll_sleeping);
517 	return (0);
518 }
519 
520 /*
521  * Remove interface from the polling list. Called from *_ioctl(), too.
522  */
523 int
ether_poll_deregister(if_t ifp)524 ether_poll_deregister(if_t ifp)
525 {
526 	int i;
527 
528 	KASSERT(ifp != NULL, ("%s: ifp is NULL", __func__));
529 
530 	mtx_lock(&poll_mtx);
531 
532 	for (i = 0 ; i < poll_handlers ; i++)
533 		if (pr[i].ifp == ifp) /* found it */
534 			break;
535 	if (i == poll_handlers) {
536 		log(LOG_DEBUG, "ether_poll_deregister: %s: not found!\n",
537 		    ifp->if_xname);
538 		mtx_unlock(&poll_mtx);
539 		return (ENOENT);
540 	}
541 	poll_handlers--;
542 	if (i < poll_handlers) { /* Last entry replaces this one. */
543 		pr[i].handler = pr[poll_handlers].handler;
544 		pr[i].ifp = pr[poll_handlers].ifp;
545 	}
546 	mtx_unlock(&poll_mtx);
547 	return (0);
548 }
549 
550 static void
poll_idle(void)551 poll_idle(void)
552 {
553 	struct thread *td = curthread;
554 	struct rtprio rtp;
555 
556 	rtp.prio = RTP_PRIO_MAX;	/* lowest priority */
557 	rtp.type = RTP_PRIO_IDLE;
558 	PROC_SLOCK(td->td_proc);
559 	rtp_to_pri(&rtp, td);
560 	PROC_SUNLOCK(td->td_proc);
561 
562 	for (;;) {
563 		if (poll_in_idle_loop && poll_handlers > 0) {
564 			idlepoll_sleeping = 0;
565 			ether_poll(poll_each_burst);
566 			thread_lock(td);
567 			mi_switch(SW_VOL);
568 		} else {
569 			idlepoll_sleeping = 1;
570 			tsleep(&idlepoll_sleeping, 0, "pollid", hz * 3);
571 		}
572 	}
573 }
574 
575 static struct proc *idlepoll;
576 static struct kproc_desc idlepoll_kp = {
577 	 "idlepoll",
578 	 poll_idle,
579 	 &idlepoll
580 };
581 SYSINIT(idlepoll, SI_SUB_KTHREAD_VM, SI_ORDER_ANY, kproc_start,
582     &idlepoll_kp);
583