Execution and synchronisation
Single-page view · as markdown
Linux-specific ELF idiosyncrasies
Peios Kernel / Userspace interfaces / System and device interfaces / Execution and synchronisation
Definitions #
"First" program header is the one with the smallest offset in the file: e_phoff.
"Last" program header is the one with the biggest offset in the file: e_phoff + (e_phnum - 1) * sizeof(Elf_Phdr).
PT_INTERP #
First PT_INTERP program header is used to locate the filename of ELF interpreter. Other PT_INTERP headers are ignored (since Linux 2.4.11).
PT_GNU_STACK #
Last PT_GNU_STACK program header defines userspace stack executability (since Linux 2.6.6). Other PT_GNU_STACK headers are ignored.
PT_GNU_PROPERTY #
ELF interpreter's last PT_GNU_PROPERTY program header is used (since Linux 5.8). If interpreter doesn't have one, then the last PT_GNU_PROPERTY program header of an executable is used. Other PT_GNU_PROPERTY headers are ignored.
Executability check
Peios Kernel / Userspace interfaces / System and device interfaces / Execution and synchronisation
The AT_EXECVE_CHECK execveat(2) flag, and the SECBIT_EXEC_RESTRICT_FILE and SECBIT_EXEC_DENY_INTERACTIVE securebits are intended for script interpreters and dynamic linkers to enforce a consistent execution security policy handled by the kernel. See the samples/check-exec/inc.c example.
Whether an interpreter should check these securebits or not depends on the security risk of running malicious scripts with respect to the execution environment, and whether the kernel can check if a script is trustworthy or not. For instance, Python scripts running on a server can use arbitrary syscalls and access arbitrary files. Such interpreters should then be enlighten to use these securebits and let users define their security policy. However, a JavaScript engine running in a web browser should already be sandboxed and then should not be able to harm the user's environment.
Script interpreters or dynamic linkers built for tailored execution environments (e.g. hardened Linux distributions or hermetic container images) could use AT_EXECVE_CHECK without checking the related securebits if backward compatibility is handled by something else (e.g. atomic update ensuring that all legitimate libraries are allowed to be executed). It is then recommended for script interpreters and dynamic linkers to check the securebits at run time by default, but also to provide the ability for custom builds to behave like if SECBIT_EXEC_RESTRICT_FILE or SECBIT_EXEC_DENY_INTERACTIVE were always set to 1 (i.e. always enforce restrictions).
AT_EXECVE_CHECK #
Passing the AT_EXECVE_CHECK flag to execveat(2) only performs a check on a regular file and returns 0 if execution of this file would be allowed, ignoring the file format and then the related interpreter dependencies (e.g. ELF libraries, script's shebang).
Programs should always perform this check to apply kernel-level checks against files that are not directly executed by the kernel but passed to a user space interpreter instead. All files that contain executable code, from the point of view of the interpreter, should be checked. However the result of this check should only be enforced according to SECBIT_EXEC_RESTRICT_FILE or SECBIT_EXEC_DENY_INTERACTIVE..
The main purpose of this flag is to improve the security and consistency of an execution environment to ensure that direct file execution (e.g. ./script.sh) and indirect file execution (e.g. sh script.sh) lead to the same result. For instance, this can be used to check if a file is trustworthy according to the caller's environment.
In a secure environment, libraries and any executable dependencies should also be checked. For instance, dynamic linking should make sure that all libraries are allowed for execution to avoid trivial bypass (e.g. using LD_PRELOAD). For such secure execution environment to make sense, only trusted code should be executable, which also requires integrity guarantees.
To avoid race conditions leading to time-of-check to time-of-use issues, AT_EXECVE_CHECK should be used with AT_EMPTY_PATH to check against a file descriptor instead of a path.
SECBIT_EXEC_RESTRICT_FILE and SECBIT_EXEC_DENY_INTERACTIVE #
When SECBIT_EXEC_RESTRICT_FILE is set, a process should only interpret or execute a file if a call to execveat(2) with the related file descriptor and the AT_EXECVE_CHECK flag succeed.
This secure bit may be set by user session managers, service managers, container runtimes, sandboxer tools... Except for test environments, the related SECBIT_EXEC_RESTRICT_FILE_LOCKED bit should also be set.
Programs should only enforce consistent restrictions according to the securebits but without relying on any other user-controlled configuration. Indeed, the use case for these securebits is to only trust executable code vetted by the system configuration (through the kernel), so we should be careful to not let untrusted users control this configuration.
However, script interpreters may still use user configuration such as environment variables as long as it is not a way to disable the securebits checks. For instance, the PATH and LD_PRELOAD variables can be set by a script's caller. Changing these variables may lead to unintended code executions, but only from vetted executable programs, which is OK. For this to make sense, the system should provide a consistent security policy to avoid arbitrary code execution e.g., by enforcing a write xor execute policy.
When SECBIT_EXEC_DENY_INTERACTIVE is set, a process should never interpret interactive user commands (e.g. scripts). However, if such commands are passed through a file descriptor (e.g. stdin), its content should be interpreted if a call to execveat(2) with the related file descriptor and the AT_EXECVE_CHECK flag succeed.
For instance, script interpreters called with a script snippet as argument should always deny such execution if SECBIT_EXEC_DENY_INTERACTIVE is set.
This secure bit may be set by user session managers, service managers, container runtimes, sandboxer tools... Except for test environments, the related SECBIT_EXEC_DENY_INTERACTIVE_LOCKED bit should also be set.
Here is the expected behavior for a script interpreter according to combination of any exec securebits:
-
SECBIT_EXEC_RESTRICT_FILE=0andSECBIT_EXEC_DENY_INTERACTIVE=0Always interpret scripts, and allow arbitrary user commands (default).
No threat, everyone and everything is trusted, but we can get ahead of potential issues thanks to the call to
execveat(2)withAT_EXECVE_CHECKwhich should always be performed but ignored by the script interpreter. Indeed, this check is still important to enable systems administrators to verify requests (e.g. with audit) and prepare for migration to a secure mode. -
SECBIT_EXEC_RESTRICT_FILE=1andSECBIT_EXEC_DENY_INTERACTIVE=0Deny script interpretation if they are not executable, but allow arbitrary user commands.
The threat is (potential) malicious scripts run by trusted (and not fooled) users. That can protect against unintended script executions (e.g.
sh /tmp/*.sh). This makes sense for (semi-restricted) user sessions. -
SECBIT_EXEC_RESTRICT_FILE=0andSECBIT_EXEC_DENY_INTERACTIVE=1Always interpret scripts, but deny arbitrary user commands.
This use case may be useful for secure services (i.e. without interactive user session) where scripts' integrity is verified (e.g. with IMA/EVM or dm-verity/IPE) but where access rights might not be ready yet. Indeed, arbitrary interactive commands would be much more difficult to check.
-
SECBIT_EXEC_RESTRICT_FILE=1andSECBIT_EXEC_DENY_INTERACTIVE=1Deny script interpretation if they are not executable, and also deny any arbitrary user commands.
The threat is malicious scripts run by untrusted users (but trusted code). This makes sense for system services that may only execute trusted scripts.
futex2
Peios Kernel / Userspace interfaces / System and device interfaces / Execution and synchronisation
Author: André Almeida <andrealmeid@collabora.com>
futex, or fast user mutex, is a set of syscalls to allow userspace to create performant synchronization mechanisms, such as mutexes, semaphores and conditional variables in userspace. C standard libraries, like glibc, uses it as a means to implement more high level interfaces like pthreads.
futex2 is a followup version of the initial futex syscall, designed to overcome limitations of the original interface.
User API #
futex_waitv() #
Wait on an array of futexes, wake on any:
futex_waitv(struct futex_waitv *waiters, unsigned int nr_futexes,
unsigned int flags, struct timespec *timeout, clockid_t clockid)
struct futex_waitv {
__u64 val;
__u64 uaddr;
__u32 flags;
__u32 __reserved;
};
Userspace sets an array of struct futex_waitv (up to a max of 128 entries), using uaddr for the address to wait for, val for the expected value and flags to specify the type (e.g. private) and size of futex. __reserved needs to be 0, but it can be used for future extension. The pointer for the first item of the array is passed as waiters. An invalid address for waiters or for any uaddr returns -EFAULT.
If userspace has 32-bit pointers, it should do a explicit cast to make sure the upper bits are zeroed. uintptr_t does the tricky and it works for both 32/64-bit pointers.
nr_futexes specifies the size of the array. Numbers out of [1, 128] interval will make the syscall return -EINVAL.
The flags argument of the syscall needs to be 0, but it can be used for future extension.
For each entry in waiters array, the current value at uaddr is compared to val. If it's different, the syscall undo all the work done so far and return -EAGAIN. If all tests and verifications succeeds, syscall waits until one of the following happens:
-
The timeout expires, returning
-ETIMEOUT. -
A signal was sent to the sleeping task, returning
-ERESTARTSYS. -
Some futex at the list was woken, returning the index of some waked futex.
An example of how to use the interface can be found at tools/testing/selftests/futex/functional/futex_waitv.c.
Timeout #
struct timespec *timeout argument is an optional argument that points to an absolute timeout. You need to specify the type of clock being used at clockid argument. CLOCK_MONOTONIC and CLOCK_REALTIME are supported. This syscall accepts only 64bit timespec structs.
Types of futex #
A futex can be either private or shared. Private is used for processes that shares the same memory space and the virtual address of the futex will be the same for all processes. This allows for optimizations in the kernel. To use private futexes, it's necessary to specify FUTEX_PRIVATE_FLAG in the futex flag. For processes that doesn't share the same memory space and therefore can have different virtual addresses for the same futex (using, for instance, a file-backed shared memory) requires different internal mechanisms to be get properly enqueued. This is the default behavior, and it works with both private and shared futexes.
Futexes can be of different sizes: 8, 16, 32 or 64 bits. Currently, the only supported one is 32 bit sized futex, and it need to be specified using FUTEX_32 flag.
Live Update uAPI
Peios Kernel / Userspace interfaces / System and device interfaces / Execution and synchronisation
Author: Pasha Tatashin <pasha.tatashin@soleen.com>
ioctl interface #
The IOCTL user-space control interface for the LUO subsystem.
It registers a character device, typically found at /dev/liveupdate,
which allows a userspace agent to manage the LUO state machine and its
associated resources, such as preservable file descriptors.
To ensure that the state machine is controlled by a single entity, access
to this device is exclusive: only one process is permitted to have
/dev/liveupdate open at any given time. Subsequent open attempts will
fail with -EBUSY until the first process closes its file descriptor.
This singleton model simplifies state management by preventing conflicting
commands from multiple userspace agents.
ioctl uAPI #
General ioctl format
The ioctl interface follows a general format to allow for extensibility. Each ioctl is passed in a structure pointer as the argument providing the size of the structure in the first u32. The kernel checks that any structure space beyond what it understands is 0. This allows userspace to use the backward compatible portion while consistently using the newer, larger, structures.
ioctls use a standard meaning for common errnos:
- ENOTTY: The IOCTL number itself is not supported at all
- E2BIG: The IOCTL number is supported, but the provided structure has non-zero in a part the kernel does not understand.
- EOPNOTSUPP: The IOCTL number is supported, and the structure is understood, however a known field has a value the kernel does not understand or support.
- EINVAL: Everything about the IOCTL was understood, but a field is not correct.
- ENOENT: A provided token does not exist.
- ENOMEM: Out of memory.
- EOVERFLOW: Mathematics overflowed.
As well as additional errnos, within specific ioctls.
struct liveupdate_ioctl_create_session #
ioctl(LIVEUPDATE_IOCTL_CREATE_SESSION)
Definition
;
Members
size: Input; sizeof(struct liveupdate_ioctl_create_session)fd: Output; The new file descriptor for the created session.name: Input; A null-terminated string for the session name, max lengthLIVEUPDATE_SESSION_NAME_LENGTHincluding termination character.
Description
Creates a new live update session for managing preserved resources. This ioctl can only be called on the main /dev/liveupdate device.
Return
0 on success, negative error code on failure.
struct liveupdate_ioctl_retrieve_session #
ioctl(LIVEUPDATE_IOCTL_RETRIEVE_SESSION)
Definition
;
Members
size: Input; sizeof(struct liveupdate_ioctl_retrieve_session)fd: Output; The new file descriptor for the retrieved session.name: Input; A null-terminated string identifying the session to retrieve. The name must exactly match the name used when the session was created in the previous kernel.
Description
Retrieves a handle (a new file descriptor) for a preserved session by its name. This is the primary mechanism for a userspace agent to regain control of its preserved resources after a live update.
The userspace application provides the null-terminated name of a session
it created before the live update. If a preserved session with a matching
name is found, the kernel instantiates it and returns a new file descriptor
in the fd field. This new session FD can then be used for all file-specific
operations, such as restoring individual file descriptors with
LIVEUPDATE_SESSION_RETRIEVE_FD.
It is the responsibility of the userspace application to know the names of the sessions it needs to retrieve. If no session with the given name is found, the ioctl will fail with -ENOENT.
This ioctl can only be called on the main /dev/liveupdate device when the system is in the LIVEUPDATE_STATE_UPDATED state.
struct liveupdate_session_preserve_fd #
ioctl(LIVEUPDATE_SESSION_PRESERVE_FD)
Definition
;
Members
size: Input; sizeof(struct liveupdate_session_preserve_fd)fd: Input; The user-space file descriptor to be preserved.token: Input; An opaque, unique token for preserved resource.
Description
Holds parameters for preserving a file descriptor.
User sets the fd field identifying the file descriptor to preserve
(e.g., memfd, kvm, iommufd, VFIO). The kernel validates if this FD type
and its dependencies are supported for preservation. If validation passes,
the kernel marks the FD internally and initiates the process of preparing
its state for saving. The actual snapshotting of the state typically occurs
during the subsequent LIVEUPDATE_IOCTL_PREPARE execution phase, though
some finalization might occur during freeze.
On successful validation and initiation, the kernel uses the token
field with an opaque identifier representing the resource being preserved.
This token confirms the FD is targeted for preservation and is required for
the subsequent LIVEUPDATE_SESSION_RETRIEVE_FD call after the live update.
Return
0 on success (validation passed, preservation initiated), negative error code on failure (e.g., unsupported FD type, dependency issue, validation failed).
struct liveupdate_session_retrieve_fd #
ioctl(LIVEUPDATE_SESSION_RETRIEVE_FD)
Definition
;
Members
size: Input; sizeof(struct liveupdate_session_retrieve_fd)fd: Output; The new file descriptor representing the fully restored kernel resource.token: Input; An opaque, token that was used to preserve the resource.
Description
Retrieve a previously preserved file descriptor.
User sets the token field to the value obtained from a successful
LIVEUPDATE_IOCTL_FD_PRESERVE call before the live update. On success,
the kernel restores the state (saved during the PREPARE/FREEZE phases)
associated with the token and populates the fd field with a new file
descriptor referencing the restored resource in the current (new) kernel.
This operation must be performed before signaling completion via
LIVEUPDATE_IOCTL_FINISH.
Return
0 on success, negative error code on failure (e.g., invalid token).
struct liveupdate_session_finish #
ioctl(LIVEUPDATE_SESSION_FINISH)
Definition
;
Members
size: Input; sizeof(struct liveupdate_session_finish)reserved: Input; Must be zero. Reserved for future use.
Description
Signals the completion of the restoration process for a retrieved session. This is the final operation that should be performed on a session file descriptor after a live update.
This ioctl must be called once all required file descriptors for the session
have been successfully retrieved (using LIVEUPDATE_SESSION_RETRIEVE_FD) and
are fully restored from the userspace and kernel perspective.
Upon success, the kernel releases its ownership of the preserved resources associated with this session. This allows internal resources to be freed, typically by decrementing reference counts on the underlying preserved objects.
If this operation fails, the resources remain preserved in memory. Userspace may attempt to call finish again. The resources will otherwise be reset during the next live update cycle.
Return
0 on success, negative error code on failure.
See Also #
NT synchronization primitive driver
Peios Kernel / Userspace interfaces / System and device interfaces / Execution and synchronisation
This page documents the user-space API for the ntsync driver.
ntsync is a support driver for emulation of NT synchronization primitives by user-space NT emulators. It exists because implementation in user-space, using existing tools, cannot match Windows performance while offering accurate semantics. It is implemented entirely in software, and does not drive any hardware device.
This interface is meant as a compatibility tool only, and should not be used for general synchronization. Instead use generic, versatile interfaces such as futex(2) and poll(2).
Synchronization primitives #
The ntsync driver exposes three types of synchronization primitives: semaphores, mutexes, and events.
A semaphore holds a single volatile 32-bit counter, and a static 32-bit integer denoting the maximum value. It is considered signaled (that is, can be acquired without contention, or will wake up a waiting thread) when the counter is nonzero. The counter is decremented by one when a wait is satisfied. Both the initial and maximum count are established when the semaphore is created.
A mutex holds a volatile 32-bit recursion count, and a volatile 32-bit identifier denoting its owner. A mutex is considered signaled when its owner is zero (indicating that it is not owned). The recursion count is incremented when a wait is satisfied, and ownership is set to the given identifier.
A mutex also holds an internal flag denoting whether its previous owner has died; such a mutex is said to be abandoned. Owner death is not tracked automatically based on thread death, but rather must be communicated using NTSYNC_IOC_MUTEX_KILL. An abandoned mutex is inherently considered unowned.
Except for the "unowned" semantics of zero, the actual value of the owner identifier is not interpreted by the ntsync driver at all. The intended use is to store a thread identifier; however, the ntsync driver does not actually validate that a calling thread provides consistent or unique identifiers.
An event is similar to a semaphore with a maximum count of one. It holds a volatile boolean state denoting whether it is signaled or not. There are two types of events, auto-reset and manual-reset. An auto-reset event is designaled when a wait is satisfied; a manual-reset event is not. The event type is specified when the event is created.
Unless specified otherwise, all operations on an object are atomic and totally ordered with respect to other operations on the same object.
Objects are represented by files. When all file descriptors to an object are closed, that object is deleted.
Char device #
The ntsync driver creates a single char device /dev/ntsync. Each file description opened on the device represents a unique instance intended to back an individual NT virtual machine. Objects created by one ntsync instance may only be used with other objects created by the same instance.
ioctl reference #
All operations on the device are done through ioctls. There are four structures used in ioctl calls:
struct ntsync_sem_args {
__u32 count;
__u32 max;
};
struct ntsync_mutex_args {
__u32 owner;
__u32 count;
};
struct ntsync_event_args {
__u32 signaled;
__u32 manual;
};
struct ntsync_wait_args {
__u64 timeout;
__u64 objs;
__u32 count;
__u32 owner;
__u32 index;
__u32 alert;
__u32 flags;
__u32 pad;
};
Depending on the ioctl, members of the structure may be used as input, output, or not at all.
The ioctls on the device file are as follows:
Create a semaphore object. Takes a pointer to struct ntsync_sem_args, which is used as follows:
|
|
Initial count of the semaphore. |
|
|
Maximum count of the semaphore. |
Fails with EINVAL if count is greater than max. On success, returns a file descriptor the created semaphore.
Create a mutex object. Takes a pointer to struct ntsync_mutex_args, which is used as follows:
|
|
Initial recursion count of the mutex. |
|
|
Initial owner of the mutex. |
If owner is nonzero and count is zero, or if owner is zero and count is nonzero, the function fails with EINVAL. On success, returns a file descriptor the created mutex.
Create an event object. Takes a pointer to struct ntsync_event_args, which is used as follows:
|
|
If nonzero, the event is initially signaled, otherwise nonsignaled. |
|
|
If nonzero, the event is a manual-reset event, otherwise auto-reset. |
On success, returns a file descriptor the created event.
The ioctls on the individual objects are as follows:
Post to a semaphore object. Takes a pointer to a 32-bit integer, which on input holds the count to be added to the semaphore, and on output contains its previous count.
If adding to the semaphore's current count would raise the latter past the semaphore's maximum count, the ioctl fails with EOVERFLOW and the semaphore is not affected. If raising the semaphore's count causes it to become signaled, eligible threads waiting on this semaphore will be woken and the semaphore's count decremented appropriately.
Release a mutex object. Takes a pointer to struct ntsync_mutex_args, which is used as follows:
|
|
Specifies the owner trying to release this mutex. |
|
|
On output, contains the previous recursion count. |
If owner is zero, the ioctl fails with EINVAL. If owner is not the current owner of the mutex, the ioctl fails with EPERM.
The mutex's count will be decremented by one. If decrementing the mutex's count causes it to become zero, the mutex is marked as unowned and signaled, and eligible threads waiting on it will be woken as appropriate.
Signal an event object. Takes a pointer to a 32-bit integer, which on output contains the previous state of the event.
Eligible threads will be woken, and auto-reset events will be designaled appropriately.
Designal an event object. Takes a pointer to a 32-bit integer, which on output contains the previous state of the event.
Wake threads waiting on an event object while leaving it in an unsignaled state. Takes a pointer to a 32-bit integer, which on output contains the previous state of the event.
A pulse operation can be thought of as a set followed by a reset, performed as a single atomic operation. If two threads are waiting on an auto-reset event which is pulsed, only one will be woken. If two threads are waiting a manual-reset event which is pulsed, both will be woken. However, in both cases, the event will be unsignaled afterwards, and a simultaneous read operation will always report the event as unsignaled.
Read the current state of a semaphore object. Takes a pointer to struct ntsync_sem_args, which is used as follows:
|
|
On output, contains the current count of the semaphore. |
|
|
On output, contains the maximum count of the semaphore. |
Read the current state of a mutex object. Takes a pointer to struct ntsync_mutex_args, which is used as follows:
|
|
On output, contains the current owner of the mutex, or zero if the mutex is not currently owned. |
|
|
On output, contains the current recursion count of the mutex. |
If the mutex is marked as abandoned, the function fails with EOWNERDEAD. In this case, count and owner are set to zero.
Read the current state of an event object. Takes a pointer to struct ntsync_event_args, which is used as follows:
|
|
On output, contains the current state of the event. |
|
|
On output, contains 1 if the event is a manual-reset event, and 0 otherwise. |
Mark a mutex as unowned and abandoned if it is owned by the given owner. Takes an input-only pointer to a 32-bit integer denoting the owner. If the owner is zero, the ioctl fails with EINVAL. If the owner does not own the mutex, the function fails with EPERM.
Eligible threads waiting on the mutex will be woken as appropriate (and such waits will fail with EOWNERDEAD, as described below).
Poll on any of a list of objects, atomically acquiring at most one. Takes a pointer to struct ntsync_wait_args, which is used as follows:
|
|
Absolute timeout in nanoseconds. If |
|
|
Pointer to an array of |
|
|
Number of objects specified in the |
|
|
Mutex owner identifier. If any object in |
|
|
On success, contains the index (into |
|
|
Optional event object file descriptor. If nonzero, this specifies an "alert" event object which, if signaled, will terminate the wait. If nonzero, the identifier must point to a valid event. |
|
|
Zero or more flags. Currently the only flag is |
|
|
Unused, must be set to zero. |
This function attempts to acquire one of the given objects. If unable to do so, it sleeps until an object becomes signaled, subsequently acquiring it, or the timeout expires. In the latter case the ioctl fails with ETIMEDOUT. The function only acquires one object, even if multiple objects are signaled.
A semaphore is considered to be signaled if its count is nonzero, and is acquired by decrementing its count by one. A mutex is considered to be signaled if it is unowned or if its owner matches the owner argument, and is acquired by incrementing its recursion count by one and setting its owner to the owner argument. An auto-reset event is acquired by designaling it; a manual-reset event is not affected by acquisition.
Acquisition is atomic and totally ordered with respect to other operations on the same object. If two wait operations (with different owner identifiers) are queued on the same mutex, only one is signaled. If two wait operations are queued on the same semaphore, and a value of one is posted to it, only one is signaled.
If an abandoned mutex is acquired, the ioctl fails with EOWNERDEAD. Although this is a failure return, the function may otherwise be considered successful. The mutex is marked as owned by the given owner (with a recursion count of 1) and as no longer abandoned, and index is still set to the index of the mutex.
The alert argument is an "extra" event which can terminate the wait, independently of all other objects.
It is valid to pass the same object more than once, including by passing the same event in the objs array and in alert. If a wakeup occurs due to that object being signaled, index is set to the lowest index corresponding to that object.
The function may fail with EINTR if a signal is received.
Poll on a list of objects, atomically acquiring all of them. Takes a pointer to struct ntsync_wait_args, which is used identically to NTSYNC_IOC_WAIT_ANY, except that index is always filled with zero on success if not woken via alert.
This function attempts to simultaneously acquire all of the given objects. If unable to do so, it sleeps until all objects become simultaneously signaled, subsequently acquiring them, or the timeout expires. In the latter case the ioctl fails with ETIMEDOUT and no objects are modified.
Objects may become signaled and subsequently designaled (through acquisition by other threads) while this thread is sleeping. Only once all objects are simultaneously signaled does the ioctl acquire them and return. The entire acquisition is atomic and totally ordered with respect to other operations on any of the given objects.
If an abandoned mutex is acquired, the ioctl fails with EOWNERDEAD. Similarly to NTSYNC_IOC_WAIT_ANY, all objects are nevertheless marked as acquired. Note that if multiple mutex objects are specified, there is no way to know which were marked as abandoned.
As with "any" waits, the alert argument is an "extra" event which can terminate the wait. Critically, however, an "all" wait will succeed if all members in objs are signaled, or if alert is signaled. In the latter case index will be set to count. As with "any" waits, if both conditions are filled, the former takes priority, and objects in objs will be acquired.
Unlike NTSYNC_IOC_WAIT_ANY, it is not valid to pass the same object more than once, nor is it valid to pass the same object in objs and in alert. If this is attempted, the function fails with EINVAL.
Restartable Sequences
Peios Kernel / Userspace interfaces / System and device interfaces / Execution and synchronisation
Restartable Sequences allow to register a per thread userspace memory area to be used as an ABI between kernel and userspace for three purposes:
userspace restartable sequences
quick access to read the current CPU number, node ID from userspace
scheduler time slice extensions
Restartable sequences (per-cpu atomics) #
Restartable sequences allow userspace to perform update operations on per-cpu data without requiring heavyweight atomic operations. The actual ABI is unfortunately only available in the code and selftests.
Quick access to CPU number, node ID #
Allows to implement per CPU data efficiently. Documentation is in code and selftests. :(
Scheduler time slice extensions #
This allows a thread to request a time slice extension when it enters a critical section to avoid contention on a resource when the thread is scheduled out inside of the critical section.
The prerequisites for this functionality are:
Enabled in Kconfig
Enabled at boot time (default is enabled)
A rseq userspace pointer has been registered for the thread
The thread has to enable the functionality via prctl(2):
prctl(PR_RSEQ_SLICE_EXTENSION, PR_RSEQ_SLICE_EXTENSION_SET,
PR_RSEQ_SLICE_EXT_ENABLE, 0, 0);
prctl() returns 0 on success or otherwise with the following error codes:
|
Errorcode |
Meaning |
|---|---|
|
EINVAL |
Functionality not available or invalid function arguments. Note: arg4 and arg5 must be zero |
|
ENOTSUPP |
Functionality was disabled on the kernel command line |
|
ENXIO |
Available, but no rseq user struct registered |
The state can be also queried via prctl(2):
prctl(PR_RSEQ_SLICE_EXTENSION, PR_RSEQ_SLICE_EXTENSION_GET, 0, 0, 0);
prctl() returns PR_RSEQ_SLICE_EXT_ENABLE when it is enabled or 0 if disabled. Otherwise it returns with the following error codes:
|
Errorcode |
Meaning |
|---|---|
|
EINVAL |
Functionality not available or invalid function arguments. Note: arg3 and arg4 and arg5 must be zero |
The availability and status is also exposed via the rseq ABI struct flags field via the RSEQ_CS_FLAG_SLICE_EXT_AVAILABLE_BIT and the RSEQ_CS_FLAG_SLICE_EXT_ENABLED_BIT. These bits are read-only for user space and only for informational purposes.
If the mechanism was enabled via prctl(), the thread can request a time slice extension by setting rseq::slice_ctrl::request to 1. If the thread is interrupted and the interrupt results in a reschedule request in the kernel, then the kernel can grant a time slice extension and return to userspace instead of scheduling out. The length of the extension is determined by debugfs:rseq/slice_ext_nsec. The default value is 5 usec; which is the minimum value. It can be incremented to 50 usecs, however doing so can/will affect the minimum scheduling latency.
Any proposed changes to this default will have to come with a selftest and rseq-slice-hist.py output that shows the new value has merrit.
The kernel indicates the grant by clearing rseq::slice_ctrl::request and setting rseq::slice_ctrl::granted to 1. If there is a reschedule of the thread after granting the extension, the kernel clears the granted bit to indicate that to userspace.
If the request bit is still set when the leaving the critical section, userspace can clear it and continue.
If the granted bit is set, then userspace invokes rseq_slice_yield(2) when leaving the critical section to relinquish the CPU. The kernel enforces this by arming a timer to prevent misbehaving userspace from abusing this mechanism.
If both the request bit and the granted bit are false when leaving the critical section, then this indicates that a grant was revoked and no further action is required by userspace.
The required code flow is as follows:
rseq->slice_ctrl.request = 1;
barrier(); // Prevent compiler reordering
critical_section();
barrier(); // Prevent compiler reordering
rseq->slice_ctrl.request = 0;
if (rseq->slice_ctrl.granted)
rseq_slice_yield();
As all of this is strictly CPU local, there are no atomicity requirements. Checking the granted state is racy, but that cannot be avoided at all:
if (rseq->slice_ctrl.granted)
-> Interrupt results in schedule and grant revocation
rseq_slice_yield();
So there is no point in pretending that this might be solved by an atomic operation.
If the thread issues a syscall other than rseq_slice_yield(2) within the granted timeslice extension, the grant is also revoked and the CPU is relinquished immediately when entering the kernel. This is required as syscalls might consume arbitrary CPU time until they reach a scheduling point when the preemption model is either NONE or VOLUNTARY and therefore might exceed the grant by far.
The preferred solution for user space is to use rseq_slice_yield(2) which is side effect free. The support for arbitrary syscalls is required to support onion layer architectured applications, where the code handling the critical section and requesting the time slice extension has no control over the code within the critical section.
The kernel enforces flag consistency and terminates the thread with SIGSEGV if it detects a violation.
unshare system call
Peios Kernel / Userspace interfaces / System and device interfaces / Execution and synchronisation
unshare() separates selected parts of the calling task's context from other
tasks that share them. It does not create a new process or grant native authority.
Document history #
Adapted from Janak Desai's January 2006 design document for the implementation in the Peios kernel. The old proposal's address-space splitting and unimplemented-System-V-semaphore descriptions do not describe this kernel.
Overview #
clone() selects resources to share when creating a task. unshare() lets an
existing task stop sharing selected resources, subject to flag combinations,
task state, namespace configuration and authorization checks. An unshared file
descriptor table still refers to the same open file descriptions: it does not
reopen files, reset their positions or obtain new KACS handle grants.
Private filesystem views #
A private mount namespace permits changes to a task's mount view without necessarily changing the original namespace. Mount propagation settings can still propagate events between namespaces. Creating the namespace and making mounts within it are separate operations with their own authorization.
Peios has a native mount-namespace creation path. When the requested nsproxy
namespace flags select only CLONE_NEWNS, kernel/nsproxy.c does not impose
its generic CAP_SYS_ADMIN gate. Native mount-namespace checks still apply.
Adding another nsproxy namespace type, such as CLONE_NEWNET or CLONE_NEWIPC,
retains that gate, interpreted as enabled SeTcbPrivilege. A new user namespace
does not create native token privileges. See
Peios kernel behaviour.
File tables and address spaces #
CLONE_FILES can copy a shared file descriptor table. CLONE_FS can separate
the root directory, working directory and umask context. In contrast,
CLONE_VM, CLONE_SIGHAND and CLONE_THREAD do not split an actively shared
address space, signal-handler table or thread group. They are accepted only
when the corresponding sharing checks establish there is nothing to split;
otherwise the call fails with EINVAL.
Allocation and lifetime #
The implementation prepares replacement contexts before publishing them to the current task. Allocation can fail. Contexts still shared with other tasks remain alive through their references. Operations must obey the relevant task, filesystem-context, namespace and credential locking rules.
Interface #
int ;
The libc interface returns zero on success, or -1 with errno on failure.
Flags include:
| Flag | Effect or constraint |
|---|---|
CLONE_FILES | Separate the file descriptor table if shared. |
CLONE_FS | Separate filesystem context if needed. |
CLONE_NEWNS | Create a mount namespace; implies CLONE_FS. |
CLONE_NEWUSER | Create a user namespace; implies CLONE_THREAD and CLONE_FS, with user-namespace and single-thread checks. |
CLONE_NEWUTS, CLONE_NEWIPC, CLONE_NEWNET, CLONE_NEWCGROUP | Request the corresponding namespace, subject to configuration and authorization. |
CLONE_NEWPID, CLONE_NEWTIME | Change the namespace context used for subsequent children; these do not move the caller into the new PID/time namespace. |
CLONE_SYSVSEM | Detach from the shared System V semaphore undo list. CLONE_NEWIPC also detaches it. |
CLONE_VM | Implies CLONE_SIGHAND; requires an already single-threaded, unshared context. |
CLONE_SIGHAND | Implies CLONE_THREAD; cannot split a shared signal-handler table. |
CLONE_THREAD | Requires an empty thread group apart from the caller. |
Unknown or incompatible flags and unsupported sharing requests can return
EINVAL. Authorization failures can return EPERM or a native denial such as
EACCES; allocation failures can return ENOMEM. Namespace creation also has
its own configuration, nesting and resource limits, so this is not an exhaustive
error list. UID 0 alone is not the native authorization rule.
Implementation #
ksys_unshare() in kernel/fork.c normalizes implied flags, checks supported
combinations, prepares filesystem/file-table changes, then prepares the user
namespace and nsproxy. Namespace-specific creation code runs its own checks.
The function also prepares credential accounting before publishing new state.
On success it detaches semaphore state when requested, handles shared-memory state for a new IPC namespace, installs the nsproxy, swaps the filesystem and file-table pointers under the required locks, and commits new user-namespace credentials. It then releases old or unused references. Failure paths release prepared state rather than leaving partially installed replacement contexts.
unshare_fs(), unshare_fd(), unshare_userns() and
unshare_nsproxy_namespaces() prepare the relevant changes. Unlike the original
design proposal, CLONE_SYSVSEM is implemented. No helper clones a live shared
address space to implement CLONE_VM unsharing.
Architecture syscall tables expose the existing unshare syscall; adding a
new resource flag does not require a new syscall number.
Validation considerations #
Test actual resource separation, implied flags, invalid combinations, failure cleanup and namespace limits. For file tables, distinguish an independent table from the shared open file descriptions it contains. For Peios, include native authorization denials and the difference between mount-only namespace requests and combined namespace requests. These are review requirements, not a report that this documentation change ran runtime tests.
Unsupported sharing changes #
Splitting a live thread group, shared signal-handler table or shared address
space is not implemented by unshare(). Programs requiring a separate address
space should use an appropriate process-creation interface instead.