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

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

Update files to match FreeBSD layout

Add compatibility with Newlib header files. Some FreeBSD header files
are mapped by the translation script:

o rtems/bsd/sys/_types.h
o rtems/bsd/sys/errno.h
o rtems/bsd/sys/lock.h
o rtems/bsd/sys/param.h
o rtems/bsd/sys/resource.h
o rtems/bsd/sys/time.h
o rtems/bsd/sys/timespec.h
o rtems/bsd/sys/types.h
o rtems/bsd/sys/unistd.h

It is now possible to include <sys/socket.h> directly for example.

Generate one Makefile which builds everything including tests.

  • Property mode set to 100644
File size: 33.6 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/*
264 * Per-CPU workstream data.
265 */
266DPCPU_DEFINE(struct netisr_workstream, nws);
267
268/*
269 * Map contiguous values between 0 and nws_count into CPU IDs appropriate for
270 * accessing workstreams.  This allows constructions of the form
271 * DPCPU_ID_GET(nws_array[arbitraryvalue % nws_count], nws).
272 */
273static u_int                             nws_array[MAXCPU];
274
275/*
276 * Number of registered workstreams.  Will be at most the number of running
277 * CPUs once fully started.
278 */
279static u_int                             nws_count;
280SYSCTL_INT(_net_isr, OID_AUTO, numthreads, CTLFLAG_RD,
281    &nws_count, 0, "Number of extant netisr threads.");
282
283/*
284 * Per-workstream flags.
285 */
286#define NWS_RUNNING     0x00000001      /* Currently running in a thread. */
287#define NWS_DISPATCHING 0x00000002      /* Currently being direct-dispatched. */
288#define NWS_SCHEDULED   0x00000004      /* Signal issued. */
289
290/*
291 * Synchronization for each workstream: a mutex protects all mutable fields
292 * in each stream, including per-protocol state (mbuf queues).  The SWI is
293 * woken up if asynchronous dispatch is required.
294 */
295#define NWS_LOCK(s)             mtx_lock(&(s)->nws_mtx)
296#define NWS_LOCK_ASSERT(s)      mtx_assert(&(s)->nws_mtx, MA_OWNED)
297#define NWS_UNLOCK(s)           mtx_unlock(&(s)->nws_mtx)
298#define NWS_SIGNAL(s)           swi_sched((s)->nws_swi_cookie, 0)
299
300#ifndef __rtems__
301/*
302 * Utility routines for protocols that implement their own mapping of flows
303 * to CPUs.
304 */
305u_int
306netisr_get_cpucount(void)
307{
308
309        return (nws_count);
310}
311
312u_int
313netisr_get_cpuid(u_int cpunumber)
314{
315
316        KASSERT(cpunumber < nws_count, ("%s: %u > %u", __func__, cpunumber,
317            nws_count));
318
319        return (nws_array[cpunumber]);
320}
321#endif  /* __rtems__ */
322
323/*
324 * The default implementation of -> CPU ID mapping.
325 *
326 * Non-static so that protocols can use it to map their own work to specific
327 * CPUs in a manner consistent to netisr for affinity purposes.
328 */
329u_int
330netisr_default_flow2cpu(u_int flowid)
331{
332
333        return (nws_array[flowid % nws_count]);
334}
335
336/*
337 * Register a new netisr handler, which requires initializing per-protocol
338 * fields for each workstream.  All netisr work is briefly suspended while
339 * the protocol is installed.
340 */
341void
342netisr_register(const struct netisr_handler *nhp)
343{
344        struct netisr_work *npwp;
345        const char *name;
346        u_int i, proto;
347
348        proto = nhp->nh_proto;
349        name = nhp->nh_name;
350
351        /*
352         * Test that the requested registration is valid.
353         */
354        KASSERT(nhp->nh_name != NULL,
355            ("%s: nh_name NULL for %u", __func__, proto));
356        KASSERT(nhp->nh_handler != NULL,
357            ("%s: nh_handler NULL for %s", __func__, name));
358        KASSERT(nhp->nh_policy == NETISR_POLICY_SOURCE ||
359            nhp->nh_policy == NETISR_POLICY_FLOW ||
360            nhp->nh_policy == NETISR_POLICY_CPU,
361            ("%s: unsupported nh_policy %u for %s", __func__,
362            nhp->nh_policy, name));
363        KASSERT(nhp->nh_policy == NETISR_POLICY_FLOW ||
364            nhp->nh_m2flow == NULL,
365            ("%s: nh_policy != FLOW but m2flow defined for %s", __func__,
366            name));
367        KASSERT(nhp->nh_policy == NETISR_POLICY_CPU || nhp->nh_m2cpuid == NULL,
368            ("%s: nh_policy != CPU but m2cpuid defined for %s", __func__,
369            name));
370        KASSERT(nhp->nh_policy != NETISR_POLICY_CPU || nhp->nh_m2cpuid != NULL,
371            ("%s: nh_policy == CPU but m2cpuid not defined for %s", __func__,
372            name));
373        KASSERT(proto < NETISR_MAXPROT,
374            ("%s(%u, %s): protocol too big", __func__, proto, name));
375
376        /*
377         * Test that no existing registration exists for this protocol.
378         */
379        NETISR_WLOCK();
380        KASSERT(np[proto].np_name == NULL,
381            ("%s(%u, %s): name present", __func__, proto, name));
382        KASSERT(np[proto].np_handler == NULL,
383            ("%s(%u, %s): handler present", __func__, proto, name));
384
385        np[proto].np_name = name;
386        np[proto].np_handler = nhp->nh_handler;
387        np[proto].np_m2flow = nhp->nh_m2flow;
388        np[proto].np_m2cpuid = nhp->nh_m2cpuid;
389        np[proto].np_drainedcpu = nhp->nh_drainedcpu;
390        if (nhp->nh_qlimit == 0)
391                np[proto].np_qlimit = netisr_defaultqlimit;
392        else if (nhp->nh_qlimit > netisr_maxqlimit) {
393                printf("%s: %s requested queue limit %u capped to "
394                    "net.isr.maxqlimit %u\n", __func__, name, nhp->nh_qlimit,
395                    netisr_maxqlimit);
396                np[proto].np_qlimit = netisr_maxqlimit;
397        } else
398                np[proto].np_qlimit = nhp->nh_qlimit;
399        np[proto].np_policy = nhp->nh_policy;
400        for (i = 0; i <= mp_maxid; i++) {
401                if (CPU_ABSENT(i))
402                        continue;
403                npwp = &(DPCPU_ID_PTR(i, nws))->nws_work[proto];
404                bzero(npwp, sizeof(*npwp));
405                npwp->nw_qlimit = np[proto].np_qlimit;
406        }
407        NETISR_WUNLOCK();
408}
409
410/*
411 * Clear drop counters across all workstreams for a protocol.
412 */
413void
414netisr_clearqdrops(const struct netisr_handler *nhp)
415{
416        struct netisr_work *npwp;
417#ifdef INVARIANTS
418        const char *name;
419#endif
420        u_int i, proto;
421
422        proto = nhp->nh_proto;
423#ifdef INVARIANTS
424        name = nhp->nh_name;
425#endif
426        KASSERT(proto < NETISR_MAXPROT,
427            ("%s(%u): protocol too big for %s", __func__, proto, name));
428
429        NETISR_WLOCK();
430        KASSERT(np[proto].np_handler != NULL,
431            ("%s(%u): protocol not registered for %s", __func__, proto,
432            name));
433
434        for (i = 0; i <= mp_maxid; i++) {
435                if (CPU_ABSENT(i))
436                        continue;
437                npwp = &(DPCPU_ID_PTR(i, nws))->nws_work[proto];
438                npwp->nw_qdrops = 0;
439        }
440        NETISR_WUNLOCK();
441}
442
443/*
444 * Query the current drop counters across all workstreams for a protocol.
445 */
446void
447netisr_getqdrops(const struct netisr_handler *nhp, u_int64_t *qdropp)
448{
449        struct netisr_work *npwp;
450        struct rm_priotracker tracker;
451#ifdef INVARIANTS
452        const char *name;
453#endif
454        u_int i, proto;
455
456        *qdropp = 0;
457        proto = nhp->nh_proto;
458#ifdef INVARIANTS
459        name = nhp->nh_name;
460#endif
461        KASSERT(proto < NETISR_MAXPROT,
462            ("%s(%u): protocol too big for %s", __func__, proto, name));
463
464        NETISR_RLOCK(&tracker);
465        KASSERT(np[proto].np_handler != NULL,
466            ("%s(%u): protocol not registered for %s", __func__, proto,
467            name));
468
469        for (i = 0; i <= mp_maxid; i++) {
470                if (CPU_ABSENT(i))
471                        continue;
472                npwp = &(DPCPU_ID_PTR(i, nws))->nws_work[proto];
473                *qdropp += npwp->nw_qdrops;
474        }
475        NETISR_RUNLOCK(&tracker);
476}
477
478/*
479 * Query the current queue limit for per-workstream queues for a protocol.
480 */
481void
482netisr_getqlimit(const struct netisr_handler *nhp, u_int *qlimitp)
483{
484        struct rm_priotracker tracker;
485#ifdef INVARIANTS
486        const char *name;
487#endif
488        u_int proto;
489
490        proto = nhp->nh_proto;
491#ifdef INVARIANTS
492        name = nhp->nh_name;
493#endif
494        KASSERT(proto < NETISR_MAXPROT,
495            ("%s(%u): protocol too big for %s", __func__, proto, name));
496
497        NETISR_RLOCK(&tracker);
498        KASSERT(np[proto].np_handler != NULL,
499            ("%s(%u): protocol not registered for %s", __func__, proto,
500            name));
501        *qlimitp = np[proto].np_qlimit;
502        NETISR_RUNLOCK(&tracker);
503}
504
505/*
506 * Update the queue limit across per-workstream queues for a protocol.  We
507 * simply change the limits, and don't drain overflowed packets as they will
508 * (hopefully) take care of themselves shortly.
509 */
510int
511netisr_setqlimit(const struct netisr_handler *nhp, u_int qlimit)
512{
513        struct netisr_work *npwp;
514#ifdef INVARIANTS
515        const char *name;
516#endif
517        u_int i, proto;
518
519        if (qlimit > netisr_maxqlimit)
520                return (EINVAL);
521
522        proto = nhp->nh_proto;
523#ifdef INVARIANTS
524        name = nhp->nh_name;
525#endif
526        KASSERT(proto < NETISR_MAXPROT,
527            ("%s(%u): protocol too big for %s", __func__, proto, name));
528
529        NETISR_WLOCK();
530        KASSERT(np[proto].np_handler != NULL,
531            ("%s(%u): protocol not registered for %s", __func__, proto,
532            name));
533
534        np[proto].np_qlimit = qlimit;
535        for (i = 0; i <= mp_maxid; i++) {
536                if (CPU_ABSENT(i))
537                        continue;
538                npwp = &(DPCPU_ID_PTR(i, nws))->nws_work[proto];
539                npwp->nw_qlimit = qlimit;
540        }
541        NETISR_WUNLOCK();
542        return (0);
543}
544
545/*
546 * Drain all packets currently held in a particular protocol work queue.
547 */
548static void
549netisr_drain_proto(struct netisr_work *npwp)
550{
551        struct mbuf *m;
552
553        /*
554         * We would assert the lock on the workstream but it's not passed in.
555         */
556        while ((m = npwp->nw_head) != NULL) {
557                npwp->nw_head = m->m_nextpkt;
558                m->m_nextpkt = NULL;
559                if (npwp->nw_head == NULL)
560                        npwp->nw_tail = NULL;
561                npwp->nw_len--;
562                m_freem(m);
563        }
564        KASSERT(npwp->nw_tail == NULL, ("%s: tail", __func__));
565        KASSERT(npwp->nw_len == 0, ("%s: len", __func__));
566}
567
568/*
569 * Remove the registration of a network protocol, which requires clearing
570 * per-protocol fields across all workstreams, including freeing all mbufs in
571 * the queues at time of unregister.  All work in netisr is briefly suspended
572 * while this takes place.
573 */
574void
575netisr_unregister(const struct netisr_handler *nhp)
576{
577        struct netisr_work *npwp;
578#ifdef INVARIANTS
579        const char *name;
580#endif
581        u_int i, proto;
582
583        proto = nhp->nh_proto;
584#ifdef INVARIANTS
585        name = nhp->nh_name;
586#endif
587        KASSERT(proto < NETISR_MAXPROT,
588            ("%s(%u): protocol too big for %s", __func__, proto, name));
589
590        NETISR_WLOCK();
591        KASSERT(np[proto].np_handler != NULL,
592            ("%s(%u): protocol not registered for %s", __func__, proto,
593            name));
594
595        np[proto].np_name = NULL;
596        np[proto].np_handler = NULL;
597        np[proto].np_m2flow = NULL;
598        np[proto].np_m2cpuid = NULL;
599        np[proto].np_qlimit = 0;
600        np[proto].np_policy = 0;
601        for (i = 0; i <= mp_maxid; i++) {
602                if (CPU_ABSENT(i))
603                        continue;
604                npwp = &(DPCPU_ID_PTR(i, nws))->nws_work[proto];
605                netisr_drain_proto(npwp);
606                bzero(npwp, sizeof(*npwp));
607        }
608        NETISR_WUNLOCK();
609}
610
611/*
612 * Look up the workstream given a packet and source identifier.  Do this by
613 * checking the protocol's policy, and optionally call out to the protocol
614 * for assistance if required.
615 */
616static struct mbuf *
617netisr_select_cpuid(struct netisr_proto *npp, uintptr_t source,
618    struct mbuf *m, u_int *cpuidp)
619{
620        struct ifnet *ifp;
621
622        NETISR_LOCK_ASSERT();
623
624        /*
625         * In the event we have only one worker, shortcut and deliver to it
626         * without further ado.
627         */
628        if (nws_count == 1) {
629                *cpuidp = nws_array[0];
630                return (m);
631        }
632
633        /*
634         * What happens next depends on the policy selected by the protocol.
635         * If we want to support per-interface policies, we should do that
636         * here first.
637         */
638        switch (npp->np_policy) {
639        case NETISR_POLICY_CPU:
640                return (npp->np_m2cpuid(m, source, cpuidp));
641
642        case NETISR_POLICY_FLOW:
643                if (!(m->m_flags & M_FLOWID) && npp->np_m2flow != NULL) {
644                        m = npp->np_m2flow(m, source);
645                        if (m == NULL)
646                                return (NULL);
647                }
648                if (m->m_flags & M_FLOWID) {
649                        *cpuidp =
650                            netisr_default_flow2cpu(m->m_pkthdr.flowid);
651                        return (m);
652                }
653                /* FALLTHROUGH */
654
655        case NETISR_POLICY_SOURCE:
656                ifp = m->m_pkthdr.rcvif;
657                if (ifp != NULL)
658                        *cpuidp = nws_array[(ifp->if_index + source) %
659                            nws_count];
660                else
661                        *cpuidp = nws_array[source % nws_count];
662                return (m);
663
664        default:
665                panic("%s: invalid policy %u for %s", __func__,
666                    npp->np_policy, npp->np_name);
667        }
668}
669
670/*
671 * Process packets associated with a workstream and protocol.  For reasons of
672 * fairness, we process up to one complete netisr queue at a time, moving the
673 * queue to a stack-local queue for processing, but do not loop refreshing
674 * from the global queue.  The caller is responsible for deciding whether to
675 * loop, and for setting the NWS_RUNNING flag.  The passed workstream will be
676 * locked on entry and relocked before return, but will be released while
677 * processing.  The number of packets processed is returned.
678 */
679static u_int
680netisr_process_workstream_proto(struct netisr_workstream *nwsp, u_int proto)
681{
682        struct netisr_work local_npw, *npwp;
683        u_int handled;
684        struct mbuf *m;
685
686        NETISR_LOCK_ASSERT();
687        NWS_LOCK_ASSERT(nwsp);
688
689        KASSERT(nwsp->nws_flags & NWS_RUNNING,
690            ("%s(%u): not running", __func__, proto));
691        KASSERT(proto >= 0 && proto < NETISR_MAXPROT,
692            ("%s(%u): invalid proto\n", __func__, proto));
693
694        npwp = &nwsp->nws_work[proto];
695        if (npwp->nw_len == 0)
696                return (0);
697
698        /*
699         * Move the global work queue to a thread-local work queue.
700         *
701         * Notice that this means the effective maximum length of the queue
702         * is actually twice that of the maximum queue length specified in
703         * the protocol registration call.
704         */
705        handled = npwp->nw_len;
706        local_npw = *npwp;
707        npwp->nw_head = NULL;
708        npwp->nw_tail = NULL;
709        npwp->nw_len = 0;
710        nwsp->nws_pendingbits &= ~(1 << proto);
711        NWS_UNLOCK(nwsp);
712        while ((m = local_npw.nw_head) != NULL) {
713                local_npw.nw_head = m->m_nextpkt;
714                m->m_nextpkt = NULL;
715                if (local_npw.nw_head == NULL)
716                        local_npw.nw_tail = NULL;
717                local_npw.nw_len--;
718                VNET_ASSERT(m->m_pkthdr.rcvif != NULL);
719                CURVNET_SET(m->m_pkthdr.rcvif->if_vnet);
720                np[proto].np_handler(m);
721                CURVNET_RESTORE();
722        }
723        KASSERT(local_npw.nw_len == 0,
724            ("%s(%u): len %u", __func__, proto, local_npw.nw_len));
725        if (np[proto].np_drainedcpu)
726                np[proto].np_drainedcpu(nwsp->nws_cpu);
727        NWS_LOCK(nwsp);
728        npwp->nw_handled += handled;
729        return (handled);
730}
731
732/*
733 * SWI handler for netisr -- processes prackets in a set of workstreams that
734 * it owns, woken up by calls to NWS_SIGNAL().  If this workstream is already
735 * being direct dispatched, go back to sleep and wait for the dispatching
736 * thread to wake us up again.
737 */
738static void
739swi_net(void *arg)
740{
741#ifdef NETISR_LOCKING
742        struct rm_priotracker tracker;
743#endif
744        struct netisr_workstream *nwsp;
745        u_int bits, prot;
746
747        nwsp = arg;
748
749#ifdef DEVICE_POLLING
750        KASSERT(nws_count == 1,
751            ("%s: device_polling but nws_count != 1", __func__));
752        netisr_poll();
753#endif
754#ifdef NETISR_LOCKING
755        NETISR_RLOCK(&tracker);
756#endif
757        NWS_LOCK(nwsp);
758        KASSERT(!(nwsp->nws_flags & NWS_RUNNING), ("swi_net: running"));
759        if (nwsp->nws_flags & NWS_DISPATCHING)
760                goto out;
761        nwsp->nws_flags |= NWS_RUNNING;
762        nwsp->nws_flags &= ~NWS_SCHEDULED;
763        while ((bits = nwsp->nws_pendingbits) != 0) {
764                while ((prot = ffs(bits)) != 0) {
765                        prot--;
766                        bits &= ~(1 << prot);
767                        (void)netisr_process_workstream_proto(nwsp, prot);
768                }
769        }
770        nwsp->nws_flags &= ~NWS_RUNNING;
771out:
772        NWS_UNLOCK(nwsp);
773#ifdef NETISR_LOCKING
774        NETISR_RUNLOCK(&tracker);
775#endif
776#ifdef DEVICE_POLLING
777        netisr_pollmore();
778#endif
779}
780
781static int
782netisr_queue_workstream(struct netisr_workstream *nwsp, u_int proto,
783    struct netisr_work *npwp, struct mbuf *m, int *dosignalp)
784{
785
786        NWS_LOCK_ASSERT(nwsp);
787
788        *dosignalp = 0;
789        if (npwp->nw_len < npwp->nw_qlimit) {
790                m->m_nextpkt = NULL;
791                if (npwp->nw_head == NULL) {
792                        npwp->nw_head = m;
793                        npwp->nw_tail = m;
794                } else {
795                        npwp->nw_tail->m_nextpkt = m;
796                        npwp->nw_tail = m;
797                }
798                npwp->nw_len++;
799                if (npwp->nw_len > npwp->nw_watermark)
800                        npwp->nw_watermark = npwp->nw_len;
801                nwsp->nws_pendingbits |= (1 << proto);
802                if (!(nwsp->nws_flags & 
803                    (NWS_RUNNING | NWS_DISPATCHING | NWS_SCHEDULED))) {
804                        nwsp->nws_flags |= NWS_SCHEDULED;
805                        *dosignalp = 1; /* Defer until unlocked. */
806                }
807                npwp->nw_queued++;
808                return (0);
809        } else {
810                m_freem(m);
811                npwp->nw_qdrops++;
812                return (ENOBUFS);
813        }
814}
815
816static int
817netisr_queue_internal(u_int proto, struct mbuf *m, u_int cpuid)
818{
819        struct netisr_workstream *nwsp;
820        struct netisr_work *npwp;
821        int dosignal, error;
822
823#ifdef NETISR_LOCKING
824        NETISR_LOCK_ASSERT();
825#endif
826        KASSERT(cpuid <= mp_maxid, ("%s: cpuid too big (%u, %u)", __func__,
827            cpuid, mp_maxid));
828        KASSERT(!CPU_ABSENT(cpuid), ("%s: CPU %u absent", __func__, cpuid));
829
830        dosignal = 0;
831        error = 0;
832        nwsp = DPCPU_ID_PTR(cpuid, nws);
833        npwp = &nwsp->nws_work[proto];
834        NWS_LOCK(nwsp);
835        error = netisr_queue_workstream(nwsp, proto, npwp, m, &dosignal);
836        NWS_UNLOCK(nwsp);
837        if (dosignal)
838                NWS_SIGNAL(nwsp);
839        return (error);
840}
841
842int
843netisr_queue_src(u_int proto, uintptr_t source, struct mbuf *m)
844{
845#ifdef NETISR_LOCKING
846        struct rm_priotracker tracker;
847#endif
848        u_int cpuid;
849        int error;
850
851        KASSERT(proto < NETISR_MAXPROT,
852            ("%s: invalid proto %u", __func__, proto));
853
854#ifdef NETISR_LOCKING
855        NETISR_RLOCK(&tracker);
856#endif
857        KASSERT(np[proto].np_handler != NULL,
858            ("%s: invalid proto %u", __func__, proto));
859
860        m = netisr_select_cpuid(&np[proto], source, m, &cpuid);
861        if (m != NULL) {
862                KASSERT(!CPU_ABSENT(cpuid), ("%s: CPU %u absent", __func__,
863                    cpuid));
864                error = netisr_queue_internal(proto, m, cpuid);
865        } else
866                error = ENOBUFS;
867#ifdef NETISR_LOCKING
868        NETISR_RUNLOCK(&tracker);
869#endif
870        return (error);
871}
872
873int
874netisr_queue(u_int proto, struct mbuf *m)
875{
876
877        return (netisr_queue_src(proto, 0, m));
878}
879
880/*
881 * Dispatch a packet for netisr processing, direct dispatch permitted by
882 * calling context.
883 */
884int
885netisr_dispatch_src(u_int proto, uintptr_t source, struct mbuf *m)
886{
887#ifdef NETISR_LOCKING
888        struct rm_priotracker tracker;
889#endif
890        struct netisr_workstream *nwsp;
891        struct netisr_work *npwp;
892        int dosignal, error;
893        u_int cpuid;
894
895        /*
896         * If direct dispatch is entirely disabled, fall back on queueing.
897         */
898        if (!netisr_direct)
899                return (netisr_queue_src(proto, source, m));
900
901        KASSERT(proto < NETISR_MAXPROT,
902            ("%s: invalid proto %u", __func__, proto));
903#ifdef NETISR_LOCKING
904        NETISR_RLOCK(&tracker);
905#endif
906        KASSERT(np[proto].np_handler != NULL,
907            ("%s: invalid proto %u", __func__, proto));
908
909        /*
910         * If direct dispatch is forced, then unconditionally dispatch
911         * without a formal CPU selection.  Borrow the current CPU's stats,
912         * even if there's no worker on it.  In this case we don't update
913         * nws_flags because all netisr processing will be source ordered due
914         * to always being forced to directly dispatch.
915         */
916        if (netisr_direct_force) {
917                nwsp = DPCPU_PTR(nws);
918                npwp = &nwsp->nws_work[proto];
919                npwp->nw_dispatched++;
920                npwp->nw_handled++;
921                np[proto].np_handler(m);
922                error = 0;
923                goto out_unlock;
924        }
925
926        /*
927         * Otherwise, we execute in a hybrid mode where we will try to direct
928         * dispatch if we're on the right CPU and the netisr worker isn't
929         * already running.
930         */
931        m = netisr_select_cpuid(&np[proto], source, m, &cpuid);
932        if (m == NULL) {
933                error = ENOBUFS;
934                goto out_unlock;
935        }
936        KASSERT(!CPU_ABSENT(cpuid), ("%s: CPU %u absent", __func__, cpuid));
937#ifndef __rtems__
938        sched_pin();
939#endif  /* __rtems__ */
940        if (cpuid != curcpu)
941                goto queue_fallback;
942        nwsp = DPCPU_PTR(nws);
943        npwp = &nwsp->nws_work[proto];
944
945        /*-
946         * We are willing to direct dispatch only if three conditions hold:
947         *
948         * (1) The netisr worker isn't already running,
949         * (2) Another thread isn't already directly dispatching, and
950         * (3) The netisr hasn't already been woken up.
951         */
952        NWS_LOCK(nwsp);
953        if (nwsp->nws_flags & (NWS_RUNNING | NWS_DISPATCHING | NWS_SCHEDULED)) {
954                error = netisr_queue_workstream(nwsp, proto, npwp, m,
955                    &dosignal);
956                NWS_UNLOCK(nwsp);
957                if (dosignal)
958                        NWS_SIGNAL(nwsp);
959                goto out_unpin;
960        }
961
962        /*
963         * The current thread is now effectively the netisr worker, so set
964         * the dispatching flag to prevent concurrent processing of the
965         * stream from another thread (even the netisr worker), which could
966         * otherwise lead to effective misordering of the stream.
967         */
968        nwsp->nws_flags |= NWS_DISPATCHING;
969        NWS_UNLOCK(nwsp);
970        np[proto].np_handler(m);
971        NWS_LOCK(nwsp);
972        nwsp->nws_flags &= ~NWS_DISPATCHING;
973        npwp->nw_handled++;
974        npwp->nw_hybrid_dispatched++;
975
976        /*
977         * If other work was enqueued by another thread while we were direct
978         * dispatching, we need to signal the netisr worker to do that work.
979         * In the future, we might want to do some of that work in the
980         * current thread, rather than trigger further context switches.  If
981         * so, we'll want to establish a reasonable bound on the work done in
982         * the "borrowed" context.
983         */
984        if (nwsp->nws_pendingbits != 0) {
985                nwsp->nws_flags |= NWS_SCHEDULED;
986                dosignal = 1;
987        } else
988                dosignal = 0;
989        NWS_UNLOCK(nwsp);
990        if (dosignal)
991                NWS_SIGNAL(nwsp);
992        error = 0;
993        goto out_unpin;
994
995queue_fallback:
996        error = netisr_queue_internal(proto, m, cpuid);
997out_unpin:
998#ifndef __rtems__
999        sched_unpin();
1000#endif  /* __rtems__ */
1001out_unlock:
1002#ifdef NETISR_LOCKING
1003        NETISR_RUNLOCK(&tracker);
1004#endif
1005        return (error);
1006}
1007
1008int
1009netisr_dispatch(u_int proto, struct mbuf *m)
1010{
1011
1012        return (netisr_dispatch_src(proto, 0, m));
1013}
1014
1015#ifdef DEVICE_POLLING
1016/*
1017 * Kernel polling borrows a netisr thread to run interface polling in; this
1018 * function allows kernel polling to request that the netisr thread be
1019 * scheduled even if no packets are pending for protocols.
1020 */
1021void
1022netisr_sched_poll(void)
1023{
1024        struct netisr_workstream *nwsp;
1025
1026        nwsp = DPCPU_ID_PTR(nws_array[0], nws);
1027        NWS_SIGNAL(nwsp);
1028}
1029#endif
1030
1031static void
1032netisr_start_swi(u_int cpuid, struct pcpu *pc)
1033{
1034        char swiname[12];
1035        struct netisr_workstream *nwsp;
1036        int error;
1037
1038        KASSERT(!CPU_ABSENT(cpuid), ("%s: CPU %u absent", __func__, cpuid));
1039
1040        nwsp = DPCPU_ID_PTR(cpuid, nws);
1041        mtx_init(&nwsp->nws_mtx, "netisr_mtx", NULL, MTX_DEF);
1042        nwsp->nws_cpu = cpuid;
1043        snprintf(swiname, sizeof(swiname), "netisr %u", cpuid);
1044        error = swi_add(&nwsp->nws_intr_event, swiname, swi_net, nwsp,
1045            SWI_NET, INTR_MPSAFE, &nwsp->nws_swi_cookie);
1046        if (error)
1047                panic("%s: swi_add %d", __func__, error);
1048#ifndef __rtems__
1049        pc->pc_netisr = nwsp->nws_intr_event;
1050        if (netisr_bindthreads) {
1051                error = intr_event_bind(nwsp->nws_intr_event, cpuid);
1052                if (error != 0)
1053                        printf("%s: cpu %u: intr_event_bind: %d", __func__,
1054                            cpuid, error);
1055        }
1056#endif
1057        NETISR_WLOCK();
1058        nws_array[nws_count] = nwsp->nws_cpu;
1059        nws_count++;
1060        NETISR_WUNLOCK();
1061}
1062
1063/*
1064 * Initialize the netisr subsystem.  We rely on BSS and static initialization
1065 * of most fields in global data structures.
1066 *
1067 * Start a worker thread for the boot CPU so that we can support network
1068 * traffic immediately in case the network stack is used before additional
1069 * CPUs are started (for example, diskless boot).
1070 */
1071static void
1072netisr_init(void *arg)
1073{
1074
1075        KASSERT(curcpu == 0, ("%s: not on CPU 0", __func__));
1076
1077        NETISR_LOCK_INIT();
1078        if (netisr_maxthreads < 1)
1079                netisr_maxthreads = 1;
1080        if (netisr_maxthreads > mp_ncpus) {
1081                printf("netisr_init: forcing maxthreads from %d to %d\n",
1082                    netisr_maxthreads, mp_ncpus);
1083                netisr_maxthreads = mp_ncpus;
1084        }
1085        if (netisr_defaultqlimit > netisr_maxqlimit) {
1086                printf("netisr_init: forcing defaultqlimit from %d to %d\n",
1087                    netisr_defaultqlimit, netisr_maxqlimit);
1088                netisr_defaultqlimit = netisr_maxqlimit;
1089        }
1090#ifdef DEVICE_POLLING
1091        /*
1092         * The device polling code is not yet aware of how to deal with
1093         * multiple netisr threads, so for the time being compiling in device
1094         * polling disables parallel netisr workers.
1095         */
1096        if (netisr_maxthreads != 1 || netisr_bindthreads != 0) {
1097                printf("netisr_init: forcing maxthreads to 1 and "
1098                    "bindthreads to 0 for device polling\n");
1099                netisr_maxthreads = 1;
1100                netisr_bindthreads = 0;
1101        }
1102#endif
1103
1104#ifndef __rtems__
1105        netisr_start_swi(curcpu, pcpu_find(curcpu));
1106#else /* __rtems__ */
1107        netisr_start_swi(0, NULL);
1108#endif /* __rtems__ */
1109}
1110SYSINIT(netisr_init, SI_SUB_SOFTINTR, SI_ORDER_FIRST, netisr_init, NULL);
1111
1112#ifndef __rtems__
1113/*
1114 * Start worker threads for additional CPUs.  No attempt to gracefully handle
1115 * work reassignment, we don't yet support dynamic reconfiguration.
1116 */
1117static void
1118netisr_start(void *arg)
1119{
1120        struct pcpu *pc;
1121
1122        SLIST_FOREACH(pc, &cpuhead, pc_allcpu) {
1123                if (nws_count >= netisr_maxthreads)
1124                        break;
1125                /* XXXRW: Is skipping absent CPUs still required here? */
1126                if (CPU_ABSENT(pc->pc_cpuid))
1127                        continue;
1128                /* Worker will already be present for boot CPU. */
1129                if (pc->pc_netisr != NULL)
1130                        continue;
1131                netisr_start_swi(pc->pc_cpuid, pc);
1132        }
1133}
1134SYSINIT(netisr_start, SI_SUB_SMP, SI_ORDER_MIDDLE, netisr_start, NULL);
1135#endif /* __rtems__ */
1136
1137#ifdef DDB
1138DB_SHOW_COMMAND(netisr, db_show_netisr)
1139{
1140        struct netisr_workstream *nwsp;
1141        struct netisr_work *nwp;
1142        int first, proto;
1143        u_int cpuid;
1144
1145        db_printf("%3s %6s %5s %5s %5s %8s %8s %8s %8s\n", "CPU", "Proto",
1146            "Len", "WMark", "Max", "Disp", "HDisp", "Drop", "Queue");
1147        for (cpuid = 0; cpuid <= mp_maxid; cpuid++) {
1148                if (CPU_ABSENT(cpuid))
1149                        continue;
1150                nwsp = DPCPU_ID_PTR(cpuid, nws);
1151                if (nwsp->nws_intr_event == NULL)
1152                        continue;
1153                first = 1;
1154                for (proto = 0; proto < NETISR_MAXPROT; proto++) {
1155                        if (np[proto].np_handler == NULL)
1156                                continue;
1157                        nwp = &nwsp->nws_work[proto];
1158                        if (first) {
1159                                db_printf("%3d ", cpuid);
1160                                first = 0;
1161                        } else
1162                                db_printf("%3s ", "");
1163                        db_printf(
1164                            "%6s %5d %5d %5d %8ju %8ju %8ju %8ju\n",
1165                            np[proto].np_name, nwp->nw_len,
1166                            nwp->nw_watermark, nwp->nw_qlimit,
1167                            nwp->nw_dispatched, nwp->nw_hybrid_dispatched,
1168                            nwp->nw_qdrops, nwp->nw_queued);
1169                }
1170        }
1171}
1172#endif
Note: See TracBrowser for help on using the repository browser.