source: rtems-libbsd/freebsd/sys/net/netisr.c @ d652c3b

4.115-freebsd-12freebsd-9.3
Last change on this file since d652c3b was d652c3b, checked in by Sebastian Huber <sebastian.huber@…>, on Oct 9, 2013 at 12:03:56 PM

Avoid per-CPU NETISR(9)

SMP support should be enabled once the new stack is ready for this.

  • Property mode set to 100644
File size: 34.5 KB
Line 
1#include <machine/rtems-bsd-config.h>
2
3/*-
4 * Copyright (c) 2007-2009 Robert N. M. Watson
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29#include <sys/cdefs.h>
30__FBSDID("$FreeBSD$");
31
32/*
33 * netisr is a packet dispatch service, allowing synchronous (directly
34 * dispatched) and asynchronous (deferred dispatch) processing of packets by
35 * registered protocol handlers.  Callers pass a protocol identifier and
36 * packet to netisr, along with a direct dispatch hint, and work will either
37 * be immediately processed with the registered handler, or passed to a
38 * kernel software interrupt (SWI) thread for deferred dispatch.  Callers
39 * will generally select one or the other based on:
40 *
41 * - Might directly dispatching a netisr handler lead to code reentrance or
42 *   lock recursion, such as entering the socket code from the socket code.
43 * - Might directly dispatching a netisr handler lead to recursive
44 *   processing, such as when decapsulating several wrapped layers of tunnel
45 *   information (IPSEC within IPSEC within ...).
46 *
47 * Maintaining ordering for protocol streams is a critical design concern.
48 * Enforcing ordering limits the opportunity for concurrency, but maintains
49 * the strong ordering requirements found in some protocols, such as TCP.  Of
50 * related concern is CPU affinity--it is desirable to process all data
51 * associated with a particular stream on the same CPU over time in order to
52 * avoid acquiring locks associated with the connection on different CPUs,
53 * keep connection data in one cache, and to generally encourage associated
54 * user threads to live on the same CPU as the stream.  It's also desirable
55 * to avoid lock migration and contention where locks are associated with
56 * more than one flow.
57 *
58 * netisr supports several policy variations, represented by the
59 * NETISR_POLICY_* constants, allowing protocols to play a varying role in
60 * identifying flows, assigning work to CPUs, etc.  These are described in
61 * detail in netisr.h.
62 */
63
64#include <rtems/bsd/local/opt_ddb.h>
65#include <rtems/bsd/local/opt_device_polling.h>
66
67#include <rtems/bsd/sys/param.h>
68#include <sys/bus.h>
69#include <sys/kernel.h>
70#include <sys/kthread.h>
71#include <sys/interrupt.h>
72#include <rtems/bsd/sys/lock.h>
73#include <sys/mbuf.h>
74#include <sys/mutex.h>
75#include <sys/pcpu.h>
76#include <sys/proc.h>
77#include <sys/rmlock.h>
78#include <sys/sched.h>
79#include <sys/smp.h>
80#include <sys/socket.h>
81#include <sys/sysctl.h>
82#include <sys/systm.h>
83
84#ifdef DDB
85#include <ddb/ddb.h>
86#endif
87
88#include <net/if.h>
89#include <net/if_var.h>
90#include <net/netisr.h>
91#include <net/vnet.h>
92
93/*-
94 * Synchronize use and modification of the registered netisr data structures;
95 * acquire a read lock while modifying the set of registered protocols to
96 * prevent partially registered or unregistered protocols from being run.
97 *
98 * The following data structures and fields are protected by this lock:
99 *
100 * - The np array, including all fields of struct netisr_proto.
101 * - The nws array, including all fields of struct netisr_worker.
102 * - The nws_array array.
103 *
104 * Note: the NETISR_LOCKING define controls whether read locks are acquired
105 * in packet processing paths requiring netisr registration stability.  This
106 * is disabled by default as it can lead to a measurable performance
107 * degradation even with rmlocks (3%-6% for loopback ping-pong traffic), and
108 * because netisr registration and unregistration is extremely rare at
109 * runtime.  If it becomes more common, this decision should be revisited.
110 *
111 * XXXRW: rmlocks don't support assertions.
112 */
113static struct rmlock    netisr_rmlock;
114#define NETISR_LOCK_INIT()      rm_init_flags(&netisr_rmlock, "netisr", \
115                                    RM_NOWITNESS)
116#define NETISR_LOCK_ASSERT()
117#define NETISR_RLOCK(tracker)   rm_rlock(&netisr_rmlock, (tracker))
118#define NETISR_RUNLOCK(tracker) rm_runlock(&netisr_rmlock, (tracker))
119#define NETISR_WLOCK()          rm_wlock(&netisr_rmlock)
120#define NETISR_WUNLOCK()        rm_wunlock(&netisr_rmlock)
121/* #define      NETISR_LOCKING */
122
123SYSCTL_NODE(_net, OID_AUTO, isr, CTLFLAG_RW, 0, "netisr");
124
125/*-
126 * Three direct dispatch policies are supported:
127 *
128 * - Always defer: all work is scheduled for a netisr, regardless of context.
129 *   (!direct)
130 *
131 * - Hybrid: if the executing context allows direct dispatch, and we're
132 *   running on the CPU the work would be done on, then direct dispatch if it
133 *   wouldn't violate ordering constraints on the workstream.
134 *   (direct && !direct_force)
135 *
136 * - Always direct: if the executing context allows direct dispatch, always
137 *   direct dispatch.  (direct && direct_force)
138 *
139 * Notice that changing the global policy could lead to short periods of
140 * misordered processing, but this is considered acceptable as compared to
141 * the complexity of enforcing ordering during policy changes.
142 */
143static int      netisr_direct_force = 1;        /* Always direct dispatch. */
144TUNABLE_INT("net.isr.direct_force", &netisr_direct_force);
145SYSCTL_INT(_net_isr, OID_AUTO, direct_force, CTLFLAG_RW,
146    &netisr_direct_force, 0, "Force direct dispatch");
147
148static int      netisr_direct = 1;      /* Enable direct dispatch. */
149TUNABLE_INT("net.isr.direct", &netisr_direct);
150SYSCTL_INT(_net_isr, OID_AUTO, direct, CTLFLAG_RW,
151    &netisr_direct, 0, "Enable direct dispatch");
152
153/*
154 * Allow the administrator to limit the number of threads (CPUs) to use for
155 * netisr.  We don't check netisr_maxthreads before creating the thread for
156 * CPU 0, so in practice we ignore values <= 1.  This must be set at boot.
157 * We will create at most one thread per CPU.
158 */
159static int      netisr_maxthreads = -1;         /* Max number of threads. */
160TUNABLE_INT("net.isr.maxthreads", &netisr_maxthreads);
161SYSCTL_INT(_net_isr, OID_AUTO, maxthreads, CTLFLAG_RD,
162    &netisr_maxthreads, 0,
163    "Use at most this many CPUs for netisr processing");
164
165static int      netisr_bindthreads = 0;         /* Bind threads to CPUs. */
166TUNABLE_INT("net.isr.bindthreads", &netisr_bindthreads);
167SYSCTL_INT(_net_isr, OID_AUTO, bindthreads, CTLFLAG_RD,
168    &netisr_bindthreads, 0, "Bind netisr threads to CPUs.");
169
170/*
171 * Limit per-workstream queues to at most net.isr.maxqlimit, both for initial
172 * configuration and later modification using netisr_setqlimit().
173 */
174#define NETISR_DEFAULT_MAXQLIMIT        10240
175static u_int    netisr_maxqlimit = NETISR_DEFAULT_MAXQLIMIT;
176TUNABLE_INT("net.isr.maxqlimit", &netisr_maxqlimit);
177SYSCTL_INT(_net_isr, OID_AUTO, maxqlimit, CTLFLAG_RD,
178    &netisr_maxqlimit, 0,
179    "Maximum netisr per-protocol, per-CPU queue depth.");
180
181/*
182 * The default per-workstream queue limit for protocols that don't initialize
183 * the nh_qlimit field of their struct netisr_handler.  If this is set above
184 * netisr_maxqlimit, we truncate it to the maximum during boot.
185 */
186#define NETISR_DEFAULT_DEFAULTQLIMIT    256
187static u_int    netisr_defaultqlimit = NETISR_DEFAULT_DEFAULTQLIMIT;
188TUNABLE_INT("net.isr.defaultqlimit", &netisr_defaultqlimit);
189SYSCTL_INT(_net_isr, OID_AUTO, defaultqlimit, CTLFLAG_RD,
190    &netisr_defaultqlimit, 0,
191    "Default netisr per-protocol, per-CPU queue limit if not set by protocol");
192
193/*
194 * Each protocol is described by a struct netisr_proto, which holds all
195 * global per-protocol information.  This data structure is set up by
196 * netisr_register(), and derived from the public struct netisr_handler.
197 */
198struct netisr_proto {
199        const char      *np_name;       /* Character string protocol name. */
200        netisr_handler_t *np_handler;   /* Protocol handler. */
201        netisr_m2flow_t *np_m2flow;     /* Query flow for untagged packet. */
202        netisr_m2cpuid_t *np_m2cpuid;   /* Query CPU to process packet on. */
203        netisr_drainedcpu_t *np_drainedcpu; /* Callback when drained a queue. */
204        u_int            np_qlimit;     /* Maximum per-CPU queue depth. */
205        u_int            np_policy;     /* Work placement policy. */
206};
207
208#define NETISR_MAXPROT          16              /* Compile-time limit. */
209
210/*
211 * The np array describes all registered protocols, indexed by protocol
212 * number.
213 */
214static struct netisr_proto      np[NETISR_MAXPROT];
215
216/*
217 * Protocol-specific work for each workstream is described by struct
218 * netisr_work.  Each work descriptor consists of an mbuf queue and
219 * statistics.
220 */
221struct netisr_work {
222        /*
223         * Packet queue, linked by m_nextpkt.
224         */
225        struct mbuf     *nw_head;
226        struct mbuf     *nw_tail;
227        u_int            nw_len;
228        u_int            nw_qlimit;
229        u_int            nw_watermark;
230
231        /*
232         * Statistics -- written unlocked, but mostly from curcpu.
233         */
234        u_int64_t        nw_dispatched; /* Number of direct dispatches. */
235        u_int64_t        nw_hybrid_dispatched; /* "" hybrid dispatches. */
236        u_int64_t        nw_qdrops;     /* "" drops. */
237        u_int64_t        nw_queued;     /* "" enqueues. */
238        u_int64_t        nw_handled;    /* "" handled in worker. */
239};
240
241/*
242 * Workstreams hold a set of ordered work across each protocol, and are
243 * described by netisr_workstream.  Each workstream is associated with a
244 * worker thread, which in turn is pinned to a CPU.  Work associated with a
245 * workstream can be processd in other threads during direct dispatch;
246 * concurrent processing is prevented by the NWS_RUNNING flag, which
247 * indicates that a thread is already processing the work queue.
248 */
249struct netisr_workstream {
250        struct intr_event *nws_intr_event;      /* Handler for stream. */
251        void            *nws_swi_cookie;        /* swi(9) cookie for stream. */
252        struct mtx       nws_mtx;               /* Synchronize work. */
253        u_int            nws_cpu;               /* CPU pinning. */
254        u_int            nws_flags;             /* Wakeup flags. */
255        u_int            nws_pendingbits;       /* Scheduled protocols. */
256
257        /*
258         * Each protocol has per-workstream data.
259         */
260        struct netisr_work      nws_work[NETISR_MAXPROT];
261} __aligned(CACHE_LINE_SIZE);
262
263#ifndef __rtems__
264/*
265 * Per-CPU workstream data.
266 */
267DPCPU_DEFINE(struct netisr_workstream, nws);
268
269/*
270 * Map contiguous values between 0 and nws_count into CPU IDs appropriate for
271 * accessing workstreams.  This allows constructions of the form
272 * DPCPU_ID_GET(nws_array[arbitraryvalue % nws_count], nws).
273 */
274static u_int                             nws_array[MAXCPU];
275
276/*
277 * Number of registered workstreams.  Will be at most the number of running
278 * CPUs once fully started.
279 */
280static u_int                             nws_count;
281SYSCTL_INT(_net_isr, OID_AUTO, numthreads, CTLFLAG_RD,
282    &nws_count, 0, "Number of extant netisr threads.");
283#else /* __rtems__ */
284static struct netisr_workstream rtems_bsd_nws;
285#endif /* __rtems__ */
286
287/*
288 * Per-workstream flags.
289 */
290#define NWS_RUNNING     0x00000001      /* Currently running in a thread. */
291#define NWS_DISPATCHING 0x00000002      /* Currently being direct-dispatched. */
292#define NWS_SCHEDULED   0x00000004      /* Signal issued. */
293
294/*
295 * Synchronization for each workstream: a mutex protects all mutable fields
296 * in each stream, including per-protocol state (mbuf queues).  The SWI is
297 * woken up if asynchronous dispatch is required.
298 */
299#define NWS_LOCK(s)             mtx_lock(&(s)->nws_mtx)
300#define NWS_LOCK_ASSERT(s)      mtx_assert(&(s)->nws_mtx, MA_OWNED)
301#define NWS_UNLOCK(s)           mtx_unlock(&(s)->nws_mtx)
302#define NWS_SIGNAL(s)           swi_sched((s)->nws_swi_cookie, 0)
303
304#ifndef __rtems__
305/*
306 * Utility routines for protocols that implement their own mapping of flows
307 * to CPUs.
308 */
309u_int
310netisr_get_cpucount(void)
311{
312
313        return (nws_count);
314}
315
316u_int
317netisr_get_cpuid(u_int cpunumber)
318{
319
320        KASSERT(cpunumber < nws_count, ("%s: %u > %u", __func__, cpunumber,
321            nws_count));
322
323        return (nws_array[cpunumber]);
324}
325
326/*
327 * The default implementation of -> CPU ID mapping.
328 *
329 * Non-static so that protocols can use it to map their own work to specific
330 * CPUs in a manner consistent to netisr for affinity purposes.
331 */
332u_int
333netisr_default_flow2cpu(u_int flowid)
334{
335
336        return (nws_array[flowid % nws_count]);
337}
338#endif  /* __rtems__ */
339
340/*
341 * Register a new netisr handler, which requires initializing per-protocol
342 * fields for each workstream.  All netisr work is briefly suspended while
343 * the protocol is installed.
344 */
345void
346netisr_register(const struct netisr_handler *nhp)
347{
348        struct netisr_work *npwp;
349        const char *name;
350        u_int i, proto;
351
352        proto = nhp->nh_proto;
353        name = nhp->nh_name;
354
355        /*
356         * Test that the requested registration is valid.
357         */
358        KASSERT(nhp->nh_name != NULL,
359            ("%s: nh_name NULL for %u", __func__, proto));
360        KASSERT(nhp->nh_handler != NULL,
361            ("%s: nh_handler NULL for %s", __func__, name));
362        KASSERT(nhp->nh_policy == NETISR_POLICY_SOURCE ||
363            nhp->nh_policy == NETISR_POLICY_FLOW ||
364            nhp->nh_policy == NETISR_POLICY_CPU,
365            ("%s: unsupported nh_policy %u for %s", __func__,
366            nhp->nh_policy, name));
367        KASSERT(nhp->nh_policy == NETISR_POLICY_FLOW ||
368            nhp->nh_m2flow == NULL,
369            ("%s: nh_policy != FLOW but m2flow defined for %s", __func__,
370            name));
371        KASSERT(nhp->nh_policy == NETISR_POLICY_CPU || nhp->nh_m2cpuid == NULL,
372            ("%s: nh_policy != CPU but m2cpuid defined for %s", __func__,
373            name));
374        KASSERT(nhp->nh_policy != NETISR_POLICY_CPU || nhp->nh_m2cpuid != NULL,
375            ("%s: nh_policy == CPU but m2cpuid not defined for %s", __func__,
376            name));
377        KASSERT(proto < NETISR_MAXPROT,
378            ("%s(%u, %s): protocol too big", __func__, proto, name));
379
380        /*
381         * Test that no existing registration exists for this protocol.
382         */
383        NETISR_WLOCK();
384        KASSERT(np[proto].np_name == NULL,
385            ("%s(%u, %s): name present", __func__, proto, name));
386        KASSERT(np[proto].np_handler == NULL,
387            ("%s(%u, %s): handler present", __func__, proto, name));
388
389        np[proto].np_name = name;
390        np[proto].np_handler = nhp->nh_handler;
391        np[proto].np_m2flow = nhp->nh_m2flow;
392        np[proto].np_m2cpuid = nhp->nh_m2cpuid;
393        np[proto].np_drainedcpu = nhp->nh_drainedcpu;
394        if (nhp->nh_qlimit == 0)
395                np[proto].np_qlimit = netisr_defaultqlimit;
396        else if (nhp->nh_qlimit > netisr_maxqlimit) {
397                printf("%s: %s requested queue limit %u capped to "
398                    "net.isr.maxqlimit %u\n", __func__, name, nhp->nh_qlimit,
399                    netisr_maxqlimit);
400                np[proto].np_qlimit = netisr_maxqlimit;
401        } else
402                np[proto].np_qlimit = nhp->nh_qlimit;
403        np[proto].np_policy = nhp->nh_policy;
404        for (i = 0; i <= mp_maxid; i++) {
405                if (CPU_ABSENT(i))
406                        continue;
407#ifndef __rtems__
408                npwp = &(DPCPU_ID_PTR(i, nws))->nws_work[proto];
409#else /* __rtems__ */
410                npwp = &rtems_bsd_nws.nws_work[proto];
411#endif /* __rtems__ */
412                bzero(npwp, sizeof(*npwp));
413                npwp->nw_qlimit = np[proto].np_qlimit;
414        }
415        NETISR_WUNLOCK();
416}
417
418/*
419 * Clear drop counters across all workstreams for a protocol.
420 */
421void
422netisr_clearqdrops(const struct netisr_handler *nhp)
423{
424        struct netisr_work *npwp;
425#ifdef INVARIANTS
426        const char *name;
427#endif
428        u_int i, proto;
429
430        proto = nhp->nh_proto;
431#ifdef INVARIANTS
432        name = nhp->nh_name;
433#endif
434        KASSERT(proto < NETISR_MAXPROT,
435            ("%s(%u): protocol too big for %s", __func__, proto, name));
436
437        NETISR_WLOCK();
438        KASSERT(np[proto].np_handler != NULL,
439            ("%s(%u): protocol not registered for %s", __func__, proto,
440            name));
441
442        for (i = 0; i <= mp_maxid; i++) {
443                if (CPU_ABSENT(i))
444                        continue;
445#ifndef __rtems__
446                npwp = &(DPCPU_ID_PTR(i, nws))->nws_work[proto];
447#else /* __rtems__ */
448                npwp = &rtems_bsd_nws.nws_work[proto];
449#endif /* __rtems__ */
450                npwp->nw_qdrops = 0;
451        }
452        NETISR_WUNLOCK();
453}
454
455/*
456 * Query the current drop counters across all workstreams for a protocol.
457 */
458void
459netisr_getqdrops(const struct netisr_handler *nhp, u_int64_t *qdropp)
460{
461        struct netisr_work *npwp;
462        struct rm_priotracker tracker;
463#ifdef INVARIANTS
464        const char *name;
465#endif
466        u_int i, proto;
467
468        *qdropp = 0;
469        proto = nhp->nh_proto;
470#ifdef INVARIANTS
471        name = nhp->nh_name;
472#endif
473        KASSERT(proto < NETISR_MAXPROT,
474            ("%s(%u): protocol too big for %s", __func__, proto, name));
475
476        NETISR_RLOCK(&tracker);
477        KASSERT(np[proto].np_handler != NULL,
478            ("%s(%u): protocol not registered for %s", __func__, proto,
479            name));
480
481        for (i = 0; i <= mp_maxid; i++) {
482                if (CPU_ABSENT(i))
483                        continue;
484#ifndef __rtems__
485                npwp = &(DPCPU_ID_PTR(i, nws))->nws_work[proto];
486#else /* __rtems__ */
487                npwp = &rtems_bsd_nws.nws_work[proto];
488#endif /* __rtems__ */
489                *qdropp += npwp->nw_qdrops;
490        }
491        NETISR_RUNLOCK(&tracker);
492}
493
494/*
495 * Query the current queue limit for per-workstream queues for a protocol.
496 */
497void
498netisr_getqlimit(const struct netisr_handler *nhp, u_int *qlimitp)
499{
500        struct rm_priotracker tracker;
501#ifdef INVARIANTS
502        const char *name;
503#endif
504        u_int proto;
505
506        proto = nhp->nh_proto;
507#ifdef INVARIANTS
508        name = nhp->nh_name;
509#endif
510        KASSERT(proto < NETISR_MAXPROT,
511            ("%s(%u): protocol too big for %s", __func__, proto, name));
512
513        NETISR_RLOCK(&tracker);
514        KASSERT(np[proto].np_handler != NULL,
515            ("%s(%u): protocol not registered for %s", __func__, proto,
516            name));
517        *qlimitp = np[proto].np_qlimit;
518        NETISR_RUNLOCK(&tracker);
519}
520
521/*
522 * Update the queue limit across per-workstream queues for a protocol.  We
523 * simply change the limits, and don't drain overflowed packets as they will
524 * (hopefully) take care of themselves shortly.
525 */
526int
527netisr_setqlimit(const struct netisr_handler *nhp, u_int qlimit)
528{
529        struct netisr_work *npwp;
530#ifdef INVARIANTS
531        const char *name;
532#endif
533        u_int i, proto;
534
535        if (qlimit > netisr_maxqlimit)
536                return (EINVAL);
537
538        proto = nhp->nh_proto;
539#ifdef INVARIANTS
540        name = nhp->nh_name;
541#endif
542        KASSERT(proto < NETISR_MAXPROT,
543            ("%s(%u): protocol too big for %s", __func__, proto, name));
544
545        NETISR_WLOCK();
546        KASSERT(np[proto].np_handler != NULL,
547            ("%s(%u): protocol not registered for %s", __func__, proto,
548            name));
549
550        np[proto].np_qlimit = qlimit;
551        for (i = 0; i <= mp_maxid; i++) {
552                if (CPU_ABSENT(i))
553                        continue;
554#ifndef __rtems__
555                npwp = &(DPCPU_ID_PTR(i, nws))->nws_work[proto];
556#else /* __rtems__ */
557                npwp = &rtems_bsd_nws.nws_work[proto];
558#endif /* __rtems__ */
559                npwp->nw_qlimit = qlimit;
560        }
561        NETISR_WUNLOCK();
562        return (0);
563}
564
565/*
566 * Drain all packets currently held in a particular protocol work queue.
567 */
568static void
569netisr_drain_proto(struct netisr_work *npwp)
570{
571        struct mbuf *m;
572
573        /*
574         * We would assert the lock on the workstream but it's not passed in.
575         */
576        while ((m = npwp->nw_head) != NULL) {
577                npwp->nw_head = m->m_nextpkt;
578                m->m_nextpkt = NULL;
579                if (npwp->nw_head == NULL)
580                        npwp->nw_tail = NULL;
581                npwp->nw_len--;
582                m_freem(m);
583        }
584        KASSERT(npwp->nw_tail == NULL, ("%s: tail", __func__));
585        KASSERT(npwp->nw_len == 0, ("%s: len", __func__));
586}
587
588/*
589 * Remove the registration of a network protocol, which requires clearing
590 * per-protocol fields across all workstreams, including freeing all mbufs in
591 * the queues at time of unregister.  All work in netisr is briefly suspended
592 * while this takes place.
593 */
594void
595netisr_unregister(const struct netisr_handler *nhp)
596{
597        struct netisr_work *npwp;
598#ifdef INVARIANTS
599        const char *name;
600#endif
601        u_int i, proto;
602
603        proto = nhp->nh_proto;
604#ifdef INVARIANTS
605        name = nhp->nh_name;
606#endif
607        KASSERT(proto < NETISR_MAXPROT,
608            ("%s(%u): protocol too big for %s", __func__, proto, name));
609
610        NETISR_WLOCK();
611        KASSERT(np[proto].np_handler != NULL,
612            ("%s(%u): protocol not registered for %s", __func__, proto,
613            name));
614
615        np[proto].np_name = NULL;
616        np[proto].np_handler = NULL;
617        np[proto].np_m2flow = NULL;
618        np[proto].np_m2cpuid = NULL;
619        np[proto].np_qlimit = 0;
620        np[proto].np_policy = 0;
621        for (i = 0; i <= mp_maxid; i++) {
622                if (CPU_ABSENT(i))
623                        continue;
624#ifndef __rtems__
625                npwp = &(DPCPU_ID_PTR(i, nws))->nws_work[proto];
626#else /* __rtems__ */
627                npwp = &rtems_bsd_nws.nws_work[proto];
628#endif /* __rtems__ */
629                netisr_drain_proto(npwp);
630                bzero(npwp, sizeof(*npwp));
631        }
632        NETISR_WUNLOCK();
633}
634
635/*
636 * Look up the workstream given a packet and source identifier.  Do this by
637 * checking the protocol's policy, and optionally call out to the protocol
638 * for assistance if required.
639 */
640static struct mbuf *
641netisr_select_cpuid(struct netisr_proto *npp, uintptr_t source,
642    struct mbuf *m, u_int *cpuidp)
643{
644        struct ifnet *ifp;
645
646        NETISR_LOCK_ASSERT();
647
648#ifndef __rtems__
649        /*
650         * In the event we have only one worker, shortcut and deliver to it
651         * without further ado.
652         */
653        if (nws_count == 1) {
654                *cpuidp = nws_array[0];
655                return (m);
656        }
657
658        /*
659         * What happens next depends on the policy selected by the protocol.
660         * If we want to support per-interface policies, we should do that
661         * here first.
662         */
663        switch (npp->np_policy) {
664        case NETISR_POLICY_CPU:
665                return (npp->np_m2cpuid(m, source, cpuidp));
666
667        case NETISR_POLICY_FLOW:
668                if (!(m->m_flags & M_FLOWID) && npp->np_m2flow != NULL) {
669                        m = npp->np_m2flow(m, source);
670                        if (m == NULL)
671                                return (NULL);
672                }
673                if (m->m_flags & M_FLOWID) {
674                        *cpuidp =
675                            netisr_default_flow2cpu(m->m_pkthdr.flowid);
676                        return (m);
677                }
678                /* FALLTHROUGH */
679
680        case NETISR_POLICY_SOURCE:
681                ifp = m->m_pkthdr.rcvif;
682                if (ifp != NULL)
683                        *cpuidp = nws_array[(ifp->if_index + source) %
684                            nws_count];
685                else
686                        *cpuidp = nws_array[source % nws_count];
687                return (m);
688
689        default:
690                panic("%s: invalid policy %u for %s", __func__,
691                    npp->np_policy, npp->np_name);
692        }
693#else /* __rtems__ */
694        *cpuidp = 0;
695        return (m);
696#endif /* __rtems__ */
697}
698
699/*
700 * Process packets associated with a workstream and protocol.  For reasons of
701 * fairness, we process up to one complete netisr queue at a time, moving the
702 * queue to a stack-local queue for processing, but do not loop refreshing
703 * from the global queue.  The caller is responsible for deciding whether to
704 * loop, and for setting the NWS_RUNNING flag.  The passed workstream will be
705 * locked on entry and relocked before return, but will be released while
706 * processing.  The number of packets processed is returned.
707 */
708static u_int
709netisr_process_workstream_proto(struct netisr_workstream *nwsp, u_int proto)
710{
711        struct netisr_work local_npw, *npwp;
712        u_int handled;
713        struct mbuf *m;
714
715        NETISR_LOCK_ASSERT();
716        NWS_LOCK_ASSERT(nwsp);
717
718        KASSERT(nwsp->nws_flags & NWS_RUNNING,
719            ("%s(%u): not running", __func__, proto));
720        KASSERT(proto >= 0 && proto < NETISR_MAXPROT,
721            ("%s(%u): invalid proto\n", __func__, proto));
722
723        npwp = &nwsp->nws_work[proto];
724        if (npwp->nw_len == 0)
725                return (0);
726
727        /*
728         * Move the global work queue to a thread-local work queue.
729         *
730         * Notice that this means the effective maximum length of the queue
731         * is actually twice that of the maximum queue length specified in
732         * the protocol registration call.
733         */
734        handled = npwp->nw_len;
735        local_npw = *npwp;
736        npwp->nw_head = NULL;
737        npwp->nw_tail = NULL;
738        npwp->nw_len = 0;
739        nwsp->nws_pendingbits &= ~(1 << proto);
740        NWS_UNLOCK(nwsp);
741        while ((m = local_npw.nw_head) != NULL) {
742                local_npw.nw_head = m->m_nextpkt;
743                m->m_nextpkt = NULL;
744                if (local_npw.nw_head == NULL)
745                        local_npw.nw_tail = NULL;
746                local_npw.nw_len--;
747                VNET_ASSERT(m->m_pkthdr.rcvif != NULL);
748                CURVNET_SET(m->m_pkthdr.rcvif->if_vnet);
749                np[proto].np_handler(m);
750                CURVNET_RESTORE();
751        }
752        KASSERT(local_npw.nw_len == 0,
753            ("%s(%u): len %u", __func__, proto, local_npw.nw_len));
754        if (np[proto].np_drainedcpu)
755                np[proto].np_drainedcpu(nwsp->nws_cpu);
756        NWS_LOCK(nwsp);
757        npwp->nw_handled += handled;
758        return (handled);
759}
760
761/*
762 * SWI handler for netisr -- processes prackets in a set of workstreams that
763 * it owns, woken up by calls to NWS_SIGNAL().  If this workstream is already
764 * being direct dispatched, go back to sleep and wait for the dispatching
765 * thread to wake us up again.
766 */
767static void
768swi_net(void *arg)
769{
770#ifdef NETISR_LOCKING
771        struct rm_priotracker tracker;
772#endif
773        struct netisr_workstream *nwsp;
774        u_int bits, prot;
775
776        nwsp = arg;
777
778#ifdef DEVICE_POLLING
779        KASSERT(nws_count == 1,
780            ("%s: device_polling but nws_count != 1", __func__));
781        netisr_poll();
782#endif
783#ifdef NETISR_LOCKING
784        NETISR_RLOCK(&tracker);
785#endif
786        NWS_LOCK(nwsp);
787        KASSERT(!(nwsp->nws_flags & NWS_RUNNING), ("swi_net: running"));
788        if (nwsp->nws_flags & NWS_DISPATCHING)
789                goto out;
790        nwsp->nws_flags |= NWS_RUNNING;
791        nwsp->nws_flags &= ~NWS_SCHEDULED;
792        while ((bits = nwsp->nws_pendingbits) != 0) {
793                while ((prot = ffs(bits)) != 0) {
794                        prot--;
795                        bits &= ~(1 << prot);
796                        (void)netisr_process_workstream_proto(nwsp, prot);
797                }
798        }
799        nwsp->nws_flags &= ~NWS_RUNNING;
800out:
801        NWS_UNLOCK(nwsp);
802#ifdef NETISR_LOCKING
803        NETISR_RUNLOCK(&tracker);
804#endif
805#ifdef DEVICE_POLLING
806        netisr_pollmore();
807#endif
808}
809
810static int
811netisr_queue_workstream(struct netisr_workstream *nwsp, u_int proto,
812    struct netisr_work *npwp, struct mbuf *m, int *dosignalp)
813{
814
815        NWS_LOCK_ASSERT(nwsp);
816
817        *dosignalp = 0;
818        if (npwp->nw_len < npwp->nw_qlimit) {
819                m->m_nextpkt = NULL;
820                if (npwp->nw_head == NULL) {
821                        npwp->nw_head = m;
822                        npwp->nw_tail = m;
823                } else {
824                        npwp->nw_tail->m_nextpkt = m;
825                        npwp->nw_tail = m;
826                }
827                npwp->nw_len++;
828                if (npwp->nw_len > npwp->nw_watermark)
829                        npwp->nw_watermark = npwp->nw_len;
830                nwsp->nws_pendingbits |= (1 << proto);
831                if (!(nwsp->nws_flags & 
832                    (NWS_RUNNING | NWS_DISPATCHING | NWS_SCHEDULED))) {
833                        nwsp->nws_flags |= NWS_SCHEDULED;
834                        *dosignalp = 1; /* Defer until unlocked. */
835                }
836                npwp->nw_queued++;
837                return (0);
838        } else {
839                m_freem(m);
840                npwp->nw_qdrops++;
841                return (ENOBUFS);
842        }
843}
844
845static int
846netisr_queue_internal(u_int proto, struct mbuf *m, u_int cpuid)
847{
848        struct netisr_workstream *nwsp;
849        struct netisr_work *npwp;
850        int dosignal, error;
851
852#ifdef NETISR_LOCKING
853        NETISR_LOCK_ASSERT();
854#endif
855        KASSERT(cpuid <= mp_maxid, ("%s: cpuid too big (%u, %u)", __func__,
856            cpuid, mp_maxid));
857        KASSERT(!CPU_ABSENT(cpuid), ("%s: CPU %u absent", __func__, cpuid));
858
859        dosignal = 0;
860        error = 0;
861#ifndef __rtems__
862        nwsp = DPCPU_ID_PTR(cpuid, nws);
863#else /* __rtems__ */
864        nwsp = &rtems_bsd_nws;
865#endif /* __rtems__ */
866        npwp = &nwsp->nws_work[proto];
867        NWS_LOCK(nwsp);
868        error = netisr_queue_workstream(nwsp, proto, npwp, m, &dosignal);
869        NWS_UNLOCK(nwsp);
870        if (dosignal)
871                NWS_SIGNAL(nwsp);
872        return (error);
873}
874
875int
876netisr_queue_src(u_int proto, uintptr_t source, struct mbuf *m)
877{
878#ifdef NETISR_LOCKING
879        struct rm_priotracker tracker;
880#endif
881        u_int cpuid;
882        int error;
883
884        KASSERT(proto < NETISR_MAXPROT,
885            ("%s: invalid proto %u", __func__, proto));
886
887#ifdef NETISR_LOCKING
888        NETISR_RLOCK(&tracker);
889#endif
890        KASSERT(np[proto].np_handler != NULL,
891            ("%s: invalid proto %u", __func__, proto));
892
893        m = netisr_select_cpuid(&np[proto], source, m, &cpuid);
894        if (m != NULL) {
895                KASSERT(!CPU_ABSENT(cpuid), ("%s: CPU %u absent", __func__,
896                    cpuid));
897                error = netisr_queue_internal(proto, m, cpuid);
898        } else
899                error = ENOBUFS;
900#ifdef NETISR_LOCKING
901        NETISR_RUNLOCK(&tracker);
902#endif
903        return (error);
904}
905
906int
907netisr_queue(u_int proto, struct mbuf *m)
908{
909
910        return (netisr_queue_src(proto, 0, m));
911}
912
913/*
914 * Dispatch a packet for netisr processing, direct dispatch permitted by
915 * calling context.
916 */
917int
918netisr_dispatch_src(u_int proto, uintptr_t source, struct mbuf *m)
919{
920#ifdef NETISR_LOCKING
921        struct rm_priotracker tracker;
922#endif
923        struct netisr_workstream *nwsp;
924        struct netisr_work *npwp;
925        int dosignal, error;
926        u_int cpuid;
927
928        /*
929         * If direct dispatch is entirely disabled, fall back on queueing.
930         */
931        if (!netisr_direct)
932                return (netisr_queue_src(proto, source, m));
933
934        KASSERT(proto < NETISR_MAXPROT,
935            ("%s: invalid proto %u", __func__, proto));
936#ifdef NETISR_LOCKING
937        NETISR_RLOCK(&tracker);
938#endif
939        KASSERT(np[proto].np_handler != NULL,
940            ("%s: invalid proto %u", __func__, proto));
941
942        /*
943         * If direct dispatch is forced, then unconditionally dispatch
944         * without a formal CPU selection.  Borrow the current CPU's stats,
945         * even if there's no worker on it.  In this case we don't update
946         * nws_flags because all netisr processing will be source ordered due
947         * to always being forced to directly dispatch.
948         */
949        if (netisr_direct_force) {
950                nwsp = DPCPU_PTR(nws);
951                npwp = &nwsp->nws_work[proto];
952                npwp->nw_dispatched++;
953                npwp->nw_handled++;
954                np[proto].np_handler(m);
955                error = 0;
956                goto out_unlock;
957        }
958
959        /*
960         * Otherwise, we execute in a hybrid mode where we will try to direct
961         * dispatch if we're on the right CPU and the netisr worker isn't
962         * already running.
963         */
964        m = netisr_select_cpuid(&np[proto], source, m, &cpuid);
965        if (m == NULL) {
966                error = ENOBUFS;
967                goto out_unlock;
968        }
969        KASSERT(!CPU_ABSENT(cpuid), ("%s: CPU %u absent", __func__, cpuid));
970#ifndef __rtems__
971        sched_pin();
972#endif  /* __rtems__ */
973        if (cpuid != curcpu)
974                goto queue_fallback;
975        nwsp = DPCPU_PTR(nws);
976        npwp = &nwsp->nws_work[proto];
977
978        /*-
979         * We are willing to direct dispatch only if three conditions hold:
980         *
981         * (1) The netisr worker isn't already running,
982         * (2) Another thread isn't already directly dispatching, and
983         * (3) The netisr hasn't already been woken up.
984         */
985        NWS_LOCK(nwsp);
986        if (nwsp->nws_flags & (NWS_RUNNING | NWS_DISPATCHING | NWS_SCHEDULED)) {
987                error = netisr_queue_workstream(nwsp, proto, npwp, m,
988                    &dosignal);
989                NWS_UNLOCK(nwsp);
990                if (dosignal)
991                        NWS_SIGNAL(nwsp);
992                goto out_unpin;
993        }
994
995        /*
996         * The current thread is now effectively the netisr worker, so set
997         * the dispatching flag to prevent concurrent processing of the
998         * stream from another thread (even the netisr worker), which could
999         * otherwise lead to effective misordering of the stream.
1000         */
1001        nwsp->nws_flags |= NWS_DISPATCHING;
1002        NWS_UNLOCK(nwsp);
1003        np[proto].np_handler(m);
1004        NWS_LOCK(nwsp);
1005        nwsp->nws_flags &= ~NWS_DISPATCHING;
1006        npwp->nw_handled++;
1007        npwp->nw_hybrid_dispatched++;
1008
1009        /*
1010         * If other work was enqueued by another thread while we were direct
1011         * dispatching, we need to signal the netisr worker to do that work.
1012         * In the future, we might want to do some of that work in the
1013         * current thread, rather than trigger further context switches.  If
1014         * so, we'll want to establish a reasonable bound on the work done in
1015         * the "borrowed" context.
1016         */
1017        if (nwsp->nws_pendingbits != 0) {
1018                nwsp->nws_flags |= NWS_SCHEDULED;
1019                dosignal = 1;
1020        } else
1021                dosignal = 0;
1022        NWS_UNLOCK(nwsp);
1023        if (dosignal)
1024                NWS_SIGNAL(nwsp);
1025        error = 0;
1026        goto out_unpin;
1027
1028queue_fallback:
1029        error = netisr_queue_internal(proto, m, cpuid);
1030out_unpin:
1031#ifndef __rtems__
1032        sched_unpin();
1033#endif  /* __rtems__ */
1034out_unlock:
1035#ifdef NETISR_LOCKING
1036        NETISR_RUNLOCK(&tracker);
1037#endif
1038        return (error);
1039}
1040
1041int
1042netisr_dispatch(u_int proto, struct mbuf *m)
1043{
1044
1045        return (netisr_dispatch_src(proto, 0, m));
1046}
1047
1048#ifdef DEVICE_POLLING
1049/*
1050 * Kernel polling borrows a netisr thread to run interface polling in; this
1051 * function allows kernel polling to request that the netisr thread be
1052 * scheduled even if no packets are pending for protocols.
1053 */
1054void
1055netisr_sched_poll(void)
1056{
1057        struct netisr_workstream *nwsp;
1058
1059        nwsp = DPCPU_ID_PTR(nws_array[0], nws);
1060        NWS_SIGNAL(nwsp);
1061}
1062#endif
1063
1064static void
1065netisr_start_swi(u_int cpuid, struct pcpu *pc)
1066{
1067        char swiname[12];
1068        struct netisr_workstream *nwsp;
1069        int error;
1070
1071        KASSERT(!CPU_ABSENT(cpuid), ("%s: CPU %u absent", __func__, cpuid));
1072
1073#ifndef __rtems__
1074        nwsp = DPCPU_ID_PTR(cpuid, nws);
1075#else /* __rtems__ */
1076        nwsp = &rtems_bsd_nws;
1077#endif /* __rtems__ */
1078        mtx_init(&nwsp->nws_mtx, "netisr_mtx", NULL, MTX_DEF);
1079        nwsp->nws_cpu = cpuid;
1080        snprintf(swiname, sizeof(swiname), "netisr %u", cpuid);
1081        error = swi_add(&nwsp->nws_intr_event, swiname, swi_net, nwsp,
1082            SWI_NET, INTR_MPSAFE, &nwsp->nws_swi_cookie);
1083        if (error)
1084                panic("%s: swi_add %d", __func__, error);
1085#ifndef __rtems__
1086        pc->pc_netisr = nwsp->nws_intr_event;
1087        if (netisr_bindthreads) {
1088                error = intr_event_bind(nwsp->nws_intr_event, cpuid);
1089                if (error != 0)
1090                        printf("%s: cpu %u: intr_event_bind: %d", __func__,
1091                            cpuid, error);
1092        }
1093        NETISR_WLOCK();
1094        nws_array[nws_count] = nwsp->nws_cpu;
1095        nws_count++;
1096        NETISR_WUNLOCK();
1097#endif
1098}
1099
1100/*
1101 * Initialize the netisr subsystem.  We rely on BSS and static initialization
1102 * of most fields in global data structures.
1103 *
1104 * Start a worker thread for the boot CPU so that we can support network
1105 * traffic immediately in case the network stack is used before additional
1106 * CPUs are started (for example, diskless boot).
1107 */
1108static void
1109netisr_init(void *arg)
1110{
1111
1112        KASSERT(curcpu == 0, ("%s: not on CPU 0", __func__));
1113
1114        NETISR_LOCK_INIT();
1115        if (netisr_maxthreads < 1)
1116                netisr_maxthreads = 1;
1117        if (netisr_maxthreads > mp_ncpus) {
1118                printf("netisr_init: forcing maxthreads from %d to %d\n",
1119                    netisr_maxthreads, mp_ncpus);
1120                netisr_maxthreads = mp_ncpus;
1121        }
1122        if (netisr_defaultqlimit > netisr_maxqlimit) {
1123                printf("netisr_init: forcing defaultqlimit from %d to %d\n",
1124                    netisr_defaultqlimit, netisr_maxqlimit);
1125                netisr_defaultqlimit = netisr_maxqlimit;
1126        }
1127#ifdef DEVICE_POLLING
1128        /*
1129         * The device polling code is not yet aware of how to deal with
1130         * multiple netisr threads, so for the time being compiling in device
1131         * polling disables parallel netisr workers.
1132         */
1133        if (netisr_maxthreads != 1 || netisr_bindthreads != 0) {
1134                printf("netisr_init: forcing maxthreads to 1 and "
1135                    "bindthreads to 0 for device polling\n");
1136                netisr_maxthreads = 1;
1137                netisr_bindthreads = 0;
1138        }
1139#endif
1140
1141#ifndef __rtems__
1142        netisr_start_swi(curcpu, pcpu_find(curcpu));
1143#else /* __rtems__ */
1144        netisr_start_swi(0, NULL);
1145#endif /* __rtems__ */
1146}
1147SYSINIT(netisr_init, SI_SUB_SOFTINTR, SI_ORDER_FIRST, netisr_init, NULL);
1148
1149#ifndef __rtems__
1150/*
1151 * Start worker threads for additional CPUs.  No attempt to gracefully handle
1152 * work reassignment, we don't yet support dynamic reconfiguration.
1153 */
1154static void
1155netisr_start(void *arg)
1156{
1157        struct pcpu *pc;
1158
1159        SLIST_FOREACH(pc, &cpuhead, pc_allcpu) {
1160                if (nws_count >= netisr_maxthreads)
1161                        break;
1162                /* XXXRW: Is skipping absent CPUs still required here? */
1163                if (CPU_ABSENT(pc->pc_cpuid))
1164                        continue;
1165                /* Worker will already be present for boot CPU. */
1166                if (pc->pc_netisr != NULL)
1167                        continue;
1168                netisr_start_swi(pc->pc_cpuid, pc);
1169        }
1170}
1171SYSINIT(netisr_start, SI_SUB_SMP, SI_ORDER_MIDDLE, netisr_start, NULL);
1172#endif /* __rtems__ */
1173
1174#ifdef DDB
1175DB_SHOW_COMMAND(netisr, db_show_netisr)
1176{
1177        struct netisr_workstream *nwsp;
1178        struct netisr_work *nwp;
1179        int first, proto;
1180        u_int cpuid;
1181
1182        db_printf("%3s %6s %5s %5s %5s %8s %8s %8s %8s\n", "CPU", "Proto",
1183            "Len", "WMark", "Max", "Disp", "HDisp", "Drop", "Queue");
1184        for (cpuid = 0; cpuid <= mp_maxid; cpuid++) {
1185                if (CPU_ABSENT(cpuid))
1186                        continue;
1187                nwsp = DPCPU_ID_PTR(cpuid, nws);
1188                if (nwsp->nws_intr_event == NULL)
1189                        continue;
1190                first = 1;
1191                for (proto = 0; proto < NETISR_MAXPROT; proto++) {
1192                        if (np[proto].np_handler == NULL)
1193                                continue;
1194                        nwp = &nwsp->nws_work[proto];
1195                        if (first) {
1196                                db_printf("%3d ", cpuid);
1197                                first = 0;
1198                        } else
1199                                db_printf("%3s ", "");
1200                        db_printf(
1201                            "%6s %5d %5d %5d %8ju %8ju %8ju %8ju\n",
1202                            np[proto].np_name, nwp->nw_len,
1203                            nwp->nw_watermark, nwp->nw_qlimit,
1204                            nwp->nw_dispatched, nwp->nw_hybrid_dispatched,
1205                            nwp->nw_qdrops, nwp->nw_queued);
1206                }
1207        }
1208}
1209#endif
Note: See TracBrowser for help on using the repository browser.