Skip to contentSkip to conversation

Restartable sequences system call

RFC PATCH In review Mathieu Desnoyers 9 participants 26 messages Aug 19, 2016 – Aug 30, 2016

Subsystems (12)
Arm (32-bit) x86 VFS PowerPC +8 more subsystems
lore
Share & tools
lore

Mathieu Desnoyers

author maintainer
#0 lore raw

v8 cover Restartable sequences system call

Hi,

Here is v8 of the restartable sequences system call patchset, after taking care of feedback received from Peter Zijlstra, Andy Lutomirski, Boqun Feng, and Dave Watson. Added PowerPC architecture support provided by Boqun Feng. It is based on Linux kernel v4.8-rc2.

The small library provided in kernel selftests now allows to perform either a single final commit (do_rseq()), a speculative store before the final commit (do_rseq2()), or a speculative memcpy before the final commit (do_rseq_memcpy()).

Feedback is welcome!

Thanks,

Mathieu

Boqun Feng (2):
Restartable sequences: powerpc architecture support Restartable sequences: Wire up powerpc system call

Mathieu Desnoyers (7):
Restartable sequences system call
tracing: instrument restartable sequences Restartable sequences: ARM 32 architecture support Restartable sequences: wire up ARM 32 system call Restartable sequences: x86 32/64 architecture support Restartable sequences: wire up x86 32/64 system call Restartable sequences: self-tests

 MAINTAINERS                                        |   11 +
 arch/Kconfig                                       |    7 +
 arch/arm/Kconfig                                   |    1 +
 arch/arm/include/uapi/asm/unistd.h                 |    1 +
 arch/arm/kernel/calls.S                            |    1 +
 arch/arm/kernel/signal.c                           |    7 +
 arch/powerpc/Kconfig                               |    1 +
 arch/powerpc/include/asm/systbl.h                  |    1 +
 arch/powerpc/include/asm/unistd.h                  |    2 +-
 arch/powerpc/include/uapi/asm/unistd.h             |    1 +
 arch/powerpc/kernel/signal.c                       |    3 +
 arch/x86/Kconfig                                   |    1 +
 arch/x86/entry/common.c                            |    1 +
 arch/x86/entry/syscalls/syscall_32.tbl             |    1 +
 arch/x86/entry/syscalls/syscall_64.tbl             |    1 +
 arch/x86/kernel/signal.c                           |    6 +
 fs/exec.c                                          |    1 +
 include/linux/sched.h                              |   72 ++
 include/trace/events/rseq.h                        |   64 ++
 include/uapi/linux/Kbuild                          |    1 +
 include/uapi/linux/rseq.h                          |  106 ++
 init/Kconfig                                       |   13 +
 kernel/Makefile                                    |    1 +
 kernel/fork.c                                      |    2 +
 kernel/rseq.c                                      |  296 ++++++
 kernel/sched/core.c                                |    1 +
 kernel/sys_ni.c                                    |    3 +
 tools/testing/selftests/rseq/.gitignore            |    3 +
 tools/testing/selftests/rseq/Makefile              |   13 +
 .../testing/selftests/rseq/basic_percpu_ops_test.c |  286 +++++
 tools/testing/selftests/rseq/basic_test.c          |  107 ++
 tools/testing/selftests/rseq/param_test.c          | 1116 ++++++++++++++++++++
 tools/testing/selftests/rseq/rseq-arm.h            |  168 +++
 tools/testing/selftests/rseq/rseq-ppc.h            |  273 +++++
 tools/testing/selftests/rseq/rseq-x86.h            |  306 ++++++
 tools/testing/selftests/rseq/rseq.c                |  231 ++++
 tools/testing/selftests/rseq/rseq.h                |  454 ++++++++
 37 files changed, 3562 insertions(+), 1 deletion(-)
 create mode 100644 include/trace/events/rseq.h
 create mode 100644 include/uapi/linux/rseq.h
 create mode 100644 kernel/rseq.c
 create mode 100644 tools/testing/selftests/rseq/.gitignore
 create mode 100644 tools/testing/selftests/rseq/Makefile
 create mode 100644 tools/testing/selftests/rseq/basic_percpu_ops_test.c
 create mode 100644 tools/testing/selftests/rseq/basic_test.c
 create mode 100644 tools/testing/selftests/rseq/param_test.c
 create mode 100644 tools/testing/selftests/rseq/rseq-arm.h
 create mode 100644 tools/testing/selftests/rseq/rseq-ppc.h
 create mode 100644 tools/testing/selftests/rseq/rseq-x86.h
 create mode 100644 tools/testing/selftests/rseq/rseq.c
 create mode 100644 tools/testing/selftests/rseq/rseq.h
Signature · 1 line
2.1.4
author maintainer
#1 lore raw

RFC PATCH v8 1/9 Restartable sequences system call

Expose a new system call allowing each thread to register one userspace memory area to be used as an ABI between kernel and user-space for two
purposes: user-space restartable sequences and quick access to read the current CPU number value from user-space.

* Restartable sequences (per-cpu atomics)

Restartables sequences allow user-space to perform update operations on per-cpu data without requiring heavy-weight atomic operations.

The restartable critical sections (percpu atomics) work has been started by Paul Turner and Andrew Hunter. It lets the kernel handle restart of critical sections. [1] [2] The re-implementation proposed here brings a few simplifications to the ABI which facilitates porting to other architectures and speeds up the user-space fast path. A locking-based fall-back, purely implemented in user-space, is proposed here to deal with debugger single-stepping. This fallback interacts with rseq_start() and rseq_finish(), which force retries in response to concurrent lock-based activity.

Here are benchmarks of counter increment in various scenarios compared to restartable sequences:

ARMv7 Processor rev 4 (v7l)
Machine model: Cubietruck

Counter increment speed (ns/increment)
1 thread 2 threads
global increment (baseline) 6 N/A

percpu rseq increment           50            52
percpu rseq spinlock            94            94
global atomic increment         48            74 (__sync_add_and_fetch_4)
global atomic CAS               50           172 (__sync_val_compare_and_swap_4)

global pthread mutex 148 862

ARMv7 Processor rev 10 (v7l)
Machine model: Wandboard

Counter increment speed (ns/increment)
1 thread 4 threads
global increment (baseline) 7 N/A

percpu rseq increment           50            50
percpu rseq spinlock            82            84
global atomic increment         44           262 (__sync_add_and_fetch_4)
global atomic CAS               46           316 (__sync_val_compare_and_swap_4)

global pthread mutex 146 1400

x86-64 Intel(R) Xeon(R) CPU E5-2630 v3 @ 2.40GHz:

Counter increment speed (ns/increment)
1 thread 8 threads

global increment (baseline)      3.0                N/A
percpu rseq increment            3.6                3.8
percpu rseq spinlock             5.6                6.2
global LOCK; inc                 8.0              166.4

global LOCK; cmpxchg 13.4 435.2
global pthread mutex 25.2 1363.6

* Reading the current CPU number

Speeding up reading the current CPU number on which the caller thread is running is done by keeping the current CPU number up do date within the cpu_id field of the memory area registered by the thread. This is done by making scheduler preemption set the TIF_NOTIFY_RESUME flag on the current thread. Upon return to user-space, a notify-resume handler updates the current CPU value within the registered user-space memory area. User-space can then read the current CPU number directly from memory.

Keeping the current cpu id in a memory area shared between kernel and user-space is an improvement over current mechanisms available to read the current CPU number, which has the following benefits over alternative approaches:

- 35x speedup on ARM vs system call through glibc
- 20x speedup on x86 compared to calling glibc, which calls vdso executing a "lsl" instruction,
- 14x speedup on x86 compared to inlined "lsl" instruction,
- Unlike vdso approaches, this cpu_id value can be read from an inline assembly, which makes it a useful building block for restartable sequences.
- The approach of reading the cpu id through memory mapping shared between kernel and user-space is portable (e.g. ARM), which is not the case for the lsl-based x86 vdso.

On x86, yet another possible approach would be to use the gs segment selector to point to user-space per-cpu data. This approach performs similarly to the cpu id cache, but it has two disadvantages: it is not portable, and it is incompatible with existing applications already using the gs segment selector for other purposes.

Benchmarking various approaches for reading the current CPU number:

ARMv7 Processor rev 4 (v7l)
Machine model: Cubietruck
- Baseline (empty loop): 8.4 ns
- Read CPU from rseq cpu_id: 16.7 ns
- Read CPU from rseq cpu_id (lazy register): 19.8 ns
- glibc 2.19-0ubuntu6.6 getcpu: 301.8 ns
- getcpu system call: 234.9 ns

x86-64 Intel(R) Xeon(R) CPU E5-2630 v3 @ 2.40GHz:

- Baseline (empty loop):                                    0.8 ns
- Read CPU from rseq cpu_id:                                0.8 ns
- Read CPU from rseq cpu_id (lazy register):                0.8 ns
- Read using gs segment selector:                           0.8 ns
- "lsl" inline assembly:                                   13.0 ns
- glibc 2.19-0ubuntu6 getcpu:                              16.6 ns
- getcpu system call:                                      53.9 ns

- Speed

Running 10 runs of hackbench -l 100000 seems to indicate, contrary to expectations, that enabling CONFIG_RSEQ slightly accelerates the scheduler:

Configuration: 2 sockets * 8-core Intel(R) Xeon(R) CPU E5-2630 v3 @ 2.40GHz (directly on hardware, hyperthreading disabled in BIOS, energy saving disabled in BIOS, turboboost disabled in BIOS, cpuidle.off=1 kernel parameter), with a Linux v4.6 defconfig+localyesconfig, restartable sequences series applied.

* CONFIG_RSEQ=n

avg.:      41.37 s
std.dev.:   0.36 s

* CONFIG_RSEQ=y

avg.:      40.46 s
std.dev.:   0.33 s

- Size

On x86-64, between CONFIG_RSEQ=n/y, the text size increase of vmlinux is 2855 bytes, and the data size increase of vmlinux is 1024 bytes.

* CONFIG_RSEQ=n

text data bss dec hex filename
9964559 4256280 962560 15183399 e7ae27 vmlinux.norseq

* CONFIG_RSEQ=y

text data bss dec hex filename
9967414 4257304 962560 15187278 e7bd4e vmlinux.rseq

[1] https://lwn.net/Articles/650333/
[2] http://www.linuxplumbersconf.org/2013/ocw/system/presentations/1695/original/LPC%20-%20PerCpu%20Atomics.pdf

CC Thomas Gleixner <[email protected]>
CC Paul Turner <[email protected]>
CC Andrew Hunter <[email protected]>
CC Peter Zijlstra <[email protected]>
CC Andy Lutomirski <[email protected]>
CC Andi Kleen <andi-Vw/[email protected]>
CC Dave Watson <[email protected]>
CC Chris Lameter <[email protected]>
CC Ingo Molnar <[email protected]>
CC "H. Peter Anvin" <[email protected]>
CC Ben Maurer <[email protected]>
CC Steven Rostedt <[email protected]>
CC "Paul E. McKenney" <[email protected]>
CC Josh Triplett <[email protected]>
CC Linus Torvalds <torvalds-de/[email protected]>
CC Andrew Morton <akpm-de/[email protected]>
CC Russell King <linux-lFZ/[email protected]>
CC Catalin Marinas <[email protected]>
CC Will Deacon <[email protected]>
CC Michael Kerrisk <[email protected]>
CC Boqun Feng <[email protected]>

---

Changes since v1:
- Return -1, errno=EINVAL if cpu_cache pointer is not aligned on sizeof(int32_t).
- Update man page to describe the pointer alignement requirements and update atomicity guarantees.
- Add MAINTAINERS file GETCPU_CACHE entry.
- Remove dynamic memory allocation: go back to having a single getcpu_cache entry per thread. Update documentation accordingly.
- Rebased on Linux 4.4.

Changes since v2:
- Introduce a "cmd" argument, along with an enum with GETCPU_CACHE_GET and GETCPU_CACHE_SET. Introduce a uapi header linux/getcpu_cache.h defining this enumeration.
- Split resume notifier architecture implementation from the system call wire up in the following arch-specific patches.
- Man pages updates.
- Handle 32-bit compat pointers.
- Simplify handling of getcpu_cache GETCPU_CACHE_SET compiler barrier:
set the current cpu cache pointer before doing the cache update, and set it back to NULL if the update fails. Setting it back to NULL on error ensures that no resume notifier will trigger a SIGSEGV if a migration happened concurrently.

Changes since v3:
- Fix __user annotations in compat code,
- Update memory ordering comments.
- Rebased on kernel v4.5-rc5.

Changes since v4:
- Inline getcpu_cache_fork, getcpu_cache_execve, and getcpu_cache_exit.
- Add new line between if() and switch() to improve readability.
- Added sched switch benchmarks (hackbench) and size overhead comparison to change log.

Changes since v5:
- Rename "getcpu_cache" to "thread_local_abi", allowing to extend this system call to cover future features such as restartable critical sections. Generalizing this system call ensures that we can add features similar to the cpu_id field within the same cache-line without having to track one pointer per feature within the task struct.
- Add a tlabi_nr parameter to the system call, thus allowing to extend the ABI beyond the initial 64-byte structure by registering structures with tlabi_nr greater than 0. The initial ABI structure is associated with tlabi_nr 0.
- Rebased on kernel v4.5.

Changes since v6:
- Integrate "restartable sequences" v2 patchset from Paul Turner.
- Add handling of single-stepping purely in user-space, with a fallback to locking after 2 rseq failures to ensure progress, and by exposing a __rseq_table section to debuggers so they know where to put breakpoints when dealing with rseq assembly blocks which can be aborted at any point.
- make the code and ABI generic: porting the kernel implementation simply requires to wire up the signal handler and return to user-space hooks, and allocate the syscall number.
- extend testing with a fully configurable test program. See param_spinlock_test -h for details.
- handling of rseq ENOSYS in user-space, also with a fallback to locking.
- modify Paul Turner's rseq ABI to only require a single TLS store on the user-space fast-path, removing the need to populate two additional registers. This is made possible by introducing struct rseq_cs into the ABI to describe a critical section start_ip, post_commit_ip, and abort_ip.
- Rebased on kernel v4.7-rc7.

Changes since v7:
- Documentation updates.
- Integrated powerpc architecture support.
- Compare rseq critical section start_ip, allows shriking the user-space fast-path code size.
- Added Peter Zijlstra, Paul E. McKenney and Boqun Feng as co-maintainers.
- Added do_rseq2 and do_rseq_memcpy to test program helper library.
- Code cleanup based on review from Peter Zijlstra, Andy Lutomirski and Boqun Feng.
- Rebase on kernel v4.8-rc2.

Man page associated:

RSEQ(2) Linux Programmer's Manual RSEQ(2)

NAME
rseq - Restartable sequences and cpu number cache

SYNOPSIS

       #include <linux/rseq.h>

       int rseq(struct rseq * rseq, int flags);

DESCRIPTION
The rseq() ABI accelerates user-space operations on per-cpu data by defining a shared data structure ABI between each user-space thread and the kernel.

It allows user-space to perform update operations on per-cpu data without requiring heavy-weight atomic operations.

Restartable sequences are atomic with respect to preemption (mak‐ ing it atomic with respect to other threads running on the same CPU), as well as signal delivery (user-space execution contexts nested over the same thread).

It is suited for update operations on per-cpu data.

It can be used on data structures shared between threads within a process, and on data structures shared between threads across dif‐ ferent processes.

Some examples of operations that can be accelerated by this ABI:

· Querying the current CPU number,

· Incrementing per-CPU counters,

· Modifying data protected by per-CPU spinlocks,

· Inserting/removing elements in per-CPU linked-lists,

· Writing/reading per-CPU ring buffers content.

The rseq argument is a pointer to the thread-local rseq structure to be shared between kernel and user-space. A NULL rseq value unregisters the current thread rseq structure.

The layout of struct rseq is as follows:

Structure alignment
This structure is aligned on multiples of 128 bytes.

Structure size
This structure has a fixed size of 128 bytes.

Fields

cpu_id
Cache of the CPU number on which the current thread is run‐ ning.

event_counter
Counter guaranteed to be incremented when the current thread is preempted or when a signal is delivered to the current thread.

rseq_cs
The rseq_cs field is a pointer to a struct rseq_cs. Is is NULL when no rseq assembly block critical section is active for the current thread. Setting it to point to a critical section descriptor (struct rseq_cs) marks the beginning of the critical section. It is cleared after the end of the critical section.

The layout of struct rseq_cs is as follows:

Structure alignment
This structure is aligned on multiples of 256 bytes.

Structure size
This structure has a fixed size of 256 bytes.

Fields

start_ip
Instruction pointer address of the first instruction of the sequence of consecutive assembly instructions.

post_commit_ip
Instruction pointer address after the last instruction of the sequence of consecutive assembly instructions.

abort_ip
Instruction pointer address where to move the execution flow in case of abort of the sequence of consecutive assem‐ bly instructions.

Upon registration, the flags argument is currently unused and must be specified as 0. Upon unregistration, the flags argument can be either specified as 0, or as RSEQ_FORCE_UNREGISTER, which will force unregistration of the current rseq address rather than requiring each registration to be matched by an unregistration.

Libraries and applications should keep the rseq structure in a thread-local storage variable. Since only one rseq address can be registered per thread, applications and libraries should define their struct rseq as a volatile thread-local storage variable with the weak symbol __rseq_abi. This allows using rseq from an appli‐ cation executable and from multiple shared libraries linked to the same executable. The cpu_id field should be initialized to -1.

Each thread is responsible for registering and unregistering its rseq structure. No more than one rseq structure address can be registered per thread at a given time. The same address can be registered more than once for a thread, and each registration needs to have a matching unregistration before the address is effectively unregistered. After the rseq address is effectively unregistered for a thread, a new address can be registered. Unreg‐ istration of associated rseq structure is implicitly performed when a thread or process exits.

In a typical usage scenario, the thread registering the rseq structure will be performing loads and stores from/to that struc‐ ture. It is however also allowed to read that structure from other threads. The rseq field updates performed by the kernel provide relaxed atomicity semantics, which guarantee that other threads performing relaxed atomic reads of the cpu number cache will always observe a consistent value.

RETURN VALUE
A return value of 0 indicates success. On error, -1 is returned, and errno is set appropriately.

ERRORS
EINVAL Either flags contains an invalid value, or rseq contains an
address which is not appropriately aligned.

ENOSYS The rseq() system call is not implemented by this kernel.

EFAULT rseq is an invalid address.

EBUSY The rseq argument contains a non-NULL address which differs
from the memory location already registered for this thread.

EOVERFLOW
Registering the rseq address is not allowed because it would cause a reference counter overflow.

ENOENT The rseq argument is NULL, but no memory location is cur‐
rently registered for this thread.

VERSIONS
The rseq() system call was added in Linux 4.X (TODO).

CONFORMING TO
rseq() is Linux-specific.

ALGORITHM
The restartable sequences mechanism is the overlap of two distinct restart mechanisms: a sequence counter tracking preemption and signal delivery for high-level code, and an ip-fixup-based mecha‐ nism for the final assembly instruction sequence.

A high-level summary of the algorithm to use rseq from user-space is as follows:

The high-level code between rseq_start() and rseq_finish() loads the current value of the sequence counter in rseq_start(), and then it gets compared with the new current value within the
rseq_finish() restartable instruction sequence. Between
rseq_start() and rseq_finish(), the high-level code can perform operations that do not have side-effects, such as getting the cur‐ rent CPU number, and loading from variables.

Stores are performed at the very end of the restartable sequence assembly block. Each assembly block defines a struct rseq_cs
structure which describes the start_ip and post_commit_ip
addresses, as well as the abort_ip address where the kernel should move the thread instruction pointer if a rseq critical section assembly block is preempted or if a signal is delivered on top of a rseq critical section assembly block.

Detailed algorithm of rseq use:

rseq_start()

0. Userspace loads the current event counter value from the event_counter field of the registered struct rseq TLS area,

rseq_finish()

Steps [1]-[3] (inclusive) need to be a sequence of instruc‐ tions in userspace that can handle being moved to the abort_ip between any of those instructions.

The abort_ip address needs to be less than start_ip, or
greater-or-equal the post_commit_ip. Step [4] and the
failure code step [F1] need to be at addresses lesser than start_ip, or greater-or-equal the post_commit_ip.

[ start_ip ]

1. Userspace stores the address of the struct rseq_cs assembly block descriptor into the rseq_cs field of the registered struct rseq TLS area.

2. Userspace tests to see whether the current event_counter value match the value loaded at [0]. Manually jumping to [F1] in case of a mismatch.

Note that if we are preempted or interrupted by a signal after [1] and before post_commit_ip, then the kernel also performs the comparison performed in [2], and conditionally clears the rseq_cs field of struct rseq, then jumps us to abort_ip.

3. Userspace critical section final instruction before
post_commit_ip is the commit. The critical section is self- terminating.

[ post_commit_ip ]

4. Userspace clears the rseq_cs field of the struct rseq TLS area.

5. Return true.

On failure at [2]:

F1.
Userspace clears the rseq_cs field of the struct rseq TLS area. Followed by step [F2].

[ abort_ip ]

F2.
Return false.

EXAMPLE

       The following code uses the rseq() system call to keep a thread-local
       storage variable up to date with the current CPU number, with a fall‐
       back on sched_getcpu(3) if the cache is not  available.  For  example
       simplicity,  it  is  done in main(), but multithreaded programs would
       need to invoke rseq() from each program thread.

           #define _GNU_SOURCE
           #include <stdlib.h>
           #include <stdio.h>
           #include <unistd.h>
           #include <stdint.h>
           #include <sched.h>
           #include <stddef.h>
           #include <errno.h>
           #include <string.h>
           #include <stdbool.h>
           #include <sys/syscall.h>
           #include <linux/rseq.h>

           __attribute__((weak)) __thread volatile struct rseq __rseq_abi = {
               .u.e.cpu_id = -1,
           };

           static int
           sys_rseq(volatile struct rseq *rseq_abi, int flags)
           {
               return syscall(__NR_rseq, rseq_abi, flags);
           }

           static int32_t
           rseq_current_cpu_raw(void)
           {
               return __rseq_abi.u.e.cpu_id;
           }

           static int32_t
           rseq_current_cpu(void)
           {
               int32_t cpu;

               cpu = rseq_current_cpu_raw();
               if (cpu < 0)
                   cpu = sched_getcpu();
               return cpu;
           }

           static int
           rseq_register_current_thread(void)
           {
               int rc;

               rc = sys_rseq(&__rseq_abi, 0);
               if (rc) {
                   fprintf(stderr,
                       "Error: sys_rseq(...) register failed(%d): %s\n",
                       errno, strerror(errno));
                   return -1;
               }
               return 0;
           }

           static int
           rseq_unregister_current_thread(void)
           {
               int rc;

               rc = sys_rseq(NULL, 0);
               if (rc) {
                   fprintf(stderr,
                       "Error: sys_rseq(...) unregister failed(%d): %s\n",
                       errno, strerror(errno));
                   return -1;
               }
               return 0;
           }

           int
           main(int argc, char **argv)
           {
               bool rseq_registered = false;

               if (!rseq_register_current_thread()) {
                   rseq_registered = true;
               } else {
                   fprintf(stderr,
                       "Unable to register restartable sequences.\n");
                   fprintf(stderr, "Using sched_getcpu() as fallback.\n");
               }

               printf("Current CPU number: %d\n", rseq_current_cpu());

               if (rseq_registered && rseq_unregister_current_thread()) {
                   exit(EXIT_FAILURE);
               }
               exit(EXIT_SUCCESS);
           }

SEE ALSO

       sched_getcpu(3)

Linux 2016-08-19 RSEQ(2)

---
 MAINTAINERS               |  10 ++
 arch/Kconfig              |   7 ++
 fs/exec.c                 |   1 +
 include/linux/sched.h     |  72 ++++++++++++
 include/uapi/linux/Kbuild |   1 +
 include/uapi/linux/rseq.h | 106 +++++++++++++++++
 init/Kconfig              |  13 +++
 kernel/Makefile           |   1 +
 kernel/fork.c             |   2 +
 kernel/rseq.c             | 287 ++++++++++++++++++++++++++++++++++++++++++++++
 kernel/sched/core.c       |   1 +
 kernel/sys_ni.c           |   3 +
 12 files changed, 504 insertions(+)
 create mode 100644 include/uapi/linux/rseq.h
 create mode 100644 kernel/rseq.c
MAINTAINERS +10 -0
index a306795..5028f03 100644
@@ -5204,6 +5204,16 @@ M:	Joe Perches <[email protected]>
 S:	Maintained
 F:	scripts/get_maintainer.pl
 
+RESTARTABLE SEQUENCES SUPPORT
+M:	Mathieu Desnoyers <mathieu.desnoyers-vg+e7yoeK/dWk0Htik3J/[email protected]>
+M:	Peter Zijlstra <[email protected]>
+M:	"Paul E. McKenney" <[email protected]>
+M:	Boqun Feng <[email protected]>
+L:	[email protected]
+S:	Supported
+F:	kernel/rseq.c
+F:	include/uapi/linux/rseq.h
+
 GFS2 FILE SYSTEM
 M:	Steven Whitehouse <[email protected]>
 M:	Bob Peterson <[email protected]>
arch/Kconfig +7 -0
index e9c9334..28c4fda 100644
@@ -242,6 +242,13 @@ config HAVE_REGS_AND_STACK_ACCESS_API
 	  declared in asm/ptrace.h
 	  For example the kprobes-based event tracer needs this API.
 
+config HAVE_RSEQ
+	bool
+	depends on HAVE_REGS_AND_STACK_ACCESS_API
+	help
+	  This symbol should be selected by an architecture if it
+	  supports an implementation of restartable sequences.
+
 config HAVE_CLK
 	bool
 	help
fs/exec.c +1 -0
index 6fcfb3f..5a0a5d7 100644
@@ -1743,6 +1743,7 @@ static int do_execveat_common(int fd, struct filename *filename,
 	/* execve succeeded */
 	current->fs->in_exec = 0;
 	current->in_execve = 0;
+	rseq_execve(current);
 	acct_update_integrals(current);
 	task_numa_free(current);
 	free_bprm(bprm);
include/linux/sched.h +72 -0

88 lines not on this page · raw message

include/uapi/linux/Kbuild +1 -0
index 185f8ea..2a1888a 100644
@@ -405,6 +405,7 @@ header-y += tcp_metrics.h
 header-y += telephony.h
 header-y += termios.h
 header-y += thermal.h
+header-y += rseq.h
 header-y += time.h
 header-y += times.h
 header-y += timex.h
include/uapi/linux/rseq.h new file +106 -0

106 lines not on this page · raw message

init/Kconfig +13 -0
index cac3f09..8da994a 100644
@@ -1656,6 +1656,19 @@ config MEMBARRIER
 
 	  If unsure, say Y.
 
+config RSEQ
+	bool "Enable rseq() system call" if EXPERT
+	default y
+	depends on HAVE_RSEQ
+	help
+	  Enable the restartable sequences system call. It provides a
+	  user-space cache for the current CPU number value, which
+	  speeds up getting the current CPU number from user-space,
+	  as well as an ABI to speed up user-space operations on
+	  per-CPU data.
+
+	  If unsure, say Y.
+
 config EMBEDDED
 	bool "Embedded system"
 	option allnoconfig_y
kernel/Makefile +1 -0
index e2ec54e..4c6d8b5 100644
@@ -112,6 +112,7 @@ obj-$(CONFIG_TORTURE_TEST) += torture.o
 obj-$(CONFIG_MEMBARRIER) += membarrier.o
 
 obj-$(CONFIG_HAS_IOMEM) += memremap.o
+obj-$(CONFIG_RSEQ) += rseq.o
 
 $(obj)/configs.o: $(obj)/config_data.h
 
kernel/fork.c +2 -0
index 52e725d..784bd97 100644
@@ -1589,6 +1589,8 @@ static struct task_struct *copy_process(unsigned long clone_flags,
 	 */
 	copy_seccomp(p);
 
+	rseq_fork(p, clone_flags);
+
 	/*
 	 * Process group and session signals need to be delivered to just the
 	 * parent before the fork or both the parent and the child after the
kernel/rseq.c new file +287 -0

287 lines not on this page · raw message

kernel/sched/core.c +1 -0
index 2a906f2..e285f68 100644
@@ -2672,6 +2672,7 @@ prepare_task_switch(struct rq *rq, struct task_struct *prev,
 {
 	sched_info_switch(rq, prev, next);
 	perf_event_task_sched_out(prev, next);
+	rseq_sched_out(prev);
 	fire_sched_out_preempt_notifiers(prev, next);
 	prepare_lock_switch(rq, next);
 	prepare_arch_switch(next);
kernel/sys_ni.c +3 -0
index 2c5e3a8..c653f78 100644
@@ -250,3 +250,6 @@ cond_syscall(sys_execveat);
 
 /* membarrier */
 cond_syscall(sys_membarrier);
+
+/* restartable sequence */
+cond_syscall(sys_rseq);
Signature · 1 line
2.1.4
author maintainer
#18 lore raw

RFC PATCH v8 2/9 tracing: instrument restartable sequences

In reply to Mathieu Desnoyers
CC Thomas Gleixner <[email protected]>
CC Paul Turner <[email protected]>
CC Andrew Hunter <[email protected]>
CC Peter Zijlstra <[email protected]>
CC Andy Lutomirski <[email protected]>
CC Andi Kleen <andi-Vw/[email protected]>
CC Dave Watson <[email protected]>
CC Chris Lameter <[email protected]>
CC Ingo Molnar <[email protected]>
CC "H. Peter Anvin" <[email protected]>
CC Ben Maurer <[email protected]>
CC Steven Rostedt <[email protected]>
CC "Paul E. McKenney" <[email protected]>
CC Josh Triplett <[email protected]>
CC Linus Torvalds <torvalds-de/[email protected]>
CC Andrew Morton <akpm-de/[email protected]>
CC Russell King <linux-lFZ/[email protected]>
CC Catalin Marinas <[email protected]>
CC Will Deacon <[email protected]>
CC Michael Kerrisk <[email protected]>
CC Boqun Feng <[email protected]>
---
 include/trace/events/rseq.h | 64 +++++++++++++++++++++++++++++++++++++++++++++
 kernel/rseq.c               | 11 +++++++-
 2 files changed, 74 insertions(+), 1 deletion(-)
 create mode 100644 include/trace/events/rseq.h
include/trace/events/rseq.h new file +64 -0
new file mode 100644
index 0000000..63a8eb7
@@ -0,0 +1,64 @@
+#undef TRACE_SYSTEM
+#define TRACE_SYSTEM rseq
+
+#if !defined(_TRACE_RSEQ_H) || defined(TRACE_HEADER_MULTI_READ)
+#define _TRACE_RSEQ_H
+
+#include <linux/tracepoint.h>
+#include <linux/types.h>
+
+TRACE_EVENT(rseq_update,
+
+	TP_PROTO(struct task_struct *t),
+
+	TP_ARGS(t),
+
+	TP_STRUCT__entry(
+		__field(s32, cpu_id)
+		__field(u32, event_counter)
+	),
+
+	TP_fast_assign(
+		__entry->cpu_id = raw_smp_processor_id();
+		__entry->event_counter = t->rseq_event_counter;
+	),
+
+	TP_printk("cpu_id=%d event_counter=%u",
+		__entry->cpu_id, __entry->event_counter)
+);
+
+TRACE_EVENT(rseq_ip_fixup,
+
+	TP_PROTO(void __user *regs_ip, void __user *start_ip,
+		void __user *post_commit_ip, void __user *abort_ip,
+		u32 kevcount, int ret),
+
+	TP_ARGS(regs_ip, start_ip, post_commit_ip, abort_ip, kevcount, ret),
+
+	TP_STRUCT__entry(
+		__field(void __user *, regs_ip)
+		__field(void __user *, start_ip)
+		__field(void __user *, post_commit_ip)
+		__field(void __user *, abort_ip)
+		__field(u32, kevcount)
+		__field(int, ret)
+	),
+
+	TP_fast_assign(
+		__entry->regs_ip = regs_ip;
+		__entry->start_ip = start_ip;
+		__entry->post_commit_ip = post_commit_ip;
+		__entry->abort_ip = abort_ip;
+		__entry->kevcount = kevcount;
+		__entry->ret = ret;
+	),
+
+	TP_printk("regs_ip=%p start_ip=%p post_commit_ip=%p abort_ip=%p kevcount=%u ret=%d",
+		__entry->regs_ip, __entry->start_ip, __entry->post_commit_ip,
+		__entry->abort_ip, __entry->kevcount, __entry->ret)
+);
+
+#endif /* _TRACE_SOCK_H */
+
+/* This part must be outside protection */
+#include <trace/define_trace.h>
kernel/rseq.c +10 -1
index 32bc1d2..a102fcc 100644
@@ -32,6 +32,9 @@
 #include <linux/types.h>
 #include <asm/ptrace.h>
 
+#define CREATE_TRACE_POINTS
+#include <trace/events/rseq.h>
+
 /*
  * The restartable sequences mechanism is the overlap of two distinct
  * restart mechanisms: a sequence counter tracking preemption and signal
@@ -137,6 +140,7 @@ static bool rseq_update_cpu_id_event_counter(struct task_struct *t)
 	u.e.event_counter = ++t->rseq_event_counter;
 	if (__put_user(u.v, &t->rseq->u.v))
 		return false;
+	trace_rseq_update(t);
 	return true;
 }
 
@@ -168,8 +172,13 @@ static bool rseq_ip_fixup(struct pt_regs *regs)
 	void __user *start_ip = NULL;
 	void __user *post_commit_ip = NULL;
 	void __user *abort_ip = NULL;
+	bool ret;
 
-	if (!rseq_get_rseq_cs(t, &start_ip, &post_commit_ip, &abort_ip))
+	ret = rseq_get_rseq_cs(t, &start_ip, &post_commit_ip, &abort_ip);
+	trace_rseq_ip_fixup((void __user *)instruction_pointer(regs),
+		start_ip, post_commit_ip, abort_ip, t->rseq_event_counter,
+		ret);
+	if (!ret)
 		return false;
 
 	/* Handle potentially not being within a critical section. */
Signature · 1 line
2.1.4
author maintainer
#19 lore raw

RFC PATCH v8 3/9 Restartable sequences: ARM 32 architecture support

In reply to Mathieu Desnoyers

Call the rseq_handle_notify_resume() function on return to userspace if TIF_NOTIFY_RESUME thread flag is set.

Increment the event counter and perform fixup on the pre-signal frame when a signal is delivered on top of a restartable sequence critical section.

CC Russell King <linux-lFZ/[email protected]>
CC Catalin Marinas <[email protected]>
CC Will Deacon <[email protected]>
CC Thomas Gleixner <[email protected]>
CC Paul Turner <[email protected]>
CC Andrew Hunter <[email protected]>
CC Peter Zijlstra <[email protected]>
CC Andy Lutomirski <[email protected]>
CC Andi Kleen <andi-Vw/[email protected]>
CC Dave Watson <[email protected]>
CC Chris Lameter <[email protected]>
CC Ingo Molnar <[email protected]>
CC Ben Maurer <[email protected]>
CC Steven Rostedt <[email protected]>
CC "Paul E. McKenney" <[email protected]>
CC Josh Triplett <[email protected]>
CC Linus Torvalds <torvalds-de/[email protected]>
CC Andrew Morton <akpm-de/[email protected]>
CC Boqun Feng <[email protected]>
---
 arch/arm/Kconfig         | 1 +
 arch/arm/kernel/signal.c | 7 +++++++
 2 files changed, 8 insertions(+)
arch/arm/Kconfig +1 -0
index a9c4e48..d9779c3 100644
@@ -77,6 +77,7 @@ config ARM
 	select HAVE_PERF_USER_STACK_DUMP
 	select HAVE_RCU_TABLE_FREE if (SMP && ARM_LPAE)
 	select HAVE_REGS_AND_STACK_ACCESS_API
+	select HAVE_RSEQ
 	select HAVE_SYSCALL_TRACEPOINTS
 	select HAVE_UID16
 	select HAVE_VIRT_CPU_ACCOUNTING_GEN
arch/arm/kernel/signal.c +7 -0
index 7b8f214..907da02 100644
@@ -475,6 +475,12 @@ static void handle_signal(struct ksignal *ksig, struct pt_regs *regs)
 	int ret;
 
 	/*
+	 * Increment event counter and perform fixup for the pre-signal
+	 * frame.
+	 */
+	rseq_signal_deliver(regs);
+
+	/*
 	 * Set up the stack frame
 	 */
 	if (ksig->ka.sa.sa_flags & SA_SIGINFO)
@@ -594,6 +600,7 @@ do_work_pending(struct pt_regs *regs, unsigned int thread_flags, int syscall)
 			} else {
 				clear_thread_flag(TIF_NOTIFY_RESUME);
 				tracehook_notify_resume(regs);
+				rseq_handle_notify_resume(regs);
 			}
 		}
 		local_irq_disable();
Signature · 1 line
2.1.4
author maintainer
#20 lore raw

RFC PATCH v8 4/9 Restartable sequences: wire up ARM 32 system call

In reply to Mathieu Desnoyers

Wire up the rseq system call on 32-bit ARM.

This provides an ABI improving the speed of a user-space getcpu operation on ARM by skipping the getcpu system call on the fast path, as well as improving the speed of user-space operations on per-cpu data compared to using load-linked/store-conditional.

CC Russell King <linux-lFZ/[email protected]>
CC Catalin Marinas <[email protected]>
CC Will Deacon <[email protected]>
CC Thomas Gleixner <[email protected]>
CC Paul Turner <[email protected]>
CC Andrew Hunter <[email protected]>
CC Peter Zijlstra <[email protected]>
CC Andy Lutomirski <[email protected]>
CC Andi Kleen <andi-Vw/[email protected]>
CC Dave Watson <[email protected]>
CC Chris Lameter <[email protected]>
CC Ingo Molnar <[email protected]>
CC Ben Maurer <[email protected]>
CC Steven Rostedt <[email protected]>
CC "Paul E. McKenney" <[email protected]>
CC Josh Triplett <[email protected]>
CC Linus Torvalds <torvalds-de/[email protected]>
CC Andrew Morton <akpm-de/[email protected]>
CC Boqun Feng <[email protected]>
---
 arch/arm/include/uapi/asm/unistd.h | 1 +
 arch/arm/kernel/calls.S            | 1 +
 2 files changed, 2 insertions(+)
arch/arm/include/uapi/asm/unistd.h +1 -0
index 2cb9dc7..8f61c79 100644
@@ -420,6 +420,7 @@
 #define __NR_copy_file_range		(__NR_SYSCALL_BASE+391)
 #define __NR_preadv2			(__NR_SYSCALL_BASE+392)
 #define __NR_pwritev2			(__NR_SYSCALL_BASE+393)
+#define __NR_rseq			(__NR_SYSCALL_BASE+394)
 
 /*
  * The following SWIs are ARM private.
arch/arm/kernel/calls.S +1 -0
index 703fa0f..0865c04 100644
@@ -403,6 +403,7 @@
 		CALL(sys_copy_file_range)
 		CALL(sys_preadv2)
 		CALL(sys_pwritev2)
+		CALL(sys_rseq)
 #ifndef syscalls_counted
 .equ syscalls_padding, ((NR_syscalls + 3) & ~3) - NR_syscalls
 #define syscalls_counted
Signature · 1 line
2.1.4
author maintainer
#21 lore raw

RFC PATCH v8 5/9 Restartable sequences: x86 32/64 architecture support

In reply to Mathieu Desnoyers

Call the rseq_handle_notify_resume() function on return to userspace if TIF_NOTIFY_RESUME thread flag is set.

Increment the event counter and perform fixup on the pre-signal frame when a signal is delivered on top of a restartable sequence critical section.

CC Russell King <linux-lFZ/[email protected]>
CC Catalin Marinas <[email protected]>
CC Will Deacon <[email protected]>
CC Thomas Gleixner <[email protected]>
CC Paul Turner <[email protected]>
CC Andrew Hunter <[email protected]>
CC Peter Zijlstra <[email protected]>
CC Andy Lutomirski <[email protected]>
CC Andi Kleen <andi-Vw/[email protected]>
CC Dave Watson <[email protected]>
CC Chris Lameter <[email protected]>
CC Ingo Molnar <[email protected]>
CC "H. Peter Anvin" <[email protected]>
CC Ben Maurer <[email protected]>
CC Steven Rostedt <[email protected]>
CC "Paul E. McKenney" <[email protected]>
CC Josh Triplett <[email protected]>
CC Linus Torvalds <torvalds-de/[email protected]>
CC Andrew Morton <akpm-de/[email protected]>
CC Boqun Feng <[email protected]>
---
 arch/x86/Kconfig         | 1 +
 arch/x86/entry/common.c  | 1 +
 arch/x86/kernel/signal.c | 6 ++++++
 3 files changed, 8 insertions(+)
arch/x86/Kconfig +1 -0
index c580d8c..ae688f3 100644
@@ -143,6 +143,7 @@ config X86
 	select HAVE_PERF_REGS
 	select HAVE_PERF_USER_STACK_DUMP
 	select HAVE_REGS_AND_STACK_ACCESS_API
+	select HAVE_RSEQ
 	select HAVE_SYSCALL_TRACEPOINTS
 	select HAVE_UID16			if X86_32 || IA32_EMULATION
 	select HAVE_UNSTABLE_SCHED_CLOCK
arch/x86/entry/common.c +1 -0
index 1433f6b..86e0c5f 100644
@@ -165,6 +165,7 @@ static void exit_to_usermode_loop(struct pt_regs *regs, u32 cached_flags)
 		if (cached_flags & _TIF_NOTIFY_RESUME) {
 			clear_thread_flag(TIF_NOTIFY_RESUME);
 			tracehook_notify_resume(regs);
+			rseq_handle_notify_resume(regs);
 		}
 
 		if (cached_flags & _TIF_USER_RETURN_NOTIFY)
arch/x86/kernel/signal.c +6 -0
index 04cb321..d7252b5 100644
@@ -683,6 +683,12 @@ setup_rt_frame(struct ksignal *ksig, struct pt_regs *regs)
 	sigset_t *set = sigmask_to_save();
 	compat_sigset_t *cset = (compat_sigset_t *) set;
 
+	/*
+	 * Increment event counter and perform fixup for the pre-signal
+	 * frame.
+	 */
+	rseq_signal_deliver(regs);
+
 	/* Set up the stack frame */
 	if (is_ia32_frame()) {
 		if (ksig->ka.sa.sa_flags & SA_SIGINFO)
Signature · 1 line
2.1.4
author maintainer
#22 lore raw

RFC PATCH v8 6/9 Restartable sequences: wire up x86 32/64 system call

In reply to Mathieu Desnoyers

Wire up the rseq system call on x86 32/64.

This provides an ABI improving the speed of a user-space getcpu operation on x86 by removing the need to perform a function call, "lsl" instruction, or system call on the fast path, as well as improving the speed of user-space operations on per-cpu data.

CC Russell King <[email protected]>
CC Catalin Marinas <[email protected]>
CC Will Deacon <[email protected]>
CC Thomas Gleixner <[email protected]>
CC Paul Turner <[email protected]>
CC Andrew Hunter <[email protected]>
CC Peter Zijlstra <[email protected]>
CC Andy Lutomirski <[email protected]>
CC Andi Kleen <[email protected]>
CC Dave Watson <[email protected]>
CC Chris Lameter <[email protected]>
CC Ingo Molnar <[email protected]>
CC "H. Peter Anvin" <[email protected]>
CC Ben Maurer <[email protected]>
CC Steven Rostedt <[email protected]>
CC "Paul E. McKenney" <[email protected]>
CC Josh Triplett <[email protected]>
CC Linus Torvalds <[email protected]>
CC Andrew Morton <[email protected]>
CC Boqun Feng <[email protected]>
---
 arch/x86/entry/syscalls/syscall_32.tbl | 1 +
 arch/x86/entry/syscalls/syscall_64.tbl | 1 +
 2 files changed, 2 insertions(+)
arch/x86/entry/syscalls/syscall_32.tbl +1 -0
index f848572..9c3fb2b 100644
@@ -386,3 +386,4 @@
 377	i386	copy_file_range		sys_copy_file_range
 378	i386	preadv2			sys_preadv2			compat_sys_preadv2
 379	i386	pwritev2		sys_pwritev2			compat_sys_pwritev2
+380	i386	rseq			sys_rseq
arch/x86/entry/syscalls/syscall_64.tbl +1 -0
index e9ce9c7..83f5ac8 100644
@@ -335,6 +335,7 @@
 326	common	copy_file_range		sys_copy_file_range
 327	64	preadv2			sys_preadv2
 328	64	pwritev2		sys_pwritev2
+329	common	rseq			sys_rseq
 
 #
 # x32-specific system call numbers start at 512 to avoid cache impact
Signature · 1 line
2.1.4
author maintainer
#23 lore raw

RFC PATCH v8 7/9 Restartable sequences: powerpc architecture support

In reply to Mathieu Desnoyers

From: Boqun Feng <[email protected]>

Call the rseq_handle_notify_resume() function on return to userspace if TIF_NOTIFY_RESUME thread flag is set.

Increment the event counter and perform fixup on the pre-signal when a signal is delivered on top of a restartable sequence critical section.

---
 arch/powerpc/Kconfig         | 1 +
 arch/powerpc/kernel/signal.c | 3 +++
 2 files changed, 4 insertions(+)
arch/powerpc/Kconfig +1 -0
index 927d2ab..4847a8a 100644
@@ -119,6 +119,7 @@ config PPC
 	select HAVE_PERF_USER_STACK_DUMP
 	select HAVE_REGS_AND_STACK_ACCESS_API
 	select HAVE_HW_BREAKPOINT if PERF_EVENTS && PPC_BOOK3S_64
+	select HAVE_RSEQ
 	select ARCH_WANT_IPC_PARSE_VERSION
 	select SPARSE_IRQ
 	select IRQ_DOMAIN
arch/powerpc/kernel/signal.c +3 -0
index cb64d6f..339d0eb 100644
@@ -131,6 +131,8 @@ static void do_signal(struct pt_regs *regs)
 	/* Re-enable the breakpoints for the signal stack */
 	thread_change_pc(current, regs);
 
+	rseq_signal_deliver(regs);
+
 	if (is32) {
         	if (ksig.ka.sa.sa_flags & SA_SIGINFO)
 			ret = handle_rt_signal32(&ksig, oldset, regs);
@@ -157,6 +159,7 @@ void do_notify_resume(struct pt_regs *regs, unsigned long thread_info_flags)
 	if (thread_info_flags & _TIF_NOTIFY_RESUME) {
 		clear_thread_flag(TIF_NOTIFY_RESUME);
 		tracehook_notify_resume(regs);
+		rseq_handle_notify_resume(regs);
 	}
 
 	user_enter();
Signature · 1 line
2.1.4
author maintainer
#24 lore raw

RFC PATCH v8 8/9 Restartable sequences: Wire up powerpc system call

In reply to Mathieu Desnoyers

From: Boqun Feng <[email protected]>

Wire up the rseq system call on powerpc.

This provides an ABI improving the speed of a user-space getcpu operation on powerpc by skipping the getcpu system call on the fast path, as well as improving the speed of user-space operations on per-cpu data compared to using load-reservation/store-conditional atomics.

---
 arch/powerpc/include/asm/systbl.h      | 1 +
 arch/powerpc/include/asm/unistd.h      | 2 +-
 arch/powerpc/include/uapi/asm/unistd.h | 1 +
 3 files changed, 3 insertions(+), 1 deletion(-)
arch/powerpc/include/asm/systbl.h +1 -0
index 2fc5d4d..c68f4d0 100644
@@ -386,3 +386,4 @@ SYSCALL(mlock2)
 SYSCALL(copy_file_range)
 COMPAT_SYS_SPU(preadv2)
 COMPAT_SYS_SPU(pwritev2)
+SYSCALL(rseq)
arch/powerpc/include/asm/unistd.h +1 -1
index cf12c58..a01e97d 100644
@@ -12,7 +12,7 @@
 #include <uapi/asm/unistd.h>
 
 
-#define NR_syscalls		382
+#define NR_syscalls		383
 
 #define __NR__exit __NR_exit
 
arch/powerpc/include/uapi/asm/unistd.h +1 -0
index e9f5f41..d1849d6 100644
@@ -392,5 +392,6 @@
 #define __NR_copy_file_range	379
 #define __NR_preadv2		380
 #define __NR_pwritev2		381
+#define __NR_rseq		382
 
 #endif /* _UAPI_ASM_POWERPC_UNISTD_H_ */
Signature · 1 line
2.1.4
author maintainer
#25 lore raw

RFC PATCH v8 9/9 Restartable sequences: self-tests

In reply to Mathieu Desnoyers

Implements two basic tests of RSEQ functionality, and one more exhaustive parameterizable test.

The first, "basic_test" only asserts that RSEQ works moderately correctly.
E.g. that:
- The CPUID pointer works
- Code infinitely looping within a critical section will eventually be interrupted.
- Critical sections are interrupted by signals.

"basic_percpu_ops_test" is a slightly more "realistic" variant, implementing a few simple per-cpu operations and testing their correctness.

"param_test" is a parametrizable restartable sequences test. See the "--help" output for usage.

As part of those tests, a helper library "rseq" implements a user-space API around restartable sequences. It takes care of ensuring progress in case of debugger single-stepping with a fall-back to locking, and exposes the instruction pointer addresses where the rseq assembly blocks begin and end, as well as the associated abort instruction pointer, in the __rseq_table section. This section allows debuggers may know where to place breakpoints when single-stepping through assembly blocks which may be aborted at any point by the kernel.

The following rseq APIs are implemented in this helper library:
- do_rseq(): Restartable sequence made of zero or more loads, completed by a word-sized store,
- do_rseq2(): Restartable sequence made of zero or more loads, one speculative word-sized store, completed by a word-sized store,
- do_rseq_memcpy(): Restartable sequence made of zero or more loads, a speculative copy of a variable length memory region, completed by a word-sized store.

PowerPC tests have been implemented by Boqun Feng.

CC Russell King <[email protected]>
CC Catalin Marinas <[email protected]>
CC Will Deacon <[email protected]>
CC Thomas Gleixner <[email protected]>
CC Paul Turner <[email protected]>
CC Andrew Hunter <[email protected]>
CC Peter Zijlstra <[email protected]>
CC Andy Lutomirski <[email protected]>
CC Andi Kleen <[email protected]>
CC Dave Watson <[email protected]>
CC Chris Lameter <[email protected]>
CC Ingo Molnar <[email protected]>
CC "H. Peter Anvin" <[email protected]>
CC Ben Maurer <[email protected]>
CC Steven Rostedt <[email protected]>
CC "Paul E. McKenney" <[email protected]>
CC Josh Triplett <[email protected]>
CC Linus Torvalds <[email protected]>
CC Andrew Morton <[email protected]>
CC Boqun Feng <[email protected]>
---
 MAINTAINERS                                        |    1 +
 tools/testing/selftests/rseq/.gitignore            |    3 +
 tools/testing/selftests/rseq/Makefile              |   13 +
 .../testing/selftests/rseq/basic_percpu_ops_test.c |  286 +++++
 tools/testing/selftests/rseq/basic_test.c          |  107 ++
 tools/testing/selftests/rseq/param_test.c          | 1116 ++++++++++++++++++++
 tools/testing/selftests/rseq/rseq-arm.h            |  168 +++
 tools/testing/selftests/rseq/rseq-ppc.h            |  273 +++++
 tools/testing/selftests/rseq/rseq-x86.h            |  306 ++++++
 tools/testing/selftests/rseq/rseq.c                |  247 +++++
 tools/testing/selftests/rseq/rseq.h                |  477 +++++++++
 11 files changed, 2997 insertions(+)
 create mode 100644 tools/testing/selftests/rseq/.gitignore
 create mode 100644 tools/testing/selftests/rseq/Makefile
 create mode 100644 tools/testing/selftests/rseq/basic_percpu_ops_test.c
 create mode 100644 tools/testing/selftests/rseq/basic_test.c
 create mode 100644 tools/testing/selftests/rseq/param_test.c
 create mode 100644 tools/testing/selftests/rseq/rseq-arm.h
 create mode 100644 tools/testing/selftests/rseq/rseq-ppc.h
 create mode 100644 tools/testing/selftests/rseq/rseq-x86.h
 create mode 100644 tools/testing/selftests/rseq/rseq.c
 create mode 100644 tools/testing/selftests/rseq/rseq.h
MAINTAINERS +1 -0
index 5028f03..5381d3a 100644
@@ -5213,6 +5213,7 @@ L:	[email protected]
 S:	Supported
 F:	kernel/rseq.c
 F:	include/uapi/linux/rseq.h
+F:	tools/testing/selftests/rseq/
 
 GFS2 FILE SYSTEM
 M:	Steven Whitehouse <[email protected]>
tools/testing/selftests/rseq/.gitignore new file +3 -0
new file mode 100644
index 0000000..2596e26
@@ -0,0 +1,3 @@
+basic_percpu_ops_test
+basic_test
+param_test
tools/testing/selftests/rseq/Makefile new file +13 -0
new file mode 100644
index 0000000..0082d02
@@ -0,0 +1,13 @@
+CFLAGS += -O2 -Wall -g -I./ -I../../../../usr/include/
+LDFLAGS += -lpthread
+
+TESTS = basic_test basic_percpu_ops_test param_test
+
+all: $(TESTS)
+%: %.c rseq.h rseq-*.h rseq.c
+	$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)
+
+include ../lib.mk
+
+clean:
+	$(RM) $(TESTS)
tools/testing/selftests/rseq/basic_percpu_ops_test.c new file +286 -0

286 lines not on this page · raw message

tools/testing/selftests/rseq/basic_test.c new file +107 -0

107 lines not on this page · raw message

tools/testing/selftests/rseq/param_test.c new file +1116 -0

1,116 lines not on this page · raw message

tools/testing/selftests/rseq/rseq-arm.h new file +168 -0

168 lines not on this page · raw message

tools/testing/selftests/rseq/rseq-ppc.h new file +273 -0

273 lines not on this page · raw message

tools/testing/selftests/rseq/rseq-x86.h new file +306 -0

306 lines not on this page · raw message

tools/testing/selftests/rseq/rseq.c new file +247 -0

247 lines not on this page · raw message

tools/testing/selftests/rseq/rseq.h new file +477 -0

474 lines not on this page · raw message

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.1.4

Part of the diff is not shown here. View the raw message.

#2 lore raw
In reply to Mathieu Desnoyers
Quoted 2 lines · Mathieu Desnoyers

Benchmarking various approaches for reading the current CPU number:

So I'd like to see the benchmarks of something that actually *does* something.

IOW, what's the bigger-picture "this is what it actually is useful for, and how it speeds things up".

Nobody gets a cpu number just to get a cpu number - it's not a useful thing to benchmark. What does getcpu() so much that we care?

We've had tons of clever features that nobody actually uses, because they aren't really portable enough. I'd like to be convinced that this is actually going to be used by real applications.

Linus

#3 lore raw
Quoted 5 lines · Linus Torvalds
Quoted 2 lines · Mathieu Desnoyers

Benchmarking various approaches for reading the current CPU number:

Quoted 7 lines

So I'd like to see the benchmarks of something that actually *does* something.

IOW, what's the bigger-picture "this is what it actually is useful for, and how it speeds things up".

Nobody gets a cpu number just to get a cpu number - it's not a useful thing to benchmark. What does getcpu() so much that we care?

The combination of CPU number and restartable sequence allows userspace to write "per-CPU" rather than "per-thread" algorithms, just as the kernel can. The kernel can do that with preempt_disable(). Userspace can do it with "tell me my CPU and restart me if preempted".

But yes, this needs a benchmark of, for instance, urcu implemented on top of this, or some concrete data structure.

#5 lore raw
In reply to Linus Torvalds
Quoted 2 lines

Nobody gets a cpu number just to get a cpu number - it's not a useful thing to benchmark. What does getcpu() so much that we care?

malloc is the primary target I believe. Saves lots of memory to keep caches per CPU rather than per thread.

-Andi

#4 lore raw
In reply to Josh Triplett
Quoted 5 lines · Josh Triplett

The combination of CPU number and restartable sequence allows userspace to write "per-CPU" rather than "per-thread" algorithms, just as the kernel can. The kernel can do that with preempt_disable(). Userspace can do it with "tell me my CPU and restart me if preempted".

Yes, I understand what the patch series wants to do. But there hasn't been a lot of discussion about why per-cpu would be better than per-thread, or who would actually use this.

The kernel cares about per-cpu, because as far as the kernel is concerned, that largely _is_ threading inside the kernel.

I'd feel a lot more warm and fuzzy about this all if I'd also see what the usage scenario is, and then the numbers on top of that.

We really _have_ had too many clever interfaces that basically never saw any real use, because the application writers don't want to limit themselves to just Linux, and even if they are happy to do that, they don't want to then limit themselves to a fairly modern kernel, and they don't want to have two different code bases.

For example, there's been a talk about number of instructions and cycles on ARMv7, but it's not clear whether the use case is going to care about tens of cycles of overhead much less individual instruction counts. Those instruction counts may matter when you benchmark an individual "cpu-atomic add", but may not matter when you actually benchmark something much bigger.

And if people end up waiting for kernel support to be universally available, then ARMv7 isn't even all that relevant any more. It takes years for things like this to percolate out. In the android space, you get new hardware quicker than you get new software..

Linus

#6 lore raw
In reply to Andi Kleen
Quoted 5 lines · Andi Kleen
Quoted 2 lines

Nobody gets a cpu number just to get a cpu number - it's not a useful thing to benchmark. What does getcpu() so much that we care?

malloc is the primary target I believe. Saves lots of memory to keep caches per CPU rather than per thread.

Agreed, a competent default malloc() in glibc would be a very nice change from the current state.

Thanx, Paul

#9 lore raw
In reply to Andi Kleen
Quoted 5 lines · Andi Kleen
Quoted 2 lines

Nobody gets a cpu number just to get a cpu number - it's not a useful thing to benchmark. What does getcpu() so much that we care?

malloc is the primary target I believe. Saves lots of memory to keep caches per CPU rather than per thread.

Also improves locality; that does seem like a good idea. Has anyone written and tested the corresponding changes to a malloc implementation?

- Josh Triplett

#7 lore raw
In reply to Paul E. McKenney
Quoted 7 lines · Paul E. McKenney
Quoted 3 lines · Andi Kleen

malloc is the primary target I believe. Saves lots of memory to keep caches per CPU rather than per thread.

Agreed, a competent default malloc() in glibc would be a very nice change from the current state.

I agree that malloc can be a very good target for something like this, but it is also something that is quite complicated. A general-purpose allocator that could be used by glibc and has not just the performance but the debug stuff etc that people inevitably want is a big project. And then the people who have special needs end up writing their own allocators anyway, just because they care about certain layout and access patterns...

Put another way: I'd really like to see some real numbers and use, rather than "this can be used for.."

Linus

#10 lore raw
In reply to Josh Triplett
Quoted 10 lines · Josh Triplett
Quoted 5 lines · Andi Kleen
Quoted 2 lines

Nobody gets a cpu number just to get a cpu number - it's not a useful thing to benchmark. What does getcpu() so much that we care?

malloc is the primary target I believe. Saves lots of memory to keep caches per CPU rather than per thread.

Also improves locality; that does seem like a good idea. Has anyone written and tested the corresponding changes to a malloc implementation?

I had modified jemalloc to use rseq instead of per-thread caches, and did some testing on one of our services.

Memory usage decreased by ~20% due to fewer caches. Our services generally have lots and lots of idle threads (~400), and we already go through a few hoops to try and flush idle thread caches. Threads are often coming from dependent libraries written by disparate teams, making them harder to reduce to a smaller number.

We also have quite a few data structures that are sharded thread-locally only to avoid contention, for example we have extensive statistics code that would also be a prime candidate for rseq . We often have to prune some stats because they're taking up too much memory, rseq would let us fit a bit more in.

jemalloc diff here (pretty stale now):

https://github.com/djwatson/jemalloc/commit/51f6e6f61b88eee8de981f0f2d52bc48f85e0d01

Original numbers posted here:

https://lkml.org/lkml/2015/10/22/588

#8 lore raw
In reply to Linus Torvalds
Quoted 18 lines · Linus Torvalds
Quoted 7 lines · Paul E. McKenney
Quoted 3 lines · Andi Kleen

malloc is the primary target I believe. Saves lots of memory to keep caches per CPU rather than per thread.

Agreed, a competent default malloc() in glibc would be a very nice change from the current state.

I agree that malloc can be a very good target for something like this, but it is also something that is quite complicated. A general-purpose allocator that could be used by glibc and has not just the performance but the debug stuff etc that people inevitably want is a big project. And then the people who have special needs end up writing their own allocators anyway, just because they care about certain layout and access patterns...

Quoted 2 lines

Put another way: I'd really like to see some real numbers and use, rather than "this can be used for.."

No argument here!

Thanx, Paul

author maintainer
#11 lore raw
In reply to Linus Torvalds
Quoted 10 lines · ----- On Aug 19, 2016, at 4:23 PM, Linus Torvalds…
Quoted 2 lines · Mathieu Desnoyers

Benchmarking various approaches for reading the current CPU number:

So I'd like to see the benchmarks of something that actually *does* something.

IOW, what's the bigger-picture "this is what it actually is useful for, and how it speeds things up".

Quoted 6 lines

Nobody gets a cpu number just to get a cpu number - it's not a useful thing to benchmark. What does getcpu() so much that we care?

We've had tons of clever features that nobody actually uses, because they aren't really portable enough. I'd like to be convinced that this is actually going to be used by real applications.

I completely agree with your request for real-life application numbers.

The most appealing application we have so far is Dave Watson's Facebook services using jemalloc as a memory allocator. It would be nice if he could re-run those benchmarks with my rseq implementation. The trade-offs here are about speed and memory usage:

1) single process-wide pool:
- speed: does not scale well to many-cores,
+ efficient use of memory.
2) per-thread pools:
+ speed: scales really well to many-cores,
- inefficient use of memory.
3) per-cpu pools without rseq:
- speed: requires atomic instructions due to migration and preemption,
+ efficient use of memory.
4) per-cpu pools with rseq:
+ speed: no atomic instructions required,
+ efficient use of memory.

His benchmarks should confirm that we get best of speed and memory use with (4).

I plan to personally start working on integrating rseq with the lttng-ust user-space tracer per-CPU ring buffer, but I expect to mainly publish microbenchmarks, as most of our heavy tracing users are proprietary applications, for which it's tricky to publish numbers. I suspect that microbenchmarks are not what you are looking for here.

Boqun Feng expressed interested in working on a userspace RCU flavor that would implement per-CPU (rather than per-thread) grace period tracking. I suspect this will be a rather large undertaking. The benefits should be visible as grace period overhead and speed in applications that have many more threads than cores.

Paul Turner from Google probably have interesting numbers too, but I suspect he is busy on other projects at the moment.

Let's see if we can get Dave Watson to provide those numbers.

Thanks!

Mathieu

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
http://www.efficios.com
#12 lore raw
Quoted 4 lines · Mathieu Desnoyers

The most appealing application we have so far is Dave Watson's Facebook
services using jemalloc as a memory allocator. It would be nice if he could re-run those benchmarks with my rseq implementation. The trade-offs here are about speed and memory usage:

One piece of context I’d like to provide about our investigation into using rseq for malloc – I think that it’s really important to keep in mind that we’ve optimized the software that we write to survive well in a world where there’s a high memory cost for jemalloc for each thread and jemalloc is unable to have allocation caches as large as we would like. We’re not going to have real world benchmarks that show a magical improvement with rseq because over time we’ve baked the constraints of our environment into the design of our programs and optimized for the current set of APIs the kernel provides. I do think rseq provides a benefit even for applications optimized for today’s malloc implementations. But the real benefit is the new types of application designed that rseq enables and the ability for rseq to provide predictable performance for low-level APIs with much less investment from users. I’ll illustrate the costs that rseq would let us avoid with two examples of design choices we’ve made:

1) Because jemalloc uses a per-thread cache, threads that are sleeping have a high memory cost. For example, if you have a thread-pool with 100 threads but only 10 are used most of the time the other 90 threads will still have a dormant cache consuming memory. In order to combat this we have an abstraction called MemoryIdler (https://github.com/facebook/folly/blob/master/folly/detail/MemoryIdler.h) which is essentially a wrapper around futex that signals jemalloc to release its caches when the thread is idle. From what I can tell this is a practice that isn’t widely adopted even though it can save a substantial amount of memory – rseq makes this a moot point since caches can be per-cpu and the memory allocator does not need to worry about an idle thread hogging the cache.
2) The per-thread nature of malloc implementations has generally led people to avoid thread-per-request designs. Things like MemoryIdler can help you if a thread is going to be idle for seconds before it is used again, but if your thread makes a 100 ms RPC to another server clearing the cache is far too expensive to justify. But you still have a bunch of memory sitting around unused for 100ms. Multiply that by many concurrent requests and you are consuming a lot of memory. This has forced people to handle multiple requests in a single thread – this leads to problems of its own like a contested lock in one request impacting many other requests on the same thread.

rseq opens up a whole world of algorithms to userspace – algorithms that are O(num CPUs) and where one can have an extremely fast fastpath at the cost of a slower slow path. Many of these algorithms are in use in the kernel today – per-cpu allocators, RCU, light-weight reader writer locks, etc. Even in cases where these APIs can be implemented today, a rseq implementation is often superior in terms of predictability and usability (eg per-thread counters consume more memory and are more expensive to read than per-cpu counters).

Isn’t the large number of uses of rseq-like algorithms in the kernel a pretty substantial sign that there would be demand for similar algorithms by user-space systems programmers?

-b

#13 lore raw
Quoted 9 lines · Ben Maurer

rseq opens up a whole world of algorithms to userspace – algorithms that are O(num CPUs) and where one can have an extremely fast fastpath at the cost of a slower slow path. Many of these algorithms are in use in the kernel today – per-cpu allocators, RCU, light-weight reader writer locks, etc. Even in cases where these APIs can be implemented today, a rseq implementation is often superior in terms of predictability and usability (eg per-thread counters consume more memory and are more expensive to read than per-cpu counters).

Quoted 3 lines

Isn’t the large number of uses of rseq-like algorithms in the kernel a pretty substantial sign that there would be demand for similar algorithms by user-space systems programmers?

Yes and no. It provides a substantial sign that such algorithms could and should exist; however "someone should do this" doesn't demonstrate that someone *will*. I do think we need a concrete example of a userspace user with benchmark numbers that demonstrate the value of this approach.

Mathieu, do you have a version of URCU that can use rseq to work per-CPU rather than per-thread? URCU's data structures would work as a benchmark.

Ben, Mathieu, Dave, do you have jemalloc benchmark numbers with and without rseq? (As well as memory usage numbers for the reduced memory usage of per-CPU pools rather than per-thread pools?)

#17 lore raw
In reply to Mathieu Desnoyers

Hi!

Quoted 10 lines

Expose a new system call allowing each thread to register one userspace memory area to be used as an ABI between kernel and user-space for two
purposes: user-space restartable sequences and quick access to read the current CPU number value from user-space.

* Restartable sequences (per-cpu atomics)

Restartables sequences allow user-space to perform update operations on per-cpu data without requiring heavy-weight atomic operations.

Quoted 9 lines

The restartable critical sections (percpu atomics) work has been started by Paul Turner and Andrew Hunter. It lets the kernel handle restart of critical sections. [1] [2] The re-implementation proposed here brings a few simplifications to the ABI which facilitates porting to other architectures and speeds up the user-space fast path. A locking-based fall-back, purely implemented in user-space, is proposed here to deal with debugger single-stepping. This fallback interacts with rseq_start() and rseq_finish(), which force retries in response to concurrent lock-based activity.

Hmm. Purely software fallback needed for singlestepping... Looks like this is malware writer's dream come true...

Also if you ever get bug in the restartable code, debugger will be useless to debug it... unless new abilities are added to debuggers to manually schedule threads on CPUs.

Is this good idea?

Pavel

author maintainer
#14 lore raw
In reply to Josh Triplett
Quoted 20 lines · ----- On Aug 27, 2016, at 12:22 AM, Josh Triplett [email protected] wrote:
Quoted 9 lines · Ben Maurer

rseq opens up a whole world of algorithms to userspace – algorithms that are O(num CPUs) and where one can have an extremely fast fastpath at the cost of a slower slow path. Many of these algorithms are in use in the kernel today – per-cpu allocators, RCU, light-weight reader writer locks, etc. Even in cases where these APIs can be implemented today, a rseq implementation is often superior in terms of predictability and usability (eg per-thread counters consume more memory and are more expensive to read than per-cpu counters).

Quoted 3 lines

Isn’t the large number of uses of rseq-like algorithms in the kernel a pretty substantial sign that there would be demand for similar algorithms by user-space systems programmers?

Yes and no. It provides a substantial sign that such algorithms could and should exist; however "someone should do this" doesn't demonstrate that someone *will*. I do think we need a concrete example of a userspace user with benchmark numbers that demonstrate the value of this approach.

Quoted 3 lines

Mathieu, do you have a version of URCU that can use rseq to work per-CPU rather than per-thread? URCU's data structures would work as a benchmark.

I currently don't have a per-cpu flavor of liburcu. All the flavors are per-thread, because currently the alternative requires atomic operations on the fast-path. We could indeed re-implement something similar to SRCU (although under LGPLv2.1 license). I've looked at what would be required over the weekend, and it seems feasible, but in the short term my customers expect me to focus my work on speeding up the LTTng-UST tracer per-cpu ring buffer by adapting it to rseq. Completing the liburcu per-cpu flavor will be in my spare time for now.

I expect liburcu per-cpu flavor to improve the slow path in many-threads use-cases (smaller grace period overhead), but not the fast path much, except perhaps by allowing faster memory reclaim in update-heavy workloads, which could then lead to better use of the cache even for reads.

Quoted 4 lines

Ben, Mathieu, Dave, do you have jemalloc benchmark numbers with and without rseq? (As well as memory usage numbers for the reduced memory usage of per-CPU pools rather than per-thread pools?)

Before I started reimplementing rseq, the numbers presented by Facebook at https://lkml.org/lkml/2015/10/22/588 were in my opinion a good proof that rseq is useful. I'm not sure if their memoryidler API was used back then.

I could take Dave's jemalloc branch adapted to Paul Turner's rseq and adapt it to mine. Then we could use this allocator to compare the memory use and speed of heavily multi-threaded applications.

Thoughts ?

Thanks,

Mathieu

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
http://www.efficios.com
#15 lore raw
Quoted 10 lines · Mathieu Desnoyers
Quoted 3 lines · ----- On Aug 27, 2016, at 12:22 AM, Josh Triplett…

Ben, Mathieu, Dave, do you have jemalloc benchmark numbers with and without rseq? (As well as memory usage numbers for the reduced memory usage of per-CPU pools rather than per-thread pools?)

Before I started reimplementing rseq, the numbers presented by Facebook at https://lkml.org/lkml/2015/10/22/588 were in my opinion a good proof that rseq is useful. I'm not sure if their memoryidler API was used back then.

Quoted 5 lines

I could take Dave's jemalloc branch adapted to Paul Turner's rseq and adapt it to mine. Then we could use this allocator to compare the memory use and speed of heavily multi-threaded applications.

Thoughts ?

That seems like it would provide a good concrete benchmark of this work, and demonstrate the value of it.

#16 lore raw
In reply to Mathieu Desnoyers
Quoted 26 lines · Mathieu Desnoyers
Quoted 20 lines · ----- On Aug 27, 2016, at 12:22 AM, Josh Triplett [email protected] wrote:
Quoted 9 lines · Ben Maurer

rseq opens up a whole world of algorithms to userspace – algorithms that are O(num CPUs) and where one can have an extremely fast fastpath at the cost of a slower slow path. Many of these algorithms are in use in the kernel today – per-cpu allocators, RCU, light-weight reader writer locks, etc. Even in cases where these APIs can be implemented today, a rseq implementation is often superior in terms of predictability and usability (eg per-thread counters consume more memory and are more expensive to read than per-cpu counters).

Quoted 3 lines

Isn’t the large number of uses of rseq-like algorithms in the kernel a pretty substantial sign that there would be demand for similar algorithms by user-space systems programmers?

Yes and no. It provides a substantial sign that such algorithms could and should exist; however "someone should do this" doesn't demonstrate that someone *will*. I do think we need a concrete example of a userspace user with benchmark numbers that demonstrate the value of this approach.

Quoted 3 lines

Mathieu, do you have a version of URCU that can use rseq to work per-CPU rather than per-thread? URCU's data structures would work as a benchmark.

Quoted 9 lines

I currently don't have a per-cpu flavor of liburcu. All the flavors are per-thread, because currently the alternative requires atomic operations on the fast-path. We could indeed re-implement something similar to SRCU (although under LGPLv2.1 license). I've looked at what would be required over the weekend, and it seems feasible, but in the short term my customers expect me to focus my work on speeding up the LTTng-UST tracer per-cpu ring buffer by adapting it to rseq. Completing the liburcu per-cpu flavor will be in my spare time for now.

Just for you information.

I have been working on the new SRCU-like flavor of liburcu since last week, but it took me a while to understand the directory architecture of urcu...

I wrote only implemetion for rcu_read_{un}lock() and synchronize_rcu(), and just is able to run the simplest multiflavor test case. My plan is to post the code and some numbers(on x86 and ppc) by the end of this week.

Regards,
Boqun

Quoted 5 lines

I expect liburcu per-cpu flavor to improve the slow path in many-threads use-cases (smaller grace period overhead), but not the fast path much, except perhaps by allowing faster memory reclaim in update-heavy workloads, which could then lead to better use of the cache even for reads.

[...]