Skip to contentSkip to conversation

coredump, files: exit files on request

RFC PATCH Superseded Christian Brauner 2 participants 24 messages Sep 2 – Sep 4

Subsystems (5)
VFS Kselftest MM core Scheduler +1 more subsystems

v2 of 4 Superseded Latest is v4 →

lore
Share & tools
lore

Christian Brauner

author maintainer
#0 lore raw

v2 cover coredump, files: exit files on request

We've had quite a few proposal for exiting files before generating the coredump (see [1]-[8]). The various proposed solution were quite unacceptable. So I took some time to look what a _remotely_ acceptable version of this could look like. Here it is.

The gist is that we allow the coredump socket to request the thread-group shed the various fdtables closed synchronously before generating the coredump.

The intricate task is that this requires us to add a primitive to close fdtables synchronously. Coredump is not enough to justify this but performance numbers for this look pretty convincing. For tasks exiting with a large file descriptor table this means getting rid of _a lot_ of cmpxchg()s and hammering on task->pi_lock. The cost of this was mentioned in various threads over the years. I found at least recent comments by Oleg and Neil.

The obvious problematic case are kernel threads. fput() punts their final __fput() to a workqueue. kthreads never return to userspace to run task work and some of them may need to finish a umount and so cannot ->release() inline. No path we change is taken by a kthread. They don't own a descriptor table and kthreadd is created with CLONE_FILES and every kthread inherits it. So all of them share init_files and init_task pins that forever. Their exit_files() never drops the last reference.

kernel_execve() refuses PF_KTHREAD outright. Usermodehelpers are spawned without the kthread flag. close_range() is a syscall. The one indirect way is a failing copy_process() calling exit_files() on a child from a kthread parent. A dup_fd() in copy_process() cannot hold the last reference to any of its files while the source table is alive.

Worker threads such as io_uring workers are user threads without PF_KTHREAD that share the fdtable. One of them can be the last to put the fdtable at exit. Today fput() hands their final __fput()s to task work. The worker runs that itself in exit_task_work() a few lines later. Now the same thread does the same work in exit_files() instead. vhost workers are created without a descriptor table at all, so they never even put an fdtable. Neither kind ever execs or calls close_range().

Now the performance numbers. I measured this on a 64 vCPU KVM guest (AMD EPYC 9754) on top of vfs-7.4.coredump with and without the series and the same x86_64_defconfig for both. The benchmark opens N files in a forked worker and times the teardown:

- process exit
- execve() with N close-on-exec descriptors
- close_range() with and without CLOSE_RANGE_UNSHARE

Here are the medians over two or three boots which agree within 2%. With /dev/null as the file and 4096, 65536 and 1M descriptors:

                         4096 fds        65536 fds        1M fds
  ----------------------------------------------------------------------
  exit                    890 -> 826 us  13.5 -> 12.4 ms  221 -> 203 ms
                          -7.2%          -7.9%            -8.3%
  ----------------------------------------------------------------------
  execve, close-on-exec  1215 -> 1113 us 15.9 -> 14.2 ms  247 -> 224 ms
                          -8.4%          -10.1%           -9.0%
  ----------------------------------------------------------------------
  close_range()           984 -> 909 us  17.3 -> 15.3 ms  268 -> 245 ms
                          -7.6%          -11.5%           -8.7%
  ----------------------------------------------------------------------
  close_range(UNSHARE)    990 -> 912 us  17.1 -> 15.3 ms  267 -> 245 ms
                          -7.9%          -10.3%           -8.4%

So that's a 7-11% win or a constant 15-25 ns per closed file. This sheds init_task_work() and task_work_add() per file with its cmpxchg() and the TIF_NOTIFY_RESUME test-and-set, the list walk with the indirect call in the path our, and then a second pass over every struct file that isn't cache-hot anymore by then.

The performance boost is linear in the number of descriptors from 256 to 1M. Note the thread count doesn't matter since one thread does the close anyway.

So with eight processes tearing down 65536 descriptors each at the same time the win grows to 13-15% (20.1 -> 17.4 ms for exit, 20.5 -> 17.4 ms for execve). The old code walks the table once to queue the task work and then walks all 16 MB of struct file a second time from task_work_run().

So once eight CPUs compete for the cache that second pass gets very expensive. With 32 or 64 processes at once both kernels are bound by pushing millions of files through slab and RCU. So then the difference shrinks to 1-4%. Still though...

Files whose own release dominates the cleanup gain a little less. 4% for eventfds, 7% for pipes, about 1% for AF_UNIX sockets and distinct tmpfs inodes. For them a release costs 1.25 us per descriptor anyway.

Using function profiling a 65536 descriptor exit spends 4.0 ms in exit_files() and 10.4 ms in task_work_run() before and now 12.5 ms in exit_files() and nothing in task_work_run() after.

close(2) is untouched and measures the same. will-it-scale (open1, open3, dup1, eventfd1, unix1, pipe1, signal1, processes and threads) is within 2% either way. dup1 a few percent better which I'd put down to layout.

So, back to coredumps. With COREDUMP_CLOSE_FILES coredumps switch to an empty file descriptor table before generating the coredump. That requires a bit of synchronization but I think I got the basics down.

The coredumping thread allocates a new empty file descriptor table. It then wakes all threads in the thread-group and tells them to switch to the empty file descriptor table and get rid of the old one. They report back once they're done.

So that handles most cases where locks would be held for an unreasonable time until the coredump is generated but since files can be shared between completely unrelated processes that's not a guarantee and we can't give one. But it solves the reported issue without resorting to even grosser hacks.

---
Changes in v2:
- Revamp.
- Link to v1: https://patch.msgid.link/[email protected]

---
Christian Brauner (16):
fs: don't open-code file_close_fd() in close_fd()
fs: add fput_close_list() and fput_list()
fs: rename do_close_on_exec() to close_cloexec_files()
fs: defer the final fput of close-on-exec files past the exec locks
fs: add switch_files_struct()
fs: move unshare_fd() to fs/file.c
fs: remove unshare_files()
exec: release fdtable after exec locks drop
fs: make close_files() synchronous
fs: make close_range() synchronous
coredump: s/startup/done/g
coredump: factor out coredump_wait_inactive()
fs: add alloc_files_struct()
coredump: add COREDUMP_CLOSE_FILES
tools: sync coredump.h header
selftests/coredump: test COREDUMP_CLOSE_FILES

 fs/coredump.c                                      |  91 +++-
 fs/exec.c                                          |  11 +-
 fs/file.c                                          | 124 +++--
 fs/file_table.c                                    |  25 +-
 fs/internal.h                                      |   3 +
 fs/open.c                                          |   2 +-
 include/linux/binfmts.h                            |   6 +
 include/linux/fdtable.h                            |   7 +-
 include/linux/sched/signal.h                       |   5 +-
 include/uapi/linux/coredump.h                      |   8 +
 kernel/exit.c                                      |  15 +-
 kernel/fork.c                                      |  48 +-
 tools/include/uapi/linux/coredump.h                |   8 +
 tools/testing/selftests/coredump/Makefile          |   4 +-
 .../selftests/coredump/coredump_close_files_test.c | 592 +++++++++++++++++++++
 .../coredump/coredump_socket_protocol_test.c       |   6 +
 .../selftests/coredump/coredump_test_helpers.c     |   3 +-
 17 files changed, 847 insertions(+), 111 deletions(-)

---
base-commit: 582e5e0d99ac356fac9656767070269bb4ffc1b2
change-id: 20260824-work-coredump-unlock-self-63a898912870

author maintainer
#1 lore raw

RFC PATCH v2 1/16 fs: don't open-code file_close_fd() in close_fd()

close_fd() takes the lock, calls file_close_fd_locked() and drops the lock, which is exactly what file_close_fd() does. Use it.

No functional changes.

---
 fs/file.c | 7 ++-----
 1 file changed, 2 insertions(+), 5 deletions(-)
fs/file.c +2 -5
index 628ca07dc4b1..59673547de90 100644
@@ -732,16 +732,13 @@ struct file *file_close_fd_locked(struct files_struct *files, unsigned fd)
 
 int close_fd(unsigned fd)
 {
-	struct files_struct *files = current->files;
 	struct file *file;
 
-	spin_lock(&files->file_lock);
-	file = file_close_fd_locked(files, fd);
-	spin_unlock(&files->file_lock);
+	file = file_close_fd(fd);
 	if (!file)
 		return -EBADF;
 
-	return filp_close(file, files);
+	return filp_close(file, current->files);
 }
 EXPORT_SYMBOL(close_fd);
 
Signature · 1 line
2.53.0
author maintainer
#2 lore raw

RFC PATCH v2 2/16 fs: add fput_close_list() and fput_list()

In reply to Christian Brauner

Add helpers for paths that close many files in one go. They collect the last references during the walk and drain them right after

fput_list() runs the final __fput() for everything on the list. delayed_fput() shares that loop.

We'll use that in the next patches.

---
 fs/file_table.c | 25 +++++++++++++++++++++----
 fs/internal.h   |  3 +++
 fs/open.c       |  2 +-
 3 files changed, 25 insertions(+), 5 deletions(-)
fs/file_table.c +21 -4
index c68b8c0a4097..617912ca4e0a 100644
@@ -528,11 +528,10 @@ static void __fput(struct file *file)
 static LLIST_HEAD(delayed_fput_list);
 static void delayed_fput(struct work_struct *unused)
 {
-	struct llist_node *node = llist_del_all(&delayed_fput_list);
-	struct file *f, *t;
+	/* Detach the shared list once, then drain it like a private one. */
+	struct llist_head list = { .first = llist_del_all(&delayed_fput_list) };
 
-	llist_for_each_entry_safe(f, t, node, f_llist)
-		__fput(f);
+	fput_list(&list);
 }
 
 static void ____fput(struct callback_head *work)
@@ -629,6 +628,24 @@ void fput_close(struct file *file)
 		__fput_deferred(file);
 }
 
+/* Like fput_close(), but the last reference goes on the caller's @list. */
+void fput_close_list(struct file *file, struct llist_head *list)
+{
+	if (file_ref_put_close(&file->f_ref))
+		__llist_add(&file->f_llist, list);
+}
+
+/* Run the final __fput() for everything on the private @list, right here. */
+void fput_list(struct llist_head *list)
+{
+	struct file *f, *t;
+
+	llist_for_each_entry_safe(f, t, __llist_del_all(list), f_llist) {
+		__fput(f);
+		cond_resched();
+	}
+}
+
 void __init files_init(void)
 {
 	struct kmem_cache_args args = {
fs/internal.h +3 -0
index c658c8a5ebd5..619eaeb23fd9 100644
@@ -129,6 +129,8 @@ static inline void put_file_access(struct file *file)
 
 void fput_close_sync(struct file *);
 void fput_close(struct file *);
+void fput_close_list(struct file *file, struct llist_head *list);
+void fput_list(struct llist_head *list);
 
 /*
  * super.c
@@ -198,6 +200,7 @@ extern struct file *do_file_open_root(const struct path *,
 extern struct open_how build_open_how(int flags, umode_t mode);
 extern int build_open_flags(const struct open_how *how, struct open_flags *op);
 struct file *file_close_fd_locked(struct files_struct *files, unsigned fd);
+int filp_flush(struct file *filp, fl_owner_t id);
 
 int do_ftruncate(struct file *file, loff_t length, unsigned int flags);
 int chmod_common(const struct path *path, umode_t mode);
fs/open.c +1 -1
index 6b1c14e684a9..7181665c3af5 100644
@@ -1506,7 +1506,7 @@ SYSCALL_DEFINE2(creat, const char __user *, pathname, umode_t, mode)
  * "id" is the POSIX thread ID. We use the
  * files pointer for this..
  */
-static int filp_flush(struct file *filp, fl_owner_t id)
+int filp_flush(struct file *filp, fl_owner_t id)
 {
 	int retval = 0;
 
Signature · 1 line
2.53.0
Reviewed-by on v2 2/16
#3 lore raw

Re: [PATCH RFC v2 02/16] fs: add fput_close_list() and fput_list()

Quoted 6 lines · Christian Brauner

Add helpers for paths that close many files in one go. They collect the last references during the walk and drain them right after

fput_list() runs the final __fput() for everything on the list. delayed_fput() shares that loop.

nit: I think fput_list is a highly misleading name here, suggesting it grabs a list of files to unref.

I don't have a proposal for a name I'm happy with and I'm not going to argue about this, but to throw some ideas: filp_close_list, fput_finish_list or similar

Regardless of what happens with the above:

Quoted 92 lines

We'll use that in the next patches.

---
 fs/file_table.c | 25 +++++++++++++++++++++----
 fs/internal.h   |  3 +++
 fs/open.c       |  2 +-
 3 files changed, 25 insertions(+), 5 deletions(-)
fs/file_table.c +21 -4
index c68b8c0a4097..617912ca4e0a 100644
@@ -528,11 +528,10 @@ static void __fput(struct file *file)
 static LLIST_HEAD(delayed_fput_list);
 static void delayed_fput(struct work_struct *unused)
 {
-       struct llist_node *node = llist_del_all(&delayed_fput_list);
-       struct file *f, *t;
+       /* Detach the shared list once, then drain it like a private one. */
+       struct llist_head list = { .first = llist_del_all(&delayed_fput_list) };
 
-       llist_for_each_entry_safe(f, t, node, f_llist)
-               __fput(f);
+       fput_list(&list);
 }
 
 static void ____fput(struct callback_head *work)
@@ -629,6 +628,24 @@ void fput_close(struct file *file)
                __fput_deferred(file);
 }
 
+/* Like fput_close(), but the last reference goes on the caller's @list. */
+void fput_close_list(struct file *file, struct llist_head *list)
+{
+       if (file_ref_put_close(&file->f_ref))
+               __llist_add(&file->f_llist, list);
+}
+
+/* Run the final __fput() for everything on the private @list, right here. */
+void fput_list(struct llist_head *list)
+{
+       struct file *f, *t;
+
+       llist_for_each_entry_safe(f, t, __llist_del_all(list), f_llist) {
+               __fput(f);
+               cond_resched();
+       }
+}
+
 void __init files_init(void)
 {
        struct kmem_cache_args args = {
fs/internal.h +3 -0
index c658c8a5ebd5..619eaeb23fd9 100644
@@ -129,6 +129,8 @@ static inline void put_file_access(struct file *file)
 
 void fput_close_sync(struct file *);
 void fput_close(struct file *);
+void fput_close_list(struct file *file, struct llist_head *list);
+void fput_list(struct llist_head *list);
 
 /*
  * super.c
@@ -198,6 +200,7 @@ extern struct file *do_file_open_root(const struct path *,
 extern struct open_how build_open_how(int flags, umode_t mode);
 extern int build_open_flags(const struct open_how *how, struct open_flags *op);
 struct file *file_close_fd_locked(struct files_struct *files, unsigned fd);
+int filp_flush(struct file *filp, fl_owner_t id);
 
 int do_ftruncate(struct file *file, loff_t length, unsigned int flags);
 int chmod_common(const struct path *path, umode_t mode);
fs/open.c +1 -2
index 6b1c14e684a9..7181665c3af5 100644
@@ -1506,7 +1506,7 @@ SYSCALL_DEFINE2(creat, const char __user *, pathname, umode_t, mode)
  * "id" is the POSIX thread ID. We use the
  * files pointer for this..
  */
-static int filp_flush(struct file *filp, fl_owner_t id)
+int filp_flush(struct file *filp, fl_owner_t id)
 {
        int retval = 0;
 
 
--

2.53.0

#4 lore raw

Re: [PATCH RFC v2 02/16] fs: add fput_close_list() and fput_list()

Quoted 9 lines · Mateusz Guzik
Quoted 6 lines · Christian Brauner

Add helpers for paths that close many files in one go. They collect the last references during the walk and drain them right after

fput_list() runs the final __fput() for everything on the list. delayed_fput() shares that loop.

Quoted 6 lines

nit: I think fput_list is a highly misleading name here, suggesting it grabs a list of files to unref.

I don't have a proposal for a name I'm happy with and I'm not going to argue about this, but to throw some ideas: filp_close_list, fput_finish_list or similar

The more I'm looking at this, the more I'm convinced I'm whatever name it should follow the convention of ending with _sync.

Quoted 96 lines

Regardless of what happens with the above:

Quoted 92 lines

We'll use that in the next patches.

---
 fs/file_table.c | 25 +++++++++++++++++++++----
 fs/internal.h   |  3 +++
 fs/open.c       |  2 +-
 3 files changed, 25 insertions(+), 5 deletions(-)
fs/file_table.c +21 -4
index c68b8c0a4097..617912ca4e0a 100644
@@ -528,11 +528,10 @@ static void __fput(struct file *file)
 static LLIST_HEAD(delayed_fput_list);
 static void delayed_fput(struct work_struct *unused)
 {
-       struct llist_node *node = llist_del_all(&delayed_fput_list);
-       struct file *f, *t;
+       /* Detach the shared list once, then drain it like a private one. */
+       struct llist_head list = { .first = llist_del_all(&delayed_fput_list) };
 
-       llist_for_each_entry_safe(f, t, node, f_llist)
-               __fput(f);
+       fput_list(&list);
 }
 
 static void ____fput(struct callback_head *work)
@@ -629,6 +628,24 @@ void fput_close(struct file *file)
                __fput_deferred(file);
 }
 
+/* Like fput_close(), but the last reference goes on the caller's @list. */
+void fput_close_list(struct file *file, struct llist_head *list)
+{
+       if (file_ref_put_close(&file->f_ref))
+               __llist_add(&file->f_llist, list);
+}
+
+/* Run the final __fput() for everything on the private @list, right here. */
+void fput_list(struct llist_head *list)
+{
+       struct file *f, *t;
+
+       llist_for_each_entry_safe(f, t, __llist_del_all(list), f_llist) {
+               __fput(f);
+               cond_resched();
+       }
+}
+
 void __init files_init(void)
 {
        struct kmem_cache_args args = {
fs/internal.h +3 -0
index c658c8a5ebd5..619eaeb23fd9 100644
@@ -129,6 +129,8 @@ static inline void put_file_access(struct file *file)
 
 void fput_close_sync(struct file *);
 void fput_close(struct file *);
+void fput_close_list(struct file *file, struct llist_head *list);
+void fput_list(struct llist_head *list);
 
 /*
  * super.c
@@ -198,6 +200,7 @@ extern struct file *do_file_open_root(const struct path *,
 extern struct open_how build_open_how(int flags, umode_t mode);
 extern int build_open_flags(const struct open_how *how, struct open_flags *op);
 struct file *file_close_fd_locked(struct files_struct *files, unsigned fd);
+int filp_flush(struct file *filp, fl_owner_t id);
 
 int do_ftruncate(struct file *file, loff_t length, unsigned int flags);
 int chmod_common(const struct path *path, umode_t mode);
fs/open.c +1 -2
index 6b1c14e684a9..7181665c3af5 100644
@@ -1506,7 +1506,7 @@ SYSCALL_DEFINE2(creat, const char __user *, pathname, umode_t, mode)
  * "id" is the POSIX thread ID. We use the
  * files pointer for this..
  */
-static int filp_flush(struct file *filp, fl_owner_t id)
+int filp_flush(struct file *filp, fl_owner_t id)
 {
        int retval = 0;
 
 
--

2.53.0

author maintainer
#5 lore raw

Re: [PATCH RFC v2 02/16] fs: add fput_close_list() and fput_list()

Quoted 13 lines · Mateusz Guzik
Quoted 12 lines · Mateusz Guzik
Quoted 6 lines · Christian Brauner

Add helpers for paths that close many files in one go. They collect the last references during the walk and drain them right after

fput_list() runs the final __fput() for everything on the list. delayed_fput() shares that loop.

nit: I think fput_list is a highly misleading name here, suggesting it grabs a list of files to unref.

Quoted 6 lines
Quoted 3 lines

I don't have a proposal for a name I'm happy with and I'm not going to argue about this, but to throw some ideas: filp_close_list, fput_finish_list or similar

The more I'm looking at this, the more I'm convinced I'm whatever name it should follow the convention of ending with _sync.

Ok, might change.

author maintainer
#6 lore raw

RFC PATCH v2 3/16 fs: rename do_close_on_exec() to close_cloexec_files()

In reply to Christian Brauner

Rename the helper and align it with close_files().

No functional changes.

---
 fs/exec.c               | 2 +-
 fs/file.c               | 2 +-
 include/linux/fdtable.h | 2 +-
 3 files changed, 3 insertions(+), 3 deletions(-)
fs/exec.c +1 -1
index 745f6eb5279e..92a02bce11d5 100644
@@ -1220,7 +1220,7 @@ int begin_new_exec(struct linux_binprm * bprm)
 	 * trying to access the should-be-closed file descriptors of a process
 	 * undergoing exec(2).
 	 */
-	do_close_on_exec(me->files);
+	close_cloexec_files(me->files);
 
 	if (bprm->secureexec) {
 		/* Make sure parent cannot signal privileged process. */
fs/file.c +1 -1
index 59673547de90..be06e09df41c 100644
@@ -884,7 +884,7 @@ struct file *file_close_fd(unsigned int fd)
 	return file;
 }
 
-void do_close_on_exec(struct files_struct *files)
+void close_cloexec_files(struct files_struct *files)
 {
 	unsigned i;
 	struct fdtable *fdt;
include/linux/fdtable.h +1 -1
index c45306a9f007..e6b641d9eb91 100644
@@ -105,7 +105,7 @@ struct fd_range {
 	unsigned int from, to;
 };
 struct files_struct *dup_fd(struct files_struct *, struct fd_range *) __latent_entropy;
-void do_close_on_exec(struct files_struct *);
+void close_cloexec_files(struct files_struct *);
 int iterate_fd(struct files_struct *, unsigned,
 		int (*)(const void *, struct file *, unsigned),
 		const void *);
Signature · 1 line
2.53.0
Reviewed-by on v2 3/16
#7 lore raw

Re: [PATCH RFC v2 03/16] fs: rename do_close_on_exec() to close_cloexec_files()

Quoted 53 lines · Christian Brauner

Rename the helper and align it with close_files().

No functional changes.

---
 fs/exec.c               | 2 +-
 fs/file.c               | 2 +-
 include/linux/fdtable.h | 2 +-
 3 files changed, 3 insertions(+), 3 deletions(-)
fs/exec.c +1 -1
index 745f6eb5279e..92a02bce11d5 100644
@@ -1220,7 +1220,7 @@ int begin_new_exec(struct linux_binprm * bprm)
         * trying to access the should-be-closed file descriptors of a process
         * undergoing exec(2).
         */
-       do_close_on_exec(me->files);
+       close_cloexec_files(me->files);
 
        if (bprm->secureexec) {
                /* Make sure parent cannot signal privileged process. */
fs/file.c +1 -1
index 59673547de90..be06e09df41c 100644
@@ -884,7 +884,7 @@ struct file *file_close_fd(unsigned int fd)
        return file;
 }
 
-void do_close_on_exec(struct files_struct *files)
+void close_cloexec_files(struct files_struct *files)
 {
        unsigned i;
        struct fdtable *fdt;
include/linux/fdtable.h +1 -2
index c45306a9f007..e6b641d9eb91 100644
@@ -105,7 +105,7 @@ struct fd_range {
        unsigned int from, to;
 };
 struct files_struct *dup_fd(struct files_struct *, struct fd_range *) __latent_entropy;
-void do_close_on_exec(struct files_struct *);
+void close_cloexec_files(struct files_struct *);
 int iterate_fd(struct files_struct *, unsigned,
                int (*)(const void *, struct file *, unsigned),
                const void *);
 
--
Quoted 2 lines

2.53.0

author maintainer
#8 lore raw

RFC PATCH v2 4/16 fs: defer the final fput of close-on-exec files past the exec locks

In reply to Christian Brauner

Taks with lots of file descriptors pay a hefy price for offloading to task work. Port them to the fput_list() mechanism instead and waste files in free_binprm().

---
 fs/exec.c               | 4 +++-
 fs/file.c               | 6 ++++--
 include/linux/binfmts.h | 4 ++++
 include/linux/fdtable.h | 2 +-
 4 files changed, 12 insertions(+), 4 deletions(-)
fs/exec.c +3 -1
index 92a02bce11d5..b1f449dba258 100644
@@ -1220,7 +1220,7 @@ int begin_new_exec(struct linux_binprm * bprm)
 	 * trying to access the should-be-closed file descriptors of a process
 	 * undergoing exec(2).
 	 */
-	close_cloexec_files(me->files);
+	close_cloexec_files(me->files, &bprm->cloexec_files);
 
 	if (bprm->secureexec) {
 		/* Make sure parent cannot signal privileged process. */
@@ -1469,6 +1469,8 @@ static void free_bprm(struct linux_binprm *bprm)
 		mutex_unlock(&current->signal->cred_guard_mutex);
 		abort_creds(bprm->cred);
 	}
+	/* The exec locks are out of the way now, see close_cloexec_files(). */
+	fput_list(&bprm->cloexec_files);
 	/* exec swapped the mm but failed before setup_new_exec() freed it */
 	if (bprm->old_mm)
 		exec_mm_put_old(bprm->old_mm);
fs/file.c +4 -2
index be06e09df41c..88ede1262b3e 100644
@@ -884,7 +884,8 @@ struct file *file_close_fd(unsigned int fd)
 	return file;
 }
 
-void close_cloexec_files(struct files_struct *files)
+/* The caller drains @list with fput_list() once it dropped its locks. */
+void close_cloexec_files(struct files_struct *files, struct llist_head *list)
 {
 	unsigned i;
 	struct fdtable *fdt;
@@ -911,7 +912,8 @@ void close_cloexec_files(struct files_struct *files)
 			rcu_assign_pointer(fdt->fd[fd], NULL);
 			__put_unused_fd(files, fd);
 			spin_unlock(&files->file_lock);
-			filp_close(file, files);
+			filp_flush(file, files);
+			fput_close_list(file, list);
 			cond_resched();
 			spin_lock(&files->file_lock);
 		}
include/linux/binfmts.h +4 -0
index 2e87faf9a8c2..be935320f1c7 100644
@@ -4,6 +4,7 @@
 
 #include <linux/sched.h>
 #include <linux/unistd.h>
+#include <linux/llist.h>
 #include <asm/exec.h>
 #include <uapi/linux/binfmts.h>
 
@@ -81,6 +82,9 @@ struct linux_binprm {
 	int execfd;		/* File descriptor of the executable */
 	unsigned long exec;
 
+	/* Close-on-exec files awaiting their final __fput(), see free_bprm(). */
+	struct llist_head cloexec_files;
+
 	struct rlimit rlim_stack; /* Saved RLIMIT_STACK used during exec. */
 
 	char buf[BINPRM_BUF_SIZE];
include/linux/fdtable.h +1 -1
index e6b641d9eb91..050f4a04157e 100644
@@ -105,7 +105,7 @@ struct fd_range {
 	unsigned int from, to;
 };
 struct files_struct *dup_fd(struct files_struct *, struct fd_range *) __latent_entropy;
-void close_cloexec_files(struct files_struct *);
+void close_cloexec_files(struct files_struct *, struct llist_head *);
 int iterate_fd(struct files_struct *, unsigned,
 		int (*)(const void *, struct file *, unsigned),
 		const void *);
Signature · 1 line
2.53.0
#9 lore raw

Re: [PATCH RFC v2 04/16] fs: defer the final fput of close-on-exec files past the exec locks

Quoted 97 lines · Christian Brauner

Taks with lots of file descriptors pay a hefy price for offloading to task work. Port them to the fput_list() mechanism instead and waste files in free_binprm().

---
 fs/exec.c               | 4 +++-
 fs/file.c               | 6 ++++--
 include/linux/binfmts.h | 4 ++++
 include/linux/fdtable.h | 2 +-
 4 files changed, 12 insertions(+), 4 deletions(-)
fs/exec.c +3 -1
index 92a02bce11d5..b1f449dba258 100644
@@ -1220,7 +1220,7 @@ int begin_new_exec(struct linux_binprm * bprm)
         * trying to access the should-be-closed file descriptors of a process
         * undergoing exec(2).
         */
-       close_cloexec_files(me->files);
+       close_cloexec_files(me->files, &bprm->cloexec_files);
 
        if (bprm->secureexec) {
                /* Make sure parent cannot signal privileged process. */
@@ -1469,6 +1469,8 @@ static void free_bprm(struct linux_binprm *bprm)
                mutex_unlock(&current->signal->cred_guard_mutex);
                abort_creds(bprm->cred);
        }
+       /* The exec locks are out of the way now, see close_cloexec_files(). */
+       fput_list(&bprm->cloexec_files);
        /* exec swapped the mm but failed before setup_new_exec() freed it */
        if (bprm->old_mm)
                exec_mm_put_old(bprm->old_mm);
fs/file.c +4 -2
index be06e09df41c..88ede1262b3e 100644
@@ -884,7 +884,8 @@ struct file *file_close_fd(unsigned int fd)
        return file;
 }
 
-void close_cloexec_files(struct files_struct *files)
+/* The caller drains @list with fput_list() once it dropped its locks. */
+void close_cloexec_files(struct files_struct *files, struct llist_head *list)
 {
        unsigned i;
        struct fdtable *fdt;
@@ -911,7 +912,8 @@ void close_cloexec_files(struct files_struct *files)
                        rcu_assign_pointer(fdt->fd[fd], NULL);
                        __put_unused_fd(files, fd);
                        spin_unlock(&files->file_lock);
-                       filp_close(file, files);
+                       filp_flush(file, files);
+                       fput_close_list(file, list);
                        cond_resched();
                        spin_lock(&files->file_lock);
                }
include/linux/binfmts.h +4 -0
index 2e87faf9a8c2..be935320f1c7 100644
@@ -4,6 +4,7 @@
 
 #include <linux/sched.h>
 #include <linux/unistd.h>
+#include <linux/llist.h>
 #include <asm/exec.h>
 #include <uapi/linux/binfmts.h>
 
@@ -81,6 +82,9 @@ struct linux_binprm {
        int execfd;             /* File descriptor of the executable */
        unsigned long exec;
 
+       /* Close-on-exec files awaiting their final __fput(), see free_bprm(). */
+       struct llist_head cloexec_files;
+
        struct rlimit rlim_stack; /* Saved RLIMIT_STACK used during exec. */
 
        char buf[BINPRM_BUF_SIZE];
include/linux/fdtable.h +1 -2
index e6b641d9eb91..050f4a04157e 100644
@@ -105,7 +105,7 @@ struct fd_range {
        unsigned int from, to;
 };
 struct files_struct *dup_fd(struct files_struct *, struct fd_range *) __latent_entropy;
-void close_cloexec_files(struct files_struct *);
+void close_cloexec_files(struct files_struct *, struct llist_head *);
 int iterate_fd(struct files_struct *, unsigned,
                int (*)(const void *, struct file *, unsigned),
                const void *);
 
--
Quoted 2 lines

2.53.0

The patch looks fine in its own right, but there is a pre-existing deadlock reported and I think this will need adjustment to take care of it:
https://lore.kernel.org/linux-fsdevel/[email protected]/T/#u
* deadlock from exec_update_lock and reading procfs

author maintainer
#10 lore raw

RFC PATCH v2 5/16 fs: add switch_files_struct()

In reply to Christian Brauner

Add switch_files_struct() to install another table on a task. It consumes the reference to the new table and hands the old one back for the caller to put. Convert every place that switches a descriptor table.

No functional changes.

---
 fs/file.c               | 28 ++++++++++++++++------------
 include/linux/fdtable.h |  2 ++
 kernel/fork.c           |  6 ++----
 3 files changed, 20 insertions(+), 16 deletions(-)
fs/file.c +16 -12
index 88ede1262b3e..aec2adf59031 100644
@@ -515,16 +515,23 @@ void put_files_struct(struct files_struct *files)
 	}
 }
 
-void exit_files(struct task_struct *tsk)
+/* Install @files on @tsk, consuming the reference; returns the old table. */
+struct files_struct *switch_files_struct(struct task_struct *tsk,
+					 struct files_struct *files)
 {
-	struct files_struct * files = tsk->files;
+	struct files_struct *old;
 
-	if (files) {
-		task_lock(tsk);
-		tsk->files = NULL;
-		task_unlock(tsk);
-		put_files_struct(files);
-	}
+	task_lock(tsk);
+	old = tsk->files;
+	tsk->files = files;
+	task_unlock(tsk);
+	return old;
+}
+
+void exit_files(struct task_struct *tsk)
+{
+	if (tsk->files)
+		put_files_struct(switch_files_struct(tsk, NULL));
 }
 
 struct files_struct init_files = {
@@ -855,10 +862,7 @@ SYSCALL_DEFINE3(close_range, unsigned int, fd, unsigned int, max_fd,
 		 * We're done closing the files we were supposed to. Time to install
 		 * the new file descriptor table and drop the old one.
 		 */
-		task_lock(me);
-		me->files = cur_fds;
-		task_unlock(me);
-		put_files_struct(fds);
+		put_files_struct(switch_files_struct(me, cur_fds));
 	}
 
 	return 0;
include/linux/fdtable.h +2 -0
index 050f4a04157e..80f192412a5a 100644
@@ -100,6 +100,8 @@ static inline bool close_on_exec(unsigned int fd, const struct files_struct *fil
 struct task_struct;
 
 void put_files_struct(struct files_struct *fs);
+struct files_struct *switch_files_struct(struct task_struct *tsk,
+					 struct files_struct *files);
 int unshare_files(void);
 struct fd_range {
 	unsigned int from, to;
kernel/fork.c +2 -4
index 416758c8a3d4..b959191edf52 100644
@@ -3320,10 +3320,8 @@ int ksys_unshare(unsigned long unshare_flags)
 		if (new_fs)
 			new_fs = switch_fs_struct(new_fs);
 
-		if (new_fd) {
-			guard(task_lock)(current);
-			swap(current->files, new_fd);
-		}
+		if (new_fd)
+			new_fd = switch_files_struct(current, new_fd);
 
 		if (new_cred) {
 			/* Install the new user namespace */
Signature · 1 line
2.53.0
author maintainer
#11 lore raw

RFC PATCH v2 6/16 fs: move unshare_fd() to fs/file.c

In reply to Christian Brauner

Move dup_fd() and switch_files_struct() where the rest of the descriptor table lifecycle helpers live.

No functional changes.

---
 fs/file.c               | 18 ++++++++++++++++++
 include/linux/fdtable.h |  1 +
 kernel/fork.c           | 18 ------------------
 3 files changed, 19 insertions(+), 18 deletions(-)
fs/file.c +18 -0
index aec2adf59031..185de8deb39d 100644
@@ -471,6 +471,24 @@ struct files_struct *dup_fd(struct files_struct *oldf, struct fd_range *punch_ho
 	return newf;
 }
 
+/*
+ * Unshare file descriptor table if it is being shared
+ */
+int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp)
+{
+	struct files_struct *fd = current->files;
+
+	if ((unshare_flags & CLONE_FILES) &&
+	    (fd && atomic_read(&fd->count) > 1)) {
+		fd = dup_fd(fd, NULL);
+		if (IS_ERR(fd))
+			return PTR_ERR(fd);
+		*new_fdp = fd;
+	}
+
+	return 0;
+}
+
 static struct fdtable *close_files(struct files_struct * files)
 {
 	/*
include/linux/fdtable.h +1 -0
index 80f192412a5a..102fe4c20b7d 100644
@@ -103,6 +103,7 @@ void put_files_struct(struct files_struct *fs);
 struct files_struct *switch_files_struct(struct task_struct *tsk,
 					 struct files_struct *files);
 int unshare_files(void);
+int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp);
 struct fd_range {
 	unsigned int from, to;
 };
kernel/fork.c +0 -18
index b959191edf52..c456958c51f4 100644
@@ -3207,24 +3207,6 @@ static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
 	return 0;
 }
 
-/*
- * Unshare file descriptor table if it is being shared
- */
-static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp)
-{
-	struct files_struct *fd = current->files;
-
-	if ((unshare_flags & CLONE_FILES) &&
-	    (fd && atomic_read(&fd->count) > 1)) {
-		fd = dup_fd(fd, NULL);
-		if (IS_ERR(fd))
-			return PTR_ERR(fd);
-		*new_fdp = fd;
-	}
-
-	return 0;
-}
-
 /*
  * unshare allows a process to 'unshare' part of the process
  * context which was originally shared using clone.  copy_*
Signature · 1 line
2.53.0
Reviewed-by on v2 6/16
#12 lore raw

Re: [PATCH RFC v2 06/16] fs: move unshare_fd() to fs/file.c

Quoted 85 lines · Christian Brauner

Move dup_fd() and switch_files_struct() where the rest of the descriptor table lifecycle helpers live.

No functional changes.

---
 fs/file.c               | 18 ++++++++++++++++++
 include/linux/fdtable.h |  1 +
 kernel/fork.c           | 18 ------------------
 3 files changed, 19 insertions(+), 18 deletions(-)
fs/file.c +18 -0
index aec2adf59031..185de8deb39d 100644
@@ -471,6 +471,24 @@ struct files_struct *dup_fd(struct files_struct *oldf, struct fd_range *punch_ho
        return newf;
 }
 
+/*
+ * Unshare file descriptor table if it is being shared
+ */
+int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp)
+{
+       struct files_struct *fd = current->files;
+
+       if ((unshare_flags & CLONE_FILES) &&
+           (fd && atomic_read(&fd->count) > 1)) {
+               fd = dup_fd(fd, NULL);
+               if (IS_ERR(fd))
+                       return PTR_ERR(fd);
+               *new_fdp = fd;
+       }
+
+       return 0;
+}
+
 static struct fdtable *close_files(struct files_struct * files)
 {
        /*
include/linux/fdtable.h +1 -0
index 80f192412a5a..102fe4c20b7d 100644
@@ -103,6 +103,7 @@ void put_files_struct(struct files_struct *fs);
 struct files_struct *switch_files_struct(struct task_struct *tsk,
                                         struct files_struct *files);
 int unshare_files(void);
+int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp);
 struct fd_range {
        unsigned int from, to;
 };
kernel/fork.c +0 -19
index b959191edf52..c456958c51f4 100644
@@ -3207,24 +3207,6 @@ static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
        return 0;
 }
 
-/*
- * Unshare file descriptor table if it is being shared
- */
-static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp)
-{
-       struct files_struct *fd = current->files;
-
-       if ((unshare_flags & CLONE_FILES) &&
-           (fd && atomic_read(&fd->count) > 1)) {
-               fd = dup_fd(fd, NULL);
-               if (IS_ERR(fd))
-                       return PTR_ERR(fd);
-               *new_fdp = fd;
-       }
-
-       return 0;
-}
-
 /*
  * unshare allows a process to 'unshare' part of the process
  * context which was originally shared using clone.  copy_*
 
--
Quoted 2 lines

2.53.0

author maintainer
#13 lore raw

RFC PATCH v2 7/16 fs: remove unshare_files()

In reply to Christian Brauner

exec is the only caller left since commit 433967cab51e ("coredump: stop unsharing the file descriptor table"). All it does is call unshare_fd() with CLONE_FILES and install the copy. Kill the pointless helper and open-code it.

No functional changes.

---
 fs/exec.c               |  5 ++++-
 include/linux/fdtable.h |  1 -
 kernel/fork.c           | 24 ------------------------
 3 files changed, 4 insertions(+), 26 deletions(-)
fs/exec.c +4 -1
index b1f449dba258..713819244d23 100644
@@ -1124,6 +1124,7 @@ static struct file *bprm_identity_file(const struct linux_binprm *bprm)
 int begin_new_exec(struct linux_binprm * bprm)
 {
 	struct task_struct *me = current;
+	struct files_struct *files = NULL;
 	int retval;
 
 	/* A pending PT_INTERP substitution this format cannot consume. */
@@ -1160,9 +1161,11 @@ int begin_new_exec(struct linux_binprm * bprm)
 	io_uring_task_cancel();
 
 	/* Ensure the files table is not shared. */
-	retval = unshare_files();
+	retval = unshare_fd(CLONE_FILES, &files);
 	if (retval)
 		goto out;
+	if (files)
+		put_files_struct(switch_files_struct(me, files));
 
 	/*
 	 * Must be called _before_ exec_mmap() as bprm->mm is
include/linux/fdtable.h +0 -1
index 102fe4c20b7d..15ee6292e0e3 100644
@@ -102,7 +102,6 @@ struct task_struct;
 void put_files_struct(struct files_struct *fs);
 struct files_struct *switch_files_struct(struct task_struct *tsk,
 					 struct files_struct *files);
-int unshare_files(void);
 int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp);
 struct fd_range {
 	unsigned int from, to;
kernel/fork.c +0 -24
index c456958c51f4..ba74705ca191 100644
@@ -3336,30 +3336,6 @@ SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
 	return ksys_unshare(unshare_flags);
 }
 
-/*
- *	Helper to unshare the files of the current task.
- *	We don't want to expose copy_files internals to
- *	the exec layer of the kernel.
- */
-
-int unshare_files(void)
-{
-	struct task_struct *task = current;
-	struct files_struct *old, *copy = NULL;
-	int error;
-
-	error = unshare_fd(CLONE_FILES, &copy);
-	if (error || !copy)
-		return error;
-
-	old = task->files;
-	task_lock(task);
-	task->files = copy;
-	task_unlock(task);
-	put_files_struct(old);
-	return 0;
-}
-
 static int sysctl_max_threads(const struct ctl_table *table, int write,
 		       void *buffer, size_t *lenp, loff_t *ppos)
 {
Signature · 1 line
2.53.0
Reviewed-by on v2 7/16
#14 lore raw

Re: [PATCH RFC v2 07/16] fs: remove unshare_files()

Quoted 89 lines · Christian Brauner

exec is the only caller left since commit 433967cab51e ("coredump: stop unsharing the file descriptor table"). All it does is call unshare_fd() with CLONE_FILES and install the copy. Kill the pointless helper and open-code it.

No functional changes.

---
 fs/exec.c               |  5 ++++-
 include/linux/fdtable.h |  1 -
 kernel/fork.c           | 24 ------------------------
 3 files changed, 4 insertions(+), 26 deletions(-)
fs/exec.c +4 -1
index b1f449dba258..713819244d23 100644
@@ -1124,6 +1124,7 @@ static struct file *bprm_identity_file(const struct linux_binprm *bprm)
 int begin_new_exec(struct linux_binprm * bprm)
 {
        struct task_struct *me = current;
+       struct files_struct *files = NULL;
        int retval;
 
        /* A pending PT_INTERP substitution this format cannot consume. */
@@ -1160,9 +1161,11 @@ int begin_new_exec(struct linux_binprm * bprm)
        io_uring_task_cancel();
 
        /* Ensure the files table is not shared. */
-       retval = unshare_files();
+       retval = unshare_fd(CLONE_FILES, &files);
        if (retval)
                goto out;
+       if (files)
+               put_files_struct(switch_files_struct(me, files));
 
        /*
         * Must be called _before_ exec_mmap() as bprm->mm is
include/linux/fdtable.h +0 -1
index 102fe4c20b7d..15ee6292e0e3 100644
@@ -102,7 +102,6 @@ struct task_struct;
 void put_files_struct(struct files_struct *fs);
 struct files_struct *switch_files_struct(struct task_struct *tsk,
                                         struct files_struct *files);
-int unshare_files(void);
 int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp);
 struct fd_range {
        unsigned int from, to;
kernel/fork.c +0 -25
index c456958c51f4..ba74705ca191 100644
@@ -3336,30 +3336,6 @@ SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
        return ksys_unshare(unshare_flags);
 }
 
-/*
- *     Helper to unshare the files of the current task.
- *     We don't want to expose copy_files internals to
- *     the exec layer of the kernel.
- */
-
-int unshare_files(void)
-{
-       struct task_struct *task = current;
-       struct files_struct *old, *copy = NULL;
-       int error;
-
-       error = unshare_fd(CLONE_FILES, &copy);
-       if (error || !copy)
-               return error;
-
-       old = task->files;
-       task_lock(task);
-       task->files = copy;
-       task_unlock(task);
-       put_files_struct(old);
-       return 0;
-}
-
 static int sysctl_max_threads(const struct ctl_table *table, int write,
                       void *buffer, size_t *lenp, loff_t *ppos)
 {
 
--
Quoted 2 lines

2.53.0

author maintainer
#15 lore raw

RFC PATCH v2 8/16 exec: release fdtable after exec locks drop

In reply to Christian Brauner

During exec the task gets a private fdtable and releases the shared fdtable. This all happens under cred_guard_mutex. If the exec'ing task has the last reference on the fdtable close_files() closes all files. Today this happens to be deferred to task work. Following patches will make that part synchronous so the final put needs to move out of the cred_guard_mutex.

The shared table now lives until free_bprm() instead of dying in begin_new_exec(). This doesn't matter as nothing can get access to the old table anymore and closing of files would've been deferred to task work anyway.

---
 fs/exec.c               | 6 ++++--
 include/linux/binfmts.h | 2 ++
 2 files changed, 6 insertions(+), 2 deletions(-)
fs/exec.c +4 -2
index 713819244d23..be8601d9c691 100644
@@ -1165,7 +1165,7 @@ int begin_new_exec(struct linux_binprm * bprm)
 	if (retval)
 		goto out;
 	if (files)
-		put_files_struct(switch_files_struct(me, files));
+		bprm->old_files = switch_files_struct(me, files);
 
 	/*
 	 * Must be called _before_ exec_mmap() as bprm->mm is
@@ -1472,7 +1472,9 @@ static void free_bprm(struct linux_binprm *bprm)
 		mutex_unlock(&current->signal->cred_guard_mutex);
 		abort_creds(bprm->cred);
 	}
-	/* The exec locks are out of the way now, see close_cloexec_files(). */
+	/* The exec locks are gone, release what begin_new_exec() closed. */
+	if (bprm->old_files)
+		put_files_struct(bprm->old_files);
 	fput_list(&bprm->cloexec_files);
 	/* exec swapped the mm but failed before setup_new_exec() freed it */
 	if (bprm->old_mm)
include/linux/binfmts.h +2 -0
index be935320f1c7..0f0fcf859b4f 100644
@@ -37,6 +37,8 @@ struct linux_binprm {
 #endif
 	struct mm_struct *mm;
 	struct mm_struct *old_mm;	/* replaced address space, freed by setup_new_exec() */
+	/* Descriptor table displaced by begin_new_exec(), put by free_bprm(). */
+	struct files_struct *old_files;
 	/* user_ns published to task->exec_state at execve, narrowed by would_dump(). */
 	struct user_namespace *user_ns;
 	unsigned long p; /* current top of mem */
Signature · 1 line
2.53.0
author maintainer
#16 lore raw

RFC PATCH v2 9/16 fs: make close_files() synchronous

In reply to Christian Brauner

When the last reference to a descriptor table is dropped close_files() closes every file but punts the actual work to task work. For an exiting task that task work only runs in exit_task_work().

Before commit 4a9d4b024a31 ("switch fput to task_work_add") fput() was synchronous everywhere and exit released its files in exit_files().

The deferral made fput() safe from any context. And exit_files() offloaded to task work as a side-effect. And that has downsides.

Oleg and Neil noticed that some time ago. A task that exits with a big descriptor table ends up queueing a very large number of files on task work. That walks the task work list under ->pi_lock and costs a lot of atomics too.

Let close_files() close right away. The walk puts the last references through filp_close_list(). If it's the last reference it places them on a private list and drains it through fput_list(). Note, this keeps keeps the exact order the deferred path had. Every filp_flush() first and then the final __fput()s in the reverse order task_work_run() giving the same ordering even.

Every put of a dying table is synchronous now:

- exit_files()
- copy_process()
- close_range(CLOSE_RANGE_UNSHARE)
- unshare(2)
- exec

Kernel threads don't own a file descriptor table and exec already splats where they to exec. kthreadd and every kthread share init_files and init_task pins that forever.

---
 fs/file.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
fs/file.c +5 -2
index 185de8deb39d..47ce844be95b 100644
@@ -489,7 +489,7 @@ int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp)
 	return 0;
 }
 
-static struct fdtable *close_files(struct files_struct * files)
+static struct fdtable *close_files(struct files_struct *files)
 {
 	/*
 	 * It is safe to dereference the fd table without RCU or
@@ -498,6 +498,7 @@ static struct fdtable *close_files(struct files_struct * files)
 	 */
 	struct fdtable *fdt = rcu_dereference_raw(files->fdt);
 	unsigned int i, j = 0;
+	LLIST_HEAD(to_close);
 
 	for (;;) {
 		unsigned long set;
@@ -509,7 +510,8 @@ static struct fdtable *close_files(struct files_struct * files)
 			if (set & 1) {
 				struct file *file = fdt->fd[i];
 				if (file) {
-					filp_close(file, files);
+					filp_flush(file, files);
+					fput_close_list(file, &to_close);
 					cond_resched();
 				}
 			}
@@ -518,6 +520,7 @@ static struct fdtable *close_files(struct files_struct * files)
 		}
 	}
 
+	fput_list(&to_close);
 	return fdt;
 }
 
Signature · 1 line
2.53.0
author maintainer
#17 lore raw

RFC PATCH v2 10/16 fs: make close_range() synchronous

In reply to Christian Brauner

__range_close() closes through filp_close() so every file the caller held the last reference to is punted to task work. That costs one cmpxchg per file plus a list entry for any later task_work_cancel() to search under ->pi_lock. close_range(2) exists to close many descriptors in one go fast. So convert it to the same synchronous treatment as close(2) and close_files().

We collect the last references through filp_close_list() and run any final __fput()s through fput_list() right before returning. close_range(2) now behaves like close(2).

---
 fs/file.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
fs/file.c +6 -3
index 47ce844be95b..608e6a1fa69b 100644
@@ -798,7 +798,7 @@ static inline void __range_cloexec(struct files_struct *cur_fds,
 }
 
 static inline void __range_close(struct files_struct *files, unsigned int fd,
-				 unsigned int max_fd)
+				 unsigned int max_fd, struct llist_head *list)
 {
 	struct file *file;
 	struct fdtable *fdt;
@@ -815,7 +815,8 @@ static inline void __range_close(struct files_struct *files, unsigned int fd,
 		file = file_close_fd_locked(files, fd);
 		if (file) {
 			spin_unlock(&files->file_lock);
-			filp_close(file, files);
+			filp_flush(file, files);
+			fput_close_list(file, list);
 			cond_resched();
 			spin_lock(&files->file_lock);
 			fdt = files_fdtable(files);
@@ -845,6 +846,7 @@ SYSCALL_DEFINE3(close_range, unsigned int, fd, unsigned int, max_fd,
 {
 	struct task_struct *me = current;
 	struct files_struct *cur_fds = me->files, *fds = NULL;
+	LLIST_HEAD(to_close);
 
 	if (flags & ~(CLOSE_RANGE_UNSHARE | CLOSE_RANGE_CLOEXEC))
 		return -EINVAL;
@@ -876,7 +878,7 @@ SYSCALL_DEFINE3(close_range, unsigned int, fd, unsigned int, max_fd,
 	if (flags & CLOSE_RANGE_CLOEXEC)
 		__range_cloexec(cur_fds, fd, max_fd);
 	else
-		__range_close(cur_fds, fd, max_fd);
+		__range_close(cur_fds, fd, max_fd, &to_close);
 
 	if (fds) {
 		/*
@@ -886,6 +888,7 @@ SYSCALL_DEFINE3(close_range, unsigned int, fd, unsigned int, max_fd,
 		put_files_struct(switch_files_struct(me, cur_fds));
 	}
 
+	fput_list(&to_close);
 	return 0;
 }
 
Signature · 1 line
2.53.0
author maintainer
#18 lore raw

RFC PATCH v2 11/16 coredump: s/startup/done/g

In reply to Christian Brauner

We're going to use that in a bit. Rename it to something easier to understand.

No functional changes.

---
 fs/coredump.c                | 4 ++--
 include/linux/sched/signal.h | 3 ++-
 kernel/exit.c                | 2 +-
 3 files changed, 5 insertions(+), 4 deletions(-)
fs/coredump.c +2 -2
index 9addd2d59b7b..545a6df48ea8 100644
@@ -523,7 +523,7 @@ static int coredump_wait(int exit_code, struct core_state *core_state)
 	struct task_struct *tsk = current;
 	int core_waiters = -EBUSY;
 
-	init_completion(&core_state->startup);
+	init_completion(&core_state->done);
 	core_state->dumper.task = tsk;
 	core_state->dumper.next = NULL;
 
@@ -531,7 +531,7 @@ static int coredump_wait(int exit_code, struct core_state *core_state)
 	if (core_waiters > 0) {
 		struct core_thread *ptr;
 
-		wait_for_completion_state(&core_state->startup,
+		wait_for_completion_state(&core_state->done,
 					  TASK_UNINTERRUPTIBLE|TASK_FREEZABLE);
 		/*
 		 * Wait for all the threads to become inactive, so that
include/linux/sched/signal.h +2 -1
index 584ae88b435e..ed9e2d49d166 100644
@@ -81,7 +81,8 @@ struct core_thread {
 struct core_state {
 	atomic_t nr_threads;
 	struct core_thread dumper;
-	struct completion startup;
+	/* Completed by the last thread to park. */
+	struct completion done;
 };
 
 /*
kernel/exit.c +1 -1
index 97686af89501..8702e3ead7dd 100644
@@ -440,7 +440,7 @@ static void coredump_task_exit(struct task_struct *tsk,
 	 * to core_state->dumper.
 	 */
 	if (atomic_dec_and_test(&core_state->nr_threads))
-		complete(&core_state->startup);
+		complete(&core_state->done);
 
 	for (;;) {
 		set_current_state(TASK_IDLE|TASK_FREEZABLE);
Signature · 1 line
2.53.0
author maintainer
#19 lore raw

RFC PATCH v2 12/16 coredump: factor out coredump_wait_inactive()

In reply to Christian Brauner

Factor out a new coredump_wait_inactive() helper that COREDUMP_CLOSE_FILES can consume in a bit.

No functional changes.

---
 fs/coredump.c | 36 ++++++++++++++++++++----------------
 1 file changed, 20 insertions(+), 16 deletions(-)
fs/coredump.c +20 -16
index 545a6df48ea8..d0796536e03f 100644
@@ -518,6 +518,24 @@ static int zap_threads(struct task_struct *tsk,
 	return nr;
 }
 
+static void coredump_wait_inactive(struct core_state *core_state)
+{
+	struct core_thread *ptr;
+
+	wait_for_completion_state(&core_state->done,
+				  TASK_UNINTERRUPTIBLE|TASK_FREEZABLE);
+	/*
+	 * Wait for all the threads to become inactive, so that
+	 * all the thread context (extended register state, like
+	 * fpu etc) gets copied to the memory.
+	 */
+	ptr = core_state->dumper.next;
+	while (ptr != NULL) {
+		wait_task_inactive(ptr->task, TASK_ANY);
+		ptr = ptr->next;
+	}
+}
+
 static int coredump_wait(int exit_code, struct core_state *core_state)
 {
 	struct task_struct *tsk = current;
@@ -528,22 +546,8 @@ static int coredump_wait(int exit_code, struct core_state *core_state)
 	core_state->dumper.next = NULL;
 
 	core_waiters = zap_threads(tsk, core_state, exit_code);
-	if (core_waiters > 0) {
-		struct core_thread *ptr;
-
-		wait_for_completion_state(&core_state->done,
-					  TASK_UNINTERRUPTIBLE|TASK_FREEZABLE);
-		/*
-		 * Wait for all the threads to become inactive, so that
-		 * all the thread context (extended register state, like
-		 * fpu etc) gets copied to the memory.
-		 */
-		ptr = core_state->dumper.next;
-		while (ptr != NULL) {
-			wait_task_inactive(ptr->task, TASK_ANY);
-			ptr = ptr->next;
-		}
-	}
+	if (core_waiters > 0)
+		coredump_wait_inactive(core_state);
 
 	return core_waiters;
 }
Signature · 1 line
2.53.0
author maintainer
#20 lore raw

RFC PATCH v2 13/16 fs: add alloc_files_struct()

In reply to Christian Brauner

Add a way to get an empty descriptor table with one reference. Let dup_fd() use that helper. The coredump code will use it too in a bit.

No functional changes.

---
 fs/file.c               | 49 ++++++++++++++++++++++++++++++++++++++-----------
 include/linux/fdtable.h |  1 +
 2 files changed, 39 insertions(+), 11 deletions(-)
fs/file.c +38 -11
index 608e6a1fa69b..ccbaa71dfbe4 100644
@@ -375,21 +375,15 @@ static unsigned int sane_fdtable_size(struct fdtable *fdt, struct fd_range *punc
 	return ALIGN(last + 1, BITS_PER_LONG);
 }
 
-/*
- * Allocate a new descriptor table and copy contents from the passed in
- * instance.  Returns a pointer to cloned table on success, ERR_PTR()
- * on failure.  For 'punch_hole' see sane_fdtable_size().
- */
-struct files_struct *dup_fd(struct files_struct *oldf, struct fd_range *punch_hole)
+/* A table with one reference and the embedded fdtable, nothing copied yet. */
+static struct files_struct *alloc_files(gfp_t gfp)
 {
 	struct files_struct *newf;
-	struct file **old_fds, **new_fds;
-	unsigned int open_files, i;
-	struct fdtable *old_fdt, *new_fdt;
+	struct fdtable *new_fdt;
 
-	newf = kmem_cache_alloc(files_cachep, GFP_KERNEL);
+	newf = kmem_cache_alloc(files_cachep, gfp);
 	if (!newf)
-		return ERR_PTR(-ENOMEM);
+		return NULL;
 
 	atomic_set(&newf->count, 1);
 
@@ -404,6 +398,39 @@ struct files_struct *dup_fd(struct files_struct *oldf, struct fd_range *punch_ho
 	new_fdt->full_fds_bits = newf->full_fds_bits_init;
 	new_fdt->fd = &newf->fd_array[0];
 
+	return newf;
+}
+
+/* An empty descriptor table with one reference. */
+struct files_struct *alloc_files_struct(void)
+{
+	struct files_struct *newf;
+
+	newf = alloc_files(GFP_KERNEL | __GFP_ZERO);
+	if (!newf)
+		return NULL;
+
+	rcu_assign_pointer(newf->fdt, &newf->fdtab);
+	return newf;
+}
+
+/*
+ * Allocate a new descriptor table and copy contents from the passed in
+ * instance.  Returns a pointer to cloned table on success, ERR_PTR()
+ * on failure.  For 'punch_hole' see sane_fdtable_size().
+ */
+struct files_struct *dup_fd(struct files_struct *oldf, struct fd_range *punch_hole)
+{
+	struct files_struct *newf;
+	struct file **old_fds, **new_fds;
+	unsigned int open_files, i;
+	struct fdtable *old_fdt, *new_fdt;
+
+	newf = alloc_files(GFP_KERNEL);
+	if (!newf)
+		return ERR_PTR(-ENOMEM);
+	new_fdt = &newf->fdtab;
+
 	spin_lock(&oldf->file_lock);
 	old_fdt = files_fdtable(oldf);
 	open_files = sane_fdtable_size(old_fdt, punch_hole);
include/linux/fdtable.h +1 -0
index 15ee6292e0e3..811994b16bed 100644
@@ -100,6 +100,7 @@ static inline bool close_on_exec(unsigned int fd, const struct files_struct *fil
 struct task_struct;
 
 void put_files_struct(struct files_struct *fs);
+struct files_struct *alloc_files_struct(void);
 struct files_struct *switch_files_struct(struct task_struct *tsk,
 					 struct files_struct *files);
 int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp);
Signature · 1 line
2.53.0
author maintainer
#21 lore raw

RFC PATCH v2 14/16 coredump: add COREDUMP_CLOSE_FILES

In reply to Christian Brauner

Add COREDUMP_CLOSE_FILES and allow a coredump server to request that the thread-group closes all files before creating the coredump.

There have been several attempts to let the dumping process decide through a new fcntl() flag, a new procfs file or a new coredump_filter bit that its descriptors go away early. That's just broken imho.

Tools like systemd-coredump walk /proc/<pid>/fd and /proc/<pid>/fdinfo and some use pidfd_getfd() to preserve files of the crashing process. Only the coredump server knows whether it still needs the descriptors.

So let the coredump server ask for it. Add a new COREDUMP_CLOSE_FILES feature bit. If the coredump server raises it the kernel drops the descriptor tables of the thread group right after the handshake and before it generates the coredump.

COREDUMP_CLOSE_FILES doesn't work with COREDUMP_REJECT. A rejected task exits and closes everything right away anyway.

---
 fs/coredump.c                 | 55 ++++++++++++++++++++++++++++++++++++++++++-
 include/linux/sched/signal.h  |  4 +++-
 include/uapi/linux/coredump.h |  8 +++++++
 kernel/exit.c                 | 13 ++++++++++
 4 files changed, 78 insertions(+), 2 deletions(-)
fs/coredump.c +54 -1
index d0796536e03f..506410132e30 100644
@@ -552,6 +552,48 @@ static int coredump_wait(int exit_code, struct core_state *core_state)
 	return core_waiters;
 }
 
+/*
+ * Allocate a new empty fdtable and switch the whole thread-group to it.
+ * Put all the old fdtables freeing up resources and locks before writing the
+ * coredump.
+ */
+static bool coredump_close_files(struct core_state *core_state)
+{
+	struct files_struct *files;
+	struct core_thread *ct;
+	int nr = 0;
+
+	files = alloc_files_struct();
+	if (!files)
+		return false;
+
+	/* Tasks without a table such as vhost workers can be skipped. */
+	for (ct = core_state->dumper.next; ct; ct = ct->next)
+		if (ct->task->files)
+			nr++;
+	atomic_set(&core_state->nr_threads, nr);
+	reinit_completion(&core_state->done);
+
+	for (ct = core_state->dumper.next; ct; ct = ct->next) {
+		if (!ct->task->files)
+			continue;
+		/* ct->files holds a reference until the thread switches to it. */
+		atomic_inc(&files->count);
+		/* Pairs with the acquire in coredump_task_exit(). */
+		smp_store_release(&ct->files, files);
+		wake_up_process(ct->task);
+	}
+
+	/* Use the dumper's real creds not the overriden ones. */
+	scoped_with_creds(current_real_cred())
+		put_files_struct(switch_files_struct(current, files));
+
+	if (nr)
+		coredump_wait_inactive(core_state);
+
+	return true;
+}
+
 static void coredump_finish(enum coredump_state state)
 {
 	struct core_thread *curr, *next;
@@ -841,7 +883,8 @@ static bool coredump_sock_request(struct core_name *cn, struct coredump_params *
 		.mask			= COREDUMP_KERNEL | COREDUMP_USERSPACE |
 					  COREDUMP_REJECT | COREDUMP_WAIT |
 					  COREDUMP_RECORDS | COREDUMP_SPARSE |
-					  COREDUMP_MEMORY_TYPES,
+					  COREDUMP_MEMORY_TYPES |
+					  COREDUMP_CLOSE_FILES,
 		.size_ack		= sizeof(struct coredump_ack),
 		.memory_types		= cprm->memory_types,
 		.memory_types_mask	= COREDUMP_MEMORY_ALL,
@@ -909,6 +952,12 @@ static bool coredump_sock_request(struct core_name *cn, struct coredump_params *
 		return false;
 	}
 
+	/* A rejected task exits right away and closes everything anyway. */
+	if ((ack.mask & COREDUMP_CLOSE_FILES) && (ack.mask & COREDUMP_REJECT)) {
+		coredump_sock_mark(cprm->file, COREDUMP_MARK_CONFLICTING);
+		return false;
+	}
+
 	if (ack.mask & COREDUMP_MEMORY_TYPES) {
 		/* The memory types need the whole field. */
 		if (usize < COREDUMP_ACK_SIZE_VER1) {
@@ -1224,6 +1273,10 @@ static void do_coredump(struct core_name *cn, struct coredump_params *cprm,
 	if (cprm->mask & COREDUMP_REJECT)
 		return;
 
+	if ((cprm->mask & COREDUMP_CLOSE_FILES) &&
+	    !coredump_close_files(current->signal->core_state))
+		return;
+
 	if ((cprm->mask & COREDUMP_KERNEL) && !coredump_write(cprm, binfmt))
 		return;
 
include/linux/sched/signal.h +3 -1
index ed9e2d49d166..fed02a427de3 100644
@@ -76,12 +76,14 @@ struct multiprocess_signals {
 struct core_thread {
 	struct task_struct *task;
 	struct core_thread *next;
+	/* The empty table to switch to, published by the dumping thread. */
+	struct files_struct *files;
 };
 
 struct core_state {
 	atomic_t nr_threads;
 	struct core_thread dumper;
-	/* Completed by the last thread to park. */
+	/* Completed by the last thread to park, reused for the table switch. */
 	struct completion done;
 };
 
include/uapi/linux/coredump.h +8 -0
index 6d0c53b534ea..ec09d7ab0131 100644
@@ -19,6 +19,9 @@
  * @COREDUMP_MEMORY_TYPES: dump the memory types in
  *                          coredump_ack->memory_types instead of the ones
  *                          the task selected; requires COREDUMP_KERNEL
+ * @COREDUMP_CLOSE_FILES: close all file descriptors of the task before the
+ *                        coredump is generated; incompatible with
+ *                        COREDUMP_REJECT
  */
 enum {
 	COREDUMP_KERNEL		= (1ULL << 0),
@@ -28,6 +31,7 @@ enum {
 	COREDUMP_RECORDS	= (1ULL << 4),
 	COREDUMP_SPARSE		= (1ULL << 5),
 	COREDUMP_MEMORY_TYPES	= (1ULL << 6),
+	COREDUMP_CLOSE_FILES	= (1ULL << 7),
 };
 
 /**
@@ -137,6 +141,10 @@ enum {
  * Note that @memory_types must be zero if COREDUMP_MEMORY_TYPES isn't
  * raised. COREDUMP_MEMORY_TYPES requires COREDUMP_KERNEL and an ack of
  * at least COREDUMP_ACK_SIZE_VER1 bytes.
+ *
+ * If COREDUMP_CLOSE_FILES is raised in @mask the kernel closes the file
+ * descriptors of the coredumping task before it generates the coredump.
+ * The task ends up with an empty descriptor table.
  */
 struct coredump_ack {
 	__u32 size;
kernel/exit.c +13 -0
index 8702e3ead7dd..70d9a862e38c 100644
@@ -25,6 +25,7 @@
 #include <linux/acct.h>
 #include <linux/tsacct_kern.h>
 #include <linux/file.h>
+#include <linux/fdtable.h>
 #include <linux/freezer.h>
 #include <linux/binfmts.h>
 #include <linux/nsproxy.h>
@@ -428,9 +429,11 @@ kill_orphaned_pgrp(struct task_struct *tsk, struct task_struct *parent)
 static void coredump_task_exit(struct task_struct *tsk,
 			       struct core_state *core_state)
 {
+	struct files_struct *files;
 	struct core_thread self;
 
 	self.task = tsk;
+	self.files = NULL;
 	if (self.task->flags & PF_SIGNALED)
 		self.next = xchg(&core_state->dumper.next, &self);
 	else
@@ -446,6 +449,16 @@ static void coredump_task_exit(struct task_struct *tsk,
 		set_current_state(TASK_IDLE|TASK_FREEZABLE);
 		if (!self.task) /* see coredump_finish() */
 			break;
+		/* Pairs with the release in coredump_close_files(). */
+		files = smp_load_acquire(&self.files);
+		if (files) {
+			__set_current_state(TASK_RUNNING);
+			self.files = NULL;
+			put_files_struct(switch_files_struct(tsk, files));
+			if (atomic_dec_and_test(&core_state->nr_threads))
+				complete(&core_state->done);
+			continue;
+		}
 		schedule();
 	}
 	__set_current_state(TASK_RUNNING);
Signature · 1 line
2.53.0
author maintainer
#22 lore raw

RFC PATCH v2 15/16 tools: sync coredump.h header

In reply to Christian Brauner

Sync the headers for the selftests.

---
 tools/include/uapi/linux/coredump.h | 8 ++++++++
 1 file changed, 8 insertions(+)
tools/include/uapi/linux/coredump.h +8 -0
index 6d0c53b534ea..ec09d7ab0131 100644
@@ -19,6 +19,9 @@
  * @COREDUMP_MEMORY_TYPES: dump the memory types in
  *                          coredump_ack->memory_types instead of the ones
  *                          the task selected; requires COREDUMP_KERNEL
+ * @COREDUMP_CLOSE_FILES: close all file descriptors of the task before the
+ *                        coredump is generated; incompatible with
+ *                        COREDUMP_REJECT
  */
 enum {
 	COREDUMP_KERNEL		= (1ULL << 0),
@@ -28,6 +31,7 @@ enum {
 	COREDUMP_RECORDS	= (1ULL << 4),
 	COREDUMP_SPARSE		= (1ULL << 5),
 	COREDUMP_MEMORY_TYPES	= (1ULL << 6),
+	COREDUMP_CLOSE_FILES	= (1ULL << 7),
 };
 
 /**
@@ -137,6 +141,10 @@ enum {
  * Note that @memory_types must be zero if COREDUMP_MEMORY_TYPES isn't
  * raised. COREDUMP_MEMORY_TYPES requires COREDUMP_KERNEL and an ack of
  * at least COREDUMP_ACK_SIZE_VER1 bytes.
+ *
+ * If COREDUMP_CLOSE_FILES is raised in @mask the kernel closes the file
+ * descriptors of the coredumping task before it generates the coredump.
+ * The task ends up with an empty descriptor table.
  */
 struct coredump_ack {
 	__u32 size;
Signature · 1 line
2.53.0
author maintainer
#23 lore raw

RFC PATCH v2 16/16 selftests/coredump: test COREDUMP_CLOSE_FILES

In reply to Christian Brauner

Test COREDUMP_CLOSE_FILES.

---
 tools/testing/selftests/coredump/Makefile          |   4 +-
 .../selftests/coredump/coredump_close_files_test.c | 592 +++++++++++++++++++++
 .../coredump/coredump_socket_protocol_test.c       |   6 +
 .../selftests/coredump/coredump_test_helpers.c     |   3 +-
 4 files changed, 603 insertions(+), 2 deletions(-)
tools/testing/selftests/coredump/Makefile +3 -1
index dece1a31d561..dc8489d40618 100644
@@ -3,7 +3,8 @@ CFLAGS += -Wall -O0 -g $(KHDR_INCLUDES) $(TOOLS_INCLUDES)
 
 TEST_GEN_PROGS := stackdump_test \
 		  coredump_socket_test \
-		  coredump_socket_protocol_test
+		  coredump_socket_protocol_test \
+		  coredump_close_files_test
 TEST_FILES := stackdump
 
 include ../lib.mk
@@ -11,3 +12,4 @@ include ../lib.mk
 $(OUTPUT)/stackdump_test: coredump_test_helpers.c
 $(OUTPUT)/coredump_socket_test: coredump_test_helpers.c
 $(OUTPUT)/coredump_socket_protocol_test: coredump_test_helpers.c
+$(OUTPUT)/coredump_close_files_test: coredump_test_helpers.c
tools/testing/selftests/coredump/coredump_close_files_test.c new file +592 -0

592 lines not on this page · raw message

tools/testing/selftests/coredump/coredump_socket_protocol_test.c +6 -0
index f5c9bad87546..beb167698cfd 100644
@@ -2377,6 +2377,12 @@ TEST_F(coredump, socket_request_memory_types_without_kernel)
 	check_conflicting_ack(_metadata, self, COREDUMP_USERSPACE | COREDUMP_MEMORY_TYPES);
 }
 
+/* A rejected task closes everything on its way out anyway. */
+TEST_F(coredump, socket_request_close_files_reject)
+{
+	check_conflicting_ack(_metadata, self, COREDUMP_REJECT | COREDUMP_CLOSE_FILES);
+}
+
 /*
  * A server built with the first structs reads the request it knows,
  * discards the rest and acks with the ack it knows. It raises nothing
tools/testing/selftests/coredump/coredump_test_helpers.c +2 -1
index 4e36e3e4fb78..65132a0deced 100644
@@ -1612,7 +1612,8 @@ bool send_coredump_ack(int fd, const struct coredump_req *req,
 #define TEST_REQ_MASK_ALL					\
 	(COREDUMP_KERNEL | COREDUMP_USERSPACE |			\
 	 COREDUMP_REJECT | COREDUMP_WAIT |			\
-	 COREDUMP_RECORDS | COREDUMP_SPARSE | COREDUMP_MEMORY_TYPES)
+	 COREDUMP_RECORDS | COREDUMP_SPARSE | COREDUMP_MEMORY_TYPES | \
+	 COREDUMP_CLOSE_FILES)
 
 bool check_coredump_req(const struct coredump_req *req)
 {
Signature · 1 line
2.53.0