xref: /freebsd-13-stable/sys/net/netisr.c (revision 3bc80996974a61a4223eae4c1ccd47b6ee32a48a)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2007-2009 Robert N. M. Watson
5  * Copyright (c) 2010-2011 Juniper Networks, Inc.
6  * All rights reserved.
7  *
8  * This software was developed by Robert N. M. Watson under contract
9  * to Juniper Networks, Inc.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #include <sys/cdefs.h>
34 /*
35  * netisr is a packet dispatch service, allowing synchronous (directly
36  * dispatched) and asynchronous (deferred dispatch) processing of packets by
37  * registered protocol handlers.  Callers pass a protocol identifier and
38  * packet to netisr, along with a direct dispatch hint, and work will either
39  * be immediately processed by the registered handler, or passed to a
40  * software interrupt (SWI) thread for deferred dispatch.  Callers will
41  * generally select one or the other based on:
42  *
43  * - Whether directly dispatching a netisr handler lead to code reentrance or
44  *   lock recursion, such as entering the socket code from the socket code.
45  * - Whether directly dispatching a netisr handler lead to recursive
46  *   processing, such as when decapsulating several wrapped layers of tunnel
47  *   information (IPSEC within IPSEC within ...).
48  *
49  * Maintaining ordering for protocol streams is a critical design concern.
50  * Enforcing ordering limits the opportunity for concurrency, but maintains
51  * the strong ordering requirements found in some protocols, such as TCP.  Of
52  * related concern is CPU affinity--it is desirable to process all data
53  * associated with a particular stream on the same CPU over time in order to
54  * avoid acquiring locks associated with the connection on different CPUs,
55  * keep connection data in one cache, and to generally encourage associated
56  * user threads to live on the same CPU as the stream.  It's also desirable
57  * to avoid lock migration and contention where locks are associated with
58  * more than one flow.
59  *
60  * netisr supports several policy variations, represented by the
61  * NETISR_POLICY_* constants, allowing protocols to play various roles in
62  * identifying flows, assigning work to CPUs, etc.  These are described in
63  * netisr.h.
64  */
65 
66 #include "opt_ddb.h"
67 #include "opt_device_polling.h"
68 
69 #include <sys/param.h>
70 #include <sys/bus.h>
71 #include <sys/kernel.h>
72 #include <sys/kthread.h>
73 #include <sys/malloc.h>
74 #include <sys/interrupt.h>
75 #include <sys/lock.h>
76 #include <sys/mbuf.h>
77 #include <sys/mutex.h>
78 #include <sys/pcpu.h>
79 #include <sys/proc.h>
80 #include <sys/rmlock.h>
81 #include <sys/sched.h>
82 #include <sys/smp.h>
83 #include <sys/socket.h>
84 #include <sys/sysctl.h>
85 #include <sys/systm.h>
86 
87 #ifdef DDB
88 #include <ddb/ddb.h>
89 #endif
90 
91 #define	_WANT_NETISR_INTERNAL	/* Enable definitions from netisr_internal.h */
92 #include <net/if.h>
93 #include <net/if_var.h>
94 #include <net/netisr.h>
95 #include <net/netisr_internal.h>
96 #include <net/vnet.h>
97 
98 /*-
99  * Synchronize use and modification of the registered netisr data structures;
100  * acquire a read lock while modifying the set of registered protocols to
101  * prevent partially registered or unregistered protocols from being run.
102  *
103  * The following data structures and fields are protected by this lock:
104  *
105  * - The netisr_proto array, including all fields of struct netisr_proto.
106  * - The nws array, including all fields of struct netisr_worker.
107  * - The nws_array array.
108  *
109  * Note: the NETISR_LOCKING define controls whether read locks are acquired
110  * in packet processing paths requiring netisr registration stability.  This
111  * is disabled by default as it can lead to measurable performance
112  * degradation even with rmlocks (3%-6% for loopback ping-pong traffic), and
113  * because netisr registration and unregistration is extremely rare at
114  * runtime.  If it becomes more common, this decision should be revisited.
115  *
116  * XXXRW: rmlocks don't support assertions.
117  */
118 static struct rmlock	netisr_rmlock;
119 #define	NETISR_LOCK_INIT()	rm_init_flags(&netisr_rmlock, "netisr", \
120 				    RM_NOWITNESS)
121 #define	NETISR_LOCK_ASSERT()
122 #define	NETISR_RLOCK(tracker)	rm_rlock(&netisr_rmlock, (tracker))
123 #define	NETISR_RUNLOCK(tracker)	rm_runlock(&netisr_rmlock, (tracker))
124 #define	NETISR_WLOCK()		rm_wlock(&netisr_rmlock)
125 #define	NETISR_WUNLOCK()	rm_wunlock(&netisr_rmlock)
126 /* #define	NETISR_LOCKING */
127 
128 static SYSCTL_NODE(_net, OID_AUTO, isr, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
129     "netisr");
130 
131 /*-
132  * Three global direct dispatch policies are supported:
133  *
134  * NETISR_DISPATCH_DEFERRED: All work is deferred for a netisr, regardless of
135  * context (may be overridden by protocols).
136  *
137  * NETISR_DISPATCH_HYBRID: If the executing context allows direct dispatch,
138  * and we're running on the CPU the work would be performed on, then direct
139  * dispatch it if it wouldn't violate ordering constraints on the workstream.
140  *
141  * NETISR_DISPATCH_DIRECT: If the executing context allows direct dispatch,
142  * always direct dispatch.  (The default.)
143  *
144  * Notice that changing the global policy could lead to short periods of
145  * misordered processing, but this is considered acceptable as compared to
146  * the complexity of enforcing ordering during policy changes.  Protocols can
147  * override the global policy (when they're not doing that, they select
148  * NETISR_DISPATCH_DEFAULT).
149  */
150 #define	NETISR_DISPATCH_POLICY_DEFAULT	NETISR_DISPATCH_DIRECT
151 #define	NETISR_DISPATCH_POLICY_MAXSTR	20 /* Used for temporary buffers. */
152 static u_int	netisr_dispatch_policy = NETISR_DISPATCH_POLICY_DEFAULT;
153 static int	sysctl_netisr_dispatch_policy(SYSCTL_HANDLER_ARGS);
154 SYSCTL_PROC(_net_isr, OID_AUTO, dispatch,
155     CTLTYPE_STRING | CTLFLAG_RWTUN | CTLFLAG_NEEDGIANT,
156     0, 0, sysctl_netisr_dispatch_policy, "A",
157     "netisr dispatch policy");
158 
159 /*
160  * Allow the administrator to limit the number of threads (CPUs) to use for
161  * netisr.  We don't check netisr_maxthreads before creating the thread for
162  * CPU 0. This must be set at boot. We will create at most one thread per CPU.
163  * By default we initialize this to 1 which would assign just 1 cpu (cpu0) and
164  * therefore only 1 workstream. If set to -1, netisr would use all cpus
165  * (mp_ncpus) and therefore would have those many workstreams. One workstream
166  * per thread (CPU).
167  */
168 static int	netisr_maxthreads = 1;		/* Max number of threads. */
169 SYSCTL_INT(_net_isr, OID_AUTO, maxthreads, CTLFLAG_RDTUN,
170     &netisr_maxthreads, 0,
171     "Use at most this many CPUs for netisr processing");
172 
173 static int	netisr_bindthreads = 0;		/* Bind threads to CPUs. */
174 SYSCTL_INT(_net_isr, OID_AUTO, bindthreads, CTLFLAG_RDTUN,
175     &netisr_bindthreads, 0, "Bind netisr threads to CPUs.");
176 
177 /*
178  * Limit per-workstream mbuf queue limits s to at most net.isr.maxqlimit,
179  * both for initial configuration and later modification using
180  * netisr_setqlimit().
181  */
182 #define	NETISR_DEFAULT_MAXQLIMIT	10240
183 static u_int	netisr_maxqlimit = NETISR_DEFAULT_MAXQLIMIT;
184 SYSCTL_UINT(_net_isr, OID_AUTO, maxqlimit, CTLFLAG_RDTUN,
185     &netisr_maxqlimit, 0,
186     "Maximum netisr per-protocol, per-CPU queue depth.");
187 
188 /*
189  * The default per-workstream mbuf queue limit for protocols that don't
190  * initialize the nh_qlimit field of their struct netisr_handler.  If this is
191  * set above netisr_maxqlimit, we truncate it to the maximum during boot.
192  */
193 #define	NETISR_DEFAULT_DEFAULTQLIMIT	256
194 static u_int	netisr_defaultqlimit = NETISR_DEFAULT_DEFAULTQLIMIT;
195 SYSCTL_UINT(_net_isr, OID_AUTO, defaultqlimit, CTLFLAG_RDTUN,
196     &netisr_defaultqlimit, 0,
197     "Default netisr per-protocol, per-CPU queue limit if not set by protocol");
198 
199 /*
200  * Store and export the compile-time constant NETISR_MAXPROT limit on the
201  * number of protocols that can register with netisr at a time.  This is
202  * required for crashdump analysis, as it sizes netisr_proto[].
203  */
204 static u_int	netisr_maxprot = NETISR_MAXPROT;
205 SYSCTL_UINT(_net_isr, OID_AUTO, maxprot, CTLFLAG_RD,
206     &netisr_maxprot, 0,
207     "Compile-time limit on the number of protocols supported by netisr.");
208 
209 /*
210  * The netisr_proto array describes all registered protocols, indexed by
211  * protocol number.  See netisr_internal.h for more details.
212  */
213 static struct netisr_proto	netisr_proto[NETISR_MAXPROT];
214 
215 #ifdef VIMAGE
216 /*
217  * The netisr_enable array describes a per-VNET flag for registered
218  * protocols on whether this netisr is active in this VNET or not.
219  * netisr_register() will automatically enable the netisr for the
220  * default VNET and all currently active instances.
221  * netisr_unregister() will disable all active VNETs, including vnet0.
222  * Individual network stack instances can be enabled/disabled by the
223  * netisr_(un)register _vnet() functions.
224  * With this we keep the one netisr_proto per protocol but add a
225  * mechanism to stop netisr processing for vnet teardown.
226  * Apart from that we expect a VNET to always be enabled.
227  */
228 VNET_DEFINE_STATIC(u_int,	netisr_enable[NETISR_MAXPROT]);
229 #define	V_netisr_enable		VNET(netisr_enable)
230 #endif
231 
232 /*
233  * Per-CPU workstream data.  See netisr_internal.h for more details.
234  */
235 DPCPU_DEFINE(struct netisr_workstream, nws);
236 
237 /*
238  * Map contiguous values between 0 and nws_count into CPU IDs appropriate for
239  * accessing workstreams.  This allows constructions of the form
240  * DPCPU_ID_GET(nws_array[arbitraryvalue % nws_count], nws).
241  */
242 static u_int				 nws_array[MAXCPU];
243 
244 /*
245  * Number of registered workstreams.  Will be at most the number of running
246  * CPUs once fully started.
247  */
248 static u_int				 nws_count;
249 SYSCTL_UINT(_net_isr, OID_AUTO, numthreads, CTLFLAG_RD,
250     &nws_count, 0, "Number of extant netisr threads.");
251 
252 /*
253  * Synchronization for each workstream: a mutex protects all mutable fields
254  * in each stream, including per-protocol state (mbuf queues).  The SWI is
255  * woken up if asynchronous dispatch is required.
256  */
257 #define	NWS_LOCK(s)		mtx_lock(&(s)->nws_mtx)
258 #define	NWS_LOCK_ASSERT(s)	mtx_assert(&(s)->nws_mtx, MA_OWNED)
259 #define	NWS_UNLOCK(s)		mtx_unlock(&(s)->nws_mtx)
260 #define	NWS_SIGNAL(s)		swi_sched((s)->nws_swi_cookie, 0)
261 
262 /*
263  * Utility routines for protocols that implement their own mapping of flows
264  * to CPUs.
265  */
266 u_int
netisr_get_cpucount(void)267 netisr_get_cpucount(void)
268 {
269 
270 	return (nws_count);
271 }
272 
273 u_int
netisr_get_cpuid(u_int cpunumber)274 netisr_get_cpuid(u_int cpunumber)
275 {
276 
277 	return (nws_array[cpunumber % nws_count]);
278 }
279 
280 /*
281  * The default implementation of flow -> CPU ID mapping.
282  *
283  * Non-static so that protocols can use it to map their own work to specific
284  * CPUs in a manner consistent to netisr for affinity purposes.
285  */
286 u_int
netisr_default_flow2cpu(u_int flowid)287 netisr_default_flow2cpu(u_int flowid)
288 {
289 
290 	return (nws_array[flowid % nws_count]);
291 }
292 
293 /*
294  * Dispatch tunable and sysctl configuration.
295  */
296 struct netisr_dispatch_table_entry {
297 	u_int		 ndte_policy;
298 	const char	*ndte_policy_str;
299 };
300 static const struct netisr_dispatch_table_entry netisr_dispatch_table[] = {
301 	{ NETISR_DISPATCH_DEFAULT, "default" },
302 	{ NETISR_DISPATCH_DEFERRED, "deferred" },
303 	{ NETISR_DISPATCH_HYBRID, "hybrid" },
304 	{ NETISR_DISPATCH_DIRECT, "direct" },
305 };
306 
307 static void
netisr_dispatch_policy_to_str(u_int dispatch_policy,char * buffer,u_int buflen)308 netisr_dispatch_policy_to_str(u_int dispatch_policy, char *buffer,
309     u_int buflen)
310 {
311 	const struct netisr_dispatch_table_entry *ndtep;
312 	const char *str;
313 	u_int i;
314 
315 	str = "unknown";
316 	for (i = 0; i < nitems(netisr_dispatch_table); i++) {
317 		ndtep = &netisr_dispatch_table[i];
318 		if (ndtep->ndte_policy == dispatch_policy) {
319 			str = ndtep->ndte_policy_str;
320 			break;
321 		}
322 	}
323 	snprintf(buffer, buflen, "%s", str);
324 }
325 
326 static int
netisr_dispatch_policy_from_str(const char * str,u_int * dispatch_policyp)327 netisr_dispatch_policy_from_str(const char *str, u_int *dispatch_policyp)
328 {
329 	const struct netisr_dispatch_table_entry *ndtep;
330 	u_int i;
331 
332 	for (i = 0; i < nitems(netisr_dispatch_table); i++) {
333 		ndtep = &netisr_dispatch_table[i];
334 		if (strcmp(ndtep->ndte_policy_str, str) == 0) {
335 			*dispatch_policyp = ndtep->ndte_policy;
336 			return (0);
337 		}
338 	}
339 	return (EINVAL);
340 }
341 
342 static int
sysctl_netisr_dispatch_policy(SYSCTL_HANDLER_ARGS)343 sysctl_netisr_dispatch_policy(SYSCTL_HANDLER_ARGS)
344 {
345 	char tmp[NETISR_DISPATCH_POLICY_MAXSTR];
346 	size_t len;
347 	u_int dispatch_policy;
348 	int error;
349 
350 	netisr_dispatch_policy_to_str(netisr_dispatch_policy, tmp,
351 	    sizeof(tmp));
352 	/*
353 	 * netisr is initialised very early during the boot when malloc isn't
354 	 * available yet so we can't use sysctl_handle_string() to process
355 	 * any non-default value that was potentially set via loader.
356 	 */
357 	if (req->newptr != NULL) {
358 		len = req->newlen - req->newidx;
359 		if (len >= NETISR_DISPATCH_POLICY_MAXSTR)
360 			return (EINVAL);
361 		error = SYSCTL_IN(req, tmp, len);
362 		if (error == 0) {
363 			tmp[len] = '\0';
364 			error = netisr_dispatch_policy_from_str(tmp,
365 			    &dispatch_policy);
366 			if (error == 0 &&
367 			    dispatch_policy == NETISR_DISPATCH_DEFAULT)
368 				error = EINVAL;
369 			if (error == 0)
370 				netisr_dispatch_policy = dispatch_policy;
371 		}
372 	} else {
373 		error = sysctl_handle_string(oidp, tmp, sizeof(tmp), req);
374 	}
375 	return (error);
376 }
377 
378 /*
379  * Register a new netisr handler, which requires initializing per-protocol
380  * fields for each workstream.  All netisr work is briefly suspended while
381  * the protocol is installed.
382  */
383 void
netisr_register(const struct netisr_handler * nhp)384 netisr_register(const struct netisr_handler *nhp)
385 {
386 	VNET_ITERATOR_DECL(vnet_iter);
387 	struct netisr_work *npwp;
388 	const char *name;
389 	u_int i, proto;
390 
391 	proto = nhp->nh_proto;
392 	name = nhp->nh_name;
393 
394 	/*
395 	 * Test that the requested registration is valid.
396 	 */
397 	KASSERT(nhp->nh_name != NULL,
398 	    ("%s: nh_name NULL for %u", __func__, proto));
399 	KASSERT(nhp->nh_handler != NULL,
400 	    ("%s: nh_handler NULL for %s", __func__, name));
401 	KASSERT(nhp->nh_policy == NETISR_POLICY_SOURCE ||
402 	    nhp->nh_policy == NETISR_POLICY_FLOW ||
403 	    nhp->nh_policy == NETISR_POLICY_CPU,
404 	    ("%s: unsupported nh_policy %u for %s", __func__,
405 	    nhp->nh_policy, name));
406 	KASSERT(nhp->nh_policy == NETISR_POLICY_FLOW ||
407 	    nhp->nh_m2flow == NULL,
408 	    ("%s: nh_policy != FLOW but m2flow defined for %s", __func__,
409 	    name));
410 	KASSERT(nhp->nh_policy == NETISR_POLICY_CPU || nhp->nh_m2cpuid == NULL,
411 	    ("%s: nh_policy != CPU but m2cpuid defined for %s", __func__,
412 	    name));
413 	KASSERT(nhp->nh_policy != NETISR_POLICY_CPU || nhp->nh_m2cpuid != NULL,
414 	    ("%s: nh_policy == CPU but m2cpuid not defined for %s", __func__,
415 	    name));
416 	KASSERT(nhp->nh_dispatch == NETISR_DISPATCH_DEFAULT ||
417 	    nhp->nh_dispatch == NETISR_DISPATCH_DEFERRED ||
418 	    nhp->nh_dispatch == NETISR_DISPATCH_HYBRID ||
419 	    nhp->nh_dispatch == NETISR_DISPATCH_DIRECT,
420 	    ("%s: invalid nh_dispatch (%u)", __func__, nhp->nh_dispatch));
421 
422 	KASSERT(proto < NETISR_MAXPROT,
423 	    ("%s(%u, %s): protocol too big", __func__, proto, name));
424 
425 	/*
426 	 * Test that no existing registration exists for this protocol.
427 	 */
428 	NETISR_WLOCK();
429 	KASSERT(netisr_proto[proto].np_name == NULL,
430 	    ("%s(%u, %s): name present", __func__, proto, name));
431 	KASSERT(netisr_proto[proto].np_handler == NULL,
432 	    ("%s(%u, %s): handler present", __func__, proto, name));
433 
434 	netisr_proto[proto].np_name = name;
435 	netisr_proto[proto].np_handler = nhp->nh_handler;
436 	netisr_proto[proto].np_m2flow = nhp->nh_m2flow;
437 	netisr_proto[proto].np_m2cpuid = nhp->nh_m2cpuid;
438 	netisr_proto[proto].np_drainedcpu = nhp->nh_drainedcpu;
439 	if (nhp->nh_qlimit == 0)
440 		netisr_proto[proto].np_qlimit = netisr_defaultqlimit;
441 	else if (nhp->nh_qlimit > netisr_maxqlimit) {
442 		printf("%s: %s requested queue limit %u capped to "
443 		    "net.isr.maxqlimit %u\n", __func__, name, nhp->nh_qlimit,
444 		    netisr_maxqlimit);
445 		netisr_proto[proto].np_qlimit = netisr_maxqlimit;
446 	} else
447 		netisr_proto[proto].np_qlimit = nhp->nh_qlimit;
448 	netisr_proto[proto].np_policy = nhp->nh_policy;
449 	netisr_proto[proto].np_dispatch = nhp->nh_dispatch;
450 	CPU_FOREACH(i) {
451 		npwp = &(DPCPU_ID_PTR(i, nws))->nws_work[proto];
452 		bzero(npwp, sizeof(*npwp));
453 		npwp->nw_qlimit = netisr_proto[proto].np_qlimit;
454 	}
455 
456 #ifdef VIMAGE
457 	/*
458 	 * Test that we are in vnet0 and have a curvnet set.
459 	 */
460 	KASSERT(curvnet != NULL, ("%s: curvnet is NULL", __func__));
461 	KASSERT(IS_DEFAULT_VNET(curvnet), ("%s: curvnet %p is not vnet0 %p",
462 	    __func__, curvnet, vnet0));
463 	VNET_LIST_RLOCK_NOSLEEP();
464 	VNET_FOREACH(vnet_iter) {
465 		CURVNET_SET(vnet_iter);
466 		V_netisr_enable[proto] = 1;
467 		CURVNET_RESTORE();
468 	}
469 	VNET_LIST_RUNLOCK_NOSLEEP();
470 #endif
471 	NETISR_WUNLOCK();
472 }
473 
474 /*
475  * Clear drop counters across all workstreams for a protocol.
476  */
477 void
netisr_clearqdrops(const struct netisr_handler * nhp)478 netisr_clearqdrops(const struct netisr_handler *nhp)
479 {
480 	struct netisr_work *npwp;
481 #ifdef INVARIANTS
482 	const char *name;
483 #endif
484 	u_int i, proto;
485 
486 	proto = nhp->nh_proto;
487 #ifdef INVARIANTS
488 	name = nhp->nh_name;
489 #endif
490 	KASSERT(proto < NETISR_MAXPROT,
491 	    ("%s(%u): protocol too big for %s", __func__, proto, name));
492 
493 	NETISR_WLOCK();
494 	KASSERT(netisr_proto[proto].np_handler != NULL,
495 	    ("%s(%u): protocol not registered for %s", __func__, proto,
496 	    name));
497 
498 	CPU_FOREACH(i) {
499 		npwp = &(DPCPU_ID_PTR(i, nws))->nws_work[proto];
500 		npwp->nw_qdrops = 0;
501 	}
502 	NETISR_WUNLOCK();
503 }
504 
505 /*
506  * Query current drop counters across all workstreams for a protocol.
507  */
508 void
netisr_getqdrops(const struct netisr_handler * nhp,u_int64_t * qdropp)509 netisr_getqdrops(const struct netisr_handler *nhp, u_int64_t *qdropp)
510 {
511 	struct netisr_work *npwp;
512 	struct rm_priotracker tracker;
513 #ifdef INVARIANTS
514 	const char *name;
515 #endif
516 	u_int i, proto;
517 
518 	*qdropp = 0;
519 	proto = nhp->nh_proto;
520 #ifdef INVARIANTS
521 	name = nhp->nh_name;
522 #endif
523 	KASSERT(proto < NETISR_MAXPROT,
524 	    ("%s(%u): protocol too big for %s", __func__, proto, name));
525 
526 	NETISR_RLOCK(&tracker);
527 	KASSERT(netisr_proto[proto].np_handler != NULL,
528 	    ("%s(%u): protocol not registered for %s", __func__, proto,
529 	    name));
530 
531 	CPU_FOREACH(i) {
532 		npwp = &(DPCPU_ID_PTR(i, nws))->nws_work[proto];
533 		*qdropp += npwp->nw_qdrops;
534 	}
535 	NETISR_RUNLOCK(&tracker);
536 }
537 
538 /*
539  * Query current per-workstream queue limit for a protocol.
540  */
541 void
netisr_getqlimit(const struct netisr_handler * nhp,u_int * qlimitp)542 netisr_getqlimit(const struct netisr_handler *nhp, u_int *qlimitp)
543 {
544 	struct rm_priotracker tracker;
545 #ifdef INVARIANTS
546 	const char *name;
547 #endif
548 	u_int proto;
549 
550 	proto = nhp->nh_proto;
551 #ifdef INVARIANTS
552 	name = nhp->nh_name;
553 #endif
554 	KASSERT(proto < NETISR_MAXPROT,
555 	    ("%s(%u): protocol too big for %s", __func__, proto, name));
556 
557 	NETISR_RLOCK(&tracker);
558 	KASSERT(netisr_proto[proto].np_handler != NULL,
559 	    ("%s(%u): protocol not registered for %s", __func__, proto,
560 	    name));
561 	*qlimitp = netisr_proto[proto].np_qlimit;
562 	NETISR_RUNLOCK(&tracker);
563 }
564 
565 /*
566  * Update the queue limit across per-workstream queues for a protocol.  We
567  * simply change the limits, and don't drain overflowed packets as they will
568  * (hopefully) take care of themselves shortly.
569  */
570 int
netisr_setqlimit(const struct netisr_handler * nhp,u_int qlimit)571 netisr_setqlimit(const struct netisr_handler *nhp, u_int qlimit)
572 {
573 	struct netisr_work *npwp;
574 #ifdef INVARIANTS
575 	const char *name;
576 #endif
577 	u_int i, proto;
578 
579 	if (qlimit > netisr_maxqlimit)
580 		return (EINVAL);
581 
582 	proto = nhp->nh_proto;
583 #ifdef INVARIANTS
584 	name = nhp->nh_name;
585 #endif
586 	KASSERT(proto < NETISR_MAXPROT,
587 	    ("%s(%u): protocol too big for %s", __func__, proto, name));
588 
589 	NETISR_WLOCK();
590 	KASSERT(netisr_proto[proto].np_handler != NULL,
591 	    ("%s(%u): protocol not registered for %s", __func__, proto,
592 	    name));
593 
594 	netisr_proto[proto].np_qlimit = qlimit;
595 	CPU_FOREACH(i) {
596 		npwp = &(DPCPU_ID_PTR(i, nws))->nws_work[proto];
597 		npwp->nw_qlimit = qlimit;
598 	}
599 	NETISR_WUNLOCK();
600 	return (0);
601 }
602 
603 /*
604  * Drain all packets currently held in a particular protocol work queue.
605  */
606 static void
netisr_drain_proto(struct netisr_work * npwp)607 netisr_drain_proto(struct netisr_work *npwp)
608 {
609 	struct mbuf *m;
610 
611 	/*
612 	 * We would assert the lock on the workstream but it's not passed in.
613 	 */
614 	while ((m = npwp->nw_head) != NULL) {
615 		npwp->nw_head = m->m_nextpkt;
616 		m->m_nextpkt = NULL;
617 		if (npwp->nw_head == NULL)
618 			npwp->nw_tail = NULL;
619 		npwp->nw_len--;
620 		m_freem(m);
621 	}
622 	KASSERT(npwp->nw_tail == NULL, ("%s: tail", __func__));
623 	KASSERT(npwp->nw_len == 0, ("%s: len", __func__));
624 }
625 
626 /*
627  * Remove the registration of a network protocol, which requires clearing
628  * per-protocol fields across all workstreams, including freeing all mbufs in
629  * the queues at time of unregister.  All work in netisr is briefly suspended
630  * while this takes place.
631  */
632 void
netisr_unregister(const struct netisr_handler * nhp)633 netisr_unregister(const struct netisr_handler *nhp)
634 {
635 	VNET_ITERATOR_DECL(vnet_iter);
636 	struct netisr_work *npwp;
637 #ifdef INVARIANTS
638 	const char *name;
639 #endif
640 	u_int i, proto;
641 
642 	proto = nhp->nh_proto;
643 #ifdef INVARIANTS
644 	name = nhp->nh_name;
645 #endif
646 	KASSERT(proto < NETISR_MAXPROT,
647 	    ("%s(%u): protocol too big for %s", __func__, proto, name));
648 
649 	NETISR_WLOCK();
650 	KASSERT(netisr_proto[proto].np_handler != NULL,
651 	    ("%s(%u): protocol not registered for %s", __func__, proto,
652 	    name));
653 
654 #ifdef VIMAGE
655 	VNET_LIST_RLOCK_NOSLEEP();
656 	VNET_FOREACH(vnet_iter) {
657 		CURVNET_SET(vnet_iter);
658 		V_netisr_enable[proto] = 0;
659 		CURVNET_RESTORE();
660 	}
661 	VNET_LIST_RUNLOCK_NOSLEEP();
662 #endif
663 
664 	netisr_proto[proto].np_name = NULL;
665 	netisr_proto[proto].np_handler = NULL;
666 	netisr_proto[proto].np_m2flow = NULL;
667 	netisr_proto[proto].np_m2cpuid = NULL;
668 	netisr_proto[proto].np_qlimit = 0;
669 	netisr_proto[proto].np_policy = 0;
670 	CPU_FOREACH(i) {
671 		npwp = &(DPCPU_ID_PTR(i, nws))->nws_work[proto];
672 		netisr_drain_proto(npwp);
673 		bzero(npwp, sizeof(*npwp));
674 	}
675 	NETISR_WUNLOCK();
676 }
677 
678 #ifdef VIMAGE
679 void
netisr_register_vnet(const struct netisr_handler * nhp)680 netisr_register_vnet(const struct netisr_handler *nhp)
681 {
682 	u_int proto;
683 
684 	proto = nhp->nh_proto;
685 
686 	KASSERT(curvnet != NULL, ("%s: curvnet is NULL", __func__));
687 	KASSERT(proto < NETISR_MAXPROT,
688 	    ("%s(%u): protocol too big for %s", __func__, proto, nhp->nh_name));
689 	NETISR_WLOCK();
690 	KASSERT(netisr_proto[proto].np_handler != NULL,
691 	    ("%s(%u): protocol not registered for %s", __func__, proto,
692 	    nhp->nh_name));
693 
694 	V_netisr_enable[proto] = 1;
695 	NETISR_WUNLOCK();
696 }
697 
698 static void
netisr_drain_proto_vnet(struct vnet * vnet,u_int proto)699 netisr_drain_proto_vnet(struct vnet *vnet, u_int proto)
700 {
701 	struct netisr_workstream *nwsp;
702 	struct netisr_work *npwp;
703 	struct mbuf *m, *mp, *n, *ne;
704 	u_int i;
705 
706 	KASSERT(vnet != NULL, ("%s: vnet is NULL", __func__));
707 	NETISR_LOCK_ASSERT();
708 
709 	CPU_FOREACH(i) {
710 		nwsp = DPCPU_ID_PTR(i, nws);
711 		if (nwsp->nws_intr_event == NULL)
712 			continue;
713 		npwp = &nwsp->nws_work[proto];
714 		NWS_LOCK(nwsp);
715 
716 		/*
717 		 * Rather than dissecting and removing mbufs from the middle
718 		 * of the chain, we build a new chain if the packet stays and
719 		 * update the head and tail pointers at the end.  All packets
720 		 * matching the given vnet are freed.
721 		 */
722 		m = npwp->nw_head;
723 		n = ne = NULL;
724 		while (m != NULL) {
725 			mp = m;
726 			m = m->m_nextpkt;
727 			mp->m_nextpkt = NULL;
728 			if (mp->m_pkthdr.rcvif->if_vnet != vnet) {
729 				if (n == NULL) {
730 					n = ne = mp;
731 				} else {
732 					ne->m_nextpkt = mp;
733 					ne = mp;
734 				}
735 				continue;
736 			}
737 			/* This is a packet in the selected vnet. Free it. */
738 			npwp->nw_len--;
739 			m_freem(mp);
740 		}
741 		npwp->nw_head = n;
742 		npwp->nw_tail = ne;
743 		NWS_UNLOCK(nwsp);
744 	}
745 }
746 
747 void
netisr_unregister_vnet(const struct netisr_handler * nhp)748 netisr_unregister_vnet(const struct netisr_handler *nhp)
749 {
750 	u_int proto;
751 
752 	proto = nhp->nh_proto;
753 
754 	KASSERT(curvnet != NULL, ("%s: curvnet is NULL", __func__));
755 	KASSERT(proto < NETISR_MAXPROT,
756 	    ("%s(%u): protocol too big for %s", __func__, proto, nhp->nh_name));
757 	NETISR_WLOCK();
758 	KASSERT(netisr_proto[proto].np_handler != NULL,
759 	    ("%s(%u): protocol not registered for %s", __func__, proto,
760 	    nhp->nh_name));
761 
762 	V_netisr_enable[proto] = 0;
763 
764 	netisr_drain_proto_vnet(curvnet, proto);
765 	NETISR_WUNLOCK();
766 }
767 #endif
768 
769 /*
770  * Compose the global and per-protocol policies on dispatch, and return the
771  * dispatch policy to use.
772  */
773 static u_int
netisr_get_dispatch(struct netisr_proto * npp)774 netisr_get_dispatch(struct netisr_proto *npp)
775 {
776 
777 	/*
778 	 * Protocol-specific configuration overrides the global default.
779 	 */
780 	if (npp->np_dispatch != NETISR_DISPATCH_DEFAULT)
781 		return (npp->np_dispatch);
782 	return (netisr_dispatch_policy);
783 }
784 
785 /*
786  * Look up the workstream given a packet and source identifier.  Do this by
787  * checking the protocol's policy, and optionally call out to the protocol
788  * for assistance if required.
789  */
790 static struct mbuf *
netisr_select_cpuid(struct netisr_proto * npp,u_int dispatch_policy,uintptr_t source,struct mbuf * m,u_int * cpuidp)791 netisr_select_cpuid(struct netisr_proto *npp, u_int dispatch_policy,
792     uintptr_t source, struct mbuf *m, u_int *cpuidp)
793 {
794 	struct ifnet *ifp;
795 	u_int policy;
796 
797 	NETISR_LOCK_ASSERT();
798 
799 	/*
800 	 * In the event we have only one worker, shortcut and deliver to it
801 	 * without further ado.
802 	 */
803 	if (nws_count == 1) {
804 		*cpuidp = nws_array[0];
805 		return (m);
806 	}
807 
808 	/*
809 	 * What happens next depends on the policy selected by the protocol.
810 	 * If we want to support per-interface policies, we should do that
811 	 * here first.
812 	 */
813 	policy = npp->np_policy;
814 	if (policy == NETISR_POLICY_CPU) {
815 		m = npp->np_m2cpuid(m, source, cpuidp);
816 		if (m == NULL)
817 			return (NULL);
818 
819 		/*
820 		 * It's possible for a protocol not to have a good idea about
821 		 * where to process a packet, in which case we fall back on
822 		 * the netisr code to decide.  In the hybrid case, return the
823 		 * current CPU ID, which will force an immediate direct
824 		 * dispatch.  In the queued case, fall back on the SOURCE
825 		 * policy.
826 		 */
827 		if (*cpuidp != NETISR_CPUID_NONE) {
828 			*cpuidp = netisr_get_cpuid(*cpuidp);
829 			return (m);
830 		}
831 		if (dispatch_policy == NETISR_DISPATCH_HYBRID) {
832 			*cpuidp = netisr_get_cpuid(curcpu);
833 			return (m);
834 		}
835 		policy = NETISR_POLICY_SOURCE;
836 	}
837 
838 	if (policy == NETISR_POLICY_FLOW) {
839 		if (M_HASHTYPE_GET(m) == M_HASHTYPE_NONE &&
840 		    npp->np_m2flow != NULL) {
841 			m = npp->np_m2flow(m, source);
842 			if (m == NULL)
843 				return (NULL);
844 		}
845 		if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE) {
846 			*cpuidp =
847 			    netisr_default_flow2cpu(m->m_pkthdr.flowid);
848 			return (m);
849 		}
850 		policy = NETISR_POLICY_SOURCE;
851 	}
852 
853 	KASSERT(policy == NETISR_POLICY_SOURCE,
854 	    ("%s: invalid policy %u for %s", __func__, npp->np_policy,
855 	    npp->np_name));
856 
857 	MPASS((m->m_pkthdr.csum_flags & CSUM_SND_TAG) == 0);
858 	ifp = m->m_pkthdr.rcvif;
859 	if (ifp != NULL)
860 		*cpuidp = nws_array[(ifp->if_index + source) % nws_count];
861 	else
862 		*cpuidp = nws_array[source % nws_count];
863 	return (m);
864 }
865 
866 /*
867  * Process packets associated with a workstream and protocol.  For reasons of
868  * fairness, we process up to one complete netisr queue at a time, moving the
869  * queue to a stack-local queue for processing, but do not loop refreshing
870  * from the global queue.  The caller is responsible for deciding whether to
871  * loop, and for setting the NWS_RUNNING flag.  The passed workstream will be
872  * locked on entry and relocked before return, but will be released while
873  * processing.  The number of packets processed is returned.
874  */
875 static u_int
netisr_process_workstream_proto(struct netisr_workstream * nwsp,u_int proto)876 netisr_process_workstream_proto(struct netisr_workstream *nwsp, u_int proto)
877 {
878 	struct netisr_work local_npw, *npwp;
879 	u_int handled;
880 	struct mbuf *m;
881 
882 	NETISR_LOCK_ASSERT();
883 	NWS_LOCK_ASSERT(nwsp);
884 
885 	KASSERT(nwsp->nws_flags & NWS_RUNNING,
886 	    ("%s(%u): not running", __func__, proto));
887 	KASSERT(proto >= 0 && proto < NETISR_MAXPROT,
888 	    ("%s(%u): invalid proto\n", __func__, proto));
889 
890 	npwp = &nwsp->nws_work[proto];
891 	if (npwp->nw_len == 0)
892 		return (0);
893 
894 	/*
895 	 * Move the global work queue to a thread-local work queue.
896 	 *
897 	 * Notice that this means the effective maximum length of the queue
898 	 * is actually twice that of the maximum queue length specified in
899 	 * the protocol registration call.
900 	 */
901 	handled = npwp->nw_len;
902 	local_npw = *npwp;
903 	npwp->nw_head = NULL;
904 	npwp->nw_tail = NULL;
905 	npwp->nw_len = 0;
906 	nwsp->nws_pendingbits &= ~(1 << proto);
907 	NWS_UNLOCK(nwsp);
908 	while ((m = local_npw.nw_head) != NULL) {
909 		local_npw.nw_head = m->m_nextpkt;
910 		m->m_nextpkt = NULL;
911 		if (local_npw.nw_head == NULL)
912 			local_npw.nw_tail = NULL;
913 		local_npw.nw_len--;
914 		VNET_ASSERT(m->m_pkthdr.rcvif != NULL,
915 		    ("%s:%d rcvif == NULL: m=%p", __func__, __LINE__, m));
916 		CURVNET_SET(m->m_pkthdr.rcvif->if_vnet);
917 		netisr_proto[proto].np_handler(m);
918 		CURVNET_RESTORE();
919 	}
920 	KASSERT(local_npw.nw_len == 0,
921 	    ("%s(%u): len %u", __func__, proto, local_npw.nw_len));
922 	if (netisr_proto[proto].np_drainedcpu)
923 		netisr_proto[proto].np_drainedcpu(nwsp->nws_cpu);
924 	NWS_LOCK(nwsp);
925 	npwp->nw_handled += handled;
926 	return (handled);
927 }
928 
929 /*
930  * SWI handler for netisr -- processes packets in a set of workstreams that
931  * it owns, woken up by calls to NWS_SIGNAL().  If this workstream is already
932  * being direct dispatched, go back to sleep and wait for the dispatching
933  * thread to wake us up again.
934  */
935 static void
swi_net(void * arg)936 swi_net(void *arg)
937 {
938 #ifdef NETISR_LOCKING
939 	struct rm_priotracker tracker;
940 #endif
941 	struct netisr_workstream *nwsp;
942 	u_int bits, prot;
943 
944 	nwsp = arg;
945 
946 #ifdef DEVICE_POLLING
947 	KASSERT(nws_count == 1,
948 	    ("%s: device_polling but nws_count != 1", __func__));
949 	netisr_poll();
950 #endif
951 #ifdef NETISR_LOCKING
952 	NETISR_RLOCK(&tracker);
953 #endif
954 	NWS_LOCK(nwsp);
955 	KASSERT(!(nwsp->nws_flags & NWS_RUNNING), ("swi_net: running"));
956 	if (nwsp->nws_flags & NWS_DISPATCHING)
957 		goto out;
958 	nwsp->nws_flags |= NWS_RUNNING;
959 	nwsp->nws_flags &= ~NWS_SCHEDULED;
960 	while ((bits = nwsp->nws_pendingbits) != 0) {
961 		while ((prot = ffs(bits)) != 0) {
962 			prot--;
963 			bits &= ~(1 << prot);
964 			(void)netisr_process_workstream_proto(nwsp, prot);
965 		}
966 	}
967 	nwsp->nws_flags &= ~NWS_RUNNING;
968 out:
969 	NWS_UNLOCK(nwsp);
970 #ifdef NETISR_LOCKING
971 	NETISR_RUNLOCK(&tracker);
972 #endif
973 #ifdef DEVICE_POLLING
974 	netisr_pollmore();
975 #endif
976 }
977 
978 static int
netisr_queue_workstream(struct netisr_workstream * nwsp,u_int proto,struct netisr_work * npwp,struct mbuf * m,int * dosignalp)979 netisr_queue_workstream(struct netisr_workstream *nwsp, u_int proto,
980     struct netisr_work *npwp, struct mbuf *m, int *dosignalp)
981 {
982 
983 	NWS_LOCK_ASSERT(nwsp);
984 
985 	*dosignalp = 0;
986 	if (npwp->nw_len < npwp->nw_qlimit) {
987 		m->m_nextpkt = NULL;
988 		if (npwp->nw_head == NULL) {
989 			npwp->nw_head = m;
990 			npwp->nw_tail = m;
991 		} else {
992 			npwp->nw_tail->m_nextpkt = m;
993 			npwp->nw_tail = m;
994 		}
995 		npwp->nw_len++;
996 		if (npwp->nw_len > npwp->nw_watermark)
997 			npwp->nw_watermark = npwp->nw_len;
998 
999 		/*
1000 		 * We must set the bit regardless of NWS_RUNNING, so that
1001 		 * swi_net() keeps calling netisr_process_workstream_proto().
1002 		 */
1003 		nwsp->nws_pendingbits |= (1 << proto);
1004 		if (!(nwsp->nws_flags &
1005 		    (NWS_RUNNING | NWS_DISPATCHING | NWS_SCHEDULED))) {
1006 			nwsp->nws_flags |= NWS_SCHEDULED;
1007 			*dosignalp = 1;	/* Defer until unlocked. */
1008 		}
1009 		npwp->nw_queued++;
1010 		return (0);
1011 	} else {
1012 		m_freem(m);
1013 		npwp->nw_qdrops++;
1014 		return (ENOBUFS);
1015 	}
1016 }
1017 
1018 static int
netisr_queue_internal(u_int proto,struct mbuf * m,u_int cpuid)1019 netisr_queue_internal(u_int proto, struct mbuf *m, u_int cpuid)
1020 {
1021 	struct netisr_workstream *nwsp;
1022 	struct netisr_work *npwp;
1023 	int dosignal, error;
1024 
1025 #ifdef NETISR_LOCKING
1026 	NETISR_LOCK_ASSERT();
1027 #endif
1028 	KASSERT(cpuid <= mp_maxid, ("%s: cpuid too big (%u, %u)", __func__,
1029 	    cpuid, mp_maxid));
1030 	KASSERT(!CPU_ABSENT(cpuid), ("%s: CPU %u absent", __func__, cpuid));
1031 
1032 	dosignal = 0;
1033 	error = 0;
1034 	nwsp = DPCPU_ID_PTR(cpuid, nws);
1035 	npwp = &nwsp->nws_work[proto];
1036 	NWS_LOCK(nwsp);
1037 	error = netisr_queue_workstream(nwsp, proto, npwp, m, &dosignal);
1038 	NWS_UNLOCK(nwsp);
1039 	if (dosignal)
1040 		NWS_SIGNAL(nwsp);
1041 	return (error);
1042 }
1043 
1044 int
netisr_queue_src(u_int proto,uintptr_t source,struct mbuf * m)1045 netisr_queue_src(u_int proto, uintptr_t source, struct mbuf *m)
1046 {
1047 #ifdef NETISR_LOCKING
1048 	struct rm_priotracker tracker;
1049 #endif
1050 	u_int cpuid;
1051 	int error;
1052 
1053 	KASSERT(proto < NETISR_MAXPROT,
1054 	    ("%s: invalid proto %u", __func__, proto));
1055 
1056 #ifdef NETISR_LOCKING
1057 	NETISR_RLOCK(&tracker);
1058 #endif
1059 	KASSERT(netisr_proto[proto].np_handler != NULL,
1060 	    ("%s: invalid proto %u", __func__, proto));
1061 
1062 #ifdef VIMAGE
1063 	if (V_netisr_enable[proto] == 0) {
1064 		m_freem(m);
1065 		return (ENOPROTOOPT);
1066 	}
1067 #endif
1068 
1069 	m = netisr_select_cpuid(&netisr_proto[proto], NETISR_DISPATCH_DEFERRED,
1070 	    source, m, &cpuid);
1071 	if (m != NULL) {
1072 		KASSERT(!CPU_ABSENT(cpuid), ("%s: CPU %u absent", __func__,
1073 		    cpuid));
1074 		VNET_ASSERT(m->m_pkthdr.rcvif != NULL,
1075 		    ("%s:%d rcvif == NULL: m=%p", __func__, __LINE__, m));
1076 		error = netisr_queue_internal(proto, m, cpuid);
1077 	} else
1078 		error = ENOBUFS;
1079 #ifdef NETISR_LOCKING
1080 	NETISR_RUNLOCK(&tracker);
1081 #endif
1082 	return (error);
1083 }
1084 
1085 int
netisr_queue(u_int proto,struct mbuf * m)1086 netisr_queue(u_int proto, struct mbuf *m)
1087 {
1088 
1089 	return (netisr_queue_src(proto, 0, m));
1090 }
1091 
1092 /*
1093  * Dispatch a packet for netisr processing; direct dispatch is permitted by
1094  * calling context.
1095  */
1096 int
netisr_dispatch_src(u_int proto,uintptr_t source,struct mbuf * m)1097 netisr_dispatch_src(u_int proto, uintptr_t source, struct mbuf *m)
1098 {
1099 #ifdef NETISR_LOCKING
1100 	struct rm_priotracker tracker;
1101 #endif
1102 	struct netisr_workstream *nwsp;
1103 	struct netisr_proto *npp;
1104 	struct netisr_work *npwp;
1105 	int dosignal, error;
1106 	u_int cpuid, dispatch_policy;
1107 
1108 	NET_EPOCH_ASSERT();
1109 	KASSERT(proto < NETISR_MAXPROT,
1110 	    ("%s: invalid proto %u", __func__, proto));
1111 #ifdef NETISR_LOCKING
1112 	NETISR_RLOCK(&tracker);
1113 #endif
1114 	npp = &netisr_proto[proto];
1115 	KASSERT(npp->np_handler != NULL, ("%s: invalid proto %u", __func__,
1116 	    proto));
1117 
1118 #ifdef VIMAGE
1119 	if (V_netisr_enable[proto] == 0) {
1120 		m_freem(m);
1121 		return (ENOPROTOOPT);
1122 	}
1123 #endif
1124 
1125 	dispatch_policy = netisr_get_dispatch(npp);
1126 	if (dispatch_policy == NETISR_DISPATCH_DEFERRED)
1127 		return (netisr_queue_src(proto, source, m));
1128 
1129 	/*
1130 	 * If direct dispatch is forced, then unconditionally dispatch
1131 	 * without a formal CPU selection.  Borrow the current CPU's stats,
1132 	 * even if there's no worker on it.  In this case we don't update
1133 	 * nws_flags because all netisr processing will be source ordered due
1134 	 * to always being forced to directly dispatch.
1135 	 */
1136 	if (dispatch_policy == NETISR_DISPATCH_DIRECT) {
1137 		nwsp = DPCPU_PTR(nws);
1138 		npwp = &nwsp->nws_work[proto];
1139 		npwp->nw_dispatched++;
1140 		npwp->nw_handled++;
1141 		netisr_proto[proto].np_handler(m);
1142 		error = 0;
1143 		goto out_unlock;
1144 	}
1145 
1146 	KASSERT(dispatch_policy == NETISR_DISPATCH_HYBRID,
1147 	    ("%s: unknown dispatch policy (%u)", __func__, dispatch_policy));
1148 
1149 	/*
1150 	 * Otherwise, we execute in a hybrid mode where we will try to direct
1151 	 * dispatch if we're on the right CPU and the netisr worker isn't
1152 	 * already running.
1153 	 */
1154 	sched_pin();
1155 	m = netisr_select_cpuid(&netisr_proto[proto], NETISR_DISPATCH_HYBRID,
1156 	    source, m, &cpuid);
1157 	if (m == NULL) {
1158 		error = ENOBUFS;
1159 		goto out_unpin;
1160 	}
1161 	KASSERT(!CPU_ABSENT(cpuid), ("%s: CPU %u absent", __func__, cpuid));
1162 	if (cpuid != curcpu)
1163 		goto queue_fallback;
1164 	nwsp = DPCPU_PTR(nws);
1165 	npwp = &nwsp->nws_work[proto];
1166 
1167 	/*-
1168 	 * We are willing to direct dispatch only if three conditions hold:
1169 	 *
1170 	 * (1) The netisr worker isn't already running,
1171 	 * (2) Another thread isn't already directly dispatching, and
1172 	 * (3) The netisr hasn't already been woken up.
1173 	 */
1174 	NWS_LOCK(nwsp);
1175 	if (nwsp->nws_flags & (NWS_RUNNING | NWS_DISPATCHING | NWS_SCHEDULED)) {
1176 		error = netisr_queue_workstream(nwsp, proto, npwp, m,
1177 		    &dosignal);
1178 		NWS_UNLOCK(nwsp);
1179 		if (dosignal)
1180 			NWS_SIGNAL(nwsp);
1181 		goto out_unpin;
1182 	}
1183 
1184 	/*
1185 	 * The current thread is now effectively the netisr worker, so set
1186 	 * the dispatching flag to prevent concurrent processing of the
1187 	 * stream from another thread (even the netisr worker), which could
1188 	 * otherwise lead to effective misordering of the stream.
1189 	 */
1190 	nwsp->nws_flags |= NWS_DISPATCHING;
1191 	NWS_UNLOCK(nwsp);
1192 	netisr_proto[proto].np_handler(m);
1193 	NWS_LOCK(nwsp);
1194 	nwsp->nws_flags &= ~NWS_DISPATCHING;
1195 	npwp->nw_handled++;
1196 	npwp->nw_hybrid_dispatched++;
1197 
1198 	/*
1199 	 * If other work was enqueued by another thread while we were direct
1200 	 * dispatching, we need to signal the netisr worker to do that work.
1201 	 * In the future, we might want to do some of that work in the
1202 	 * current thread, rather than trigger further context switches.  If
1203 	 * so, we'll want to establish a reasonable bound on the work done in
1204 	 * the "borrowed" context.
1205 	 */
1206 	if (nwsp->nws_pendingbits != 0) {
1207 		nwsp->nws_flags |= NWS_SCHEDULED;
1208 		dosignal = 1;
1209 	} else
1210 		dosignal = 0;
1211 	NWS_UNLOCK(nwsp);
1212 	if (dosignal)
1213 		NWS_SIGNAL(nwsp);
1214 	error = 0;
1215 	goto out_unpin;
1216 
1217 queue_fallback:
1218 	error = netisr_queue_internal(proto, m, cpuid);
1219 out_unpin:
1220 	sched_unpin();
1221 out_unlock:
1222 #ifdef NETISR_LOCKING
1223 	NETISR_RUNLOCK(&tracker);
1224 #endif
1225 	return (error);
1226 }
1227 
1228 int
netisr_dispatch(u_int proto,struct mbuf * m)1229 netisr_dispatch(u_int proto, struct mbuf *m)
1230 {
1231 
1232 	return (netisr_dispatch_src(proto, 0, m));
1233 }
1234 
1235 #ifdef DEVICE_POLLING
1236 /*
1237  * Kernel polling borrows a netisr thread to run interface polling in; this
1238  * function allows kernel polling to request that the netisr thread be
1239  * scheduled even if no packets are pending for protocols.
1240  */
1241 void
netisr_sched_poll(void)1242 netisr_sched_poll(void)
1243 {
1244 	struct netisr_workstream *nwsp;
1245 
1246 	nwsp = DPCPU_ID_PTR(nws_array[0], nws);
1247 	NWS_SIGNAL(nwsp);
1248 }
1249 #endif
1250 
1251 static void
netisr_start_swi(u_int cpuid,struct pcpu * pc)1252 netisr_start_swi(u_int cpuid, struct pcpu *pc)
1253 {
1254 	char swiname[12];
1255 	struct netisr_workstream *nwsp;
1256 	int error;
1257 
1258 	KASSERT(!CPU_ABSENT(cpuid), ("%s: CPU %u absent", __func__, cpuid));
1259 
1260 	nwsp = DPCPU_ID_PTR(cpuid, nws);
1261 	mtx_init(&nwsp->nws_mtx, "netisr_mtx", NULL, MTX_DEF);
1262 	nwsp->nws_cpu = cpuid;
1263 	snprintf(swiname, sizeof(swiname), "netisr %u", cpuid);
1264 	error = swi_add(&nwsp->nws_intr_event, swiname, swi_net, nwsp,
1265 	    SWI_NET, INTR_TYPE_NET | INTR_MPSAFE, &nwsp->nws_swi_cookie);
1266 	if (error)
1267 		panic("%s: swi_add %d", __func__, error);
1268 	pc->pc_netisr = nwsp->nws_intr_event;
1269 	if (netisr_bindthreads) {
1270 		error = intr_event_bind(nwsp->nws_intr_event, cpuid);
1271 		if (error != 0)
1272 			printf("%s: cpu %u: intr_event_bind: %d", __func__,
1273 			    cpuid, error);
1274 	}
1275 	NETISR_WLOCK();
1276 	nws_array[nws_count] = nwsp->nws_cpu;
1277 	nws_count++;
1278 	NETISR_WUNLOCK();
1279 }
1280 
1281 /*
1282  * Initialize the netisr subsystem.  We rely on BSS and static initialization
1283  * of most fields in global data structures.
1284  *
1285  * Start a worker thread for the boot CPU so that we can support network
1286  * traffic immediately in case the network stack is used before additional
1287  * CPUs are started (for example, diskless boot).
1288  */
1289 static void
netisr_init(void * arg)1290 netisr_init(void *arg)
1291 {
1292 	struct pcpu *pc;
1293 
1294 	NETISR_LOCK_INIT();
1295 	if (netisr_maxthreads == 0 || netisr_maxthreads < -1 )
1296 		netisr_maxthreads = 1;		/* default behavior */
1297 	else if (netisr_maxthreads == -1)
1298 		netisr_maxthreads = mp_ncpus;	/* use max cpus */
1299 	if (netisr_maxthreads > mp_ncpus) {
1300 		printf("netisr_init: forcing maxthreads from %d to %d\n",
1301 		    netisr_maxthreads, mp_ncpus);
1302 		netisr_maxthreads = mp_ncpus;
1303 	}
1304 	if (netisr_defaultqlimit > netisr_maxqlimit) {
1305 		printf("netisr_init: forcing defaultqlimit from %d to %d\n",
1306 		    netisr_defaultqlimit, netisr_maxqlimit);
1307 		netisr_defaultqlimit = netisr_maxqlimit;
1308 	}
1309 #ifdef DEVICE_POLLING
1310 	/*
1311 	 * The device polling code is not yet aware of how to deal with
1312 	 * multiple netisr threads, so for the time being compiling in device
1313 	 * polling disables parallel netisr workers.
1314 	 */
1315 	if (netisr_maxthreads != 1 || netisr_bindthreads != 0) {
1316 		printf("netisr_init: forcing maxthreads to 1 and "
1317 		    "bindthreads to 0 for device polling\n");
1318 		netisr_maxthreads = 1;
1319 		netisr_bindthreads = 0;
1320 	}
1321 #endif
1322 
1323 #ifdef EARLY_AP_STARTUP
1324 	STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
1325 		if (nws_count >= netisr_maxthreads)
1326 			break;
1327 		netisr_start_swi(pc->pc_cpuid, pc);
1328 	}
1329 #else
1330 	pc = get_pcpu();
1331 	netisr_start_swi(pc->pc_cpuid, pc);
1332 #endif
1333 }
1334 SYSINIT(netisr_init, SI_SUB_SOFTINTR, SI_ORDER_FIRST, netisr_init, NULL);
1335 
1336 #ifndef EARLY_AP_STARTUP
1337 /*
1338  * Start worker threads for additional CPUs.  No attempt to gracefully handle
1339  * work reassignment, we don't yet support dynamic reconfiguration.
1340  */
1341 static void
netisr_start(void * arg)1342 netisr_start(void *arg)
1343 {
1344 	struct pcpu *pc;
1345 
1346 	STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
1347 		if (nws_count >= netisr_maxthreads)
1348 			break;
1349 		/* Worker will already be present for boot CPU. */
1350 		if (pc->pc_netisr != NULL)
1351 			continue;
1352 		netisr_start_swi(pc->pc_cpuid, pc);
1353 	}
1354 }
1355 SYSINIT(netisr_start, SI_SUB_SMP, SI_ORDER_MIDDLE, netisr_start, NULL);
1356 #endif
1357 
1358 /*
1359  * Sysctl monitoring for netisr: query a list of registered protocols.
1360  */
1361 static int
sysctl_netisr_proto(SYSCTL_HANDLER_ARGS)1362 sysctl_netisr_proto(SYSCTL_HANDLER_ARGS)
1363 {
1364 	struct rm_priotracker tracker;
1365 	struct sysctl_netisr_proto *snpp, *snp_array;
1366 	struct netisr_proto *npp;
1367 	u_int counter, proto;
1368 	int error;
1369 
1370 	if (req->newptr != NULL)
1371 		return (EINVAL);
1372 	snp_array = malloc(sizeof(*snp_array) * NETISR_MAXPROT, M_TEMP,
1373 	    M_ZERO | M_WAITOK);
1374 	counter = 0;
1375 	NETISR_RLOCK(&tracker);
1376 	for (proto = 0; proto < NETISR_MAXPROT; proto++) {
1377 		npp = &netisr_proto[proto];
1378 		if (npp->np_name == NULL)
1379 			continue;
1380 		snpp = &snp_array[counter];
1381 		snpp->snp_version = sizeof(*snpp);
1382 		strlcpy(snpp->snp_name, npp->np_name, NETISR_NAMEMAXLEN);
1383 		snpp->snp_proto = proto;
1384 		snpp->snp_qlimit = npp->np_qlimit;
1385 		snpp->snp_policy = npp->np_policy;
1386 		snpp->snp_dispatch = npp->np_dispatch;
1387 		if (npp->np_m2flow != NULL)
1388 			snpp->snp_flags |= NETISR_SNP_FLAGS_M2FLOW;
1389 		if (npp->np_m2cpuid != NULL)
1390 			snpp->snp_flags |= NETISR_SNP_FLAGS_M2CPUID;
1391 		if (npp->np_drainedcpu != NULL)
1392 			snpp->snp_flags |= NETISR_SNP_FLAGS_DRAINEDCPU;
1393 		counter++;
1394 	}
1395 	NETISR_RUNLOCK(&tracker);
1396 	KASSERT(counter <= NETISR_MAXPROT,
1397 	    ("sysctl_netisr_proto: counter too big (%d)", counter));
1398 	error = SYSCTL_OUT(req, snp_array, sizeof(*snp_array) * counter);
1399 	free(snp_array, M_TEMP);
1400 	return (error);
1401 }
1402 
1403 SYSCTL_PROC(_net_isr, OID_AUTO, proto,
1404     CTLFLAG_RD|CTLTYPE_STRUCT|CTLFLAG_MPSAFE, 0, 0, sysctl_netisr_proto,
1405     "S,sysctl_netisr_proto",
1406     "Return list of protocols registered with netisr");
1407 
1408 /*
1409  * Sysctl monitoring for netisr: query a list of workstreams.
1410  */
1411 static int
sysctl_netisr_workstream(SYSCTL_HANDLER_ARGS)1412 sysctl_netisr_workstream(SYSCTL_HANDLER_ARGS)
1413 {
1414 	struct rm_priotracker tracker;
1415 	struct sysctl_netisr_workstream *snwsp, *snws_array;
1416 	struct netisr_workstream *nwsp;
1417 	u_int counter, cpuid;
1418 	int error;
1419 
1420 	if (req->newptr != NULL)
1421 		return (EINVAL);
1422 	snws_array = malloc(sizeof(*snws_array) * MAXCPU, M_TEMP,
1423 	    M_ZERO | M_WAITOK);
1424 	counter = 0;
1425 	NETISR_RLOCK(&tracker);
1426 	CPU_FOREACH(cpuid) {
1427 		nwsp = DPCPU_ID_PTR(cpuid, nws);
1428 		if (nwsp->nws_intr_event == NULL)
1429 			continue;
1430 		NWS_LOCK(nwsp);
1431 		snwsp = &snws_array[counter];
1432 		snwsp->snws_version = sizeof(*snwsp);
1433 
1434 		/*
1435 		 * For now, we equate workstream IDs and CPU IDs in the
1436 		 * kernel, but expose them independently to userspace in case
1437 		 * that assumption changes in the future.
1438 		 */
1439 		snwsp->snws_wsid = cpuid;
1440 		snwsp->snws_cpu = cpuid;
1441 		if (nwsp->nws_intr_event != NULL)
1442 			snwsp->snws_flags |= NETISR_SNWS_FLAGS_INTR;
1443 		NWS_UNLOCK(nwsp);
1444 		counter++;
1445 	}
1446 	NETISR_RUNLOCK(&tracker);
1447 	KASSERT(counter <= MAXCPU,
1448 	    ("sysctl_netisr_workstream: counter too big (%d)", counter));
1449 	error = SYSCTL_OUT(req, snws_array, sizeof(*snws_array) * counter);
1450 	free(snws_array, M_TEMP);
1451 	return (error);
1452 }
1453 
1454 SYSCTL_PROC(_net_isr, OID_AUTO, workstream,
1455     CTLFLAG_RD|CTLTYPE_STRUCT|CTLFLAG_MPSAFE, 0, 0, sysctl_netisr_workstream,
1456     "S,sysctl_netisr_workstream",
1457     "Return list of workstreams implemented by netisr");
1458 
1459 /*
1460  * Sysctl monitoring for netisr: query per-protocol data across all
1461  * workstreams.
1462  */
1463 static int
sysctl_netisr_work(SYSCTL_HANDLER_ARGS)1464 sysctl_netisr_work(SYSCTL_HANDLER_ARGS)
1465 {
1466 	struct rm_priotracker tracker;
1467 	struct sysctl_netisr_work *snwp, *snw_array;
1468 	struct netisr_workstream *nwsp;
1469 	struct netisr_proto *npp;
1470 	struct netisr_work *nwp;
1471 	u_int counter, cpuid, proto;
1472 	int error;
1473 
1474 	if (req->newptr != NULL)
1475 		return (EINVAL);
1476 	snw_array = malloc(sizeof(*snw_array) * MAXCPU * NETISR_MAXPROT,
1477 	    M_TEMP, M_ZERO | M_WAITOK);
1478 	counter = 0;
1479 	NETISR_RLOCK(&tracker);
1480 	CPU_FOREACH(cpuid) {
1481 		nwsp = DPCPU_ID_PTR(cpuid, nws);
1482 		if (nwsp->nws_intr_event == NULL)
1483 			continue;
1484 		NWS_LOCK(nwsp);
1485 		for (proto = 0; proto < NETISR_MAXPROT; proto++) {
1486 			npp = &netisr_proto[proto];
1487 			if (npp->np_name == NULL)
1488 				continue;
1489 			nwp = &nwsp->nws_work[proto];
1490 			snwp = &snw_array[counter];
1491 			snwp->snw_version = sizeof(*snwp);
1492 			snwp->snw_wsid = cpuid;		/* See comment above. */
1493 			snwp->snw_proto = proto;
1494 			snwp->snw_len = nwp->nw_len;
1495 			snwp->snw_watermark = nwp->nw_watermark;
1496 			snwp->snw_dispatched = nwp->nw_dispatched;
1497 			snwp->snw_hybrid_dispatched =
1498 			    nwp->nw_hybrid_dispatched;
1499 			snwp->snw_qdrops = nwp->nw_qdrops;
1500 			snwp->snw_queued = nwp->nw_queued;
1501 			snwp->snw_handled = nwp->nw_handled;
1502 			counter++;
1503 		}
1504 		NWS_UNLOCK(nwsp);
1505 	}
1506 	KASSERT(counter <= MAXCPU * NETISR_MAXPROT,
1507 	    ("sysctl_netisr_work: counter too big (%d)", counter));
1508 	NETISR_RUNLOCK(&tracker);
1509 	error = SYSCTL_OUT(req, snw_array, sizeof(*snw_array) * counter);
1510 	free(snw_array, M_TEMP);
1511 	return (error);
1512 }
1513 
1514 SYSCTL_PROC(_net_isr, OID_AUTO, work,
1515     CTLFLAG_RD|CTLTYPE_STRUCT|CTLFLAG_MPSAFE, 0, 0, sysctl_netisr_work,
1516     "S,sysctl_netisr_work",
1517     "Return list of per-workstream, per-protocol work in netisr");
1518 
1519 #ifdef DDB
DB_SHOW_COMMAND(netisr,db_show_netisr)1520 DB_SHOW_COMMAND(netisr, db_show_netisr)
1521 {
1522 	struct netisr_workstream *nwsp;
1523 	struct netisr_work *nwp;
1524 	int first, proto;
1525 	u_int cpuid;
1526 
1527 	db_printf("%3s %6s %5s %5s %5s %8s %8s %8s %8s\n", "CPU", "Proto",
1528 	    "Len", "WMark", "Max", "Disp", "HDisp", "Drop", "Queue");
1529 	CPU_FOREACH(cpuid) {
1530 		nwsp = DPCPU_ID_PTR(cpuid, nws);
1531 		if (nwsp->nws_intr_event == NULL)
1532 			continue;
1533 		first = 1;
1534 		for (proto = 0; proto < NETISR_MAXPROT; proto++) {
1535 			if (netisr_proto[proto].np_handler == NULL)
1536 				continue;
1537 			nwp = &nwsp->nws_work[proto];
1538 			if (first) {
1539 				db_printf("%3d ", cpuid);
1540 				first = 0;
1541 			} else
1542 				db_printf("%3s ", "");
1543 			db_printf(
1544 			    "%6s %5d %5d %5d %8ju %8ju %8ju %8ju\n",
1545 			    netisr_proto[proto].np_name, nwp->nw_len,
1546 			    nwp->nw_watermark, nwp->nw_qlimit,
1547 			    nwp->nw_dispatched, nwp->nw_hybrid_dispatched,
1548 			    nwp->nw_qdrops, nwp->nw_queued);
1549 		}
1550 	}
1551 }
1552 #endif
1553