Skip to contentSkip to conversation

pin_on_cpu: Introduce thread CPU pinning system call

RFC PATCH In review Mathieu Desnoyers 6 participants 15 messages Jan 21, 2020 – Feb 14, 2020

Subsystems (8)
x86 VFS Kselftest Scheduler +4 more subsystems
lore
Share & tools
lore
#0 lore raw

RFC PATCH 1/1 pin_on_cpu: Introduce thread CPU pinning system call

There is an important use-case which is not possible with the "rseq" (Restartable Sequences) system call, which was left as future work.

That use-case is to modify user-space per-cpu data structures belonging to specific CPUs which may be brought offline and online again by CPU hotplug. This can be used by memory allocators to migrate free memory pools when CPUs are brought offline, or by ring buffer consumers to target specific per-CPU buffers, even when CPUs are brought offline.

A few rather complex prior attempts were made to solve this. Those were based on in-kernel interpreters (cpu_opv, do_on_cpu). That complexity was generally frowned upon, even by their author.

This patch fulfills this use-case in a refreshingly simple way:
it introduces a "pin_on_cpu" system call, which allows user-space threads to pin themselves on a specific CPU (which needs to be present in the thread's allowed cpu mask), and then clear this pinned state.

"But this can already be done with sched_setaffinity", some would rightfully reply. However, there is a significant twist in the way pin_on_cpu deals with CPU hotplug compared to the allowed cpu mask.

When all CPUs part of the thread's allowed cpu mask are offlined, this mask is effectively reset to include all CPUs. This behavior is completely incompatible with modifying per-cpu data structures:
the updates then become racy between concurrent CPUs trying to update the given per-cpu data.

Conversely, all threads pinned on a given CPU with pin_on_cpu are guaranteed to be scheduled on the same runqueue when that CPU is offline. If that CPU is brought back online, the CPU hotplug scheduler hooks are responsible for migrating back the tasks to their pinned CPU.

For instance, this allows implementing this userspace library API for incrementing a per-cpu counter for a specific cpu number received as parameter:

static inline __attribute__((always_inline)) int percpu_addv(intptr_t *v, intptr_t count, int cpu)

{
        int ret;

        ret = rseq_addv(v, count, cpu);
check:
        if (rseq_unlikely(ret)) {
                pin_on_cpu_set(cpu);
                ret = rseq_addv(v, count, percpu_current_cpu());
                pin_on_cpu_clear();
                goto check;
        }
        return 0;
}
Cc Thomas Gleixner <[email protected]>
Cc Joel Fernandes <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Ingo Molnar <[email protected]>
Cc Catalin Marinas <[email protected]>
Cc Dave Watson <[email protected]>
Cc Will Deacon <[email protected]>
Cc Shuah Khan <[email protected]>
Cc Andi Kleen <[email protected]>
Cc "H . Peter Anvin" <[email protected]>
Cc Chris Lameter <[email protected]>
Cc Russell King <[email protected]>
Cc Michael Kerrisk <[email protected]>
Cc "Paul E . McKenney" <[email protected]>
Cc Paul Turner <[email protected]>
Cc Boqun Feng <[email protected]>
Cc Josh Triplett <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Ben Maurer <[email protected]>
Cc Andy Lutomirski <[email protected]>
---
 arch/x86/entry/syscalls/syscall_32.tbl |   1 +
 arch/x86/entry/syscalls/syscall_64.tbl |   1 +
 fs/exec.c                              |   1 +
 include/linux/sched.h                  |   1 +
 include/linux/syscalls.h               |   1 +
 include/uapi/asm-generic/unistd.h      |   5 +-
 include/uapi/linux/sched.h             |   6 +
 init/init_task.c                       |   1 +
 kernel/sched/core.c                    | 321 +++++++++++++++++++++++--
 kernel/sched/deadline.c                |  54 +++--
 kernel/sched/fair.c                    |  19 ++
 kernel/sched/rt.c                      |  15 +-
 kernel/sched/sched.h                   |  28 +++
 kernel/sys_ni.c                        |   1 +
 14 files changed, 413 insertions(+), 42 deletions(-)
arch/x86/entry/syscalls/syscall_32.tbl +1 -0
index 15908eb9b17e..0b1081a9b872 100644
@@ -440,3 +440,4 @@
 433	i386	fspick			sys_fspick			__ia32_sys_fspick
 434	i386	pidfd_open		sys_pidfd_open			__ia32_sys_pidfd_open
 435	i386	clone3			sys_clone3			__ia32_sys_clone3
+436	i386	pin_on_cpu		sys_pin_on_cpu			__ia32_sys_pin_on_cpu
arch/x86/entry/syscalls/syscall_64.tbl +1 -0
index c29976eca4a8..90f9b3cab88d 100644
@@ -357,6 +357,7 @@
 433	common	fspick			__x64_sys_fspick
 434	common	pidfd_open		__x64_sys_pidfd_open
 435	common	clone3			__x64_sys_clone3/ptregs
+436	common	pin_on_cpu		__x64_sys_pin_on_cpu
 
 #
 # x32-specific system call numbers start at 512 to avoid cache impact
fs/exec.c +1 -0
index c27231234764..6d882dbdd1e3 100644
@@ -1827,6 +1827,7 @@ static int __do_execve_file(int fd, struct filename *filename,
 	current->fs->in_exec = 0;
 	current->in_execve = 0;
 	rseq_execve(current);
+	current->pinned_cpu = -1;
 	acct_update_integrals(current);
 	task_numa_free(current, false);
 	free_bprm(bprm);
include/linux/sched.h +1 -0
index 7f0bb6fff27c..ac0cac7b8d1d 100644
@@ -651,6 +651,7 @@ struct task_struct {
 	/* Current CPU: */
 	unsigned int			cpu;
 #endif
+	int				pinned_cpu;
 	unsigned int			wakee_flips;
 	unsigned long			wakee_flip_decay_ts;
 	struct task_struct		*last_wakee;
include/linux/syscalls.h +1 -0
index be0d0cf788ba..46fee5af99e3 100644
@@ -1000,6 +1000,7 @@ asmlinkage long sys_fspick(int dfd, const char __user *path, unsigned int flags)
 asmlinkage long sys_pidfd_send_signal(int pidfd, int sig,
 				       siginfo_t __user *info,
 				       unsigned int flags);
+asmlinkage long sys_pin_on_cpu(int cmd, int flags, int cpu);
 
 /*
  * Architecture-specific system calls
include/uapi/asm-generic/unistd.h +4 -1
index 1fc8faa6e973..43b0c956cc3c 100644
@@ -851,8 +851,11 @@ __SYSCALL(__NR_pidfd_open, sys_pidfd_open)
 __SYSCALL(__NR_clone3, sys_clone3)
 #endif
 
+#define __NR_pin_on_cpu 436
+__SYSCALL(__NR_pin_on_cpu, sys_pin_on_cpu)
+
 #undef __NR_syscalls
-#define __NR_syscalls 436
+#define __NR_syscalls 437
 
 /*
  * 32 bit systems traditionally used different
include/uapi/linux/sched.h +6 -0
index 25b4fa00bad1..590cdc613698 100644
@@ -114,4 +114,10 @@ struct clone_args {
 			 SCHED_FLAG_KEEP_ALL		| \
 			 SCHED_FLAG_UTIL_CLAMP)
 
+enum pin_on_cpu_cmd {
+	PIN_ON_CPU_CMD_QUERY				= 0,
+	PIN_ON_CPU_CMD_SET				= (1 << 0),
+	PIN_ON_CPU_CMD_CLEAR				= (1 << 1),
+};
+
 #endif /* _UAPI_LINUX_SCHED_H */
init/init_task.c +1 -0
index 9e5cbe5eab7b..9aabce589cc7 100644
@@ -88,6 +88,7 @@ struct task_struct init_task
 	.tasks		= LIST_HEAD_INIT(init_task.tasks),
 #ifdef CONFIG_SMP
 	.pushable_tasks	= PLIST_NODE_INIT(init_task.pushable_tasks, MAX_PRIO),
+	.pinned_cpu	= -1,
 #endif
 #ifdef CONFIG_CGROUP_SCHED
 	.sched_task_group = &root_task_group,
kernel/sched/core.c +304 -17

399 lines not on this page · raw message

kernel/sched/deadline.c +34 -20

74 lines not on this page · raw message

kernel/sched/fair.c +19 -0
index 69a81a5709ff..e96ae1ce9829 100644
@@ -7223,6 +7223,25 @@ int can_migrate_task(struct task_struct *p, struct lb_env *env)
 
 	lockdep_assert_held(&env->src_rq->lock);
 
+	if (is_pinned_task(p)) {
+		if (task_running(env->src_rq, p)) {
+			schedstat_inc(p->se.statistics.nr_failed_migrations_running);
+			return 0;
+		}
+		if (cpu_online(p->pinned_cpu)) {
+			if (env->dst_cpu == p->pinned_cpu)
+				return 1;
+			else
+				return 0;
+		} else {
+			if (env->dst_cpu ==
+			    pinned_cpu_offline_offload(p))
+				return 1;
+			else
+				return 0;
+		}
+	}
+
 	/*
 	 * We do not migrate tasks that are:
 	 * 1) throttled_lb_pair, or
kernel/sched/rt.c +11 -4
index 9b8adc01be3d..2774311e5750 100644
@@ -1600,9 +1600,15 @@ static void put_prev_task_rt(struct rq *rq, struct task_struct *p)
 
 static int pick_rt_task(struct rq *rq, struct task_struct *p, int cpu)
 {
-	if (!task_running(rq, p) &&
-	    cpumask_test_cpu(cpu, p->cpus_ptr))
-		return 1;
+	if (!task_running(rq, p)) {
+		if (is_pinned_task(p)) {
+			if (allowed_pinned_cpu(p, cpu))
+				return 1;
+		} else {
+			if (cpumask_test_cpu(cpu, p->cpus_ptr))
+				return 1;
+		}
+	}
 
 	return 0;
 }
@@ -1738,7 +1744,8 @@ static struct rq *find_lock_lowest_rq(struct task_struct *task, struct rq *rq)
 			 * Also make sure that it wasn't scheduled on its rq.
 			 */
 			if (unlikely(task_rq(task) != rq ||
-				     !cpumask_test_cpu(lowest_rq->cpu, task->cpus_ptr) ||
+				     (is_pinned_task(task) && !allowed_pinned_cpu(task, lowest_rq->cpu)) ||
+				     (!is_pinned_task(task) && !cpumask_test_cpu(lowest_rq->cpu, task->cpus_ptr)) ||
 				     task_running(rq, task) ||
 				     !rt_task(task) ||
 				     !task_on_rq_queued(task))) {
kernel/sched/sched.h +28 -0
index 49ed949f850c..922bc618cc87 100644
@@ -187,6 +187,34 @@ static inline int task_has_dl_policy(struct task_struct *p)
 	return dl_policy(p->policy);
 }
 
+/*
+ * All tasks which require to be pinned on offlined CPUs are sent
+ * to runqueue of the first online CPU.
+ */
+static inline bool is_pinned_task(struct task_struct *p)
+{
+	return p->pinned_cpu >= 0;
+}
+
+static inline int pinned_cpu_offline_offload(struct task_struct *p)
+{
+	return cpumask_first(cpu_online_mask);
+}
+
+static inline bool allowed_pinned_cpu(struct task_struct *p, int cpu)
+{
+	if (!cpu_possible(cpu))
+		return false;
+	if (cpu_online(p->pinned_cpu)) {
+		if (p->pinned_cpu == cpu)
+			return true;
+	} else {
+		if (cpu == pinned_cpu_offline_offload(p))
+			return true;
+	}
+	return false;
+}
+
 #define cap_scale(v, s) ((v)*(s) >> SCHED_CAPACITY_SHIFT)
 
 /*
kernel/sys_ni.c +1 -0
index 34b76895b81e..7e5192cd8d9d 100644
@@ -449,3 +449,4 @@ COND_SYSCALL(setuid16);
 
 /* restartable sequence */
 COND_SYSCALL(rseq);
+COND_SYSCALL(pin_on_cpu);
Signature · 1 line
2.17.1
#1 lore raw
Quoted 20 lines · Mathieu Desnoyers

There is an important use-case which is not possible with the "rseq" (Restartable Sequences) system call, which was left as future work.

That use-case is to modify user-space per-cpu data structures belonging to specific CPUs which may be brought offline and online again by CPU hotplug. This can be used by memory allocators to migrate free memory pools when CPUs are brought offline, or by ring buffer consumers to target specific per-CPU buffers, even when CPUs are brought offline.

A few rather complex prior attempts were made to solve this. Those were based on in-kernel interpreters (cpu_opv, do_on_cpu). That complexity was generally frowned upon, even by their author.

This patch fulfills this use-case in a refreshingly simple way:
it introduces a "pin_on_cpu" system call, which allows user-space threads to pin themselves on a specific CPU (which needs to be present in the thread's allowed cpu mask), and then clear this pinned state.

[...]

Quoted 6 lines

For instance, this allows implementing this userspace library API for incrementing a per-cpu counter for a specific cpu number received as parameter:

static inline __attribute__((always_inline)) int percpu_addv(intptr_t *v, intptr_t count, int cpu)

Quoted 13 lines
{
        int ret;

        ret = rseq_addv(v, count, cpu);
check:
        if (rseq_unlikely(ret)) {
                pin_on_cpu_set(cpu);
                ret = rseq_addv(v, count, percpu_current_cpu());
                pin_on_cpu_clear();
                goto check;
        }
        return 0;
}

What does userspace have to do if the set of allowed CPUs switches all the time? For example, on Android, if you first open Chrome and then look at its allowed CPUs, Chrome is allowed to use all CPU cores because it's running in the foreground:

walleye:/ # ps -AZ | grep 'android.chrome$' u:r:untrusted_app:s0:c145,c256,c512,c768 u0_a145 7845 805 1474472 197868 SyS_epoll_wait f09c0194 S com.android.chrome walleye:/ # grep cpuset /proc/7845/cgroup; grep Cpus_allowed_list /proc/7845/status
3:cpuset:/top-app
Cpus_allowed_list: 0-7

But if you then switch to the home screen, the application is moved into a different cgroup, and is restricted to two CPU cores:

walleye:/ # grep cpuset /proc/7845/cgroup; grep Cpus_allowed_list /proc/7845/status
3:cpuset:/background
Cpus_allowed_list: 0-1

At the same time, I also wonder whether it is a good idea to allow userspace to stay active on a CPU even after the task has been told to move to another CPU core - that's probably not exactly a big deal, but seems suboptimal to me.

I'm wondering whether it might be possible to rework this mechanism such that, instead of moving the current task onto a target CPU, it prevents all *other* threads of the current process from running on that CPU (either entirely or in user mode). That might be the easiest way to take care of issues like CPU hotplugging and changing cpusets all at once? The only potential issue I see with that approach would be that you wouldn't be able to use it for inter-process communication; and I have no idea whether this would be good or bad performance-wise.

#2 lore raw
Quoted 56 lines · ----- On Jan 21, 2020, at 12:20 PM, Jann Horn [email protected] wrote:
Quoted 20 lines · Mathieu Desnoyers

There is an important use-case which is not possible with the "rseq" (Restartable Sequences) system call, which was left as future work.

That use-case is to modify user-space per-cpu data structures belonging to specific CPUs which may be brought offline and online again by CPU hotplug. This can be used by memory allocators to migrate free memory pools when CPUs are brought offline, or by ring buffer consumers to target specific per-CPU buffers, even when CPUs are brought offline.

A few rather complex prior attempts were made to solve this. Those were based on in-kernel interpreters (cpu_opv, do_on_cpu). That complexity was generally frowned upon, even by their author.

This patch fulfills this use-case in a refreshingly simple way:
it introduces a "pin_on_cpu" system call, which allows user-space threads to pin themselves on a specific CPU (which needs to be present in the thread's allowed cpu mask), and then clear this pinned state.

[...]

Quoted 6 lines

For instance, this allows implementing this userspace library API for incrementing a per-cpu counter for a specific cpu number received as parameter:

static inline __attribute__((always_inline)) int percpu_addv(intptr_t *v, intptr_t count, int cpu)

Quoted 13 lines
{
        int ret;

        ret = rseq_addv(v, count, cpu);
check:
        if (rseq_unlikely(ret)) {
                pin_on_cpu_set(cpu);
                ret = rseq_addv(v, count, percpu_current_cpu());
                pin_on_cpu_clear();
                goto check;
        }
        return 0;
}

What does userspace have to do if the set of allowed CPUs switches all the time? For example, on Android, if you first open Chrome and then look at its allowed CPUs, Chrome is allowed to use all CPU cores because it's running in the foreground:

walleye:/ # ps -AZ | grep 'android.chrome$' u:r:untrusted_app:s0:c145,c256,c512,c768 u0_a145 7845 805 1474472 197868 SyS_epoll_wait f09c0194 S com.android.chrome walleye:/ # grep cpuset /proc/7845/cgroup; grep Cpus_allowed_list /proc/7845/status
3:cpuset:/top-app
Cpus_allowed_list: 0-7

Quoted 7 lines

But if you then switch to the home screen, the application is moved into a different cgroup, and is restricted to two CPU cores:

walleye:/ # grep cpuset /proc/7845/cgroup; grep Cpus_allowed_list /proc/7845/status
3:cpuset:/background
Cpus_allowed_list: 0-1

Then at that point, pin_on_cpu() would only be allowed to pin on CPUs 0 and 1.

Quoted 4 lines

At the same time, I also wonder whether it is a good idea to allow userspace to stay active on a CPU even after the task has been told to move to another CPU core - that's probably not exactly a big deal, but seems suboptimal to me.

Do you mean the following scenario for a given task ?

1) set affinity to CPU 0,1,2
2) pin on CPU 2
3) set affinity to CPU 0,1

In the patch I propose here, step (3) is forbidden by this added check in __set_cpus_allowed_ptr, which is used by sched_setaffinity(2):

+ /* Prevent removing the currently pinned CPU from the allowed cpu mask. */
+ if (is_pinned_task(p) && !cpumask_test_cpu(p->pinned_cpu, new_mask)) {
+ ret = -EINVAL;
+ goto out;
+ }

Quoted 9 lines

I'm wondering whether it might be possible to rework this mechanism such that, instead of moving the current task onto a target CPU, it prevents all *other* threads of the current process from running on that CPU (either entirely or in user mode). That might be the easiest way to take care of issues like CPU hotplugging and changing cpusets all at once? The only potential issue I see with that approach would be that you wouldn't be able to use it for inter-process communication; and I have no idea whether this would be good or bad performance-wise.

Firstly, inter-process communication over shared memory is one of my use-cases (for lttng-ust's ring buffer).

I'm not convinced that applying constraints on all other threads belonging to the current process would be easier or faster than migrating the current thread over to the target CPU. I'm unsure how those additional constraints would fit with other threads already having their own cpu affinity masks (which could generate an empty cpumask by adding an extra constraint).

Thanks for the feedback!

Mathieu

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
http://www.efficios.com
#3 lore raw
Quoted 62 lines · Mathieu Desnoyers
Quoted 59 lines · ----- On Jan 21, 2020, at 12:20 PM, Jann Horn [email protected] wrote:
Quoted 20 lines · Mathieu Desnoyers

There is an important use-case which is not possible with the "rseq" (Restartable Sequences) system call, which was left as future work.

That use-case is to modify user-space per-cpu data structures belonging to specific CPUs which may be brought offline and online again by CPU hotplug. This can be used by memory allocators to migrate free memory pools when CPUs are brought offline, or by ring buffer consumers to target specific per-CPU buffers, even when CPUs are brought offline.

A few rather complex prior attempts were made to solve this. Those were based on in-kernel interpreters (cpu_opv, do_on_cpu). That complexity was generally frowned upon, even by their author.

This patch fulfills this use-case in a refreshingly simple way:
it introduces a "pin_on_cpu" system call, which allows user-space threads to pin themselves on a specific CPU (which needs to be present in the thread's allowed cpu mask), and then clear this pinned state.

[...]

Quoted 6 lines

For instance, this allows implementing this userspace library API for incrementing a per-cpu counter for a specific cpu number received as parameter:

static inline __attribute__((always_inline)) int percpu_addv(intptr_t *v, intptr_t count, int cpu)

Quoted 13 lines
{
        int ret;

        ret = rseq_addv(v, count, cpu);
check:
        if (rseq_unlikely(ret)) {
                pin_on_cpu_set(cpu);
                ret = rseq_addv(v, count, percpu_current_cpu());
                pin_on_cpu_clear();
                goto check;
        }
        return 0;
}

What does userspace have to do if the set of allowed CPUs switches all the time? For example, on Android, if you first open Chrome and then look at its allowed CPUs, Chrome is allowed to use all CPU cores because it's running in the foreground:

walleye:/ # ps -AZ | grep 'android.chrome$' u:r:untrusted_app:s0:c145,c256,c512,c768 u0_a145 7845 805 1474472 197868 SyS_epoll_wait f09c0194 S com.android.chrome walleye:/ # grep cpuset /proc/7845/cgroup; grep Cpus_allowed_list /proc/7845/status
3:cpuset:/top-app
Cpus_allowed_list: 0-7

But if you then switch to the home screen, the application is moved into a different cgroup, and is restricted to two CPU cores:

Quoted 7 lines
Quoted 4 lines

walleye:/ # grep cpuset /proc/7845/cgroup; grep Cpus_allowed_list /proc/7845/status
3:cpuset:/background
Cpus_allowed_list: 0-1

Then at that point, pin_on_cpu() would only be allowed to pin on CPUs 0 and 1.

Which means that you can't actually reliably use pin_on_cpu_set() to manipulate percpu data structures since you have to call it with the assumption that it might randomly fail at any time, right? And then userspace needs to code a fallback path that somehow halts all the threads with thread-directed signals or something? Especially if the task trying to use pin_on_cpu_set() isn't allowed to pin to the target CPU, but all the other tasks using the shared data structure are allowed to do that. Or if the CPU you want to pin to is always removed from your affinity mask immediately before pin_on_cpu_set() and added back immediately afterwards.

Quoted 14 lines
Quoted 4 lines

At the same time, I also wonder whether it is a good idea to allow userspace to stay active on a CPU even after the task has been told to move to another CPU core - that's probably not exactly a big deal, but seems suboptimal to me.

Do you mean the following scenario for a given task ?

1) set affinity to CPU 0,1,2
2) pin on CPU 2
3) set affinity to CPU 0,1

In the patch I propose here, step (3) is forbidden by this added check in __set_cpus_allowed_ptr, which is used by sched_setaffinity(2):

kernel/sched/core.c static int __set_cpus_allowed_ptr(struct task_struct *p, · line 1676

Quoted 5 lines
kernel/sched/core.c +5 -0
+       /* Prevent removing the currently pinned CPU from the allowed cpu mask. */
+       if (is_pinned_task(p) && !cpumask_test_cpu(p->pinned_cpu, new_mask)) {
+               ret = -EINVAL;
+               goto out;
+       }

How does that interact with things like cgroups? What happens when root tries to move a process from the cpuset:/top-app cgroup to the cpuset:/background cgroup? Does that also just throw an error code?

Quoted 10 lines
Quoted 9 lines

I'm wondering whether it might be possible to rework this mechanism such that, instead of moving the current task onto a target CPU, it prevents all *other* threads of the current process from running on that CPU (either entirely or in user mode). That might be the easiest way to take care of issues like CPU hotplugging and changing cpusets all at once? The only potential issue I see with that approach would be that you wouldn't be able to use it for inter-process communication; and I have no idea whether this would be good or bad performance-wise.

Quoted 8 lines

Firstly, inter-process communication over shared memory is one of my use-cases (for lttng-ust's ring buffer).

I'm not convinced that applying constraints on all other threads belonging to the current process would be easier or faster than migrating the current thread over to the target CPU. I'm unsure how those additional constraints would fit with other threads already having their own cpu affinity masks (which could generate an empty cpumask by adding an extra constraint).

Hm - is an empty cpumask a problem here? If one task is in the middle of a critical section for performing maintenance on a percpu data structure, isn't it a nice design property to exclude concurrent access from other tasks to that data structure automatically (by preventing those tasks by running on that CPU)? That way the (presumably rarely-executed) update path doesn't have to be rseq-reentrancy-safe.

#4 lore raw
Quoted 69 lines · ----- On Jan 21, 2020, at 3:35 PM, Jann Horn [email protected] wrote:
Quoted 67 lines · Mathieu Desnoyers
Quoted 63 lines · ----- On Jan 21, 2020, at 12:20 PM, Jann Horn [email protected] wrote:
Quoted 20 lines · Mathieu Desnoyers

There is an important use-case which is not possible with the "rseq" (Restartable Sequences) system call, which was left as future work.

That use-case is to modify user-space per-cpu data structures belonging to specific CPUs which may be brought offline and online again by CPU hotplug. This can be used by memory allocators to migrate free memory pools when CPUs are brought offline, or by ring buffer consumers to target specific per-CPU buffers, even when CPUs are brought offline.

A few rather complex prior attempts were made to solve this. Those were based on in-kernel interpreters (cpu_opv, do_on_cpu). That complexity was generally frowned upon, even by their author.

This patch fulfills this use-case in a refreshingly simple way:
it introduces a "pin_on_cpu" system call, which allows user-space threads to pin themselves on a specific CPU (which needs to be present in the thread's allowed cpu mask), and then clear this pinned state.

[...]

Quoted 6 lines

For instance, this allows implementing this userspace library API for incrementing a per-cpu counter for a specific cpu number received as parameter:

static inline __attribute__((always_inline)) int percpu_addv(intptr_t *v, intptr_t count, int cpu)

Quoted 13 lines
{
        int ret;

        ret = rseq_addv(v, count, cpu);
check:
        if (rseq_unlikely(ret)) {
                pin_on_cpu_set(cpu);
                ret = rseq_addv(v, count, percpu_current_cpu());
                pin_on_cpu_clear();
                goto check;
        }
        return 0;
}

What does userspace have to do if the set of allowed CPUs switches all the time? For example, on Android, if you first open Chrome and then look at its allowed CPUs, Chrome is allowed to use all CPU cores because it's running in the foreground:

walleye:/ # ps -AZ | grep 'android.chrome$' u:r:untrusted_app:s0:c145,c256,c512,c768 u0_a145 7845 805 1474472 197868 SyS_epoll_wait f09c0194 S com.android.chrome walleye:/ # grep cpuset /proc/7845/cgroup; grep Cpus_allowed_list /proc/7845/status
3:cpuset:/top-app
Cpus_allowed_list: 0-7

But if you then switch to the home screen, the application is moved into a different cgroup, and is restricted to two CPU cores:

walleye:/ # grep cpuset /proc/7845/cgroup; grep Cpus_allowed_list /proc/7845/status
3:cpuset:/background
Cpus_allowed_list: 0-1

Quoted 6 lines
Quoted 2 lines

Then at that point, pin_on_cpu() would only be allowed to pin on CPUs 0 and 1.

Which means that you can't actually reliably use pin_on_cpu_set() to manipulate percpu data structures since you have to call it with the assumption that it might randomly fail at any time, right?

Only if the cpu affinity of the thread is being changed concurrently by another thread which is a possibility in some applications, indeed.

Quoted 3 lines

And then
userspace needs to code a fallback path that somehow halts all the threads with thread-directed signals or something?

The example use of pin_on_cpu() did not include handling of the return value in that case (-1, errno=EINVAL) for conciseness. But yes, the application would have to handle this.

It's not so different from error handling which is required when using sched_setaffinity(), which can fail with -1, errno=EINVAL in the following scenario:

EINVAL The affinity bit mask mask contains no processors that are cur‐
rently physically on the system and permitted to the thread according to any restrictions that may be imposed by the "cpuset" mechanism described in cpuset(7).

Quoted 5 lines

Especially if the task trying to use pin_on_cpu_set() isn't allowed to pin to the target CPU, but all the other tasks using the shared data structure are allowed to do that. Or if the CPU you want to pin to is always removed from your affinity mask immediately before pin_on_cpu_set() and added back immediately afterwards.

I am tempted to state that using pin_on_cpu() targeting a disallowed cpu should be considered a programming error and handled accordingly by the application.

Quoted 22 lines
Quoted 17 lines
Quoted 5 lines

At the same time, I also wonder whether it is a good idea to allow userspace to stay active on a CPU even after the task has been told to move to another CPU core - that's probably not exactly a big deal, but seems suboptimal to me.

Do you mean the following scenario for a given task ?

1) set affinity to CPU 0,1,2
2) pin on CPU 2
3) set affinity to CPU 0,1

In the patch I propose here, step (3) is forbidden by this added check in __set_cpus_allowed_ptr, which is used by sched_setaffinity(2):

+ /* Prevent removing the currently pinned CPU from the allowed cpu mask.
*/

kernel/sched/core.c static int __set_cpus_allowed_ptr(struct task_struct *p, · line 1676

Quoted 4 lines
kernel/sched/core.c +4 -0
+       if (is_pinned_task(p) && !cpumask_test_cpu(p->pinned_cpu, new_mask)) {
+               ret = -EINVAL;
+               goto out;
+       }
Quoted 3 lines

How does that interact with things like cgroups? What happens when root tries to move a process from the cpuset:/top-app cgroup to the cpuset:/background cgroup? Does that also just throw an error code?

Looking at kernel/cgroup/cpuset.c use of set_cpus_allowed_ptr(), either it:

A) silently ignores the error (3 instances),
or
B) triggers a WARN_ON_ONCE() (1 instance).

So yeah, that cgroup code seems rather optimistic that this operation should always succeed (?!?)

I can say up front I am not entirely sure what's the best way to proceed here. Either sched_setaffinity and cgroup can fail if trying to remove a CPU from affinity mask while the task is pinned, or we let them succeed and leave the task running on the pinned CPU anyway, or any better idea ?

Quoted 20 lines
Quoted 11 lines
Quoted 10 lines

I'm wondering whether it might be possible to rework this mechanism such that, instead of moving the current task onto a target CPU, it prevents all *other* threads of the current process from running on that CPU (either entirely or in user mode). That might be the easiest way to take care of issues like CPU hotplugging and changing cpusets all at once? The only potential issue I see with that approach would be that you wouldn't be able to use it for inter-process communication; and I have no idea whether this would be good or bad performance-wise.

Quoted 8 lines

Firstly, inter-process communication over shared memory is one of my use-cases (for lttng-ust's ring buffer).

I'm not convinced that applying constraints on all other threads belonging to the current process would be easier or faster than migrating the current thread over to the target CPU. I'm unsure how those additional constraints would fit with other threads already having their own cpu affinity masks (which could generate an empty cpumask by adding an extra constraint).

Quoted 7 lines

Hm - is an empty cpumask a problem here? If one task is in the middle of a critical section for performing maintenance on a percpu data structure, isn't it a nice design property to exclude concurrent access from other tasks to that data structure automatically (by preventing those tasks by running on that CPU)? That way the (presumably rarely-executed) update path doesn't have to be rseq-reentrancy-safe.

Given we already have rseq, simply using it to protect against other threads trying to touch the same per-cpu data seems rather more lightweight than to try to exclude all other threads from that CPU for a possibly unbounded amount of time.

Allowing a completely empty cpumask could effectively allow those critical sections to prevent execution of possibly higher priority threads on the system, which ends up being the definition of a priority inversion, which I'd like to avoid.

Thanks,

Mathieu

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

These scenarios are all pretty complex and will be difficult to understand for the user of these APIs.

I think the easiest solution (and most comprehensible) is for the user space process that does per cpu operations to get some sort of signal. If its not able to handle that then terminate it. The code makes a basic assumption after all that the process is running on a specific cpu. If this is no longer the case then its better to abort if the process cannot handle moving to a different processor.

#6 lore raw
Quoted 9 lines · ----- On Jan 21, 2020, at 4:44 PM, Chris Lameter…

These scenarios are all pretty complex and will be difficult to understand for the user of these APIs.

I think the easiest solution (and most comprehensible) is for the user space process that does per cpu operations to get some sort of signal. If its not able to handle that then terminate it. The code makes a basic assumption after all that the process is running on a specific cpu. If this is no longer the case then its better to abort if the process cannot handle moving to a different processor.

The point of pin_on_cpu() is to allow threads to access per-cpu data structures belonging to a given CPU even if they cannot run on that CPU (because it is offline).

I am not sure what scenario your signal delivery proposal aims to cover.

Just to try to put this into the context of a specific scenario to see if I understand your point, is the following what you have in mind ?

1. Thread A issues pin_on_cpu(5),
2. Thread B issues sched_setaffinity removing cpu 5 from thread A's affinity mask,
3. Noticing that it would generate an invalid combination, rather than failing sched_setaffinity, it would send a SIGSEGV (or other) signal to thread A.

Or so you have something entirely different in mind ?

Thanks,

Mathieu

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
http://www.efficios.com
#7 lore raw
Quoted 21 lines · Mathieu Desnoyers
Quoted 9 lines · ----- On Jan 21, 2020, at 4:44 PM, Chris Lameter…

These scenarios are all pretty complex and will be difficult to understand for the user of these APIs.

I think the easiest solution (and most comprehensible) is for the user space process that does per cpu operations to get some sort of signal. If its not able to handle that then terminate it. The code makes a basic assumption after all that the process is running on a specific cpu. If this is no longer the case then its better to abort if the process cannot handle moving to a different processor.

The point of pin_on_cpu() is to allow threads to access per-cpu data structures belonging to a given CPU even if they cannot run on that CPU (because it is offline).

I am not sure what scenario your signal delivery proposal aims to cover.

Just to try to put this into the context of a specific scenario to see if I understand your point, is the following what you have in mind ?

Quoted 9 lines

1. Thread A issues pin_on_cpu(5),
2. Thread B issues sched_setaffinity removing cpu 5 from thread A's affinity mask,
3. Noticing that it would generate an invalid combination, rather than failing sched_setaffinity, it would send a SIGSEGV (or other) signal to thread A.

Or so you have something entirely different in mind ?

I would agree that this seems like the only sane option, or you will be in a world of hurt because of conflicting semantics. It is not just offlining, but what happens if a policy manager calls sched_setaffinity() on another thread -- and now the universe breaks because a library is updated to use this new system call which collides with the expectations of the policy manager.

There doesn't seem to be any way to get this to be a local event which doesn't break assumptions elsewhere in the system without making this an abort event of some type. However, signals are painful in their own right, mostly because of the lack of any infrastructure for allocating signals to libraries in user space. I was actually thinking about exactly that issue just this weekend.

-hpa

#8 lore raw

* H. Peter Anvin:

Quoted 32 lines · Mathieu Desnoyers
Quoted 21 lines
Quoted 9 lines · ----- On Jan 21, 2020, at 4:44 PM, Chris Lameter…

These scenarios are all pretty complex and will be difficult to understand for the user of these APIs.

I think the easiest solution (and most comprehensible) is for the user space process that does per cpu operations to get some sort of signal. If its not able to handle that then terminate it. The code makes a basic assumption after all that the process is running on a specific cpu. If this is no longer the case then its better to abort if the process cannot handle moving to a different processor.

The point of pin_on_cpu() is to allow threads to access per-cpu data structures belonging to a given CPU even if they cannot run on that CPU (because it is offline).

I am not sure what scenario your signal delivery proposal aims to cover.

Just to try to put this into the context of a specific scenario to see if I understand your point, is the following what you have in mind ?

Quoted 9 lines

1. Thread A issues pin_on_cpu(5),
2. Thread B issues sched_setaffinity removing cpu 5 from thread A's affinity mask,
3. Noticing that it would generate an invalid combination, rather than failing sched_setaffinity, it would send a SIGSEGV (or other) signal to thread A.

Or so you have something entirely different in mind ?

Quoted 6 lines

I would agree that this seems like the only sane option, or you will be in a world of hurt because of conflicting semantics. It is not just offlining, but what happens if a policy manager calls sched_setaffinity() on another thread -- and now the universe breaks because a library is updated to use this new system call which collides with the expectations of the policy manager.

Yes, this new interface seems fundamentally incompatible with how affinity masks are changed today.

Would it be possible to make pin_on_cpu_set to use fallback synchronization via a futex if the CPU cannot be acquired by running on it? The rseq section would need to check the futex as well, but would not have to acquire it.

Thanks,
Florian

#9 lore raw
Quoted 41 lines · ----- On Jan 23, 2020, at 3:19 AM, Florian Weimer…

* H. Peter Anvin:

Quoted 32 lines · Mathieu Desnoyers
Quoted 21 lines
Quoted 9 lines · ----- On Jan 21, 2020, at 4:44 PM, Chris Lameter…

These scenarios are all pretty complex and will be difficult to understand for the user of these APIs.

I think the easiest solution (and most comprehensible) is for the user space process that does per cpu operations to get some sort of signal. If its not able to handle that then terminate it. The code makes a basic assumption after all that the process is running on a specific cpu. If this is no longer the case then its better to abort if the process cannot handle moving to a different processor.

The point of pin_on_cpu() is to allow threads to access per-cpu data structures belonging to a given CPU even if they cannot run on that CPU (because it is offline).

I am not sure what scenario your signal delivery proposal aims to cover.

Just to try to put this into the context of a specific scenario to see if I understand your point, is the following what you have in mind ?

Quoted 9 lines

1. Thread A issues pin_on_cpu(5),
2. Thread B issues sched_setaffinity removing cpu 5 from thread A's affinity mask,
3. Noticing that it would generate an invalid combination, rather than failing sched_setaffinity, it would send a SIGSEGV (or other) signal to thread A.

Or so you have something entirely different in mind ?

Quoted 6 lines

I would agree that this seems like the only sane option, or you will be in a world of hurt because of conflicting semantics. It is not just offlining, but what happens if a policy manager calls sched_setaffinity() on another thread -- and now the universe breaks because a library is updated to use this new system call which collides with the expectations of the policy manager.

Quoted 7 lines

Yes, this new interface seems fundamentally incompatible with how affinity masks are changed today.

Would it be possible to make pin_on_cpu_set to use fallback synchronization via a futex if the CPU cannot be acquired by running on it? The rseq section would need to check the futex as well, but would not have to acquire it.

I would really prefer to avoid adding any "mutual-exclusion-based" locking to rseq, because it would then remove lock-freedom guarantees, which are really useful when designing data structures shared across processes over shared memory. Also, I would prefer to avoid adding additional load and comparisons to the rseq fast-path, because those quickly add up in terms of overhead compared to the "basic" fast-path.

It brings an interesting idea to the table though. Let's assume for now that the only intended use of pin_on_cpu(2) would be to allow rseq(2) critical sections to update per-cpu data on specific cpu number targets. In fact, considering that userspace can be preempted at any point, we still need a mechanism to guarantee atomicity with respect to other threads running on the same runqueue, which rseq(2) provides. Therefore, that assumption does not appear too far-fetched.

There are 2 scenarios we need to consider here:

A) pin_on_cpu(2) targets a CPU which is not part of the affinity mask.

This case is easy: pin_on_cpu can return an error, and the caller needs to act accordingly (e.g. figure out that this is a design error and report it, or decide that it really did not want to touch that per-cpu data that badly and make the entire process fall-back to a mechanism which does not use per-cpu data at all from that point onwards)

B) pin_on_cpu(2) targets a CPU part of affinity mask, which is then removed by cpuset or sched_setaffinity before unpin.

When the pinned cpu is removed from the affinity mask, we make sure the target task enters the kernel (or is already in the kernel) so it can update __rseq_abi.cpu_id when returning to user-space setting it to:

__rseq_abi.cpu_id = RSEQ_CPU_ID_PINNED_DISALLOWED (= -3)

Which would ensure that all rseq critical sections fail. It would be restored to the proper CPU number value when unpinning.

This would allow us to ensure user-space does not update the per-cpu data while it is in the wrong state without having to play tricks with signals, which can be rather cumbersome to do from userspace libraries.

Independently of the mechanism we choose to deliver information about this unexpected state (pinned && disallowed), whether it's signal delivery or through a special __rseq_abi.cpu_id value, the important part is to figure out how exactly we expect applications to handle this condition. If the application has a fallback available which does not require per-cpu data, it could be enabled from that point onwards (quiescence of that transition could be provided by a rseq barrier). Or if the application really requires per-cpu data by design, it could simply choose to abort.

Thoughts ?

Thanks,

Mathieu

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

* Mathieu Desnoyers:

Quoted 10 lines

It brings an interesting idea to the table though. Let's assume for now that the only intended use of pin_on_cpu(2) would be to allow rseq(2) critical sections to update per-cpu data on specific cpu number targets. In fact, considering that userspace can be preempted at any point, we still need a mechanism to guarantee atomicity with respect to other threads running on the same runqueue, which rseq(2) provides. Therefore, that assumption does not appear too far-fetched.

There are 2 scenarios we need to consider here:

Quoted 7 lines

A) pin_on_cpu(2) targets a CPU which is not part of the affinity mask.

This case is easy: pin_on_cpu can return an error, and the caller needs to act accordingly (e.g. figure out that this is a design error and report it, or decide that it really did not want to touch that per-cpu data that badly and make the entire process fall-back to a mechanism which does not use per-cpu data at all from that point onwards)

Affinity masks currently are not like process memory: there is an expectation that they can be altered from outside the process.

Given that the caller may not have any ways to recover from the suggested pin_on_cpu behavior, that seems problematic.

What I would expect is that if pin_on_cpu cannot achieve implied exclusion by running on the associated CPU, it acquires a lock that prevents others pin_on_cpu calls from entering the critical section, and tasks in the same task group from running on that CPU (if the CPU becomes available to the task group). The second part should maintain exclusion of rseq sequences even if their fast path is not changed.

(On the other hand, I'm worried that per-CPU data structures are a dead end for user space unless we get containerized affinity masks, so that contains only see resources that are actually available to them.)

Thanks,
Florian

#11 lore raw
Quoted 14 lines · ----- On Jan 30, 2020, at 6:10 AM, Florian Weimer [email protected] wrote:

* Mathieu Desnoyers:

Quoted 12 lines

It brings an interesting idea to the table though. Let's assume for now that the only intended use of pin_on_cpu(2) would be to allow rseq(2) critical sections to update per-cpu data on specific cpu number targets. In fact, considering that userspace can be preempted at any point, we still need a mechanism to guarantee atomicity with respect to other threads running on the same runqueue, which rseq(2) provides. Therefore, that assumption does not appear too far-fetched.

There are 2 scenarios we need to consider here:

A) pin_on_cpu(2) targets a CPU which is not part of the affinity mask.

Quoted 8 lines
Quoted 5 lines

This case is easy: pin_on_cpu can return an error, and the caller needs to act accordingly (e.g. figure out that this is a design error and report it, or decide that it really did not want to touch that per-cpu data that badly and make the entire process fall-back to a mechanism which does not use per-cpu data at all from that point onwards)

Affinity masks currently are not like process memory: there is an expectation that they can be altered from outside the process.

Yes, that's my main issue.

Quoted 2 lines

Given that the caller may not have any ways to recover from the suggested pin_on_cpu behavior, that seems problematic.

Indeed.

Quoted 7 lines

What I would expect is that if pin_on_cpu cannot achieve implied exclusion by running on the associated CPU, it acquires a lock that prevents others pin_on_cpu calls from entering the critical section, and tasks in the same task group from running on that CPU (if the CPU becomes available to the task group). The second part should maintain exclusion of rseq sequences even if their fast path is not changed.

I try to avoid mutual exclusion over shared memory as rseq fallback whenever I can, so we can use rseq from lock-free algorithms without losing lock-freedom.

Quoted 3 lines

(On the other hand, I'm worried that per-CPU data structures are a dead end for user space unless we get containerized affinity masks, so that contains only see resources that are actually available to them.)

I'm currently implementing a prototype of the following ideas, and I'm curious to read your thoughts on those:

I'm adding a "affinity_pinned" flag to the task struct of each thread. It can be set and cleared only by the owner thread through pin_on_cpu syscall commands. When the affinity is pinned by a thread, trying to change its affinity (from an external thread, or possibly from itself) will fail.

Whenever a thread would (temporarily) pin itself on a specific CPU, it would also pin its affinity mask as a side-effect. When a thread unpins from a CPU, the affinity mask stays pinned. The purpose of keeping this affinity pinned state per-thread is to ensure we don't end up with tiny race windows where changing the thread's affinity mask "typically" works, but fails once in a while because it's done concurrently with a 1ms long cpu pinning. This would lead to flaky code, and I try hard to avoid that.

How changing this affinity should fail (from sched_setaffinity and cpusets) is a big unanswered question. I see two major alternatives so far:

1) We deliver a signal to the target thread (SIGKILL ? SIGSEGV ?), considering that failure to be able to change its affinity mask means we need to send a signal. How exactly would the killed application recover (or if it should) is still unclear.

2) Return an error to the sched_setaffinity or cpusets caller, and let it deal with the error as it sees fit: ignore it, log it, or send a signal.

I think option (2) provides the most flexiblity, and moves policy outside of the kernel, which is a good thing. However, looking at how cpusets seems to simply ignore errors when setting a task's cpumask, I wonder if asking from cpusets to handle any kind of error is asking too much. :-/

Thanks,

Mathieu

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
http://www.efficios.com
#12 lore raw
In reply to Mathieu Desnoyers
Quoted 74 lines · Mathieu Desnoyers
Quoted 72 lines · ----- On Jan 21, 2020, at 3:35 PM, Jann Horn [email protected] wrote:
Quoted 69 lines · Mathieu Desnoyers
Quoted 56 lines · ----- On Jan 21, 2020, at 12:20 PM, Jann Horn [email protected] wrote:
Quoted 20 lines · Mathieu Desnoyers

There is an important use-case which is not possible with the "rseq" (Restartable Sequences) system call, which was left as future work.

That use-case is to modify user-space per-cpu data structures belonging to specific CPUs which may be brought offline and online again by CPU hotplug. This can be used by memory allocators to migrate free memory pools when CPUs are brought offline, or by ring buffer consumers to target specific per-CPU buffers, even when CPUs are brought offline.

A few rather complex prior attempts were made to solve this. Those were based on in-kernel interpreters (cpu_opv, do_on_cpu). That complexity was generally frowned upon, even by their author.

This patch fulfills this use-case in a refreshingly simple way:
it introduces a "pin_on_cpu" system call, which allows user-space threads to pin themselves on a specific CPU (which needs to be present in the thread's allowed cpu mask), and then clear this pinned state.

[...]

Quoted 6 lines

For instance, this allows implementing this userspace library API for incrementing a per-cpu counter for a specific cpu number received as parameter:

static inline __attribute__((always_inline)) int percpu_addv(intptr_t *v, intptr_t count, int cpu)

Quoted 13 lines
{
        int ret;

        ret = rseq_addv(v, count, cpu);
check:
        if (rseq_unlikely(ret)) {
                pin_on_cpu_set(cpu);
                ret = rseq_addv(v, count, percpu_current_cpu());
                pin_on_cpu_clear();
                goto check;
        }
        return 0;
}

What does userspace have to do if the set of allowed CPUs switches all the time? For example, on Android, if you first open Chrome and then look at its allowed CPUs, Chrome is allowed to use all CPU cores because it's running in the foreground:

walleye:/ # ps -AZ | grep 'android.chrome$' u:r:untrusted_app:s0:c145,c256,c512,c768 u0_a145 7845 805 1474472 197868 SyS_epoll_wait f09c0194 S com.android.chrome walleye:/ # grep cpuset /proc/7845/cgroup; grep Cpus_allowed_list /proc/7845/status
3:cpuset:/top-app
Cpus_allowed_list: 0-7

Quoted 7 lines

But if you then switch to the home screen, the application is moved into a different cgroup, and is restricted to two CPU cores:

walleye:/ # grep cpuset /proc/7845/cgroup; grep Cpus_allowed_list /proc/7845/status
3:cpuset:/background
Cpus_allowed_list: 0-1

Then at that point, pin_on_cpu() would only be allowed to pin on CPUs 0 and 1.

Quoted 6 lines
Quoted 3 lines

Which means that you can't actually reliably use pin_on_cpu_set() to manipulate percpu data structures since you have to call it with the assumption that it might randomly fail at any time, right?

Only if the cpu affinity of the thread is being changed concurrently by another thread which is a possibility in some applications, indeed.

Not just some applications, but also some environments, right? See the Android example - the set of permitted CPUs is changed not by the application itself, but by a management process that uses cgroup modifications to indirectly change the set of permitted CPUs. I wouldn't be surprised if the same could happen in e.g. container environments.

Quoted 8 lines
Quoted 3 lines

And then
userspace needs to code a fallback path that somehow halts all the threads with thread-directed signals or something?

The example use of pin_on_cpu() did not include handling of the return value in that case (-1, errno=EINVAL) for conciseness. But yes, the application would have to handle this.

Quoted 8 lines

It's not so different from error handling which is required when using sched_setaffinity(), which can fail with -1, errno=EINVAL in the following scenario:

EINVAL The affinity bit mask mask contains no processors that are cur‐
rently physically on the system and permitted to the thread according to any restrictions that may be imposed by the "cpuset" mechanism described in cpuset(7).

Except that sched_setaffinity() is normally just a performance optimization, right? Whereas pin_to_cpu() is more of a correctness thing?

Quoted 9 lines
Quoted 5 lines

Especially if the task trying to use pin_on_cpu_set() isn't allowed to pin to the target CPU, but all the other tasks using the shared data structure are allowed to do that. Or if the CPU you want to pin to is always removed from your affinity mask immediately before pin_on_cpu_set() and added back immediately afterwards.

I am tempted to state that using pin_on_cpu() targeting a disallowed cpu should be considered a programming error and handled accordingly by the application.

How can it be a programming error if that situation can be triggered by legitimate external modifications to CPU affinity?

[...]

Quoted 27 lines
Quoted 19 lines
Quoted 10 lines
Quoted 9 lines

I'm wondering whether it might be possible to rework this mechanism such that, instead of moving the current task onto a target CPU, it prevents all *other* threads of the current process from running on that CPU (either entirely or in user mode). That might be the easiest way to take care of issues like CPU hotplugging and changing cpusets all at once? The only potential issue I see with that approach would be that you wouldn't be able to use it for inter-process communication; and I have no idea whether this would be good or bad performance-wise.

Quoted 8 lines

Firstly, inter-process communication over shared memory is one of my use-cases (for lttng-ust's ring buffer).

I'm not convinced that applying constraints on all other threads belonging to the current process would be easier or faster than migrating the current thread over to the target CPU. I'm unsure how those additional constraints would fit with other threads already having their own cpu affinity masks (which could generate an empty cpumask by adding an extra constraint).

Quoted 7 lines

Hm - is an empty cpumask a problem here? If one task is in the middle of a critical section for performing maintenance on a percpu data structure, isn't it a nice design property to exclude concurrent access from other tasks to that data structure automatically (by preventing those tasks by running on that CPU)? That way the (presumably rarely-executed) update path doesn't have to be rseq-reentrancy-safe.

Quoted 4 lines

Given we already have rseq, simply using it to protect against other threads trying to touch the same per-cpu data seems rather more lightweight than to try to exclude all other threads from that CPU for a possibly unbounded amount of time.

That only works if the cpu-targeted maintenance operation is something that can be implemented in rseq, right? I was thinking that it might be nice to avoid that limitation - but I don't know much about the kinds of data structures that one might want to build on top of rseq, so maybe that's a silly idea.

Quoted 4 lines

Allowing a completely empty cpumask could effectively allow those critical sections to prevent execution of possibly higher priority threads on the system, which ends up being the definition of a priority inversion, which I'd like to avoid.

Linux does have the infrastructure for RT futexes, right? Maybe that could be useful here.

#13 lore raw
In reply to Mathieu Desnoyers
[if your patch is applied to the wrong git tree, please drop us a note to help improve the system. BTW, we also suggest to use '--base' option to specify the base tree in git format-patch, please…

Hi Mathieu,

[FYI, it's a private test report for your RFC patch.]
[auto build test ERROR on tip/x86/asm]
[also build test ERROR on asm-generic/master linus/master v5.5-rc7] [cannot apply to tip/sched/core next-20200123]
[if your patch is applied to the wrong git tree, please drop us a note to help improve the system. BTW, we also suggest to use '--base' option to specify the base tree in git format-patch, please see https://stackoverflow.com/a/37406982]

url:    https://github.com/0day-ci/linux/commits/Mathieu-Desnoyers/pin_on_cpu-Introduce-thread-CPU-pinning-system-call/20200124-092039
base:   https://git.kernel.org/pub/scm/linux/kernel/git/tip/tip.git 183ef7adf4ed638ac0fb0c3c9a71fc00e8512b61
config: m68k-defconfig (attached as .config)
compiler: m68k-linux-gcc (GCC) 7.5.0

reproduce:
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross chmod +x ~/bin/make.cross
# save the attached .config to linux build tree
GCC_VERSION=7.5.0 make.cross ARCH=m68k

If you fix the issue, kindly add following tag

All error/warnings (new ones prefixed by >>):

In file included from kernel//sched/core.c:9:0:
kernel//sched/sched.h: In function 'is_pinned_task':

>> kernel//sched/sched.h:196:10: error: 'struct task_struct' has no member named 'pinned_cpu'
     return p->pinned_cpu >= 0;
             ^~
   In file included from include/linux/rcupdate.h:31:0,
                    from include/linux/rculist.h:11,
                    from include/linux/pid.h:5,
                    from include/linux/sched.h:14,
                    from kernel//sched/sched.h:5,
                    from kernel//sched/core.c:9:
   kernel//sched/sched.h: In function 'allowed_pinned_cpu':
   kernel//sched/sched.h:208:18: error: 'struct task_struct' has no member named 'pinned_cpu'
     if (cpu_online(p->pinned_cpu)) {
                     ^
   include/linux/cpumask.h:126:28: note: in definition of macro 'cpu_online'
    #define cpu_online(cpu)  ((cpu) == 0)
                               ^~~
   In file included from kernel//sched/core.c:9:0:
   kernel//sched/sched.h:209:8: error: 'struct task_struct' has no member named 'pinned_cpu'
      if (p->pinned_cpu == cpu)
           ^~
   In file included from include/linux/kernel.h:11:0,
                    from include/linux/list.h:9,
                    from include/linux/rculist.h:10,
                    from include/linux/pid.h:5,
                    from include/linux/sched.h:14,
                    from kernel//sched/sched.h:5,
                    from kernel//sched/core.c:9:
   kernel//sched/core.c: In function 'do_set_pinned_cpu':
>> kernel//sched/core.c:8081:14: error: 'struct task_struct' has no member named 'pinned_cpu'
     WRITE_ONCE(p->pinned_cpu, cpu);
                 ^
   include/linux/compiler.h:286:17: note: in definition of macro 'WRITE_ONCE'
     union { typeof(x) __val; char __c[1]; } __u = \
                    ^
>> kernel//sched/core.c:8081:14: error: 'struct task_struct' has no member named 'pinned_cpu'
     WRITE_ONCE(p->pinned_cpu, cpu);
                 ^
   include/linux/compiler.h:287:30: note: in definition of macro 'WRITE_ONCE'
      { .__val = (__force typeof(x)) (val) }; \
                                 ^
>> kernel//sched/core.c:8081:14: error: 'struct task_struct' has no member named 'pinned_cpu'
     WRITE_ONCE(p->pinned_cpu, cpu);
                 ^
   include/linux/compiler.h:288:22: note: in definition of macro 'WRITE_ONCE'
     __write_once_size(&(x), __u.__c, sizeof(x)); \
                         ^
>> kernel//sched/core.c:8081:14: error: 'struct task_struct' has no member named 'pinned_cpu'
     WRITE_ONCE(p->pinned_cpu, cpu);
                 ^
   include/linux/compiler.h:288:42: note: in definition of macro 'WRITE_ONCE'
     __write_once_size(&(x), __u.__c, sizeof(x)); \
                                             ^
   kernel//sched/core.c: In function '__do_pin_on_cpu':
>> kernel//sched/core.c:8095:9: error: variable 'arg' has initializer but incomplete type
     struct migration_arg arg = { p };
            ^~~~~~~~~~~~~
>> kernel//sched/core.c:8095:31: warning: excess elements in struct initializer
     struct migration_arg arg = { p };
                                  ^
   kernel//sched/core.c:8095:31: note: (near initialization for 'arg')
>> kernel//sched/core.c:8095:23: error: storage size of 'arg' isn't known
     struct migration_arg arg = { p };
                          ^~~
   kernel//sched/core.c:8095:23: warning: unused variable 'arg' [-Wunused-variable]
   kernel//sched/core.c:8094:15: warning: unused variable 'dest_cpu' [-Wunused-variable]
     int ret = 0, dest_cpu;
                  ^~~~~~~~

At top level:
kernel//sched/core.c:8060:13: warning: 'do_set_pinned_cpu' defined but not used [-Wunused-function]
static void do_set_pinned_cpu(struct task_struct *p, int cpu)
^~~~~~~~~~~~~~~~~
--
In file included from kernel//sched/loadavg.c:9:0:
kernel//sched/sched.h: In function 'is_pinned_task':

>> kernel//sched/sched.h:196:10: error: 'struct task_struct' has no member named 'pinned_cpu'
     return p->pinned_cpu >= 0;
             ^~
   In file included from include/linux/rcupdate.h:31:0,
                    from include/linux/rculist.h:11,
                    from include/linux/pid.h:5,
                    from include/linux/sched.h:14,
                    from kernel//sched/sched.h:5,
                    from kernel//sched/loadavg.c:9:
   kernel//sched/sched.h: In function 'allowed_pinned_cpu':
   kernel//sched/sched.h:208:18: error: 'struct task_struct' has no member named 'pinned_cpu'
     if (cpu_online(p->pinned_cpu)) {
                     ^
   include/linux/cpumask.h:126:28: note: in definition of macro 'cpu_online'
    #define cpu_online(cpu)  ((cpu) == 0)
                               ^~~
   In file included from kernel//sched/loadavg.c:9:0:
   kernel//sched/sched.h:209:8: error: 'struct task_struct' has no member named 'pinned_cpu'
      if (p->pinned_cpu == cpu)
           ^~

vim +196 kernel//sched/sched.h

189
190 /*
191 * All tasks which require to be pinned on offlined CPUs are sent
192 * to runqueue of the first online CPU.
193 */
194 static inline bool is_pinned_task(struct task_struct *p)
195 {

 > 196		return p->pinned_cpu >= 0;

197 }
198

---
0-DAY kernel test infrastructure Open Source Technology Center
https://lists.01.org/hyperkitty/list/kbuild-all(a)lists.01.org Intel Corporation

#14 lore raw
In reply to Mathieu Desnoyers
[if your patch is applied to the wrong git tree, please drop us a note to help improve the system. BTW, we also suggest to use '--base' option to specify the base tree in git format-patch, please…

Hi Mathieu,

[FYI, it's a private test report for your RFC patch.]
[auto build test ERROR on tip/x86/asm]
[also build test ERROR on asm-generic/master linus/master v5.5-rc7] [cannot apply to tip/sched/core next-20200123]
[if your patch is applied to the wrong git tree, please drop us a note to help improve the system. BTW, we also suggest to use '--base' option to specify the base tree in git format-patch, please see https://stackoverflow.com/a/37406982]

url:    https://github.com/0day-ci/linux/commits/Mathieu-Desnoyers/pin_on_cpu-Introduce-thread-CPU-pinning-system-call/20200124-092039
base:   https://git.kernel.org/pub/scm/linux/kernel/git/tip/tip.git 183ef7adf4ed638ac0fb0c3c9a71fc00e8512b61
config: m68k-defconfig (attached as .config)
compiler: m68k-linux-gcc (GCC) 7.5.0

reproduce:
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross chmod +x ~/bin/make.cross
# save the attached .config to linux build tree
GCC_VERSION=7.5.0 make.cross ARCH=m68k

If you fix the issue, kindly add following tag

All errors (new ones prefixed by >>):

fs/exec.c: In function '__do_execve_file':

>> fs/exec.c:1829:9: error: 'struct task_struct' has no member named 'pinned_cpu'
     current->pinned_cpu = -1;
            ^~

vim +1829 fs/exec.c

1711
1712 /*
1713 * sys_execve() executes a new program.
1714 */
1715 static int __do_execve_file(int fd, struct filename *filename,

  1716				    struct user_arg_ptr argv,
  1717				    struct user_arg_ptr envp,
  1718				    int flags, struct file *file)
  1719	{
  1720		char *pathbuf = NULL;
  1721		struct linux_binprm *bprm;
  1722		struct files_struct *displaced;
  1723		int retval;
  1724	
  1725		if (IS_ERR(filename))
  1726			return PTR_ERR(filename);
  1727	
  1728		/*
  1729		 * We move the actual failure in case of RLIMIT_NPROC excess from
  1730		 * set*uid() to execve() because too many poorly written programs
  1731		 * don't check setuid() return code.  Here we additionally recheck
  1732		 * whether NPROC limit is still exceeded.
  1733		 */
  1734		if ((current->flags & PF_NPROC_EXCEEDED) &&
  1735		    atomic_read(&current_user()->processes) > rlimit(RLIMIT_NPROC)) {
  1736			retval = -EAGAIN;
  1737			goto out_ret;
  1738		}
  1739	
  1740		/* We're below the limit (still or again), so we don't want to make
  1741		 * further execve() calls fail. */
  1742		current->flags &= ~PF_NPROC_EXCEEDED;
  1743	
  1744		retval = unshare_files(&displaced);
  1745		if (retval)
  1746			goto out_ret;
  1747	
  1748		retval = -ENOMEM;
  1749		bprm = kzalloc(sizeof(*bprm), GFP_KERNEL);
  1750		if (!bprm)
  1751			goto out_files;
  1752	
  1753		retval = prepare_bprm_creds(bprm);
  1754		if (retval)
  1755			goto out_free;
  1756	
  1757		check_unsafe_exec(bprm);
  1758		current->in_execve = 1;
  1759	
  1760		if (!file)
  1761			file = do_open_execat(fd, filename, flags);
  1762		retval = PTR_ERR(file);
  1763		if (IS_ERR(file))
  1764			goto out_unmark;
  1765	
  1766		sched_exec();
  1767	
  1768		bprm->file = file;
  1769		if (!filename) {
  1770			bprm->filename = "none";
  1771		} else if (fd == AT_FDCWD || filename->name[0] == '/') {
  1772			bprm->filename = filename->name;
  1773		} else {
  1774			if (filename->name[0] == '\0')
  1775				pathbuf = kasprintf(GFP_KERNEL, "/dev/fd/%d", fd);
  1776			else
  1777				pathbuf = kasprintf(GFP_KERNEL, "/dev/fd/%d/%s",
  1778						    fd, filename->name);
  1779			if (!pathbuf) {
  1780				retval = -ENOMEM;
  1781				goto out_unmark;
  1782			}
  1783			/*
  1784			 * Record that a name derived from an O_CLOEXEC fd will be
  1785			 * inaccessible after exec. Relies on having exclusive access to
  1786			 * current->files (due to unshare_files above).
  1787			 */
  1788			if (close_on_exec(fd, rcu_dereference_raw(current->files->fdt)))
  1789				bprm->interp_flags |= BINPRM_FLAGS_PATH_INACCESSIBLE;
  1790			bprm->filename = pathbuf;
  1791		}
  1792		bprm->interp = bprm->filename;
  1793	
  1794		retval = bprm_mm_init(bprm);
  1795		if (retval)
  1796			goto out_unmark;
  1797	
  1798		retval = prepare_arg_pages(bprm, argv, envp);
  1799		if (retval < 0)
  1800			goto out;
  1801	
  1802		retval = prepare_binprm(bprm);
  1803		if (retval < 0)
  1804			goto out;
  1805	
  1806		retval = copy_strings_kernel(1, &bprm->filename, bprm);
  1807		if (retval < 0)
  1808			goto out;
  1809	
  1810		bprm->exec = bprm->p;
  1811		retval = copy_strings(bprm->envc, envp, bprm);
  1812		if (retval < 0)
  1813			goto out;
  1814	
  1815		retval = copy_strings(bprm->argc, argv, bprm);
  1816		if (retval < 0)
  1817			goto out;
  1818	
  1819		would_dump(bprm, bprm->file);
  1820	
  1821		retval = exec_binprm(bprm);
  1822		if (retval < 0)
  1823			goto out;
  1824	
  1825		/* execve succeeded */
  1826		current->fs->in_exec = 0;
  1827		current->in_execve = 0;
  1828		rseq_execve(current);
> 1829		current->pinned_cpu = -1;

1830 acct_update_integrals(current);
1831 task_numa_free(current, false);
1832 free_bprm(bprm);
1833 kfree(pathbuf);
1834 if (filename)
1835 putname(filename);
1836 if (displaced)
1837 put_files_struct(displaced);
1838 return retval;
1839
1840 out:
1841 if (bprm->mm) {
1842 acct_arg_size(bprm, 0);
1843 mmput(bprm->mm);
1844 }
1845
1846 out_unmark:
1847 current->fs->in_exec = 0;
1848 current->in_execve = 0;
1849
1850 out_free:
1851 free_bprm(bprm);
1852 kfree(pathbuf);
1853
1854 out_files:
1855 if (displaced)
1856 reset_files_struct(displaced);
1857 out_ret:
1858 if (filename)
1859 putname(filename);
1860 return retval;
1861 }
1862

---
0-DAY kernel test infrastructure Open Source Technology Center
https://lists.01.org/hyperkitty/list/kbuild-all(a)lists.01.org Intel Corporation