Skip to contentSkip to conversation

UMCG early preview/RFC patchset

RFC PATCH In review Peter Oskolkov 9 participants 40 messages May 20, 2021 – Jul 8, 2021 1 message not in the archive

Subsystems (9)
lore
Share & tools
lore
#0 lore raw

cover UMCG early preview/RFC patchset

As indicated earlier in the FUTEX_SWAP patchset:

https://lore.kernel.org/lkml/[email protected]/

"Google Fibers" is a userspace scheduling framework
used widely and successfully at Google to improve in-process workload isolation and response latencies. We are working on open-sourcing this framework, and UMCG (User-Managed Concurrency Groups) kernel patches are intended as the foundation of this.

This patchset is "early preview/RFC" - an earlier version of the "core UMCG API" was discussed offlist, and I was asked to post "what I have" to LKML before I consider the work ready for a full review.

Notes:
- the first six patches cover "core UMCG API" and are more "ready" than the last three, in the sense that I expect to see few, if any, material changes to them, unless the whole approach is NACKed;
- the last three patches cover "server/worker UMCG API" and need more work and testing:
- while I'm not aware of any specific issues with them, I have not implemented and/or tested, yet, many important use cases, such as:
- tracing
- signals/interrupts
- explicit preemption of workers other than cooperative wait/swap
- comments/documentation is missing in many important places, or maybe even wrong/outdated.

As such, please pay more attention to the high-level intended behavior and design than to things like patch organization, contents of commit messages, comments or indentation, especially in the last three patches.

Unless the feedback here points to a different approach, my next step is to add timeout handling to sys_umcg_wait/sys_umcg_swap, as this will open up a lot of Google-internal tests that cover most of use/corner cases other than explicit preemption of workers (Google Fibers use cooperative scheduling features only). Then I'll work on issues uncovered by those tests. Then I'll address preemption and tracing.

This work is loosely based on Google-internal SwitchTo and SwitchTo Groups kernel patches developed by Paul Turner and Ben Segall.

Peter Oskolkov (9):
sched/umcg: add UMCG syscall stubs and CONFIG_UMCG sched/umcg: add uapi/linux/umcg.h and sched/umcg.c
sched: add WF_CURRENT_CPU and externise ttwu sched/umcg: implement core UMCG API lib/umcg: implement UMCG core API for userspace selftests/umcg: add UMCG core API selftest sched/umcg: add UMCG server/worker API (early RFC) lib/umcg: add UMCG server/worker API (early RFC) selftests/umcg: add UMCG server/worker API selftest

 arch/x86/entry/syscalls/syscall_64.tbl        |   11 +
 include/linux/mm_types.h                      |    5 +
 include/linux/sched.h                         |    7 +-
 include/linux/syscalls.h                      |   14 +
 include/uapi/asm-generic/unistd.h             |   25 +-
 include/uapi/linux/umcg.h                     |   70 ++
 init/Kconfig                                  |   10 +
 kernel/fork.c                                 |   11 +
 kernel/sched/Makefile                         |    1 +
 kernel/sched/core.c                           |   17 +-
 kernel/sched/fair.c                           |    4 +
 kernel/sched/sched.h                          |   15 +-
 kernel/sched/umcg.c                           | 1114 +++++++++++++++++
 kernel/sched/umcg.h                           |   96 ++
 kernel/sys_ni.c                               |   13 +
 mm/init-mm.c                                  |    4 +
 tools/lib/umcg/.gitignore                     |    4 +
 tools/lib/umcg/Makefile                       |   11 +
 tools/lib/umcg/libumcg.c                      |  572 +++++++++
 tools/lib/umcg/libumcg.h                      |  262 ++++
 tools/testing/selftests/umcg/.gitignore       |    3 +
 tools/testing/selftests/umcg/Makefile         |   15 +
 tools/testing/selftests/umcg/umcg_core_test.c |  347 +++++
 tools/testing/selftests/umcg/umcg_test.c      |  475 +++++++
 24 files changed, 3096 insertions(+), 10 deletions(-)
 create mode 100644 include/uapi/linux/umcg.h
 create mode 100644 kernel/sched/umcg.c
 create mode 100644 kernel/sched/umcg.h
 create mode 100644 tools/lib/umcg/.gitignore
 create mode 100644 tools/lib/umcg/Makefile
 create mode 100644 tools/lib/umcg/libumcg.c
 create mode 100644 tools/lib/umcg/libumcg.h
 create mode 100644 tools/testing/selftests/umcg/.gitignore
 create mode 100644 tools/testing/selftests/umcg/Makefile
 create mode 100644 tools/testing/selftests/umcg/umcg_core_test.c
 create mode 100644 tools/testing/selftests/umcg/umcg_test.c
Signature · 1 line
2.31.1.818.g46aad6cb9e-goog
#1 lore raw

RFC PATCH 1/9 sched/umcg: add UMCG syscall stubs and CONFIG_UMCG

User Managed Concurrency Groups is a fast context switching and in-process userspace scheduling framework.

Two main use cases are security sandboxes and userspace scheduling.

Security sandboxes: fast X-process context switching will open up a bunch of light-weight security tools, e.g. gVisor, or Tor Project's Shadow simulator, to more use cases.

In-process userspace scheduling is used extensively at Google to provide latency control and isolation guarantees for diverse workloads while maintaining high CPU utilization.

---
 arch/x86/entry/syscalls/syscall_64.tbl | 11 +++++++++++
 include/uapi/asm-generic/unistd.h      | 25 ++++++++++++++++++++++++-
 init/Kconfig                           | 10 ++++++++++
 kernel/sys_ni.c                        | 13 +++++++++++++
 4 files changed, 58 insertions(+), 1 deletion(-)
arch/x86/entry/syscalls/syscall_64.tbl +11 -0
index ecd551b08d05..2e984a77eb23 100644
@@ -368,6 +368,17 @@
 444	common	landlock_create_ruleset	sys_landlock_create_ruleset
 445	common	landlock_add_rule	sys_landlock_add_rule
 446	common	landlock_restrict_self	sys_landlock_restrict_self
+447	common	umcg_api_version	sys_umcg_api_version
+448	common	umcg_register_task	sys_umcg_register_task
+449	common	umcg_unregister_task	sys_umcg_unregister_task
+450	common	umcg_wait		sys_umcg_wait
+451	common	umcg_wake		sys_umcg_wake
+452	common	umcg_swap		sys_umcg_swap
+453	common	umcg_create_group	sys_umcg_create_group
+454	common	umcg_destroy_group	sys_umcg_destroy_group
+455	common	umcg_poll_worker	sys_umcg_poll_worker
+456	common	umcg_run_worker		sys_umcg_run_worker
+457	common	umcg_preempt_worker	sys_umcg_preempt_worker
 
 #
 # Due to a historical design error, certain syscalls are numbered differently
include/uapi/asm-generic/unistd.h +24 -1
index 6de5a7fc066b..cb8504e7ae07 100644
@@ -873,8 +873,31 @@ __SYSCALL(__NR_landlock_add_rule, sys_landlock_add_rule)
 #define __NR_landlock_restrict_self 446
 __SYSCALL(__NR_landlock_restrict_self, sys_landlock_restrict_self)
 
+#define __NR_umcg_api_version 447
+__SYSCALL(__NR_umcg_api_version, sys_umcg_api_version)
+#define __NR_umcg_register_task 448
+__SYSCALL(__NR_umcg_register_task, sys_umcg_register_task)
+#define __NR_umcg_unregister_task 449
+__SYSCALL(__NR_umcg_unregister_task, sys_umcg_unregister_task)
+#define __NR_umcg_wait 450
+__SYSCALL(__NR_umcg_wait, sys_umcg_wait)
+#define __NR_umcg_wake 451
+__SYSCALL(__NR_umcg_wake, sys_umcg_wake)
+#define __NR_umcg_swap 452
+__SYSCALL(__NR_umcg_swap, sys_umcg_swap)
+#define __NR_umcg_create_group 453
+__SYSCALL(__NR_umcg_create_group, sys_umcg_create_group)
+#define __NR_umcg_destroy_group 454
+__SYSCALL(__NR_umcg_destroy_group, sys_umcg_destroy_group)
+#define __NR_umcg_poll_worker 455
+__SYSCALL(__NR_umcg_poll_worker, sys_umcg_poll_worker)
+#define __NR_umcg_run_worker 456
+__SYSCALL(__NR_umcg_run_worker, sys_umcg_run_worker)
+#define __NR_umcg_preempt_worker 457
+__SYSCALL(__NR_umcg_preempt_worker, sys_umcg_preempt_worker)
+
 #undef __NR_syscalls
-#define __NR_syscalls 447
+#define __NR_syscalls 458
 
 /*
  * 32 bit systems traditionally used different
init/Kconfig +10 -0
index 1ea12c64e4c9..bfac88dd5d73 100644
@@ -1661,6 +1661,16 @@ config MEMBARRIER
 
 	  If unsure, say Y.
 
+config UMCG
+	bool "Enable User Managed Concurrency Groups API"
+	default n
+	help
+	  Enable UMCG core wait/wake/swap operations as well as UMCG
+	  group/server/worker API. The core API is useful for fast IPC
+	  and context switching, while the group/server/worker API, together
+	  with the core API, form the basis for an in-process M:N userspace
+	  scheduling framework implemented in lib/umcg.
+
 config KALLSYMS
 	bool "Load all symbols for debugging/ksymoops" if EXPERT
 	default y
kernel/sys_ni.c +13 -0
index 0ea8128468c3..fea55aa0222a 100644
@@ -272,6 +272,19 @@ COND_SYSCALL(landlock_create_ruleset);
 COND_SYSCALL(landlock_add_rule);
 COND_SYSCALL(landlock_restrict_self);
 
+/* kernel/sched/umcg.c */
+COND_SYSCALL(umcg_api_version);
+COND_SYSCALL(umcg_register_task);
+COND_SYSCALL(umcg_unregister_task);
+COND_SYSCALL(umcg_wait);
+COND_SYSCALL(umcg_wake);
+COND_SYSCALL(umcg_swap);
+COND_SYSCALL(umcg_create_group);
+COND_SYSCALL(umcg_destroy_group);
+COND_SYSCALL(umcg_poll_worker);
+COND_SYSCALL(umcg_run_worker);
+COND_SYSCALL(umcg_preempt_worker);
+
 /* arch/example/kernel/sys_example.c */
 
 /* mm/fadvise.c */
Signature · 1 line
2.31.1.818.g46aad6cb9e-goog
#2 lore raw

Re: [RFC PATCH v0.1 1/9] sched/umcg: add UMCG syscall stubs and CONFIG_UMCG

[If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in https://git-scm.com/docs/git-format-patch]

Hi Peter,

[FYI, it's a private test report for your RFC patch.]
[auto build test ERROR on tip/sched/core]
[also build test ERROR on kselftest/next tip/master linus/master v5.13-rc2] [cannot apply to next-20210521]
[If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch]

url:    https://github.com/0day-ci/linux/commits/Peter-Oskolkov/UMCG-early-preview-RFC-patchset/20210522-232442
base:   https://git.kernel.org/pub/scm/linux/kernel/git/tip/tip.git 1699949d3314e5d1956fb082e4cd4798bf6149fc
config: riscv-randconfig-r031-20210523 (attached as .config)
compiler: clang version 13.0.0 (https://github.com/llvm/llvm-project e84a9b9bb3051c35dea993cdad7b3d2575638f85)

reproduce (this is a W=1 build):
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross chmod +x ~/bin/make.cross
# install riscv cross compiling tool for clang build
# apt-get install binutils-riscv64-linux-gnu
# https://github.com/0day-ci/linux/commit/cefa48e9b296faf3d52b8ebb7dd53f7123993ee0
git remote add linux-review https://github.com/0day-ci/linux
git fetch --no-tags linux-review Peter-Oskolkov/UMCG-early-preview-RFC-patchset/20210522-232442 git checkout cefa48e9b296faf3d52b8ebb7dd53f7123993ee0
# save the attached .config to linux build tree
COMPILER_INSTALL_PATH=$HOME/0day COMPILER=clang make.cross ARCH=riscv

If you fix the issue, kindly add following tag as appropriate

All errors (new ones prefixed by >>):

In file included from arch/riscv/kernel/syscall_table.c:18:
In file included from arch/riscv/include/asm/unistd.h:13:
In file included from arch/riscv/include/uapi/asm/unistd.h:24:

>> include/uapi/asm-generic/unistd.h:877:34: error: use of undeclared identifier 'sys_umcg_api_version'
   __SYSCALL(__NR_umcg_api_version, sys_umcg_api_version)
                                    ^
>> include/uapi/asm-generic/unistd.h:879:36: error: use of undeclared identifier 'sys_umcg_register_task'
   __SYSCALL(__NR_umcg_register_task, sys_umcg_register_task)
                                      ^
>> include/uapi/asm-generic/unistd.h:881:38: error: use of undeclared identifier 'sys_umcg_unregister_task'
   __SYSCALL(__NR_umcg_unregister_task, sys_umcg_unregister_task)
                                        ^
>> include/uapi/asm-generic/unistd.h:883:27: error: use of undeclared identifier 'sys_umcg_wait'; did you mean 'sys_epoll_wait'?
   __SYSCALL(__NR_umcg_wait, sys_umcg_wait)
                             ^~~~~~~~~~~~~
                             sys_epoll_wait
   arch/riscv/kernel/syscall_table.c:14:37: note: expanded from macro '__SYSCALL'
   #define __SYSCALL(nr, call)     [nr] = (call),
                                           ^
   include/linux/syscalls.h:1154:17: note: 'sys_epoll_wait' declared here
   asmlinkage long sys_epoll_wait(int epfd, struct epoll_event __user *events,
                   ^
   In file included from arch/riscv/kernel/syscall_table.c:18:
   In file included from arch/riscv/include/asm/unistd.h:13:
   In file included from arch/riscv/include/uapi/asm/unistd.h:24:
>> include/uapi/asm-generic/unistd.h:885:27: error: use of undeclared identifier 'sys_umcg_wake'
   __SYSCALL(__NR_umcg_wake, sys_umcg_wake)
                             ^
>> include/uapi/asm-generic/unistd.h:887:27: error: use of undeclared identifier 'sys_umcg_swap'
   __SYSCALL(__NR_umcg_swap, sys_umcg_swap)
                             ^
>> include/uapi/asm-generic/unistd.h:889:35: error: use of undeclared identifier 'sys_umcg_create_group'; did you mean 'sysfs_create_group'?
   __SYSCALL(__NR_umcg_create_group, sys_umcg_create_group)
                                     ^~~~~~~~~~~~~~~~~~~~~
                                     sysfs_create_group
   arch/riscv/kernel/syscall_table.c:14:37: note: expanded from macro '__SYSCALL'
   #define __SYSCALL(nr, call)     [nr] = (call),
                                           ^
   include/linux/sysfs.h:285:18: note: 'sysfs_create_group' declared here
   int __must_check sysfs_create_group(struct kobject *kobj,
                    ^
   In file included from arch/riscv/kernel/syscall_table.c:18:
   In file included from arch/riscv/include/asm/unistd.h:13:
   In file included from arch/riscv/include/uapi/asm/unistd.h:24:
>> include/uapi/asm-generic/unistd.h:891:36: error: use of undeclared identifier 'sys_umcg_destroy_group'
   __SYSCALL(__NR_umcg_destroy_group, sys_umcg_destroy_group)
                                      ^
>> include/uapi/asm-generic/unistd.h:893:34: error: use of undeclared identifier 'sys_umcg_poll_worker'
   __SYSCALL(__NR_umcg_poll_worker, sys_umcg_poll_worker)
                                    ^
>> include/uapi/asm-generic/unistd.h:895:33: error: use of undeclared identifier 'sys_umcg_run_worker'
   __SYSCALL(__NR_umcg_run_worker, sys_umcg_run_worker)
                                   ^
>> include/uapi/asm-generic/unistd.h:897:37: error: use of undeclared identifier 'sys_umcg_preempt_worker'
   __SYSCALL(__NR_umcg_preempt_worker, sys_umcg_preempt_worker)
                                       ^

11 errors generated.

Kconfig warnings: (for reference only)
WARNING: unmet direct dependencies detected for LOCKDEP
Depends on DEBUG_KERNEL && LOCK_DEBUGGING_SUPPORT && (FRAME_POINTER || MIPS || PPC || S390 || MICROBLAZE || ARM || ARC || X86) Selected by
- DEBUG_LOCK_ALLOC && DEBUG_KERNEL && LOCK_DEBUGGING_SUPPORT

vim +/sys_umcg_api_version +877 include/uapi/asm-generic/unistd.h

875
876 #define __NR_umcg_api_version 447

 > 877	__SYSCALL(__NR_umcg_api_version, sys_umcg_api_version)
   878	#define __NR_umcg_register_task 448
 > 879	__SYSCALL(__NR_umcg_register_task, sys_umcg_register_task)
   880	#define __NR_umcg_unregister_task 449
 > 881	__SYSCALL(__NR_umcg_unregister_task, sys_umcg_unregister_task)
   882	#define __NR_umcg_wait 450
 > 883	__SYSCALL(__NR_umcg_wait, sys_umcg_wait)
   884	#define __NR_umcg_wake 451
 > 885	__SYSCALL(__NR_umcg_wake, sys_umcg_wake)
   886	#define __NR_umcg_swap 452
 > 887	__SYSCALL(__NR_umcg_swap, sys_umcg_swap)
   888	#define __NR_umcg_create_group 453
 > 889	__SYSCALL(__NR_umcg_create_group, sys_umcg_create_group)
   890	#define __NR_umcg_destroy_group 454
 > 891	__SYSCALL(__NR_umcg_destroy_group, sys_umcg_destroy_group)
   892	#define __NR_umcg_poll_worker 455
 > 893	__SYSCALL(__NR_umcg_poll_worker, sys_umcg_poll_worker)
   894	#define __NR_umcg_run_worker 456
 > 895	__SYSCALL(__NR_umcg_run_worker, sys_umcg_run_worker)
   896	#define __NR_umcg_preempt_worker 457
 > 897	__SYSCALL(__NR_umcg_preempt_worker, sys_umcg_preempt_worker)

898

---
0-DAY CI Kernel Test Service, Intel Corporation
https://lists.01.org/hyperkitty/list/kbuild-all(a)lists.01.org

#3 lore raw

Re: [RFC PATCH v0.1 1/9] sched/umcg: add UMCG syscall stubs and CONFIG_UMCG

In reply to Peter Oskolkov
[If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in https://git-scm.com/docs/git-format-patch]

Hi Peter,

[FYI, it's a private test report for your RFC patch.]
[auto build test WARNING on tip/sched/core]
[also build test WARNING on kselftest/next tip/master linus/master v5.13-rc2] [cannot apply to next-20210521]
[If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch]

url:    https://github.com/0day-ci/linux/commits/Peter-Oskolkov/UMCG-early-preview-RFC-patchset/20210522-232442
base:   https://git.kernel.org/pub/scm/linux/kernel/git/tip/tip.git 1699949d3314e5d1956fb082e4cd4798bf6149fc
config: arm64-randconfig-r016-20210523 (attached as .config)
compiler: aarch64-linux-gcc (GCC) 9.3.0

reproduce (this is a W=1 build):
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross chmod +x ~/bin/make.cross
# https://github.com/0day-ci/linux/commit/cefa48e9b296faf3d52b8ebb7dd53f7123993ee0
git remote add linux-review https://github.com/0day-ci/linux
git fetch --no-tags linux-review Peter-Oskolkov/UMCG-early-preview-RFC-patchset/20210522-232442 git checkout cefa48e9b296faf3d52b8ebb7dd53f7123993ee0
# save the attached .config to linux build tree
COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-9.3.0 make.cross ARCH=arm64

If you fix the issue, kindly add following tag as appropriate

All warnings (new ones prefixed by >>):

         |                         ^~~~~~~~~~~~~~~~~~~
   kernel/sys_ni.c:249:1: note: in expansion of macro 'COND_SYSCALL_COMPAT'
     249 | COND_SYSCALL_COMPAT(getsockopt);
         | ^~~~~~~~~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_sendto' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:250:1: note: in expansion of macro 'COND_SYSCALL'
     250 | COND_SYSCALL(sendto);
         | ^~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_shutdown' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:251:1: note: in expansion of macro 'COND_SYSCALL'
     251 | COND_SYSCALL(shutdown);
         | ^~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_recvfrom' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:252:1: note: in expansion of macro 'COND_SYSCALL'
     252 | COND_SYSCALL(recvfrom);
         | ^~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:41:25: warning: no previous prototype for '__arm64_compat_sys_recvfrom' [-Wmissing-prototypes]
      41 |  asmlinkage long __weak __arm64_compat_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~~~~~~~~
   kernel/sys_ni.c:253:1: note: in expansion of macro 'COND_SYSCALL_COMPAT'
     253 | COND_SYSCALL_COMPAT(recvfrom);
         | ^~~~~~~~~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_sendmsg' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:254:1: note: in expansion of macro 'COND_SYSCALL'
     254 | COND_SYSCALL(sendmsg);
         | ^~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:41:25: warning: no previous prototype for '__arm64_compat_sys_sendmsg' [-Wmissing-prototypes]
      41 |  asmlinkage long __weak __arm64_compat_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~~~~~~~~
   kernel/sys_ni.c:255:1: note: in expansion of macro 'COND_SYSCALL_COMPAT'
     255 | COND_SYSCALL_COMPAT(sendmsg);
         | ^~~~~~~~~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_recvmsg' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:256:1: note: in expansion of macro 'COND_SYSCALL'
     256 | COND_SYSCALL(recvmsg);
         | ^~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:41:25: warning: no previous prototype for '__arm64_compat_sys_recvmsg' [-Wmissing-prototypes]
      41 |  asmlinkage long __weak __arm64_compat_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~~~~~~~~
   kernel/sys_ni.c:257:1: note: in expansion of macro 'COND_SYSCALL_COMPAT'
     257 | COND_SYSCALL_COMPAT(recvmsg);
         | ^~~~~~~~~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_mremap' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:262:1: note: in expansion of macro 'COND_SYSCALL'
     262 | COND_SYSCALL(mremap);
         | ^~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_add_key' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:265:1: note: in expansion of macro 'COND_SYSCALL'
     265 | COND_SYSCALL(add_key);
         | ^~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_request_key' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:266:1: note: in expansion of macro 'COND_SYSCALL'
     266 | COND_SYSCALL(request_key);
         | ^~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_keyctl' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:267:1: note: in expansion of macro 'COND_SYSCALL'
     267 | COND_SYSCALL(keyctl);
         | ^~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:41:25: warning: no previous prototype for '__arm64_compat_sys_keyctl' [-Wmissing-prototypes]
      41 |  asmlinkage long __weak __arm64_compat_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~~~~~~~~
   kernel/sys_ni.c:268:1: note: in expansion of macro 'COND_SYSCALL_COMPAT'
     268 | COND_SYSCALL_COMPAT(keyctl);
         | ^~~~~~~~~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_landlock_create_ruleset' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:271:1: note: in expansion of macro 'COND_SYSCALL'
     271 | COND_SYSCALL(landlock_create_ruleset);
         | ^~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_landlock_add_rule' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:272:1: note: in expansion of macro 'COND_SYSCALL'
     272 | COND_SYSCALL(landlock_add_rule);
         | ^~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_landlock_restrict_self' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:273:1: note: in expansion of macro 'COND_SYSCALL'
     273 | COND_SYSCALL(landlock_restrict_self);
         | ^~~~~~~~~~~~
>> arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_umcg_api_version' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:276:1: note: in expansion of macro 'COND_SYSCALL'
     276 | COND_SYSCALL(umcg_api_version);
         | ^~~~~~~~~~~~
>> arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_umcg_register_task' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:277:1: note: in expansion of macro 'COND_SYSCALL'
     277 | COND_SYSCALL(umcg_register_task);
         | ^~~~~~~~~~~~
>> arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_umcg_unregister_task' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:278:1: note: in expansion of macro 'COND_SYSCALL'
     278 | COND_SYSCALL(umcg_unregister_task);
         | ^~~~~~~~~~~~
>> arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_umcg_wait' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:279:1: note: in expansion of macro 'COND_SYSCALL'
     279 | COND_SYSCALL(umcg_wait);
         | ^~~~~~~~~~~~
>> arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_umcg_wake' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:280:1: note: in expansion of macro 'COND_SYSCALL'
     280 | COND_SYSCALL(umcg_wake);
         | ^~~~~~~~~~~~
>> arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_umcg_swap' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:281:1: note: in expansion of macro 'COND_SYSCALL'
     281 | COND_SYSCALL(umcg_swap);
         | ^~~~~~~~~~~~
>> arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_umcg_create_group' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:282:1: note: in expansion of macro 'COND_SYSCALL'
     282 | COND_SYSCALL(umcg_create_group);
         | ^~~~~~~~~~~~
>> arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_umcg_destroy_group' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:283:1: note: in expansion of macro 'COND_SYSCALL'
     283 | COND_SYSCALL(umcg_destroy_group);
         | ^~~~~~~~~~~~
>> arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_umcg_poll_worker' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:284:1: note: in expansion of macro 'COND_SYSCALL'
     284 | COND_SYSCALL(umcg_poll_worker);
         | ^~~~~~~~~~~~
>> arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_umcg_run_worker' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:285:1: note: in expansion of macro 'COND_SYSCALL'
     285 | COND_SYSCALL(umcg_run_worker);
         | ^~~~~~~~~~~~
>> arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_umcg_preempt_worker' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:286:1: note: in expansion of macro 'COND_SYSCALL'
     286 | COND_SYSCALL(umcg_preempt_worker);
         | ^~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_fadvise64_64' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:291:1: note: in expansion of macro 'COND_SYSCALL'
     291 | COND_SYSCALL(fadvise64_64);
         | ^~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_swapon' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:294:1: note: in expansion of macro 'COND_SYSCALL'
     294 | COND_SYSCALL(swapon);
         | ^~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_swapoff' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:295:1: note: in expansion of macro 'COND_SYSCALL'
     295 | COND_SYSCALL(swapoff);
         | ^~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_mprotect' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:296:1: note: in expansion of macro 'COND_SYSCALL'
     296 | COND_SYSCALL(mprotect);
         | ^~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_msync' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:297:1: note: in expansion of macro 'COND_SYSCALL'
     297 | COND_SYSCALL(msync);
         | ^~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_mlock' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:298:1: note: in expansion of macro 'COND_SYSCALL'
     298 | COND_SYSCALL(mlock);
         | ^~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_munlock' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:299:1: note: in expansion of macro 'COND_SYSCALL'
     299 | COND_SYSCALL(munlock);
         | ^~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_mlockall' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:300:1: note: in expansion of macro 'COND_SYSCALL'
     300 | COND_SYSCALL(mlockall);
         | ^~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_munlockall' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:301:1: note: in expansion of macro 'COND_SYSCALL'
     301 | COND_SYSCALL(munlockall);
         | ^~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_mincore' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:302:1: note: in expansion of macro 'COND_SYSCALL'
     302 | COND_SYSCALL(mincore);
         | ^~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_madvise' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:303:1: note: in expansion of macro 'COND_SYSCALL'
     303 | COND_SYSCALL(madvise);
         | ^~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_process_madvise' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:304:1: note: in expansion of macro 'COND_SYSCALL'
     304 | COND_SYSCALL(process_madvise);
         | ^~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_remap_file_pages' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:305:1: note: in expansion of macro 'COND_SYSCALL'
     305 | COND_SYSCALL(remap_file_pages);
         | ^~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_mbind' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:306:1: note: in expansion of macro 'COND_SYSCALL'
     306 | COND_SYSCALL(mbind);
         | ^~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:41:25: warning: no previous prototype for '__arm64_compat_sys_mbind' [-Wmissing-prototypes]
      41 |  asmlinkage long __weak __arm64_compat_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~~~~~~~~
   kernel/sys_ni.c:307:1: note: in expansion of macro 'COND_SYSCALL_COMPAT'
     307 | COND_SYSCALL_COMPAT(mbind);
         | ^~~~~~~~~~~~~~~~~~~
   arch/arm64/include/asm/syscall_wrapper.h:76:25: warning: no previous prototype for '__arm64_sys_get_mempolicy' [-Wmissing-prototypes]
      76 |  asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs) \
         |                         ^~~~~~~~~~~~
   kernel/sys_ni.c:308:1: note: in expansion of macro 'COND_SYSCALL'
     308 | COND_SYSCALL(get_mempolicy);

vim +/__arm64_sys_umcg_api_version +76 arch/arm64/include/asm/syscall_wrapper.h

4378a7d4be30ec Mark Rutland  2018-07-11  50  
4378a7d4be30ec Mark Rutland  2018-07-11  51  #define __SYSCALL_DEFINEx(x, name, ...)						\
4378a7d4be30ec Mark Rutland  2018-07-11  52  	asmlinkage long __arm64_sys##name(const struct pt_regs *regs);		\
4378a7d4be30ec Mark Rutland  2018-07-11  53  	ALLOW_ERROR_INJECTION(__arm64_sys##name, ERRNO);			\
4378a7d4be30ec Mark Rutland  2018-07-11  54  	static long __se_sys##name(__MAP(x,__SC_LONG,__VA_ARGS__));		\
4378a7d4be30ec Mark Rutland  2018-07-11  55  	static inline long __do_sys##name(__MAP(x,__SC_DECL,__VA_ARGS__));	\
4378a7d4be30ec Mark Rutland  2018-07-11  56  	asmlinkage long __arm64_sys##name(const struct pt_regs *regs)		\
4378a7d4be30ec Mark Rutland  2018-07-11  57  	{									\
4378a7d4be30ec Mark Rutland  2018-07-11  58  		return __se_sys##name(SC_ARM64_REGS_TO_ARGS(x,__VA_ARGS__));	\
4378a7d4be30ec Mark Rutland  2018-07-11  59  	}									\
4378a7d4be30ec Mark Rutland  2018-07-11  60  	static long __se_sys##name(__MAP(x,__SC_LONG,__VA_ARGS__))		\
4378a7d4be30ec Mark Rutland  2018-07-11  61  	{									\
4378a7d4be30ec Mark Rutland  2018-07-11  62  		long ret = __do_sys##name(__MAP(x,__SC_CAST,__VA_ARGS__));	\
4378a7d4be30ec Mark Rutland  2018-07-11  63  		__MAP(x,__SC_TEST,__VA_ARGS__);					\
4378a7d4be30ec Mark Rutland  2018-07-11  64  		__PROTECT(x, ret,__MAP(x,__SC_ARGS,__VA_ARGS__));		\
4378a7d4be30ec Mark Rutland  2018-07-11  65  		return ret;							\
4378a7d4be30ec Mark Rutland  2018-07-11  66  	}									\
4378a7d4be30ec Mark Rutland  2018-07-11  67  	static inline long __do_sys##name(__MAP(x,__SC_DECL,__VA_ARGS__))
4378a7d4be30ec Mark Rutland  2018-07-11  68  
4378a7d4be30ec Mark Rutland  2018-07-11  69  #define SYSCALL_DEFINE0(sname)							\
4378a7d4be30ec Mark Rutland  2018-07-11  70  	SYSCALL_METADATA(_##sname, 0);						\
0e358bd7b7ebd2 Sami Tolvanen 2019-05-24  71  	asmlinkage long __arm64_sys_##sname(const struct pt_regs *__unused);	\
4378a7d4be30ec Mark Rutland  2018-07-11  72  	ALLOW_ERROR_INJECTION(__arm64_sys_##sname, ERRNO);			\
0e358bd7b7ebd2 Sami Tolvanen 2019-05-24  73  	asmlinkage long __arm64_sys_##sname(const struct pt_regs *__unused)
4378a7d4be30ec Mark Rutland  2018-07-11  74  
c27eccfe4d6c74 Sami Tolvanen 2019-09-10  75  #define COND_SYSCALL(name)							\
c27eccfe4d6c74 Sami Tolvanen 2019-09-10 @76  	asmlinkage long __weak __arm64_sys_##name(const struct pt_regs *regs)	\
c27eccfe4d6c74 Sami Tolvanen 2019-09-10  77  	{									\
c27eccfe4d6c74 Sami Tolvanen 2019-09-10  78  		return sys_ni_syscall();					\
c27eccfe4d6c74 Sami Tolvanen 2019-09-10  79  	}

4378a7d4be30ec Mark Rutland 2018-07-11 80

---
0-DAY CI Kernel Test Service, Intel Corporation
https://lists.01.org/hyperkitty/list/kbuild-all(a)lists.01.org

#4 lore raw

RFC PATCH 2/9 sched/umcg: add uapi/linux/umcg.h and sched/umcg.c

In reply to Peter Oskolkov

Introduce the uapi UMCG header file and document core UMCG API syscalls.

It is sometimes useful to separate the discussion of API from the implementation details, and it seems to be the case here.

---
 include/linux/syscalls.h  |   9 +++
 include/uapi/linux/umcg.h |  70 +++++++++++++++++++
 kernel/sched/Makefile     |   1 +
 kernel/sched/umcg.c       | 143 ++++++++++++++++++++++++++++++++++++++
 4 files changed, 223 insertions(+)
 create mode 100644 include/uapi/linux/umcg.h
 create mode 100644 kernel/sched/umcg.c
include/linux/syscalls.h +9 -0
index 050511e8f1f8..15de3e34ccee 100644
@@ -71,6 +71,7 @@ struct open_how;
 struct mount_attr;
 struct landlock_ruleset_attr;
 enum landlock_rule_type;
+struct umcg_task;
 
 #include <linux/types.h>
 #include <linux/aio_abi.h>
@@ -1050,6 +1051,14 @@ asmlinkage long sys_landlock_create_ruleset(const struct landlock_ruleset_attr _
 asmlinkage long sys_landlock_add_rule(int ruleset_fd, enum landlock_rule_type rule_type,
 		const void __user *rule_attr, __u32 flags);
 asmlinkage long sys_landlock_restrict_self(int ruleset_fd, __u32 flags);
+asmlinkage long umcg_api_version(u32 api_version, u32 flags);
+asmlinkage long umcg_register_task(u32 api_version, u32 flags, u32 group_id,
+					struct umcg_task __user *umcg_task);
+asmlinkage long umcg_unregister_task(u32 flags);
+asmlinkage long umcg_wait(u32 flags, const struct __kernel_timespec __user *timeout);
+asmlinkage long umcg_wake(u32 flags, u32 next_tid);
+asmlinkage long umcg_swap(u32 wake_flags, u32 next_tid, u32 wait_flags,
+				const struct __kernel_timespec __user *timeout);
 
 /*
  * Architecture-specific system calls
include/uapi/linux/umcg.h new file +70 -0

70 lines not on this page · raw message

kernel/sched/Makefile +1 -0
index 978fcfca5871..e4e481eee1b7 100644
@@ -37,3 +37,4 @@ obj-$(CONFIG_MEMBARRIER) += membarrier.o
 obj-$(CONFIG_CPU_ISOLATION) += isolation.o
 obj-$(CONFIG_PSI) += psi.o
 obj-$(CONFIG_SCHED_CORE) += core_sched.o
+obj-$(CONFIG_UMCG) += umcg.o
kernel/sched/umcg.c new file +143 -0

143 lines not on this page · raw message

Signature · 1 line
2.31.1.818.g46aad6cb9e-goog
#5 lore raw

RFC PATCH 3/9 sched: add WF_CURRENT_CPU and externise ttwu

In reply to Peter Oskolkov

Add WF_CURRENT_CPU wake flag that advices the scheduler to move the wakee to the current CPU. This is useful for fast on-CPU context switching use cases such as UMCG.

In addition, make ttwu external rather than static so that the flag could be passed to it from outside of sched/core.c.

---
 kernel/sched/core.c  |  3 +--
 kernel/sched/fair.c  |  4 ++++
 kernel/sched/sched.h | 15 +++++++++------
 3 files changed, 14 insertions(+), 8 deletions(-)
kernel/sched/core.c +1 -2
index 3d2527239c3e..88506bc2617f 100644
@@ -3683,8 +3683,7 @@ static void ttwu_queue(struct task_struct *p, int cpu, int wake_flags)
  * Return: %true if @p->state changes (an actual wakeup was done),
  *	   %false otherwise.
  */
-static int
-try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
+int try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
 {
 	unsigned long flags;
 	int cpu, success = 0;
kernel/sched/fair.c +4 -0
index 161b92aa1c79..e55256bbb60b 100644
@@ -6764,6 +6764,10 @@ select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags)
 	if (wake_flags & WF_TTWU) {
 		record_wakee(p);
 
+		if ((wake_flags & WF_CURRENT_CPU) &&
+		    cpumask_test_cpu(cpu, p->cpus_ptr))
+			return cpu;
+
 		if (sched_energy_enabled()) {
 			new_cpu = find_energy_efficient_cpu(p, prev_cpu);
 			if (new_cpu >= 0)
kernel/sched/sched.h +9 -6
index 8f0194cee0ba..205d05571d9e 100644
@@ -2027,13 +2027,14 @@ static inline int task_on_rq_migrating(struct task_struct *p)
 }
 
 /* Wake flags. The first three directly map to some SD flag value */
-#define WF_EXEC     0x02 /* Wakeup after exec; maps to SD_BALANCE_EXEC */
-#define WF_FORK     0x04 /* Wakeup after fork; maps to SD_BALANCE_FORK */
-#define WF_TTWU     0x08 /* Wakeup;            maps to SD_BALANCE_WAKE */
+#define WF_EXEC         0x02 /* Wakeup after exec; maps to SD_BALANCE_EXEC */
+#define WF_FORK         0x04 /* Wakeup after fork; maps to SD_BALANCE_FORK */
+#define WF_TTWU         0x08 /* Wakeup;            maps to SD_BALANCE_WAKE */
 
-#define WF_SYNC     0x10 /* Waker goes to sleep after wakeup */
-#define WF_MIGRATED 0x20 /* Internal use, task got migrated */
-#define WF_ON_CPU   0x40 /* Wakee is on_cpu */
+#define WF_SYNC         0x10 /* Waker goes to sleep after wakeup */
+#define WF_MIGRATED     0x20 /* Internal use, task got migrated */
+#define WF_ON_CPU       0x40 /* Wakee is on_cpu */
+#define WF_CURRENT_CPU  0x80 /* Prefer to move the wakee to the current CPU. */
 
 #ifdef CONFIG_SMP
 static_assert(WF_EXEC == SD_BALANCE_EXEC);
@@ -3018,6 +3019,8 @@ static inline bool is_per_cpu_kthread(struct task_struct *p)
 extern void swake_up_all_locked(struct swait_queue_head *q);
 extern void __prepare_to_swait(struct swait_queue_head *q, struct swait_queue *wait);
 
+extern int try_to_wake_up(struct task_struct *tsk, unsigned int state, int wake_flags);
+
 #ifdef CONFIG_PREEMPT_DYNAMIC
 extern int preempt_dynamic_mode;
 extern int sched_dynamic_mode(const char *str);
Signature · 1 line
2.31.1.818.g46aad6cb9e-goog
#6 lore raw

RFC PATCH 4/9 sched/umcg: implement core UMCG API

In reply to Peter Oskolkov

Implement version 1 of core UMCG API (wait/wake/swap).

As has been outlined in
https://lore.kernel.org/lkml/[email protected]/,
efficient and synchronous on-CPU context switching is key to enabling two broad use cases: in-process M:N userspace scheduling and fast X-process RPCs for security wrappers.

High-level design considerations/approaches used:
- wait & wake can race with each other;
- offload as much work as possible to libumcg in tools/lib/umcg, specifically:
- most state changes, e.g. RUNNABLE <=> RUNNING, are done in

    the userspace (libumcg);

- retries are offloaded to the userspace.

This implementation misses timeout handling in sys_umcg_wait and sys_umcg_swap, which will be added in version 2.

---
 include/linux/sched.h |   7 +-
 kernel/sched/core.c   |   3 +
 kernel/sched/umcg.c   | 237 ++++++++++++++++++++++++++++++++++++++++--
 kernel/sched/umcg.h   |  42 ++++++++
 4 files changed, 282 insertions(+), 7 deletions(-)
 create mode 100644 kernel/sched/umcg.h
include/linux/sched.h +6 -1
index c7e7d50e2fdc..fc4b8775f514 100644
@@ -66,6 +66,7 @@ struct sighand_struct;
 struct signal_struct;
 struct task_delay_info;
 struct task_group;
+struct umcg_task_data;
 
 /*
  * Task state bitmask. NOTE! These bits are also
@@ -778,6 +779,10 @@ struct task_struct {
 	struct mm_struct		*mm;
 	struct mm_struct		*active_mm;
 
+#ifdef CONFIG_UMCG
+	struct umcg_task_data __rcu	*umcg_task_data;
+#endif
+
 	/* Per-thread vma caching: */
 	struct vmacache			vmacache;
 
@@ -1022,7 +1027,7 @@ struct task_struct {
 	u64				parent_exec_id;
 	u64				self_exec_id;
 
-	/* Protection against (de-)allocation: mm, files, fs, tty, keyrings, mems_allowed, mempolicy: */
+	/* Protection against (de-)allocation: mm, files, fs, tty, keyrings, mems_allowed, mempolicy, umcg: */
 	spinlock_t			alloc_lock;
 
 	/* Protection of the PI data structures: */
kernel/sched/core.c +3 -0
index 88506bc2617f..462104f13c28 100644
@@ -3964,6 +3964,9 @@ static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
 	p->wake_entry.u_flags = CSD_TYPE_TTWU;
 	p->migration_pending = NULL;
 #endif
+#ifdef CONFIG_UMCG
+	rcu_assign_pointer(p->umcg_task_data, NULL);
+#endif
 }
 
 DEFINE_STATIC_KEY_FALSE(sched_numa_balancing);
kernel/sched/umcg.c +231 -6

282 lines not on this page · raw message

kernel/sched/umcg.h new file +42 -0

42 lines not on this page · raw message

Signature · 1 line
2.31.1.818.g46aad6cb9e-goog
#7 lore raw

Re: [RFC PATCH v0.1 4/9] sched/umcg: implement core UMCG API

Quoted 14 lines · Peter Oskolkov
kernel/sched/umcg.c +9 -1
@@ -67,7 +137,75 @@ SYSCALL_DEFINE4(umcg_register_task, u32, api_version, u32, flags, u32, group_id,
  */
 SYSCALL_DEFINE1(umcg_unregister_task, u32, flags)
 {
-	return -ENOSYS;
+	struct umcg_task_data *utd;
+	int ret = -EINVAL;
+
+	rcu_read_lock();
+	utd = rcu_dereference(current->umcg_task_data);
+
+	if (!utd || flags)
+		goto out;
+

kernel/sched/umcg.c SYSCALL_DEFINE4(umcg_register_task, u32, api_version, u32, flags, u32, group_id, · line 158

Quoted 10 lines
kernel/sched/umcg.c +10 -0
+	task_lock(current);
+	rcu_assign_pointer(current->umcg_task_data, NULL);
+	task_unlock(current);
+
+	ret = 0;
+
+out:
+	rcu_read_unlock();
+	if (!ret && utd) {
+		synchronize_rcu();

synchronize_rcu is expensive. Do we really need to call it here? Can we use kfree_rcu?

Where is task->umcg_task_data freed when a task is destroyed?

Quoted 5 lines
kernel/sched/umcg.c +5 -0
+		kfree(utd);
+	}
+	return ret;
+}
+
#8 lore raw

Re: [RFC PATCH v0.1 4/9] sched/umcg: implement core UMCG API

Quoted 29 lines · Andrei Vagin
Quoted 14 lines · Peter Oskolkov
kernel/sched/umcg.c +9 -1
@@ -67,7 +137,75 @@ SYSCALL_DEFINE4(umcg_register_task, u32, api_version, u32, flags, u32, group_id,
  */
 SYSCALL_DEFINE1(umcg_unregister_task, u32, flags)
 {
-     return -ENOSYS;
+     struct umcg_task_data *utd;
+     int ret = -EINVAL;
+
+     rcu_read_lock();
+     utd = rcu_dereference(current->umcg_task_data);
+
+     if (!utd || flags)
+             goto out;
+

kernel/sched/umcg.c SYSCALL_DEFINE4(umcg_register_task, u32, api_version, u32, flags, u32, group_id, · line 158

Quoted 10 lines
kernel/sched/umcg.c +10 -0
+     task_lock(current);
+     rcu_assign_pointer(current->umcg_task_data, NULL);
+     task_unlock(current);
+
+     ret = 0;
+
+out:
+     rcu_read_unlock();
+     if (!ret && utd) {
+             synchronize_rcu();

synchronize_rcu is expensive. Do we really need to call it here? Can we use kfree_rcu?

Quoted 1 line

Where is task->umcg_task_data freed when a task is destroyed?

or executed - the umcg stuff includes a userspace pointer, so it probably shouldn't normally be kept around across execve?

#9 lore raw

Re: [RFC PATCH v0.1 4/9] sched/umcg: implement core UMCG API

Quoted 31 lines · Jann Horn
Quoted 29 lines · Andrei Vagin
Quoted 14 lines · Peter Oskolkov
kernel/sched/umcg.c +9 -1
@@ -67,7 +137,75 @@ SYSCALL_DEFINE4(umcg_register_task, u32, api_version, u32, flags, u32, group_id,
  */
 SYSCALL_DEFINE1(umcg_unregister_task, u32, flags)
 {
-     return -ENOSYS;
+     struct umcg_task_data *utd;
+     int ret = -EINVAL;
+
+     rcu_read_lock();
+     utd = rcu_dereference(current->umcg_task_data);
+
+     if (!utd || flags)
+             goto out;
+

kernel/sched/umcg.c SYSCALL_DEFINE4(umcg_register_task, u32, api_version, u32, flags, u32, group_id, · line 158

Quoted 10 lines
kernel/sched/umcg.c +10 -0
+     task_lock(current);
+     rcu_assign_pointer(current->umcg_task_data, NULL);
+     task_unlock(current);
+
+     ret = 0;
+
+out:
+     rcu_read_unlock();
+     if (!ret && utd) {
+             synchronize_rcu();

synchronize_rcu is expensive. Do we really need to call it here? Can we use kfree_rcu?

Quoted 4 lines
Quoted 1 line

Where is task->umcg_task_data freed when a task is destroyed?

or executed - the umcg stuff includes a userspace pointer, so it probably shouldn't normally be kept around across execve?

Ack - thanks for these and other comments. Please keep them coming. I'll address them in v0.2.

Thanks,
Peter

maintainer
#10 lore raw

Re: [RFC PATCH v0.1 4/9] sched/umcg: implement core UMCG API

In reply to Peter Oskolkov
Quoted 9 lines · Peter Oskolkov

Implement version 1 of core UMCG API (wait/wake/swap).

As has been outlined in
https://lore.kernel.org/lkml/[email protected]/,
efficient and synchronous on-CPU context switching is key to enabling two broad use cases: in-process M:N userspace scheduling and fast X-process RPCs for security wrappers.

Quoted 7 lines

High-level design considerations/approaches used:
- wait & wake can race with each other;
- offload as much work as possible to libumcg in tools/lib/umcg, specifically:
- most state changes, e.g. RUNNABLE <=> RUNNING, are done in

    the userspace (libumcg);

- retries are offloaded to the userspace.

Do you have some perf numbers as to how long a UMCG context switch takes compared to a normal one?

--Andy

#11 lore raw

Re: [RFC PATCH v0.1 4/9] sched/umcg: implement core UMCG API

Quoted 19 lines · Andy Lutomirski
Quoted 9 lines · Peter Oskolkov

Implement version 1 of core UMCG API (wait/wake/swap).

As has been outlined in
https://lore.kernel.org/lkml/[email protected]/,
efficient and synchronous on-CPU context switching is key to enabling two broad use cases: in-process M:N userspace scheduling and fast X-process RPCs for security wrappers.

Quoted 7 lines

High-level design considerations/approaches used:
- wait & wake can race with each other;
- offload as much work as possible to libumcg in tools/lib/umcg, specifically:
- most state changes, e.g. RUNNABLE <=> RUNNING, are done in

    the userspace (libumcg);

- retries are offloaded to the userspace.

Quoted 2 lines

Do you have some perf numbers as to how long a UMCG context switch takes compared to a normal one?

I'm not sure what is a "normal context switch" in this context. Futex wakeup on a remote idle CPU takes 5-10usec; an on-CPU UMCG context switch takes less than 1usec; futex wake + futex wait on the same CPU (taskset ***) takes about 1-1.5usec in my benchmarks.

Quoted 2 lines

--Andy

#12 lore raw

Re: [RFC PATCH v0.1 4/9] sched/umcg: implement core UMCG API

In reply to Peter Oskolkov
Quoted 15 lines · Peter Oskolkov

Implement version 1 of core UMCG API (wait/wake/swap).

As has been outlined in
https://lore.kernel.org/lkml/[email protected]/,
efficient and synchronous on-CPU context switching is key to enabling two broad use cases: in-process M:N userspace scheduling and fast X-process RPCs for security wrappers.

High-level design considerations/approaches used:
- wait & wake can race with each other;
- offload as much work as possible to libumcg in tools/lib/umcg, specifically:
- most state changes, e.g. RUNNABLE <=> RUNNING, are done in

    the userspace (libumcg);

- retries are offloaded to the userspace.

[...]

Quoted 1 line
kernel/sched/umcg.c +0 -0

[...]

kernel/sched/umcg.c line 49

Quoted 3 lines
kernel/sched/umcg.c +3 -0
+static int get_state(struct umcg_task __user *ut, u32 *state)
+{
+       return get_user(*state, (u32 __user *)ut);

Why the cast instead of get_user(*state, &ut->state)?
And maybe do this inline instead of adding a separate helper for it?

Quoted 6 lines
kernel/sched/umcg.c +6 -0
+}
+
+static int put_state(struct umcg_task __user *ut, u32 state)
+{
+       return put_user(state, (u32 __user *)ut);
+}

[...]

Quoted 13 lines
kernel/sched/umcg.c +13 -0
+static int do_context_switch(struct task_struct *next)
+{
+       struct umcg_task_data *utd = rcu_access_pointer(current->umcg_task_data);
+
+       /*
+        * It is important to set_current_state(TASK_INTERRUPTIBLE) before
+        * waking @next, as @next may immediately try to wake current back
+        * (e.g. current is a server, @next is a worker that immediately
+        * blocks or waits), and this next wakeup must not be lost.
+        */
+       set_current_state(TASK_INTERRUPTIBLE);
+
+       WRITE_ONCE(utd->in_wait, true);

kernel/sched/umcg.c SYSCALL_DEFINE4(umcg_register_task, u32, api_version, u32, flags, u32, group_id, · line 186

Quoted 10 lines
kernel/sched/umcg.c +10 -0
+
+       if (!try_to_wake_up(next, TASK_NORMAL, WF_CURRENT_CPU))
+               return -EAGAIN;
+
+       freezable_schedule();
+
+       WRITE_ONCE(utd->in_wait, false);
+
+       if (signal_pending(current))
+               return -EINTR;

What is this -EINTR supposed to tell userspace? We can't tell whether we were woken up by a signal or by do_context_switch() or the umcg_wake syscall, right? If we're woken by another thread calling do_context_switch() and then get a signal immediately afterwards, can't that lead to a lost wakeup?

I don't know whether trying to track the origin of the wakeup is a workable approach here; you might have to instead do cmpxchg() on the ->in_wait field and give it three states (default, waiting-for-wake and successfully-woken)?
Or you give up on trying to figure out who woke you, just always return zero, and let userspace deal with figuring out whether the wakeup was real or not. I don't know whether that'd be acceptable.

Quoted 34 lines
kernel/sched/umcg.c +26 -1
+       return 0;
+}
+
+static int do_wait(void)
+{
+       struct umcg_task_data *utd = rcu_access_pointer(current->umcg_task_data);
+
+       if (!utd)
+               return -EINVAL;
+
+       WRITE_ONCE(utd->in_wait, true);
+
+       set_current_state(TASK_INTERRUPTIBLE);
+       freezable_schedule();
+
+       WRITE_ONCE(utd->in_wait, false);
+
+       if (signal_pending(current))
+               return -EINTR;
+
+       return 0;
 }
 
 /**
@@ -90,7 +228,23 @@ SYSCALL_DEFINE1(umcg_unregister_task, u32, flags)
 SYSCALL_DEFINE2(umcg_wait, u32, flags,
                const struct __kernel_timespec __user *, timeout)
 {
-       return -ENOSYS;
+       struct umcg_task_data *utd;
+
+       if (flags)
+               return -EINVAL;
+       if (timeout)

kernel/sched/umcg.c SYSCALL_DEFINE1(umcg_unregister_task, u32, flags) · line 245

Quoted 10 lines
kernel/sched/umcg.c +10 -0
+               return -EOPNOTSUPP;
+
+       rcu_read_lock();
+       utd = rcu_dereference(current->umcg_task_data);
+       if (!utd) {
+               rcu_read_unlock();
+               return -EINVAL;
+       }
+
+       rcu_read_unlock();

rcu_access_pointer() instead of the locking and unlocking?

Quoted 12 lines
kernel/sched/umcg.c +4 -1
+       return do_wait();
 }
 
 /**
@@ -110,7 +264,39 @@ SYSCALL_DEFINE2(umcg_wait, u32, flags,
  */
 SYSCALL_DEFINE2(umcg_wake, u32, flags, u32, next_tid)
 {
-       return -ENOSYS;
+       struct umcg_task_data *next_utd;
+       struct task_struct *next;
+       int ret = -EINVAL;

kernel/sched/umcg.c SYSCALL_DEFINE2(umcg_wait, u32, flags, · line 279

Quoted 10 lines
kernel/sched/umcg.c +10 -0
+
+       if (!next_tid)
+               return -EINVAL;
+       if (flags)
+               return -EINVAL;
+
+       next = find_get_task_by_vpid(next_tid);
+       if (!next)
+               return -ESRCH;
+       rcu_read_lock();

Wouldn't it be more efficient to replace the last 4 lines with the following?

rcu_read_lock();
next = find_task_by_vpid(next_tid);
if (!next) {
err = -ESRCH;
goto out;
}

Then you don't need to use refcounting here...

kernel/sched/umcg.c SYSCALL_DEFINE2(umcg_wait, u32, flags, · line 291

Quoted 11 lines
kernel/sched/umcg.c +11 -0
+       next_utd = rcu_dereference(next->umcg_task_data);
+       if (!next_utd)
+               goto out;
+
+       if (!READ_ONCE(next_utd->in_wait)) {
+               ret = -EAGAIN;
+               goto out;
+       }
+
+       ret = wake_up_process(next);
+       put_task_struct(next);

... and you'd be able to drop this put_task_struct(), too.

Quoted 27 lines
kernel/sched/umcg.c +19 -1
+       if (ret)
+               ret = 0;
+       else
+               ret = -EAGAIN;
+
+out:
+       rcu_read_unlock();
+       return ret;
 }
 
 /**
@@ -139,5 +325,44 @@ SYSCALL_DEFINE2(umcg_wake, u32, flags, u32, next_tid)
 SYSCALL_DEFINE4(umcg_swap, u32, wake_flags, u32, next_tid, u32, wait_flags,
                const struct __kernel_timespec __user *, timeout)
 {
-       return -ENOSYS;
+       struct umcg_task_data *curr_utd;
+       struct umcg_task_data *next_utd;
+       struct task_struct *next;
+       int ret = -EINVAL;
+
+       rcu_read_lock();
+       curr_utd = rcu_dereference(current->umcg_task_data);
+
+       if (!next_tid || wake_flags || wait_flags || !curr_utd)
+               goto out;
+

kernel/sched/umcg.c SYSCALL_DEFINE2(umcg_wake, u32, flags, u32, next_tid) · line 348

Quoted 10 lines
kernel/sched/umcg.c +10 -0
+       if (timeout) {
+               ret = -EOPNOTSUPP;
+               goto out;
+       }
+
+       next = find_get_task_by_vpid(next_tid);
+       if (!next) {
+               ret = -ESRCH;
+               goto out;
+       }

There isn't any type of access check here, right? Any task can wake up any other task? That feels a bit weird to me - and if you want to keep it as-is, it should probably at least be documented that any task on the system can send you spurious wakeups if you opt in to umcg.

In contrast, shared futexes can avoid this because they get their access control implicitly from the VMA.

Quoted 4 lines
kernel/sched/umcg.c +4 -0
+       next_utd = rcu_dereference(next->umcg_task_data);
+       if (!next_utd) {
+               ret = -EINVAL;
+               goto out;

kernel/sched/umcg.c SYSCALL_DEFINE2(umcg_wake, u32, flags, u32, next_tid) · line 363

Quoted 10 lines
kernel/sched/umcg.c +10 -0
+       }
+
+       if (!READ_ONCE(next_utd->in_wait)) {
+               ret = -EAGAIN;
+               goto out;
+       }
+
+       rcu_read_unlock();
+
+       return do_context_switch(next);

It looks like the refcount of the target task is incremented but never decremented, so this probably currently leaks references?

I'd maybe try to split do_context_switch() into two parts, one that does the non-blocking waking of another task and one that does the sleeping. Then you can avoid taking a reference on the task as above - this is supposed to be a really hot fastpath, so it's a good idea to avoid atomic instructions if possible, right?

Quoted 4 lines
kernel/sched/umcg.c +3 -0
+out:
+       rcu_read_unlock();
+       return ret;
 }
maintainer
#13 lore raw

Re: [RFC PATCH v0.1 4/9] sched/umcg: implement core UMCG API

Quoted 19 lines · Jann Horn
Quoted 6 lines

SYSCALL_DEFINE2(umcg_wake, u32, flags, u32, next_tid) {

kernel/sched/umcg.c +3 -1
-       return -ENOSYS;
+       struct umcg_task_data *next_utd;
+       struct task_struct *next;
+       int ret = -EINVAL;

kernel/sched/umcg.c SYSCALL_DEFINE2(umcg_wait, u32, flags, · line 280

Quoted 10 lines
kernel/sched/umcg.c +10 -0
+
+       if (!next_tid)
+               return -EINVAL;
+       if (flags)
+               return -EINVAL;
+
+       next = find_get_task_by_vpid(next_tid);
+       if (!next)
+               return -ESRCH;
+       rcu_read_lock();

Wouldn't it be more efficient to replace the last 4 lines with the following?

Quoted 6 lines

rcu_read_lock();
next = find_task_by_vpid(next_tid);
if (!next) {
err = -ESRCH;
goto out;
}

This wakeup crud needs to modify the umcg->state, which is a user variable. That can't be done under RCU. Weirdly the proposed code doesn't actually do any of that for undocumented raisins :/

Quoted 50 lines

Then you don't need to use refcounting here...

kernel/sched/umcg.c SYSCALL_DEFINE2(umcg_wait, u32, flags, · line 291

Quoted 11 lines
kernel/sched/umcg.c +11 -0
+       next_utd = rcu_dereference(next->umcg_task_data);
+       if (!next_utd)
+               goto out;
+
+       if (!READ_ONCE(next_utd->in_wait)) {
+               ret = -EAGAIN;
+               goto out;
+       }
+
+       ret = wake_up_process(next);
+       put_task_struct(next);

... and you'd be able to drop this put_task_struct(), too.

Quoted 34 lines
kernel/sched/umcg.c +26 -1
+       if (ret)
+               ret = 0;
+       else
+               ret = -EAGAIN;
+
+out:
+       rcu_read_unlock();
+       return ret;
 }
 
 /**
@@ -139,5 +325,44 @@ SYSCALL_DEFINE2(umcg_wake, u32, flags, u32, next_tid)
 SYSCALL_DEFINE4(umcg_swap, u32, wake_flags, u32, next_tid, u32, wait_flags,
                const struct __kernel_timespec __user *, timeout)
 {
-       return -ENOSYS;
+       struct umcg_task_data *curr_utd;
+       struct umcg_task_data *next_utd;
+       struct task_struct *next;
+       int ret = -EINVAL;
+
+       rcu_read_lock();
+       curr_utd = rcu_dereference(current->umcg_task_data);
+
+       if (!next_tid || wake_flags || wait_flags || !curr_utd)
+               goto out;
+
+       if (timeout) {
+               ret = -EOPNOTSUPP;
+               goto out;
+       }
+
+       next = find_get_task_by_vpid(next_tid);
+       if (!next) {
Quoted 8 lines

kernel/sched/umcg.c SYSCALL_DEFINE2(umcg_wake, u32, flags, u32, next_tid) · line 348

Quoted 3 lines
kernel/sched/umcg.c +3 -0
+               ret = -ESRCH;
+               goto out;
+       }

There isn't any type of access check here, right? Any task can wake up any other task? That feels a bit weird to me - and if you want to keep it as-is, it should probably at least be documented that any task on the system can send you spurious wakeups if you opt in to umcg.

You can only send wakeups to other UMCG thingies, per the next->umcg_task_data check below. That said..

Quoted 2 lines

In contrast, shared futexes can avoid this because they get their access control implicitly from the VMA.

Every task must expect spurious wakups at all times, always (for TASK_NORMAL wakeups that is). There's plenty ways to generate them.

Quoted 5 lines
Quoted 5 lines
kernel/sched/umcg.c +5 -0
+       next_utd = rcu_dereference(next->umcg_task_data);
+       if (!next_utd) {
+               ret = -EINVAL;
+               goto out;
+       }
#14 lore raw

RFC PATCH 5/9 lib/umcg: implement UMCG core API for userspace

In reply to Peter Oskolkov

UMCG (= User Managed Concurrency Groups) kernel API is designed to be minimalistic and requires tightly coupled userspace code to make it easy to use.

Add userspace UMCG core API to achieve this goal.

---
 tools/lib/umcg/.gitignore |   4 +
 tools/lib/umcg/Makefile   |  11 ++
 tools/lib/umcg/libumcg.c  | 350 ++++++++++++++++++++++++++++++++++++++
 tools/lib/umcg/libumcg.h  | 154 +++++++++++++++++
 4 files changed, 519 insertions(+)
 create mode 100644 tools/lib/umcg/.gitignore
 create mode 100644 tools/lib/umcg/Makefile
 create mode 100644 tools/lib/umcg/libumcg.c
 create mode 100644 tools/lib/umcg/libumcg.h
tools/lib/umcg/.gitignore new file +4 -0
new file mode 100644
index 000000000000..ea55ae666041
@@ -0,0 +1,4 @@
+PDX-License-Identifier: GPL-2.0-only
+libumcg.a
+libumcg.o
+
tools/lib/umcg/Makefile new file +11 -0
new file mode 100644
index 000000000000..fa53fd5a851a
@@ -0,0 +1,11 @@
+# SPDX-License-Identifier: GPL-2.0
+
+CFLAGS += -g -I../../../usr/include/ -I../../include/
+
+libumcg.a: libumcg.o
+	ar rc libumcg.a libumcg.o
+
+libumcg.o: libumcg.c
+
+clean :
+	rm libumcg.a libumcg.o
tools/lib/umcg/libumcg.c new file +350 -0

350 lines not on this page · raw message

tools/lib/umcg/libumcg.h new file +154 -0

154 lines not on this page · raw message

Signature · 1 line
2.31.1.818.g46aad6cb9e-goog
#15 lore raw

RFC PATCH 6/9 selftests/umcg: add UMCG core API selftest

In reply to Peter Oskolkov

Add UMCG core API selftests. In particular, test that umcg_wait/umcg_wake/umcg_swap behave correctly when racing with each other.

---
 tools/testing/selftests/umcg/.gitignore       |   2 +
 tools/testing/selftests/umcg/Makefile         |  13 +
 tools/testing/selftests/umcg/umcg_core_test.c | 347 ++++++++++++++++++
 3 files changed, 362 insertions(+)
 create mode 100644 tools/testing/selftests/umcg/.gitignore
 create mode 100644 tools/testing/selftests/umcg/Makefile
 create mode 100644 tools/testing/selftests/umcg/umcg_core_test.c
tools/testing/selftests/umcg/.gitignore new file +2 -0
new file mode 100644
index 000000000000..89cca24e5907
@@ -0,0 +1,2 @@
+# SPDX-License-Identifier: GPL-2.0-only
+umcg_core_test
tools/testing/selftests/umcg/Makefile new file +13 -0
new file mode 100644
index 000000000000..b151098e2ed1
@@ -0,0 +1,13 @@
+# SPDX-License-Identifier: GPL-2.0-only
+
+TOOLSDIR := $(abspath ../../..)
+LIBUMCGDIR := $(TOOLSDIR)/lib/umcg
+
+CFLAGS += -g -O0 -I$(LIBUMCGDIR) -I$(TOOLSDIR)/include/ -I../../../../usr/include/
+LDLIBS += -lpthread -static
+
+TEST_GEN_PROGS := umcg_core_test
+
+include ../lib.mk
+
+$(OUTPUT)/umcg_core_test: umcg_core_test.c $(LIBUMCGDIR)/libumcg.c
tools/testing/selftests/umcg/umcg_core_test.c new file +347 -0

347 lines not on this page · raw message

Signature · 1 line
2.31.1.818.g46aad6cb9e-goog
#16 lore raw

RFC PATCH 7/9 sched/umcg: add UMCG server/worker API (early RFC)

In reply to Peter Oskolkov

Implement UMCG server/worker API.

This is an early RFC patch - the code seems working, but more testing is needed. Gaps I plan to address before this is ready for a detailed review:

- preemption/interrupt handling;
- better documentation/comments;
- tracing;
- additional testing;
- corner cases like abnormal process/task termination;
- in some cases where I kill the task (umcg_segv), returning an error may be more appropriate.

All in all, please focus more on the high-level approach
and less on things like variable names, (doc) comments, or indentation.

---
 include/linux/mm_types.h |   5 +
 include/linux/syscalls.h |   5 +
 kernel/fork.c            |  11 +
 kernel/sched/core.c      |  11 +
 kernel/sched/umcg.c      | 764 ++++++++++++++++++++++++++++++++++++++-
 kernel/sched/umcg.h      |  54 +++
 mm/init-mm.c             |   4 +
 7 files changed, 845 insertions(+), 9 deletions(-)
include/linux/mm_types.h +5 -0
index 6613b26a8894..5ca7b7d55775 100644
@@ -562,6 +562,11 @@ struct mm_struct {
 #ifdef CONFIG_IOMMU_SUPPORT
 		u32 pasid;
 #endif
+
+#ifdef CONFIG_UMCG
+	spinlock_t umcg_lock;
+	struct list_head umcg_groups;
+#endif
 	} __randomize_layout;
 
 	/*
include/linux/syscalls.h +5 -0
index 15de3e34ccee..2781659daaf1 100644
@@ -1059,6 +1059,11 @@ asmlinkage long umcg_wait(u32 flags, const struct __kernel_timespec __user *time
 asmlinkage long umcg_wake(u32 flags, u32 next_tid);
 asmlinkage long umcg_swap(u32 wake_flags, u32 next_tid, u32 wait_flags,
 				const struct __kernel_timespec __user *timeout);
+asmlinkage long umcg_create_group(u32 api_version, u64, flags);
+asmlinkage long umcg_destroy_group(u32 group_id);
+asmlinkage long umcg_poll_worker(u32 flags, struct umcg_task __user **ut);
+asmlinkage long umcg_run_worker(u32 flags, u32 worker_tid,
+		struct umcg_task __user **ut);
 
 /*
  * Architecture-specific system calls
kernel/fork.c +11 -0
index ace4631b5b54..3a2a7950df8e 100644
@@ -1026,6 +1026,10 @@ static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
 	seqcount_init(&mm->write_protect_seq);
 	mmap_init_lock(mm);
 	INIT_LIST_HEAD(&mm->mmlist);
+#ifdef CONFIG_UMCG
+	spin_lock_init(&mm->umcg_lock);
+	INIT_LIST_HEAD(&mm->umcg_groups);
+#endif
 	mm->core_state = NULL;
 	mm_pgtables_bytes_init(mm);
 	mm->map_count = 0;
@@ -1102,6 +1106,13 @@ static inline void __mmput(struct mm_struct *mm)
 		list_del(&mm->mmlist);
 		spin_unlock(&mmlist_lock);
 	}
+#ifdef CONFIG_UMCG
+	if (!list_empty(&mm->umcg_groups)) {
+		spin_lock(&mm->umcg_lock);
+		list_del(&mm->umcg_groups);
+		spin_unlock(&mm->umcg_lock);
+	}
+#endif
 	if (mm->binfmt)
 		module_put(mm->binfmt->module);
 	mmdrop(mm);
kernel/sched/core.c +11 -0
index 462104f13c28..e657a35655b1 100644
@@ -26,6 +26,7 @@
 
 #include "pelt.h"
 #include "smp.h"
+#include "umcg.h"
 
 /*
  * Export tracepoints that act as a bare tracehook (ie: have no trace event
@@ -6012,10 +6013,20 @@ static inline void sched_submit_work(struct task_struct *tsk)
 	 */
 	if (blk_needs_flush_plug(tsk))
 		blk_schedule_flush_plug(tsk);
+
+#ifdef CONFIG_UMCG
+	if (rcu_access_pointer(tsk->umcg_task_data))
+		umcg_on_block();
+#endif
 }
 
 static void sched_update_worker(struct task_struct *tsk)
 {
+#ifdef CONFIG_UMCG
+	if (rcu_access_pointer(tsk->umcg_task_data))
+		umcg_on_wake();
+#endif
+
 	if (tsk->flags & (PF_WQ_WORKER | PF_IO_WORKER)) {
 		if (tsk->flags & PF_WQ_WORKER)
 			wq_worker_running(tsk);
kernel/sched/umcg.c +755 -9

896 lines not on this page · raw message

kernel/sched/umcg.h +54 -0

71 lines not on this page · raw message

mm/init-mm.c +4 -0
index 153162669f80..85e4a8ecfd91 100644
@@ -36,6 +36,10 @@ struct mm_struct init_mm = {
 	.page_table_lock =  __SPIN_LOCK_UNLOCKED(init_mm.page_table_lock),
 	.arg_lock	=  __SPIN_LOCK_UNLOCKED(init_mm.arg_lock),
 	.mmlist		= LIST_HEAD_INIT(init_mm.mmlist),
+#ifdef CONFIG_UMCG
+	.umcg_lock	= __SPIN_LOCK_UNLOCKED(init_mm.umcg_lock),
+	.umcg_groups	= LIST_HEAD_INIT(init_mm.umcg_groups),
+#endif
 	.user_ns	= &init_user_ns,
 	.cpu_bitmap	= CPU_BITS_NONE,
 	INIT_MM_CONTEXT(init_mm)
Signature · 1 line
2.31.1.818.g46aad6cb9e-goog
#17 lore raw

Re: [RFC PATCH v0.1 7/9] sched/umcg: add UMCG server/worker API (early RFC)

Quoted 76 lines · Peter Oskolkov

Implement UMCG server/worker API.

This is an early RFC patch - the code seems working, but more testing is needed. Gaps I plan to address before this is ready for a detailed review:

- preemption/interrupt handling;
- better documentation/comments;
- tracing;
- additional testing;
- corner cases like abnormal process/task termination;
- in some cases where I kill the task (umcg_segv), returning an error may be more appropriate.

All in all, please focus more on the high-level approach
and less on things like variable names, (doc) comments, or indentation.

---
 include/linux/mm_types.h |   5 +
 include/linux/syscalls.h |   5 +
 kernel/fork.c            |  11 +
 kernel/sched/core.c      |  11 +
 kernel/sched/umcg.c      | 764 ++++++++++++++++++++++++++++++++++++++-
 kernel/sched/umcg.h      |  54 +++
 mm/init-mm.c             |   4 +
 7 files changed, 845 insertions(+), 9 deletions(-)
include/linux/mm_types.h +5 -0
index 6613b26a8894..5ca7b7d55775 100644
@@ -562,6 +562,11 @@ struct mm_struct {
 #ifdef CONFIG_IOMMU_SUPPORT
 		u32 pasid;
 #endif
+
+#ifdef CONFIG_UMCG
+	spinlock_t umcg_lock;
+	struct list_head umcg_groups;
+#endif
 	} __randomize_layout;
 
 	/*
include/linux/syscalls.h +5 -0
index 15de3e34ccee..2781659daaf1 100644
@@ -1059,6 +1059,11 @@ asmlinkage long umcg_wait(u32 flags, const struct __kernel_timespec __user *time
 asmlinkage long umcg_wake(u32 flags, u32 next_tid);
 asmlinkage long umcg_swap(u32 wake_flags, u32 next_tid, u32 wait_flags,
 				const struct __kernel_timespec __user *timeout);
+asmlinkage long umcg_create_group(u32 api_version, u64, flags);
+asmlinkage long umcg_destroy_group(u32 group_id);
+asmlinkage long umcg_poll_worker(u32 flags, struct umcg_task __user **ut);
+asmlinkage long umcg_run_worker(u32 flags, u32 worker_tid,
+		struct umcg_task __user **ut);
 
 /*
  * Architecture-specific system calls
kernel/fork.c +4 -0
index ace4631b5b54..3a2a7950df8e 100644
@@ -1026,6 +1026,10 @@ static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
 	seqcount_init(&mm->write_protect_seq);
 	mmap_init_lock(mm);
 	INIT_LIST_HEAD(&mm->mmlist);
+#ifdef CONFIG_UMCG
+	spin_lock_init(&mm->umcg_lock);
+	INIT_LIST_HEAD(&mm->umcg_groups);
+#endif
 	mm->core_state = NULL;
 	mm_pgtables_bytes_init(mm);
 	mm->map_count = 0;

kernel/fork.c static inline void __mmput(struct mm_struct *mm) · line 1112

Quoted 7 lines
kernel/fork.c +4 -0
@@ -1102,6 +1106,13 @@ static inline void __mmput(struct mm_struct *mm)
 		list_del(&mm->mmlist);
 		spin_unlock(&mmlist_lock);
 	}
+#ifdef CONFIG_UMCG
+	if (!list_empty(&mm->umcg_groups)) {
+		spin_lock(&mm->umcg_lock);
+		list_del(&mm->umcg_groups);

I am not sure that I understand what is going on here. umsg_groups is the head of a group list. list_del is usually called on list entries.

Should we enumirate all groups here and destroy them?

Quoted 6 lines
kernel/fork.c +3 -0
+		spin_unlock(&mm->umcg_lock);
+	}
+#endif
 	if (mm->binfmt)
 		module_put(mm->binfmt->module);
 	mmdrop(mm);

...

Quoted 30 lines
kernel/fork.c +30 -0
+/**
+ * sys_umcg_create_group - create a UMCG group
+ * @api_version:           Requested API version.
+ * @flags:                 Reserved.
+ *
+ * Return:
+ * >= 0                - the group ID
+ * -EOPNOTSUPP         - @api_version is not supported
+ * -EINVAL             - @flags is not valid
+ * -ENOMEM             - not enough memory
+ */
+SYSCALL_DEFINE2(umcg_create_group, u32, api_version, u64, flags)
+{
+	int ret;
+	struct umcg_group *group;
+	struct umcg_group *list_entry;
+	struct mm_struct *mm = current->mm;
+
+	if (flags)
+		return -EINVAL;
+
+	if (__api_version(api_version))
+		return -EOPNOTSUPP;
+
+	group = kzalloc(sizeof(struct umcg_group), GFP_KERNEL);
+	if (!group)
+		return -ENOMEM;
+
+	spin_lock_init(&group->lock);
+	INIT_LIST_HEAD(&group->list);

kernel/fork.c

Quoted 10 lines
kernel/fork.c +10 -0
+	INIT_LIST_HEAD(&group->waiters);
+	group->flags = flags;
+	group->api_version = api_version;
+
+	spin_lock(&mm->umcg_lock);
+
+	list_for_each_entry_rcu(list_entry, &mm->umcg_groups, list) {
+		if (list_entry->group_id >= group->group_id)
+			group->group_id = list_entry->group_id + 1;
+	}

pls take into account that we need to be able to save and restore umcg groups from user-space. There is the CRIU project that allows to checkpoint/restore processes.

kernel/fork.c

Quoted 2 lines
kernel/fork.c +2 -0
+
+	list_add_rcu(&mm->umcg_groups, &group->list);

I think it should be:

	list_add_rcu(&group->list, &mm->umcg_groups);

kernel/fork.c

Quoted 7 lines
kernel/fork.c +7 -0
+
+	ret = group->group_id;
+	spin_unlock(&mm->umcg_lock);
+
+	return ret;
+}
+

Thanks,
Andrei

#18 lore raw

Re: [RFC PATCH v0.1 7/9] sched/umcg: add UMCG server/worker API (early RFC)

In reply to Peter Oskolkov
[If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in https://git-scm.com/docs/git-format-patch]

Hi Peter,

[FYI, it's a private test report for your RFC patch.]
[auto build test WARNING on tip/sched/core]
[also build test WARNING on tip/master]
[cannot apply to kselftest/next linus/master v5.13-rc2 next-20210521] [If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch]

url:    https://github.com/0day-ci/linux/commits/Peter-Oskolkov/UMCG-early-preview-RFC-patchset/20210522-232442
base:   https://git.kernel.org/pub/scm/linux/kernel/git/tip/tip.git 1699949d3314e5d1956fb082e4cd4798bf6149fc
config: um-allmodconfig (attached as .config)
compiler: gcc-9 (Debian 9.3.0-22) 9.3.0

reproduce (this is a W=1 build):
# https://github.com/0day-ci/linux/commit/634e0c0b3bf5d6ede3674f9c754202b1a521ab89
git remote add linux-review https://github.com/0day-ci/linux
git fetch --no-tags linux-review Peter-Oskolkov/UMCG-early-preview-RFC-patchset/20210522-232442 git checkout 634e0c0b3bf5d6ede3674f9c754202b1a521ab89
# save the attached .config to linux build tree
make W=1 ARCH=um

If you fix the issue, kindly add following tag as appropriate

All warnings (new ones prefixed by >>):

In file included from kernel/sched/umcg.c:8:
include/linux/syscalls.h:1062:57: error: unknown type name 'flags'

    1062 | asmlinkage long umcg_create_group(u32 api_version, u64, flags);
         |                                                         ^~~~~
   kernel/sched/umcg.c: In function '__do_sys_umcg_run_worker':
>> kernel/sched/umcg.c:889:27: warning: variable 'worker_ut' set but not used [-Wunused-but-set-variable]
     889 |  struct umcg_task __user *worker_ut;
         |                           ^~~~~~~~~
>> kernel/sched/umcg.c:888:27: warning: variable 'server_ut' set but not used [-Wunused-but-set-variable]
     888 |  struct umcg_task __user *server_ut;
         |                           ^~~~~~~~~

vim +/worker_ut +889 kernel/sched/umcg.c

858
859 /**
860 * sys_umcg_run_worker - "run" a RUNNABLE worker as a server

   861	 * @flags:       reserved;
   862	 * @worker_tid:  tid of the worker to run;
   863	 * @ut:          the control struct umcg_task of the worker that blocked
   864	 *               during this "run".
   865	 *
   866	 * The worker must be in RUNNABLE state. The server (=current task)
   867	 * wakes the worker and blocks; when the worker, or one of the workers
   868	 * in umcg_swap chain, blocks, the server is woken and the syscall returns
   869	 * with ut indicating the blocked worker.
   870	 *
   871	 * If the worker exits or unregisters itself, the syscall succeeds with
   872	 * ut == NULL.
   873	 *
   874	 * Return:
   875	 * 0       - Ok;
   876	 * -EINTR  - a signal was received;
   877	 * -EINVAL - one of the parameters is wrong, or a precondition was not met.
   878	 */
   879	SYSCALL_DEFINE3(umcg_run_worker, u32, flags, u32, worker_tid,
   880			struct umcg_task __user **, ut)
   881	{
   882		int ret = -EINVAL;
   883		struct task_struct *worker;
   884		struct task_struct *server = current;
   885		struct umcg_task __user *result = NULL;
   886		struct umcg_task_data *worker_utd;
   887		struct umcg_task_data *server_utd;
 > 888		struct umcg_task __user *server_ut;
 > 889		struct umcg_task __user *worker_ut;

890
891 if (!ut)
892 return -EINVAL;
893
894 rcu_read_lock();
895 server_utd = rcu_dereference(server->umcg_task_data);
896
897 if (!server_utd || server_utd->task_type != UMCG_TT_SERVER)
898 goto out_rcu;
899
900 if (flags)
901 goto out_rcu;
902
903 worker = find_get_task_by_vpid(worker_tid);
904 if (!worker) {
905 ret = -ESRCH;
906 goto out_rcu;
907 }
908
909 worker_utd = rcu_dereference(worker->umcg_task_data);
910 if (!worker_utd)
911 goto out_rcu;
912
913 if (!READ_ONCE(worker_utd->in_wait)) {
914 ret = -EAGAIN;
915 goto out_rcu;
916 }
917
918 if (server_utd->group != worker_utd->group)
919 goto out_rcu;
920
921 if (rcu_access_pointer(server_utd->peer) != worker)
922 umcg_detach_peer();
923
924 if (!rcu_access_pointer(server_utd->peer)) {
925 umcg_lock_pair(server, worker);
926 WARN_ON(worker_utd->peer);
927 rcu_assign_pointer(server_utd->peer, worker);
928 rcu_assign_pointer(worker_utd->peer, server);
929 umcg_unlock_pair(server, worker);
930 }
931
932 server_ut = server_utd->umcg_task;
933 worker_ut = server_utd->umcg_task;
934
935 rcu_read_unlock();
936
937 ret = do_context_switch(worker);
938 if (ret)
939 return ret;
940
941 rcu_read_lock();
942 worker = rcu_dereference(server_utd->peer);
943 if (worker) {
944 worker_utd = rcu_dereference(worker->umcg_task_data);
945 if (worker_utd)
946 result = worker_utd->umcg_task;
947 }
948 rcu_read_unlock();
949
950 if (put_user(result, ut))
951 return -EFAULT;
952 return 0;
953
954 out_rcu:
955 rcu_read_unlock();
956 return ret;
957 }
958

---
0-DAY CI Kernel Test Service, Intel Corporation
https://lists.01.org/hyperkitty/list/kbuild-all(a)lists.01.org

#19 lore raw

Re: [RFC PATCH v0.1 7/9] sched/umcg: add UMCG server/worker API (early RFC)

In reply to Peter Oskolkov
[If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in https://git-scm.com/docs/git-format-patch]

Hi Peter,

[FYI, it's a private test report for your RFC patch.]
[auto build test WARNING on tip/sched/core]
[also build test WARNING on tip/master]
[cannot apply to kselftest/next linus/master v5.13-rc2 next-20210521] [If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch]

url:    https://github.com/0day-ci/linux/commits/Peter-Oskolkov/UMCG-early-preview-RFC-patchset/20210522-232442
base:   https://git.kernel.org/pub/scm/linux/kernel/git/tip/tip.git 1699949d3314e5d1956fb082e4cd4798bf6149fc
config: riscv-randconfig-r031-20210523 (attached as .config)
compiler: clang version 13.0.0 (https://github.com/llvm/llvm-project e84a9b9bb3051c35dea993cdad7b3d2575638f85)

reproduce (this is a W=1 build):
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross chmod +x ~/bin/make.cross
# install riscv cross compiling tool for clang build
# apt-get install binutils-riscv64-linux-gnu
# https://github.com/0day-ci/linux/commit/634e0c0b3bf5d6ede3674f9c754202b1a521ab89
git remote add linux-review https://github.com/0day-ci/linux
git fetch --no-tags linux-review Peter-Oskolkov/UMCG-early-preview-RFC-patchset/20210522-232442 git checkout 634e0c0b3bf5d6ede3674f9c754202b1a521ab89
# save the attached .config to linux build tree
COMPILER_INSTALL_PATH=$HOME/0day COMPILER=clang make.cross ARCH=riscv

If you fix the issue, kindly add following tag as appropriate

All warnings (new ones prefixed by >>):

In file included from arch/riscv/kernel/signal.c:11:

>> include/linux/syscalls.h:1062:57: warning: declaration specifier missing, defaulting to 'int'
   asmlinkage long umcg_create_group(u32 api_version, u64, flags);
                                                           ^
                                                           int
   arch/riscv/kernel/signal.c:309:27: warning: no previous prototype for function 'do_notify_resume' [-Wmissing-prototypes]
   asmlinkage __visible void do_notify_resume(struct pt_regs *regs,
                             ^
   arch/riscv/kernel/signal.c:309:22: note: declare 'static' if the function is not intended to be used outside of this translation unit
   asmlinkage __visible void do_notify_resume(struct pt_regs *regs,
                        ^
                        static 
   2 warnings generated.
--
   In file included from arch/riscv/kernel/syscall_table.c:8:
>> include/linux/syscalls.h:1062:57: warning: declaration specifier missing, defaulting to 'int'
   asmlinkage long umcg_create_group(u32 api_version, u64, flags);
                                                           ^
                                                           int
   In file included from arch/riscv/kernel/syscall_table.c:18:
   In file included from arch/riscv/include/asm/unistd.h:13:
   In file included from arch/riscv/include/uapi/asm/unistd.h:24:
   include/uapi/asm-generic/unistd.h:877:34: error: use of undeclared identifier 'sys_umcg_api_version'; did you mean 'umcg_api_version'?
   __SYSCALL(__NR_umcg_api_version, sys_umcg_api_version)
                                    ^~~~~~~~~~~~~~~~~~~~
                                    umcg_api_version
   arch/riscv/kernel/syscall_table.c:14:37: note: expanded from macro '__SYSCALL'
   #define __SYSCALL(nr, call)     [nr] = (call),
                                           ^
   include/linux/syscalls.h:1054:17: note: 'umcg_api_version' declared here
   asmlinkage long umcg_api_version(u32 api_version, u32 flags);
                   ^
   In file included from arch/riscv/kernel/syscall_table.c:18:
   In file included from arch/riscv/include/asm/unistd.h:13:
   In file included from arch/riscv/include/uapi/asm/unistd.h:24:
   include/uapi/asm-generic/unistd.h:879:36: error: use of undeclared identifier 'sys_umcg_register_task'; did you mean 'umcg_register_task'?
   __SYSCALL(__NR_umcg_register_task, sys_umcg_register_task)
                                      ^~~~~~~~~~~~~~~~~~~~~~
                                      umcg_register_task
   arch/riscv/kernel/syscall_table.c:14:37: note: expanded from macro '__SYSCALL'
   #define __SYSCALL(nr, call)     [nr] = (call),
                                           ^
   include/linux/syscalls.h:1055:17: note: 'umcg_register_task' declared here
   asmlinkage long umcg_register_task(u32 api_version, u32 flags, u32 group_id,
                   ^
   In file included from arch/riscv/kernel/syscall_table.c:18:
   In file included from arch/riscv/include/asm/unistd.h:13:
   In file included from arch/riscv/include/uapi/asm/unistd.h:24:
   include/uapi/asm-generic/unistd.h:881:38: error: use of undeclared identifier 'sys_umcg_unregister_task'; did you mean 'umcg_unregister_task'?
   __SYSCALL(__NR_umcg_unregister_task, sys_umcg_unregister_task)
                                        ^~~~~~~~~~~~~~~~~~~~~~~~
                                        umcg_unregister_task
   arch/riscv/kernel/syscall_table.c:14:37: note: expanded from macro '__SYSCALL'
   #define __SYSCALL(nr, call)     [nr] = (call),
                                           ^
   include/linux/syscalls.h:1057:17: note: 'umcg_unregister_task' declared here
   asmlinkage long umcg_unregister_task(u32 flags);
                   ^
   In file included from arch/riscv/kernel/syscall_table.c:18:
   In file included from arch/riscv/include/asm/unistd.h:13:
   In file included from arch/riscv/include/uapi/asm/unistd.h:24:
   include/uapi/asm-generic/unistd.h:883:27: error: use of undeclared identifier 'sys_umcg_wait'; did you mean 'umcg_wait'?
   __SYSCALL(__NR_umcg_wait, sys_umcg_wait)
                             ^~~~~~~~~~~~~
                             umcg_wait
   arch/riscv/kernel/syscall_table.c:14:37: note: expanded from macro '__SYSCALL'
   #define __SYSCALL(nr, call)     [nr] = (call),
                                           ^
   include/linux/syscalls.h:1058:17: note: 'umcg_wait' declared here
   asmlinkage long umcg_wait(u32 flags, const struct __kernel_timespec __user *timeout);
                   ^
   In file included from arch/riscv/kernel/syscall_table.c:18:
   In file included from arch/riscv/include/asm/unistd.h:13:
   In file included from arch/riscv/include/uapi/asm/unistd.h:24:
   include/uapi/asm-generic/unistd.h:885:27: error: use of undeclared identifier 'sys_umcg_wake'; did you mean 'umcg_wake'?
   __SYSCALL(__NR_umcg_wake, sys_umcg_wake)
                             ^~~~~~~~~~~~~
                             umcg_wake
   arch/riscv/kernel/syscall_table.c:14:37: note: expanded from macro '__SYSCALL'
   #define __SYSCALL(nr, call)     [nr] = (call),
                                           ^
   include/linux/syscalls.h:1059:17: note: 'umcg_wake' declared here
   asmlinkage long umcg_wake(u32 flags, u32 next_tid);
                   ^
   In file included from arch/riscv/kernel/syscall_table.c:18:
   In file included from arch/riscv/include/asm/unistd.h:13:
   In file included from arch/riscv/include/uapi/asm/unistd.h:24:
   include/uapi/asm-generic/unistd.h:887:27: error: use of undeclared identifier 'sys_umcg_swap'; did you mean 'umcg_swap'?
   __SYSCALL(__NR_umcg_swap, sys_umcg_swap)
                             ^~~~~~~~~~~~~
                             umcg_swap
   arch/riscv/kernel/syscall_table.c:14:37: note: expanded from macro '__SYSCALL'
   #define __SYSCALL(nr, call)     [nr] = (call),
                                           ^
   include/linux/syscalls.h:1060:17: note: 'umcg_swap' declared here
   asmlinkage long umcg_swap(u32 wake_flags, u32 next_tid, u32 wait_flags,
                   ^
   In file included from arch/riscv/kernel/syscall_table.c:18:
   In file included from arch/riscv/include/asm/unistd.h:13:
   In file included from arch/riscv/include/uapi/asm/unistd.h:24:
   include/uapi/asm-generic/unistd.h:889:35: error: use of undeclared identifier 'sys_umcg_create_group'; did you mean 'umcg_create_group'?
   __SYSCALL(__NR_umcg_create_group, sys_umcg_create_group)
                                     ^~~~~~~~~~~~~~~~~~~~~
                                     umcg_create_group
   arch/riscv/kernel/syscall_table.c:14:37: note: expanded from macro '__SYSCALL'
   #define __SYSCALL(nr, call)     [nr] = (call),
                                           ^
   include/linux/syscalls.h:1062:17: note: 'umcg_create_group' declared here
   asmlinkage long umcg_create_group(u32 api_version, u64, flags);
                   ^
   In file included from arch/riscv/kernel/syscall_table.c:18:
   In file included from arch/riscv/include/asm/unistd.h:13:
   In file included from arch/riscv/include/uapi/asm/unistd.h:24:
   include/uapi/asm-generic/unistd.h:891:36: error: use of undeclared identifier 'sys_umcg_destroy_group'; did you mean 'umcg_destroy_group'?
   __SYSCALL(__NR_umcg_destroy_group, sys_umcg_destroy_group)
                                      ^~~~~~~~~~~~~~~~~~~~~~
--
   In file included from arch/riscv/kernel/sys_riscv.c:8:
>> include/linux/syscalls.h:1062:57: warning: declaration specifier missing, defaulting to 'int'
   asmlinkage long umcg_create_group(u32 api_version, u64, flags);
                                                           ^
                                                           int

1 warning generated.

Kconfig warnings: (for reference only)
WARNING: unmet direct dependencies detected for LOCKDEP
Depends on DEBUG_KERNEL && LOCK_DEBUGGING_SUPPORT && (FRAME_POINTER || MIPS || PPC || S390 || MICROBLAZE || ARM || ARC || X86) Selected by
- DEBUG_LOCK_ALLOC && DEBUG_KERNEL && LOCK_DEBUGGING_SUPPORT

vim +/int +1062 include/linux/syscalls.h

903
904 /* mm/, CONFIG_MMU only */
905 asmlinkage long sys_swapon(const char __user *specialfile, int swap_flags);
906 asmlinkage long sys_swapoff(const char __user *specialfile);
907 asmlinkage long sys_mprotect(unsigned long start, size_t len,
908 unsigned long prot);
909 asmlinkage long sys_msync(unsigned long start, size_t len, int flags);
910 asmlinkage long sys_mlock(unsigned long start, size_t len);
911 asmlinkage long sys_munlock(unsigned long start, size_t len);
912 asmlinkage long sys_mlockall(int flags);
913 asmlinkage long sys_munlockall(void);
914 asmlinkage long sys_mincore(unsigned long start, size_t len,
915 unsigned char __user * vec);
916 asmlinkage long sys_madvise(unsigned long start, size_t len, int behavior);
917 asmlinkage long sys_process_madvise(int pidfd, const struct iovec __user *vec,
918 size_t vlen, int behavior, unsigned int flags);
919 asmlinkage long sys_remap_file_pages(unsigned long start, unsigned long size,
920 unsigned long prot, unsigned long pgoff,
921 unsigned long flags);
922 asmlinkage long sys_mbind(unsigned long start, unsigned long len,
923 unsigned long mode,
924 const unsigned long __user *nmask,
925 unsigned long maxnode,
926 unsigned flags);
927 asmlinkage long sys_get_mempolicy(int __user *policy,
928 unsigned long __user *nmask,
929 unsigned long maxnode,
930 unsigned long addr, unsigned long flags);
931 asmlinkage long sys_set_mempolicy(int mode, const unsigned long __user *nmask,
932 unsigned long maxnode);
933 asmlinkage long sys_migrate_pages(pid_t pid, unsigned long maxnode,
934 const unsigned long __user *from,
935 const unsigned long __user *to);
936 asmlinkage long sys_move_pages(pid_t pid, unsigned long nr_pages,
937 const void __user * __user *pages,
938 const int __user *nodes,
939 int __user *status,
940 int flags);
941
942 asmlinkage long sys_rt_tgsigqueueinfo(pid_t tgid, pid_t pid, int sig,
943 siginfo_t __user *uinfo);
944 asmlinkage long sys_perf_event_open(
945 struct perf_event_attr __user *attr_uptr,
946 pid_t pid, int cpu, int group_fd, unsigned long flags);
947 asmlinkage long sys_accept4(int, struct sockaddr __user *, int __user *, int);
948 asmlinkage long sys_recvmmsg(int fd, struct mmsghdr __user *msg,
949 unsigned int vlen, unsigned flags,
950 struct __kernel_timespec __user *timeout);
951 asmlinkage long sys_recvmmsg_time32(int fd, struct mmsghdr __user *msg,
952 unsigned int vlen, unsigned flags,
953 struct old_timespec32 __user *timeout);
954
955 asmlinkage long sys_wait4(pid_t pid, int __user *stat_addr,
956 int options, struct rusage __user *ru);
957 asmlinkage long sys_prlimit64(pid_t pid, unsigned int resource,
958 const struct rlimit64 __user *new_rlim,
959 struct rlimit64 __user *old_rlim);
960 asmlinkage long sys_fanotify_init(unsigned int flags, unsigned int event_f_flags);
961 asmlinkage long sys_fanotify_mark(int fanotify_fd, unsigned int flags,
962 u64 mask, int fd,
963 const char __user *pathname);
964 asmlinkage long sys_name_to_handle_at(int dfd, const char __user *name,
965 struct file_handle __user *handle,
966 int __user *mnt_id, int flag);
967 asmlinkage long sys_open_by_handle_at(int mountdirfd,
968 struct file_handle __user *handle,
969 int flags);
970 asmlinkage long sys_clock_adjtime(clockid_t which_clock,
971 struct __kernel_timex __user *tx);
972 asmlinkage long sys_clock_adjtime32(clockid_t which_clock,
973 struct old_timex32 __user *tx);
974 asmlinkage long sys_syncfs(int fd);
975 asmlinkage long sys_setns(int fd, int nstype);
976 asmlinkage long sys_pidfd_open(pid_t pid, unsigned int flags);
977 asmlinkage long sys_sendmmsg(int fd, struct mmsghdr __user *msg,
978 unsigned int vlen, unsigned flags);
979 asmlinkage long sys_process_vm_readv(pid_t pid,

   980					     const struct iovec __user *lvec,
   981					     unsigned long liovcnt,
   982					     const struct iovec __user *rvec,
   983					     unsigned long riovcnt,
   984					     unsigned long flags);
   985	asmlinkage long sys_process_vm_writev(pid_t pid,
   986					      const struct iovec __user *lvec,
   987					      unsigned long liovcnt,
   988					      const struct iovec __user *rvec,
   989					      unsigned long riovcnt,
   990					      unsigned long flags);
   991	asmlinkage long sys_kcmp(pid_t pid1, pid_t pid2, int type,
   992				 unsigned long idx1, unsigned long idx2);
   993	asmlinkage long sys_finit_module(int fd, const char __user *uargs, int flags);
   994	asmlinkage long sys_sched_setattr(pid_t pid,
   995						struct sched_attr __user *attr,
   996						unsigned int flags);
   997	asmlinkage long sys_sched_getattr(pid_t pid,
   998						struct sched_attr __user *attr,
   999						unsigned int size,
  1000						unsigned int flags);
  1001	asmlinkage long sys_renameat2(int olddfd, const char __user *oldname,
  1002				      int newdfd, const char __user *newname,
  1003				      unsigned int flags);
  1004	asmlinkage long sys_seccomp(unsigned int op, unsigned int flags,
  1005				    void __user *uargs);
  1006	asmlinkage long sys_getrandom(char __user *buf, size_t count,
  1007				      unsigned int flags);
  1008	asmlinkage long sys_memfd_create(const char __user *uname_ptr, unsigned int flags);
  1009	asmlinkage long sys_bpf(int cmd, union bpf_attr *attr, unsigned int size);
  1010	asmlinkage long sys_execveat(int dfd, const char __user *filename,
  1011				const char __user *const __user *argv,
  1012				const char __user *const __user *envp, int flags);
  1013	asmlinkage long sys_userfaultfd(int flags);
  1014	asmlinkage long sys_membarrier(int cmd, unsigned int flags, int cpu_id);
  1015	asmlinkage long sys_mlock2(unsigned long start, size_t len, int flags);
  1016	asmlinkage long sys_copy_file_range(int fd_in, loff_t __user *off_in,
  1017					    int fd_out, loff_t __user *off_out,
  1018					    size_t len, unsigned int flags);
  1019	asmlinkage long sys_preadv2(unsigned long fd, const struct iovec __user *vec,
  1020				    unsigned long vlen, unsigned long pos_l, unsigned long pos_h,
  1021				    rwf_t flags);
  1022	asmlinkage long sys_pwritev2(unsigned long fd, const struct iovec __user *vec,
  1023				    unsigned long vlen, unsigned long pos_l, unsigned long pos_h,
  1024				    rwf_t flags);
  1025	asmlinkage long sys_pkey_mprotect(unsigned long start, size_t len,
  1026					  unsigned long prot, int pkey);
  1027	asmlinkage long sys_pkey_alloc(unsigned long flags, unsigned long init_val);
  1028	asmlinkage long sys_pkey_free(int pkey);
  1029	asmlinkage long sys_statx(int dfd, const char __user *path, unsigned flags,
  1030				  unsigned mask, struct statx __user *buffer);
  1031	asmlinkage long sys_rseq(struct rseq __user *rseq, uint32_t rseq_len,
  1032				 int flags, uint32_t sig);
  1033	asmlinkage long sys_open_tree(int dfd, const char __user *path, unsigned flags);
  1034	asmlinkage long sys_move_mount(int from_dfd, const char __user *from_path,
  1035				       int to_dfd, const char __user *to_path,
  1036				       unsigned int ms_flags);
  1037	asmlinkage long sys_mount_setattr(int dfd, const char __user *path,
  1038					  unsigned int flags,
  1039					  struct mount_attr __user *uattr, size_t usize);
  1040	asmlinkage long sys_fsopen(const char __user *fs_name, unsigned int flags);
  1041	asmlinkage long sys_fsconfig(int fs_fd, unsigned int cmd, const char __user *key,
  1042				     const void __user *value, int aux);
  1043	asmlinkage long sys_fsmount(int fs_fd, unsigned int flags, unsigned int ms_flags);
  1044	asmlinkage long sys_fspick(int dfd, const char __user *path, unsigned int flags);
  1045	asmlinkage long sys_pidfd_send_signal(int pidfd, int sig,
  1046					       siginfo_t __user *info,
  1047					       unsigned int flags);
  1048	asmlinkage long sys_pidfd_getfd(int pidfd, int fd, unsigned int flags);
  1049	asmlinkage long sys_landlock_create_ruleset(const struct landlock_ruleset_attr __user *attr,
  1050			size_t size, __u32 flags);
  1051	asmlinkage long sys_landlock_add_rule(int ruleset_fd, enum landlock_rule_type rule_type,
  1052			const void __user *rule_attr, __u32 flags);
  1053	asmlinkage long sys_landlock_restrict_self(int ruleset_fd, __u32 flags);
  1054	asmlinkage long umcg_api_version(u32 api_version, u32 flags);
  1055	asmlinkage long umcg_register_task(u32 api_version, u32 flags, u32 group_id,
  1056						struct umcg_task __user *umcg_task);
  1057	asmlinkage long umcg_unregister_task(u32 flags);
  1058	asmlinkage long umcg_wait(u32 flags, const struct __kernel_timespec __user *timeout);
  1059	asmlinkage long umcg_wake(u32 flags, u32 next_tid);
  1060	asmlinkage long umcg_swap(u32 wake_flags, u32 next_tid, u32 wait_flags,
  1061					const struct __kernel_timespec __user *timeout);
> 1062	asmlinkage long umcg_create_group(u32 api_version, u64, flags);

1063 asmlinkage long umcg_destroy_group(u32 group_id);
1064 asmlinkage long umcg_poll_worker(u32 flags, struct umcg_task __user **ut);
1065 asmlinkage long umcg_run_worker(u32 flags, u32 worker_tid,
1066 struct umcg_task __user **ut);
1067

---
0-DAY CI Kernel Test Service, Intel Corporation
https://lists.01.org/hyperkitty/list/kbuild-all(a)lists.01.org

#20 lore raw

Re: [RFC PATCH v0.1 7/9] sched/umcg: add UMCG server/worker API (early RFC)

In reply to Peter Oskolkov
[If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in https://git-scm.com/docs/git-format-patch]

Hi Peter,

[FYI, it's a private test report for your RFC patch.]
[auto build test ERROR on tip/sched/core]
[also build test ERROR on tip/master]
[cannot apply to kselftest/next linus/master v5.13-rc2 next-20210521] [If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch]

url:    https://github.com/0day-ci/linux/commits/Peter-Oskolkov/UMCG-early-preview-RFC-patchset/20210522-232442
base:   https://git.kernel.org/pub/scm/linux/kernel/git/tip/tip.git 1699949d3314e5d1956fb082e4cd4798bf6149fc
config: um-randconfig-p001-20210522 (attached as .config)
compiler: gcc-9 (Debian 9.3.0-22) 9.3.0

reproduce (this is a W=1 build):
# https://github.com/0day-ci/linux/commit/634e0c0b3bf5d6ede3674f9c754202b1a521ab89
git remote add linux-review https://github.com/0day-ci/linux
git fetch --no-tags linux-review Peter-Oskolkov/UMCG-early-preview-RFC-patchset/20210522-232442 git checkout 634e0c0b3bf5d6ede3674f9c754202b1a521ab89
# save the attached .config to linux build tree
make W=1 ARCH=um

If you fix the issue, kindly add following tag as appropriate

All errors (new ones prefixed by >>):

In file included from init/main.c:21:

>> include/linux/syscalls.h:1062:57: error: unknown type name 'flags'
    1062 | asmlinkage long umcg_create_group(u32 api_version, u64, flags);
         |                                                         ^~~~~
   init/main.c:764:20: warning: no previous prototype for 'arch_post_acpi_subsys_init' [-Wmissing-prototypes]
     764 | void __init __weak arch_post_acpi_subsys_init(void) { }
         |                    ^~~~~~~~~~~~~~~~~~~~~~~~~~
   init/main.c:776:20: warning: no previous prototype for 'mem_encrypt_init' [-Wmissing-prototypes]
     776 | void __init __weak mem_encrypt_init(void) { }
         |                    ^~~~~~~~~~~~~~~~
   init/main.c:778:20: warning: no previous prototype for 'poking_init' [-Wmissing-prototypes]
     778 | void __init __weak poking_init(void) { }
         |                    ^~~~~~~~~~~
--
   In file included from init/do_mounts.h:5,
                    from init/do_mounts.c:29:
>> include/linux/syscalls.h:1062:57: error: unknown type name 'flags'
    1062 | asmlinkage long umcg_create_group(u32 api_version, u64, flags);
         |                                                         ^~~~~
--
   In file included from arch/um/kernel/syscall.c:11:
>> include/linux/syscalls.h:1062:57: error: unknown type name 'flags'
    1062 | asmlinkage long umcg_create_group(u32 api_version, u64, flags);
         |                                                         ^~~~~

arch/um/kernel/syscall.c:17:6: warning: no previous prototype for 'old_mmap' [-Wmissing-prototypes]
17 | long old_mmap(unsigned long addr, unsigned long len,
| ^~~~~~~~
--
In file included from arch/x86/um/tls_32.c:8:

>> include/linux/syscalls.h:1062:57: error: unknown type name 'flags'
    1062 | asmlinkage long umcg_create_group(u32 api_version, u64, flags);
         |                                                         ^~~~~

arch/x86/um/tls_32.c:23:5: warning: no previous prototype for 'do_set_thread_area' [-Wmissing-prototypes]
23 | int do_set_thread_area(struct user_desc *info)
| ^~~~~~~~~~~~~~~~~~
arch/x86/um/tls_32.c:39:5: warning: no previous prototype for 'do_get_thread_area' [-Wmissing-prototypes]
39 | int do_get_thread_area(struct user_desc *info)
| ^~~~~~~~~~~~~~~~~~
arch/x86/um/tls_32.c:187:5: warning: no previous prototype for 'arch_switch_tls' [-Wmissing-prototypes]
187 | int arch_switch_tls(struct task_struct *to)
| ^~~~~~~~~~~~~~~
--
In file included from kernel/fork.c:54:

>> include/linux/syscalls.h:1062:57: error: unknown type name 'flags'
    1062 | asmlinkage long umcg_create_group(u32 api_version, u64, flags);
         |                                                         ^~~~~
   kernel/fork.c:162:13: warning: no previous prototype for 'arch_release_task_struct' [-Wmissing-prototypes]
     162 | void __weak arch_release_task_struct(struct task_struct *tsk)
         |             ^~~~~~~~~~~~~~~~~~~~~~~~
   kernel/fork.c:752:20: warning: no previous prototype for 'arch_task_cache_init' [-Wmissing-prototypes]
     752 | void __init __weak arch_task_cache_init(void) { }
         |                    ^~~~~~~~~~~~~~~~~~~~

kernel/fork.c:842:12: warning: no previous prototype for 'arch_dup_task_struct' [-Wmissing-prototypes]
842 | int __weak arch_dup_task_struct(struct task_struct *dst,
| ^~~~~~~~~~~~~~~~~~~~
--
In file included from kernel/exit.c:42:

>> include/linux/syscalls.h:1062:57: error: unknown type name 'flags'
    1062 | asmlinkage long umcg_create_group(u32 api_version, u64, flags);
         |                                                         ^~~~~
   kernel/exit.c:1811:13: warning: no previous prototype for 'abort' [-Wmissing-prototypes]
    1811 | __weak void abort(void)
         |             ^~~~~
--
   In file included from fs/d_path.c:2:
>> include/linux/syscalls.h:1062:57: error: unknown type name 'flags'
    1062 | asmlinkage long umcg_create_group(u32 api_version, u64, flags);
         |                                                         ^~~~~

fs/d_path.c:315:7: warning: no previous prototype for 'simple_dname' [-Wmissing-prototypes]
315 | char *simple_dname(struct dentry *dentry, char *buffer, int buflen)
| ^~~~~~~~~~~~
--
In file included from drivers/char/random.c:335:

>> include/linux/syscalls.h:1062:57: error: unknown type name 'flags'
    1062 | asmlinkage long umcg_create_group(u32 api_version, u64, flags);
         |                                                         ^~~~~

drivers/char/random.c:2272:6: warning: no previous prototype for 'add_hwgenerator_randomness' [-Wmissing-prototypes]
2272 | void add_hwgenerator_randomness(const char *buffer, size_t count,
| ^~~~~~~~~~~~~~~~~~~~~~~~~~
--
In file included from net/socket.c:78:

>> include/linux/syscalls.h:1062:57: error: unknown type name 'flags'
    1062 | asmlinkage long umcg_create_group(u32 api_version, u64, flags);
         |                                                         ^~~~~
   net/socket.c: In function '__sys_getsockopt':
   net/socket.c:2143:6: warning: variable 'max_optlen' set but not used [-Wunused-but-set-variable]
    2143 |  int max_optlen;
         |      ^~~~~~~~~~
--
   In file included from kernel/printk/printk.c:36:
>> include/linux/syscalls.h:1062:57: error: unknown type name 'flags'
    1062 | asmlinkage long umcg_create_group(u32 api_version, u64, flags);
         |                                                         ^~~~~

kernel/printk/printk.c:175:5: warning: no previous prototype for 'devkmsg_sysctl_set_loglvl' [-Wmissing-prototypes]
175 | int devkmsg_sysctl_set_loglvl(struct ctl_table *table, int write,
| ^~~~~~~~~~~~~~~~~~~~~~~~~
--
In file included from kernel/sched/sched.h:67,
from kernel/sched/core.c:13:

>> include/linux/syscalls.h:1062:57: error: unknown type name 'flags'
    1062 | asmlinkage long umcg_create_group(u32 api_version, u64, flags);
         |                                                         ^~~~~
   kernel/sched/core.c: In function 'ttwu_stat':
   kernel/sched/core.c:3274:13: warning: variable 'rq' set but not used [-Wunused-but-set-variable]
    3274 |  struct rq *rq;
         |             ^~

..

Kconfig warnings: (for reference only)
WARNING: unmet direct dependencies detected for LOCKDEP
Depends on DEBUG_KERNEL && LOCK_DEBUGGING_SUPPORT && (FRAME_POINTER || MIPS || PPC || S390 || MICROBLAZE || ARM || ARC || X86) Selected by
- DEBUG_LOCK_ALLOC && DEBUG_KERNEL && LOCK_DEBUGGING_SUPPORT

vim +/flags +1062 include/linux/syscalls.h

903
904 /* mm/, CONFIG_MMU only */
905 asmlinkage long sys_swapon(const char __user *specialfile, int swap_flags);
906 asmlinkage long sys_swapoff(const char __user *specialfile);
907 asmlinkage long sys_mprotect(unsigned long start, size_t len,
908 unsigned long prot);
909 asmlinkage long sys_msync(unsigned long start, size_t len, int flags);
910 asmlinkage long sys_mlock(unsigned long start, size_t len);
911 asmlinkage long sys_munlock(unsigned long start, size_t len);
912 asmlinkage long sys_mlockall(int flags);
913 asmlinkage long sys_munlockall(void);
914 asmlinkage long sys_mincore(unsigned long start, size_t len,
915 unsigned char __user * vec);
916 asmlinkage long sys_madvise(unsigned long start, size_t len, int behavior);
917 asmlinkage long sys_process_madvise(int pidfd, const struct iovec __user *vec,
918 size_t vlen, int behavior, unsigned int flags);
919 asmlinkage long sys_remap_file_pages(unsigned long start, unsigned long size,
920 unsigned long prot, unsigned long pgoff,
921 unsigned long flags);
922 asmlinkage long sys_mbind(unsigned long start, unsigned long len,
923 unsigned long mode,
924 const unsigned long __user *nmask,
925 unsigned long maxnode,
926 unsigned flags);
927 asmlinkage long sys_get_mempolicy(int __user *policy,
928 unsigned long __user *nmask,
929 unsigned long maxnode,
930 unsigned long addr, unsigned long flags);
931 asmlinkage long sys_set_mempolicy(int mode, const unsigned long __user *nmask,
932 unsigned long maxnode);
933 asmlinkage long sys_migrate_pages(pid_t pid, unsigned long maxnode,
934 const unsigned long __user *from,
935 const unsigned long __user *to);
936 asmlinkage long sys_move_pages(pid_t pid, unsigned long nr_pages,
937 const void __user * __user *pages,
938 const int __user *nodes,
939 int __user *status,
940 int flags);
941
942 asmlinkage long sys_rt_tgsigqueueinfo(pid_t tgid, pid_t pid, int sig,
943 siginfo_t __user *uinfo);
944 asmlinkage long sys_perf_event_open(
945 struct perf_event_attr __user *attr_uptr,
946 pid_t pid, int cpu, int group_fd, unsigned long flags);
947 asmlinkage long sys_accept4(int, struct sockaddr __user *, int __user *, int);
948 asmlinkage long sys_recvmmsg(int fd, struct mmsghdr __user *msg,
949 unsigned int vlen, unsigned flags,
950 struct __kernel_timespec __user *timeout);
951 asmlinkage long sys_recvmmsg_time32(int fd, struct mmsghdr __user *msg,
952 unsigned int vlen, unsigned flags,
953 struct old_timespec32 __user *timeout);
954
955 asmlinkage long sys_wait4(pid_t pid, int __user *stat_addr,
956 int options, struct rusage __user *ru);
957 asmlinkage long sys_prlimit64(pid_t pid, unsigned int resource,
958 const struct rlimit64 __user *new_rlim,
959 struct rlimit64 __user *old_rlim);
960 asmlinkage long sys_fanotify_init(unsigned int flags, unsigned int event_f_flags);
961 asmlinkage long sys_fanotify_mark(int fanotify_fd, unsigned int flags,
962 u64 mask, int fd,
963 const char __user *pathname);
964 asmlinkage long sys_name_to_handle_at(int dfd, const char __user *name,
965 struct file_handle __user *handle,
966 int __user *mnt_id, int flag);
967 asmlinkage long sys_open_by_handle_at(int mountdirfd,
968 struct file_handle __user *handle,
969 int flags);
970 asmlinkage long sys_clock_adjtime(clockid_t which_clock,
971 struct __kernel_timex __user *tx);
972 asmlinkage long sys_clock_adjtime32(clockid_t which_clock,
973 struct old_timex32 __user *tx);
974 asmlinkage long sys_syncfs(int fd);
975 asmlinkage long sys_setns(int fd, int nstype);
976 asmlinkage long sys_pidfd_open(pid_t pid, unsigned int flags);
977 asmlinkage long sys_sendmmsg(int fd, struct mmsghdr __user *msg,
978 unsigned int vlen, unsigned flags);
979 asmlinkage long sys_process_vm_readv(pid_t pid,

   980					     const struct iovec __user *lvec,
   981					     unsigned long liovcnt,
   982					     const struct iovec __user *rvec,
   983					     unsigned long riovcnt,
   984					     unsigned long flags);
   985	asmlinkage long sys_process_vm_writev(pid_t pid,
   986					      const struct iovec __user *lvec,
   987					      unsigned long liovcnt,
   988					      const struct iovec __user *rvec,
   989					      unsigned long riovcnt,
   990					      unsigned long flags);
   991	asmlinkage long sys_kcmp(pid_t pid1, pid_t pid2, int type,
   992				 unsigned long idx1, unsigned long idx2);
   993	asmlinkage long sys_finit_module(int fd, const char __user *uargs, int flags);
   994	asmlinkage long sys_sched_setattr(pid_t pid,
   995						struct sched_attr __user *attr,
   996						unsigned int flags);
   997	asmlinkage long sys_sched_getattr(pid_t pid,
   998						struct sched_attr __user *attr,
   999						unsigned int size,
  1000						unsigned int flags);
  1001	asmlinkage long sys_renameat2(int olddfd, const char __user *oldname,
  1002				      int newdfd, const char __user *newname,
  1003				      unsigned int flags);
  1004	asmlinkage long sys_seccomp(unsigned int op, unsigned int flags,
  1005				    void __user *uargs);
  1006	asmlinkage long sys_getrandom(char __user *buf, size_t count,
  1007				      unsigned int flags);
  1008	asmlinkage long sys_memfd_create(const char __user *uname_ptr, unsigned int flags);
  1009	asmlinkage long sys_bpf(int cmd, union bpf_attr *attr, unsigned int size);
  1010	asmlinkage long sys_execveat(int dfd, const char __user *filename,
  1011				const char __user *const __user *argv,
  1012				const char __user *const __user *envp, int flags);
  1013	asmlinkage long sys_userfaultfd(int flags);
  1014	asmlinkage long sys_membarrier(int cmd, unsigned int flags, int cpu_id);
  1015	asmlinkage long sys_mlock2(unsigned long start, size_t len, int flags);
  1016	asmlinkage long sys_copy_file_range(int fd_in, loff_t __user *off_in,
  1017					    int fd_out, loff_t __user *off_out,
  1018					    size_t len, unsigned int flags);
  1019	asmlinkage long sys_preadv2(unsigned long fd, const struct iovec __user *vec,
  1020				    unsigned long vlen, unsigned long pos_l, unsigned long pos_h,
  1021				    rwf_t flags);
  1022	asmlinkage long sys_pwritev2(unsigned long fd, const struct iovec __user *vec,
  1023				    unsigned long vlen, unsigned long pos_l, unsigned long pos_h,
  1024				    rwf_t flags);
  1025	asmlinkage long sys_pkey_mprotect(unsigned long start, size_t len,
  1026					  unsigned long prot, int pkey);
  1027	asmlinkage long sys_pkey_alloc(unsigned long flags, unsigned long init_val);
  1028	asmlinkage long sys_pkey_free(int pkey);
  1029	asmlinkage long sys_statx(int dfd, const char __user *path, unsigned flags,
  1030				  unsigned mask, struct statx __user *buffer);
  1031	asmlinkage long sys_rseq(struct rseq __user *rseq, uint32_t rseq_len,
  1032				 int flags, uint32_t sig);
  1033	asmlinkage long sys_open_tree(int dfd, const char __user *path, unsigned flags);
  1034	asmlinkage long sys_move_mount(int from_dfd, const char __user *from_path,
  1035				       int to_dfd, const char __user *to_path,
  1036				       unsigned int ms_flags);
  1037	asmlinkage long sys_mount_setattr(int dfd, const char __user *path,
  1038					  unsigned int flags,
  1039					  struct mount_attr __user *uattr, size_t usize);
  1040	asmlinkage long sys_fsopen(const char __user *fs_name, unsigned int flags);
  1041	asmlinkage long sys_fsconfig(int fs_fd, unsigned int cmd, const char __user *key,
  1042				     const void __user *value, int aux);
  1043	asmlinkage long sys_fsmount(int fs_fd, unsigned int flags, unsigned int ms_flags);
  1044	asmlinkage long sys_fspick(int dfd, const char __user *path, unsigned int flags);
  1045	asmlinkage long sys_pidfd_send_signal(int pidfd, int sig,
  1046					       siginfo_t __user *info,
  1047					       unsigned int flags);
  1048	asmlinkage long sys_pidfd_getfd(int pidfd, int fd, unsigned int flags);
  1049	asmlinkage long sys_landlock_create_ruleset(const struct landlock_ruleset_attr __user *attr,
  1050			size_t size, __u32 flags);
  1051	asmlinkage long sys_landlock_add_rule(int ruleset_fd, enum landlock_rule_type rule_type,
  1052			const void __user *rule_attr, __u32 flags);
  1053	asmlinkage long sys_landlock_restrict_self(int ruleset_fd, __u32 flags);
  1054	asmlinkage long umcg_api_version(u32 api_version, u32 flags);
  1055	asmlinkage long umcg_register_task(u32 api_version, u32 flags, u32 group_id,
  1056						struct umcg_task __user *umcg_task);
  1057	asmlinkage long umcg_unregister_task(u32 flags);
  1058	asmlinkage long umcg_wait(u32 flags, const struct __kernel_timespec __user *timeout);
  1059	asmlinkage long umcg_wake(u32 flags, u32 next_tid);
  1060	asmlinkage long umcg_swap(u32 wake_flags, u32 next_tid, u32 wait_flags,
  1061					const struct __kernel_timespec __user *timeout);
> 1062	asmlinkage long umcg_create_group(u32 api_version, u64, flags);

1063 asmlinkage long umcg_destroy_group(u32 group_id);
1064 asmlinkage long umcg_poll_worker(u32 flags, struct umcg_task __user **ut);
1065 asmlinkage long umcg_run_worker(u32 flags, u32 worker_tid,
1066 struct umcg_task __user **ut);
1067

---
0-DAY CI Kernel Test Service, Intel Corporation
https://lists.01.org/hyperkitty/list/kbuild-all(a)lists.01.org

#21 lore raw

RFC PATCH 8/9 lib/umcg: add UMCG server/worker API (early RFC)

In reply to Peter Oskolkov

Add userspace UMCG server/worker API.

This is an early RFC patch, with a lot of changes expected on the way.

---
 tools/lib/umcg/libumcg.c | 222 +++++++++++++++++++++++++++++++++++++++
 tools/lib/umcg/libumcg.h | 108 +++++++++++++++++++
 2 files changed, 330 insertions(+)
tools/lib/umcg/libumcg.c +222 -0
index b177fb1d4b17..a11c2fc9e6e1 100644
@@ -101,6 +101,86 @@ umcg_tid umcg_register_core_task(intptr_t tag)
 	return umcg_task_tls->self;
 }
 
+umcg_tid umcg_register_worker(umcg_t group_id, intptr_t tag)
+{
+	int ret;
+	struct umcg_group *group;
+
+	if (group_id == UMCG_NONE) {
+		errno = EINVAL;
+		return UMCG_NONE;
+	}
+
+	if (umcg_task_tls != NULL) {
+		errno = EINVAL;
+		return UMCG_NONE;
+	}
+
+	group = (struct umcg_group *)group_id;
+
+	umcg_task_tls = malloc(sizeof(struct umcg_task_tls));
+	if (!umcg_task_tls) {
+		errno = ENOMEM;
+		return UMCG_NONE;
+	}
+
+	umcg_task_tls->umcg_task.state = UMCG_TASK_NONE;
+	umcg_task_tls->self = (umcg_tid)&umcg_task_tls;
+	umcg_task_tls->tag = tag;
+	umcg_task_tls->tid = gettid();
+
+	ret = sys_umcg_register_task(umcg_api_version, UMCG_REGISTER_WORKER,
+			group->group_id, &umcg_task_tls->umcg_task);
+	if (ret) {
+		free(umcg_task_tls);
+		umcg_task_tls = NULL;
+		errno = ret;
+		return UMCG_NONE;
+	}
+
+	return umcg_task_tls->self;
+}
+
+umcg_tid umcg_register_server(umcg_t group_id, intptr_t tag)
+{
+	int ret;
+	struct umcg_group *group;
+
+	if (group_id == UMCG_NONE) {
+		errno = EINVAL;
+		return UMCG_NONE;
+	}
+
+	if (umcg_task_tls != NULL) {
+		errno = EINVAL;
+		return UMCG_NONE;
+	}
+
+	group = (struct umcg_group *)group_id;
+
+	umcg_task_tls = malloc(sizeof(struct umcg_task_tls));
+	if (!umcg_task_tls) {
+		errno = ENOMEM;
+		return UMCG_NONE;
+	}
+
+	umcg_task_tls->umcg_task.state = UMCG_TASK_NONE;
+	umcg_task_tls->self = (umcg_tid)&umcg_task_tls;
+	umcg_task_tls->tag = tag;
+	umcg_task_tls->tid = gettid();
+
+	ret = sys_umcg_register_task(umcg_api_version, UMCG_REGISTER_SERVER,
+			group->group_id, &umcg_task_tls->umcg_task);
+	if (ret) {
+		free(umcg_task_tls);
+		umcg_task_tls = NULL;
+		errno = ret;
+		return UMCG_NONE;
+	}
+
+	return umcg_task_tls->self;
+}
+
 int umcg_unregister_task(void)
 {
 	int ret;
@@ -348,3 +428,145 @@ int umcg_swap(umcg_tid next, const struct timespec *timeout)
 
 	return 0;
 }
+
+umcg_t umcg_create_group(uint32_t flags)
+{
+	int res = sys_umcg_create_group(umcg_api_version, flags);
+	struct umcg_group *group;
+
+	if (res < 0) {
+		errno = -res;
+		return -1;
+	}
+
+	group = malloc(sizeof(struct umcg_group));
+	if (!group) {
+		errno = ENOMEM;
+		return UMCG_NONE;
+	}
+
+	group->group_id = res;
+	return (intptr_t)group;
+}
+
+int umcg_destroy_group(umcg_t umcg)
+{
+	int res;
+	struct umcg_group *group = (struct umcg_group *)umcg;
+
+	res = sys_umcg_destroy_group(group->group_id);
+	if (res) {
+		errno = -res;
+		return -1;
+	}
+
+	free(group);
+	return 0;
+}
+
+umcg_tid umcg_poll_worker(void)
+{
+	struct umcg_task *server_ut = &umcg_task_tls->umcg_task;
+	struct umcg_task *worker_ut;
+	uint32_t expected_state;
+	int ret;
+
+	expected_state = UMCG_TASK_PROCESSING;
+	if (!atomic_compare_exchange_strong_explicit(&server_ut->state,
+			&expected_state, UMCG_TASK_POLLING,
+			memory_order_seq_cst, memory_order_seq_cst)) {
+		fprintf(stderr, "umcg_poll_worker: wrong server state before: %u\n",
+				expected_state);
+		exit(1);
+		return UMCG_NONE;
+	}
+	ret = sys_umcg_poll_worker(0, &worker_ut);
+
+	expected_state = UMCG_TASK_POLLING;
+	if (!atomic_compare_exchange_strong_explicit(&server_ut->state,
+			&expected_state, UMCG_TASK_PROCESSING,
+			memory_order_seq_cst, memory_order_seq_cst)) {
+		fprintf(stderr, "umcg_poll_worker: wrong server state after: %u\n",
+				expected_state);
+		exit(1);
+		return UMCG_NONE;
+	}
+
+	if (ret) {
+		fprintf(stderr, "sys_umcg_poll_worker: unexpected result %d\n",
+				errno);
+		exit(1);
+		return UMCG_NONE;
+	}
+
+	return umcg_task_to_utid(worker_ut);
+}
+
+umcg_tid umcg_run_worker(umcg_tid worker)
+{
+	struct umcg_task_tls *worker_utls;
+	struct umcg_task *server_ut = &umcg_task_tls->umcg_task;
+	struct umcg_task *worker_ut;
+	uint32_t expected_state;
+	int ret;
+
+	worker_utls = atomic_load_explicit((struct umcg_task_tls **)worker,
+			memory_order_seq_cst);
+	if (!worker_utls)
+		return UMCG_NONE;
+
+	worker_ut = &worker_utls->umcg_task;
+
+	expected_state = UMCG_TASK_RUNNABLE;
+	if (!atomic_compare_exchange_strong_explicit(&worker_ut->state,
+			&expected_state, UMCG_TASK_RUNNING,
+			memory_order_seq_cst, memory_order_seq_cst)) {
+		fprintf(stderr, "umcg_run_worker: wrong worker state: %u\n",
+				expected_state);
+		exit(1);
+		return UMCG_NONE;
+	}
+
+	expected_state = UMCG_TASK_PROCESSING;
+	if (!atomic_compare_exchange_strong_explicit(&server_ut->state,
+			&expected_state, UMCG_TASK_SERVING,
+			memory_order_seq_cst, memory_order_seq_cst)) {
+		fprintf(stderr, "umcg_run_worker: wrong server state: %u\n",
+				expected_state);
+		exit(1);
+		return UMCG_NONE;
+	}
+
+again:
+	ret = sys_umcg_run_worker(0, worker_utls->tid, &worker_ut);
+	if (ret && errno == EAGAIN)
+		goto again;
+
+	if (ret) {
+		fprintf(stderr, "umcg_run_worker failed: %d %d\n", ret, errno);
+		return UMCG_NONE;
+	}
+
+	expected_state = UMCG_TASK_SERVING;
+	if (!atomic_compare_exchange_strong_explicit(&server_ut->state,
+			&expected_state, UMCG_TASK_PROCESSING,
+			memory_order_seq_cst, memory_order_seq_cst)) {
+		fprintf(stderr, "umcg_run_worker: wrong server state: %u\n",
+				expected_state);
+		exit(1);
+		return UMCG_NONE;
+	}
+
+	return umcg_task_to_utid(worker_ut);
+}
+
+uint32_t umcg_get_task_state(umcg_tid task)
+{
+	struct umcg_task_tls *utls = atomic_load_explicit(
+			(struct umcg_task_tls **)task, memory_order_seq_cst);
+
+	if (!utls)
+		return UMCG_TASK_NONE;
+
+	return atomic_load_explicit(&utls->umcg_task.state, memory_order_relaxed);
+}
tools/lib/umcg/libumcg.h +108 -0

124 lines not on this page · raw message

Signature · 1 line
2.31.1.818.g46aad6cb9e-goog
#22 lore raw

RFC PATCH 9/9 selftests/umcg: add UMCG server/worker API selftest

In reply to Peter Oskolkov

Add UMCG server/worker API selftests. These are only basic tests, they do not cover many important use cases/conditions.

More to come.

---
 tools/testing/selftests/umcg/.gitignore  |   1 +
 tools/testing/selftests/umcg/Makefile    |   4 +-
 tools/testing/selftests/umcg/umcg_test.c | 475 +++++++++++++++++++++++
 3 files changed, 479 insertions(+), 1 deletion(-)
 create mode 100644 tools/testing/selftests/umcg/umcg_test.c
tools/testing/selftests/umcg/.gitignore +1 -0
index 89cca24e5907..f488ec82882a 100644
@@ -1,2 +1,3 @@
 # SPDX-License-Identifier: GPL-2.0-only
 umcg_core_test
+umcg_test
tools/testing/selftests/umcg/Makefile +3 -1
index b151098e2ed1..916897d82e53 100644
@@ -6,8 +6,10 @@ LIBUMCGDIR := $(TOOLSDIR)/lib/umcg
 CFLAGS += -g -O0 -I$(LIBUMCGDIR) -I$(TOOLSDIR)/include/ -I../../../../usr/include/
 LDLIBS += -lpthread -static
 
-TEST_GEN_PROGS := umcg_core_test
+TEST_GEN_PROGS := umcg_core_test umcg_test
 
 include ../lib.mk
 
 $(OUTPUT)/umcg_core_test: umcg_core_test.c $(LIBUMCGDIR)/libumcg.c
+
+$(OUTPUT)/umcg_test: umcg_test.c $(LIBUMCGDIR)/libumcg.c
tools/testing/selftests/umcg/umcg_test.c new file +475 -0

475 lines not on this page · raw message

Signature · 1 line
2.31.1.818.g46aad6cb9e-goog
#23 lore raw
In reply to Peter Oskolkov
Quoted 9 lines · Peter Oskolkov

As indicated earlier in the FUTEX_SWAP patchset:

https://lore.kernel.org/lkml/[email protected]/

"Google Fibers" is a userspace scheduling framework
used widely and successfully at Google to improve in-process workload isolation and response latencies. We are working on open-sourcing this framework, and UMCG (User-Managed Concurrency Groups) kernel patches are intended as the foundation of this.

So I have to ask...is there *any* documentation out there on what this is and how people are supposed to use it? Shockingly, typing "Google fibers" into Google leads to a less than fully joyful outcome... This won't be easy for anybody to review if they have to start by reverse-engineering what it's supposed to do.

Thanks,

jon

#24 lore raw
Quoted 13 lines · Jonathan Corbet
Quoted 9 lines · Peter Oskolkov

As indicated earlier in the FUTEX_SWAP patchset:

https://lore.kernel.org/lkml/[email protected]/

"Google Fibers" is a userspace scheduling framework
used widely and successfully at Google to improve in-process workload isolation and response latencies. We are working on open-sourcing this framework, and UMCG (User-Managed Concurrency Groups) kernel patches are intended as the foundation of this.

Quoted 5 lines

So I have to ask...is there *any* documentation out there on what this is and how people are supposed to use it? Shockingly, typing "Google fibers" into Google leads to a less than fully joyful outcome... This won't be easy for anybody to review if they have to start by reverse-engineering what it's supposed to do.

Hi Jonathan,

There is this Linux Plumbers video: https://www.youtube.com/watch?v=KXuZi9aeGTw
And the pdf: http://pdxplumbers.osuosl.org/2013/ocw//system/presentations/1653/original/LPC%20-%20User%20Threading.pdf

I did not reference them in the patchset because links to sites other than kernel.org are strongly discouraged... I will definitely add a documentation patch.

Feel free to reach out to me directly or through this LKML thread if you have any questions.

Do you think a documentation patch would be useful at this point, as opposed to a free-form email discussion?

Thanks,
Peter

Quoted 4 lines

Thanks,

jon

#25 lore raw
Quoted 20 lines · Peter Oskolkov
Quoted 13 lines · Jonathan Corbet
Quoted 9 lines · Peter Oskolkov

As indicated earlier in the FUTEX_SWAP patchset:

https://lore.kernel.org/lkml/[email protected]/

"Google Fibers" is a userspace scheduling framework
used widely and successfully at Google to improve in-process workload isolation and response latencies. We are working on open-sourcing this framework, and UMCG (User-Managed Concurrency Groups) kernel patches are intended as the foundation of this.

Quoted 5 lines

So I have to ask...is there *any* documentation out there on what this is and how people are supposed to use it? Shockingly, typing "Google fibers" into Google leads to a less than fully joyful outcome... This won't be easy for anybody to review if they have to start by reverse-engineering what it's supposed to do.

Quoted 8 lines

Hi Jonathan,

There is this Linux Plumbers video: https://www.youtube.com/watch?v=KXuZi9aeGTw
And the pdf: http://pdxplumbers.osuosl.org/2013/ocw//system/presentations/1653/original/LPC%20-%20User%20Threading.pdf

I did not reference them in the patchset because links to sites other than kernel.org are strongly discouraged... I will definitely add a documentation patch.

Certainly for links to email, we prefer to use lore.kernel.org archives. Are links to other sites discouraged? If so, that's news to me.

Quoted 5 lines

Feel free to reach out to me directly or through this LKML thread if you have any questions.

Do you think a documentation patch would be useful at this point, as opposed to a free-form email discussion?

thanks.

Signature · 1 line
~Randy
maintainer
#26 lore raw
Quoted 9 lines · Randy Dunlap
Quoted 6 lines

There is this Linux Plumbers video: https://www.youtube.com/watch?v=KXuZi9aeGTw
And the pdf: http://pdxplumbers.osuosl.org/2013/ocw//system/presentations/1653/original/LPC%20-%20User%20Threading.pdf

I did not reference them in the patchset because links to sites other than kernel.org are strongly discouraged... I will definitely add a documentation patch.

Certainly for links to email, we prefer to use lore.kernel.org archives. Are links to other sites discouraged? If so, that's news to me.

Discouraged in so far as that when an email solely references external resources and doesn't bother to summarize or otherwise recap the contents in the email proper; I'll ignore the whole thing.

Basically, if I have to click a link to figure out basic information of a patch series, the whole thing is a fail and goes into the bit bucket.

That said; I have no objection against having links, as long as they're not used to convey the primary information that _should_ be in the cover letter and/or changelogs.

#27 lore raw
In reply to Peter Oskolkov
Quoted 20 lines · Peter Oskolkov
Quoted 13 lines · Jonathan Corbet
Quoted 9 lines · Peter Oskolkov

As indicated earlier in the FUTEX_SWAP patchset:

https://lore.kernel.org/lkml/[email protected]/

"Google Fibers" is a userspace scheduling framework
used widely and successfully at Google to improve in-process workload isolation and response latencies. We are working on open-sourcing this framework, and UMCG (User-Managed Concurrency Groups) kernel patches are intended as the foundation of this.

Quoted 5 lines

So I have to ask...is there *any* documentation out there on what this is and how people are supposed to use it? Shockingly, typing "Google fibers" into Google leads to a less than fully joyful outcome... This won't be easy for anybody to review if they have to start by reverse-engineering what it's supposed to do.

Quoted 8 lines

Hi Jonathan,

There is this Linux Plumbers video: https://www.youtube.com/watch?v=KXuZi9aeGTw
And the pdf: http://pdxplumbers.osuosl.org/2013/ocw//system/presentations/1653/original/LPC%20-%20User%20Threading.pdf

I did not reference them in the patchset because links to sites other than kernel.org are strongly discouraged... I will definitely add a documentation patch.

I did look at those - but a presentation from 2013 is going to be of limited relevance for a 2021 patch set. In particular, the syscall API appears to have evolved considerably since then.

Quoted 5 lines

Feel free to reach out to me directly or through this LKML thread if you have any questions.

Do you think a documentation patch would be useful at this point, as opposed to a free-form email discussion?

Documentation patches can help to guide that discussion; they also need to be reviewed as well. So yes, I think they should be present from the beginning. But then, that's the position I'm supposed to take :) This is a big change to the kernel's system-call API, I don't think that there can be a proper discussion of that without a description of what you're trying to do.

Thanks,

jon

#28 lore raw

On Fri, May 21, 2021 at 8:08 AM Jonathan Corbet <[email protected]> wrote:

[...]

Quoted 6 lines

Documentation patches can help to guide that discussion; they also need to be reviewed as well. So yes, I think they should be present from the beginning. But then, that's the position I'm supposed to take :) This is a big change to the kernel's system-call API, I don't think that there can be a proper discussion of that without a description of what you're trying to do.

Hi Jon,

There are doc comments in patches 2 and 7 in umcg.c documenting the new syscalls. That said, I'll prepare a separate doc patch - I guess I'll add Documentation/scheduler/umcg.rst, unless you tell me there is a better place to do that. ETA mid-to-late next week.

Thanks,
Peter

#29 lore raw
Quoted 10 lines · Peter Oskolkov

On Fri, May 21, 2021 at 8:08 AM Jonathan Corbet <[email protected]> wrote:

[...]

Quoted 6 lines

Documentation patches can help to guide that discussion; they also need to be reviewed as well. So yes, I think they should be present from the beginning. But then, that's the position I'm supposed to take :) This is a big change to the kernel's system-call API, I don't think that there can be a proper discussion of that without a description of what you're trying to do.

Quoted 6 lines

Hi Jon,

There are doc comments in patches 2 and 7 in umcg.c documenting the new syscalls. That said, I'll prepare a separate doc patch - I guess I'll add Documentation/scheduler/umcg.rst, unless you tell me there is a better place to do that. ETA mid-to-late next week.

Yes, I saw those; they are a bit terse at best. What are the "worker states"? What's a "UMCG group"? Yes, all this can be worked out by pounding one's head against the code for long enough, but you're asking a fair amount of your reviewers.

A good overall description would be nice, perhaps for the userspace-api book. But *somebody* is also going to have to write real man pages for all these system calls; if you provided those, the result should be a good description of how you expect this subsystem to work.

Thanks,

jon

#30 lore raw

On Fri, May 21, 2021 at 12:17 PM Jonathan Corbet <[email protected]> wrote:

[...]

Quoted 9 lines

What are the "worker
states"? What's a "UMCG group"? Yes, all this can be worked out by pounding one's head against the code for long enough, but you're asking a fair amount of your reviewers.

A good overall description would be nice, perhaps for the userspace-api book. But *somebody* is also going to have to write real man pages for all these system calls; if you provided those, the result should be a good description of how you expect this subsystem to work.

Hi Jon,

I've pasted below the content of umcg.rst file that I'll add as a doc patch to the next version of the patchset. I've also attached a PDF version of the file rendered, in case it is useful. I also think that it is a bit early for manpages - I expect the API and/or behavior to change quite a bit before this is all merged. I'm also not completely sure whether the manpages should describe the "porcelain API" or the "plumbing API" (see the .rst below).

Please let me know if you have any questions, comments, or suggestions.

Thanks,
Peter

======================================
User Managed Concurrency Groups (UMCG)
======================================

User Managed Concurrency Groups (UMCG) is an M:N threading subsystem/toolkit that lets user space application developers implement in-process user space schedulers.

.. contents:: :local:

Why? Heterogeneous in-process workloads
=======================================
Linux kernel's CFS scheduler is designed for the "common" use case, with efficiency/throughput in mind. Work isolation and workloads of different "urgency" are addressed by tools such as cgroups, CPU affinity, priorities, etc., which are difficult or impossible to efficiently use in-process.

For example, a single DBMS process may receive tens of thousands requests per second; some of these requests may have strong response latency requirements as they serve live user requests (e.g. login authentication); some of these requests may not care much about latency but must be served within a certain time period (e.g. an hourly aggregate usage report); some of these requests are to be served only on a best-effort basis and can be NACKed under high load (e.g. an exploratory research/hypothesis testing workload).

Beyond different work item latency/throughput requirements as outlined above, the DBMS may need to provide certain guarantees to different users; for example, user A may "reserve" 1 CPU for their high-priority/low latency requests, 2 CPUs for mid-level throughput workloads, and be allowed to send as many best-effort requests as possible, which may or may not be served, depending on the DBMS load. Besides, the best-effort work, started when the load was low, may need to be delayed if suddenly a large amount of higher-priority work arrives. With hundreds or thousands of users like this, it is very difficult to guarantee the application's responsiveness using standard Linux tools while maintaining high CPU utilization.

Gaming is another use case: some in-process work must be completed before a certain deadline dictated by frame rendering schedule, while other work items can be delayed; some work may need to be cancelled/discarded because the deadline has passed; etc.

User Managed Concurrency Groups is an M:N threading toolkit that allows constructing user space schedulers designed to efficiently manage heterogeneous in-process workloads described above while maintaining high CPU utilization (95%+).

Requirements
============
One relatively established way to design high-efficiency, low-latency systems is to split all work into small on-cpu work items, with asynchronous I/O and continuations, all executed on a thread pool with the number of threads not exceeding the number of available CPUs. Although this approach works, it is quite difficult to develop and maintain such a system, as, for example, small continuations are difficult to piece together when debugging. Besides, such asynchronous callback-based systems tend to be somewhat cache-inefficient, as continuations can get scheduled on any CPU regardless of cache locality.

M:N threading and cooperative user space scheduling enables controlled CPU usage (minimal OS preemption), synchronous coding style, and better cache locality.

Specifically:

- a variable/fluctuating number M of "application" threads should be "scheduled over" a relatively fixed number N of "kernel" threads, where N is less than or equal to the number of CPUs available;
- only those application threads that are attached to kernel threads are scheduled "on CPU";
- application threads should be able to cooperatively yield to each other;
- when an application thread blocks in kernel (e.g. in I/O), this becomes a scheduling event ("block") that the userspace scheduler should be able to efficiently detect, and reassign a waiting application thread to the freeded "kernel" thread;
- when a blocked application thread wakes (e.g. its I/O operation completes), this even ("wake") should also be detectable by the userspace scheduler, which should be able to either quickly dispatch the newly woken thread to an idle "kernel" thread or, if all "kernel" threads are busy, put it in the waiting queue;
- in addition to the above, it would be extremely useful for a separate in-process "watchdog" facility to be able to monitor the state of each of the M+N threads, and to intervene in case of runaway workloads (interrupt/preempt).

The building blocks
===================
Main Objects
------------
Based on the requirements above, UMCG exposes the following "objects":

- server tasks/threads: these are the N "kernel" threads from the requirements section above;
- worker tasks/threads: these are the M application threads from the requirements section above;
- UMCG groups: all UMCG worker and server threads belong to a UMCG group; a process (a shared MM) can have multiple groups; workers and servers must belong to the same UMCG group to interact (note: multiple groups per process can be useful to e.g. partition scheduling per NUMA node).

Key operations/API
------------------
As described above, the framework/toolkit must be able to efficiently process block/wake events, run workers, and provide cooperative worker scheduling facilities. As such, there are five runtime operations (not including control/support facilities), two for servers (explicit scheduling), and three for workers (cooperative scheduling):

- (server) run_worker(): a server specifies which worker to run; the call blocks; when the worker the server is running blocks in the kernel, the call returns, telling the server that its worker has blocked;
- (server) poll_worker(): a server polls the kernel for workers whose blocking operations has completed; the call returns the worker who woke the earliest (or blocks until there is such a worker);
- (worker) wait(): a worker can cooperatively "yield"; its attached server's run_worker() call returns;
- (worker) wake(): any task/thread can "wake" a worker that has yielded;
- (worker) swap(): a running worker can cooperatively "swap" its server with another worker.

Detailed state transitions are described below.

umcg_context_switch
-------------------
This subsection explains some kernel-internal details.

It is important to emphasize that for a userspace scheduling framework to be of use, it is essential that common scenarios such as

- worker W1 blocks, wakes its serving server S which then runs worker W2
- worker W1 swaps into worker W2
- worker W unblocks, wakes a polling server S which then runs it

be as fast and efficient as possible. If these operations mean simply "wake remote task T and go to sleep", with T scheduled on a remote (idle) CPU, the overall performance of the system will be poor due to wakeup delays and cache locality issues (e.g. a server on CPU_A processes a worker blocked on CPU_B).

umcg_context_switch() is basically "wake remote task T on the current CPU and context switch into it"; it is a kernel-internal function that most operations outlined above use; it is exposed to the userspace indirectly via run_worker() (= context switch from the current server to the worker) and swap() (= context switch between two workers).

Initially, umcg_context_switch() is implemented by adding WF_CURRENT_CPU flag that is passed to ttwu; this change of the "wake remotely and go to sleep" operation to "wake on the current CPU and go to sleep" reduces the overall latency of swap about 8x on average (6-10 usec to less than 1 usec).

Another use case: fast IPC
==========================
Fast, synchronous on-CPU context switching can also be used for fast IPC (cross-process). For example, a typical security wrapper intercepts syscalls of an untrusted process, consults with external (out-of-process) "syscall firewall", and then delivers the allow/deny decision back (or the remote process actually proxies the syscall execution on behalf of the monitored process). This roundtrip is usually relatively slow, consuming at least 5-10 usec, as it involves waking a task on a remote CPU. A fast on-CPU context switch not only helps with the wakeup latency, but also has beneficial cache locality properties.

UMCG addresses this use case by providing another type of UMCG task: a "core" task. A core UMCG task can be thought of as a UMCG worker that does not belong to a UMCG group and that runs without a UMCG server attached to it, but that has access to the same UMCG worker operations, namely wait/wake/swap.

Userspace API
=============

This section outlines the key components of UMCG API.

UMCG task states and state transitions
--------------------------------------

At a high level, UMCG is a task/thread managing/scheduling framework. The following task states are defined in uapi/linux/umcg.h (extra state flags are omitted here):

.. code-block:: C

#define UMCG_TASK_NONE 0
/* UMCG server states. */
#define UMCG_TASK_POLLING 1
#define UMCG_TASK_SERVING 2
#define UMCG_TASK_PROCESSING 3
/* UMCG worker states. */
#define UMCG_TASK_RUNNABLE 4
#define UMCG_TASK_RUNNING 5
#define UMCG_TASK_BLOCKED 6
#define UMCG_TASK_UNBLOCKED 7

Server states and state transitions are easy:

- UMCG_TASK_POLLING: the server task is blocked in umcg_poll_worker(), waiting for an UNBLOCKED worker;
- UMCG_TASK_SERVING: the server task is blocked in umcg_run_worker(), serving a RUNNING worker;
- UMCG_TASK_PROCESSING: the server task is running in the userspace, presumably processing worker events.

Worker states and state transitions are more complicated:

- UMCG_TASK_RUNNING: the worker task is runnable/schedulable from the OS scheduler point of view (and is most likely running on a CPU);
- UMCG_TASK_RUNNABLE: this is a special worker state indicating that the worker is not runnable/schedulable by the OS scheduler, but can be scheduled by the user space scheduler; it is a sort of "voluntarily blocked" state;
- UMCG_TASK_BLOCKED: a previously RUNNING worker involuntarily blocked in the kernel, e.g. in a synchronous I/O operation; not runnable/schedulable by the OS scheduler;
- UMCG_TASK_UNBLOCKED: the blocking operation of a BLOCKED worker has completed, but the user space has not yet been notified of the event; not runnable/schedulable by the OS scheduler.

State transitions:

::

RUNNABLE => RUNNING : umcg_run_worker()
RUNNABLE => RUNNING : umcg_swap() (RUNNABLE next becomes RUNNING)

RUNNING => RUNNABLE: umcg_swap() (RUNNING current becomes RUNNABLE) RUNNING => RUNNABLE: umcg_wait() (RUNNING current becomes RUNNABLE)

RUNNING => BLOCKED : the worker blocks in the kernel
BLOCKED => UNBLOCKED: the worker's blocking operation has completed
UNBLOCKED => RUNNABLE : umcg_poll_worker()

RUNNABLE => UNBLOCKED: umcg_wake()

Block/wake events are delivered to server tasks in userspace by waking them from their blocking operations:

- umcg_run_worker() returns (wakes the server) when the worker either blocks voluntarily via umcg_wait(), RUNNABLE, or involuntarily, BLOCKED;
- umcg_poll_worker() returns (wakes the server) when a new UNBLOCKED worker becomes available; if more then one UNBLOCKED worker is present, they are queued and umcg_poll_worker() returns immediately, with the longest waiting worker.

Several optimized state transitions will be possible in later versions of UMCG API. For example, it will be possible to call umcg_run_worker() on a BLOCKED worker so that BLOCKED => UNBLOCKED => RUNNABLE => RUNNING chain of states is "short cut" and happens behind the scenes. Or umcg_poll_worker() will be able to immediately run the polled worker, expediting UNBLOCKED => RUNNABLE => RUNNING.

The state transitions described above become somewhat more complicated in the presence of interrupts/signals, and the exact behavior in the presence of signals/interrupts is still work-in-progress.

UMCG core tasks have only two states: RUNNABLE and RUNNING; block/unblock detection logic is not applicable: if a UMCG core task blocks on I/O, it is still considered RUNNING. In a way, UMCG core tasks participate in cooperative scheduling, in that they can yield to each other via umcg_wait() and umcg_swap() and wake RUNNABLE tasks via umcg_wake().

Please note that while UMCG server/worker tasks must belong to the same UMCG group, and thus the same user process, UMCG core tasks can interact with each other across process boundaries.

UMCG API
--------

- Runtime/scheduling:

- Server API (explicit user space scheduling):

- umcg_run_worker
- umcg_poll_worker

- Core/Worker API (cooperative scheduling):

- umcg_wait
- umcg_wake
- umcg_swap

- Management:

- umcg_create_group
- umcg_destroy_group
- umcg_register_task
- umcg_unregister_task

API levels: porcelain and plumbing
----------------------------------
Similarly to Git Porcelain and Plumbing API_, UMCG exposes two API "surfaces": a higher-level "porcelain" API via libumcg, and a lower-level "plumbing" API via syscalls.

.. _Git Porcelain and Plumbing API:
https://git-scm.com/book/en/v2/Git-Internals-Plumbing-and-Porcelain

This design helps keep UMCG syscalls relatively lightweight, while hiding many implementation details from end users inside libumcg. It can be useful to think of libumcg as the only true UMCG API for end-users, while UMCG syscalls are a low-level toolkit that enables the higher-level API.

Porcelain API: libumcg
----------------------
Located in $KDIR/tools/lib/umcg, libumcg exposes the following key API functions in libumcg.h (some non-essential helper functions are omitted here):

.. code-block:: C

typedef intptr_t umcg_t; /* UMCG group ID. */
typedef intptr_t umcg_tid; /* UMCG thread ID. */

#define UMCG_NONE (0)

/**
* umcg_get_utid - return the UMCG ID of the current thread. *
* The function always succeeds, and the returned ID is guaranteed to be
* stable over the life of the thread (and multiple
* umcg_register/umcg_unregister calls).
*
* The ID is NOT guaranteed to be unique over the life of the process. */
umcg_tid umcg_get_utid(void);

/**
* umcg_register_core_task - register the current thread as a UMCG core task *
* Return:
* UMCG_NONE - an error occurred. Check errno.
* != UMCG_NONE - the ID of the thread to be used with UMCG API (guaranteed
* to match the value returned by umcg_get_utid).
*/
umcg_tid umcg_register_core_task(intptr_t tag);

/**
* umcg_register_worker - register the current thread as a UMCG worker
* @group_id: The ID of the UMCG group the thread should join.
*
* Return:
* UMCG_NONE - an error occurred. Check errno.
* != UMCG_NONE - the ID of the thread to be used with UMCG API (guaranteed
* to match the value returned by umcg_get_utid).
*/
umcg_tid umcg_register_worker(umcg_t group_id, intptr_t tag);

/**
* umcg_register_server - register the current thread as a UMCG server
* @group_id: The ID of the UMCG group the thread should join.
*
* Return:
* UMCG_NONE - an error occurred. Check errno.
* != UMCG_NONE - the ID of the thread to be used with UMCG API (guaranteed
* to match the value returned by umcg_get_utid).
*/
umcg_tid umcg_register_server(umcg_t group_id, intptr_t tag);

/**
* umcg_unregister_task - unregister the current thread *
* Return:
* 0 - OK
* -1 - the current thread is not a UMCG thread
*/
int umcg_unregister_task(void);

/**
* umcg_wait - block the current thread
* @timeout: absolute timeout (not supported at the moment)
*
* Blocks the current thread, which must have been registered via
umcg_register,
* until it is woken via umcg_wake or swapped into via umcg_swap. If
the current
* thread has a wakeup queued (see umcg_wake), returns zero immediately,
* consuming the wakeup.
*
* Return:
* 0 - OK, the thread was waken;
* -1 - did not wake normally;
* errno:
* EINTR: interrupted
* EINVAL: some other error occurred
*/
int umcg_wait(const struct timespec *timeout);

/**
* umcg_wake - wake @next
* @next: ID of the thread to wake (IDs are returned by umcg_register).
*
* If @next is blocked via umcg_wait, or umcg_swap, wake it. If @next is
* running, queue the wakeup, so that a future block of @next will consume
* the wakeup but will not block.
*
* umcg_wake is non-blocking, but may retry a few times to make sure @next
* has indeed woken.
*
* umcg_wake can queue at most one wakeup; if @next has a wakeup queued,
* an error is returned.
*
* Return:
* 0 - OK, @next has woken, or a wakeup has been queued;
* -1 - an error occurred.
*/
int umcg_wake(umcg_tid next);

/**
* umcg_swap - wake @next, put the current thread to sleep
* @next: ID of the thread to wake
* @timeout: absolute timeout (not supported at the moment)
*
* umcg_swap is semantically equivalent to
*
* int ret = umcg_wake(next);
* if (ret)
* return ret;
* return umcg_wait(timeout);
*
* but may do a synchronous context switch into @next on the current CPU. */
int umcg_swap(umcg_tid next, const struct timespec *timeout);

/**
* umcg_create_group - create a UMCG group
* @flags: Reserved.
*
* UMCG groups have worker and server threads.
*
* Worker threads are either RUNNABLE/RUNNING "on behalf" of server threads
* (see umcg_run_worker), or are BLOCKED/UNBLOCKED. A worker thread can be
* running only if it is attached to a server thread (interrupts can
* complicate the matter - TBD).
*
* Server threads are either blocked while running worker threads or are
* blocked waiting for available (=UNBLOCKED) workers. A server thread
* can "run" only one worker thread.
*
* Return:
* UMCG_NONE - an error occurred. Check errno.
* != UMCG_NONE - the ID of the group, to be used in e.g. umcg_register. */
umcg_t umcg_create_group(uint32_t flags);

/**
* umcg_destroy_group - destroy a UMCG group
* @umcg: ID of the group to destroy
*
* The group must be empty (no server or worker threads). *
* Return:
* 0 - Ok
* -1 - an error occurred. Check errno.
* errno == EAGAIN: the group has server or worker threads
*/
int umcg_destroy_group(umcg_t umcg);

/**
* umcg_poll_worker - wait for the first available UNBLOCKED worker *
* The current thread must be a UMCG server. If there is a list/queue of
* waiting UNBLOCKED workers in the server's group, umcg_poll_worker
* picks the longest waiting one; if there are no UNBLOCKED workers, the
* current thread sleeps in the polling queue.
*
* Return:
* UMCG_NONE - an error occurred; check errno;
* != UMCG_NONE - a RUNNABLE worker.
*/
umcg_tid umcg_poll_worker(void);

/**
* umcg_run_worker - run @worker as a UMCG server
* @worker: the ID of a RUNNABLE worker to run
*
* The current thread must be a UMCG "server".
*
* Return:
* UMCG_NONE - if errno == 0, the last worker the server was running
* unregistered itself; if errno != 0, an error occurred
* != UMCG_NONE - the ID of the last worker the server was running before
* the worker was blocked or preempted.
*/
umcg_tid umcg_run_worker(umcg_tid worker);

/**
* umcg_get_task-state - return the current UMCG state of @task
* @task: the ID of a UMCG task
*
* Return: one of UMCG_TASK_*** values defined in uapi/linux/umcg.h */
uint32_t umcg_get_task_state(umcg_tid task);

Plumbing API: sys_umcg_*** syscalls
-----------------------------------

The following new Linux syscalls are proposed:

::

sys_umcg_api_version
sys_umcg_register_task
sys_umcg_unregister_task
sys_umcg_wait
sys_umcg_wake
sys_umcg_swap
sys_umcg_create_group
sys_umcg_destroy_group
sys_umcg_poll_worker
sys_umcg_run_worker
sys_umcg_preempt_worker

They closely resemble umcg_*** functions from libumcg, but are more lightweight. For example, some of the state transitions described above are technically handled in the user space (libumcg), with the syscalls doing the absolute minimum. The exact boundary of what is done in the kernel and what is delegated to the userspace is still work-in-progress. End users are supposed to use libumcg rather than call sys_umcg_*** directly.

sys_umcg_preempt_worker() is a placeholder for a new syscall to be added in the future.

A brief historical note
=======================

In 2012-2013 Paul Turner and his team at Google developed SwitchTo and SwitchTo Groups Linux kernel extensions, on top of which a C++ user space scheduling framework called "Google Fibers" is built; it is used widely and successfully at Google.

UMCG core API (wait/wake/swap) is based on SwitchTo API, while the overall UMCG API resembles SwitchTo Groups API.

#31 lore raw
Quoted 9 lines · Peter Oskolkov

I've pasted below the content of umcg.rst file that I'll add as a doc patch to the next version of the patchset. I've also attached a PDF version of the file rendered, in case it is useful. I also think that it is a bit early for manpages - I expect the API and/or behavior to change quite a bit before this is all merged. I'm also not completely sure whether the manpages should describe the "porcelain API" or the "plumbing API" (see the .rst below).

Please let me know if you have any questions, comments, or suggestions.

So this is very helpful, thanks. I've been through it once, and have some overall comments.

- Parts of it read more like a requirements document. A document going into the kernel should describe what the code actually does, not what we think it should be.

- I would make a serious effort to get a handle on the terminology. The term "kernel thread" has a meaning other than the one you give it; saying "kernel thread" here will lead to a lot of confusion. I hesitate to suggest terms because I'm terrible at naming (just ask my kids), but I would pick clear and concise names for your "server threads" and "worker threads", then stick to them.

- The library documentation is good to have, but it will really be necessary to document the system calls as well. *That* is the part that the kernel community will have to support forever if this is merged.

Thanks,

jon

A message that is not in the archive (sent off-list or not yet received): CAEWA0a72SvpcuN4ov=98T3uWtExPCr7BQePOgjkqD1ofWKEASw@mail.gmail.com

#33 lore raw
Quoted 5 lines · Andrei Vagin
Quoted 1 line · Peter Oskolkov
Quoted 8 lines
Quoted 3 lines

As indicated earlier in the FUTEX_SWAP patchset:

https://lore.kernel.org/lkml/[email protected]/

Hi Peter,

Do you have benchmark results? How fast is it compared with futex_swap and the google switchto?

Hi Andrei,

I did not run benchmarks on the same machine/kernel, but umcg_swap between "core" tasks (your use case for gVisor) should be somewhat faster than futex_swap, as there is no reading from the userspace and no futex hash lookup/dequeue ops; umcg_swap should be slower than switchto_switch because umcg_swap does go through ttwu+schedule, which switchto_switch bypasses.

I expect that if UMCG is merged in a form similar to what I posted, we will explore how to make UMCG context switches faster in later patches.

Thanks,
Peter

Quoted 3 lines

Thanks,
Andrei

#34 lore raw
Quoted 10 lines · Peter Oskolkov
Quoted 9 lines · Andrei Vagin
Quoted 4 lines · Peter Oskolkov

As indicated earlier in the FUTEX_SWAP patchset:

https://lore.kernel.org/lkml/[email protected]/

Hi Peter,

Quoted 8 lines
Quoted 1 line

Do you have benchmark results? How fast is it compared with futex_swap and the google switchto?

Hi Andrei,

I did not run benchmarks on the same machine/kernel, but umcg_swap between "core" tasks (your use case for gVisor) should be somewhat faster than futex_swap, as there is no reading from the userspace and no futex hash lookup/dequeue ops;

The futex code currently creates and destroys hash table elements on wait/wake, which does involve locking, but you could probably avoid that if you built a faster futex variant optimized for the single-waiter case that uses a bit more kernel memory to keep a persistent hash table element (with RCU freeing) per pre-registered lock address around? Whether that'd be significantly faster, I don't know.

(As a sidenote, the futex code could slow down if the number of futex buckets isn't well-calibrated - meaning you have something like >200 distinct futex addresses per CPU core, see futex_init(). Then futex_init() probably needs to be tuned a bit. Actually, on my work laptop, this is what I see right now (not counting multiple waiters on the same address in the same process, since they intentionally occupy the same bucket):

# for tasks_dir in /proc/*/task; do cat $tasks_dir/*/syscall | grep
'^202 ' | cut -d' ' -f2 | sort | uniq; done | wc -l
1193
# cat /sys/devices/system/cpu/possible
0-3
# gdb -core=/proc/kcore -ex "print ((unsigned long *)(0x$(grep
__futex_data /proc/kallsyms | cut -d' ' -f1)))[1]" -batch
[...]
$1 = 1024

So the load factor of the futex hash table on this machine right now is ~117%, which I think is quite a bit higher than you'd normally want in a hash table? I don't know how representative that is though. Seems to mostly come from the tons of Chrome processes.)

maintainer
#35 lore raw
In reply to Peter Oskolkov

Quoting random parts of the first few patches folded.

You present an API without explaining, *at*all*, how it's supposed to be used and I can't seem to figure it out from the implementation either :/

arch/x86/entry/syscalls/syscall_64.tbl line 374

Quoted 12 lines

Index: linux-2.6/arch/x86/entry/syscalls/syscall_64.tbl
===================================================================

arch/x86/entry/syscalls/syscall_64.tbl +3 -0
@@ -368,6 +368,17 @@
 444	common	landlock_create_ruleset	sys_landlock_create_ruleset
 445	common	landlock_add_rule	sys_landlock_add_rule
 446	common	landlock_restrict_self	sys_landlock_restrict_self
 
+447	common	umcg_api_version	sys_umcg_api_version
+448	common	umcg_register_task	sys_umcg_register_task
+449	common	umcg_unregister_task	sys_umcg_unregister_task

I think we can do away with the api_version thing and frob that in register. Also, do we really need unregister over just letting a task exit? Is there a sane use-case where task goes in and out of service?

arch/x86/entry/syscalls/syscall_64.tbl line 376

Quoted 2 lines
arch/x86/entry/syscalls/syscall_64.tbl +2 -0
+450	common	umcg_wait		sys_umcg_wait
+451	common	umcg_wake		sys_umcg_wake

Right, except I'm confused by the proposed implementation. I thought the whole point was to let UMCG tasks block in kernel, at which point we'd change their state to BLOCKED and have userspace select another task to run. Such BLOCKED tasks would then also be captured before they return to userspace, i.e. the whole admission scheduler thing.

I don't see any of that in these patches. So what are they actually implementing? I can't find enough clues to tell :-(

arch/x86/entry/syscalls/syscall_64.tbl line 377

Quoted 1 line
arch/x86/entry/syscalls/syscall_64.tbl +1 -0
+452	common	umcg_swap		sys_umcg_swap

You're presenting it like a pure optimization, but IIRC this is what enables us to frob the scheduler state to ensure the whole thing is seen (to the rest of the system) as the M server tasks, instead of the constellation of N+M worker and server tasks.

Also, you're not doing any of the frobbing required.

arch/x86/entry/syscalls/syscall_64.tbl line 379

Quoted 2 lines
arch/x86/entry/syscalls/syscall_64.tbl +2 -0
+453	common	umcg_create_group	sys_umcg_create_group
+454	common	umcg_destroy_group	sys_umcg_destroy_group

This is basically needed for cross-server things, right? What we in the kernel would call SMP. Some thoughts on that below.

arch/x86/entry/syscalls/syscall_64.tbl line 380

Quoted 1 line
arch/x86/entry/syscalls/syscall_64.tbl +1 -0
+455	common	umcg_poll_worker	sys_umcg_poll_worker

Shouldn't this be called idle or something, instead of poll, the whole point of having this syscall is to that you can indeed go idle. Userspace can implement polling just fine without help:

	for (;;) {
		struct umcg_task *runnable = xchg(me->umcg_runnable_ptr, NULL);
		if (runnable) {
			// put them on a list and run one
		}
		cpu_relax();
	}

comes to mind (see below).

arch/x86/entry/syscalls/syscall_64.tbl line 381

Quoted 1 line
arch/x86/entry/syscalls/syscall_64.tbl +1 -0
+456	common	umcg_run_worker		sys_umcg_run_worker

This I'm confused about again.. there is no fundamental difference between a worker or server, they're all the same.

arch/x86/entry/syscalls/syscall_64.tbl line 382

Quoted 1 line
arch/x86/entry/syscalls/syscall_64.tbl +1 -0
+457	common	umcg_preempt_worker	sys_umcg_preempt_worker

And that's magic, we'll get to it..

Quoted 5 lines

Index: linux-2.6/include/uapi/linux/umcg.h
===================================================================

include/uapi/linux/umcg.h line 9

Quoted 9 lines
include/uapi/linux/umcg.h new file +9 -0
@@ -0,0 +1,70 @@
+/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */
+#ifndef _UAPI_LINUX_UMCG_H
+#define _UAPI_LINUX_UMCG_H
+
+#include <linux/limits.h>
+#include <linux/types.h>
+
+/*
+ * UMCG task states, the first 8 bits.

All that needs a state transition diagram included

include/uapi/linux/umcg.h line 15

Quoted 6 lines
include/uapi/linux/umcg.h new file +6 -0
+ */
+#define UMCG_TASK_NONE			0
+/* UMCG server states. */
+#define UMCG_TASK_POLLING		1
+#define UMCG_TASK_SERVING		2
+#define UMCG_TASK_PROCESSING		3

I get POLLING, although per the above, this probably wants to be IDLE.

What are the other two again? That is, along with the diagram, each state wants a description.

include/uapi/linux/umcg.h line 20

Quoted 5 lines
include/uapi/linux/umcg.h new file +5 -0
+/* UMCG worker states. */
+#define UMCG_TASK_RUNNABLE		4
+#define UMCG_TASK_RUNNING		5
+#define UMCG_TASK_BLOCKED		6
+#define UMCG_TASK_UNBLOCKED		7

Weird order, also I can't remember why we need the UNBLOCKED, isn't that the same as the RUNNABLE, or did we want to distinguish the state were we're no longer BLOCKED but the user scheduler hasn't yet put us on it's ready queue (IOW, we're on the runnable_ptr list, see below).

Quoted 26 lines
include/uapi/linux/umcg.h new file +26 -0
+
+/* UMCG task state flags, bits 8-15 */
+#define UMCG_TF_WAKEUP_QUEUED		(1 << 8)
+
+/*
+ * Unused at the moment flags reserved for features to be introduced
+ * in the near future.
+ */
+#define UMCG_TF_PREEMPT_DISABLED	(1 << 9)
+#define UMCG_TF_PREEMPTED		(1 << 10)
+
+#define UMCG_NOID	UINT_MAX
+
+/**
+ * struct umcg_task - controls the state of UMCG-enabled tasks.
+ *
+ * While at the moment only one field is present (@state), in future
+ * versions additional fields will be added, e.g. for the userspace to
+ * provide performance-improving hints and for the kernel to export sched
+ * stats.
+ *
+ * The struct is aligned at 32 bytes to ensure that even with future additions
+ * it fits into a single cache line.
+ */
+struct umcg_task {
+	/**

include/uapi/linux/umcg.h line 56

Quoted 10 lines
include/uapi/linux/umcg.h new file +10 -0
+	 * @state: the current state of the UMCG task described by this struct.
+	 *
+	 * UMCG task state:
+	 *   bits  0 -  7: task state;
+	 *   bits  8 - 15: state flags;
+	 *   bits 16 - 23: reserved; must be zeroes;
+	 *   bits 24 - 31: for userspace use.
+	 */
+	uint32_t	state;
+} __attribute((packed, aligned(4 * sizeof(uint64_t))));

So last time I really looked at this it looked something like this:

struct umcg_task {

        u32     umcg_status;            /* r/w */
        u32     umcg_server_tid;        /* r   */
        u32     umcg_next_tid;          /* r   */
        u32     __hole__;
        u64     umcg_blocked_ptr;       /*   w */
        u64     umcg_runnable_ptr;      /*   w */

};

(where r/w is from the kernel's pov)
(also see uapi/linux/rseq.h's ptr magic)

So a PF_UMCG_WORKER would be added to sched_submit_work()'s PF_*_WORKER path to capture these tasks blocking. The umcg_sleeping() hook added there would:

    put_user(BLOCKED, umcg_task->umcg_status);

    tid = get_user(umcg_task->next_tid);
    if (!tid)
	tid = get_user(umcg_task->umcg_server_tid);
    umcg_server = find_task(tid);

    /* append to blocked list */
    umcg_task->umcg_blocked_ptr = umcg_server->umcg_blocked_ptr;
    umcg_server->umcg_blocked_ptr = umcg_task;

    // with some user_cmpxchg() sprinkled on to make it an atomic single
    // linked list, we can borrow from futex_atomic_cmpxchg_inatomic().

    /* capture return to user */
    add_task_work(current, &current->umcg->task_work, TWA_RESUME);

    umcg_server->state = RUNNING;
    wake_up_process(umcg_server);

That task_work would, as the comment says, capture the return to user, and do something like:

    put_user(RUNNABLE, umcg_task->umcg_status);

    tid = get_user(umcg_task->umcg_server_tid);
    umcg_server = find_task(tid);

    /* append to runable list */
    umcg_task->umcg_runnable_ptr = umcg_server->umcg_runnable_ptr;
    umcg_server->umcg_runnable_ptr = umcg_task;
    // same as above, this wants some user cmpxchg

    umcg_wait();

And for that we had something like:

void umcg_wait(void)

{
	u32 state;

	for (;;) {
		set_current_state(TASK_INTERRUPTIBLE);
		if (get_user(state, current->umcg->state))
			break;
		if (state == UMCG_RUNNING)
			break;
		if (signal_pending(current))
			break;
		schedule();
	}
	__set_current_state(TASK_RUNNING);
}

Which would wait until the userspace admission logic lets us rip by setting state to RUNNING and prodding us with a sharp stick.

This all ensures that when a UMCG task goes to sleep, we mark ourselves BLOCKED, we add ourselves to a user visible blocked list and wake the owner of that blocked list.

We can either pre-select some task to run after us (next_tid) or it'll pick the dedicated server task we're assigned to (server_tid).

Any time a task wakes up, it needs to check the blocked list and update userspace ready queues and the sort, after which it can either run things if it's a worker or pick another task to run if that's its work (a server isn't special in this regard).

This was the absolute bare minimum, and I'm not seeing any of that here. Nor an explanation of what there actually is :/

On top of this there's 'fun' questions about signals, ptrace and umcg_preemption to be answered.

I think we want to allow signals to happen to UMCG RUNNABLE tasks, but have them resume umcg_wait() on sigreturn.

I've not re-read the discussion with tglx on ptrace, he had some cute corner cases IIRC.

The whole preemption thing should be doable with a task_work. Basically check if the victim is RUNNING, send it TWA_SIGNAL to handle the task work, the task_work would attempt a RUNNING->RUNNABLE (cmpxchg) transition, success thereof needs to be propagated back to the syscall and returned.

Adding preemption also means you have to deal with appending to runnable_ptr list when the server isn't reaily available (most times).

Now on to those group things; they would basically replace the above server_tid with a group/list of related server tasks, right? So why not do so, litearlly:

struct umcg_task {

        u32     umcg_status;            /* r/w */
        u32     umcg_next_tid;          /* r   */
        u64     umcg_server_ptr;        /* r   */
        u64     umcg_blocked_ptr;       /*   w */
        u64     umcg_runnable_ptr;      /*   w */

};

Then have the kernel iterate the umcg_server_ptr list, looking for an available (RUNNING or IDLE) server, also see the preemption point above.

This does, however, require a umcg_task to pid translation, which we've so far avoided :/ OTOH it makes that grouping crud a user problem and we can make the syscalls go away (and I that CRUI would like this better too).

Quoted 36 lines
include/uapi/linux/umcg.h new file +36 -0
+static int do_context_switch(struct task_struct *next)
+{
+	struct umcg_task_data *utd = rcu_access_pointer(current->umcg_task_data);
+
+	/*
+	 * It is important to set_current_state(TASK_INTERRUPTIBLE) before
+	 * waking @next, as @next may immediately try to wake current back
+	 * (e.g. current is a server, @next is a worker that immediately
+	 * blocks or waits), and this next wakeup must not be lost.
+	 */
+	set_current_state(TASK_INTERRUPTIBLE);
+
+	WRITE_ONCE(utd->in_wait, true);
+
+	if (!try_to_wake_up(next, TASK_NORMAL, WF_CURRENT_CPU))
+		return -EAGAIN;
+
+	freezable_schedule();
+
+	WRITE_ONCE(utd->in_wait, false);
+
+	if (signal_pending(current))
+		return -EINTR;
+
+	return 0;
+}
+
+static int do_wait(void)
+{
+	struct umcg_task_data *utd = rcu_access_pointer(current->umcg_task_data);
+
+	if (!utd)
+		return -EINVAL;
+
+	WRITE_ONCE(utd->in_wait, true);
+

include/uapi/linux/umcg.h

Quoted 10 lines
include/uapi/linux/umcg.h new file +10 -0
+	set_current_state(TASK_INTERRUPTIBLE);
+	freezable_schedule();
+
+	WRITE_ONCE(utd->in_wait, false);
+
+	if (signal_pending(current))
+		return -EINTR;
+
+	return 0;
+}

Both these are fundamentally buggered for not having a loop.

Quoted 9 lines
include/uapi/linux/umcg.h new file +9 -0
+/**
+ * sys_umcg_wait - block the current task (if all condtions are met).
+ * @flags:         Reserved.
+ * @timeout:       The absolute timeout of the wait. Not supported yet.
+ *                 Must be NULL.
+ *
+ * Sleep until woken, interrupted, or @timeout expires.
+ *
+ * Return:

include/uapi/linux/umcg.h

Quoted 10 lines
include/uapi/linux/umcg.h new file +10 -0
+ * 0           - Ok;
+ * -EFAULT     - failed to read struct umcg_task assigned to this task
+ *               via sys_umcg_register();
+ * -EAGAIN     - try again;
+ * -EINTR      - signal pending;
+ * -EOPNOTSUPP - @timeout != NULL (not supported yet).
+ * -EINVAL     - a parameter or a member of struct umcg_task has a wrong value.
+ */
+SYSCALL_DEFINE2(umcg_wait, u32, flags,
+		const struct __kernel_timespec __user *, timeout)

I despise timespec, tglx?

Quoted 6 lines
include/uapi/linux/umcg.h new file +6 -0
+{
+	struct umcg_task_data *utd;
+
+	if (flags)
+		return -EINVAL;
+	if (timeout)

include/uapi/linux/umcg.h

Quoted 10 lines
include/uapi/linux/umcg.h new file +10 -0
+		return -EOPNOTSUPP;
+
+	rcu_read_lock();
+	utd = rcu_dereference(current->umcg_task_data);
+	if (!utd) {
+		rcu_read_unlock();
+		return -EINVAL;
+	}
+
+	rcu_read_unlock();

What Jann said.

Quoted 33 lines
include/uapi/linux/umcg.h new file +33 -0
+
+	return do_wait();
+}
+
+/**
+ * sys_umcg_wake - wake @next_tid task blocked in sys_umcg_wait.
+ * @flags:         Reserved.
+ * @next_tid:      The ID of the task to wake.
+ *
+ * Wake @next identified by @next_tid. @next must be either a UMCG core
+ * task or a UMCG worker task.
+ *
+ * Return:
+ * 0           - Ok;
+ * -EFAULT     - failed to read struct umcg_task assigned to next;
+ * -ESRCH      - @next_tid did not identify a task;
+ * -EAGAIN     - try again;
+ * -EINVAL     - a parameter or a member of next->umcg_task has a wrong value.
+ */
+SYSCALL_DEFINE2(umcg_wake, u32, flags, u32, next_tid)
+{
+	struct umcg_task_data *next_utd;
+	struct task_struct *next;
+	int ret = -EINVAL;
+
+	if (!next_tid)
+		return -EINVAL;
+	if (flags)
+		return -EINVAL;
+
+	next = find_get_task_by_vpid(next_tid);
+	if (!next)
+		return -ESRCH;

include/uapi/linux/umcg.h

Quoted 10 lines
include/uapi/linux/umcg.h new file +10 -0
+
+	rcu_read_lock();
+	next_utd = rcu_dereference(next->umcg_task_data);
+	if (!next_utd)
+		goto out;
+
+	if (!READ_ONCE(next_utd->in_wait)) {
+		ret = -EAGAIN;
+		goto out;
+	}

I'm thining this might want to be a user cmpxchg from RUNNABLE->RUNNING.

You need to deal with concurrent wakeups.

Quoted 12 lines
include/uapi/linux/umcg.h new file +12 -0
+
+	ret = wake_up_process(next);
+	put_task_struct(next);
+	if (ret)
+		ret = 0;
+	else
+		ret = -EAGAIN;
+
+out:
+	rcu_read_unlock();
+	return ret;
+}
#36 lore raw

On Wed, Jun 9, 2021 at 5:55 AM Peter Zijlstra <[email protected]> wrote:

Finally, a high-level review - thanks a lot, Peter! My comments below, and two high-level "important questions" at the end of my reply (with some less important questions here and there).

[...]

Quoted 2 lines

You present an API without explaining, *at*all*, how it's supposed to be used and I can't seem to figure it out from the implementation either :/

I tried to explain it in the doc patch that I followed up with:
https://lore.kernel.org/patchwork/cover/1433967/#1632328

Or do you mean it more narrowly, i.e. I do not explain syscalls in detail? This assessment I agree with - my approach was/is to finalize the userpace API (libumcg) first, and make the userspace vs kernel decisions later.

For example, you wonder why there is no looping in umcg_wait (do_wait). This is because the looping happens in the userspace in libumcg. My overall approach was to make the syscalls as simple as possible and push extra logic to the userspace.

It seems that this approach is not resonating with kernel developers/maintainers - you are the third person asking why there is no looping in sys_umcg_wait, despite the fact that I explicitly mentioned pushing it out to the userspace.

Let me try to make my case once more here.

umcg_wait/umcg_wake: the RUNNABLE/RUNNING state changes, checks, and looping happen in the userspace (libumcg - see umcg_wait/umcg_wake in patch 5 here: https://lore.kernel.org/patchwork/patch/1433971/), while the syscalls simply sleep/wake. I find doing it in the userspace is much simpler and easier than in the kernel, as state reads and writes are just atomic memory accesses; in the kernel it becomes much more difficult - rcu locked sections, tasks locked, etc.

On the other hand I agree that having syscalls more logically complete, in the sense that they do not require much hand-holding and retries from the userspace, is probably better from the API design perspective. My worry here is that state validation and retries in the userspace are unavoidable, and so going the usual way we will end up with retry loops both in the kernel and in the userspace.

So I pose this IMPORTANT QUESTION #1 to you that I hope to get a clear answer to: it is strongly preferable to have syscalls be "logically complete" in the sense that they retry things internally, and in generally try to cover all possible corner cases; or, alternatively, is it OK to make syscalls lightweight but "logically incomplete", and have the accompanied userspace wrappers do all of the heavy lifting
re: state changes/validation, retries, etc.?

I see two additional benefits of thin/lightweight syscalls:
- reading userspace state is needed much less often (e.g. my umcg_wait and umcg_wake syscalls do not access userspace data at all - also see my "second important question" below)
- looping in the kernel, combined with reading/writing to userspace memory, can easily lead to spinning in the kernel (e.g. trying to atomically change a variable and looping until succeeding)

A clear answer one way or the other will help a lot!

[...]

Quoted 5 lines
Quoted 2 lines
+448  common  umcg_register_task      sys_umcg_register_task
+449  common  umcg_unregister_task    sys_umcg_unregister_task

I think we can do away with the api_version thing and frob that in register.

Ok, will do.

Quoted 2 lines

Also, do we really need unregister over just letting a task exit? Is there a sane use-case where task goes in and out of service?

I do not know of a specific use case here. On the other hand, I do not know of a specific use case to unregister RSEQ, but the capability is there. Maybe the assumption is that the userspace memory passed to the kernel in register() may be freed before the task exits, and so there should be a way to tell the kernel to no longer use it?

Quoted 4 lines
Quoted 3 lines
+450  common  umcg_wait               sys_umcg_wait
+451  common  umcg_wake               sys_umcg_wake
Quoted 8 lines

Right, except I'm confused by the proposed implementation. I thought the whole point was to let UMCG tasks block in kernel, at which point we'd change their state to BLOCKED and have userspace select another task to run. Such BLOCKED tasks would then also be captured before they return to userspace, i.e. the whole admission scheduler thing.

I don't see any of that in these patches. So what are they actually implementing? I can't find enough clues to tell :-(

As I mentioned above, state changes are done in libumcg in userspace
here: https://lore.kernel.org/patchwork/cover/1433967/#1632328

If you insist this logic should live in the kernel, I'll do it (grudgingly).

Quoted 7 lines
Quoted 2 lines

+452 common umcg_swap sys_umcg_swap

You're presenting it like a pure optimization, but IIRC this is what enables us to frob the scheduler state to ensure the whole thing is seen (to the rest of the system) as the M server tasks, instead of the constellation of N+M worker and server tasks.

Yes, you recall it correctly.

Quoted 1 line

Also, you're not doing any of the frobbing required.

This is because I consider the frobbing a (very) nice to have rather than a required feature, and so I am hoping to argue about how to properly do it in later patchsets. This whole thing (UMCG) will be extremely useful even without runtime accounting hacking and whatnot, and so I hope to have everything else settled and tested and merged before we spend another several weeks/months trying to make the frobbing perfect.

Quoted 6 lines
Quoted 3 lines
+453  common  umcg_create_group       sys_umcg_create_group
+454  common  umcg_destroy_group      sys_umcg_destroy_group

This is basically needed for cross-server things, right? What we in the kernel would call SMP. Some thoughts on that below.

Yes, right.

Quoted 5 lines
Quoted 2 lines

+455 common umcg_poll_worker sys_umcg_poll_worker

Shouldn't this be called idle or something, instead of poll, the whole point of having this syscall is to that you can indeed go idle.

That's another way of looking at it. Yes, this means the server idles until a worker becomes available. How would you call it? umcg_idle()?

Quoted 10 lines

Userspace can implement polling just fine without help:

        for (;;) {
                struct umcg_task *runnable = xchg(me->umcg_runnable_ptr, NULL);
                if (runnable) {
                        // put them on a list and run one
                }
                cpu_relax();
        }
Quoted 6 lines

comes to mind (see below).

Quoted 1 line

+456 common umcg_run_worker sys_umcg_run_worker

This I'm confused about again.. there is no fundamental difference between a worker or server, they're all the same.

I don't see it this way. A server runs (on CPU) by itself and blocks when there is a worker attached; a worker runs (on CPU) only when it has a (blocked) server attached to it and, when the worker blocks, its server detaches and runs another worker. So workers and servers are the opposite of each other.

Quoted 5 lines
Quoted 2 lines

+457 common umcg_preempt_worker sys_umcg_preempt_worker

And that's magic, we'll get to it..

Quoted 16 lines
Quoted 5 lines

Index: linux-2.6/include/uapi/linux/umcg.h
===================================================================

include/uapi/linux/umcg.h line 9

Quoted 9 lines
include/uapi/linux/umcg.h new file +9 -0
@@ -0,0 +1,70 @@
+/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */
+#ifndef _UAPI_LINUX_UMCG_H
+#define _UAPI_LINUX_UMCG_H
+
+#include <linux/limits.h>
+#include <linux/types.h>
+
+/*
+ * UMCG task states, the first 8 bits.

All that needs a state transition diagram included

I will add it. For now the doc patch can be consulted:
https://lore.kernel.org/patchwork/cover/1433967/#1632328

Quoted 9 lines

include/uapi/linux/umcg.h line 15

Quoted 7 lines
include/uapi/linux/umcg.h new file +6 -0
+ */
+#define UMCG_TASK_NONE                       0
+/* UMCG server states. */
+#define UMCG_TASK_POLLING            1
+#define UMCG_TASK_SERVING            2
+#define UMCG_TASK_PROCESSING         3

I get POLLING, although per the above, this probably wants to be IDLE.

Ack.

Quoted 3 lines

What are the other two again? That is, along with the diagram, each state wants a description.

SERVING: the server is blocked, its attached worker is running
PROCESSING: the server is running (= processing a block or wake event), has no running worker attached

Both of these states are different from POLLING/IDLE and from each other.

Quoted 11 lines

include/uapi/linux/umcg.h line 20

Quoted 6 lines
include/uapi/linux/umcg.h new file +5 -0
+/* UMCG worker states. */
+#define UMCG_TASK_RUNNABLE           4
+#define UMCG_TASK_RUNNING            5
+#define UMCG_TASK_BLOCKED            6
+#define UMCG_TASK_UNBLOCKED          7

Weird order, also I can't remember why we need the UNBLOCKED, isn't that the same as the RUNNABLE, or did we want to distinguish the state were we're no longer BLOCKED but the user scheduler hasn't yet put us on it's ready queue (IOW, we're on the runnable_ptr list, see below).

Yes, UNBLOCKED it a transitory state meaning the worker's blocking operation has completed, but the wake event hasn't been delivered to the userspace yet (and so the worker it not yet RUNNABLE)

[...]

Quoted 22 lines

include/uapi/linux/umcg.h line 32

Quoted 12 lines
include/uapi/linux/umcg.h new file +12 -0
+struct umcg_task {
+     /**
+      * @state: the current state of the UMCG task described by this struct.
+      *
+      * UMCG task state:
+      *   bits  0 -  7: task state;
+      *   bits  8 - 15: state flags;
+      *   bits 16 - 23: reserved; must be zeroes;
+      *   bits 24 - 31: for userspace use.
+      */
+     uint32_t        state;
+} __attribute((packed, aligned(4 * sizeof(uint64_t))));

So last time I really looked at this it looked something like this:

struct umcg_task {

        u32     umcg_status;            /* r/w */
        u32     umcg_server_tid;        /* r   */
        u32     umcg_next_tid;          /* r   */
        u32     __hole__;
        u64     umcg_blocked_ptr;       /*   w */
        u64     umcg_runnable_ptr;      /*   w */
Quoted 4 lines

};

(where r/w is from the kernel's pov)
(also see uapi/linux/rseq.h's ptr magic)

I tried doing it this way, i.e. to only have only userspace struct added (without kernel-only data), and I found it really cumbersome and inconvenient and much slower than the proposed implementation. For example, when a worker blocks, it seems working with "struct task_struct *peer" to get to the worker's server is easy and straightforward; reading server_tid from userspace, then looking up the task and only then doing what is needed (change state and wakeup) is ... unnecessary? Also validating things becomes really important but difficult (what if the user put something weird in umcg_server_tid? or the ptr fields?). In my proposed implementation only the state is user-writable, and it does not really affect most of the kernel-side work.

Why do you think everything should be in the userspace memory?

Quoted 110 lines

So a PF_UMCG_WORKER would be added to sched_submit_work()'s PF_*_WORKER path to capture these tasks blocking. The umcg_sleeping() hook added there would:

    put_user(BLOCKED, umcg_task->umcg_status);

    tid = get_user(umcg_task->next_tid);
    if (!tid)
        tid = get_user(umcg_task->umcg_server_tid);
    umcg_server = find_task(tid);

    /* append to blocked list */
    umcg_task->umcg_blocked_ptr = umcg_server->umcg_blocked_ptr;
    umcg_server->umcg_blocked_ptr = umcg_task;

    // with some user_cmpxchg() sprinkled on to make it an atomic single
    // linked list, we can borrow from futex_atomic_cmpxchg_inatomic().

    /* capture return to user */
    add_task_work(current, &current->umcg->task_work, TWA_RESUME);

    umcg_server->state = RUNNING;
    wake_up_process(umcg_server);

That task_work would, as the comment says, capture the return to user, and do something like:

    put_user(RUNNABLE, umcg_task->umcg_status);

    tid = get_user(umcg_task->umcg_server_tid);
    umcg_server = find_task(tid);

    /* append to runable list */
    umcg_task->umcg_runnable_ptr = umcg_server->umcg_runnable_ptr;
    umcg_server->umcg_runnable_ptr = umcg_task;
    // same as above, this wants some user cmpxchg

    umcg_wait();

And for that we had something like:

void umcg_wait(void)

{
        u32 state;

        for (;;) {
                set_current_state(TASK_INTERRUPTIBLE);
                if (get_user(state, current->umcg->state))
                        break;
                if (state == UMCG_RUNNING)
                        break;
                if (signal_pending(current))
                        break;
                schedule();
        }
        __set_current_state(TASK_RUNNING);
}

Which would wait until the userspace admission logic lets us rip by setting state to RUNNING and prodding us with a sharp stick.

This all ensures that when a UMCG task goes to sleep, we mark ourselves BLOCKED, we add ourselves to a user visible blocked list and wake the owner of that blocked list.

We can either pre-select some task to run after us (next_tid) or it'll pick the dedicated server task we're assigned to (server_tid).

Any time a task wakes up, it needs to check the blocked list and update userspace ready queues and the sort, after which it can either run things if it's a worker or pick another task to run if that's its work (a server isn't special in this regard).

This was the absolute bare minimum, and I'm not seeing any of that here. Nor an explanation of what there actually is :/

On top of this there's 'fun' questions about signals, ptrace and umcg_preemption to be answered.

I think we want to allow signals to happen to UMCG RUNNABLE tasks, but have them resume umcg_wait() on sigreturn.

I've not re-read the discussion with tglx on ptrace, he had some cute corner cases IIRC.

The whole preemption thing should be doable with a task_work. Basically check if the victim is RUNNING, send it TWA_SIGNAL to handle the task work, the task_work would attempt a RUNNING->RUNNABLE (cmpxchg) transition, success thereof needs to be propagated back to the syscall and returned.

Adding preemption also means you have to deal with appending to runnable_ptr list when the server isn't reaily available (most times).

Now on to those group things; they would basically replace the above server_tid with a group/list of related server tasks, right? So why not do so, litearlly:

struct umcg_task {

        u32     umcg_status;            /* r/w */
        u32     umcg_next_tid;          /* r   */
        u64     umcg_server_ptr;        /* r   */
        u64     umcg_blocked_ptr;       /*   w */
        u64     umcg_runnable_ptr;      /*   w */

};

Quoted 7 lines

Then have the kernel iterate the umcg_server_ptr list, looking for an available (RUNNING or IDLE) server, also see the preemption point above.

This does, however, require a umcg_task to pid translation, which we've so far avoided :/ OTOH it makes that grouping crud a user problem and we can make the syscalls go away (and I that CRUI would like this better too).

All of the code above assumes userspace-only data. I did not look into every detail of your suggestions because I want to make sure we first agree on this: do we keep every bit of information in the userspace (other than "struct umcg_task __user *" pointer in task_struct) or do we have some kernel-only details as well?

So IMPORTANT QUESTION #2: why would we want to keep __everything__ in the userspace memory? I understand that CRIU would like this, but given that the implementation would at a minimum have to

1. read a umcg_server_ptr (points to the server's umcg_task)
2. get the server tid out of it (presumably by reading a field from the server's umcg_task; what if the tid is wrong?)
3. do a tid lookup

to get a task_struct pointer, it will be slower; I am also not sure it call be done safely at all: with kernel-side data and I can do rcu locking, task locking, etc. to ensure that the value I got does not change while I'm working with it; with userspace data, a lot of races will have to be specially coded for that can be easily handled by kernel-side rcu locks or spin locks... Maybe this is just my ignorance showing, and indeed things can be done simply and easily with userspace-only data, but I am not sure how.

A common example:

- worker W1 with server S1 calls umcg_wait()
- worker W2 with server S2 calls umcg_swap(W1)

If due to preemption and other concurrency weirdness the two syscalls above race with each other, each trying to change the server assigned to W1. I can easily handle the race by doing kernel-side locking; without kernel-side locking (cannot do rcu locks and/or spin locks while accessing userspace data) I am not sure how to handle the race. Maybe it is possible with careful atomic writes to states and looping to handle this specific race (what if the userspace antagonistically writes to the same location? will it force the syscall to spin indefinitely?); but with proper locking many potential races can be handled; with atomic ops and looping it is more difficult... Will we have to add a lock to struct umcg_task? And acquire it from the kernel side? And worry about spinning forever?

Quoted 3 lines
Quoted 3 lines
include/uapi/linux/umcg.h new file +2 -0
+static int do_context_switch(struct task_struct *next)
+{

[...]

Quoted 4 lines
Quoted 4 lines
include/uapi/linux/umcg.h new file +4 -0
+}
+
+static int do_wait(void)
+{

[...]

Quoted 3 lines
Quoted 1 line

+}

Both these are fundamentally buggered for not having a loop.

As I mentioned above, the loop is in the userpace.

[...]

Quoted 4 lines

include/uapi/linux/umcg.h

Quoted 2 lines
include/uapi/linux/umcg.h new file +2 -0
+SYSCALL_DEFINE2(umcg_wait, u32, flags,
+             const struct __kernel_timespec __user *, timeout)

I despise timespec, tglx?

What are the alternatives? I just picked what the futex code uses.

[...]

Quoted 2 lines
Quoted 2 lines
include/uapi/linux/umcg.h new file +2 -0
+SYSCALL_DEFINE2(umcg_wake, u32, flags, u32, next_tid)
+{

[...]

Quoted 4 lines

I'm thinking this might want to be a user cmpxchg from RUNNABLE->RUNNING.

You need to deal with concurrent wakeups.

This is done in the userspace - much easier to do it there...

In summary, two IMPORTANT QUESTIONS:

1. thin vs fat syscalls: can we push some code/logic to the userspace (state changes, looping/retries), or do we insist on syscalls handling everything? Please have in mind that even if we choose the second approach (fat syscalls), the userspace will most likely still have to do everything it does under the first option just to handle signals/interrupts (i.e. unscheduled wakeups);
2. kernel-side data vs userspace-only: can we avoid having kernel-side data? More specifically, what alternatives to rcu_read_lock and/or task_lock are available when working with userspace data?

When these two questions are answered to everybody's satisfaction, we can discuss this patchset/library/API in more detail.

Thanks,
Peter

maintainer
#37 lore raw
Quoted 6 lines · Peter Oskolkov

On Wed, Jun 9, 2021 at 5:55 AM Peter Zijlstra <[email protected]> wrote:

Finally, a high-level review - thanks a lot, Peter! My comments below, and two high-level "important questions" at the end of my reply (with some less important questions here and there).

Quoted 7 lines

[...]

Quoted 2 lines

You present an API without explaining, *at*all*, how it's supposed to be used and I can't seem to figure it out from the implementation either :/

I tried to explain it in the doc patch that I followed up with:
https://lore.kernel.org/patchwork/cover/1433967/#1632328

Urgh, you write RST :-( That sorta helps, but I'm still unclear on a number of things, more below.

Quoted 4 lines

Or do you mean it more narrowly, i.e. I do not explain syscalls in detail? This assessment I agree with - my approach was/is to finalize the userpace API (libumcg) first, and make the userspace vs kernel decisions later.

Yeah, I couldn't figure out how to use the syscalls and thus how to interpret their implementation. A little more in the way of comments would've been helpful.

Quoted 4 lines

For example, you wonder why there is no looping in umcg_wait (do_wait). This is because the looping happens in the userspace in libumcg. My overall approach was to make the syscalls as simple as possible and push extra logic to the userspace.

So a simple comment on the syscall that says:

Userspace is expected to do:

	do {
		sys_umcg_wait();
	} while (smp_load_acquire(&umcg_task->state) != RUNNING);

would've made all the difference. It provides context.

Quoted 4 lines

It seems that this approach is not resonating with kernel developers/maintainers - you are the third person asking why there is no looping in sys_umcg_wait, despite the fact that I explicitly mentioned pushing it out to the userspace.

We've been trained, through years of 'funny' bugs, to go 'BUG BUG BUG' when schedule() is not in a loop. And pushing the loop to userspace has me all on edge for being 'weird'.

Quoted 9 lines

Let me try to make my case once more here.

umcg_wait/umcg_wake: the RUNNABLE/RUNNING state changes, checks, and looping happen in the userspace (libumcg - see umcg_wait/umcg_wake in patch 5 here: https://lore.kernel.org/patchwork/patch/1433971/), while the syscalls simply sleep/wake. I find doing it in the userspace is much simpler and easier than in the kernel, as state reads and writes are just atomic memory accesses; in the kernel it becomes much more difficult - rcu locked sections, tasks locked, etc.

Small difficulties as far as things go I think. The worst part is having to do arch asm for the userspace cmpxchg. Luckily we can crib/share with futex there.

Quoted 6 lines

On the other hand I agree that having syscalls more logically complete, in the sense that they do not require much hand-holding and retries from the userspace, is probably better from the API design perspective. My worry here is that state validation and retries in the userspace are unavoidable, and so going the usual way we will end up with retry loops both in the kernel and in the userspace.

Can you expand on where you'd see the need for userspace to retry?

The canonical case in my mind is where a task, that's been BLOCKED in kernelspace transitions to UNBLOCK/RUNNABLE in return-to-user and waits for RUNNING.

Once it gets RUNNING, userspace can assume it can just go. It will never have to re-check, because there's no way RUNNING can go away again. The only way for RUNNING to become anything else, is setting it yourself and/or doing a syscall.

Also, by having the BLOCKED thing block properly in return-to-user, you don't have to wrap *all* the userspace syscall invocations. If you let it return early, you get to wrap syscalls, which is both fragile and bad for performance.

Quoted 7 lines

So I pose this IMPORTANT QUESTION #1 to you that I hope to get a clear answer to: it is strongly preferable to have syscalls be "logically complete" in the sense that they retry things internally, and in generally try to cover all possible corner cases; or, alternatively, is it OK to make syscalls lightweight but "logically incomplete", and have the accompanied userspace wrappers do all of the heavy lifting
re: state changes/validation, retries, etc.?

Intuitively I'd go with complete. I'd have never even considered the incomplete option. But let me try and get my head around the incomplete cases.

Oooh, I found the BLOCKED stuff, you hid it inside the grouping patch, that makes no sense :-( Reason I'm looking is that I don't see how you get around the blocked and runnable lists. You have to tell userspace about them.

FWIW: I think you placed umcg_on_block() wrong, it needs to be before the terrible PI thing. Also, like said, please avoid yet another branch here by using PF_UMCG_WORKER.

Quoted 4 lines

I see two additional benefits of thin/lightweight syscalls:
- reading userspace state is needed much less often (e.g. my umcg_wait and umcg_wake syscalls do not access userspace data at all - also see my "second important question" below)

It is also broken I think, best I can make of it is somsething like this:

    WAIT						WAKE

    if (smp_load_acquire(&state) == RUNNING)
	return;

							state = RUNNING;


    do {
      sys_umcg_wait()
      {
	in_wait = true;
							sys_umcg_wake()
							{
							  if (in_wait)
							    wake_up_process()
							}
	set_current_state(INTERRUPTIBLE);
	schedule();
	in_wait = false;
      }
    } while (smp_load_acquire(&state) != RUNNING);

missed wakeup, 'forever' stuck. You have to check your blocking condition between setting state and scheduling. And if you do that, you have a 'fat' syscall again.

Quoted 3 lines

- looping in the kernel, combined with reading/writing to userspace memory, can easily lead to spinning in the kernel (e.g. trying to atomically change a variable and looping until succeeding)

I don't imagine spinning in kernel or userspace matters.

Quoted 8 lines
Quoted 2 lines

Also, do we really need unregister over just letting a task exit? Is there a sane use-case where task goes in and out of service?

I do not know of a specific use case here. On the other hand, I do not know of a specific use case to unregister RSEQ, but the capability is there. Maybe the assumption is that the userspace memory passed to the kernel in register() may be freed before the task exits, and so there should be a way to tell the kernel to no longer use it?

Fair enough I suppose.

Quoted 10 lines
Quoted 10 lines
Quoted 3 lines
+450  common  umcg_wait               sys_umcg_wait
+451  common  umcg_wake               sys_umcg_wake

Right, except I'm confused by the proposed implementation. I thought the whole point was to let UMCG tasks block in kernel, at which point we'd change their state to BLOCKED and have userspace select another task to run. Such BLOCKED tasks would then also be captured before they return to userspace, i.e. the whole admission scheduler thing.

Quoted 7 lines
Quoted 2 lines

I don't see any of that in these patches. So what are they actually implementing? I can't find enough clues to tell :-(

As I mentioned above, state changes are done in libumcg in userspace
here: https://lore.kernel.org/patchwork/cover/1433967/#1632328

If you insist this logic should live in the kernel, I'll do it (grudgingly).

So you have some of it, I just didn't find it because it's hidding in that grouping thing.

Quoted 11 lines
Quoted 6 lines
Quoted 1 line

+452 common umcg_swap sys_umcg_swap

You're presenting it like a pure optimization, but IIRC this is what enables us to frob the scheduler state to ensure the whole thing is seen (to the rest of the system) as the M server tasks, instead of the constellation of N+M worker and server tasks.

Yes, you recall it correctly.

Quoted 1 line

Also, you're not doing any of the frobbing required.

Quoted 7 lines

This is because I consider the frobbing a (very) nice to have rather than a required feature, and so I am hoping to argue about how to properly do it in later patchsets. This whole thing (UMCG) will be extremely useful even without runtime accounting hacking and whatnot, and so I hope to have everything else settled and tested and merged before we spend another several weeks/months trying to make the frobbing perfect.

Sure, not saying you need the frobbing from the get-go, but it's a much stronger argument for having the API in the first place. So mentioning this property (along with a TODO) is a stronger justification.

This goes to *why again. It's fairly easy to see what from the code, but code rarely explains why.

That said; if we do: @next_pid, we might be able to do away with this. A !RUNING transition will attempt to wake-and-switch to @next_tid. This is BLOCKED from syscall or explicit using umcg_wait().

Quoted 7 lines
Quoted 4 lines
Quoted 1 line

+455 common umcg_poll_worker sys_umcg_poll_worker

Shouldn't this be called idle or something, instead of poll, the whole point of having this syscall is to that you can indeed go idle.

That's another way of looking at it. Yes, this means the server idles until a worker becomes available. How would you call it? umcg_idle()?

I'm trying to digest the thing; it's doing *far* more than just idling, but yes, sys_umcg_idle() or something.

Quoted 8 lines
Quoted 2 lines

This I'm confused about again.. there is no fundamental difference between a worker or server, they're all the same.

I don't see it this way. A server runs (on CPU) by itself and blocks when there is a worker attached; a worker runs (on CPU) only when it has a (blocked) server attached to it and, when the worker blocks, its server detaches and runs another worker. So workers and servers are the opposite of each other.

So I was viewing the server more like the idle thread, its 'work' is idle, which is always available.

Quoted 12 lines
Quoted 8 lines

Review

Quoted 6 lines

+ */

(quoted diff) +5 -0
+#define UMCG_TASK_NONE                       0
+/* UMCG server states. */
+#define UMCG_TASK_POLLING            1
+#define UMCG_TASK_SERVING            2
+#define UMCG_TASK_PROCESSING         3

I get POLLING, although per the above, this probably wants to be IDLE.

Ack.

Quoted 1 line
Quoted 8 lines
Quoted 2 lines

What are the other two again? That is, along with the diagram, each state wants a description.

SERVING: the server is blocked, its attached worker is running
PROCESSING: the server is running (= processing a block or wake event), has no running worker attached

Both of these states are different from POLLING/IDLE and from each other.

But if we view the server as the worker with work 'idle', then serving becomes RUNNABLE and PROCESSING becomes RUNNING, right?

And sys_run_worker(next); becomes:

	self->state = RUNNABLE;
	self->next_tid = next;
	sys_umcg_wait();

The question is if we need an explicit IDLE state along with calling sys_umcg_idle(). I can't seem to make up my mind on that.

Quoted 11 lines
Quoted 10 lines

Review

Quoted 5 lines
(quoted diff) +5 -0
+/* UMCG worker states. */
+#define UMCG_TASK_RUNNABLE           4
+#define UMCG_TASK_RUNNING            5
+#define UMCG_TASK_BLOCKED            6
+#define UMCG_TASK_UNBLOCKED          7

Weird order, also I can't remember why we need the UNBLOCKED, isn't that the same as the RUNNABLE, or did we want to distinguish the state were we're no longer BLOCKED but the user scheduler hasn't yet put us on it's ready queue (IOW, we're on the runnable_ptr list, see below).

Quoted 3 lines

Yes, UNBLOCKED it a transitory state meaning the worker's blocking operation has completed, but the wake event hasn't been delivered to the userspace yet (and so the worker it not yet RUNNABLE)

So if I understand the proposal correctly the only possible option is something like:

	for (;;) {
		next = user_sched_pick();
		if (next) {
			sys_umcg_run(next);
			continue;
		}

		sys_umcg_poll(&next);
		if (next) {
			next->state = RUNNABLE;
			user_sched_enqueue(next);
		}
	}

This seems incapable of implementing generic scheduling policies and has a hard-coded FIFO policy.

The poll() thing cannot differentiate between: 'find new task' and 'go idle'. So you cannot keep running it until all new tasks are found.

But you basically get to do a syscall to discover every new task, while the other proposal gets you a user visible list of new tasks, no syscalls needed at all.

It's also not quite clear to me what you do about RUNNING->BLOCKED, how does the userspace scheduler know to dequeue a task?

My proposal gets you something like:

	for (;;) {
		self->state = RUNNABLE;
		self->next_tid = 0; // next == self == server -> idle

		p = xchg(self->blocked_ptr, NULL);
		while (p) {
			n = new->blocked_ptr;
			user_sched_dequeue(p);
			p = n;
		}

		// Worker can have unblocked again before we got here,
		// hence we need to process blocked before runnable.
		// Worker cannot have blocked again, since we didn't
		// know it was runnable, hence it cannot have ran again.

		p = xchg(self->runnable_ptr, NULL);
		while (p) {
			n = new->runnable_ptr;
			user_sched_enqeue(p);
			p = n;
		}

		n = user_sched_pick();
		if (n)
			self->next_tid = n->tid;

		// new self->*_ptr state will have changed self->state
		// to RUNNING and we'll not switch to ->next.

		sys_umcg_wait();

		// self->state == RUNNING
	}

This allows you to implement arbitrary policies and instantly works with preemption once we implement that. Preemption would put the running worker in RUNNABLE, mark the server RUNNING and switch.

Hmm, looking at it written out like that, we don't need sys_umcg_wake(), sys_umcg_swap() at all.

Anyway, and this is how I got here, UNBLOCKED is not required because we cannot run it before we've observed it RUNNABLE. Yes the state exists where it's no longer BLOCKED, and it's not yet on the runqueue, but when we don't know it's RUNNABLE we'll not pick it, so its moot.

Quoted 18 lines
Quoted 9 lines

So last time I really looked at this it looked something like this:

struct umcg_task {

        u32     umcg_status;            /* r/w */
        u32     umcg_server_tid;        /* r   */
        u32     umcg_next_tid;          /* r   */
        u32     __hole__;
        u64     umcg_blocked_ptr;       /*   w */
        u64     umcg_runnable_ptr;      /*   w */
Quoted 4 lines

};

(where r/w is from the kernel's pov)
(also see uapi/linux/rseq.h's ptr magic)

I tried doing it this way, i.e. to only have only userspace struct added (without kernel-only data), and I found it really cumbersome and inconvenient and much slower than the proposed implementation.

Quoted 5 lines

For example, when a worker blocks, it seems working with "struct task_struct *peer" to get to the worker's server is easy and straightforward; reading server_tid from userspace, then looking up the task and only then doing what is needed (change state and wakeup) is ... unnecessary?

Is find_task_by_vpid() really that slow? The advantage of having it in userspace is that you can very easily change 'affinities' of the workers. You can simply set ->server_tid and it goes elsewhere.

Quoted 3 lines

Also validating things becomes really important but difficult (what if the user put something weird in umcg_server_tid? or the ptr fields?).

If find_task_by_vpid() returns NULL, we return -ESRCH. If the user cmpxchg returns -EFAULT we pass along the message. If userspace put a valid but crap pointer in it, userspace gets to keep the pieces.

Quoted 4 lines

In my proposed implementation only the state is user-writable, and it does not really affect most of the kernel-side work.

Why do you think everything should be in the userspace memory?

Because then we avoid all the kernel state and userspace gets to have all the state without endless syscalls.

Note that with the proposal, per the above, we're at:

enum {
UMCG_STATE_RUNNING,
UMCG_STATE_RUNABLE,
UMCG_STATE_BLOCKED,
};

struct umcg_task {

        u32     umcg_status;            /* r/w */
        u32     umcg_server_tid;        /* r   */
        u32     umcg_next_tid;          /* r   */
        u32     umcg_tid;		/* r   */
        u64     umcg_blocked_ptr;       /*   w */
        u64     umcg_runnable_ptr;      /*   w */

};

/*
* Register current's UMCG state.
*/
sys_umcg_register(struct umcg_task *self, unsigned int flags);

/*
* Just 'cause.
*/
sys_umcg_unregister(struct umcg_task *self)

/*
* UMCG context switch.
*/
sys_umcg_wait(u64 time, unsigned int flags)

{
	unsigned int state = RUNNABLE;
	unsigned int tid;

	if (self->state == RUNNING)
		return;

	tid = self->next_tid;
	if (!tid)
		tid = self->server_tid;

	if (tid == self->server_tid && tid == self->tid)
		return umcg_idle(time, flags);

	next = find_process_by_pid(tid);
	if (!next) {
		return -ESRCH;

	ret = user_try_cmpxchg(next->umcg->state, &state, RUNNING);
	if (!ret)
		ret = -EBUSY;
	if (ret < 0)
		return ret;

	return umcg_switch_to(next);
}

With this (and the BLOCKING bits outlined last time) we can implement full N:1 userspace scheduling (UP).

( Note that so far we assume all UMCG workers share the same address
space, otherwise the user_try_cmpxchg() doesn't work. )

And I _think_ you can do the whole SMP thing in userspace as well, just have the servers share queue state and reassign ->server_tid where needed. No additional syscalls required.

Quoted 5 lines

All of the code above assumes userspace-only data. I did not look into every detail of your suggestions because I want to make sure we first agree on this: do we keep every bit of information in the userspace (other than "struct umcg_task __user *" pointer in task_struct) or do we have some kernel-only details as well?

Most of the kernel state you seem to have implemented seems to limit flexibility / implement specific policy. All because apparently find_task_by_vpid() is considered expensive?

You've enangled the whole BLOCKING stuff with the SMP stuff. And by putting that state in the kernel you've limited flexibility.

Also, if you don't have kernel state it can't go out of sync and cause problems.

Quoted 8 lines

So IMPORTANT QUESTION #2: why would we want to keep __everything__ in the userspace memory? I understand that CRIU would like this, but given that the implementation would at a minimum have to

1. read a umcg_server_ptr (points to the server's umcg_task)
2. get the server tid out of it (presumably by reading a field from the server's umcg_task; what if the tid is wrong?)
3. do a tid lookup

So if we leave SMP as an exercise in scheduling queue management, And implement the above, then you need:

- copy_from_user()/get_user() for the first 4 words
- find_task_by_vpid()

that gets you a task pointer, then we get to update a blocked_ptr.

If anything goes wrong, simply return an error and let userspace sort it out.

Quoted 14 lines

to get a task_struct pointer, it will be slower; I am also not sure it call be done safely at all: with kernel-side data and I can do rcu locking, task locking, etc. to ensure that the value I got does not change while I'm working with it; with userspace data, a lot of races will have to be specially coded for that can be easily handled by kernel-side rcu locks or spin locks... Maybe this is just my ignorance showing, and indeed things can be done simply and easily with userspace-only data, but I am not sure how.

A common example:

- worker W1 with server S1 calls umcg_wait()
- worker W2 with server S2 calls umcg_swap(W1)

Quoted 12 lines

If due to preemption and other concurrency weirdness the two syscalls above race with each other, each trying to change the server assigned to W1. I can easily handle the race by doing kernel-side locking; without kernel-side locking (cannot do rcu locks and/or spin locks while accessing userspace data) I am not sure how to handle the race. Maybe it is possible with careful atomic writes to states and looping to handle this specific race (what if the userspace antagonistically writes to the same location? will it force the syscall to spin indefinitely?); but with proper locking many potential races can be handled; with atomic ops and looping it is more difficult... Will we have to add a lock to struct umcg_task? And acquire it from the kernel side? And worry about spinning forever?

What would you want locking for? I really don't see a problem here.

Both blocked_ptr and runnable_ptr are cmpxchg single-linked-lists. Yes they can spin a little, but that's not a new problem, futex has all that.

And ->state only needs single cmpxchg ops, no loops, either we got the wakeup, or we didn't. The rest is done with memory ordering:

	server				worker

	self->state = RUNNABLE;		self->state = BLOCKED;

	head = xchg(list, NULL)		add_to_list(self, &server->blocked_ptr);

					if (try_cmpxchg_user(&server->umcg->state, RUNNABLE, RUNNING) > 0)
	sys_umcg_wait()				wake_up_process(server);

Either server sees the add, or we see it's RUNNABLE and wake it up (or both).

If anything on the BLOCKED side goes wrong (bad pointers, whatever), have it segfault.

<edit> Ooh, I forgot you can't just go wake the server when it's running something else... so that does indeed need more states/complication, the ordering argument stands though. We'll need something like self->current_tid or somesuch </edit>

Quoted 6 lines
Quoted 4 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+SYSCALL_DEFINE2(umcg_wait, u32, flags,
+             const struct __kernel_timespec __user *, timeout)

I despise timespec, tglx?

What are the alternatives? I just picked what the futex code uses.

u64 nanoseconds. Not sure tglx really wants to do that though, but still, timespec is a terrible thing.

Quoted 5 lines

In summary, two IMPORTANT QUESTIONS:

1. thin vs fat syscalls: can we push some code/logic to the userspace (state changes, looping/retries), or do we insist on syscalls handling everything?

Well, the way I see it it's a trade of what is handled where. I get a smaller API (although I'm sure I've forgotten something trivial again that wrecks everything <edit> I did :/ </edit>) and userspace gets to deal with all of SMP and scheduling policies.

You hard-coded a global-fifo and had a enormous number of syscalls and needed to wrap every syscall invocation in order to fix up the return.

Quoted 4 lines

Please have in mind that even if we choose the second approach (fat syscalls), the userspace will most likely still have to do everything it does under the first option just to handle signals/interrupts (i.e. unscheduled wakeups);

IIRC sigreturn goes back into the kernel and we can resume blocking there.

Quoted 3 lines

2. kernel-side data vs userspace-only: can we avoid having kernel-side data? More specifically, what alternatives to rcu_read_lock and/or task_lock are available when working with userspace data?

What would you want locked and why?

Anyway, this email is far too long again (basically took me all day :/), hope it helps a bit. Thomas is stuck fixing XSAVE disasters, but I'll ask him to chime in once that's done.

#38 lore raw

On Thu, Jun 10, 2021 at 11:02 AM Peter Zijlstra <[email protected]> wrote:

Thanks a lot for the detailed reply!

I'll try again the data-in-userspace-only route (= everything in TLS):
if you are right and everything can be done without needing to lock anything - great!

The last time I tried it I could not do it properly/safely, though, because I could not fix races without rcu and/or spin locking stuff, which was impossible with data in the userspace. I don't remember the specifics now, though...

Thanks,
Peter

Quoted 616 lines · Peter Oskolkov
Quoted 6 lines · Peter Zijlstra

Finally, a high-level review - thanks a lot, Peter! My comments below, and two high-level "important questions" at the end of my reply (with some less important questions here and there).

Quoted 7 lines

[...]

Quoted 2 lines

You present an API without explaining, *at*all*, how it's supposed to be used and I can't seem to figure it out from the implementation either :/

I tried to explain it in the doc patch that I followed up with:
https://lore.kernel.org/patchwork/cover/1433967/#1632328

Urgh, you write RST :-( That sorta helps, but I'm still unclear on a number of things, more below.

Quoted 4 lines

Or do you mean it more narrowly, i.e. I do not explain syscalls in detail? This assessment I agree with - my approach was/is to finalize the userpace API (libumcg) first, and make the userspace vs kernel decisions later.

Yeah, I couldn't figure out how to use the syscalls and thus how to interpret their implementation. A little more in the way of comments would've been helpful.

Quoted 4 lines

For example, you wonder why there is no looping in umcg_wait (do_wait). This is because the looping happens in the userspace in libumcg. My overall approach was to make the syscalls as simple as possible and push extra logic to the userspace.

So a simple comment on the syscall that says:

Userspace is expected to do:

        do {
                sys_umcg_wait();
        } while (smp_load_acquire(&umcg_task->state) != RUNNING);

would've made all the difference. It provides context.

Quoted 4 lines

It seems that this approach is not resonating with kernel developers/maintainers - you are the third person asking why there is no looping in sys_umcg_wait, despite the fact that I explicitly mentioned pushing it out to the userspace.

We've been trained, through years of 'funny' bugs, to go 'BUG BUG BUG' when schedule() is not in a loop. And pushing the loop to userspace has me all on edge for being 'weird'.

Quoted 9 lines

Let me try to make my case once more here.

umcg_wait/umcg_wake: the RUNNABLE/RUNNING state changes, checks, and looping happen in the userspace (libumcg - see umcg_wait/umcg_wake in patch 5 here: https://lore.kernel.org/patchwork/patch/1433971/), while the syscalls simply sleep/wake. I find doing it in the userspace is much simpler and easier than in the kernel, as state reads and writes are just atomic memory accesses; in the kernel it becomes much more difficult - rcu locked sections, tasks locked, etc.

Small difficulties as far as things go I think. The worst part is having to do arch asm for the userspace cmpxchg. Luckily we can crib/share with futex there.

Quoted 6 lines

On the other hand I agree that having syscalls more logically complete, in the sense that they do not require much hand-holding and retries from the userspace, is probably better from the API design perspective. My worry here is that state validation and retries in the userspace are unavoidable, and so going the usual way we will end up with retry loops both in the kernel and in the userspace.

Can you expand on where you'd see the need for userspace to retry?

The canonical case in my mind is where a task, that's been BLOCKED in kernelspace transitions to UNBLOCK/RUNNABLE in return-to-user and waits for RUNNING.

Once it gets RUNNING, userspace can assume it can just go. It will never have to re-check, because there's no way RUNNING can go away again. The only way for RUNNING to become anything else, is setting it yourself and/or doing a syscall.

Also, by having the BLOCKED thing block properly in return-to-user, you don't have to wrap *all* the userspace syscall invocations. If you let it return early, you get to wrap syscalls, which is both fragile and bad for performance.

Quoted 7 lines

So I pose this IMPORTANT QUESTION #1 to you that I hope to get a clear answer to: it is strongly preferable to have syscalls be "logically complete" in the sense that they retry things internally, and in generally try to cover all possible corner cases; or, alternatively, is it OK to make syscalls lightweight but "logically incomplete", and have the accompanied userspace wrappers do all of the heavy lifting
re: state changes/validation, retries, etc.?

Intuitively I'd go with complete. I'd have never even considered the incomplete option. But let me try and get my head around the incomplete cases.

Oooh, I found the BLOCKED stuff, you hid it inside the grouping patch, that makes no sense :-( Reason I'm looking is that I don't see how you get around the blocked and runnable lists. You have to tell userspace about them.

FWIW: I think you placed umcg_on_block() wrong, it needs to be before the terrible PI thing. Also, like said, please avoid yet another branch here by using PF_UMCG_WORKER.

Quoted 4 lines

I see two additional benefits of thin/lightweight syscalls:
- reading userspace state is needed much less often (e.g. my umcg_wait and umcg_wake syscalls do not access userspace data at all - also see my "second important question" below)

It is also broken I think, best I can make of it is somsething like this:

    WAIT                                                WAKE

    if (smp_load_acquire(&state) == RUNNING)
        return;

                                                        state = RUNNING;


    do {
      sys_umcg_wait()
      {
        in_wait = true;
                                                        sys_umcg_wake()
                                                        {
                                                          if (in_wait)
                                                            wake_up_process()
                                                        }
        set_current_state(INTERRUPTIBLE);
        schedule();
        in_wait = false;
      }
    } while (smp_load_acquire(&state) != RUNNING);

missed wakeup, 'forever' stuck. You have to check your blocking condition between setting state and scheduling. And if you do that, you have a 'fat' syscall again.

Quoted 3 lines

- looping in the kernel, combined with reading/writing to userspace memory, can easily lead to spinning in the kernel (e.g. trying to atomically change a variable and looping until succeeding)

I don't imagine spinning in kernel or userspace matters.

Quoted 8 lines
Quoted 2 lines

Also, do we really need unregister over just letting a task exit? Is there a sane use-case where task goes in and out of service?

I do not know of a specific use case here. On the other hand, I do not know of a specific use case to unregister RSEQ, but the capability is there. Maybe the assumption is that the userspace memory passed to the kernel in register() may be freed before the task exits, and so there should be a way to tell the kernel to no longer use it?

Fair enough I suppose.

Quoted 10 lines
Quoted 10 lines
Quoted 3 lines
+450  common  umcg_wait               sys_umcg_wait
+451  common  umcg_wake               sys_umcg_wake

Right, except I'm confused by the proposed implementation. I thought the whole point was to let UMCG tasks block in kernel, at which point we'd change their state to BLOCKED and have userspace select another task to run. Such BLOCKED tasks would then also be captured before they return to userspace, i.e. the whole admission scheduler thing.

Quoted 7 lines
Quoted 2 lines

I don't see any of that in these patches. So what are they actually implementing? I can't find enough clues to tell :-(

As I mentioned above, state changes are done in libumcg in userspace
here: https://lore.kernel.org/patchwork/cover/1433967/#1632328

If you insist this logic should live in the kernel, I'll do it (grudgingly).

So you have some of it, I just didn't find it because it's hidding in that grouping thing.

Quoted 11 lines
Quoted 6 lines
Quoted 1 line

+452 common umcg_swap sys_umcg_swap

You're presenting it like a pure optimization, but IIRC this is what enables us to frob the scheduler state to ensure the whole thing is seen (to the rest of the system) as the M server tasks, instead of the constellation of N+M worker and server tasks.

Yes, you recall it correctly.

Quoted 1 line

Also, you're not doing any of the frobbing required.

Quoted 7 lines

This is because I consider the frobbing a (very) nice to have rather than a required feature, and so I am hoping to argue about how to properly do it in later patchsets. This whole thing (UMCG) will be extremely useful even without runtime accounting hacking and whatnot, and so I hope to have everything else settled and tested and merged before we spend another several weeks/months trying to make the frobbing perfect.

Sure, not saying you need the frobbing from the get-go, but it's a much stronger argument for having the API in the first place. So mentioning this property (along with a TODO) is a stronger justification.

This goes to *why again. It's fairly easy to see what from the code, but code rarely explains why.

That said; if we do: @next_pid, we might be able to do away with this. A !RUNING transition will attempt to wake-and-switch to @next_tid. This is BLOCKED from syscall or explicit using umcg_wait().

Quoted 7 lines
Quoted 4 lines
Quoted 1 line

+455 common umcg_poll_worker sys_umcg_poll_worker

Shouldn't this be called idle or something, instead of poll, the whole point of having this syscall is to that you can indeed go idle.

That's another way of looking at it. Yes, this means the server idles until a worker becomes available. How would you call it? umcg_idle()?

I'm trying to digest the thing; it's doing *far* more than just idling, but yes, sys_umcg_idle() or something.

Quoted 8 lines
Quoted 2 lines

This I'm confused about again.. there is no fundamental difference between a worker or server, they're all the same.

I don't see it this way. A server runs (on CPU) by itself and blocks when there is a worker attached; a worker runs (on CPU) only when it has a (blocked) server attached to it and, when the worker blocks, its server detaches and runs another worker. So workers and servers are the opposite of each other.

So I was viewing the server more like the idle thread, its 'work' is idle, which is always available.

Quoted 12 lines
Quoted 8 lines

Review

Quoted 6 lines

+ */

(quoted diff) +5 -0
+#define UMCG_TASK_NONE                       0
+/* UMCG server states. */
+#define UMCG_TASK_POLLING            1
+#define UMCG_TASK_SERVING            2
+#define UMCG_TASK_PROCESSING         3

I get POLLING, although per the above, this probably wants to be IDLE.

Ack.

Quoted 1 line
Quoted 8 lines
Quoted 2 lines

What are the other two again? That is, along with the diagram, each state wants a description.

SERVING: the server is blocked, its attached worker is running
PROCESSING: the server is running (= processing a block or wake event), has no running worker attached

Both of these states are different from POLLING/IDLE and from each other.

But if we view the server as the worker with work 'idle', then serving becomes RUNNABLE and PROCESSING becomes RUNNING, right?

And sys_run_worker(next); becomes:

        self->state = RUNNABLE;
        self->next_tid = next;
        sys_umcg_wait();

The question is if we need an explicit IDLE state along with calling sys_umcg_idle(). I can't seem to make up my mind on that.

Quoted 11 lines
Quoted 10 lines

Review

Quoted 5 lines
(quoted diff) +5 -0
+/* UMCG worker states. */
+#define UMCG_TASK_RUNNABLE           4
+#define UMCG_TASK_RUNNING            5
+#define UMCG_TASK_BLOCKED            6
+#define UMCG_TASK_UNBLOCKED          7

Weird order, also I can't remember why we need the UNBLOCKED, isn't that the same as the RUNNABLE, or did we want to distinguish the state were we're no longer BLOCKED but the user scheduler hasn't yet put us on it's ready queue (IOW, we're on the runnable_ptr list, see below).

Quoted 3 lines

Yes, UNBLOCKED it a transitory state meaning the worker's blocking operation has completed, but the wake event hasn't been delivered to the userspace yet (and so the worker it not yet RUNNABLE)

So if I understand the proposal correctly the only possible option is something like:

        for (;;) {
                next = user_sched_pick();
                if (next) {
                        sys_umcg_run(next);
                        continue;
                }

                sys_umcg_poll(&next);
                if (next) {
                        next->state = RUNNABLE;
                        user_sched_enqueue(next);
                }
        }

This seems incapable of implementing generic scheduling policies and has a hard-coded FIFO policy.

The poll() thing cannot differentiate between: 'find new task' and 'go idle'. So you cannot keep running it until all new tasks are found.

But you basically get to do a syscall to discover every new task, while the other proposal gets you a user visible list of new tasks, no syscalls needed at all.

It's also not quite clear to me what you do about RUNNING->BLOCKED, how does the userspace scheduler know to dequeue a task?

My proposal gets you something like:

        for (;;) {
                self->state = RUNNABLE;
                self->next_tid = 0; // next == self == server -> idle

                p = xchg(self->blocked_ptr, NULL);
                while (p) {
                        n = new->blocked_ptr;
                        user_sched_dequeue(p);
                        p = n;
                }

                // Worker can have unblocked again before we got here,
                // hence we need to process blocked before runnable.
                // Worker cannot have blocked again, since we didn't
                // know it was runnable, hence it cannot have ran again.

                p = xchg(self->runnable_ptr, NULL);
                while (p) {
                        n = new->runnable_ptr;
                        user_sched_enqeue(p);
                        p = n;
                }

                n = user_sched_pick();
                if (n)
                        self->next_tid = n->tid;

                // new self->*_ptr state will have changed self->state
                // to RUNNING and we'll not switch to ->next.

                sys_umcg_wait();

                // self->state == RUNNING
        }

This allows you to implement arbitrary policies and instantly works with preemption once we implement that. Preemption would put the running worker in RUNNABLE, mark the server RUNNING and switch.

Hmm, looking at it written out like that, we don't need sys_umcg_wake(), sys_umcg_swap() at all.

Anyway, and this is how I got here, UNBLOCKED is not required because we cannot run it before we've observed it RUNNABLE. Yes the state exists where it's no longer BLOCKED, and it's not yet on the runqueue, but when we don't know it's RUNNABLE we'll not pick it, so its moot.

Quoted 18 lines
Quoted 9 lines

So last time I really looked at this it looked something like this:

struct umcg_task {

        u32     umcg_status;            /* r/w */
        u32     umcg_server_tid;        /* r   */
        u32     umcg_next_tid;          /* r   */
        u32     __hole__;
        u64     umcg_blocked_ptr;       /*   w */
        u64     umcg_runnable_ptr;      /*   w */
Quoted 4 lines

};

(where r/w is from the kernel's pov)
(also see uapi/linux/rseq.h's ptr magic)

I tried doing it this way, i.e. to only have only userspace struct added (without kernel-only data), and I found it really cumbersome and inconvenient and much slower than the proposed implementation.

Quoted 5 lines

For example, when a worker blocks, it seems working with "struct task_struct *peer" to get to the worker's server is easy and straightforward; reading server_tid from userspace, then looking up the task and only then doing what is needed (change state and wakeup) is ... unnecessary?

Is find_task_by_vpid() really that slow? The advantage of having it in userspace is that you can very easily change 'affinities' of the workers. You can simply set ->server_tid and it goes elsewhere.

Quoted 3 lines

Also validating things becomes really important but difficult (what if the user put something weird in umcg_server_tid? or the ptr fields?).

If find_task_by_vpid() returns NULL, we return -ESRCH. If the user cmpxchg returns -EFAULT we pass along the message. If userspace put a valid but crap pointer in it, userspace gets to keep the pieces.

Quoted 4 lines

In my proposed implementation only the state is user-writable, and it does not really affect most of the kernel-side work.

Why do you think everything should be in the userspace memory?

Because then we avoid all the kernel state and userspace gets to have all the state without endless syscalls.

Note that with the proposal, per the above, we're at:

enum {
UMCG_STATE_RUNNING,
UMCG_STATE_RUNABLE,
UMCG_STATE_BLOCKED,
};

struct umcg_task {

        u32     umcg_status;            /* r/w */
        u32     umcg_server_tid;        /* r   */
        u32     umcg_next_tid;          /* r   */
        u32     umcg_tid;               /* r   */
        u64     umcg_blocked_ptr;       /*   w */
        u64     umcg_runnable_ptr;      /*   w */

};

/*
* Register current's UMCG state.
*/
sys_umcg_register(struct umcg_task *self, unsigned int flags);

/*
* Just 'cause.
*/
sys_umcg_unregister(struct umcg_task *self)

/*
* UMCG context switch.
*/
sys_umcg_wait(u64 time, unsigned int flags)

{
        unsigned int state = RUNNABLE;
        unsigned int tid;

        if (self->state == RUNNING)
                return;

        tid = self->next_tid;
        if (!tid)
                tid = self->server_tid;

        if (tid == self->server_tid && tid == self->tid)
                return umcg_idle(time, flags);

        next = find_process_by_pid(tid);
        if (!next) {
                return -ESRCH;

        ret = user_try_cmpxchg(next->umcg->state, &state, RUNNING);
        if (!ret)
                ret = -EBUSY;
        if (ret < 0)
                return ret;

        return umcg_switch_to(next);
}

With this (and the BLOCKING bits outlined last time) we can implement full N:1 userspace scheduling (UP).

( Note that so far we assume all UMCG workers share the same address
space, otherwise the user_try_cmpxchg() doesn't work. )

And I _think_ you can do the whole SMP thing in userspace as well, just have the servers share queue state and reassign ->server_tid where needed. No additional syscalls required.

Quoted 5 lines

All of the code above assumes userspace-only data. I did not look into every detail of your suggestions because I want to make sure we first agree on this: do we keep every bit of information in the userspace (other than "struct umcg_task __user *" pointer in task_struct) or do we have some kernel-only details as well?

Most of the kernel state you seem to have implemented seems to limit flexibility / implement specific policy. All because apparently find_task_by_vpid() is considered expensive?

You've enangled the whole BLOCKING stuff with the SMP stuff. And by putting that state in the kernel you've limited flexibility.

Also, if you don't have kernel state it can't go out of sync and cause problems.

Quoted 8 lines

So IMPORTANT QUESTION #2: why would we want to keep __everything__ in the userspace memory? I understand that CRIU would like this, but given that the implementation would at a minimum have to

1. read a umcg_server_ptr (points to the server's umcg_task)
2. get the server tid out of it (presumably by reading a field from the server's umcg_task; what if the tid is wrong?)
3. do a tid lookup

So if we leave SMP as an exercise in scheduling queue management, And implement the above, then you need:

- copy_from_user()/get_user() for the first 4 words
- find_task_by_vpid()

that gets you a task pointer, then we get to update a blocked_ptr.

If anything goes wrong, simply return an error and let userspace sort it out.

Quoted 14 lines

to get a task_struct pointer, it will be slower; I am also not sure it call be done safely at all: with kernel-side data and I can do rcu locking, task locking, etc. to ensure that the value I got does not change while I'm working with it; with userspace data, a lot of races will have to be specially coded for that can be easily handled by kernel-side rcu locks or spin locks... Maybe this is just my ignorance showing, and indeed things can be done simply and easily with userspace-only data, but I am not sure how.

A common example:

- worker W1 with server S1 calls umcg_wait()
- worker W2 with server S2 calls umcg_swap(W1)

Quoted 12 lines

If due to preemption and other concurrency weirdness the two syscalls above race with each other, each trying to change the server assigned to W1. I can easily handle the race by doing kernel-side locking; without kernel-side locking (cannot do rcu locks and/or spin locks while accessing userspace data) I am not sure how to handle the race. Maybe it is possible with careful atomic writes to states and looping to handle this specific race (what if the userspace antagonistically writes to the same location? will it force the syscall to spin indefinitely?); but with proper locking many potential races can be handled; with atomic ops and looping it is more difficult... Will we have to add a lock to struct umcg_task? And acquire it from the kernel side? And worry about spinning forever?

What would you want locking for? I really don't see a problem here.

Both blocked_ptr and runnable_ptr are cmpxchg single-linked-lists. Yes they can spin a little, but that's not a new problem, futex has all that.

And ->state only needs single cmpxchg ops, no loops, either we got the wakeup, or we didn't. The rest is done with memory ordering:

        server                          worker

        self->state = RUNNABLE;         self->state = BLOCKED;

        head = xchg(list, NULL)         add_to_list(self, &server->blocked_ptr);

                                        if (try_cmpxchg_user(&server->umcg->state, RUNNABLE, RUNNING) > 0)
        sys_umcg_wait()                         wake_up_process(server);

Either server sees the add, or we see it's RUNNABLE and wake it up (or both).

If anything on the BLOCKED side goes wrong (bad pointers, whatever), have it segfault.

<edit> Ooh, I forgot you can't just go wake the server when it's running something else... so that does indeed need more states/complication, the ordering argument stands though. We'll need something like self->current_tid or somesuch </edit>

Quoted 6 lines
Quoted 4 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+SYSCALL_DEFINE2(umcg_wait, u32, flags,
+             const struct __kernel_timespec __user *, timeout)

I despise timespec, tglx?

What are the alternatives? I just picked what the futex code uses.

u64 nanoseconds. Not sure tglx really wants to do that though, but still, timespec is a terrible thing.

Quoted 5 lines

In summary, two IMPORTANT QUESTIONS:

1. thin vs fat syscalls: can we push some code/logic to the userspace (state changes, looping/retries), or do we insist on syscalls handling everything?

Well, the way I see it it's a trade of what is handled where. I get a smaller API (although I'm sure I've forgotten something trivial again that wrecks everything <edit> I did :/ </edit>) and userspace gets to deal with all of SMP and scheduling policies.

You hard-coded a global-fifo and had a enormous number of syscalls and needed to wrap every syscall invocation in order to fix up the return.

Quoted 4 lines

Please have in mind that even if we choose the second approach (fat syscalls), the userspace will most likely still have to do everything it does under the first option just to handle signals/interrupts (i.e. unscheduled wakeups);

IIRC sigreturn goes back into the kernel and we can resume blocking there.

Quoted 3 lines

2. kernel-side data vs userspace-only: can we avoid having kernel-side data? More specifically, what alternatives to rcu_read_lock and/or task_lock are available when working with userspace data?

What would you want locked and why?

Anyway, this email is far too long again (basically took me all day :/), hope it helps a bit. Thomas is stuck fixing XSAVE disasters, but I'll ask him to chime in once that's done.

#39 lore raw
In reply to Peter Zijlstra

Hi,
I wanted to way-in on this. I am one of the main developer's on the Cforall programming language (https://cforall.uwaterloo.ca), which implements its own M:N user-threading runtime. I want to state that this RFC is an interesting feature, which we would be able to take advantage of immediately, assuming performance and flexibility closely match state-of-the-art implementations.

Precisely, we would benefit from two aspects of User Managed Control Groups:

1. user-level threads would become regular pthreads, so that gdb, valgrind, ptrace and TLS works normally, etc.

2. The user-space scheduler can react on user-threads blocking in the kernel.

However, we would need to look at performance issues like thread creation and context switch to know if your scheme is performant with user-level threading. We are also conscious about use cases that involve a very high (100Ks to 1Ms) number of concurrent sessions and thus threads.

Note, our team published a comprehensive look at M:N threading in ACM Sigmetrics 2020: https://doi.org/10.1145/3379483, which highlights the expected performance of M:N threading, and another look at high-performance control flow in SP&E 2021: https://onlinelibrary.wiley.com/doi/10.1002/spe.2925

 > > Yes, UNBLOCKED it a transitory state meaning the worker's blocking > > operation has completed, but the wake event hasn't been delivered to > > the userspace yet (and so the worker it not yet RUNNABLE) >
 > So if I understand the proposal correctly the only possible option is > something like:
 >
 >     for (;;) {
 >         next = user_sched_pick();
 >         if (next) {
 >             sys_umcg_run(next);
 >             continue;
 >         }
 >
 >         sys_umcg_poll(&next);
 >         if (next) {
 >             next->state = RUNNABLE;
 >             user_sched_enqueue(next);
 >         }
 >     }
 >
 > This seems incapable of implementing generic scheduling policies and has > a hard-coded FIFO policy.
 >
 > The poll() thing cannot differentiate between: 'find new task' and 'go > idle'. So you cannot keep running it until all new tasks are found. >
 > But you basically get to do a syscall to discover every new task, while > the other proposal gets you a user visible list of new tasks, no > syscalls needed at all.

I agree strongly with this comment, sys_umcg_poll() does not appear to be flexible enough for generic policies. I also suspect it would become a bottleneck in any SMP scheduler due to this central serial data-structure.

 > But you basically get to do a syscall to discover every new task, while > the other proposal gets you a user visible list of new tasks, no > syscalls needed at all.
 >
 > It's also not quite clear to me what you do about RUNNING->BLOCKED, how > does the userspace scheduler know to dequeue a task?

In the schedulers we have implemented, threads are dequeued *before* being run. That is, the head of the queue is not the currently running thread.

If the currently running threads need to be in the scheduler data-structure, I believe it can be dequeued immediately after sys_umcg_run() has returned. More on this below.

 > My proposal gets you something like:
 >
 > [...]
 >
 > struct umcg_task {
 >    u32 umcg_status;            /* r/w */
 >    u32 umcg_server_tid;        /* r   */
 >    u32 umcg_next_tid;          /* r   */
 >    u32 umcg_tid;               /* r   */
 >    u64 umcg_blocked_ptr;       /*   w */
 >    u64 umcg_runnable_ptr;      /*   w */
 > };

I believe this approach may work, but could you elaborate on it? I wasn't able to find a more complete description.

For example, I fail to see what purpose the umcg_blocked_ptr serves. When could it contain anything other then a single element that is already pointed to by "n" in the proposed loop? The only case I can come up with, is if a worker thread tries to context switch directly to another worker thread. But in that case, I do not know what state that second worker would need to be in for this operation to be correct. Is the objective to allow the scheduler to be invoked from worker threads?

Also, what is the purpose of umcg_status being writable by the user-space? (I'm assuming status == state)? The code in sys_umcg_wait suggests it is for managing potential out-of-order wakes and waits, but the kernel should be able to handle them already, the same way FUTEX_WAKE and FUTEX_WAIT are handled. When would these state transition not be handled by the kernel?

I would also point out that creating worker threads as regular pthreads and then converting them to worker threads sounds less then ideal. It would probably be preferable directly appended new worker threads to the umcg_runnable_ptr list without scheduling them in the kernel. It makes the placement of the umcg_task trickier but maintains a stronger M:N model.

Finally, I would recommend adding a 64-bit user pointer to umcg_task that is neither read nor written from the kernel. These kind of fields are always useful for implementers.

Thank you for your time,

Thierry

#40 lore raw
Quoted 8 lines · Thierry Delisle

Hi,
I wanted to way-in on this. I am one of the main developer's on the Cforall programming language (https://cforall.uwaterloo.ca), which implements its own
M:N user-threading runtime. I want to state that this RFC is an interesting feature, which we would be able to take advantage of immediately, assuming performance and flexibility closely match state-of-the-art implementations.

Hi Thierry,

Thank you for your message! I just posted a new version/approach:

https://lore.kernel.org/lkml/[email protected]/

Let's move the discussion to the new thread.

Thanks,
Peter

[...]