linux-security-module.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
* [PATCH RFC 00/19] exec: move sleeping work out of exec_update_lock
@ 2026-11-24 22:58 Christian Brauner
  2026-11-24 22:58 ` [PATCH RFC 01/19] proc: copy namespace link after dropping exec_update_lock Christian Brauner
                   ` (19 more replies)
  0 siblings, 20 replies; 22+ messages in thread
From: Christian Brauner @ 2026-11-24 22:58 UTC (permalink / raw)
  To: Jann Horn
  Cc: Linus Torvalds, linux-fsdevel, Arnaldo Carvalho de Melo,
	linux-perf-users, bpf, selinux, Kees Cook, linux-mm,
	linux-security-module, apparmor, David Hildenbrand,
	Christian Brauner (Amutable), stable

I've been massaging exec quite a bit to move a bunch of stuff around
and get rid of a lot of sleeping work out of that path or at least move
it out from precious locks that are used for access checks.

This is another round I plan to upstream. The gist is that we're relying
on exec_update_lock in a bunch more places now and we've been
willy-nilly moving stuff beneath that lock for a while. That's not
sustainable. We need to clean that up and really only do the absolute
minimum of work under that lock to avoid stalling tasks indefinitely
just because stalls an exec. It's also just good hygiene because it's
getting really hard to understand what that lock really protects.

I've spent some time playing with various patches. Some of them went out
independently. This is another core chunk:

* proc_ns_readlink() copies the link to userspace with the lock held.

* kcmp(KCMP_EPOLL_TFD) copies the epoll slot from userspace with the
  lock of both tasks held and then waits for the epoll mutex which
  epoll_wait() holds across a page fault.

* perf_read() and perf_ioctl() copy to and from userspace with the mutex
  of the perf context held. perf_event_exec() takes that mutex with
  exec_update_lock held.

* SELinux ignores a failing replace_fd() when it revokes inherited files
  during exec.

* A vfork() parent is woken up in exec_mmap() but a child that shares
  its signal table with the parent only gets a private one after that.

* SELinux and AppArmor revalidate the inherited files from the
  bprm_committing_creds hook, i.e., with the lock held.

* Move the time namespace switch out of the lock. It doesn't need it.

* Drop the lock right after the new credentials are committed instead of
  in setup_new_exec().

* Don't take the mmap lock of the old mm in exec_mmap().

* Look up the vma for a link in /proc/<pid>/map_files without
  exec_update_lock held.

While at it, don't take the mmap lock in exit_mm() either. It's the same
leftover. A vfork() child that exits without having exec'ed waits on the
mmap lock of the parent it has just woken up.

* A vfork() parent is woken up before the child has left the mm, in exec
  as well as in exit.

What's left under the lock that can block is the hardware breakpoint
flush in flush_thread(), perf_event_exec(), perf_event_exit_task(), the
allocation in set_cred_ucounts() and a sleepable bpf lsm program on the
bprm_committing_creds hook.

The perf ones still take the mutex of the perf context but perf_read()
and perf_ioctl() don't sleep in a page fault with it held anymore.

Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
---
Christian Brauner (19):
      proc: copy namespace link after dropping exec_update_lock
      kcmp: look up epoll target without exec_update_lock held
      perf: copy counter values after dropping ctx->mutex
      perf: copy ioctl arguments without ctx->mutex held
      selinux: close inherited files that can't be replaced
      exec: move unshare_sighand() before exec_mmap()
      selftests/exec: test exec with a task sleeping in a page fault
      selftests/exec: test exec with a shared signal table
      lsm: add security_bprm_revalidate_files()
      bpf: mark bprm_revalidate_files as sleepable
      selinux: revalidate inherited files before taking exec_update_lock
      apparmor: revalidate inherited files before taking exec_update_lock
      exec: drop exec_update_lock after the credentials are committed
      exec: switch time namespace after dropping exec_update_lock
      exec: don't take the mmap lock of the old mm
      exit: don't take the mmap lock in exit_mm()
      proc: look up map_files vma without exec_update_lock held
      vfork: wake up the parent once the child has left the mm
      selftests/exec: test when a vfork() parent is woken up

 fs/exec.c                                        |  81 ++--
 fs/proc/base.c                                   |  68 ++-
 fs/proc/namespaces.c                             |   7 +-
 include/linux/lsm_hook_defs.h                    |   1 +
 include/linux/sched/mm.h                         |   4 +-
 include/linux/security.h                         |   5 +
 kernel/bpf/bpf_lsm.c                             |   1 +
 kernel/events/core.c                             | 138 +++---
 kernel/exit.c                                    |  10 +-
 kernel/fork.c                                    |  24 +-
 kernel/kcmp.c                                    |  72 ++-
 security/apparmor/lsm.c                          |  23 +-
 security/security.c                              |  27 +-
 security/selinux/hooks.c                         |  22 +-
 tools/testing/selftests/exec/.gitignore          |   3 +
 tools/testing/selftests/exec/Makefile            |   6 +
 tools/testing/selftests/exec/config              |   3 +
 tools/testing/selftests/exec/unshare-sighand.c   | 236 ++++++++++
 tools/testing/selftests/exec/update-lock-fault.c | 547 +++++++++++++++++++++++
 tools/testing/selftests/exec/vfork-mm.c          | 363 +++++++++++++++
 20 files changed, 1480 insertions(+), 161 deletions(-)
---
base-commit: 666539eecdf4db623f5e3c3e55cf9f2dfad24aa4
change-id: 20261120-work-exec-update_lock-7f4bec04bd81


^ permalink raw reply	[flat|nested] 22+ messages in thread

* [PATCH RFC 01/19] proc: copy namespace link after dropping exec_update_lock
  2026-11-24 22:58 [PATCH RFC 00/19] exec: move sleeping work out of exec_update_lock Christian Brauner
@ 2026-11-24 22:58 ` Christian Brauner
  2026-11-24 22:58 ` [PATCH RFC 02/19] kcmp: look up epoll target without exec_update_lock held Christian Brauner
                   ` (18 subsequent siblings)
  19 siblings, 0 replies; 22+ messages in thread
From: Christian Brauner @ 2026-11-24 22:58 UTC (permalink / raw)
  To: Jann Horn
  Cc: Linus Torvalds, linux-fsdevel, Arnaldo Carvalho de Melo,
	linux-perf-users, bpf, selinux, Kees Cook, linux-mm,
	linux-security-module, apparmor, David Hildenbrand,
	Christian Brauner (Amutable), stable

proc_ns_readlink() copies the name of the namespace to userspace under
exec_update_lock. If that faults the lock is held for as long as the
fault takes. With a buffer in a mapping of a file on a FUSE filesystem
or in a range registered with userfaultfd it's the caller who decides
how long that is:

  locks held by ns-reader/230:
   #0: (&sig->exec_update_lock){++++}-{4:4}, at: proc_ns_readlink+0x180/0x340

In the meantime an exec of the task waits for exec_update_lock past the
point of no return. And everyone else who needs the exec_update_lock of
the task queues up behind the exec. So a read of /proc/<pid>/stat hangs
as well:

  task:exec-task       state:D pid:229
  Call Trace:
   __schedule+0x1691/0x4b00
   schedule+0xe0/0x2e0
   schedule_preempt_disabled+0x11/0x20
   rwsem_down_write_slowpath+0x472/0x1820
   down_write_killable+0x1ba/0x240
   begin_new_exec+0xa4b/0x2df0
   load_elf_binary+0x340/0x4af0
   bprm_execve+0x772/0x1400
   do_execveat_common.isra.0+0x3d9/0x540
   __x64_sys_execve+0x8c/0xc0
   do_syscall_64+0x110/0x600
   entry_SYSCALL_64_after_hwframe+0x77/0x7f

  task:stat-reader     state:D pid:231
  Call Trace:
   __schedule+0x1691/0x4b00
   schedule+0xe0/0x2e0
   schedule_preempt_disabled+0x11/0x20
   rwsem_down_read_slowpath+0x5cc/0x10c0
   down_read_killable+0xf1/0x5f0
   do_task_stat+0x13b/0x2870
   proc_single_show+0x110/0x1d0
   seq_read_iter+0x2e4/0x1280
   seq_read+0x29b/0x550
   vfs_read+0x171/0xb20
   ksys_read+0x111/0x250
   do_syscall_64+0x110/0x600
   entry_SYSCALL_64_after_hwframe+0x77/0x7f

All it takes is being allowed to read the namespace links of the task.

The name is formatted into a buffer on the stack anyway. So drop the
lock before it's copied out.

Fixes: 6650527444da ("proc: protect ptrace_may_access() with exec_update_lock (part 1)")
Cc: stable@vger.kernel.org
Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
---
 fs/proc/namespaces.c | 7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)

diff --git a/fs/proc/namespaces.c b/fs/proc/namespaces.c
index ea6ec61a0430b..4c91ccbed21ef 100644
--- a/fs/proc/namespaces.c
+++ b/fs/proc/namespaces.c
@@ -92,12 +92,11 @@ static int proc_ns_readlink(struct dentry *dentry, char __user *buffer, int bufl
 		goto out_put_task;
 
 	res = -EACCES;
-	if (ptrace_may_access(task, PTRACE_MODE_READ_FSCREDS)) {
+	if (ptrace_may_access(task, PTRACE_MODE_READ_FSCREDS))
 		res = ns_get_name(name, sizeof(name), task, ns_ops);
-		if (res >= 0)
-			res = readlink_copy(buffer, buflen, name, strlen(name));
-	}
 	up_read(&task->signal->exec_update_lock);
+	if (res >= 0)
+		res = readlink_copy(buffer, buflen, name, strlen(name));
 out_put_task:
 	put_task_struct(task);
 	return res;

-- 
2.53.0


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH RFC 02/19] kcmp: look up epoll target without exec_update_lock held
  2026-11-24 22:58 [PATCH RFC 00/19] exec: move sleeping work out of exec_update_lock Christian Brauner
  2026-11-24 22:58 ` [PATCH RFC 01/19] proc: copy namespace link after dropping exec_update_lock Christian Brauner
@ 2026-11-24 22:58 ` Christian Brauner
  2026-11-24 22:58 ` [PATCH RFC 03/19] perf: copy counter values after dropping ctx->mutex Christian Brauner
                   ` (17 subsequent siblings)
  19 siblings, 0 replies; 22+ messages in thread
From: Christian Brauner @ 2026-11-24 22:58 UTC (permalink / raw)
  To: Jann Horn
  Cc: Linus Torvalds, linux-fsdevel, Arnaldo Carvalho de Melo,
	linux-perf-users, bpf, selinux, Kees Cook, linux-mm,
	linux-security-module, apparmor, David Hildenbrand,
	Christian Brauner (Amutable), stable

kcmp(KCMP_EPOLL_TFD) holds exec_update_lock and two things both of which
are susceptible to page fault induced, userspace controlled delays:

(1) cpy struct kcmp_epoll_slot from userspace

   locks held by kcmp-reader/233:
    #0: (&sig->exec_update_lock){++++}-{4:4}, at: __do_sys_kcmp+0x2ec/0xb10
    #1: (&sig->exec_update_lock/1){.+.+}-{4:4}, at: __do_sys_kcmp+0x210/0xb10

(2) takes the mutex of the epoll file to look up the target file.

   locks held by epoll-waiter/236:
    #0: (&ep->mtx){+.+.}-{4:4}, at: ep_send_events+0x10a/0x9f0
   locks held by kcmp-caller/237:
    #0: (&sig->exec_update_lock){++++}-{4:4}, at: __do_sys_kcmp+0x2ec/0xb10
    #1: (&sig->exec_update_lock/1){.+.+}-{4:4}, at: __do_sys_kcmp+0x210/0xb10
    #2: (&ep->mtx){+.+.}-{4:4}, at: get_epoll_tfile_raw_ptr+0xa5/0x190

In the meantime an exec of either task waits for exec_update_lock past
the point of no return. And everyone else who needs the exec_update_lock
of that task queues up behind the exec. So a read of /proc/<pid>/stat
hangs as well:

  task:exec-task       state:D pid:235
  Call Trace:
   __schedule+0x1691/0x4b00
   schedule+0xe0/0x2e0
   schedule_preempt_disabled+0x11/0x20
   rwsem_down_write_slowpath+0x472/0x1820
   down_write_killable+0x1ba/0x240
   begin_new_exec+0xa4b/0x2df0
   load_elf_binary+0x340/0x4af0
   bprm_execve+0x772/0x1400
   do_execveat_common.isra.0+0x3d9/0x540
   __x64_sys_execve+0x8c/0xc0
   do_syscall_64+0x110/0x600
   entry_SYSCALL_64_after_hwframe+0x77/0x7f

  task:stat-reader     state:D pid:238
  Call Trace:
   __schedule+0x1691/0x4b00
   schedule+0xe0/0x2e0
   schedule_preempt_disabled+0x11/0x20
   rwsem_down_read_slowpath+0x5cc/0x10c0
   down_read_killable+0xf1/0x5f0
   do_task_stat+0x13b/0x2870
   proc_single_show+0x110/0x1d0
   seq_read_iter+0x2e4/0x1280
   seq_read+0x29b/0x550
   vfs_read+0x171/0xb20
   ksys_read+0x111/0x250
   do_syscall_64+0x110/0x600
   entry_SYSCALL_64_after_hwframe+0x77/0x7f

All it takes is being allowed to kcmp() the two tasks.

Stop that and copy the before the locks are taken. With the locks held
only take a reference to the epoll file and look up the target after
they have been dropped. The epoll file is still taken from the task
after the access check and with exec_update_lock held.

Note that the target is now looked up a moment later. So if the task
execs in between and keeps the epoll file the caller may get to compare
a target that only the new image registered. The caller still only gets
at the epoll file while it's allowed to look at the task and all it
learns is how two files compare.

Fixes: 0791e3644e5e ("kcmp: add KCMP_EPOLL_TFD mode to compare epoll target files")
Cc: stable@vger.kernel.org
Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
---
 kernel/kcmp.c | 72 +++++++++++++++++++++++++++++++++++++++++------------------
 1 file changed, 50 insertions(+), 22 deletions(-)

diff --git a/kernel/kcmp.c b/kernel/kcmp.c
index 76476aeee067b..8102e5825efc5 100644
--- a/kernel/kcmp.c
+++ b/kernel/kcmp.c
@@ -94,6 +94,34 @@ static int kcmp_lock(struct rw_semaphore *l1, struct rw_semaphore *l2)
 	return err;
 }
 
+static void kcmp_unlock_tasks(struct task_struct *task1,
+			      struct task_struct *task2)
+{
+	kcmp_unlock(&task1->signal->exec_update_lock,
+		    &task2->signal->exec_update_lock);
+}
+
+static int kcmp_lock_tasks(struct task_struct *task1,
+			   struct task_struct *task2)
+{
+	int ret;
+
+	ret = kcmp_lock(&task1->signal->exec_update_lock,
+			&task2->signal->exec_update_lock);
+	if (ret)
+		return ret;
+
+	/*
+	 * One should have enough rights to inspect task details.
+	 */
+	if (ptrace_may_access(task1, PTRACE_MODE_READ_REALCREDS) &&
+	    ptrace_may_access(task2, PTRACE_MODE_READ_REALCREDS))
+		return 0;
+
+	kcmp_unlock_tasks(task1, task2);
+	return -EPERM;
+}
+
 #ifdef CONFIG_EPOLL
 static int kcmp_epoll_target(struct task_struct *task1,
 			     struct task_struct *task2,
@@ -102,18 +130,26 @@ static int kcmp_epoll_target(struct task_struct *task1,
 {
 	struct file *filp, *filp_epoll, *filp_tgt;
 	struct kcmp_epoll_slot slot;
+	int ret;
 
+	/* This may fault so do it before exec_update_lock is taken. */
 	if (copy_from_user(&slot, uslot, sizeof(slot)))
 		return -EFAULT;
 
-	filp = get_file_raw_ptr(task1, idx1);
-	if (!filp)
-		return -EBADF;
+	ret = kcmp_lock_tasks(task1, task2);
+	if (ret)
+		return ret;
 
-	filp_epoll = fget_task(task2, slot.efd);
+	filp = get_file_raw_ptr(task1, idx1);
+	filp_epoll = filp ? fget_task(task2, slot.efd) : NULL;
+	kcmp_unlock_tasks(task1, task2);
 	if (!filp_epoll)
 		return -EBADF;
 
+	/*
+	 * This takes the epoll mutex which is held across page faults. So
+	 * do it after exec_update_lock has been dropped.
+	 */
 	filp_tgt = get_epoll_tfile_raw_ptr(filp_epoll, slot.tfd, slot.toff);
 	fput(filp_epoll);
 
@@ -153,19 +189,16 @@ SYSCALL_DEFINE5(kcmp, pid_t, pid1, pid_t, pid2, int, type,
 
 	rcu_read_unlock();
 
-	/*
-	 * One should have enough rights to inspect task details.
-	 */
-	ret = kcmp_lock(&task1->signal->exec_update_lock,
-			&task2->signal->exec_update_lock);
-	if (ret)
-		goto err;
-	if (!ptrace_may_access(task1, PTRACE_MODE_READ_REALCREDS) ||
-	    !ptrace_may_access(task2, PTRACE_MODE_READ_REALCREDS)) {
-		ret = -EPERM;
-		goto err_unlock;
+	/* Takes and drops exec_update_lock itself. */
+	if (type == KCMP_EPOLL_TFD) {
+		ret = kcmp_epoll_target(task1, task2, idx1, (void __user *)idx2);
+		goto out;
 	}
 
+	ret = kcmp_lock_tasks(task1, task2);
+	if (ret)
+		goto out;
+
 	switch (type) {
 	case KCMP_FILE: {
 		struct file *filp1, *filp2;
@@ -203,18 +236,13 @@ SYSCALL_DEFINE5(kcmp, pid_t, pid1, pid_t, pid2, int, type,
 		ret = -EOPNOTSUPP;
 #endif
 		break;
-	case KCMP_EPOLL_TFD:
-		ret = kcmp_epoll_target(task1, task2, idx1, (void *)idx2);
-		break;
 	default:
 		ret = -EINVAL;
 		break;
 	}
 
-err_unlock:
-	kcmp_unlock(&task1->signal->exec_update_lock,
-		    &task2->signal->exec_update_lock);
-err:
+	kcmp_unlock_tasks(task1, task2);
+out:
 	put_task_struct(task1);
 	put_task_struct(task2);
 

-- 
2.53.0


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH RFC 03/19] perf: copy counter values after dropping ctx->mutex
  2026-11-24 22:58 [PATCH RFC 00/19] exec: move sleeping work out of exec_update_lock Christian Brauner
  2026-11-24 22:58 ` [PATCH RFC 01/19] proc: copy namespace link after dropping exec_update_lock Christian Brauner
  2026-11-24 22:58 ` [PATCH RFC 02/19] kcmp: look up epoll target without exec_update_lock held Christian Brauner
@ 2026-11-24 22:58 ` Christian Brauner
  2026-11-24 22:58 ` [PATCH RFC 04/19] perf: copy ioctl arguments without ctx->mutex held Christian Brauner
                   ` (16 subsequent siblings)
  19 siblings, 0 replies; 22+ messages in thread
From: Christian Brauner @ 2026-11-24 22:58 UTC (permalink / raw)
  To: Jann Horn
  Cc: Linus Torvalds, linux-fsdevel, Arnaldo Carvalho de Melo,
	linux-perf-users, bpf, selinux, Kees Cook, linux-mm,
	linux-security-module, apparmor, David Hildenbrand,
	Christian Brauner (Amutable), stable

perf_read() copies the values to userspace with the mutex of the
event's context held. If that faults the mutex is held for as long as
the fault takes. With a buffer in a mapping of a file on a FUSE
filesystem or in a range registered with userfaultfd it's the caller who
decides how long that is:

  locks held by perf-reader/212:
   #0: (&ctx->mutex){+.+.}-{4:4}, at: perf_event_ctx_lock_nested+0x18f/0x360

Since commit 2e498d0a74e5 ("perf: Add support for event removal on
exec") perf_event_exec() takes that mutex whenever the task has a perf
context. And begin_new_exec() calls it with exec_update_lock held. So an
exec of the task the event counts for hangs past the point of no return
until the fault is resolved. It can't be killed either:

  locks held by exec-task/211:
   #0: (&sig->cred_guard_mutex){+.+.}-{4:4}, at: bprm_execve+0xb7/0x1400
   #1: (&sig->exec_update_lock){++++}-{4:4}, at: begin_new_exec+0xa4b/0x2df0
   #2: (&ctx->mutex){+.+.}-{4:4}, at: perf_event_exec+0x17e/0xe40

  task:exec-task       state:D pid:211
  Call Trace:
   __schedule+0x1691/0x4b00
   schedule+0xe0/0x2e0
   schedule_preempt_disabled+0x11/0x20
   __mutex_lock+0x6d7/0x2700
   perf_event_exec+0x17e/0xe40
   begin_new_exec+0x1c1e/0x2df0
   load_elf_binary+0x340/0x4af0
   bprm_execve+0x772/0x1400
   do_execveat_common.isra.0+0x3d9/0x540
   __x64_sys_execve+0x8c/0xc0
   do_syscall_64+0x110/0x600
   entry_SYSCALL_64_after_hwframe+0x77/0x7f

And everyone who needs the exec_update_lock of the task waits with it.
Since commit 6650527444da ("proc: protect ptrace_may_access() with
exec_update_lock (part 1)") that includes a read of /proc/<pid>/stat:

  task:stat-reader     state:D pid:214
  Call Trace:
   __schedule+0x1691/0x4b00
   schedule+0xe0/0x2e0
   schedule_preempt_disabled+0x11/0x20
   rwsem_down_read_slowpath+0x5cc/0x10c0
   down_read_killable+0xf1/0x5f0
   do_task_stat+0x13b/0x2870
   proc_single_show+0x110/0x1d0
   seq_read_iter+0x2e4/0x1280
   seq_read+0x29b/0x550
   vfs_read+0x171/0xb20
   ksys_read+0x111/0x250
   do_syscall_64+0x110/0x600
   entry_SYSCALL_64_after_hwframe+0x77/0x7f

The values are gathered in a kernel buffer anyway. So hand that buffer
to perf_read() and copy it out after the mutex has been dropped. What a
read returns goes into a struct on the stack of perf_read() that the
helpers fill in.

Fixes: 2e498d0a74e5 ("perf: Add support for event removal on exec")
Cc: stable@vger.kernel.org
Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
---
 kernel/events/core.c | 43 +++++++++++++++++++++++++------------------
 1 file changed, 25 insertions(+), 18 deletions(-)

diff --git a/kernel/events/core.c b/kernel/events/core.c
index e870f12c3ad81..f00eeded212c4 100644
--- a/kernel/events/core.c
+++ b/kernel/events/core.c
@@ -6188,8 +6188,15 @@ static int __perf_read_group_add(struct perf_event *leader,
 	return ret;
 }
 
-static int perf_read_group(struct perf_event *event,
-				   u64 read_format, char __user *buf)
+/* What a read of an event returns, filled in with ctx->mutex held. */
+struct perf_read_buf {
+	size_t	count;		/* room in the buffer of the reader */
+	u64	values[5];	/* a single event */
+	u64	*group_values;	/* PERF_FORMAT_GROUP, allocated */
+};
+
+static int perf_read_group(struct perf_event *event, u64 read_format,
+			   struct perf_read_buf *rb)
 {
 	struct perf_event *leader = event->group_leader, *child;
 	struct perf_event_context *ctx = leader->ctx;
@@ -6218,23 +6225,20 @@ static int perf_read_group(struct perf_event *event,
 
 	mutex_unlock(&leader->child_mutex);
 
-	ret = event->read_size;
-	if (copy_to_user(buf, values, event->read_size))
-		ret = -EFAULT;
-	goto out;
+	rb->group_values = values;
+	return event->read_size;
 
 unlock:
 	mutex_unlock(&leader->child_mutex);
-out:
 	kfree(values);
 	return ret;
 }
 
-static int perf_read_one(struct perf_event *event,
-				 u64 read_format, char __user *buf)
+static int perf_read_one(struct perf_event *event, u64 read_format,
+			 struct perf_read_buf *rb)
 {
 	u64 enabled, running;
-	u64 values[5];
+	u64 *values = rb->values;
 	int n = 0;
 
 	values[n++] = __perf_event_read_value(event, &enabled, &running);
@@ -6247,9 +6251,6 @@ static int perf_read_one(struct perf_event *event,
 	if (read_format & PERF_FORMAT_LOST)
 		values[n++] = atomic64_read(&event->lost_samples);
 
-	if (copy_to_user(buf, values, n * sizeof(u64)))
-		return -EFAULT;
-
 	return n * sizeof(u64);
 }
 
@@ -6270,7 +6271,7 @@ static bool is_event_hup(struct perf_event *event)
  * Read the performance event - simple non blocking version for now
  */
 static ssize_t
-__perf_read(struct perf_event *event, char __user *buf, size_t count)
+__perf_read(struct perf_event *event, struct perf_read_buf *rb)
 {
 	u64 read_format = event->attr.read_format;
 	int ret;
@@ -6283,14 +6284,14 @@ __perf_read(struct perf_event *event, char __user *buf, size_t count)
 	if (event->state == PERF_EVENT_STATE_ERROR)
 		return 0;
 
-	if (count < event->read_size)
+	if (rb->count < event->read_size)
 		return -ENOSPC;
 
 	WARN_ON_ONCE(event->ctx->parent_ctx);
 	if (read_format & PERF_FORMAT_GROUP)
-		ret = perf_read_group(event, read_format, buf);
+		ret = perf_read_group(event, read_format, rb);
 	else
-		ret = perf_read_one(event, read_format, buf);
+		ret = perf_read_one(event, read_format, rb);
 
 	return ret;
 }
@@ -6299,6 +6300,7 @@ static ssize_t
 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
 {
 	struct perf_event *event = file->private_data;
+	struct perf_read_buf rb = { .count = count };
 	struct perf_event_context *ctx;
 	int ret;
 
@@ -6307,9 +6309,14 @@ perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
 		return ret;
 
 	ctx = perf_event_ctx_lock(event);
-	ret = __perf_read(event, buf, count);
+	ret = __perf_read(event, &rb);
 	perf_event_ctx_unlock(event, ctx);
 
+	/* The copy can sleep in a page fault. Don't hold ctx->mutex for it. */
+	if (ret > 0 && copy_to_user(buf, rb.group_values ?: rb.values, ret))
+		ret = -EFAULT;
+
+	kfree(rb.group_values);
 	return ret;
 }
 

-- 
2.53.0


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH RFC 04/19] perf: copy ioctl arguments without ctx->mutex held
  2026-11-24 22:58 [PATCH RFC 00/19] exec: move sleeping work out of exec_update_lock Christian Brauner
                   ` (2 preceding siblings ...)
  2026-11-24 22:58 ` [PATCH RFC 03/19] perf: copy counter values after dropping ctx->mutex Christian Brauner
@ 2026-11-24 22:58 ` Christian Brauner
  2026-11-24 22:58 ` [PATCH RFC 05/19] selinux: close inherited files that can't be replaced Christian Brauner
                   ` (15 subsequent siblings)
  19 siblings, 0 replies; 22+ messages in thread
From: Christian Brauner @ 2026-11-24 22:58 UTC (permalink / raw)
  To: Jann Horn
  Cc: Linus Torvalds, linux-fsdevel, Arnaldo Carvalho de Melo,
	linux-perf-users, bpf, selinux, Kees Cook, linux-mm,
	linux-security-module, apparmor, David Hildenbrand,
	Christian Brauner (Amutable), stable

perf_ioctl() calls _perf_ioctl() with the mutex of the event's context
held and a number of commands access userspace from there:

- PERF_EVENT_IOC_PERIOD copies the period from userspace.

- PERF_EVENT_IOC_ID copies the id to userspace.

- PERF_EVENT_IOC_SET_FILTER copies the filter string from userspace.

- PERF_EVENT_IOC_QUERY_BPF copies the query from userspace and the ids
  of the programs back.

- PERF_EVENT_IOC_MODIFY_ATTRIBUTES copies the attributes from userspace.

This is the same problem as for read(). If one of them faults the mutex
is held for as long as the fault takes and an exec of the task the event
counts for hangs with exec_update_lock held:

  locks held by perf-ioctl/217:
   #0: (&ctx->mutex){+.+.}-{4:4}, at: perf_event_ctx_lock_nested+0x18f/0x360
  locks held by exec-task/216:
   #0: (&sig->cred_guard_mutex){+.+.}-{4:4}, at: bprm_execve+0xb7/0x1400
   #1: (&sig->exec_update_lock){++++}-{4:4}, at: begin_new_exec+0xa4b/0x2df0
   #2: (&ctx->mutex){+.+.}-{4:4}, at: perf_event_exec+0x17e/0xe40
  locks held by stat-reader/218:
   #0: (&p->lock){+.+.}-{4:4}, at: seq_read_iter+0xc5/0x1280
   #1: (&sig->exec_update_lock){++++}-{4:4}, at: do_task_stat+0x13b/0x2870

Copy what comes from userspace before the mutex is taken and what goes
to userspace after it has been dropped.

PERF_EVENT_IOC_QUERY_BPF doesn't need the mutex. The programs of a
tracepoint are protected by bpf_event_mutex. So call
perf_event_query_prog_array() before the mutex is taken.

Fixes: 2e498d0a74e5 ("perf: Add support for event removal on exec")
Cc: stable@vger.kernel.org
Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
---
 kernel/events/core.c | 93 ++++++++++++++++++++++++++++++++--------------------
 1 file changed, 57 insertions(+), 36 deletions(-)

diff --git a/kernel/events/core.c b/kernel/events/core.c
index f00eeded212c4..5f648e00ae661 100644
--- a/kernel/events/core.c
+++ b/kernel/events/core.c
@@ -6635,14 +6635,25 @@ static inline bool is_perf_file(struct fd f)
 
 static int perf_event_set_output(struct perf_event *event,
 				 struct perf_event *output_event);
-static int perf_event_set_filter(struct perf_event *event, void __user *arg);
+static int perf_event_set_filter(struct perf_event *event, char *filter_str);
 static int perf_copy_attr(struct perf_event_attr __user *uattr,
 			  struct perf_event_attr *attr);
 static int __perf_event_set_bpf_prog(struct perf_event *event,
 				     struct bpf_prog *prog,
 				     u64 bpf_cookie);
 
-static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
+/*
+ * What perf_ioctl() copies from userspace before it takes ctx->mutex and
+ * what it copies back once it dropped it.
+ */
+struct perf_ioctl_data {
+	u64			value;
+	char			*filter;
+	struct perf_event_attr	attr;
+};
+
+static long _perf_ioctl(struct perf_event *event, unsigned int cmd,
+			unsigned long arg, struct perf_ioctl_data *data)
 {
 	void (*func)(struct perf_event *);
 	u32 flags = arg;
@@ -6665,22 +6676,11 @@ static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned lon
 		return _perf_event_refresh(event, arg);
 
 	case PERF_EVENT_IOC_PERIOD:
-	{
-		u64 value;
+		return _perf_event_period(event, data->value);
 
-		if (copy_from_user(&value, (u64 __user *)arg, sizeof(value)))
-			return -EFAULT;
-
-		return _perf_event_period(event, value);
-	}
 	case PERF_EVENT_IOC_ID:
-	{
-		u64 id = primary_event_id(event);
-
-		if (copy_to_user((void __user *)arg, &id, sizeof(id)))
-			return -EFAULT;
+		data->value = primary_event_id(event);
 		return 0;
-	}
 
 	case PERF_EVENT_IOC_SET_OUTPUT:
 	{
@@ -6695,7 +6695,7 @@ static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned lon
 	}
 
 	case PERF_EVENT_IOC_SET_FILTER:
-		return perf_event_set_filter(event, (void __user *)arg);
+		return perf_event_set_filter(event, data->filter);
 
 	case PERF_EVENT_IOC_SET_BPF:
 	{
@@ -6729,19 +6729,9 @@ static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned lon
 		return 0;
 	}
 
-	case PERF_EVENT_IOC_QUERY_BPF:
-		return perf_event_query_prog_array(event, (void __user *)arg);
-
-	case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
-		struct perf_event_attr new_attr;
-		int err = perf_copy_attr((struct perf_event_attr __user *)arg,
-					 &new_attr);
+	case PERF_EVENT_IOC_MODIFY_ATTRIBUTES:
+		return perf_event_modify_attr(event, &data->attr);
 
-		if (err)
-			return err;
-
-		return perf_event_modify_attr(event,  &new_attr);
-	}
 	default:
 		return -ENOTTY;
 	}
@@ -6758,6 +6748,7 @@ static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
 {
 	struct perf_event *event = file->private_data;
 	struct perf_event_context *ctx;
+	struct perf_ioctl_data data;
 	long ret;
 
 	/* Treat ioctl like writes as it is likely a mutating operation. */
@@ -6765,10 +6756,46 @@ static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
 	if (ret)
 		return ret;
 
+	/*
+	 * A copy from or to userspace can sleep in a page fault. Don't hold
+	 * ctx->mutex for it.
+	 */
+	data.filter = NULL;
+	switch (cmd) {
+	case PERF_EVENT_IOC_PERIOD:
+		if (copy_from_user(&data.value, (u64 __user *)arg,
+				   sizeof(data.value)))
+			return -EFAULT;
+		break;
+
+	case PERF_EVENT_IOC_SET_FILTER:
+		data.filter = strndup_user((void __user *)arg, PAGE_SIZE);
+		if (IS_ERR(data.filter))
+			return PTR_ERR(data.filter);
+		break;
+
+	case PERF_EVENT_IOC_QUERY_BPF:
+		/* Looks at the tracepoint's programs under bpf_event_mutex. */
+		return perf_event_query_prog_array(event, (void __user *)arg);
+
+	case PERF_EVENT_IOC_MODIFY_ATTRIBUTES:
+		ret = perf_copy_attr((struct perf_event_attr __user *)arg,
+				     &data.attr);
+		if (ret)
+			return ret;
+		break;
+	}
+
 	ctx = perf_event_ctx_lock(event);
-	ret = _perf_ioctl(event, cmd, arg);
+	ret = _perf_ioctl(event, cmd, arg, &data);
 	perf_event_ctx_unlock(event, ctx);
 
+	kfree(data.filter);
+
+	if (!ret && cmd == PERF_EVENT_IOC_ID &&
+	    copy_to_user((void __user *)arg, &data.value, sizeof(data.value)))
+		return -EFAULT;
+
 	return ret;
 }
 
@@ -12367,14 +12394,9 @@ perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
 	return ret;
 }
 
-static int perf_event_set_filter(struct perf_event *event, void __user *arg)
+static int perf_event_set_filter(struct perf_event *event, char *filter_str)
 {
 	int ret = -EINVAL;
-	char *filter_str;
-
-	filter_str = strndup_user(arg, PAGE_SIZE);
-	if (IS_ERR(filter_str))
-		return PTR_ERR(filter_str);
 
 #ifdef CONFIG_EVENT_TRACING
 	if (perf_event_is_tracing(event)) {
@@ -12399,7 +12421,6 @@ static int perf_event_set_filter(struct perf_event *event, void __user *arg)
 	if (has_addr_filter(event))
 		ret = perf_event_set_addr_filter(event, filter_str);
 
-	kfree(filter_str);
 	return ret;
 }
 

-- 
2.53.0


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH RFC 05/19] selinux: close inherited files that can't be replaced
  2026-11-24 22:58 [PATCH RFC 00/19] exec: move sleeping work out of exec_update_lock Christian Brauner
                   ` (3 preceding siblings ...)
  2026-11-24 22:58 ` [PATCH RFC 04/19] perf: copy ioctl arguments without ctx->mutex held Christian Brauner
@ 2026-11-24 22:58 ` Christian Brauner
  2026-11-24 22:58 ` [PATCH RFC 06/19] exec: move unshare_sighand() before exec_mmap() Christian Brauner
                   ` (14 subsequent siblings)
  19 siblings, 0 replies; 22+ messages in thread
From: Christian Brauner @ 2026-11-24 22:58 UTC (permalink / raw)
  To: Jann Horn
  Cc: Linus Torvalds, linux-fsdevel, Arnaldo Carvalho de Melo,
	linux-perf-users, bpf, selinux, Kees Cook, linux-mm,
	linux-security-module, apparmor, David Hildenbrand,
	Christian Brauner (Amutable), stable

When an exec transitions to a new SID flush_unauthorized_files()
replaces the inherited files the new SID isn't allowed to use with the
null device. It uses replace_fd() for that and ignores the return value.

replace_fd() refuses a file descriptor at or above RLIMIT_NOFILE. And a
task can lower its own soft limit as it likes. So a task that sets
RLIMIT_NOFILE to the number of a file descriptor right before the exec
keeps that file open in the new image:

	fd = open(path, O_RDONLY);	/* 3 */
	getrlimit(RLIMIT_NOFILE, &rl);
	rl.rlim_cur = fd;
	setrlimit(RLIMIT_NOFILE, &rl);
	execve(...);

The new SID still can't read from the file as that is checked again on
every use. But it holds on to the file and what isn't checked on use
like lseek() works.

Before commit ee97cd872d08 ("switch flush_unauthorized_files() to
replace_fd()") the file was closed first and stayed closed if its file
descriptor couldn't be allocated again. So close the file if it can't be
replaced.

Fixes: ee97cd872d08 ("switch flush_unauthorized_files() to replace_fd()")
Cc: stable@vger.kernel.org
Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
---
 security/selinux/hooks.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/security/selinux/hooks.c b/security/selinux/hooks.c
index 9950f89dfaa23..4ec9ec723cacc 100644
--- a/security/selinux/hooks.c
+++ b/security/selinux/hooks.c
@@ -2521,7 +2521,9 @@ static inline void flush_unauthorized_files(const struct cred *cred,
 		devnull = NULL;
 	/* replace all the matching ones with this */
 	do {
-		replace_fd(n - 1, devnull, 0);
+		/* replace_fd() fails for an fd at or above RLIMIT_NOFILE. */
+		if (replace_fd(n - 1, devnull, 0) < 0)
+			close_fd(n - 1);
 	} while ((n = iterate_fd(files, n, match_file, cred)) != 0);
 	if (devnull)
 		fput(devnull);

-- 
2.53.0


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH RFC 06/19] exec: move unshare_sighand() before exec_mmap()
  2026-11-24 22:58 [PATCH RFC 00/19] exec: move sleeping work out of exec_update_lock Christian Brauner
                   ` (4 preceding siblings ...)
  2026-11-24 22:58 ` [PATCH RFC 05/19] selinux: close inherited files that can't be replaced Christian Brauner
@ 2026-11-24 22:58 ` Christian Brauner
  2026-11-24 22:58 ` [PATCH RFC 07/19] selftests/exec: test exec with a task sleeping in a page fault Christian Brauner
                   ` (13 subsequent siblings)
  19 siblings, 0 replies; 22+ messages in thread
From: Christian Brauner @ 2026-11-24 22:58 UTC (permalink / raw)
  To: Jann Horn
  Cc: Linus Torvalds, linux-fsdevel, Arnaldo Carvalho de Melo,
	linux-perf-users, bpf, selinux, Kees Cook, linux-mm,
	linux-security-module, apparmor, David Hildenbrand,
	Christian Brauner (Amutable), stable

A task that called vfork() sleeps until the child has released the mm.
During exec that happens in exec_mmap(). A child that was created with
CLONE_SIGHAND shares its signal table with the parent and
unshare_sighand() only gives it a private one after exec_mmap(). So the
parent runs again while the child is still on the table they share. If
the parent ignores a signal right after vfork() returned the new image
can end up ignoring it as well.

It used to be the other way around. Commit ccf0fa6be026 ("exec: Move
exec_mmap right after de_thread in flush_old_exec") moved exec_mmap() in
front of it for two reasons. bprm->mm was to tell whether exec is past
the point of no return and everything that can wait for userspace
indefinitely was to sit in front of the lock that became
exec_update_lock.

Move it back to where it used to be, right after de_thread() and the
posix timer cleanup. Nothing in between relies on the signal table still
being shared. With that the table is private before the parent is woken
up. And the new table isn't allocated with exec_update_lock held
anymore.

Fixes: ccf0fa6be026 ("exec: Move exec_mmap right after de_thread in flush_old_exec")
Cc: stable@vger.kernel.org
Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
---
 fs/exec.c | 15 ++++++++-------
 1 file changed, 8 insertions(+), 7 deletions(-)

diff --git a/fs/exec.c b/fs/exec.c
index 8d2b14e1d455c..87b78fce609de 100644
--- a/fs/exec.c
+++ b/fs/exec.c
@@ -1171,6 +1171,14 @@ int begin_new_exec(struct linux_binprm * bprm)
 	 */
 	posixtimer_exec();
 
+	/*
+	 * Make the signal table private before a vfork() parent that shares
+	 * it is woken up.
+	 */
+	retval = unshare_sighand(me);
+	if (retval)
+		goto out;
+
 	/* see the comment in check_unsafe_exec() */
 	current->fs->in_exec = 0;
 
@@ -1223,13 +1231,6 @@ int begin_new_exec(struct linux_binprm * bprm)
 	if (retval)
 		goto out_unlock;
 
-	/*
-	 * Make the signal table private.
-	 */
-	retval = unshare_sighand(me);
-	if (retval)
-		goto out_unlock;
-
 	me->flags &= ~(PF_RANDOMIZE | PF_FORKNOEXEC |
 					PF_NOFREEZE | PF_NO_SETAFFINITY);
 	flush_thread();

-- 
2.53.0


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH RFC 07/19] selftests/exec: test exec with a task sleeping in a page fault
  2026-11-24 22:58 [PATCH RFC 00/19] exec: move sleeping work out of exec_update_lock Christian Brauner
                   ` (5 preceding siblings ...)
  2026-11-24 22:58 ` [PATCH RFC 06/19] exec: move unshare_sighand() before exec_mmap() Christian Brauner
@ 2026-11-24 22:58 ` Christian Brauner
  2026-11-24 22:58 ` [PATCH RFC 08/19] selftests/exec: test exec with a shared signal table Christian Brauner
                   ` (12 subsequent siblings)
  19 siblings, 0 replies; 22+ messages in thread
From: Christian Brauner @ 2026-11-24 22:58 UTC (permalink / raw)
  To: Jann Horn
  Cc: Linus Torvalds, linux-fsdevel, Arnaldo Carvalho de Melo,
	linux-perf-users, bpf, selinux, Kees Cook, linux-mm,
	linux-security-module, apparmor, David Hildenbrand,
	Christian Brauner (Amutable)

Test that a task which sleeps in a page fault while it looks at another
task doesn't block an exec of that task:

- readlink() on /proc/<pid>/ns/mnt with a buffer that faults

- kcmp() with KCMP_EPOLL_TFD and a slot that faults

- kcmp() with KCMP_EPOLL_TFD while another thread faults in epoll_wait()
  on the same epoll file

- read() on a perf event of the task with a buffer that faults

- ioctl() on a perf event of the task with an argument that faults, for
  each command that copies to or from userspace

The buffer is registered with userfaultfd so the fault only completes
after the exec had its chance.

Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
---
 tools/testing/selftests/exec/.gitignore          |   1 +
 tools/testing/selftests/exec/Makefile            |   3 +
 tools/testing/selftests/exec/config              |   3 +
 tools/testing/selftests/exec/update-lock-fault.c | 547 +++++++++++++++++++++++
 4 files changed, 554 insertions(+)

diff --git a/tools/testing/selftests/exec/.gitignore b/tools/testing/selftests/exec/.gitignore
index e42ecd4c908d1..4613c68537395 100644
--- a/tools/testing/selftests/exec/.gitignore
+++ b/tools/testing/selftests/exec/.gitignore
@@ -16,6 +16,7 @@ null-argv
 !load_address.c
 /recursion-depth
 /set-exec
+/update-lock-fault
 xxxxxxxx*
 pipe
 S_I*.test
diff --git a/tools/testing/selftests/exec/Makefile b/tools/testing/selftests/exec/Makefile
index 91decfa8ff2c1..3756a250f9591 100644
--- a/tools/testing/selftests/exec/Makefile
+++ b/tools/testing/selftests/exec/Makefile
@@ -20,6 +20,7 @@ TEST_FILES := Makefile
 TEST_GEN_PROGS += recursion-depth
 TEST_GEN_PROGS += null-argv
 TEST_GEN_PROGS += check-exec
+TEST_GEN_PROGS += update-lock-fault
 
 # binfmt_misc must not be reachable as an exec source or as a stacking layer,
 # or an 'F' entry can pin the instance that owns it. Unprivileged, no bpf.
@@ -115,6 +116,8 @@ $(OUTPUT)/binfmt_misc_selfpin: ../filesystems/utils.c
 $(OUTPUT)/binfmt_misc_interplimit: CFLAGS += $(TOOLS_INCLUDES)
 $(OUTPUT)/binfmt_misc_interplimit: ../filesystems/utils.c
 
+$(OUTPUT)/update-lock-fault: LDLIBS += -lpthread
+
 # --- binfmt_misc bpf ('B') handler test ---------------------------------
 # The struct_ops bpf objects are compiled against the running kernel's BTF.
 # CLANG/BPFTOOL/VMLINUX_BTF are set above next to the toolchain check;
diff --git a/tools/testing/selftests/exec/config b/tools/testing/selftests/exec/config
index ea359a929ae82..2b7563a234112 100644
--- a/tools/testing/selftests/exec/config
+++ b/tools/testing/selftests/exec/config
@@ -4,9 +4,12 @@ CONFIG_BINFMT_MISC=y
 CONFIG_BINFMT_MISC_BPF=y
 CONFIG_BPF_JIT=y
 CONFIG_BPF_SYSCALL=y
+CONFIG_CHECKPOINT_RESTORE=y
 CONFIG_DEBUG_INFO=y
 CONFIG_DEBUG_INFO_BTF=y
 CONFIG_DEBUG_INFO_DWARF4=y
 CONFIG_OVERLAY_FS=y
+CONFIG_PERF_EVENTS=y
 CONFIG_TMPFS=y
+CONFIG_USERFAULTFD=y
 CONFIG_USER_NS=y
diff --git a/tools/testing/selftests/exec/update-lock-fault.c b/tools/testing/selftests/exec/update-lock-fault.c
new file mode 100644
index 0000000000000..d57a6703f56c5
--- /dev/null
+++ b/tools/testing/selftests/exec/update-lock-fault.c
@@ -0,0 +1,547 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Test that a task which sleeps in a page fault while it looks at another
+ * task doesn't hold a lock that an exec in that task needs: the
+ * exec_update_lock of the task or the mutex of its perf context. Otherwise
+ * the exec hangs until the fault is resolved.
+ *
+ * The buffer handed to the kernel is registered with userfaultfd so the
+ * fault only completes once the test says so.
+ */
+#define _GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <poll.h>
+#include <pthread.h>
+#include <sched.h>
+#include <signal.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/epoll.h>
+#include <sys/ioctl.h>
+#include <sys/mman.h>
+#include <sys/syscall.h>
+#include <sys/wait.h>
+#include <unistd.h>
+#include <linux/kcmp.h>
+#include <linux/perf_event.h>
+#include <linux/userfaultfd.h>
+
+#include "kselftest_harness.h"
+
+/* Makes the exec'd image exit right away. */
+#define EXECED_ARG	"execed"
+
+/* How long the exec'd image gets to exit before the exec counts as stuck. */
+#define EXEC_TIMEOUT_MS	5000
+
+/* A page that faults until fault_resolve() is called. */
+struct fault {
+	int uffd;
+	void *buf;
+	size_t size;
+};
+
+static bool fault_setup(struct __test_metadata *_metadata, struct fault *fault)
+{
+	struct uffdio_api api = { .api = UFFD_API };
+	struct uffdio_register reg = {};
+
+	/*
+	 * Faults from kernel mode need CAP_SYS_PTRACE or
+	 * vm.unprivileged_userfaultfd=1. poll() only works on a nonblocking
+	 * userfaultfd.
+	 */
+	fault->uffd = syscall(SYS_userfaultfd, O_CLOEXEC | O_NONBLOCK);
+	if (fault->uffd < 0)
+		SKIP(return false, "userfaultfd: %s", strerror(errno));
+	ASSERT_EQ(ioctl(fault->uffd, UFFDIO_API, &api), 0);
+
+	fault->size = sysconf(_SC_PAGESIZE);
+	fault->buf = mmap(NULL, fault->size, PROT_READ | PROT_WRITE,
+			  MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+	ASSERT_NE(fault->buf, MAP_FAILED);
+	reg.range.start = (unsigned long)fault->buf;
+	reg.range.len = fault->size;
+	reg.mode = UFFDIO_REGISTER_MODE_MISSING;
+	ASSERT_EQ(ioctl(fault->uffd, UFFDIO_REGISTER, &reg), 0);
+	return true;
+}
+
+/* Someone sleeps in a fault on the page now. */
+static void fault_read(struct __test_metadata *_metadata, struct fault *fault)
+{
+	struct uffd_msg msg;
+
+	ASSERT_EQ(read(fault->uffd, &msg, sizeof(msg)), (ssize_t)sizeof(msg));
+	ASSERT_EQ(msg.event, UFFD_EVENT_PAGEFAULT);
+}
+
+static void fault_resolve(struct __test_metadata *_metadata,
+			  struct fault *fault)
+{
+	struct uffdio_zeropage zeropage = {};
+
+	zeropage.range.start = (unsigned long)fault->buf;
+	zeropage.range.len = fault->size;
+	ASSERT_EQ(ioctl(fault->uffd, UFFDIO_ZEROPAGE, &zeropage), 0);
+}
+
+static void fault_cleanup(struct __test_metadata *_metadata,
+			  struct fault *fault)
+{
+	EXPECT_EQ(munmap(fault->buf, fault->size), 0);
+	EXPECT_EQ(close(fault->uffd), 0);
+}
+
+/* A child that execs when it is told to. */
+struct child {
+	pid_t pid;
+	int pidfd;
+	int exec_fd;
+};
+
+static void child_start(struct __test_metadata *_metadata, struct child *child)
+{
+	int exec_pipe[2];
+	char c;
+
+	ASSERT_EQ(pipe2(exec_pipe, O_CLOEXEC), 0);
+	child->pid = fork();
+	ASSERT_GE(child->pid, 0);
+	if (child->pid == 0) {
+		close(exec_pipe[1]);
+		if (read(exec_pipe[0], &c, 1) == 1)
+			execl("/proc/self/exe", "update-lock-fault", EXECED_ARG,
+			      (char *)NULL);
+		_exit(EXIT_FAILURE);
+	}
+	ASSERT_EQ(close(exec_pipe[0]), 0);
+	child->exec_fd = exec_pipe[1];
+	child->pidfd = syscall(SYS_pidfd_open, child->pid, 0);
+	ASSERT_GE(child->pidfd, 0);
+}
+
+/* Whether the exec'd image ran and exited in time. */
+static bool child_exec(struct __test_metadata *_metadata, struct child *child)
+{
+	struct pollfd pfd = { .fd = child->pidfd, .events = POLLIN };
+	int ret;
+
+	ASSERT_EQ(write(child->exec_fd, "", 1), 1);
+	ret = poll(&pfd, 1, EXEC_TIMEOUT_MS);
+	ASSERT_GE(ret, 0);
+	return ret > 0;
+}
+
+static void child_reap(struct __test_metadata *_metadata, struct child *child,
+		       bool kill_it)
+{
+	int status;
+
+	if (kill_it)
+		ASSERT_EQ(kill(child->pid, SIGKILL), 0);
+	ASSERT_EQ(waitpid(child->pid, &status, 0), child->pid);
+	if (!kill_it) {
+		ASSERT_TRUE(WIFEXITED(status));
+		ASSERT_EQ(WEXITSTATUS(status), EXIT_SUCCESS);
+	}
+	EXPECT_EQ(close(child->pidfd), 0);
+	EXPECT_EQ(close(child->exec_fd), 0);
+}
+
+/* A thread that makes one system call. */
+struct caller {
+	long (*fn)(struct caller *caller);
+	pid_t pid;
+	void *buf;
+	unsigned long cmd;
+	int epfd;
+	int tfd;
+	pthread_t thread;
+	int pipe[2];
+	pid_t tid;
+	long ret;
+	int err;
+	bool skip;
+};
+
+/* The kernel copies the name of the namespace to the buffer. */
+static long do_ns_readlink(struct caller *caller)
+{
+	char path[64];
+
+	snprintf(path, sizeof(path), "/proc/%d/ns/mnt", caller->pid);
+	return readlink(path, caller->buf, 64);
+}
+
+/* The kernel copies a struct kcmp_epoll_slot from the buffer. */
+static long do_kcmp_epoll_tfd(struct caller *caller)
+{
+	return syscall(SYS_kcmp, getpid(), caller->pid, KCMP_EPOLL_TFD, 0,
+		       caller->buf);
+}
+
+/* The kernel copies an event to the buffer with the epoll mutex held. */
+static long do_epoll_wait(struct caller *caller)
+{
+	return epoll_wait(caller->epfd, caller->buf, 1, -1);
+}
+
+/* The kernel takes the epoll mutex to look up the target file. */
+static long do_kcmp_epoll_mutex(struct caller *caller)
+{
+	struct kcmp_epoll_slot slot = {
+		.efd = caller->epfd,
+		.tfd = caller->tfd,
+	};
+
+	return syscall(SYS_kcmp, getpid(), caller->pid, KCMP_EPOLL_TFD,
+		       caller->tfd, &slot);
+}
+
+static int tracepoint_id(void)
+{
+	static const char * const paths[] = {
+		"/sys/kernel/tracing/events/sched/sched_switch/id",
+		"/sys/kernel/debug/tracing/events/sched/sched_switch/id",
+	};
+	char buf[16];
+	ssize_t len;
+	size_t i;
+	int fd;
+
+	for (i = 0; i < ARRAY_SIZE(paths); i++) {
+		fd = open(paths[i], O_RDONLY | O_CLOEXEC);
+		if (fd < 0)
+			continue;
+		len = read(fd, buf, sizeof(buf) - 1);
+		close(fd);
+		if (len <= 0)
+			break;
+		buf[len] = '\0';
+		return atoi(buf);
+	}
+	return -1;
+}
+
+/*
+ * read() or an ioctl() on a perf event that counts for the other task. The
+ * kernel copies to or from the buffer.
+ */
+static long do_perf(struct caller *caller)
+{
+	struct perf_event_attr attr = {
+		.type		= PERF_TYPE_SOFTWARE,
+		.size		= sizeof(attr),
+		.config		= PERF_COUNT_SW_TASK_CLOCK,
+		.exclude_kernel	= 1,
+	};
+	int fd, err, id;
+	long ret;
+
+	/* Only a tracepoint can be asked for its bpf programs. */
+	if (caller->cmd == PERF_EVENT_IOC_QUERY_BPF) {
+		id = tracepoint_id();
+		if (id < 0) {
+			caller->skip = true;
+			return -1;
+		}
+		attr.type = PERF_TYPE_TRACEPOINT;
+		attr.config = id;
+		attr.exclude_kernel = 0;
+	}
+
+	fd = syscall(SYS_perf_event_open, &attr, caller->pid, -1, -1,
+		     PERF_FLAG_FD_CLOEXEC);
+	if (fd < 0) {
+		caller->skip = true;
+		return -1;
+	}
+
+	if (caller->cmd)
+		ret = ioctl(fd, caller->cmd, caller->buf);
+	else
+		ret = read(fd, caller->buf, sizeof(__u64));
+	err = errno;
+	close(fd);
+	/* The bpf programs can only be queried with CAP_PERFMON. */
+	if (caller->cmd == PERF_EVENT_IOC_QUERY_BPF && ret < 0 &&
+	    (err == EPERM || err == EACCES))
+		caller->skip = true;
+	errno = err;
+	return ret;
+}
+
+static void *caller_thread(void *arg)
+{
+	struct caller *caller = arg;
+
+	caller->tid = syscall(SYS_gettid);
+	if (write(caller->pipe[1], "", 1) != 1)
+		return NULL;
+	caller->ret = caller->fn(caller);
+	caller->err = caller->ret < 0 ? errno : 0;
+	if (write(caller->pipe[1], "", 1) != 1)
+		caller->err = EIO;
+	return NULL;
+}
+
+/* The pipe is readable again once the system call is back. */
+static void caller_start(struct __test_metadata *_metadata,
+			 struct caller *caller)
+{
+	char c;
+
+	ASSERT_EQ(pipe2(caller->pipe, O_CLOEXEC), 0);
+	ASSERT_EQ(pthread_create(&caller->thread, NULL, caller_thread, caller),
+		  0);
+	ASSERT_EQ(read(caller->pipe[0], &c, 1), 1);
+}
+
+static void caller_join(struct __test_metadata *_metadata,
+			struct caller *caller)
+{
+	ASSERT_EQ(pthread_join(caller->thread, NULL), 0);
+	EXPECT_EQ(close(caller->pipe[0]), 0);
+	EXPECT_EQ(close(caller->pipe[1]), 0);
+}
+
+/*
+ * Whether a thread of this process sleeps in system call @nr.
+ * /proc/<pid>/syscall only has the number for a task that isn't running.
+ * Returns -1 if that file can't be read.
+ */
+static int thread_sleeps_in(pid_t tid, long nr)
+{
+	char path[64], buf[64];
+	ssize_t len;
+	int fd;
+
+	snprintf(path, sizeof(path), "/proc/self/task/%d/syscall", tid);
+	fd = open(path, O_RDONLY | O_CLOEXEC);
+	if (fd < 0)
+		return -1;
+	len = read(fd, buf, sizeof(buf) - 1);
+	close(fd);
+	if (len <= 0)
+		return -1;
+	buf[len] = '\0';
+	/* "running" if it doesn't sleep, -1 if it sleeps outside of a syscall */
+	return strtol(buf, NULL, 10) == nr;
+}
+
+/*
+ * Wait until the thread sleeps in system call @nr. Returns 1 if it does, 0
+ * if the call is back already and -1 if there's no way to tell.
+ */
+static int caller_wait_sleeping(struct __test_metadata *_metadata,
+				struct caller *caller, long nr)
+{
+	struct pollfd pfd = { .fd = caller->pipe[0], .events = POLLIN };
+	int ret;
+
+	for (;;) {
+		ret = poll(&pfd, 1, 0);
+		ASSERT_GE(ret, 0);
+		if (ret > 0)
+			return 0;
+		ret = thread_sleeps_in(caller->tid, nr);
+		if (ret)
+			return ret;
+		sched_yield();
+	}
+}
+
+static bool not_supported(const struct caller *caller)
+{
+	return caller->skip || caller->err == ENOSYS ||
+	       caller->err == EOPNOTSUPP;
+}
+
+static void exec_with_reader_in_fault(struct __test_metadata *_metadata,
+				      long (*fn)(struct caller *caller),
+				      unsigned long cmd)
+{
+	struct caller reader = { .fn = fn, .cmd = cmd };
+	struct pollfd pfds[2];
+	struct fault fault;
+	struct child child;
+	bool exec_done;
+
+	if (!fault_setup(_metadata, &fault))
+		return;
+	child_start(_metadata, &child);
+
+	reader.pid = child.pid;
+	reader.buf = fault.buf;
+	caller_start(_metadata, &reader);
+
+	pfds[0].fd = fault.uffd;
+	pfds[0].events = POLLIN;
+	pfds[1].fd = reader.pipe[0];
+	pfds[1].events = POLLIN;
+	ASSERT_GT(poll(pfds, 2, -1), 0);
+	if (!(pfds[0].revents & POLLIN)) {
+		/* The reader came back without touching the buffer. */
+		caller_join(_metadata, &reader);
+		child_reap(_metadata, &child, true);
+		if (not_supported(&reader))
+			SKIP(return, "not supported: %s", strerror(reader.err));
+		ASSERT_TRUE(false) {
+			TH_LOG("reader returned %ld without a fault: %s",
+			       reader.ret, strerror(reader.err));
+		}
+	}
+	fault_read(_metadata, &fault);
+
+	/* The reader sleeps in the fault now. The exec must not wait for it. */
+	exec_done = child_exec(_metadata, &child);
+
+	/* Let the reader finish and with it an exec that waits for it. */
+	fault_resolve(_metadata, &fault);
+	caller_join(_metadata, &reader);
+	if (fn == do_ns_readlink)
+		EXPECT_GT(reader.ret, 0);
+	child_reap(_metadata, &child, false);
+
+	EXPECT_TRUE(exec_done) {
+		TH_LOG("exec waited for a task sleeping in a page fault");
+	}
+
+	fault_cleanup(_metadata, &fault);
+}
+
+/* readlink() on /proc/<pid>/ns/<name> */
+TEST(ns_readlink)
+{
+	exec_with_reader_in_fault(_metadata, do_ns_readlink, 0);
+}
+
+/* kcmp(KCMP_EPOLL_TFD) */
+TEST(kcmp_epoll_tfd)
+{
+	exec_with_reader_in_fault(_metadata, do_kcmp_epoll_tfd, 0);
+}
+
+/*
+ * kcmp(KCMP_EPOLL_TFD) with the mutex of the epoll file held by a thread
+ * that sleeps in a page fault in epoll_wait().
+ */
+TEST(kcmp_epoll_mutex)
+{
+	struct epoll_event ev = { .events = EPOLLIN };
+	struct caller waiter = { .fn = do_epoll_wait };
+	struct caller comparer = { .fn = do_kcmp_epoll_mutex };
+	struct pollfd pfd = { .events = POLLIN };
+	int epfd, ready[2], sleeping;
+	struct fault fault;
+	struct child child;
+	bool exec_done;
+
+	if (!fault_setup(_metadata, &fault))
+		return;
+
+	/* An epoll file with an event that is ready right away. */
+	epfd = epoll_create1(EPOLL_CLOEXEC);
+	if (epfd < 0 && errno == ENOSYS)
+		SKIP(return, "epoll: %s", strerror(errno));
+	ASSERT_GE(epfd, 0);
+	ASSERT_EQ(pipe2(ready, O_CLOEXEC), 0);
+	ASSERT_EQ(write(ready[1], "", 1), 1);
+	ASSERT_EQ(epoll_ctl(epfd, EPOLL_CTL_ADD, ready[0], &ev), 0);
+
+	/* The child inherits the epoll file. kcmp() looks it up there. */
+	child_start(_metadata, &child);
+
+	waiter.epfd = epfd;
+	waiter.buf = fault.buf;
+	caller_start(_metadata, &waiter);
+	pfd.fd = fault.uffd;
+	ASSERT_EQ(poll(&pfd, 1, -1), 1);
+	fault_read(_metadata, &fault);
+
+	/* epoll_wait() sleeps in the fault now. kcmp() waits for the mutex. */
+	comparer.pid = child.pid;
+	comparer.epfd = epfd;
+	comparer.tfd = ready[0];
+	caller_start(_metadata, &comparer);
+	sleeping = caller_wait_sleeping(_metadata, &comparer, SYS_kcmp);
+	if (sleeping < 0 || (!sleeping && comparer.err)) {
+		/* It can't be watched or it failed before it got anywhere. */
+		fault_resolve(_metadata, &fault);
+		caller_join(_metadata, &waiter);
+		caller_join(_metadata, &comparer);
+		child_reap(_metadata, &child, true);
+		if (sleeping < 0)
+			SKIP(return, "can't read /proc/<pid>/syscall");
+		if (not_supported(&comparer))
+			SKIP(return, "not supported: %s", strerror(comparer.err));
+		ASSERT_EQ(comparer.err, 0) {
+			TH_LOG("kcmp() failed: %s", strerror(comparer.err));
+		}
+	}
+
+	/* The exec must not wait for either of them. */
+	exec_done = child_exec(_metadata, &child);
+
+	/* Let epoll_wait() finish and with it kcmp() and the exec. */
+	fault_resolve(_metadata, &fault);
+	caller_join(_metadata, &waiter);
+	caller_join(_metadata, &comparer);
+	EXPECT_EQ(waiter.ret, 1);
+	child_reap(_metadata, &child, false);
+
+	EXPECT_TRUE(exec_done) {
+		TH_LOG("exec waited for a task sleeping on the epoll mutex");
+	}
+
+	EXPECT_EQ(close(ready[0]), 0);
+	EXPECT_EQ(close(ready[1]), 0);
+	EXPECT_EQ(close(epfd), 0);
+	fault_cleanup(_metadata, &fault);
+}
+
+/* read() on a perf event */
+TEST(perf_read)
+{
+	exec_with_reader_in_fault(_metadata, do_perf, 0);
+}
+
+/* The ioctls of a perf event that copy to or from userspace. */
+TEST(perf_ioctl_id)
+{
+	exec_with_reader_in_fault(_metadata, do_perf, PERF_EVENT_IOC_ID);
+}
+
+TEST(perf_ioctl_period)
+{
+	exec_with_reader_in_fault(_metadata, do_perf, PERF_EVENT_IOC_PERIOD);
+}
+
+TEST(perf_ioctl_set_filter)
+{
+	exec_with_reader_in_fault(_metadata, do_perf,
+				  PERF_EVENT_IOC_SET_FILTER);
+}
+
+TEST(perf_ioctl_modify_attributes)
+{
+	exec_with_reader_in_fault(_metadata, do_perf,
+				  PERF_EVENT_IOC_MODIFY_ATTRIBUTES);
+}
+
+/* Needs CAP_PERFMON and tracefs. */
+TEST(perf_ioctl_query_bpf)
+{
+	exec_with_reader_in_fault(_metadata, do_perf, PERF_EVENT_IOC_QUERY_BPF);
+}
+
+int main(int argc, char **argv)
+{
+	if (argc == 2 && !strcmp(argv[1], EXECED_ARG))
+		return EXIT_SUCCESS;
+	return test_harness_run(argc, argv);
+}

-- 
2.53.0


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH RFC 08/19] selftests/exec: test exec with a shared signal table
  2026-11-24 22:58 [PATCH RFC 00/19] exec: move sleeping work out of exec_update_lock Christian Brauner
                   ` (6 preceding siblings ...)
  2026-11-24 22:58 ` [PATCH RFC 07/19] selftests/exec: test exec with a task sleeping in a page fault Christian Brauner
@ 2026-11-24 22:58 ` Christian Brauner
  2026-11-24 22:58 ` [PATCH RFC 09/19] lsm: add security_bprm_revalidate_files() Christian Brauner
                   ` (11 subsequent siblings)
  19 siblings, 0 replies; 22+ messages in thread
From: Christian Brauner @ 2026-11-24 22:58 UTC (permalink / raw)
  To: Jann Horn
  Cc: Linus Torvalds, linux-fsdevel, Arnaldo Carvalho de Melo,
	linux-perf-users, bpf, selinux, Kees Cook, linux-mm,
	linux-security-module, apparmor, David Hildenbrand,
	Christian Brauner (Amutable)

Test that exec gives a task that shares its signal table with another
process a private one:

- handlers the processes shared are reset in the new image

- an ignored signal stays ignored in the new image

- the other process keeps all of its handlers

- a signal the other process ignores right after vfork() returned isn't
  ignored in the new image

The task is created with CLONE_SIGHAND but without CLONE_THREAD so it
isn't taken care of by de_thread(). For the last one the parent runs in
a realtime scheduling class on the cpu of the task so that it gets to
ignore the signal as soon as it's woken up.

Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
---
 tools/testing/selftests/exec/.gitignore        |   1 +
 tools/testing/selftests/exec/Makefile          |   2 +
 tools/testing/selftests/exec/unshare-sighand.c | 236 +++++++++++++++++++++++++
 3 files changed, 239 insertions(+)

diff --git a/tools/testing/selftests/exec/.gitignore b/tools/testing/selftests/exec/.gitignore
index 4613c68537395..b27f4db42f87b 100644
--- a/tools/testing/selftests/exec/.gitignore
+++ b/tools/testing/selftests/exec/.gitignore
@@ -16,6 +16,7 @@ null-argv
 !load_address.c
 /recursion-depth
 /set-exec
+/unshare-sighand
 /update-lock-fault
 xxxxxxxx*
 pipe
diff --git a/tools/testing/selftests/exec/Makefile b/tools/testing/selftests/exec/Makefile
index 3756a250f9591..70f090a5f7648 100644
--- a/tools/testing/selftests/exec/Makefile
+++ b/tools/testing/selftests/exec/Makefile
@@ -21,6 +21,7 @@ TEST_GEN_PROGS += recursion-depth
 TEST_GEN_PROGS += null-argv
 TEST_GEN_PROGS += check-exec
 TEST_GEN_PROGS += update-lock-fault
+TEST_GEN_PROGS += unshare-sighand
 
 # binfmt_misc must not be reachable as an exec source or as a stacking layer,
 # or an 'F' entry can pin the instance that owns it. Unprivileged, no bpf.
@@ -117,6 +118,7 @@ $(OUTPUT)/binfmt_misc_interplimit: CFLAGS += $(TOOLS_INCLUDES)
 $(OUTPUT)/binfmt_misc_interplimit: ../filesystems/utils.c
 
 $(OUTPUT)/update-lock-fault: LDLIBS += -lpthread
+$(OUTPUT)/unshare-sighand: LDLIBS += -lpthread
 
 # --- binfmt_misc bpf ('B') handler test ---------------------------------
 # The struct_ops bpf objects are compiled against the running kernel's BTF.
diff --git a/tools/testing/selftests/exec/unshare-sighand.c b/tools/testing/selftests/exec/unshare-sighand.c
new file mode 100644
index 0000000000000..425b46d4d5c9c
--- /dev/null
+++ b/tools/testing/selftests/exec/unshare-sighand.c
@@ -0,0 +1,236 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Test exec in a task that shares its signal table with another process
+ * without being one of its threads, i.e. CLONE_SIGHAND without CLONE_THREAD.
+ * The exec has to give the task a private table before it resets the
+ * handlers so the other process keeps the table they shared. If the other
+ * process waits for the task in vfork() the task has to have its private
+ * table before that process runs again.
+ */
+#define _GNU_SOURCE
+#include <pthread.h>
+#include <sched.h>
+#include <signal.h>
+#include <stdbool.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#include "kselftest_harness.h"
+
+#define STACK_SIZE	(64 * 1024)
+
+/* Makes the exec'd image check its dispositions. */
+#define EXECED_ARG	"execed"
+/* Makes the exec'd image check the signal its vfork() parent ignored. */
+#define EXECED_VFORK_ARG	"execed-vfork"
+
+/* Exit status of a sharer that never made it into the exec'd image. */
+#define EXIT_NO_EXEC	127
+
+/* Handled before the clone. */
+static const int handled_signals[] = { SIGUSR1, SIGUSR2 };
+/* Handled by the sharer right before its exec. */
+#define SHARER_SIGNAL	SIGTERM
+/* Ignored before the clone. */
+#define IGNORED_SIGNAL	SIGHUP
+/* Ignored by a vfork() parent as soon as it runs again. */
+#define VFORK_SIGNAL	SIGINT
+
+/* How often a vfork() parent races with the exec of its child. */
+#define VFORK_ROUNDS	16
+
+/* How much the thread that holds the mmap lock has to work on. */
+#define WRITER_SIZE	(1UL << 30)
+
+static void handler(int sig)
+{
+}
+
+static int set_disposition(int sig, sighandler_t disposition)
+{
+	const struct sigaction sa = { .sa_handler = disposition };
+
+	return sigaction(sig, &sa, NULL);
+}
+
+static const char *disposition_name(sighandler_t disposition)
+{
+	if (disposition == SIG_DFL)
+		return "default";
+	if (disposition == SIG_IGN)
+		return "ignored";
+	return "handled";
+}
+
+static bool has_disposition(const char *who, int sig, sighandler_t disposition)
+{
+	struct sigaction sa;
+
+	if (sigaction(sig, NULL, &sa))
+		return false;
+	ksft_print_msg("%s: signal %d (%s) is %s\n", who, sig, strsignal(sig),
+		       disposition_name(sa.sa_handler));
+	return sa.sa_handler == disposition;
+}
+
+/* The signals with a handler must have @handled, the ignored one SIG_IGN. */
+static bool check_dispositions(const char *who, sighandler_t handled)
+{
+	bool ret = true;
+	unsigned int i;
+
+	for (i = 0; i < ARRAY_SIZE(handled_signals); i++)
+		ret &= has_disposition(who, handled_signals[i], handled);
+	ret &= has_disposition(who, SHARER_SIGNAL, handled);
+	ret &= has_disposition(who, IGNORED_SIGNAL, SIG_IGN);
+	return ret;
+}
+
+static int setup_dispositions(void)
+{
+	unsigned int i;
+
+	for (i = 0; i < ARRAY_SIZE(handled_signals); i++) {
+		if (set_disposition(handled_signals[i], handler))
+			return -1;
+	}
+	return set_disposition(IGNORED_SIGNAL, SIG_IGN);
+}
+
+static int sharer(void *arg)
+{
+	/* The parent only gets to see this if the table really is shared. */
+	if (!set_disposition(SHARER_SIGNAL, handler))
+		execl("/proc/self/exe", "unshare-sighand", EXECED_ARG,
+		      (char *)NULL);
+	_exit(EXIT_NO_EXEC);
+}
+
+TEST(exec_unshares_sighand)
+{
+	char *stack;
+	int status;
+	pid_t pid;
+
+	ASSERT_EQ(setup_dispositions(), 0);
+
+	stack = mmap(NULL, STACK_SIZE, PROT_READ | PROT_WRITE,
+		     MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);
+	ASSERT_NE(stack, MAP_FAILED);
+
+	pid = clone(sharer, stack + STACK_SIZE,
+		    CLONE_VM | CLONE_SIGHAND | SIGCHLD, NULL);
+	ASSERT_GT(pid, 0);
+	ASSERT_EQ(waitpid(pid, &status, 0), pid);
+	ASSERT_TRUE(WIFEXITED(status));
+	/* The exec'd image has the handlers reset and SIG_IGN inherited. */
+	EXPECT_EQ(WEXITSTATUS(status), EXIT_SUCCESS);
+
+	/* The table was shared up to the exec and the exec left it alone. */
+	EXPECT_TRUE(check_dispositions("parent", handler));
+
+	EXPECT_EQ(munmap(stack, STACK_SIZE), 0);
+}
+
+struct mmap_writer {
+	pthread_t thread;
+	char *map;
+	bool stop;
+};
+
+/*
+ * Hold the mmap lock for writing most of the time. An exec that waits for
+ * the mmap lock of the old mm after it has woken up a vfork() parent gives
+ * that parent all the time it needs.
+ */
+static void *mmap_writer(void *arg)
+{
+	struct mmap_writer *writer = arg;
+
+	while (!__atomic_load_n(&writer->stop, __ATOMIC_RELAXED)) {
+		mprotect(writer->map, WRITER_SIZE, PROT_NONE);
+		mprotect(writer->map, WRITER_SIZE, PROT_READ);
+	}
+	return NULL;
+}
+
+static int vfork_sharer(void *arg)
+{
+	execl("/proc/self/exe", "unshare-sighand", EXECED_VFORK_ARG,
+	      (char *)NULL);
+	_exit(EXIT_NO_EXEC);
+}
+
+TEST(exec_unshares_sighand_before_vfork_returns)
+{
+	struct sched_param param = { .sched_priority = 1 };
+	struct mmap_writer writer = {};
+	cpu_set_t cpu;
+	char *stack;
+	int status;
+	pid_t pid;
+	int i;
+
+	stack = mmap(NULL, STACK_SIZE, PROT_READ | PROT_WRITE,
+		     MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);
+	ASSERT_NE(stack, MAP_FAILED);
+
+	/* One page table entry per page, all of them the zero page. */
+	writer.map = mmap(NULL, WRITER_SIZE, PROT_READ,
+			  MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
+	ASSERT_NE(writer.map, MAP_FAILED);
+	madvise(writer.map, WRITER_SIZE, MADV_NOHUGEPAGE);
+	madvise(writer.map, WRITER_SIZE, MADV_POPULATE_READ);
+	ASSERT_EQ(pthread_create(&writer.thread, NULL, mmap_writer, &writer), 0);
+
+	/*
+	 * The task that is cloned below runs on our cpu and, as the policy
+	 * isn't inherited, not in a realtime scheduling class. On a kernel
+	 * with preemption we run as soon as it wakes us up and it doesn't get
+	 * any further meanwhile. Without the privilege for that only an exec
+	 * that sleeps after it has woken us up is caught.
+	 */
+	CPU_ZERO(&cpu);
+	CPU_SET(sched_getcpu(), &cpu);
+	if (!sched_setaffinity(0, sizeof(cpu), &cpu))
+		sched_setscheduler(0, SCHED_FIFO | SCHED_RESET_ON_FORK, &param);
+
+	for (i = 0; i < VFORK_ROUNDS; i++) {
+		ASSERT_EQ(set_disposition(VFORK_SIGNAL, SIG_DFL), 0);
+
+		pid = clone(vfork_sharer, stack + STACK_SIZE,
+			    CLONE_VM | CLONE_VFORK | CLONE_SIGHAND | SIGCHLD,
+			    NULL);
+		/* The task has its own table. This is none of its business. */
+		set_disposition(VFORK_SIGNAL, SIG_IGN);
+		ASSERT_GT(pid, 0);
+		ASSERT_EQ(waitpid(pid, &status, 0), pid);
+		ASSERT_TRUE(WIFEXITED(status));
+		ASSERT_EQ(WEXITSTATUS(status), EXIT_SUCCESS) {
+			TH_LOG("round %d: ignored after vfork(), ignored in the exec'd image", i);
+		}
+	}
+
+	__atomic_store_n(&writer.stop, true, __ATOMIC_RELAXED);
+	ASSERT_EQ(pthread_join(writer.thread, NULL), 0);
+	EXPECT_EQ(munmap(writer.map, WRITER_SIZE), 0);
+	EXPECT_EQ(munmap(stack, STACK_SIZE), 0);
+}
+
+int main(int argc, char **argv)
+{
+	struct sigaction sa;
+
+	if (argc == 2 && !strcmp(argv[1], EXECED_ARG))
+		return check_dispositions("exec'd image", SIG_DFL) ?
+		       EXIT_SUCCESS : EXIT_FAILURE;
+	if (argc == 2 && !strcmp(argv[1], EXECED_VFORK_ARG)) {
+		if (sigaction(VFORK_SIGNAL, NULL, &sa))
+			return EXIT_FAILURE;
+		return sa.sa_handler == SIG_DFL ? EXIT_SUCCESS : EXIT_FAILURE;
+	}
+	return test_harness_run(argc, argv);
+}

-- 
2.53.0


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH RFC 09/19] lsm: add security_bprm_revalidate_files()
  2026-11-24 22:58 [PATCH RFC 00/19] exec: move sleeping work out of exec_update_lock Christian Brauner
                   ` (7 preceding siblings ...)
  2026-11-24 22:58 ` [PATCH RFC 08/19] selftests/exec: test exec with a shared signal table Christian Brauner
@ 2026-11-24 22:58 ` Christian Brauner
  2026-11-24 22:58 ` [PATCH RFC 10/19] bpf: mark bprm_revalidate_files as sleepable Christian Brauner
                   ` (10 subsequent siblings)
  19 siblings, 0 replies; 22+ messages in thread
From: Christian Brauner @ 2026-11-24 22:58 UTC (permalink / raw)
  To: Jann Horn
  Cc: Linus Torvalds, linux-fsdevel, Arnaldo Carvalho de Melo,
	linux-perf-users, bpf, selinux, Kees Cook, linux-mm,
	linux-security-module, apparmor, David Hildenbrand,
	Christian Brauner (Amutable), stable

SELinux and AppArmor revalidate the controlling terminal and the
inherited files during exec when the security context changes. Files
the new credentials aren't allowed to use are replaced with the null
device or closed and a controlling terminal they aren't allowed to use
is dropped. Currently, they do this from the bprm_committing_creds hook
which begin_new_exec() calls with exec_update_lock held.

Closing a file calls into the filesystem's ->flush() method and that may
block for a long time. For the same reason commit e780259b54e6 ("exec:
do_close_on_exec() before taking exec_update_lock") moved the closing of
close-on-exec files in front of exec_update_lock.

Add a new hook that is called right after the close-on-exec files have
been closed. At that point we're past the point of no return, all other
threads are gone and the file descriptor table isn't shared anymore. So
nobody but the task itself can install new files or acquire a new
controlling terminal until the new credentials are committed. And
nothing between the new hook and the bprm_committing_creds hook touches
the file descriptor table.

The hook has no users yet. SELinux and AppArmor are switched over
separately. Note that bpf lsm programs can attach to it like to any
other LSM hook.

Fixes: 6650527444da ("proc: protect ptrace_may_access() with exec_update_lock (part 1)")
Cc: stable@vger.kernel.org
Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
---
 fs/exec.c                     |  3 +++
 include/linux/lsm_hook_defs.h |  1 +
 include/linux/security.h      |  5 +++++
 security/security.c           | 27 ++++++++++++++++++++++++---
 4 files changed, 33 insertions(+), 3 deletions(-)

diff --git a/fs/exec.c b/fs/exec.c
index 87b78fce609de..855437c352137 100644
--- a/fs/exec.c
+++ b/fs/exec.c
@@ -1203,6 +1203,9 @@ int begin_new_exec(struct linux_binprm * bprm)
 	 */
 	close_cloexec_files(me->files);
 
+	/* Let LSMs revoke inherited files the new creds may not use. */
+	security_bprm_revalidate_files(bprm);
+
 	/*
 	 * Must be called _before_ exec_mmap() as bprm->mm is
 	 * not visible until then. Doing it here also ensures
diff --git a/include/linux/lsm_hook_defs.h b/include/linux/lsm_hook_defs.h
index 87d9d06710cb2..c1bb7501d530d 100644
--- a/include/linux/lsm_hook_defs.h
+++ b/include/linux/lsm_hook_defs.h
@@ -52,6 +52,7 @@ LSM_HOOK(int, 0, vm_enough_memory, struct mm_struct *mm, long pages)
 LSM_HOOK(int, 0, bprm_creds_for_exec, struct linux_binprm *bprm)
 LSM_HOOK(int, 0, bprm_creds_from_file, struct linux_binprm *bprm, const struct file *file)
 LSM_HOOK(int, 0, bprm_check_security, struct linux_binprm *bprm)
+LSM_HOOK(void, LSM_RET_VOID, bprm_revalidate_files, const struct linux_binprm *bprm)
 LSM_HOOK(void, LSM_RET_VOID, bprm_committing_creds, const struct linux_binprm *bprm)
 LSM_HOOK(void, LSM_RET_VOID, bprm_committed_creds, const struct linux_binprm *bprm)
 LSM_HOOK(int, 0, fs_context_submount, struct fs_context *fc, struct super_block *reference)
diff --git a/include/linux/security.h b/include/linux/security.h
index 40831fab54709..e1a85b2f7005e 100644
--- a/include/linux/security.h
+++ b/include/linux/security.h
@@ -360,6 +360,7 @@ int security_vm_enough_memory_mm(struct mm_struct *mm, long pages);
 int security_bprm_creds_for_exec(struct linux_binprm *bprm);
 int security_bprm_creds_from_file(struct linux_binprm *bprm, const struct file *file);
 int security_bprm_check(struct linux_binprm *bprm);
+void security_bprm_revalidate_files(const struct linux_binprm *bprm);
 void security_bprm_committing_creds(const struct linux_binprm *bprm);
 void security_bprm_committed_creds(const struct linux_binprm *bprm);
 int security_fs_context_submount(struct fs_context *fc, struct super_block *reference);
@@ -753,6 +754,10 @@ static inline int security_bprm_check(struct linux_binprm *bprm)
 	return 0;
 }
 
+static inline void security_bprm_revalidate_files(const struct linux_binprm *bprm)
+{
+}
+
 static inline void security_bprm_committing_creds(const struct linux_binprm *bprm)
 {
 }
diff --git a/security/security.c b/security/security.c
index 4727b8347fc4e..f340880ce77ff 100644
--- a/security/security.c
+++ b/security/security.c
@@ -834,6 +834,25 @@ int security_bprm_check(struct linux_binprm *bprm)
 	return call_int_hook(bprm_check_security, bprm);
 }
 
+/**
+ * security_bprm_revalidate_files() - Revalidate open files during exec()
+ * @bprm: binary program information
+ *
+ * Revalidate access to the controlling tty and the open file descriptors of a
+ * process being transformed by an execve operation, based on the old
+ * credentials pointed to by @current->cred and the information set in
+ * @bprm->cred by the bprm_creds_for_exec hook.  Files to which access will no
+ * longer be granted may be closed or replaced.  @bprm points to the
+ * linux_binprm structure.  This is called after the point of no return, once
+ * the file descriptor table has been unshared and close-on-exec files have been
+ * closed, but before exec_update_lock is taken, as closing a file may block in
+ * the filesystem.
+ */
+void security_bprm_revalidate_files(const struct linux_binprm *bprm)
+{
+	call_void_hook(bprm_revalidate_files, bprm);
+}
+
 /**
  * security_bprm_committing_creds() - Install creds for a process during exec()
  * @bprm: binary program information
@@ -842,9 +861,11 @@ int security_bprm_check(struct linux_binprm *bprm)
  * transformed by an execve operation, based on the old credentials pointed to
  * by @current->cred and the information set in @bprm->cred by the
  * bprm_creds_for_exec hook.  @bprm points to the linux_binprm structure.  This
- * hook is a good place to perform state changes on the process such as closing
- * open file descriptors to which access will no longer be granted when the
- * attributes are changed.  This is called immediately before commit_creds().
+ * hook is a good place to perform state changes on the process such as
+ * resetting resource limits.  It is called with exec_update_lock held so it
+ * should not block on a filesystem.  In particular, it must not close files.
+ * Use the bprm_revalidate_files hook for that.  This is called immediately
+ * before commit_creds().
  */
 void security_bprm_committing_creds(const struct linux_binprm *bprm)
 {

-- 
2.53.0


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH RFC 10/19] bpf: mark bprm_revalidate_files as sleepable
  2026-11-24 22:58 [PATCH RFC 00/19] exec: move sleeping work out of exec_update_lock Christian Brauner
                   ` (8 preceding siblings ...)
  2026-11-24 22:58 ` [PATCH RFC 09/19] lsm: add security_bprm_revalidate_files() Christian Brauner
@ 2026-11-24 22:58 ` Christian Brauner
  2026-11-24 22:58 ` [PATCH RFC 11/19] selinux: revalidate inherited files before taking exec_update_lock Christian Brauner
                   ` (9 subsequent siblings)
  19 siblings, 0 replies; 22+ messages in thread
From: Christian Brauner @ 2026-11-24 22:58 UTC (permalink / raw)
  To: Jann Horn
  Cc: Linus Torvalds, linux-fsdevel, Arnaldo Carvalho de Melo,
	linux-perf-users, bpf, selinux, Kees Cook, linux-mm,
	linux-security-module, apparmor, David Hildenbrand,
	Christian Brauner (Amutable)

The bprm_revalidate_files hook is called from begin_new_exec() right
after the close-on-exec files have been closed. It only exists so that
an LSM can revoke inherited files before exec_update_lock is taken as
that may block on the filesystem. So it's always called from sleepable
context.

Add it to sleepable_lsm_hooks so that sleepable bpf lsm programs can
attach to it. All the other bprm hooks are sleepable already.

Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
---
 kernel/bpf/bpf_lsm.c | 1 +
 1 file changed, 1 insertion(+)

diff --git a/kernel/bpf/bpf_lsm.c b/kernel/bpf/bpf_lsm.c
index 468e63dbd922d..df6ee6e3674dd 100644
--- a/kernel/bpf/bpf_lsm.c
+++ b/kernel/bpf/bpf_lsm.c
@@ -324,6 +324,7 @@ BTF_ID(func, bpf_lsm_bprm_committed_creds)
 BTF_ID(func, bpf_lsm_bprm_committing_creds)
 BTF_ID(func, bpf_lsm_bprm_creds_for_exec)
 BTF_ID(func, bpf_lsm_bprm_creds_from_file)
+BTF_ID(func, bpf_lsm_bprm_revalidate_files)
 BTF_ID(func, bpf_lsm_capget)
 BTF_ID(func, bpf_lsm_capset)
 BTF_ID(func, bpf_lsm_cred_prepare)

-- 
2.53.0


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH RFC 11/19] selinux: revalidate inherited files before taking exec_update_lock
  2026-11-24 22:58 [PATCH RFC 00/19] exec: move sleeping work out of exec_update_lock Christian Brauner
                   ` (9 preceding siblings ...)
  2026-11-24 22:58 ` [PATCH RFC 10/19] bpf: mark bprm_revalidate_files as sleepable Christian Brauner
@ 2026-11-24 22:58 ` Christian Brauner
  2026-11-24 22:58 ` [PATCH RFC 12/19] apparmor: " Christian Brauner
                   ` (8 subsequent siblings)
  19 siblings, 0 replies; 22+ messages in thread
From: Christian Brauner @ 2026-11-24 22:58 UTC (permalink / raw)
  To: Jann Horn
  Cc: Linus Torvalds, linux-fsdevel, Arnaldo Carvalho de Melo,
	linux-perf-users, bpf, selinux, Kees Cook, linux-mm,
	linux-security-module, apparmor, David Hildenbrand,
	Christian Brauner (Amutable), stable

When an exec transitions to a new SID flush_unauthorized_files()
revalidates the controlling terminal and the inherited files against the
new SID. Files the new SID isn't allowed to use are replaced with the
null device. This is done from selinux_bprm_committing_creds() which
runs with exec_update_lock held for writing.

Replacing a file closes the old one and so calls its ->flush() method
which can block waiting on the filesystem. So a hung filesystem blocks
everyone who needs the exec_update_lock of that task. And a FUSE server
that looks at the task it serves the flush request for deadlocks:

  exec                                 FUSE server
  begin_new_exec()
    exec_mmap()
      down_write(exec_update_lock)
    security_bprm_committing_creds()
      flush_unauthorized_files()
        replace_fd()
          filp_close()
            fuse_flush()
                                       do_task_stat()
                                         down_read(exec_update_lock)

With a FUSE server that reads /proc/<pid>/stat of the task that sent the
flush request the exec hangs until the server is killed:

  task:se-target       state:S pid:143
  Call Trace:
   __schedule+0x53e/0x13f0
   schedule+0x36/0x100
   request_wait_answer+0x1a9/0x320
   fuse_chan_send+0x110/0x250
   fuse_flush+0x1af/0x1f0
   filp_flush+0x33/0x90
   filp_close+0x12/0x30
   do_dup2+0xbf/0x1b0
   replace_fd+0x7e/0xd0
   selinux_bprm_committing_creds+0x1a7/0x2d0
   security_bprm_committing_creds+0x1e/0x30
   begin_new_exec+0x6dc/0xf90
   load_elf_binary+0x12a/0x1990
   bprm_execve+0x39d/0x870
   do_execveat_common.isra.0+0x165/0x180
   __x64_sys_execve+0x38/0x50
   do_syscall_64+0x110/0x600
   entry_SYSCALL_64_after_hwframe+0x77/0x7f

  task:se-fuse         state:D pid:142
  Call Trace:
   __schedule+0x53e/0x13f0
   schedule+0x36/0x100
   schedule_preempt_disabled+0x11/0x20
   rwsem_down_read_slowpath+0x186/0x5f0
   down_read_killable+0x78/0x1b0
   do_task_stat+0x87/0x10c0
   proc_single_show+0x67/0xe0
   seq_read_iter+0x11c/0x480
   seq_read+0x127/0x1c0
   vfs_read+0xd8/0x4a0
   ksys_read+0x7c/0x110
   do_syscall_64+0x110/0x600
   entry_SYSCALL_64_after_hwframe+0x77/0x7f

The flush is a forced request so the exec can't even be killed while it
waits for the reply.

This is the same problem that commit e780259b54e6 ("exec:
do_close_on_exec() before taking exec_update_lock") fixed for
close-on-exec files.

Fix this by moving the revalidation into the new bprm_revalidate_files
hook which is called before exec_update_lock is taken.

Fixes: 6650527444da ("proc: protect ptrace_may_access() with exec_update_lock (part 1)")
Cc: stable@vger.kernel.org
Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
---
 security/selinux/hooks.c | 18 +++++++++++++++---
 1 file changed, 15 insertions(+), 3 deletions(-)

diff --git a/security/selinux/hooks.c b/security/selinux/hooks.c
index 4ec9ec723cacc..71ea94f663772 100644
--- a/security/selinux/hooks.c
+++ b/security/selinux/hooks.c
@@ -2529,6 +2529,20 @@ static inline void flush_unauthorized_files(const struct cred *cred,
 		fput(devnull);
 }
 
+/*
+ * Close files for which the new task SID is not authorized. Called before
+ * exec_update_lock is taken as closing files may block in the filesystem.
+ */
+static void selinux_bprm_revalidate_files(const struct linux_binprm *bprm)
+{
+	const struct cred_security_struct *new_crsec = selinux_cred(bprm->cred);
+
+	if (new_crsec->sid == new_crsec->osid)
+		return;
+
+	flush_unauthorized_files(bprm->cred, current->files);
+}
+
 /*
  * Prepare a process for imminent new credential changes due to exec
  */
@@ -2542,9 +2556,6 @@ static void selinux_bprm_committing_creds(const struct linux_binprm *bprm)
 	if (new_crsec->sid == new_crsec->osid)
 		return;
 
-	/* Close files for which the new task SID is not authorized. */
-	flush_unauthorized_files(bprm->cred, current->files);
-
 	/* Always clear parent death signal on SID transitions. */
 	current->pdeath_signal = 0;
 
@@ -7690,6 +7701,7 @@ static struct security_hook_list selinux_hooks[] __ro_after_init = {
 	LSM_HOOK_INIT(netlink_send, selinux_netlink_send),
 
 	LSM_HOOK_INIT(bprm_creds_for_exec, selinux_bprm_creds_for_exec),
+	LSM_HOOK_INIT(bprm_revalidate_files, selinux_bprm_revalidate_files),
 	LSM_HOOK_INIT(bprm_committing_creds, selinux_bprm_committing_creds),
 	LSM_HOOK_INIT(bprm_committed_creds, selinux_bprm_committed_creds),
 

-- 
2.53.0


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH RFC 12/19] apparmor: revalidate inherited files before taking exec_update_lock
  2026-11-24 22:58 [PATCH RFC 00/19] exec: move sleeping work out of exec_update_lock Christian Brauner
                   ` (10 preceding siblings ...)
  2026-11-24 22:58 ` [PATCH RFC 11/19] selinux: revalidate inherited files before taking exec_update_lock Christian Brauner
@ 2026-11-24 22:58 ` Christian Brauner
  2026-11-24 22:58 ` [PATCH RFC 13/19] exec: drop exec_update_lock after the credentials are committed Christian Brauner
                   ` (7 subsequent siblings)
  19 siblings, 0 replies; 22+ messages in thread
From: Christian Brauner @ 2026-11-24 22:58 UTC (permalink / raw)
  To: Jann Horn
  Cc: Linus Torvalds, linux-fsdevel, Arnaldo Carvalho de Melo,
	linux-perf-users, bpf, selinux, Kees Cook, linux-mm,
	linux-security-module, apparmor, David Hildenbrand,
	Christian Brauner (Amutable), stable

When an exec changes the profile aa_inherit_files() revalidates the
controlling terminal and the inherited files against the new label.
Everything the new label isn't allowed to use is taken away from the
task. This is done from apparmor_bprm_committing_creds() which runs with
exec_update_lock held for writing.

Taking a file away closes it and so calls its ->flush() method which can
block waiting on the filesystem. So a hung filesystem blocks everyone
who needs the exec_update_lock of that task. And a FUSE server that
looks at the task it serves the flush request for deadlocks:

  exec                                 FUSE server
  begin_new_exec()
    exec_mmap()
      down_write(exec_update_lock)
    security_bprm_committing_creds()
      aa_inherit_files()
        replace_fd()
          filp_close()
            fuse_flush()
                                       do_task_stat()
                                         down_read(exec_update_lock)

With a FUSE server that reads /proc/<pid>/stat of the task that sent the
flush request the exec hangs until the server is killed:

  task:aa-target       state:S pid:98
  Call Trace:
   __schedule+0x53e/0x13f0
   schedule+0x36/0x100
   request_wait_answer+0x1a9/0x320
   fuse_chan_send+0x110/0x250
   fuse_flush+0x1af/0x1f0
   filp_flush+0x33/0x90
   filp_close+0x12/0x30
   aa_inherit_files+0x191/0x2a0
   apparmor_bprm_committing_creds+0x61/0x90
   security_bprm_committing_creds+0x19/0x30
   begin_new_exec+0x6dc/0xf90
   load_elf_binary+0x12a/0x1990
   bprm_execve+0x39d/0x870
   do_execveat_common.isra.0+0x165/0x180
   __x64_sys_execve+0x38/0x50
   do_syscall_64+0x110/0x600
   entry_SYSCALL_64_after_hwframe+0x77/0x7f

  task:aa-fuse         state:D pid:97
  Call Trace:
   __schedule+0x53e/0x13f0
   schedule+0x36/0x100
   schedule_preempt_disabled+0x11/0x20
   rwsem_down_read_slowpath+0x186/0x5f0
   down_read_killable+0x78/0x1b0
   do_task_stat+0x87/0x10c0
   proc_single_show+0x67/0xe0
   seq_read_iter+0x11c/0x480
   seq_read+0x127/0x1c0
   vfs_read+0xd8/0x4a0
   ksys_read+0x7c/0x110
   do_syscall_64+0x110/0x600
   entry_SYSCALL_64_after_hwframe+0x77/0x7f

The flush is a forced request so the exec can't even be killed while it
waits for the reply.

This is the same problem that commit e780259b54e6 ("exec:
do_close_on_exec() before taking exec_update_lock") fixed for
close-on-exec files.

Fix this by moving the revalidation into the new bprm_revalidate_files
hook which is called before exec_update_lock is taken.

Fixes: 6650527444da ("proc: protect ptrace_may_access() with exec_update_lock (part 1)")
Cc: stable@vger.kernel.org
Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
---
 security/apparmor/lsm.c | 23 +++++++++++++++++++++--
 1 file changed, 21 insertions(+), 2 deletions(-)

diff --git a/security/apparmor/lsm.c b/security/apparmor/lsm.c
index eaebc3c60c5af..e40619b0f4ba9 100644
--- a/security/apparmor/lsm.c
+++ b/security/apparmor/lsm.c
@@ -951,10 +951,13 @@ static int apparmor_setprocattr(const char *name, void *value,
 }
 
 /**
- * apparmor_bprm_committing_creds - do task cleanup on committing new creds
+ * apparmor_bprm_revalidate_files - revalidate inherited files on exec
  * @bprm: binprm for the exec  (NOT NULL)
+ *
+ * Called before exec_update_lock is taken as closing files may block in
+ * the filesystem.
  */
-static void apparmor_bprm_committing_creds(const struct linux_binprm *bprm)
+static void apparmor_bprm_revalidate_files(const struct linux_binprm *bprm)
 {
 	struct aa_label *label = aa_current_raw_label();
 	struct aa_label *new_label = cred_label(bprm->cred);
@@ -965,6 +968,21 @@ static void apparmor_bprm_committing_creds(const struct linux_binprm *bprm)
 		return;
 
 	aa_inherit_files(bprm->cred, current->files);
+}
+
+/**
+ * apparmor_bprm_committing_creds - do task cleanup on committing new creds
+ * @bprm: binprm for the exec  (NOT NULL)
+ */
+static void apparmor_bprm_committing_creds(const struct linux_binprm *bprm)
+{
+	struct aa_label *label = aa_current_raw_label();
+	struct aa_label *new_label = cred_label(bprm->cred);
+
+	/* bail out if unconfined or not changing profile */
+	if ((new_label->proxy == label->proxy) ||
+	    (unconfined(new_label)))
+		return;
 
 	current->pdeath_signal = 0;
 
@@ -1860,6 +1878,7 @@ static struct security_hook_list apparmor_hooks[] __ro_after_init = {
 	LSM_HOOK_INIT(cred_transfer, apparmor_cred_transfer),
 
 	LSM_HOOK_INIT(bprm_creds_for_exec, apparmor_bprm_creds_for_exec),
+	LSM_HOOK_INIT(bprm_revalidate_files, apparmor_bprm_revalidate_files),
 	LSM_HOOK_INIT(bprm_committing_creds, apparmor_bprm_committing_creds),
 	LSM_HOOK_INIT(bprm_committed_creds, apparmor_bprm_committed_creds),
 

-- 
2.53.0


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH RFC 13/19] exec: drop exec_update_lock after the credentials are committed
  2026-11-24 22:58 [PATCH RFC 00/19] exec: move sleeping work out of exec_update_lock Christian Brauner
                   ` (11 preceding siblings ...)
  2026-11-24 22:58 ` [PATCH RFC 12/19] apparmor: " Christian Brauner
@ 2026-11-24 22:58 ` Christian Brauner
  2026-11-24 22:58 ` [PATCH RFC 14/19] exec: switch time namespace after dropping exec_update_lock Christian Brauner
                   ` (6 subsequent siblings)
  19 siblings, 0 replies; 22+ messages in thread
From: Christian Brauner @ 2026-11-24 22:58 UTC (permalink / raw)
  To: Jann Horn
  Cc: Linus Torvalds, linux-fsdevel, Arnaldo Carvalho de Melo,
	linux-perf-users, bpf, selinux, Kees Cook, linux-mm,
	linux-security-module, apparmor, David Hildenbrand,
	Christian Brauner (Amutable)

exec_update_lock makes sure that nobody who takes it can see the new mm
together with the old credentials. It is taken in exec_mmap() and
currently held until setup_new_exec().

When it was added in commit eea9673250db ("exec: Add exec_update_mutex
to replace cred_guard_mutex") it was dropped at the end of
install_exec_creds(), right after the new credentials were committed and
the LSMs had been told about it. Back then the personality and the mmap
layout were set up before the credentials were committed. They only
ended up between commit_creds() and the unlock when commit df9e4d2c4a53
("exec: Move most of setup_new_exec into flush_old_exec") moved the
credential commit into flush_old_exec() and left the unlock in
setup_new_exec().

Once the mm, the exec state and the credentials are switched and
perf_event_exit_task() has run every reader is checked against the new
credentials. But we still do a bunch of work with exec_update_lock held:

- security_bprm_committed_creds() which is a sleepable hook for bpf lsm
  programs

- installing the execfd which may have to grow the file descriptor table

- the binfmt setting the personality

- arch_pick_mmap_layout() and arch_setup_new_exec()

So drop it right after perf_event_exit_task(). The LSM hooks don't move
relative to commit_creds() and cred_guard_mutex is still held until
setup_new_exec() so nothing changes for ptrace.

While at it, fix the comments that still point to setup_new_exec(). It's
begin_new_exec() that commits the new credentials, changes whether the
task is dumpable and calls perf_event_exit_task().

Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
---
 fs/exec.c            | 39 ++++++++++++++++++++++++---------------
 kernel/events/core.c |  2 +-
 2 files changed, 25 insertions(+), 16 deletions(-)

diff --git a/fs/exec.c b/fs/exec.c
index 855437c352137..7b261b0a5f33c 100644
--- a/fs/exec.c
+++ b/fs/exec.c
@@ -837,8 +837,10 @@ EXPORT_SYMBOL(read_code);
 /*
  * Maps the mm_struct mm into the current task struct.
  * On success, this function returns with exec_update_lock
- * held for writing. The replaced address space is stashed in
- * bprm->old_mm for setup_new_exec() to release outside the lock.
+ * held for writing. begin_new_exec() drops it once the new
+ * credentials are committed. The replaced address space is
+ * stashed in bprm->old_mm for setup_new_exec() to release
+ * outside the exec locks.
  */
 static int exec_mmap(struct linux_binprm *bprm)
 {
@@ -1191,8 +1193,8 @@ int begin_new_exec(struct linux_binprm * bprm)
 
 	/*
 	 * We have to apply CLOEXEC before we change whether the process is
-	 * dumpable (in setup_new_exec) to avoid a race with a process in userspace
-	 * trying to access the should-be-closed file descriptors of a process
+	 * dumpable to avoid a race with a process in userspace trying to
+	 * access the should-be-closed file descriptors of a process
 	 * undergoing exec(2).
 	 *
 	 * This can block on filesystem ->flush() and ->release() handlers,
@@ -1232,7 +1234,7 @@ int begin_new_exec(struct linux_binprm * bprm)
 
 	retval = exec_task_namespaces();
 	if (retval)
-		goto out_unlock;
+		goto out_unlock_exec_update;
 
 	me->flags &= ~(PF_RANDOMIZE | PF_FORKNOEXEC |
 					PF_NOFREEZE | PF_NO_SETAFFINITY);
@@ -1303,7 +1305,7 @@ int begin_new_exec(struct linux_binprm * bprm)
 
 	retval = set_cred_ucounts(bprm->cred);
 	if (retval < 0)
-		goto out_unlock;
+		goto out_unlock_exec_update;
 
 	/*
 	 * install the new credentials for this executable
@@ -1321,6 +1323,10 @@ int begin_new_exec(struct linux_binprm * bprm)
 	 */
 	if (task_exec_state_get_dumpable(me) != TASK_DUMPABLE_OWNER)
 		perf_event_exit_task(me);
+
+	/* The mm, exec state and creds are switched. Let readers back in. */
+	up_write(&me->signal->exec_update_lock);
+
 	/*
 	 * cred_guard_mutex must be held at least to this point to prevent
 	 * ptrace_attach() from altering our determination of the task's
@@ -1339,17 +1345,20 @@ int begin_new_exec(struct linux_binprm * bprm)
 		if (retval < 0) {
 			/* The reference was not consumed. */
 			fput(executable);
-			goto out_unlock;
+			goto out_unlock_cred_guard;
 		}
 		bprm->execfd = retval;
 	}
 	return 0;
 
-out_unlock:
-	up_write(&me->signal->exec_update_lock);
-	if (!bprm->cred)
-		mutex_unlock(&me->signal->cred_guard_mutex);
+out_unlock_cred_guard:
+	/* free_bprm() only unlocks cred_guard_mutex if bprm->cred is set. */
+	mutex_unlock(&me->signal->cred_guard_mutex);
+	return retval;
 
+out_unlock_exec_update:
+	/* bprm->cred is still set so free_bprm() unlocks cred_guard_mutex. */
+	up_write(&me->signal->exec_update_lock);
 out:
 	return retval;
 }
@@ -1391,7 +1400,6 @@ void setup_new_exec(struct linux_binprm * bprm)
 	 * some architectures like powerpc
 	 */
 	me->mm->task_size = TASK_SIZE;
-	up_write(&me->signal->exec_update_lock);
 	mutex_unlock(&me->signal->cred_guard_mutex);
 
 	/* The exec locks are dropped: release the old address space now. */
@@ -1414,9 +1422,10 @@ EXPORT_SYMBOL(finalize_exec);
 
 /*
  * Prepare credentials and lock ->cred_guard_mutex.
- * setup_new_exec() commits the new creds and drops the lock.
- * Or, if exec fails before, free_bprm() should release ->cred
- * and unlock.
+ * begin_new_exec() commits the new creds and setup_new_exec()
+ * drops the lock. If exec fails before the creds are committed
+ * free_bprm() releases ->cred and unlocks. If it fails after
+ * that begin_new_exec() unlocks.
  */
 static int prepare_bprm_creds(struct linux_binprm *bprm)
 {
diff --git a/kernel/events/core.c b/kernel/events/core.c
index 5f648e00ae661..10612214e89cd 100644
--- a/kernel/events/core.c
+++ b/kernel/events/core.c
@@ -14871,7 +14871,7 @@ static void perf_event_exit_task_context(struct task_struct *task, bool exit)
  * When a task exits, feed back event values to parent events.
  *
  * Can be called with exec_update_lock held when called from
- * setup_new_exec().
+ * begin_new_exec().
  */
 void perf_event_exit_task(struct task_struct *task)
 {

-- 
2.53.0


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH RFC 14/19] exec: switch time namespace after dropping exec_update_lock
  2026-11-24 22:58 [PATCH RFC 00/19] exec: move sleeping work out of exec_update_lock Christian Brauner
                   ` (12 preceding siblings ...)
  2026-11-24 22:58 ` [PATCH RFC 13/19] exec: drop exec_update_lock after the credentials are committed Christian Brauner
@ 2026-11-24 22:58 ` Christian Brauner
  2026-11-24 22:58 ` [PATCH RFC 15/19] exec: don't take the mmap lock of the old mm Christian Brauner
                   ` (5 subsequent siblings)
  19 siblings, 0 replies; 22+ messages in thread
From: Christian Brauner @ 2026-11-24 22:58 UTC (permalink / raw)
  To: Jann Horn
  Cc: Linus Torvalds, linux-fsdevel, Arnaldo Carvalho de Melo,
	linux-perf-users, bpf, selinux, Kees Cook, linux-mm,
	linux-security-module, apparmor, David Hildenbrand,
	Christian Brauner (Amutable)

If the task has unshared its time namespace then exec moves it into the
new time namespace as it's getting a new mm. That allocates a new
nsproxy, may take the timens offset mutex and the mmap lock of the new
mm to switch the vdso data and may drop the last reference to the old
nsproxy. Currently, all of that happens with exec_update_lock held.

The time namespace switch isn't tied to the credentials changing. So do
it after exec_update_lock has been dropped. It still happens before the
vdso is mapped. Call it after security_bprm_committed_creds() so there's
no failure between committing the credentials and telling the LSMs about
it.

Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
---
 fs/exec.c | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)

diff --git a/fs/exec.c b/fs/exec.c
index 7b261b0a5f33c..6120310f3fbab 100644
--- a/fs/exec.c
+++ b/fs/exec.c
@@ -1232,10 +1232,6 @@ int begin_new_exec(struct linux_binprm * bprm)
 
 	bprm->mm = NULL;
 
-	retval = exec_task_namespaces();
-	if (retval)
-		goto out_unlock_exec_update;
-
 	me->flags &= ~(PF_RANDOMIZE | PF_FORKNOEXEC |
 					PF_NOFREEZE | PF_NO_SETAFFINITY);
 	flush_thread();
@@ -1334,6 +1330,11 @@ int begin_new_exec(struct linux_binprm * bprm)
 	 */
 	security_bprm_committed_creds(bprm);
 
+	/* Switch time namespace now that the task has a new mm. */
+	retval = exec_task_namespaces();
+	if (retval)
+		goto out_unlock_cred_guard;
+
 	/* Pass the opened binary to the interpreter. */
 	if (bprm->have_execfd) {
 		struct file *executable = bprm->executable;

-- 
2.53.0


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH RFC 15/19] exec: don't take the mmap lock of the old mm
  2026-11-24 22:58 [PATCH RFC 00/19] exec: move sleeping work out of exec_update_lock Christian Brauner
                   ` (13 preceding siblings ...)
  2026-11-24 22:58 ` [PATCH RFC 14/19] exec: switch time namespace after dropping exec_update_lock Christian Brauner
@ 2026-11-24 22:58 ` Christian Brauner
  2026-11-24 22:58 ` [PATCH RFC 16/19] exit: don't take the mmap lock in exit_mm() Christian Brauner
                   ` (4 subsequent siblings)
  19 siblings, 0 replies; 22+ messages in thread
From: Christian Brauner @ 2026-11-24 22:58 UTC (permalink / raw)
  To: Jann Horn
  Cc: Linus Torvalds, linux-fsdevel, Arnaldo Carvalho de Melo,
	linux-perf-users, bpf, selinux, Kees Cook, linux-mm,
	linux-security-module, apparmor, David Hildenbrand,
	Christian Brauner (Amutable)

exec_mmap() takes the mmap lock of the old mm for reading while it
switches the task over to the new mm. And it does that with
exec_update_lock held for writing.

That lock was only ever needed for coredumps. The coredump code used to
take the mmap lock for writing and then killed every task using the mm.
So exec had to check for a coredump in progress under the mmap lock
before it left the mm. Commit 7e3c4fb7fc19 ("exec: Check for a pending
fatal signal instead of core_state") replaced that check with
mmap_read_lock_killable(). And since commit 0258b5fd7c71 ("coredump:
Limit coredumps to a single thread group") a coredump doesn't kill
anything outside of its own thread-group and doesn't take the mmap lock
to find tasks anymore. An exec in the same thread-group is serialized
against the coredump in de_thread().

Nothing else relies on the mmap lock to keep a task from leaving its mm.

exit_mm() takes the mmap lock for the same historical reason. The next
patch removes that one.

Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
---
 fs/exec.c | 14 --------------
 1 file changed, 14 deletions(-)

diff --git a/fs/exec.c b/fs/exec.c
index 6120310f3fbab..78046ed839646 100644
--- a/fs/exec.c
+++ b/fs/exec.c
@@ -864,19 +864,6 @@ static int exec_mmap(struct linux_binprm *bprm)
 	if (ret)
 		return ret;
 
-	if (old_mm) {
-		/*
-		 * If there is a pending fatal signal perhaps a signal
-		 * whose default action is to create a coredump get
-		 * out and die instead of going through with the exec.
-		 */
-		ret = mmap_read_lock_killable(old_mm);
-		if (ret) {
-			up_write(&tsk->signal->exec_update_lock);
-			return ret;
-		}
-	}
-
 	task_lock(tsk);
 	membarrier_exec_mmap(mm);
 
@@ -903,7 +890,6 @@ static int exec_mmap(struct linux_binprm *bprm)
 	task_unlock(tsk);
 	lru_gen_use_mm(mm);
 	if (old_mm) {
-		mmap_read_unlock(old_mm);
 		BUG_ON(active_mm != old_mm);
 		/* Defer teardown to setup_new_exec(), outside the exec locks. */
 		bprm->old_mm = old_mm;

-- 
2.53.0


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH RFC 16/19] exit: don't take the mmap lock in exit_mm()
  2026-11-24 22:58 [PATCH RFC 00/19] exec: move sleeping work out of exec_update_lock Christian Brauner
                   ` (14 preceding siblings ...)
  2026-11-24 22:58 ` [PATCH RFC 15/19] exec: don't take the mmap lock of the old mm Christian Brauner
@ 2026-11-24 22:58 ` Christian Brauner
  2026-11-24 22:58 ` [PATCH RFC 17/19] proc: look up map_files vma without exec_update_lock held Christian Brauner
                   ` (3 subsequent siblings)
  19 siblings, 0 replies; 22+ messages in thread
From: Christian Brauner @ 2026-11-24 22:58 UTC (permalink / raw)
  To: Jann Horn
  Cc: Linus Torvalds, linux-fsdevel, Arnaldo Carvalho de Melo,
	linux-perf-users, bpf, selinux, Kees Cook, linux-mm,
	linux-security-module, apparmor, David Hildenbrand,
	Christian Brauner (Amutable)

exit_mm() takes the mmap lock for reading around clearing current->mm.
That goes back to 2003 (cf. [1]). A coredump took the lock for writing
and counted every thread that had an mm in mm->core_waiters. An exiting
thread had to look at core_waiters and clear its mm without the dumping
thread getting in between.

Commit 92307383082d ("coredump:  Don't perform any cleanups before
dumping core") moved that check into coredump_task_exit() which runs
before exit_mm(). And commit 0258b5fd7c71 ("coredump: Limit coredumps to
a single thread group") moved core_state into signal_struct and the
check under siglock. Since then the lock in exit_mm() doesn't protect
anything a coredump looks at.

So don't take it.

While at it, drop the comment that calls task_lock() more a memory
barrier than a real lock. It's the only lock that's left around clearing
current->mm.

[1]: https://git.kernel.org/pub/scm/linux/kernel/git/history/history.git/commit/?id=99365bd4725d431255ff4bdd51fb3dca60c47322

Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
---
 kernel/exit.c | 3 ---
 1 file changed, 3 deletions(-)

diff --git a/kernel/exit.c b/kernel/exit.c
index d5e7bc2af804a..38de318a07aaa 100644
--- a/kernel/exit.c
+++ b/kernel/exit.c
@@ -559,10 +559,8 @@ static void exit_mm(void)
 
 	sched_cache_exit_mm(current);
 
-	mmap_read_lock(mm);
 	mmgrab_lazy_tlb(mm);
 	BUG_ON(mm != current->active_mm);
-	/* more a memory barrier than a real lock */
 	task_lock(current);
 	/*
 	 * When a thread stops operating on an address space, the loop
@@ -581,7 +579,6 @@ static void exit_mm(void)
 	enter_lazy_tlb(mm, current);
 	local_irq_enable();
 	task_unlock(current);
-	mmap_read_unlock(mm);
 	mm_update_next_owner(mm);
 	mmput(mm);
 	if (test_thread_flag(TIF_MEMDIE))

-- 
2.53.0


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH RFC 17/19] proc: look up map_files vma without exec_update_lock held
  2026-11-24 22:58 [PATCH RFC 00/19] exec: move sleeping work out of exec_update_lock Christian Brauner
                   ` (15 preceding siblings ...)
  2026-11-24 22:58 ` [PATCH RFC 16/19] exit: don't take the mmap lock in exit_mm() Christian Brauner
@ 2026-11-24 22:58 ` Christian Brauner
  2026-11-24 23:09   ` sashiko-bot
  2026-11-24 22:58 ` [PATCH RFC 18/19] vfork: wake up the parent once the child has left the mm Christian Brauner
                   ` (2 subsequent siblings)
  19 siblings, 1 reply; 22+ messages in thread
From: Christian Brauner @ 2026-11-24 22:58 UTC (permalink / raw)
  To: Jann Horn
  Cc: Linus Torvalds, linux-fsdevel, Arnaldo Carvalho de Melo,
	linux-perf-users, bpf, selinux, Kees Cook, linux-mm,
	linux-security-module, apparmor, David Hildenbrand,
	Christian Brauner (Amutable)

Since commit 6255da28d4bb ("proc: protect ptrace_may_access() with
exec_update_lock (FD links)") the links in /proc/<pid>/map_files are
resolved with exec_update_lock of the task held. To find the file
map_files_get_link() looks up the vma and for that it waits for the mmap
lock of the mm.

So whoever reads such a link makes an exec of the task wait for the mmap
lock of its old mm although exec_mmap() doesn't take that lock anymore.
And everyone else who wants to look at the task queues up behind the
exec.

The lock is only needed for the access check and to get at the mm the
check was made for. So only do that with the lock held and look up the
vma afterwards.

The links don't go through call_proc_get_link() anymore so they don't
need ->proc_get_link().

Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
---
 fs/proc/base.c | 68 ++++++++++++++++++++++++++++++++++++++++++++--------------
 1 file changed, 52 insertions(+), 16 deletions(-)

diff --git a/fs/proc/base.c b/fs/proc/base.c
index 7685660c36241..b28bd6c57e1d8 100644
--- a/fs/proc/base.c
+++ b/fs/proc/base.c
@@ -2228,18 +2228,40 @@ static const struct dentry_operations tid_map_files_dentry_operations = {
 	.d_delete	= pid_delete_dentry,
 };
 
-static int map_files_get_link(struct dentry *dentry, struct path *path,
-			      struct task_struct *task)
+/* Check the access and pin the mm with exec_update_lock held. */
+static struct mm_struct *map_files_mm(struct inode *inode)
+{
+	struct task_struct *task __free(put_task) = NULL;
+	struct mm_struct *mm;
+	int err;
+
+	task = get_proc_task(inode);
+	if (!task)
+		return ERR_PTR(-ENOENT);
+
+	err = down_read_killable(&task->signal->exec_update_lock);
+	if (err)
+		return ERR_PTR(err);
+	if (ptrace_may_access(task, PTRACE_MODE_READ_FSCREDS))
+		mm = get_task_mm(task) ?: ERR_PTR(-ENOENT);
+	else
+		mm = ERR_PTR(-EACCES);
+	up_read(&task->signal->exec_update_lock);
+	return mm;
+}
+
+/* The vma lookup waits for the mmap lock so do it without exec_update_lock. */
+static int map_files_get_link(struct dentry *dentry, struct inode *inode,
+			      struct path *path)
 {
 	unsigned long vm_start, vm_end;
 	struct vm_area_struct *vma;
 	struct mm_struct *mm;
 	int rc;
 
-	rc = -ENOENT;
-	mm = get_task_mm(task);
-	if (!mm)
-		goto out;
+	mm = map_files_mm(inode);
+	if (IS_ERR(mm))
+		return PTR_ERR(mm);
 
 	rc = dname_to_vma_addr(dentry, &vm_start, &vm_end);
 	if (rc)
@@ -2260,7 +2282,6 @@ static int map_files_get_link(struct dentry *dentry, struct path *path,
 
 out_mmput:
 	mmput(mm);
-out:
 	return rc;
 }
 
@@ -2280,17 +2301,36 @@ proc_map_files_get_link(struct dentry *dentry,
 			struct inode *inode,
 		        struct delayed_call *done)
 {
+	struct path path;
+	int error;
+
 	if (!checkpoint_restore_ns_capable(&init_user_ns))
 		return ERR_PTR(-EPERM);
 
-	return proc_pid_get_link(dentry, inode, done);
+	if (!dentry)
+		return ERR_PTR(-ECHILD);
+	error = map_files_get_link(dentry, inode, &path);
+	if (!error)
+		error = nd_jump_link(&path);
+	return ERR_PTR(error);
+}
+
+static int proc_map_files_readlink(struct dentry *dentry, char __user *buffer,
+				   int buflen)
+{
+	struct path path;
+	int error;
+
+	error = map_files_get_link(dentry, d_inode(dentry), &path);
+	if (!error) {
+		error = do_proc_readlink(&path, buffer, buflen);
+		path_put(&path);
+	}
+	return error;
 }
 
-/*
- * Identical to proc_pid_link_inode_operations except for get_link()
- */
 static const struct inode_operations proc_map_files_link_inode_operations = {
-	.readlink	= proc_pid_readlink,
+	.readlink	= proc_map_files_readlink,
 	.get_link	= proc_map_files_get_link,
 	.setattr	= proc_nochmod_setattr,
 };
@@ -2300,7 +2340,6 @@ proc_map_files_instantiate(struct dentry *dentry,
 			   struct task_struct *task, const void *ptr)
 {
 	fmode_t mode = (fmode_t)(unsigned long)ptr;
-	struct proc_inode *ei;
 	struct inode *inode;
 
 	inode = proc_pid_make_inode(dentry->d_sb, task, S_IFLNK |
@@ -2309,9 +2348,6 @@ proc_map_files_instantiate(struct dentry *dentry,
 	if (!inode)
 		return ERR_PTR(-ENOENT);
 
-	ei = PROC_I(inode);
-	ei->op.proc_get_link = map_files_get_link;
-
 	inode->i_op = &proc_map_files_link_inode_operations;
 	inode->i_size = 64;
 

-- 
2.53.0


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH RFC 18/19] vfork: wake up the parent once the child has left the mm
  2026-11-24 22:58 [PATCH RFC 00/19] exec: move sleeping work out of exec_update_lock Christian Brauner
                   ` (16 preceding siblings ...)
  2026-11-24 22:58 ` [PATCH RFC 17/19] proc: look up map_files vma without exec_update_lock held Christian Brauner
@ 2026-11-24 22:58 ` Christian Brauner
  2026-11-24 22:58 ` [PATCH RFC 19/19] selftests/exec: test when a vfork() parent is woken up Christian Brauner
  2026-11-24 23:15 ` [PATCH RFC 00/19] exec: move sleeping work out of exec_update_lock sashiko-bot
  19 siblings, 0 replies; 22+ messages in thread
From: Christian Brauner @ 2026-11-24 22:58 UTC (permalink / raw)
  To: Jann Horn
  Cc: Linus Torvalds, linux-fsdevel, Arnaldo Carvalho de Melo,
	linux-perf-users, bpf, selinux, Kees Cook, linux-mm,
	linux-security-module, apparmor, David Hildenbrand,
	Christian Brauner (Amutable)

A task that called vfork() sleeps until the child has released the mm in
mm_release(). But exec_mmap() releases the old mm, then waits for
exec_update_lock and only then switches to the new mm. And exit_mm()
releases the mm and only then drops it. So the parent is woken up while
the child is still on its mm.

It wasn't meant to be that way. When mm_release() was added in 2.2 it
was called after the task had been switched away from the mm. exec only
moved it in front of the switch in 2.5.56 because deactivate_mm() and
the write to the child tid address need the old mm (cf. [1]).

The release has to stay where it is as it can sleep in a page fault for
as long as userspace likes. So take the wakeup out of mm_release(). Wake
up the parent in exec_mmap() once the task has switched to its new mm
and in exit_mm() once it has dropped the mm.

While at it, fix the comment above mm_release(). It hasn't been called
after the mm was removed from the task since 2.5.56.

Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
---
 fs/exec.c                |  3 ++-
 include/linux/sched/mm.h |  4 +++-
 kernel/exit.c            |  7 ++++++-
 kernel/fork.c            | 24 ++++++++++++++----------
 4 files changed, 25 insertions(+), 13 deletions(-)

diff --git a/fs/exec.c b/fs/exec.c
index 78046ed839646..4d3f78ea0b0e6 100644
--- a/fs/exec.c
+++ b/fs/exec.c
@@ -854,7 +854,6 @@ static int exec_mmap(struct linux_binprm *bprm)
 	if (!exec_state)
 		return -ENOMEM;
 
-	/* Notify parent that we're no longer interested in the old VM */
 	tsk = current;
 	old_mm = current->mm;
 	/* Clean up futexes and release the mm */
@@ -897,6 +896,8 @@ static int exec_mmap(struct linux_binprm *bprm)
 		mmdrop_lazy_tlb(active_mm);
 	}
 	futex_exec_done(tsk);
+	/* We've left the old mm so a vfork() parent can run again. */
+	complete_vfork_done(tsk);
 	return 0;
 }
 
diff --git a/include/linux/sched/mm.h b/include/linux/sched/mm.h
index d7c6a942aa7e0..2adfba6217133 100644
--- a/include/linux/sched/mm.h
+++ b/include/linux/sched/mm.h
@@ -158,9 +158,11 @@ extern struct mm_struct *mm_access(struct task_struct *task, unsigned int mode);
 
 /*
  * Remove the current tasks stale references to the old mm_struct on exit() and
- * exec(). Cleans up futexes as well.
+ * exec(). Cleans up futexes as well. A parent that sleeps in vfork() is only
+ * woken up by complete_vfork_done() once the task has left the mm.
  */
 extern void mm_exit_exec_release(struct task_struct *, struct mm_struct *);
+void complete_vfork_done(struct task_struct *tsk);
 
 #ifdef CONFIG_MEMCG
 extern void mm_update_next_owner(struct mm_struct *mm);
diff --git a/kernel/exit.c b/kernel/exit.c
index 38de318a07aaa..6120f0dc3b17d 100644
--- a/kernel/exit.c
+++ b/kernel/exit.c
@@ -554,8 +554,11 @@ static void exit_mm(void)
 	struct mm_struct *mm = current->mm;
 
 	mm_exit_exec_release(current, mm);
-	if (!mm)
+	if (!mm) {
+		/* kthread_stop() waits for this. */
+		complete_vfork_done(current);
 		return;
+	}
 
 	sched_cache_exit_mm(current);
 
@@ -579,6 +582,8 @@ static void exit_mm(void)
 	enter_lazy_tlb(mm, current);
 	local_irq_enable();
 	task_unlock(current);
+	/* We've left the mm so a vfork() parent can run again. */
+	complete_vfork_done(current);
 	mm_update_next_owner(mm);
 	mmput(mm);
 	if (test_thread_flag(TIF_MEMDIE))
diff --git a/kernel/fork.c b/kernel/fork.c
index 5efceb8d58a78..f63133b9e6faf 100644
--- a/kernel/fork.c
+++ b/kernel/fork.c
@@ -1428,10 +1428,21 @@ struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
 	return mm;
 }
 
-static void complete_vfork_done(struct task_struct *tsk)
+/**
+ * complete_vfork_done - wake up whoever waits for @tsk in vfork()
+ * @tsk: task that execs or exits
+ *
+ * A parent that sleeps in vfork() must not run before the child is off its
+ * mm. So this is called once @tsk has switched to its new mm in exec or has
+ * dropped its mm in exit. kthread_stop() uses this completion as well.
+ */
+void complete_vfork_done(struct task_struct *tsk)
 {
 	struct completion *vfork;
 
+	if (!tsk->vfork_done)
+		return;
+
 	task_lock(tsk);
 	vfork = tsk->vfork_done;
 	if (likely(vfork)) {
@@ -1465,8 +1476,8 @@ static int wait_for_vfork_done(struct task_struct *child,
  * mmput is called whenever we stop holding onto a mm_struct,
  * error success whatever.
  *
- * mm_release is called after a mm_struct has been removed
- * from the current process.
+ * mm_release is called when the current process is about to
+ * leave a mm_struct in exec or in exit. It's still on it.
  *
  * This difference is important for error handling, when we
  * only half set up a mm_struct for a new process and need to restore
@@ -1498,13 +1509,6 @@ static void mm_release(struct task_struct *tsk, struct mm_struct *mm)
 		}
 		tsk->clear_child_tid = NULL;
 	}
-
-	/*
-	 * All done, finally we can wake up parent and return this mm to him.
-	 * Also kthread_stop() uses this completion for synchronization.
-	 */
-	if (tsk->vfork_done)
-		complete_vfork_done(tsk);
 }
 
 void mm_exit_exec_release(struct task_struct *tsk, struct mm_struct *mm)

-- 
2.53.0


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH RFC 19/19] selftests/exec: test when a vfork() parent is woken up
  2026-11-24 22:58 [PATCH RFC 00/19] exec: move sleeping work out of exec_update_lock Christian Brauner
                   ` (17 preceding siblings ...)
  2026-11-24 22:58 ` [PATCH RFC 18/19] vfork: wake up the parent once the child has left the mm Christian Brauner
@ 2026-11-24 22:58 ` Christian Brauner
  2026-11-24 23:15 ` [PATCH RFC 00/19] exec: move sleeping work out of exec_update_lock sashiko-bot
  19 siblings, 0 replies; 22+ messages in thread
From: Christian Brauner @ 2026-11-24 22:58 UTC (permalink / raw)
  To: Jann Horn
  Cc: Linus Torvalds, linux-fsdevel, Arnaldo Carvalho de Melo,
	linux-perf-users, bpf, selinux, Kees Cook, linux-mm,
	linux-security-module, apparmor, David Hildenbrand,
	Christian Brauner (Amutable)

Test that a task which called vfork() only runs again once the child has
left the mm:

- when the child execs

- when the child is killed in the middle of the exec

- when the child exits

A parent that is woken up too early only has a few instructions to catch
the child on the mm. So the parent runs in a realtime scheduling class
on the cpu of the child and preempts it as soon as it's woken up. That
takes a kernel with preemption. The tests are skipped without it and
without the right to use a realtime class.

To kill the child between the release of the old mm and the switch to
the new one it has to wait for exec_update_lock there. So there are more
readers of its /proc/<pid>/stat than the cpu they share can run and some
of them are preempted with the lock held.

Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
---
 tools/testing/selftests/exec/.gitignore |   1 +
 tools/testing/selftests/exec/Makefile   |   1 +
 tools/testing/selftests/exec/vfork-mm.c | 363 ++++++++++++++++++++++++++++++++
 3 files changed, 365 insertions(+)

diff --git a/tools/testing/selftests/exec/.gitignore b/tools/testing/selftests/exec/.gitignore
index b27f4db42f87b..24f8f80543df1 100644
--- a/tools/testing/selftests/exec/.gitignore
+++ b/tools/testing/selftests/exec/.gitignore
@@ -18,6 +18,7 @@ null-argv
 /set-exec
 /unshare-sighand
 /update-lock-fault
+/vfork-mm
 xxxxxxxx*
 pipe
 S_I*.test
diff --git a/tools/testing/selftests/exec/Makefile b/tools/testing/selftests/exec/Makefile
index 70f090a5f7648..7d61203d6547b 100644
--- a/tools/testing/selftests/exec/Makefile
+++ b/tools/testing/selftests/exec/Makefile
@@ -22,6 +22,7 @@ TEST_GEN_PROGS += null-argv
 TEST_GEN_PROGS += check-exec
 TEST_GEN_PROGS += update-lock-fault
 TEST_GEN_PROGS += unshare-sighand
+TEST_GEN_PROGS += vfork-mm
 
 # binfmt_misc must not be reachable as an exec source or as a stacking layer,
 # or an 'F' entry can pin the instance that owns it. Unprivileged, no bpf.
diff --git a/tools/testing/selftests/exec/vfork-mm.c b/tools/testing/selftests/exec/vfork-mm.c
new file mode 100644
index 0000000000000..43cdae8e1e7b3
--- /dev/null
+++ b/tools/testing/selftests/exec/vfork-mm.c
@@ -0,0 +1,363 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Test that a task which called vfork() only runs again once the child has
+ * left the mm, i.e. once it has switched to its new mm in exec or has dropped
+ * the mm in exit, also when it is killed in the middle of an exec.
+ *
+ * The first field of /proc/<pid>/statm is the size of the mm a task is on.
+ * The parent has a mapping that is larger than anything the child ends up
+ * with: an exec'd image of this program is a lot smaller and a task that has
+ * dropped its mm shows 0.
+ *
+ * A parent that is woken up too early only has a few instructions to look
+ * before the child is gone. So it runs in a realtime scheduling class and the
+ * child, which is on the same cpu, doesn't. On a kernel with preemption the
+ * parent runs as soon as it's woken up and the child doesn't get any further
+ * meanwhile. Without preemption the child gets too far for the parent to see
+ * anything so the tests are skipped there.
+ */
+#define _GNU_SOURCE
+#include <fcntl.h>
+#include <linux/futex.h>
+#include <sched.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <sys/prctl.h>
+#include <sys/syscall.h>
+#include <sys/utsname.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#include "kselftest_harness.h"
+
+/* 32 bit architectures that only have the time64 system calls. */
+#if !defined(SYS_futex) && defined(SYS_futex_time64)
+#define SYS_futex SYS_futex_time64
+#endif
+
+/* Makes the exec'd image wait to be killed. */
+#define EXECED_ARG	"execed"
+
+/* Exit status of a child that never made it into the exec'd image. */
+#define EXIT_NO_EXEC	127
+
+/* How often the parent looks at a child. */
+#define ROUNDS		16
+
+/* What only the mm of the parent has. */
+#define MAPPING_SIZE	(1UL << 30)
+
+/* How many readers of /proc/<pid>/stat share one cpu. */
+#define READERS		8
+
+/* Size in pages of the mm @pid is on, 0 if it has none. */
+static long mm_size(pid_t pid)
+{
+	char path[64], buf[128];
+	ssize_t len;
+	int fd;
+
+	snprintf(path, sizeof(path), "/proc/%d/statm", pid);
+	fd = open(path, O_RDONLY | O_CLOEXEC);
+	if (fd < 0)
+		return -1;
+	len = read(fd, buf, sizeof(buf) - 1);
+	close(fd);
+	if (len <= 0)
+		return -1;
+	buf[len] = '\0';
+	return strtol(buf, NULL, 10);
+}
+
+/* A kernel that preempts kernel code says so in its version string. */
+static bool kernel_preempts(void)
+{
+	struct utsname u;
+
+	return !uname(&u) && strstr(u.version, "PREEMPT");
+}
+
+/* The child only gets to call exec and _exit(). */
+static pid_t vfork_exec(void)
+{
+	pid_t pid = vfork();
+
+	if (pid == 0) {
+		execl("/proc/self/exe", "vfork-mm", EXECED_ARG, (char *)NULL);
+		_exit(EXIT_NO_EXEC);
+	}
+	return pid;
+}
+
+/*
+ * Same, but the child tells whoever reads from @tell who it is and waits to
+ * be told on @go. The kernel clears *@tid when the child releases the mm.
+ */
+static pid_t vfork_exec_tid(int tell, int go, int *tid)
+{
+	pid_t pid = vfork();
+
+	if (pid == 0) {
+		pid_t self = getpid();
+		char c;
+
+		*tid = self;
+		syscall(SYS_set_tid_address, tid);
+		if (write(tell, &self, sizeof(self)) == sizeof(self) &&
+		    read(go, &c, 1) == 1)
+			execl("/proc/self/exe", "vfork-mm", EXECED_ARG,
+			      (char *)NULL);
+		_exit(EXIT_NO_EXEC);
+	}
+	return pid;
+}
+
+static pid_t vfork_exit(void)
+{
+	pid_t pid = vfork();
+
+	if (pid == 0)
+		_exit(EXIT_SUCCESS);
+	return pid;
+}
+
+FIXTURE(vfork_mm)
+{
+	char *map;
+	long pages;
+	/* The clear_child_tid word of a child, shared with the helper. */
+	int *tid;
+	/* The cpu the parent and its children are on. */
+	int cpu;
+	/* The cpus the test was started on. */
+	cpu_set_t allowed;
+};
+
+FIXTURE_SETUP(vfork_mm)
+{
+	struct sched_param param = { .sched_priority = 1 };
+	cpu_set_t cpus;
+	long size;
+
+	if (!kernel_preempts())
+		SKIP(return, "Needs a kernel with preemption");
+
+	self->pages = MAPPING_SIZE / sysconf(_SC_PAGESIZE);
+	self->map = mmap(NULL, MAPPING_SIZE, PROT_NONE,
+			 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
+	if (self->map == MAP_FAILED)
+		SKIP(return, "Can't map %lu bytes", MAPPING_SIZE);
+	size = mm_size(getpid());
+	if (size < 0)
+		SKIP(return, "Can't read /proc/self/statm");
+	ASSERT_GE(size, self->pages);
+
+	self->tid = mmap(NULL, sizeof(*self->tid), PROT_READ | PROT_WRITE,
+			 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
+	ASSERT_NE(self->tid, MAP_FAILED);
+
+	/* Too many cpus for the mask: the helper takes any cpu it can get. */
+	if (sched_getaffinity(0, sizeof(self->allowed), &self->allowed))
+		memset(&self->allowed, 0xff, sizeof(self->allowed));
+
+	/* The policy isn't inherited, the cpu is. */
+	self->cpu = sched_getcpu();
+	CPU_ZERO(&cpus);
+	CPU_SET(self->cpu, &cpus);
+	if (sched_setaffinity(0, sizeof(cpus), &cpus) ||
+	    sched_setscheduler(0, SCHED_FIFO | SCHED_RESET_ON_FORK, &param))
+		SKIP(return, "Can't make the parent preempt the child");
+}
+
+FIXTURE_TEARDOWN(vfork_mm)
+{
+	munmap(self->map, MAPPING_SIZE);
+	munmap(self->tid, sizeof(*self->tid));
+}
+
+TEST_F(vfork_mm, exec)
+{
+	int status;
+	pid_t pid;
+	long size;
+	int i;
+
+	for (i = 0; i < ROUNDS; i++) {
+		pid = vfork_exec();
+		/* Look before anything else. */
+		size = mm_size(pid);
+		ASSERT_GT(pid, 0);
+		kill(pid, SIGKILL);
+		ASSERT_EQ(waitpid(pid, &status, 0), pid);
+		/* It didn't exit on its own so the exec didn't fail. */
+		ASSERT_TRUE(WIFSIGNALED(status));
+		ASSERT_GE(size, 0);
+		ASSERT_LT(size, self->pages) {
+			TH_LOG("round %d: vfork() returned with the child still on the mm", i);
+		}
+	}
+}
+
+/* Take exec_update_lock of @pid for reading until it's gone. */
+static void stat_reader(pid_t pid, int ready)
+{
+	char path[64], buf[1024];
+	int fd;
+
+	snprintf(path, sizeof(path), "/proc/%d/stat", pid);
+	fd = open(path, O_RDONLY | O_CLOEXEC);
+	if (fd < 0 || pread(fd, buf, sizeof(buf), 0) <= 0 ||
+	    write(ready, "", 1) != 1)
+		_exit(EXIT_FAILURE);
+	while (pread(fd, buf, sizeof(buf), 0) > 0)
+		;
+	_exit(EXIT_SUCCESS);
+}
+
+/*
+ * Kill whoever shows up on @tell right when it has released its mm in exec.
+ * It only stops there if it has to wait for exec_update_lock. So there are
+ * more readers of its /proc/<pid>/stat than the one cpu they share can run:
+ * most of them are preempted at any time, some of them with the lock held.
+ */
+static void killer(FIXTURE_DATA(vfork_mm) *self, pid_t parent, int tell,
+		   int go)
+{
+	struct sched_param param = { .sched_priority = 1 };
+	pid_t helper = getpid();
+	cpu_set_t cpus;
+	int ready[2];
+	int cpu, tid;
+	pid_t pid;
+	char c;
+	int i;
+
+	prctl(PR_SET_PDEATHSIG, SIGKILL);
+	if (getppid() != parent)
+		_exit(EXIT_FAILURE);
+
+	/* Any cpu the test may use but the one of the child. */
+	for (cpu = 0; cpu < CPU_SETSIZE; cpu++) {
+		if (cpu == self->cpu || !CPU_ISSET(cpu, &self->allowed))
+			continue;
+		CPU_ZERO(&cpus);
+		CPU_SET(cpu, &cpus);
+		if (!sched_setaffinity(0, sizeof(cpus), &cpus))
+			break;
+	}
+
+	if (read(tell, &pid, sizeof(pid)) != sizeof(pid) ||
+	    pipe2(ready, O_CLOEXEC))
+		_exit(EXIT_FAILURE);
+
+	for (i = 0; i < READERS; i++) {
+		pid_t reader = fork();
+
+		if (reader < 0)
+			_exit(EXIT_FAILURE);
+		if (reader == 0) {
+			prctl(PR_SET_PDEATHSIG, SIGKILL);
+			if (getppid() != helper)
+				_exit(EXIT_FAILURE);
+			stat_reader(pid, ready[1]);
+		}
+	}
+	for (i = 0; i < READERS; i++) {
+		if (read(ready[0], &c, 1) != 1)
+			_exit(EXIT_FAILURE);
+	}
+
+	/* The kernel wakes us up when it has cleared the word. */
+	if (sched_setscheduler(0, SCHED_FIFO, &param) || write(go, "", 1) != 1)
+		_exit(EXIT_FAILURE);
+	while ((tid = __atomic_load_n(self->tid, __ATOMIC_RELAXED)))
+		syscall(SYS_futex, self->tid, FUTEX_WAIT, tid, NULL, NULL, 0);
+	kill(pid, SIGKILL);
+
+	/* The readers go when we do. */
+	for (;;)
+		pause();
+}
+
+/*
+ * A child that is killed in exec after it has released the mm doesn't get to
+ * switch to a new one. It leaves the mm when it exits.
+ */
+TEST_F(vfork_mm, exec_killed)
+{
+	pid_t parent = getpid();
+	int tell[2], go[2];
+	pid_t pid, helper;
+	int nomm = 0;
+	int status;
+	long size;
+	int i;
+
+	for (i = 0; i < ROUNDS; i++) {
+		ASSERT_EQ(pipe2(tell, O_CLOEXEC), 0);
+		ASSERT_EQ(pipe2(go, O_CLOEXEC), 0);
+		*self->tid = 1;
+
+		helper = fork();
+		ASSERT_GE(helper, 0);
+		if (helper == 0) {
+			close(tell[1]);
+			close(go[0]);
+			killer(self, parent, tell[0], go[1]);
+		}
+		close(tell[0]);
+		close(go[1]);
+
+		pid = vfork_exec_tid(tell[1], go[0], self->tid);
+		/* Look before anything else. */
+		size = mm_size(pid);
+		ASSERT_GT(pid, 0);
+		kill(pid, SIGKILL);
+		ASSERT_EQ(waitpid(pid, &status, 0), pid);
+		kill(helper, SIGKILL);
+		ASSERT_EQ(waitpid(helper, NULL, 0), helper);
+		close(tell[1]);
+		close(go[0]);
+		ASSERT_TRUE(WIFSIGNALED(status));
+		ASSERT_GE(size, 0);
+		ASSERT_LT(size, self->pages) {
+			TH_LOG("round %d: vfork() returned with the child still on the mm", i);
+		}
+		if (!size)
+			nomm++;
+	}
+	if (!nomm)
+		SKIP(return, "The child was never killed before it got to the new mm");
+}
+
+TEST_F(vfork_mm, exit)
+{
+	int status;
+	pid_t pid;
+	long size;
+	int i;
+
+	for (i = 0; i < ROUNDS; i++) {
+		pid = vfork_exit();
+		/* Look before anything else. */
+		size = mm_size(pid);
+		ASSERT_GT(pid, 0);
+		ASSERT_EQ(waitpid(pid, &status, 0), pid);
+		ASSERT_TRUE(WIFEXITED(status));
+		ASSERT_EQ(size, 0) {
+			TH_LOG("round %d: vfork() returned with the child still on the mm", i);
+		}
+	}
+}
+
+int main(int argc, char **argv)
+{
+	if (argc == 2 && !strcmp(argv[1], EXECED_ARG)) {
+		for (;;)
+			pause();
+	}
+	return test_harness_run(argc, argv);
+}

-- 
2.53.0


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* Re: [PATCH RFC 17/19] proc: look up map_files vma without exec_update_lock held
  2026-11-24 22:58 ` [PATCH RFC 17/19] proc: look up map_files vma without exec_update_lock held Christian Brauner
@ 2026-11-24 23:09   ` sashiko-bot
  0 siblings, 0 replies; 22+ messages in thread
From: sashiko-bot @ 2026-11-24 23:09 UTC (permalink / raw)
  To: Christian Brauner, Jann Horn
  Cc: Linus Torvalds, Arnaldo Carvalho de Melo, linux-perf-users, bpf,
	selinux, Kees Cook, linux-mm, linux-security-module, apparmor,
	David Hildenbrand

Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Low] proc: separate __free() declaration and initialization in
  map_files_mm()
--

commit 6e8b44b478838f53cfc44f13f68cf03b45a869ce
Author: Christian Brauner <brauner@kernel.org>

proc: look up map_files vma without exec_update_lock held

This commit restricts holding exec_update_lock during /proc/<pid>/map_files
symlink resolution to the access check and mm pinning in map_files_mm(),
performing the VMA lookup after releasing the lock.

> diff --git a/fs/proc/base.c b/fs/proc/base.c
> index 7685660c36241..b28bd6c57e1d8 100644
> --- a/fs/proc/base.c
> +++ b/fs/proc/base.c
> @@ -2228,18 +2228,40 @@ static const struct dentry_operations tid_map_files_dentry_operations = {
>  	.d_delete	= pid_delete_dentry,
>  };
>  
> -static int map_files_get_link(struct dentry *dentry, struct path *path,
> -			      struct task_struct *task)
> +/* Check the access and pin the mm with exec_update_lock held. */
> +static struct mm_struct *map_files_mm(struct inode *inode)
> +{
> +	struct task_struct *task __free(put_task) = NULL;
> +	struct mm_struct *mm;
> +	int err;
> +
> +	task = get_proc_task(inode);

[Severity: Low]
This isn't a bug, but per the cleanup.h convention, task can be defined
and initialized with get_proc_task(inode) in a single statement rather
than being initialized to NULL and assigned right after.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261124-work-exec-update_lock-v1-0-e489035395b8@kernel.org?part=17

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: [PATCH RFC 00/19] exec: move sleeping work out of exec_update_lock
  2026-11-24 22:58 [PATCH RFC 00/19] exec: move sleeping work out of exec_update_lock Christian Brauner
                   ` (18 preceding siblings ...)
  2026-11-24 22:58 ` [PATCH RFC 19/19] selftests/exec: test when a vfork() parent is woken up Christian Brauner
@ 2026-11-24 23:15 ` sashiko-bot
  19 siblings, 0 replies; 22+ messages in thread
From: sashiko-bot @ 2026-11-24 23:15 UTC (permalink / raw)
  To: Christian Brauner; +Cc: linux-perf-users, selinux, linux-security-module

Sashiko has finished reviewing this 19-patch series:

- Patches 1-16, 18, and 19: no issues found.
- Patch 17 ("proc: look up map_files vma without exec_update_lock..."):
  1 potential issue (1 Low)

A detailed review has been sent as a separate reply to patch 17.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261124-work-exec-update_lock-v1-0-e489035395b8@kernel.org

^ permalink raw reply	[flat|nested] 22+ messages in thread

end of thread, other threads:[~2026-11-24 23:15 UTC | newest]

Thread overview: 22+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-11-24 22:58 [PATCH RFC 00/19] exec: move sleeping work out of exec_update_lock Christian Brauner
2026-11-24 22:58 ` [PATCH RFC 01/19] proc: copy namespace link after dropping exec_update_lock Christian Brauner
2026-11-24 22:58 ` [PATCH RFC 02/19] kcmp: look up epoll target without exec_update_lock held Christian Brauner
2026-11-24 22:58 ` [PATCH RFC 03/19] perf: copy counter values after dropping ctx->mutex Christian Brauner
2026-11-24 22:58 ` [PATCH RFC 04/19] perf: copy ioctl arguments without ctx->mutex held Christian Brauner
2026-11-24 22:58 ` [PATCH RFC 05/19] selinux: close inherited files that can't be replaced Christian Brauner
2026-11-24 22:58 ` [PATCH RFC 06/19] exec: move unshare_sighand() before exec_mmap() Christian Brauner
2026-11-24 22:58 ` [PATCH RFC 07/19] selftests/exec: test exec with a task sleeping in a page fault Christian Brauner
2026-11-24 22:58 ` [PATCH RFC 08/19] selftests/exec: test exec with a shared signal table Christian Brauner
2026-11-24 22:58 ` [PATCH RFC 09/19] lsm: add security_bprm_revalidate_files() Christian Brauner
2026-11-24 22:58 ` [PATCH RFC 10/19] bpf: mark bprm_revalidate_files as sleepable Christian Brauner
2026-11-24 22:58 ` [PATCH RFC 11/19] selinux: revalidate inherited files before taking exec_update_lock Christian Brauner
2026-11-24 22:58 ` [PATCH RFC 12/19] apparmor: " Christian Brauner
2026-11-24 22:58 ` [PATCH RFC 13/19] exec: drop exec_update_lock after the credentials are committed Christian Brauner
2026-11-24 22:58 ` [PATCH RFC 14/19] exec: switch time namespace after dropping exec_update_lock Christian Brauner
2026-11-24 22:58 ` [PATCH RFC 15/19] exec: don't take the mmap lock of the old mm Christian Brauner
2026-11-24 22:58 ` [PATCH RFC 16/19] exit: don't take the mmap lock in exit_mm() Christian Brauner
2026-11-24 22:58 ` [PATCH RFC 17/19] proc: look up map_files vma without exec_update_lock held Christian Brauner
2026-11-24 23:09   ` sashiko-bot
2026-11-24 22:58 ` [PATCH RFC 18/19] vfork: wake up the parent once the child has left the mm Christian Brauner
2026-11-24 22:58 ` [PATCH RFC 19/19] selftests/exec: test when a vfork() parent is woken up Christian Brauner
2026-11-24 23:15 ` [PATCH RFC 00/19] exec: move sleeping work out of exec_update_lock sashiko-bot

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).