xref: /dflybsd-src/sys/net/if_poll.c (revision f0140465f072dacd8b485e76b254a999329a1d3c)
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  */
29 
30 #include "opt_ifpoll.h"
31 
32 #include <sys/param.h>
33 #include <sys/kernel.h>
34 #include <sys/ktr.h>
35 #include <sys/malloc.h>
36 #include <sys/serialize.h>
37 #include <sys/socket.h>
38 #include <sys/sysctl.h>
39 
40 #include <sys/thread2.h>
41 #include <sys/msgport2.h>
42 
43 #include <machine/atomic.h>
44 #include <machine/clock.h>
45 #include <machine/smp.h>
46 
47 #include <net/if.h>
48 #include <net/if_poll.h>
49 #include <net/netmsg2.h>
50 
51 /*
52  * Polling support for network device drivers.
53  *
54  * Drivers which support this feature try to register one status polling
55  * handler and several TX/RX polling handlers with the polling code.
56  * If interface's if_npoll is called with non-NULL second argument, then
57  * a register operation is requested, else a deregister operation is
58  * requested.  If the requested operation is "register", driver should
59  * setup the ifpoll_info passed in accoding its own needs:
60  *   ifpoll_info.ifpi_status.status_func == NULL
61  *     No status polling handler will be installed on CPU(0)
62  *   ifpoll_info.ifpi_rx[n].poll_func == NULL
63  *     No RX polling handler will be installed on CPU(n)
64  *   ifpoll_info.ifpi_tx[n].poll_func == NULL
65  *     No TX polling handler will be installed on CPU(n)
66  *
67  * RX is polled at the specified polling frequency (net.ifpoll.X.pollhz).
68  * TX and status polling could be done at lower frequency than RX frequency
69  * (net.ifpoll.0.status_frac and net.ifpoll.X.tx_frac).  To avoid systimer
70  * staggering at high frequency, RX systimer gives TX and status polling a
71  * piggyback (XXX).
72  *
73  * All of the registered polling handlers are called only if the interface
74  * is marked as 'IFF_RUNNING and IFF_NPOLLING'.  However, the interface's
75  * register and deregister function (ifnet.if_npoll) will be called even
76  * if interface is not marked with 'IFF_RUNNING'.
77  *
78  * If registration is successful, the driver must disable interrupts,
79  * and further I/O is performed through the TX/RX polling handler, which
80  * are invoked (at least once per clock tick) with 3 arguments: the "arg"
81  * passed at register time, a struct ifnet pointer, and a "count" limit.
82  * The registered serializer will be held before calling the related
83  * polling handler.
84  *
85  * The count limit specifies how much work the handler can do during the
86  * call -- typically this is the number of packets to be received, or
87  * transmitted, etc. (drivers are free to interpret this number, as long
88  * as the max time spent in the function grows roughly linearly with the
89  * count).
90  *
91  * A second variable controls the sharing of CPU between polling/kernel
92  * network processing, and other activities (typically userlevel tasks):
93  * net.ifpoll.X.{rx,tx}.user_frac (between 0 and 100, default 50) sets the
94  * share of CPU allocated to user tasks.  CPU is allocated proportionally
95  * to the shares, by dynamically adjusting the "count" (poll_burst).
96  *
97  * Other parameters can should be left to their default values.
98  * The following constraints hold
99  *
100  *	1 <= poll_burst <= poll_burst_max
101  *	1 <= poll_each_burst <= poll_burst_max
102  *	MIN_POLL_BURST_MAX <= poll_burst_max <= MAX_POLL_BURST_MAX
103  */
104 
105 #define IFPOLL_LIST_LEN		128
106 #define IFPOLL_FREQ_MAX		30000
107 
108 #define MIN_IOPOLL_BURST_MAX	10
109 #define MAX_IOPOLL_BURST_MAX	1000
110 #define IOPOLL_BURST_MAX	150	/* good for 100Mbit net and HZ=1000 */
111 
112 #define IOPOLL_EACH_BURST	5
113 
114 #define IFPOLL_FREQ_DEFAULT	2000
115 
116 #define IFPOLL_TXFRAC_DEFAULT	1	/* 1/2 of the pollhz */
117 #define IFPOLL_STFRAC_DEFAULT	19	/* 1/20 of the pollhz */
118 
119 #define IFPOLL_RX		0x1
120 #define IFPOLL_TX		0x2
121 
122 union ifpoll_time {
123 	struct timeval		tv;
124 	uint64_t		tsc;
125 };
126 
127 struct iopoll_rec {
128 	struct lwkt_serialize	*serializer;
129 	struct ifnet		*ifp;
130 	void			*arg;
131 	ifpoll_iofn_t		poll_func;
132 };
133 
134 struct iopoll_ctx {
135 	union ifpoll_time	prev_t;
136 	u_long			short_ticks;		/* statistics */
137 	u_long			lost_polls;		/* statistics */
138 	u_long			suspect;		/* statistics */
139 	u_long			stalled;		/* statistics */
140 	uint32_t		pending_polls;		/* state */
141 
142 	struct netmsg_base	poll_netmsg;
143 	struct netmsg_base	poll_more_netmsg;
144 
145 	int			poll_cpuid;
146 	int			pollhz;
147 	uint32_t		phase;			/* state */
148 	int			residual_burst;		/* state */
149 	uint32_t		poll_each_burst;	/* tunable */
150 	union ifpoll_time	poll_start_t;		/* state */
151 
152 	uint32_t		poll_burst;		/* state */
153 	uint32_t		poll_burst_max;		/* tunable */
154 	uint32_t		user_frac;		/* tunable */
155 	uint32_t		kern_frac;		/* state */
156 
157 	uint32_t		poll_handlers; /* next free entry in pr[]. */
158 	struct iopoll_rec	pr[IFPOLL_LIST_LEN];
159 
160 	struct sysctl_ctx_list	poll_sysctl_ctx;
161 	struct sysctl_oid	*poll_sysctl_tree;
162 } __cachealign;
163 
164 struct poll_comm {
165 	struct systimer		pollclock;
166 	int			poll_cpuid;
167 
168 	int			stfrac_count;		/* state */
169 	int			poll_stfrac;		/* tunable */
170 
171 	int			txfrac_count;		/* state */
172 	int			poll_txfrac;		/* tunable */
173 
174 	int			pollhz;			/* tunable */
175 
176 	struct sysctl_ctx_list	sysctl_ctx;
177 	struct sysctl_oid	*sysctl_tree;
178 } __cachealign;
179 
180 struct stpoll_rec {
181 	struct lwkt_serialize	*serializer;
182 	struct ifnet		*ifp;
183 	ifpoll_stfn_t		status_func;
184 };
185 
186 struct stpoll_ctx {
187 	struct netmsg_base	poll_netmsg;
188 
189 	int			pollhz;
190 
191 	uint32_t		poll_handlers; /* next free entry in pr[]. */
192 	struct stpoll_rec	pr[IFPOLL_LIST_LEN];
193 
194 	struct sysctl_ctx_list	poll_sysctl_ctx;
195 	struct sysctl_oid	*poll_sysctl_tree;
196 };
197 
198 struct iopoll_sysctl_netmsg {
199 	struct netmsg_base	base;
200 	struct iopoll_ctx	*ctx;
201 };
202 
203 void		ifpoll_init_pcpu(int);
204 static void	ifpoll_register_handler(netmsg_t);
205 static void	ifpoll_deregister_handler(netmsg_t);
206 
207 /*
208  * Status polling
209  */
210 static void	stpoll_init(void);
211 static void	stpoll_handler(netmsg_t);
212 static void	stpoll_clock(struct stpoll_ctx *);
213 static int	stpoll_register(struct ifnet *, const struct ifpoll_status *);
214 static int	stpoll_deregister(struct ifnet *);
215 
216 /*
217  * RX/TX polling
218  */
219 static struct iopoll_ctx *iopoll_ctx_create(int, int);
220 static void	iopoll_init(int);
221 static void	rxpoll_handler(netmsg_t);
222 static void	txpoll_handler(netmsg_t);
223 static void	rxpollmore_handler(netmsg_t);
224 static void	txpollmore_handler(netmsg_t);
225 static void	iopoll_clock(struct iopoll_ctx *);
226 static int	iopoll_register(struct ifnet *, struct iopoll_ctx *,
227 		    const struct ifpoll_io *);
228 static int	iopoll_deregister(struct ifnet *, struct iopoll_ctx *);
229 
230 static void	iopoll_add_sysctl(struct sysctl_ctx_list *,
231 		    struct sysctl_oid_list *, struct iopoll_ctx *, int);
232 static void	sysctl_burstmax_handler(netmsg_t);
233 static int	sysctl_burstmax(SYSCTL_HANDLER_ARGS);
234 static void	sysctl_eachburst_handler(netmsg_t);
235 static int	sysctl_eachburst(SYSCTL_HANDLER_ARGS);
236 
237 /*
238  * Common functions
239  */
240 static void	poll_comm_init(int);
241 static void	poll_comm_start(int);
242 static void	poll_comm_adjust_pollhz(struct poll_comm *);
243 static void	poll_comm_systimer0(systimer_t, int, struct intrframe *);
244 static void	poll_comm_systimer(systimer_t, int, struct intrframe *);
245 static void	sysctl_pollhz_handler(netmsg_t);
246 static void	sysctl_stfrac_handler(netmsg_t);
247 static void	sysctl_txfrac_handler(netmsg_t);
248 static int	sysctl_pollhz(SYSCTL_HANDLER_ARGS);
249 static int	sysctl_stfrac(SYSCTL_HANDLER_ARGS);
250 static int	sysctl_txfrac(SYSCTL_HANDLER_ARGS);
251 
252 static struct stpoll_ctx	stpoll_context;
253 static struct poll_comm		*poll_common[MAXCPU];
254 static struct iopoll_ctx	*rxpoll_context[MAXCPU];
255 static struct iopoll_ctx	*txpoll_context[MAXCPU];
256 
257 SYSCTL_NODE(_net, OID_AUTO, ifpoll, CTLFLAG_RW, 0,
258 	    "Network device polling parameters");
259 
260 static int	iopoll_burst_max = IOPOLL_BURST_MAX;
261 static int	iopoll_each_burst = IOPOLL_EACH_BURST;
262 
263 static int	ifpoll_pollhz = IFPOLL_FREQ_DEFAULT;
264 static int	ifpoll_stfrac = IFPOLL_STFRAC_DEFAULT;
265 static int	ifpoll_txfrac = IFPOLL_TXFRAC_DEFAULT;
266 
267 TUNABLE_INT("net.ifpoll.burst_max", &iopoll_burst_max);
268 TUNABLE_INT("net.ifpoll.each_burst", &iopoll_each_burst);
269 TUNABLE_INT("net.ifpoll.pollhz", &ifpoll_pollhz);
270 TUNABLE_INT("net.ifpoll.status_frac", &ifpoll_stfrac);
271 TUNABLE_INT("net.ifpoll.tx_frac", &ifpoll_txfrac);
272 
273 static __inline void
274 ifpoll_sendmsg_oncpu(netmsg_t msg)
275 {
276 	if (msg->lmsg.ms_flags & MSGF_DONE)
277 		lwkt_sendmsg(netisr_portfn(mycpuid), &msg->lmsg);
278 }
279 
280 static __inline void
281 sched_stpoll(struct stpoll_ctx *st_ctx)
282 {
283 	ifpoll_sendmsg_oncpu((netmsg_t)&st_ctx->poll_netmsg);
284 }
285 
286 static __inline void
287 sched_iopoll(struct iopoll_ctx *io_ctx)
288 {
289 	ifpoll_sendmsg_oncpu((netmsg_t)&io_ctx->poll_netmsg);
290 }
291 
292 static __inline void
293 sched_iopollmore(struct iopoll_ctx *io_ctx)
294 {
295 	ifpoll_sendmsg_oncpu((netmsg_t)&io_ctx->poll_more_netmsg);
296 }
297 
298 static __inline void
299 ifpoll_time_get(union ifpoll_time *t)
300 {
301 	if (__predict_true(tsc_present))
302 		t->tsc = rdtsc();
303 	else
304 		microuptime(&t->tv);
305 }
306 
307 /* Return time diff in us */
308 static __inline int
309 ifpoll_time_diff(const union ifpoll_time *s, const union ifpoll_time *e)
310 {
311 	if (__predict_true(tsc_present)) {
312 		return (((e->tsc - s->tsc) * 1000000) / tsc_frequency);
313 	} else {
314 		return ((e->tv.tv_usec - s->tv.tv_usec) +
315 			(e->tv.tv_sec - s->tv.tv_sec) * 1000000);
316 	}
317 }
318 
319 /*
320  * Initialize per-cpu qpolling(4) context.  Called from kern_clock.c:
321  */
322 void
323 ifpoll_init_pcpu(int cpuid)
324 {
325 	if (cpuid >= ncpus2)
326 		return;
327 
328 	poll_comm_init(cpuid);
329 
330 	if (cpuid == 0)
331 		stpoll_init();
332 	iopoll_init(cpuid);
333 
334 	poll_comm_start(cpuid);
335 }
336 
337 int
338 ifpoll_register(struct ifnet *ifp)
339 {
340 	struct ifpoll_info *info;
341 	struct netmsg_base nmsg;
342 	int error;
343 
344 	if (ifp->if_npoll == NULL) {
345 		/* Device does not support polling */
346 		return EOPNOTSUPP;
347 	}
348 
349 	info = kmalloc(sizeof(*info), M_TEMP, M_WAITOK | M_ZERO);
350 
351 	/*
352 	 * Attempt to register.  Interlock with IFF_NPOLLING.
353 	 */
354 
355 	ifnet_serialize_all(ifp);
356 
357 	if (ifp->if_flags & IFF_NPOLLING) {
358 		/* Already polling */
359 		ifnet_deserialize_all(ifp);
360 		kfree(info, M_TEMP);
361 		return EBUSY;
362 	}
363 
364 	info->ifpi_ifp = ifp;
365 
366 	ifp->if_flags |= IFF_NPOLLING;
367 	ifp->if_npoll(ifp, info);
368 	KASSERT(ifp->if_npoll_cpuid >= 0, ("invalid npoll cpuid"));
369 
370 	ifnet_deserialize_all(ifp);
371 
372 	netmsg_init(&nmsg, NULL, &curthread->td_msgport,
373 		    0, ifpoll_register_handler);
374 	nmsg.lmsg.u.ms_resultp = info;
375 
376 	error = lwkt_domsg(netisr_portfn(0), &nmsg.lmsg, 0);
377 	if (error) {
378 		if (!ifpoll_deregister(ifp)) {
379 			if_printf(ifp, "ifpoll_register: "
380 				  "ifpoll_deregister failed!\n");
381 		}
382 	}
383 
384 	kfree(info, M_TEMP);
385 	return error;
386 }
387 
388 int
389 ifpoll_deregister(struct ifnet *ifp)
390 {
391 	struct netmsg_base nmsg;
392 	int error;
393 
394 	if (ifp->if_npoll == NULL)
395 		return EOPNOTSUPP;
396 
397 	ifnet_serialize_all(ifp);
398 
399 	if ((ifp->if_flags & IFF_NPOLLING) == 0) {
400 		ifnet_deserialize_all(ifp);
401 		return EINVAL;
402 	}
403 	ifp->if_flags &= ~IFF_NPOLLING;
404 
405 	ifnet_deserialize_all(ifp);
406 
407 	netmsg_init(&nmsg, NULL, &curthread->td_msgport,
408 		    0, ifpoll_deregister_handler);
409 	nmsg.lmsg.u.ms_resultp = ifp;
410 
411 	error = lwkt_domsg(netisr_portfn(0), &nmsg.lmsg, 0);
412 	if (!error) {
413 		ifnet_serialize_all(ifp);
414 		ifp->if_npoll(ifp, NULL);
415 		KASSERT(ifp->if_npoll_cpuid < 0, ("invalid npoll cpuid"));
416 		ifnet_deserialize_all(ifp);
417 	}
418 	return error;
419 }
420 
421 static void
422 ifpoll_register_handler(netmsg_t nmsg)
423 {
424 	const struct ifpoll_info *info = nmsg->lmsg.u.ms_resultp;
425 	int cpuid = mycpuid, nextcpu;
426 	int error;
427 
428 	KKASSERT(cpuid < ncpus2);
429 	KKASSERT(&curthread->td_msgport == netisr_portfn(cpuid));
430 
431 	if (cpuid == 0) {
432 		error = stpoll_register(info->ifpi_ifp, &info->ifpi_status);
433 		if (error)
434 			goto failed;
435 	}
436 
437 	error = iopoll_register(info->ifpi_ifp, rxpoll_context[cpuid],
438 				&info->ifpi_rx[cpuid]);
439 	if (error)
440 		goto failed;
441 
442 	error = iopoll_register(info->ifpi_ifp, txpoll_context[cpuid],
443 				&info->ifpi_tx[cpuid]);
444 	if (error)
445 		goto failed;
446 
447 	/* Adjust polling frequency, after all registration is done */
448 	poll_comm_adjust_pollhz(poll_common[cpuid]);
449 
450 	nextcpu = cpuid + 1;
451 	if (nextcpu < ncpus2)
452 		lwkt_forwardmsg(netisr_portfn(nextcpu), &nmsg->lmsg);
453 	else
454 		lwkt_replymsg(&nmsg->lmsg, 0);
455 	return;
456 failed:
457 	lwkt_replymsg(&nmsg->lmsg, error);
458 }
459 
460 static void
461 ifpoll_deregister_handler(netmsg_t nmsg)
462 {
463 	struct ifnet *ifp = nmsg->lmsg.u.ms_resultp;
464 	int cpuid = mycpuid, nextcpu;
465 
466 	KKASSERT(cpuid < ncpus2);
467 	KKASSERT(&curthread->td_msgport == netisr_portfn(cpuid));
468 
469 	/* Ignore errors */
470 	if (cpuid == 0)
471 		stpoll_deregister(ifp);
472 	iopoll_deregister(ifp, rxpoll_context[cpuid]);
473 	iopoll_deregister(ifp, txpoll_context[cpuid]);
474 
475 	/* Adjust polling frequency, after all deregistration is done */
476 	poll_comm_adjust_pollhz(poll_common[cpuid]);
477 
478 	nextcpu = cpuid + 1;
479 	if (nextcpu < ncpus2)
480 		lwkt_forwardmsg(netisr_portfn(nextcpu), &nmsg->lmsg);
481 	else
482 		lwkt_replymsg(&nmsg->lmsg, 0);
483 }
484 
485 static void
486 stpoll_init(void)
487 {
488 	struct stpoll_ctx *st_ctx = &stpoll_context;
489 	const struct poll_comm *comm = poll_common[0];
490 
491 	st_ctx->pollhz = comm->pollhz / (comm->poll_stfrac + 1);
492 
493 	sysctl_ctx_init(&st_ctx->poll_sysctl_ctx);
494 	st_ctx->poll_sysctl_tree = SYSCTL_ADD_NODE(&st_ctx->poll_sysctl_ctx,
495 				   SYSCTL_CHILDREN(comm->sysctl_tree),
496 				   OID_AUTO, "status", CTLFLAG_RD, 0, "");
497 
498 	SYSCTL_ADD_UINT(&st_ctx->poll_sysctl_ctx,
499 			SYSCTL_CHILDREN(st_ctx->poll_sysctl_tree),
500 			OID_AUTO, "handlers", CTLFLAG_RD,
501 			&st_ctx->poll_handlers, 0,
502 			"Number of registered status poll handlers");
503 
504 	netmsg_init(&st_ctx->poll_netmsg, NULL, &netisr_adone_rport,
505 		    0, stpoll_handler);
506 }
507 
508 /*
509  * stpoll_handler is scheduled by sched_stpoll when appropriate, typically
510  * once per polling systimer tick.
511  */
512 static void
513 stpoll_handler(netmsg_t msg)
514 {
515 	struct stpoll_ctx *st_ctx = &stpoll_context;
516 	struct thread *td = curthread;
517 	int i;
518 
519 	KKASSERT(&td->td_msgport == netisr_portfn(0));
520 
521 	crit_enter_quick(td);
522 
523 	/* Reply ASAP */
524 	lwkt_replymsg(&msg->lmsg, 0);
525 
526 	if (st_ctx->poll_handlers == 0) {
527 		crit_exit_quick(td);
528 		return;
529 	}
530 
531 	for (i = 0; i < st_ctx->poll_handlers; ++i) {
532 		const struct stpoll_rec *rec = &st_ctx->pr[i];
533 		struct ifnet *ifp = rec->ifp;
534 
535 		if (!lwkt_serialize_try(rec->serializer))
536 			continue;
537 
538 		if ((ifp->if_flags & (IFF_RUNNING | IFF_NPOLLING)) ==
539 		    (IFF_RUNNING | IFF_NPOLLING))
540 			rec->status_func(ifp, st_ctx->pollhz);
541 
542 		lwkt_serialize_exit(rec->serializer);
543 	}
544 
545 	crit_exit_quick(td);
546 }
547 
548 /*
549  * Hook from status poll systimer.  Tries to schedule an status poll.
550  * NOTE: Caller should hold critical section.
551  */
552 static void
553 stpoll_clock(struct stpoll_ctx *st_ctx)
554 {
555 	KKASSERT(mycpuid == 0);
556 
557 	if (st_ctx->poll_handlers == 0)
558 		return;
559 	sched_stpoll(st_ctx);
560 }
561 
562 static int
563 stpoll_register(struct ifnet *ifp, const struct ifpoll_status *st_rec)
564 {
565 	struct stpoll_ctx *st_ctx = &stpoll_context;
566 	int error;
567 
568 	KKASSERT(&curthread->td_msgport == netisr_portfn(0));
569 
570 	if (st_rec->status_func == NULL)
571 		return 0;
572 
573 	/*
574 	 * Check if there is room.
575 	 */
576 	if (st_ctx->poll_handlers >= IFPOLL_LIST_LEN) {
577 		/*
578 		 * List full, cannot register more entries.
579 		 * This should never happen; if it does, it is probably a
580 		 * broken driver trying to register multiple times. Checking
581 		 * this at runtime is expensive, and won't solve the problem
582 		 * anyways, so just report a few times and then give up.
583 		 */
584 		static int verbose = 10; /* XXX */
585 
586 		if (verbose > 0) {
587 			kprintf("status poll handlers list full, "
588 				"maybe a broken driver ?\n");
589 			verbose--;
590 		}
591 		error = ENOENT;
592 	} else {
593 		struct stpoll_rec *rec = &st_ctx->pr[st_ctx->poll_handlers];
594 
595 		rec->ifp = ifp;
596 		rec->serializer = st_rec->serializer;
597 		rec->status_func = st_rec->status_func;
598 
599 		st_ctx->poll_handlers++;
600 		error = 0;
601 	}
602 	return error;
603 }
604 
605 static int
606 stpoll_deregister(struct ifnet *ifp)
607 {
608 	struct stpoll_ctx *st_ctx = &stpoll_context;
609 	int i, error;
610 
611 	KKASSERT(&curthread->td_msgport == netisr_portfn(0));
612 
613 	for (i = 0; i < st_ctx->poll_handlers; ++i) {
614 		if (st_ctx->pr[i].ifp == ifp) /* Found it */
615 			break;
616 	}
617 	if (i == st_ctx->poll_handlers) {
618 		kprintf("stpoll_deregister: ifp not found!!!\n");
619 		error = ENOENT;
620 	} else {
621 		st_ctx->poll_handlers--;
622 		if (i < st_ctx->poll_handlers) {
623 			/* Last entry replaces this one. */
624 			st_ctx->pr[i] = st_ctx->pr[st_ctx->poll_handlers];
625 		}
626 		error = 0;
627 	}
628 	return error;
629 }
630 
631 static __inline void
632 iopoll_reset_state(struct iopoll_ctx *io_ctx)
633 {
634 	crit_enter();
635 	io_ctx->poll_burst = 5;
636 	io_ctx->pending_polls = 0;
637 	io_ctx->residual_burst = 0;
638 	io_ctx->phase = 0;
639 	io_ctx->kern_frac = 0;
640 	bzero(&io_ctx->poll_start_t, sizeof(io_ctx->poll_start_t));
641 	bzero(&io_ctx->prev_t, sizeof(io_ctx->prev_t));
642 	crit_exit();
643 }
644 
645 static void
646 iopoll_init(int cpuid)
647 {
648 	KKASSERT(cpuid < ncpus2);
649 
650 	rxpoll_context[cpuid] = iopoll_ctx_create(cpuid, IFPOLL_RX);
651 	txpoll_context[cpuid] = iopoll_ctx_create(cpuid, IFPOLL_TX);
652 }
653 
654 static struct iopoll_ctx *
655 iopoll_ctx_create(int cpuid, int poll_type)
656 {
657 	struct poll_comm *comm;
658 	struct iopoll_ctx *io_ctx;
659 	const char *poll_type_str;
660 	netisr_fn_t handler, more_handler;
661 
662 	KKASSERT(poll_type == IFPOLL_RX || poll_type == IFPOLL_TX);
663 
664 	/*
665 	 * Make sure that tunables are in sane state
666 	 */
667 	if (iopoll_burst_max < MIN_IOPOLL_BURST_MAX)
668 		iopoll_burst_max = MIN_IOPOLL_BURST_MAX;
669 	else if (iopoll_burst_max > MAX_IOPOLL_BURST_MAX)
670 		iopoll_burst_max = MAX_IOPOLL_BURST_MAX;
671 
672 	if (iopoll_each_burst > iopoll_burst_max)
673 		iopoll_each_burst = iopoll_burst_max;
674 
675 	comm = poll_common[cpuid];
676 
677 	/*
678 	 * Create the per-cpu polling context
679 	 */
680 	io_ctx = kmalloc(sizeof(*io_ctx), M_DEVBUF, M_WAITOK | M_ZERO);
681 
682 	io_ctx->poll_each_burst = iopoll_each_burst;
683 	io_ctx->poll_burst_max = iopoll_burst_max;
684 	io_ctx->user_frac = 50;
685 	if (poll_type == IFPOLL_RX)
686 		io_ctx->pollhz = comm->pollhz;
687 	else
688 		io_ctx->pollhz = comm->pollhz / (comm->poll_txfrac + 1);
689 	io_ctx->poll_cpuid = cpuid;
690 	iopoll_reset_state(io_ctx);
691 
692 	if (poll_type == IFPOLL_RX) {
693 		handler = rxpoll_handler;
694 		more_handler = rxpollmore_handler;
695 	} else {
696 		handler = txpoll_handler;
697 		more_handler = txpollmore_handler;
698 	}
699 
700 	netmsg_init(&io_ctx->poll_netmsg, NULL, &netisr_adone_rport,
701 	    0, handler);
702 	io_ctx->poll_netmsg.lmsg.u.ms_resultp = io_ctx;
703 
704 	netmsg_init(&io_ctx->poll_more_netmsg, NULL, &netisr_adone_rport,
705 	    0, more_handler);
706 	io_ctx->poll_more_netmsg.lmsg.u.ms_resultp = io_ctx;
707 
708 	/*
709 	 * Initialize per-cpu sysctl nodes
710 	 */
711 	if (poll_type == IFPOLL_RX)
712 		poll_type_str = "rx";
713 	else
714 		poll_type_str = "tx";
715 
716 	sysctl_ctx_init(&io_ctx->poll_sysctl_ctx);
717 	io_ctx->poll_sysctl_tree = SYSCTL_ADD_NODE(&io_ctx->poll_sysctl_ctx,
718 				   SYSCTL_CHILDREN(comm->sysctl_tree),
719 				   OID_AUTO, poll_type_str, CTLFLAG_RD, 0, "");
720 	iopoll_add_sysctl(&io_ctx->poll_sysctl_ctx,
721 	    SYSCTL_CHILDREN(io_ctx->poll_sysctl_tree), io_ctx, poll_type);
722 
723 	return io_ctx;
724 }
725 
726 /*
727  * Hook from iopoll systimer.  Tries to schedule an iopoll, but keeps
728  * track of lost ticks due to the previous handler taking too long.
729  * Normally, this should not happen, because polling handler should
730  * run for a short time.  However, in some cases (e.g. when there are
731  * changes in link status etc.) the drivers take a very long time
732  * (even in the order of milliseconds) to reset and reconfigure the
733  * device, causing apparent lost polls.
734  *
735  * The first part of the code is just for debugging purposes, and tries
736  * to count how often hardclock ticks are shorter than they should,
737  * meaning either stray interrupts or delayed events.
738  *
739  * WARNING! called from fastint or IPI, the MP lock might not be held.
740  * NOTE: Caller should hold critical section.
741  */
742 static void
743 iopoll_clock(struct iopoll_ctx *io_ctx)
744 {
745 	union ifpoll_time t;
746 	int delta;
747 
748 	KKASSERT(mycpuid == io_ctx->poll_cpuid);
749 
750 	if (io_ctx->poll_handlers == 0)
751 		return;
752 
753 	ifpoll_time_get(&t);
754 	delta = ifpoll_time_diff(&io_ctx->prev_t, &t);
755 	if (delta * io_ctx->pollhz < 500000)
756 		io_ctx->short_ticks++;
757 	else
758 		io_ctx->prev_t = t;
759 
760 	if (io_ctx->pending_polls > 100) {
761 		/*
762 		 * Too much, assume it has stalled (not always true
763 		 * see comment above).
764 		 */
765 		io_ctx->stalled++;
766 		io_ctx->pending_polls = 0;
767 		io_ctx->phase = 0;
768 	}
769 
770 	if (io_ctx->phase <= 2) {
771 		if (io_ctx->phase != 0)
772 			io_ctx->suspect++;
773 		io_ctx->phase = 1;
774 		sched_iopoll(io_ctx);
775 		io_ctx->phase = 2;
776 	}
777 	if (io_ctx->pending_polls++ > 0)
778 		io_ctx->lost_polls++;
779 }
780 
781 /*
782  * rxpoll_handler and txpoll_handler are scheduled by sched_iopoll when
783  * appropriate, typically once per polling systimer tick.
784  *
785  * Note that the message is replied immediately in order to allow a new
786  * ISR to be scheduled in the handler.
787  */
788 static void
789 rxpoll_handler(netmsg_t msg)
790 {
791 	struct iopoll_ctx *io_ctx;
792 	struct thread *td = curthread;
793 	int i, cycles;
794 
795 	io_ctx = msg->lmsg.u.ms_resultp;
796 	KKASSERT(&td->td_msgport == netisr_portfn(io_ctx->poll_cpuid));
797 
798 	crit_enter_quick(td);
799 
800 	/* Reply ASAP */
801 	lwkt_replymsg(&msg->lmsg, 0);
802 
803 	if (io_ctx->poll_handlers == 0) {
804 		crit_exit_quick(td);
805 		return;
806 	}
807 
808 	io_ctx->phase = 3;
809 	if (io_ctx->residual_burst == 0) {
810 		/* First call in this tick */
811 		ifpoll_time_get(&io_ctx->poll_start_t);
812 		io_ctx->residual_burst = io_ctx->poll_burst;
813 	}
814 	cycles = (io_ctx->residual_burst < io_ctx->poll_each_burst) ?
815 		 io_ctx->residual_burst : io_ctx->poll_each_burst;
816 	io_ctx->residual_burst -= cycles;
817 
818 	for (i = 0; i < io_ctx->poll_handlers; i++) {
819 		const struct iopoll_rec *rec = &io_ctx->pr[i];
820 		struct ifnet *ifp = rec->ifp;
821 
822 		if (!lwkt_serialize_try(rec->serializer))
823 			continue;
824 
825 		if ((ifp->if_flags & (IFF_RUNNING | IFF_NPOLLING)) ==
826 		    (IFF_RUNNING | IFF_NPOLLING))
827 			rec->poll_func(ifp, rec->arg, cycles);
828 
829 		lwkt_serialize_exit(rec->serializer);
830 	}
831 
832 	/*
833 	 * Do a quick exit/enter to catch any higher-priority
834 	 * interrupt sources.
835 	 */
836 	crit_exit_quick(td);
837 	crit_enter_quick(td);
838 
839 	sched_iopollmore(io_ctx);
840 	io_ctx->phase = 4;
841 
842 	crit_exit_quick(td);
843 }
844 
845 static void
846 txpoll_handler(netmsg_t msg)
847 {
848 	struct iopoll_ctx *io_ctx;
849 	struct thread *td = curthread;
850 	int i;
851 
852 	io_ctx = msg->lmsg.u.ms_resultp;
853 	KKASSERT(&td->td_msgport == netisr_portfn(io_ctx->poll_cpuid));
854 
855 	crit_enter_quick(td);
856 
857 	/* Reply ASAP */
858 	lwkt_replymsg(&msg->lmsg, 0);
859 
860 	if (io_ctx->poll_handlers == 0) {
861 		crit_exit_quick(td);
862 		return;
863 	}
864 
865 	io_ctx->phase = 3;
866 
867 	for (i = 0; i < io_ctx->poll_handlers; i++) {
868 		const struct iopoll_rec *rec = &io_ctx->pr[i];
869 		struct ifnet *ifp = rec->ifp;
870 
871 		if (!lwkt_serialize_try(rec->serializer))
872 			continue;
873 
874 		if ((ifp->if_flags & (IFF_RUNNING | IFF_NPOLLING)) ==
875 		    (IFF_RUNNING | IFF_NPOLLING))
876 			rec->poll_func(ifp, rec->arg, -1);
877 
878 		lwkt_serialize_exit(rec->serializer);
879 	}
880 
881 	/*
882 	 * Do a quick exit/enter to catch any higher-priority
883 	 * interrupt sources.
884 	 */
885 	crit_exit_quick(td);
886 	crit_enter_quick(td);
887 
888 	sched_iopollmore(io_ctx);
889 	io_ctx->phase = 4;
890 
891 	crit_exit_quick(td);
892 }
893 
894 /*
895  * rxpollmore_handler and txpollmore_handler are called after other netisr's,
896  * possibly scheduling another rxpoll_handler or txpoll_handler call, or
897  * adapting the burst size for the next cycle.
898  *
899  * It is very bad to fetch large bursts of packets from a single card at once,
900  * because the burst could take a long time to be completely processed leading
901  * to unfairness.  To reduce the problem, and also to account better for time
902  * spent in network-related processing, we split the burst in smaller chunks
903  * of fixed size, giving control to the other netisr's between chunks.  This
904  * helps in improving the fairness, reducing livelock and accounting for the
905  * work performed in low level handling.
906  */
907 static void
908 rxpollmore_handler(netmsg_t msg)
909 {
910 	struct thread *td = curthread;
911 	struct iopoll_ctx *io_ctx;
912 	union ifpoll_time t;
913 	int kern_load;
914 	uint32_t pending_polls;
915 
916 	io_ctx = msg->lmsg.u.ms_resultp;
917 	KKASSERT(&td->td_msgport == netisr_portfn(io_ctx->poll_cpuid));
918 
919 	crit_enter_quick(td);
920 
921 	/* Replay ASAP */
922 	lwkt_replymsg(&msg->lmsg, 0);
923 
924 	if (io_ctx->poll_handlers == 0) {
925 		crit_exit_quick(td);
926 		return;
927 	}
928 
929 	io_ctx->phase = 5;
930 	if (io_ctx->residual_burst > 0) {
931 		sched_iopoll(io_ctx);
932 		crit_exit_quick(td);
933 		/* Will run immediately on return, followed by netisrs */
934 		return;
935 	}
936 
937 	/* Here we can account time spent in iopoll's in this tick */
938 	ifpoll_time_get(&t);
939 	kern_load = ifpoll_time_diff(&io_ctx->poll_start_t, &t);
940 	kern_load = (kern_load * io_ctx->pollhz) / 10000; /* 0..100 */
941 	io_ctx->kern_frac = kern_load;
942 
943 	if (kern_load > (100 - io_ctx->user_frac)) {
944 		/* Try decrease ticks */
945 		if (io_ctx->poll_burst > 1)
946 			io_ctx->poll_burst--;
947 	} else {
948 		if (io_ctx->poll_burst < io_ctx->poll_burst_max)
949 			io_ctx->poll_burst++;
950 	}
951 
952 	io_ctx->pending_polls--;
953 	pending_polls = io_ctx->pending_polls;
954 
955 	if (pending_polls == 0) {
956 		/* We are done */
957 		io_ctx->phase = 0;
958 	} else {
959 		/*
960 		 * Last cycle was long and caused us to miss one or more
961 		 * hardclock ticks.  Restart processing again, but slightly
962 		 * reduce the burst size to prevent that this happens again.
963 		 */
964 		io_ctx->poll_burst -= (io_ctx->poll_burst / 8);
965 		if (io_ctx->poll_burst < 1)
966 			io_ctx->poll_burst = 1;
967 		sched_iopoll(io_ctx);
968 		io_ctx->phase = 6;
969 	}
970 
971 	crit_exit_quick(td);
972 }
973 
974 static void
975 txpollmore_handler(netmsg_t msg)
976 {
977 	struct thread *td = curthread;
978 	struct iopoll_ctx *io_ctx;
979 	uint32_t pending_polls;
980 
981 	io_ctx = msg->lmsg.u.ms_resultp;
982 	KKASSERT(&td->td_msgport == netisr_portfn(io_ctx->poll_cpuid));
983 
984 	crit_enter_quick(td);
985 
986 	/* Replay ASAP */
987 	lwkt_replymsg(&msg->lmsg, 0);
988 
989 	if (io_ctx->poll_handlers == 0) {
990 		crit_exit_quick(td);
991 		return;
992 	}
993 
994 	io_ctx->phase = 5;
995 
996 	io_ctx->pending_polls--;
997 	pending_polls = io_ctx->pending_polls;
998 
999 	if (pending_polls == 0) {
1000 		/* We are done */
1001 		io_ctx->phase = 0;
1002 	} else {
1003 		/*
1004 		 * Last cycle was long and caused us to miss one or more
1005 		 * hardclock ticks.  Restart processing again.
1006 		 */
1007 		sched_iopoll(io_ctx);
1008 		io_ctx->phase = 6;
1009 	}
1010 
1011 	crit_exit_quick(td);
1012 }
1013 
1014 static void
1015 iopoll_add_sysctl(struct sysctl_ctx_list *ctx, struct sysctl_oid_list *parent,
1016     struct iopoll_ctx *io_ctx, int poll_type)
1017 {
1018 	if (poll_type == IFPOLL_RX) {
1019 		SYSCTL_ADD_PROC(ctx, parent, OID_AUTO, "burst_max",
1020 		    CTLTYPE_UINT | CTLFLAG_RW, io_ctx, 0, sysctl_burstmax,
1021 		    "IU", "Max Polling burst size");
1022 
1023 		SYSCTL_ADD_PROC(ctx, parent, OID_AUTO, "each_burst",
1024 		    CTLTYPE_UINT | CTLFLAG_RW, io_ctx, 0, sysctl_eachburst,
1025 		    "IU", "Max size of each burst");
1026 
1027 		SYSCTL_ADD_UINT(ctx, parent, OID_AUTO, "burst", CTLFLAG_RD,
1028 		    &io_ctx->poll_burst, 0, "Current polling burst size");
1029 
1030 		SYSCTL_ADD_UINT(ctx, parent, OID_AUTO, "user_frac", CTLFLAG_RW,
1031 		    &io_ctx->user_frac, 0, "Desired user fraction of cpu time");
1032 
1033 		SYSCTL_ADD_UINT(ctx, parent, OID_AUTO, "kern_frac", CTLFLAG_RD,
1034 		    &io_ctx->kern_frac, 0, "Kernel fraction of cpu time");
1035 
1036 		SYSCTL_ADD_INT(ctx, parent, OID_AUTO, "residual_burst", CTLFLAG_RD,
1037 		    &io_ctx->residual_burst, 0,
1038 		    "# of residual cycles in burst");
1039 	}
1040 
1041 	SYSCTL_ADD_UINT(ctx, parent, OID_AUTO, "phase", CTLFLAG_RD,
1042 	    &io_ctx->phase, 0, "Polling phase");
1043 
1044 	SYSCTL_ADD_ULONG(ctx, parent, OID_AUTO, "suspect", CTLFLAG_RW,
1045 	    &io_ctx->suspect, "Suspected events");
1046 
1047 	SYSCTL_ADD_ULONG(ctx, parent, OID_AUTO, "stalled", CTLFLAG_RW,
1048 	    &io_ctx->stalled, "Potential stalls");
1049 
1050 	SYSCTL_ADD_ULONG(ctx, parent, OID_AUTO, "short_ticks", CTLFLAG_RW,
1051 	    &io_ctx->short_ticks,
1052 	    "Hardclock ticks shorter than they should be");
1053 
1054 	SYSCTL_ADD_ULONG(ctx, parent, OID_AUTO, "lost_polls", CTLFLAG_RW,
1055 	    &io_ctx->lost_polls,
1056 	    "How many times we would have lost a poll tick");
1057 
1058 	SYSCTL_ADD_UINT(ctx, parent, OID_AUTO, "pending_polls", CTLFLAG_RD,
1059 	    &io_ctx->pending_polls, 0, "Do we need to poll again");
1060 
1061 	SYSCTL_ADD_UINT(ctx, parent, OID_AUTO, "handlers", CTLFLAG_RD,
1062 	    &io_ctx->poll_handlers, 0, "Number of registered poll handlers");
1063 }
1064 
1065 static void
1066 sysctl_burstmax_handler(netmsg_t nmsg)
1067 {
1068 	struct iopoll_sysctl_netmsg *msg = (struct iopoll_sysctl_netmsg *)nmsg;
1069 	struct iopoll_ctx *io_ctx;
1070 
1071 	io_ctx = msg->ctx;
1072 	KKASSERT(&curthread->td_msgport == netisr_portfn(io_ctx->poll_cpuid));
1073 
1074 	io_ctx->poll_burst_max = nmsg->lmsg.u.ms_result;
1075 	if (io_ctx->poll_each_burst > io_ctx->poll_burst_max)
1076 		io_ctx->poll_each_burst = io_ctx->poll_burst_max;
1077 	if (io_ctx->poll_burst > io_ctx->poll_burst_max)
1078 		io_ctx->poll_burst = io_ctx->poll_burst_max;
1079 	if (io_ctx->residual_burst > io_ctx->poll_burst_max)
1080 		io_ctx->residual_burst = io_ctx->poll_burst_max;
1081 
1082 	lwkt_replymsg(&nmsg->lmsg, 0);
1083 }
1084 
1085 static int
1086 sysctl_burstmax(SYSCTL_HANDLER_ARGS)
1087 {
1088 	struct iopoll_ctx *io_ctx = arg1;
1089 	struct iopoll_sysctl_netmsg msg;
1090 	uint32_t burst_max;
1091 	int error;
1092 
1093 	burst_max = io_ctx->poll_burst_max;
1094 	error = sysctl_handle_int(oidp, &burst_max, 0, req);
1095 	if (error || req->newptr == NULL)
1096 		return error;
1097 	if (burst_max < MIN_IOPOLL_BURST_MAX)
1098 		burst_max = MIN_IOPOLL_BURST_MAX;
1099 	else if (burst_max > MAX_IOPOLL_BURST_MAX)
1100 		burst_max = MAX_IOPOLL_BURST_MAX;
1101 
1102 	netmsg_init(&msg.base, NULL, &curthread->td_msgport,
1103 		    0, sysctl_burstmax_handler);
1104 	msg.base.lmsg.u.ms_result = burst_max;
1105 	msg.ctx = io_ctx;
1106 
1107 	return lwkt_domsg(netisr_portfn(io_ctx->poll_cpuid), &msg.base.lmsg, 0);
1108 }
1109 
1110 static void
1111 sysctl_eachburst_handler(netmsg_t nmsg)
1112 {
1113 	struct iopoll_sysctl_netmsg *msg = (struct iopoll_sysctl_netmsg *)nmsg;
1114 	struct iopoll_ctx *io_ctx;
1115 	uint32_t each_burst;
1116 
1117 	io_ctx = msg->ctx;
1118 	KKASSERT(&curthread->td_msgport == netisr_portfn(io_ctx->poll_cpuid));
1119 
1120 	each_burst = nmsg->lmsg.u.ms_result;
1121 	if (each_burst > io_ctx->poll_burst_max)
1122 		each_burst = io_ctx->poll_burst_max;
1123 	else if (each_burst < 1)
1124 		each_burst = 1;
1125 	io_ctx->poll_each_burst = each_burst;
1126 
1127 	lwkt_replymsg(&nmsg->lmsg, 0);
1128 }
1129 
1130 static int
1131 sysctl_eachburst(SYSCTL_HANDLER_ARGS)
1132 {
1133 	struct iopoll_ctx *io_ctx = arg1;
1134 	struct iopoll_sysctl_netmsg msg;
1135 	uint32_t each_burst;
1136 	int error;
1137 
1138 	each_burst = io_ctx->poll_each_burst;
1139 	error = sysctl_handle_int(oidp, &each_burst, 0, req);
1140 	if (error || req->newptr == NULL)
1141 		return error;
1142 
1143 	netmsg_init(&msg.base, NULL, &curthread->td_msgport,
1144 		    0, sysctl_eachburst_handler);
1145 	msg.base.lmsg.u.ms_result = each_burst;
1146 	msg.ctx = io_ctx;
1147 
1148 	return lwkt_domsg(netisr_portfn(io_ctx->poll_cpuid), &msg.base.lmsg, 0);
1149 }
1150 
1151 static int
1152 iopoll_register(struct ifnet *ifp, struct iopoll_ctx *io_ctx,
1153 		const struct ifpoll_io *io_rec)
1154 {
1155 	int error;
1156 
1157 	KKASSERT(&curthread->td_msgport == netisr_portfn(io_ctx->poll_cpuid));
1158 
1159 	if (io_rec->poll_func == NULL)
1160 		return 0;
1161 
1162 	/*
1163 	 * Check if there is room.
1164 	 */
1165 	if (io_ctx->poll_handlers >= IFPOLL_LIST_LEN) {
1166 		/*
1167 		 * List full, cannot register more entries.
1168 		 * This should never happen; if it does, it is probably a
1169 		 * broken driver trying to register multiple times. Checking
1170 		 * this at runtime is expensive, and won't solve the problem
1171 		 * anyways, so just report a few times and then give up.
1172 		 */
1173 		static int verbose = 10; /* XXX */
1174 		if (verbose > 0) {
1175 			kprintf("io poll handlers list full, "
1176 				"maybe a broken driver ?\n");
1177 			verbose--;
1178 		}
1179 		error = ENOENT;
1180 	} else {
1181 		struct iopoll_rec *rec = &io_ctx->pr[io_ctx->poll_handlers];
1182 
1183 		rec->ifp = ifp;
1184 		rec->serializer = io_rec->serializer;
1185 		rec->arg = io_rec->arg;
1186 		rec->poll_func = io_rec->poll_func;
1187 
1188 		io_ctx->poll_handlers++;
1189 		error = 0;
1190 	}
1191 	return error;
1192 }
1193 
1194 static int
1195 iopoll_deregister(struct ifnet *ifp, struct iopoll_ctx *io_ctx)
1196 {
1197 	int i, error;
1198 
1199 	KKASSERT(&curthread->td_msgport == netisr_portfn(io_ctx->poll_cpuid));
1200 
1201 	for (i = 0; i < io_ctx->poll_handlers; ++i) {
1202 		if (io_ctx->pr[i].ifp == ifp) /* Found it */
1203 			break;
1204 	}
1205 	if (i == io_ctx->poll_handlers) {
1206 		error = ENOENT;
1207 	} else {
1208 		io_ctx->poll_handlers--;
1209 		if (i < io_ctx->poll_handlers) {
1210 			/* Last entry replaces this one. */
1211 			io_ctx->pr[i] = io_ctx->pr[io_ctx->poll_handlers];
1212 		}
1213 
1214 		if (io_ctx->poll_handlers == 0)
1215 			iopoll_reset_state(io_ctx);
1216 		error = 0;
1217 	}
1218 	return error;
1219 }
1220 
1221 static void
1222 poll_comm_init(int cpuid)
1223 {
1224 	struct poll_comm *comm;
1225 	char cpuid_str[16];
1226 
1227 	comm = kmalloc(sizeof(*comm), M_DEVBUF, M_WAITOK | M_ZERO);
1228 
1229 	if (ifpoll_stfrac < 0)
1230 		ifpoll_stfrac = IFPOLL_STFRAC_DEFAULT;
1231 	if (ifpoll_txfrac < 0)
1232 		ifpoll_txfrac = IFPOLL_TXFRAC_DEFAULT;
1233 
1234 	comm->pollhz = ifpoll_pollhz;
1235 	comm->poll_cpuid = cpuid;
1236 	comm->poll_stfrac = ifpoll_stfrac;
1237 	comm->poll_txfrac = ifpoll_txfrac;
1238 
1239 	ksnprintf(cpuid_str, sizeof(cpuid_str), "%d", cpuid);
1240 
1241 	sysctl_ctx_init(&comm->sysctl_ctx);
1242 	comm->sysctl_tree = SYSCTL_ADD_NODE(&comm->sysctl_ctx,
1243 			    SYSCTL_STATIC_CHILDREN(_net_ifpoll),
1244 			    OID_AUTO, cpuid_str, CTLFLAG_RD, 0, "");
1245 
1246 	SYSCTL_ADD_PROC(&comm->sysctl_ctx, SYSCTL_CHILDREN(comm->sysctl_tree),
1247 			OID_AUTO, "pollhz", CTLTYPE_INT | CTLFLAG_RW,
1248 			comm, 0, sysctl_pollhz,
1249 			"I", "Device polling frequency");
1250 
1251 	if (cpuid == 0) {
1252 		SYSCTL_ADD_PROC(&comm->sysctl_ctx,
1253 				SYSCTL_CHILDREN(comm->sysctl_tree),
1254 				OID_AUTO, "status_frac",
1255 				CTLTYPE_INT | CTLFLAG_RW,
1256 				comm, 0, sysctl_stfrac,
1257 				"I", "# of cycles before status is polled");
1258 	}
1259 	SYSCTL_ADD_PROC(&comm->sysctl_ctx, SYSCTL_CHILDREN(comm->sysctl_tree),
1260 			OID_AUTO, "tx_frac", CTLTYPE_INT | CTLFLAG_RW,
1261 			comm, 0, sysctl_txfrac,
1262 			"I", "# of cycles before TX is polled");
1263 
1264 	poll_common[cpuid] = comm;
1265 }
1266 
1267 static void
1268 poll_comm_start(int cpuid)
1269 {
1270 	struct poll_comm *comm = poll_common[cpuid];
1271 	systimer_func_t func;
1272 
1273 	/*
1274 	 * Initialize systimer
1275 	 */
1276 	if (cpuid == 0)
1277 		func = poll_comm_systimer0;
1278 	else
1279 		func = poll_comm_systimer;
1280 	systimer_init_periodic_nq(&comm->pollclock, func, comm, 1);
1281 }
1282 
1283 static void
1284 _poll_comm_systimer(struct poll_comm *comm)
1285 {
1286 	if (comm->txfrac_count-- == 0) {
1287 		comm->txfrac_count = comm->poll_txfrac;
1288 		iopoll_clock(txpoll_context[comm->poll_cpuid]);
1289 	}
1290 	iopoll_clock(rxpoll_context[comm->poll_cpuid]);
1291 }
1292 
1293 static void
1294 poll_comm_systimer0(systimer_t info, int in_ipi __unused,
1295     struct intrframe *frame __unused)
1296 {
1297 	struct poll_comm *comm = info->data;
1298 	globaldata_t gd = mycpu;
1299 
1300 	KKASSERT(comm->poll_cpuid == gd->gd_cpuid && gd->gd_cpuid == 0);
1301 
1302 	crit_enter_gd(gd);
1303 
1304 	if (comm->stfrac_count-- == 0) {
1305 		comm->stfrac_count = comm->poll_stfrac;
1306 		stpoll_clock(&stpoll_context);
1307 	}
1308 	_poll_comm_systimer(comm);
1309 
1310 	crit_exit_gd(gd);
1311 }
1312 
1313 static void
1314 poll_comm_systimer(systimer_t info, int in_ipi __unused,
1315     struct intrframe *frame __unused)
1316 {
1317 	struct poll_comm *comm = info->data;
1318 	globaldata_t gd = mycpu;
1319 
1320 	KKASSERT(comm->poll_cpuid == gd->gd_cpuid && gd->gd_cpuid != 0);
1321 
1322 	crit_enter_gd(gd);
1323 	_poll_comm_systimer(comm);
1324 	crit_exit_gd(gd);
1325 }
1326 
1327 static void
1328 poll_comm_adjust_pollhz(struct poll_comm *comm)
1329 {
1330 	uint32_t handlers;
1331 	int pollhz = 1;
1332 
1333 	KKASSERT(&curthread->td_msgport == netisr_portfn(comm->poll_cpuid));
1334 
1335 	/*
1336 	 * If there is no polling handler registered, set systimer
1337 	 * frequency to the lowest value.  Polling systimer frequency
1338 	 * will be adjusted to the requested value, once there are
1339 	 * registered handlers.
1340 	 */
1341 	handlers = rxpoll_context[mycpuid]->poll_handlers +
1342 		   txpoll_context[mycpuid]->poll_handlers;
1343 	if (comm->poll_cpuid == 0)
1344 		handlers += stpoll_context.poll_handlers;
1345 	if (handlers)
1346 		pollhz = comm->pollhz;
1347 	systimer_adjust_periodic(&comm->pollclock, pollhz);
1348 }
1349 
1350 static int
1351 sysctl_pollhz(SYSCTL_HANDLER_ARGS)
1352 {
1353 	struct poll_comm *comm = arg1;
1354 	struct netmsg_base nmsg;
1355 	int error, phz;
1356 
1357 	phz = comm->pollhz;
1358 	error = sysctl_handle_int(oidp, &phz, 0, req);
1359 	if (error || req->newptr == NULL)
1360 		return error;
1361 	if (phz <= 0)
1362 		return EINVAL;
1363 	else if (phz > IFPOLL_FREQ_MAX)
1364 		phz = IFPOLL_FREQ_MAX;
1365 
1366 	netmsg_init(&nmsg, NULL, &curthread->td_msgport,
1367 		    0, sysctl_pollhz_handler);
1368 	nmsg.lmsg.u.ms_result = phz;
1369 
1370 	return lwkt_domsg(netisr_portfn(comm->poll_cpuid), &nmsg.lmsg, 0);
1371 }
1372 
1373 static void
1374 sysctl_pollhz_handler(netmsg_t nmsg)
1375 {
1376 	struct poll_comm *comm = poll_common[mycpuid];
1377 
1378 	KKASSERT(&curthread->td_msgport == netisr_portfn(comm->poll_cpuid));
1379 
1380 	/* Save polling frequency */
1381 	comm->pollhz = nmsg->lmsg.u.ms_result;
1382 
1383 	/*
1384 	 * Adjust cached pollhz
1385 	 */
1386 	rxpoll_context[mycpuid]->pollhz = comm->pollhz;
1387 	txpoll_context[mycpuid]->pollhz =
1388 	    comm->pollhz / (comm->poll_txfrac + 1);
1389 	if (mycpuid == 0)
1390 		stpoll_context.pollhz = comm->pollhz / (comm->poll_stfrac + 1);
1391 
1392 	/*
1393 	 * Adjust polling frequency
1394 	 */
1395 	poll_comm_adjust_pollhz(comm);
1396 
1397 	lwkt_replymsg(&nmsg->lmsg, 0);
1398 }
1399 
1400 static int
1401 sysctl_stfrac(SYSCTL_HANDLER_ARGS)
1402 {
1403 	struct poll_comm *comm = arg1;
1404 	struct netmsg_base nmsg;
1405 	int error, stfrac;
1406 
1407 	KKASSERT(comm->poll_cpuid == 0);
1408 
1409 	stfrac = comm->poll_stfrac;
1410 	error = sysctl_handle_int(oidp, &stfrac, 0, req);
1411 	if (error || req->newptr == NULL)
1412 		return error;
1413 	if (stfrac < 0)
1414 		return EINVAL;
1415 
1416 	netmsg_init(&nmsg, NULL, &curthread->td_msgport,
1417 		    0, sysctl_stfrac_handler);
1418 	nmsg.lmsg.u.ms_result = stfrac;
1419 
1420 	return lwkt_domsg(netisr_portfn(comm->poll_cpuid), &nmsg.lmsg, 0);
1421 }
1422 
1423 static void
1424 sysctl_stfrac_handler(netmsg_t nmsg)
1425 {
1426 	struct poll_comm *comm = poll_common[mycpuid];
1427 	int stfrac = nmsg->lmsg.u.ms_result;
1428 
1429 	KKASSERT(&curthread->td_msgport == netisr_portfn(comm->poll_cpuid));
1430 
1431 	crit_enter();
1432 	comm->poll_stfrac = stfrac;
1433 	if (comm->stfrac_count > comm->poll_stfrac)
1434 		comm->stfrac_count = comm->poll_stfrac;
1435 	crit_exit();
1436 
1437 	lwkt_replymsg(&nmsg->lmsg, 0);
1438 }
1439 
1440 static int
1441 sysctl_txfrac(SYSCTL_HANDLER_ARGS)
1442 {
1443 	struct poll_comm *comm = arg1;
1444 	struct netmsg_base nmsg;
1445 	int error, txfrac;
1446 
1447 	txfrac = comm->poll_txfrac;
1448 	error = sysctl_handle_int(oidp, &txfrac, 0, req);
1449 	if (error || req->newptr == NULL)
1450 		return error;
1451 	if (txfrac < 0)
1452 		return EINVAL;
1453 
1454 	netmsg_init(&nmsg, NULL, &curthread->td_msgport,
1455 		    0, sysctl_txfrac_handler);
1456 	nmsg.lmsg.u.ms_result = txfrac;
1457 
1458 	return lwkt_domsg(netisr_portfn(comm->poll_cpuid), &nmsg.lmsg, 0);
1459 }
1460 
1461 static void
1462 sysctl_txfrac_handler(netmsg_t nmsg)
1463 {
1464 	struct poll_comm *comm = poll_common[mycpuid];
1465 	int txfrac = nmsg->lmsg.u.ms_result;
1466 
1467 	KKASSERT(&curthread->td_msgport == netisr_portfn(comm->poll_cpuid));
1468 
1469 	crit_enter();
1470 	comm->poll_txfrac = txfrac;
1471 	if (comm->txfrac_count > comm->poll_txfrac)
1472 		comm->txfrac_count = comm->poll_txfrac;
1473 	crit_exit();
1474 
1475 	lwkt_replymsg(&nmsg->lmsg, 0);
1476 }
1477