Skip to contentSkip to conversation

coredump, files: exit files on request

RFC PATCH Superseded Christian Brauner 3 participants 17 messages Aug 24 – Aug 28

Subsystems (2)

v1 of 4 Superseded Latest is v4 →

lore
Share & tools
lore

Christian Brauner

author maintainer
#0 lore raw

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 first patch is somewhat unrelated but without it the code would have to become so ugly to the point of being unacceptable so it's a stylistic prerequisite imho.

In the first patch we make exit_files() synchronous and stop shunting all files onto task work only to run task work right after. For tasks exiting with a very 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.

So let close_files() close right away. No locks are held, the path already sleeps, close() does the same thing already. Kernel threads can just keep deferring. ->flush() and ->release() now run before exit_fs() and disassociate_ctty() which should be fine.

The other half is adding support for coredumps to 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.

A new COREDUMP_CLOSE_FILES extension that allows a coredump server to request that the thread-group close all files before generating the coredump.

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.

---
Christian Brauner (7):
fs: add filp_close_sync()
fs: make close_files() synchronous
fs: add switch_files_struct()
coredump: s/startup/done/g
coredump: add COREDUMP_CLOSE_FILES
tools: sync coredump.h header selftests/coredump: test COREDUMP_CLOSE_FILES

 fs/coredump.c                                      |  18 +-
 fs/file.c                                          | 152 +++++-
 fs/file_table.c                                    |  53 +-
 fs/internal.h                                      |   3 +-
 fs/open.c                                          |  39 +-
 include/linux/fdtable.h                            |   5 +
 include/linux/sched/signal.h                       |   5 +-
 include/uapi/linux/coredump.h                      |   8 +
 kernel/exit.c                                      |   7 +-
 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 +-
 14 files changed, 832 insertions(+), 71 deletions(-)

---
base-commit: 5870ce43c013ad564b3b83bae330b160e056df67
change-id: 20260824-work-coredump-unlock-self-63a898912870

author maintainer
#1 lore raw

RFC PATCH 1/7 fs: add filp_close_sync()

Currently close() already does a synchronous release of the last reference since the task is about to return to userspace and the deferral through task work buys nothing.

Turn that into a filp_close_sync() helper. We'll use that in one of the next patches.

No functional changes.

---
 fs/file_table.c | 53 ++++++++++++++++++++++++++++++++++++++++++++++-------
 fs/internal.h   |  3 ++-
 fs/open.c       | 39 +--------------------------------------
 3 files changed, 49 insertions(+), 46 deletions(-)
fs/file_table.c +46 -7
index c68b8c0a4097..3c705917646b 100644
@@ -13,6 +13,7 @@
 #include <linux/module.h>
 #include <linux/fs.h>
 #include <linux/filelock.h>
+#include <linux/dnotify.h>
 #include <linux/security.h>
 #include <linux/cred.h>
 #include <linux/eventpoll.h>
@@ -606,15 +607,53 @@ void __fput_sync(struct file *file)
 EXPORT_SYMBOL(__fput_sync);
 
 /*
- * Equivalent to __fput_sync(), but optimized for being called with the last
- * reference.
- *
- * See file_ref_put_close() for details.
+ * "id" is the POSIX thread ID. We use the
+ * files pointer for this..
  */
-void fput_close_sync(struct file *file)
+static int filp_flush(struct file *filp, fl_owner_t id)
 {
-	if (likely(file_ref_put_close(&file->f_ref)))
-		__fput(file);
+	int retval = 0;
+
+	if (CHECK_DATA_CORRUPTION(file_count(filp) == 0, filp,
+			"VFS: Close: file count is 0 (f_op=%ps)",
+			filp->f_op)) {
+		return 0;
+	}
+
+	if (filp->f_op->flush)
+		retval = filp->f_op->flush(filp, id);
+
+	if (likely(!(filp->f_mode & FMODE_PATH))) {
+		dnotify_flush(filp, id);
+		locks_remove_posix(filp, id);
+	}
+	return retval;
+}
+
+int filp_close(struct file *filp, fl_owner_t id)
+{
+	int retval;
+
+	retval = filp_flush(filp, id);
+	fput_close(filp);
+
+	return retval;
+}
+EXPORT_SYMBOL(filp_close);
+
+/*
+ * Like filp_close() but without deferring the release of the last
+ * reference, see file_ref_put_close() for details.
+ */
+int filp_close_sync(struct file *filp, fl_owner_t id)
+{
+	int retval;
+
+	retval = filp_flush(filp, id);
+	if (likely(file_ref_put_close(&filp->f_ref)))
+		__fput(filp);
+
+	return retval;
 }
 
 /*
fs/internal.h +2 -1
index 355d93f92208..7ba8cd26a698 100644
@@ -127,7 +127,7 @@ static inline void put_file_access(struct file *file)
 	}
 }
 
-void fput_close_sync(struct file *);
+int filp_close_sync(struct file *filp, fl_owner_t id);
 void fput_close(struct file *);
 
 /*
@@ -190,6 +190,7 @@ struct open_flags {
 	int intent;
 	int lookup_flags;
 };
+
 extern struct file *do_file_open(int dfd, struct filename *pathname,
 		const struct open_flags *op);
 extern struct file *do_file_open_root(const struct path *,
fs/open.c +1 -38
index 408925d7bd0b..d036736d5d43 100644
@@ -1453,41 +1453,6 @@ SYSCALL_DEFINE2(creat, const char __user *, pathname, umode_t, mode)
 }
 #endif
 
-/*
- * "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 retval = 0;
-
-	if (CHECK_DATA_CORRUPTION(file_count(filp) == 0, filp,
-			"VFS: Close: file count is 0 (f_op=%ps)",
-			filp->f_op)) {
-		return 0;
-	}
-
-	if (filp->f_op->flush)
-		retval = filp->f_op->flush(filp, id);
-
-	if (likely(!(filp->f_mode & FMODE_PATH))) {
-		dnotify_flush(filp, id);
-		locks_remove_posix(filp, id);
-	}
-	return retval;
-}
-
-int filp_close(struct file *filp, fl_owner_t id)
-{
-	int retval;
-
-	retval = filp_flush(filp, id);
-	fput_close(filp);
-
-	return retval;
-}
-EXPORT_SYMBOL(filp_close);
-
 /*
  * Careful here! We test whether the file pointer is NULL before
  * releasing the fd. This ensures that one clone task can't release
@@ -1502,13 +1467,11 @@ SYSCALL_DEFINE1(close, unsigned int, fd)
 	if (!file)
 		return -EBADF;
 
-	retval = filp_flush(file, current->files);
-
 	/*
 	 * We're returning to user space. Don't bother
 	 * with any delayed fput() cases.
 	 */
-	fput_close_sync(file);
+	retval = filp_close_sync(file, current->files);
 
 	if (likely(retval == 0))
 		return 0;
Signature · 1 line
2.53.0
author maintainer
#2 lore raw

RFC PATCH 2/7 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.

Note, today closing the files runs after exit_fs(), disassociate_ctty() and exit_task_namespaces(). So ->flush() and ->release() get a task that has already lost its fs, its namespaces and its controlling terminal even though the files were closed long before that.

So let close_files() close right away. No locks are held, the path already sleeps, close() does the same thing already. Kernel threads can just keep deferring. ->flush() and ->release() now run before exit_fs() and disassociate_ctty().

---
 fs/file.c | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)
fs/file.c +9 -1
index 628ca07dc4b1..e2d4b72c2e26 100644
@@ -480,6 +480,11 @@ static struct fdtable *close_files(struct files_struct * files)
 	 */
 	struct fdtable *fdt = rcu_dereference_raw(files->fdt);
 	unsigned int i, j = 0;
+	/*
+	 * A kernel thread that might be needed to make progress on some
+	 * umount must not run __fput() itself, see __fput_sync().
+	 */
+	bool sync = !(current->flags & PF_KTHREAD);
 
 	for (;;) {
 		unsigned long set;
@@ -491,7 +496,10 @@ static struct fdtable *close_files(struct files_struct * files)
 			if (set & 1) {
 				struct file *file = fdt->fd[i];
 				if (file) {
-					filp_close(file, files);
+					if (sync)
+						filp_close_sync(file, files);
+					else
+						filp_close(file, files);
 					cond_resched();
 				}
 			}
Signature · 1 line
2.53.0
#3 lore raw

Re: [PATCH RFC 2/7] fs: make close_files() synchronous

Quoted 16 lines · On Mon, 24 Aug 2026 17:28:16 +0200 Christian Brauner <[email protected]> wrote:
fs/file.c +5 -0
@@ -480,6 +480,11 @@ static struct fdtable *close_files(struct files_struct * files)
 	 */
 	struct fdtable *fdt = rcu_dereference_raw(files->fdt);
 	unsigned int i, j = 0;
+	/*
+	 * A kernel thread that might be needed to make progress on some
+	 * umount must not run __fput() itself, see __fput_sync().
+	 */
+	bool sync = !(current->flags & PF_KTHREAD);
 
 	for (;;) {
 		unsigned long set;
@@ -491,7 +496,10 @@ static struct fdtable *close_files(struct files_struct * files)
 			if (set & 1) {

fs/file.c static struct fdtable *close_files(struct files_struct * files) · line 505

Quoted 10 lines
fs/file.c +4 -1
 				struct file *file = fdt->fd[i];
 				if (file) {
-					filp_close(file, files);
+					if (sync)
+						filp_close_sync(file, files);
+					else
+						filp_close(file, files);
 					cond_resched();
 				}
 			}

This seems to be a significant change that affects the release timing during every task exit. If this modification is indeed feasible, it is certainly more straightforward than my previous approach of adding a PFUMPCORE flag check NOT to use task_work to release files.

Thanks
Xin Zhao

author maintainer
#4 lore raw

RFC PATCH 3/7 fs: add switch_files_struct()

In reply to Christian Brauner

Add switch_files_struct() so a task can switch to a new file descriptor table and close the old one. That's very restricted to the exit path and coredumps.

No functional changes.

---
 fs/file.c | 63 +++++++++++++++++++++++++++++++++++++++++++++------------------
 1 file changed, 45 insertions(+), 18 deletions(-)
fs/file.c +45 -18
index e2d4b72c2e26..391b6d4292c4 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,26 @@ 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;
+}
+
+/*
+ * 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);
@@ -523,16 +537,29 @@ void put_files_struct(struct files_struct *files)
 	}
 }
 
-void exit_files(struct task_struct *tsk)
+/* Hand @tsk the table @files, or none, and drop the one it had. */
+static void 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;
+	if (old) {
+		if (files)
+			atomic_inc(&files->count);
+		tsk->files = files;
 	}
+	task_unlock(tsk);
+	if (old)
+		put_files_struct(old);
+}
+
+void exit_files(struct task_struct *tsk)
+{
+	if (!tsk->files)
+		return;
+	switch_files_struct(tsk, NULL);
 }
 
 struct files_struct init_files = {
Signature · 1 line
2.53.0
author maintainer
#5 lore raw

RFC PATCH 4/7 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 ec9359e382ea..27d9cdc77cec 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 2c0b1c02920f..b535bc1ed68d 100644
@@ -441,7 +441,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
#6 lore raw

RFC PATCH 5/7 coredump: add COREDUMP_CLOSE_FILES

In reply to Christian Brauner

Add COREDUMP_CLOSE_FILES extension that allows a coredump server to request that the thread-group close all files before generating 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                 | 14 +++++++-
 fs/file.c                     | 81 +++++++++++++++++++++++++++++++++++++++++++
 include/linux/fdtable.h       |  5 +++
 include/linux/sched/signal.h  |  4 ++-
 include/uapi/linux/coredump.h |  8 +++++
 kernel/exit.c                 |  5 +++
 6 files changed, 115 insertions(+), 2 deletions(-)
fs/coredump.c +13 -1
index 27d9cdc77cec..a6e7da0bc16a 100644
@@ -837,7 +837,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,
@@ -905,6 +906,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) {
@@ -1225,6 +1232,11 @@ 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()) {
+		coredump_report_failure("Failed to close files, aborting core");
+		return;
+	}
+
 	/* get us an unshared descriptor table; almost always a no-op */
 	/* The cell spufs coredump code reads the file descriptor tables */
 	if (unshare_files())
fs/file.c +81 -0

93 lines not on this page · raw message

include/linux/fdtable.h +5 -0
index c45306a9f007..f0c1003da8ce 100644
@@ -99,11 +99,16 @@ static inline bool close_on_exec(unsigned int fd, const struct files_struct *fil
 
 struct task_struct;
 
+struct core_thread;
+
 void put_files_struct(struct files_struct *fs);
+bool coredump_close_files(void);
+bool coredump_task_close_files(struct core_thread *self);
 int unshare_files(void);
 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 *);
 int iterate_fd(struct files_struct *, unsigned,
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 +5 -0
index b535bc1ed68d..b651679c12e9 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>
@@ -432,6 +433,7 @@ static void coredump_task_exit(struct task_struct *tsk,
 	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
@@ -447,6 +449,9 @@ static void coredump_task_exit(struct task_struct *tsk,
 		set_current_state(TASK_IDLE|TASK_FREEZABLE);
 		if (!self.task) /* see coredump_finish() */
 			break;
+		/* see coredump_close_files() */
+		if (coredump_task_close_files(&self))
+			continue;
 		schedule();
 	}
 	__set_current_state(TASK_RUNNING);
Signature · 1 line
2.53.0
#7 lore raw

Re: [PATCH RFC 5/7] coredump: add COREDUMP_CLOSE_FILES

Quoted 9 lines · On Mon, 24 Aug 2026 17:28:19 +0200 Christian Brauner <[email protected]> wrote:

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.

Quoted 5 lines

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

---

I don't know if I was the one who initially raised this requirement or issue in the community. If so, could the tag
'Reported-by: Xin Zhao <[email protected]>' be added?

Thanks
Xin Zhao

author maintainer
#8 lore raw

RFC PATCH 6/7 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
#9 lore raw

RFC PATCH 7/7 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
#10 lore raw
In reply to Christian Brauner
Quoted 3 lines · On Mon, 24 Aug 2026 17:28:14 +0200 Christian Brauner <[email protected]> wrote:

A new COREDUMP_CLOSE_FILES extension that allows a coredump server to request that the thread-group close all files before generating the coredump.

I indeed couldn't think of a way to address how to release files earlier in the coredump pipe mode in our project, although I also knew that adding a step in the cump socket case was relatively easy. Anyway, being able to support early release in the coredump socket is definitely better than not supporting early release in any mode at all.

Thanks
Xin Zhao

#11 lore raw
In reply to Christian Brauner
Quoted 17 lines · Christian Brauner

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 first patch is somewhat unrelated but without it the code would have to become so ugly to the point of being unacceptable so it's a stylistic prerequisite imho.

In the first patch we make exit_files() synchronous and stop shunting all files onto task work only to run task work right after. For tasks exiting with a very 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.

Quoted 4 lines

So let close_files() close right away. No locks are held, the path already sleeps, close() does the same thing already. Kernel threads can just keep deferring. ->flush() and ->release() now run before exit_fs() and disassociate_ctty() which should be fine.

I think close on exec handling could use the same treatment.

Quoted 14 lines

The other half is adding support for coredumps to 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.

A new COREDUMP_CLOSE_FILES extension that allows a coredump server to request that the thread-group close all files before generating the coredump.

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.

Quoted 6 lines

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.

I find this rather unsatisfactory. What if a coredumper *wants* fd info and does not want to stall userspace on file locks? Sooner or later someone is going to show up complaining about it.

I proposed merely dropping all the locks early, which on its own should be easy to implement. I have not checked how fd reporting is implemented, it might be there is no way to convey what locks were held in a backwards-compatible manner in which case plain early unlock might be a no-go.

Perhaps a new extension could be added to remedy that aspect -- it would unlock early and add some extra info which fds had locks on them, ultimately preserving all the information.

In that case userspace would need to get patched to stop suffering the problem, but that's true with your patchset as well.

author maintainer
#12 lore raw
Quoted 50 lines · Mateusz Guzik
Quoted 17 lines · Christian Brauner

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 first patch is somewhat unrelated but without it the code would have to become so ugly to the point of being unacceptable so it's a stylistic prerequisite imho.

In the first patch we make exit_files() synchronous and stop shunting all files onto task work only to run task work right after. For tasks exiting with a very 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.

Quoted 4 lines

So let close_files() close right away. No locks are held, the path already sleeps, close() does the same thing already. Kernel threads can just keep deferring. ->flush() and ->release() now run before exit_fs() and disassociate_ctty() which should be fine.

I think close on exec handling could use the same treatment.

Quoted 14 lines

The other half is adding support for coredumps to 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.

A new COREDUMP_CLOSE_FILES extension that allows a coredump server to request that the thread-group close all files before generating the coredump.

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.

Quoted 6 lines

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.

I find this rather unsatisfactory. What if a coredumper *wants* fd info and does not want to stall userspace on file locks? Sooner or later someone is going to show up complaining about it.

Quoted 5 lines

I proposed merely dropping all the locks early, which on its own should be easy to implement. I have not checked how fd reporting is implemented, it might be there is no way to convey what locks were held in a backwards-compatible manner in which case plain early unlock might be a no-go.

I don't understand how it would even remotely be safe to drop locks before we've called into ->flush() and ->release(). The only locks that satisfy this requirement right away are posix file locks. Not even all of them, just a limited subset.

So then we introduce a concept of "drop some locks" which might grow over time. I really fail to see how this is attractive at all.

For a bunch of locks they will only be dropable in ->release(). So then we need to annotate locks that are droppable prior to exit_files() and locks that are droppable after it. Why would we place that analytical burden on anyone? Coredumps alone cannot justify it. They can hardly justify what I'm doing. The only saving grace is that I think having exit_files() run synchronously makes sense given how it hammers on task work. And then the coredump thing can fall out of it as a side-effect.

So I don't understand what early lock release buys at all other than complexity. Without clear proof that early-lock release is elegant and non-invasive I don't see why we would do it.

Exiting files early can be done cooperatively on the other hand and it'll satisfy most use-cases just fine.

#13 lore raw
Quoted 58 lines · Christian Brauner
Quoted 50 lines · Mateusz Guzik
Quoted 17 lines · Christian Brauner

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 first patch is somewhat unrelated but without it the code would have to become so ugly to the point of being unacceptable so it's a stylistic prerequisite imho.

In the first patch we make exit_files() synchronous and stop shunting all files onto task work only to run task work right after. For tasks exiting with a very 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.

Quoted 4 lines

So let close_files() close right away. No locks are held, the path already sleeps, close() does the same thing already. Kernel threads can just keep deferring. ->flush() and ->release() now run before exit_fs() and disassociate_ctty() which should be fine.

I think close on exec handling could use the same treatment.

Quoted 14 lines

The other half is adding support for coredumps to 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.

A new COREDUMP_CLOSE_FILES extension that allows a coredump server to request that the thread-group close all files before generating the coredump.

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.

Quoted 6 lines

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.

I find this rather unsatisfactory. What if a coredumper *wants* fd info and does not want to stall userspace on file locks? Sooner or later someone is going to show up complaining about it.

Quoted 5 lines

I proposed merely dropping all the locks early, which on its own should be easy to implement. I have not checked how fd reporting is implemented, it might be there is no way to convey what locks were held in a backwards-compatible manner in which case plain early unlock might be a no-go.

Quoted 5 lines

I don't understand how it would even remotely be safe to drop locks before we've called into ->flush() and ->release(). The only locks that satisfy this requirement right away are posix file locks. Not even all of them, just a limited subset.

That's my bad, I was somehow convinced locks get dropped before any other work and did not even bother to check. Apologies. :>

Fortunately for me this is not my problem and I'm free to bugger off this subject, which is what I'm thereby doing.

Quoted 17 lines

So then we introduce a concept of "drop some locks" which might grow over time. I really fail to see how this is attractive at all.

For a bunch of locks they will only be dropable in ->release(). So then we need to annotate locks that are droppable prior to exit_files() and locks that are droppable after it. Why would we place that analytical burden on anyone? Coredumps alone cannot justify it. They can hardly justify what I'm doing. The only saving grace is that I think having exit_files() run synchronously makes sense given how it hammers on task work. And then the coredump thing can fall out of it as a side-effect.

So I don't understand what early lock release buys at all other than complexity. Without clear proof that early-lock release is elegant and non-invasive I don't see why we would do it.

Exiting files early can be done cooperatively on the other hand and it'll satisfy most use-cases just fine.

author maintainer
#14 lore raw
In reply to Mateusz Guzik
Quoted 18 lines · Mateusz Guzik
Quoted 17 lines · Christian Brauner

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 first patch is somewhat unrelated but without it the code would have to become so ugly to the point of being unacceptable so it's a stylistic prerequisite imho.

In the first patch we make exit_files() synchronous and stop shunting all files onto task work only to run task work right after. For tasks exiting with a very 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.

Quoted 6 lines
Quoted 4 lines

So let close_files() close right away. No locks are held, the path already sleeps, close() does the same thing already. Kernel threads can just keep deferring. ->flush() and ->release() now run before exit_fs() and disassociate_ctty() which should be fine.

I think close on exec handling could use the same treatment.

do_close_on_exec() runs under cred_guard_mutex and would introduce new lock ordering. So dropping should move out from under that mutex which introduces additional complexity.

author maintainer
#15 lore raw
Quoted 24 lines · Christian Brauner
Quoted 23 lines · Mateusz Guzik
Quoted 21 lines · Christian Brauner

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 first patch is somewhat unrelated but without it the code would have to become so ugly to the point of being unacceptable so it's a stylistic prerequisite imho.

In the first patch we make exit_files() synchronous and stop shunting all files onto task work only to run task work right after. For tasks exiting with a very 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.

So let close_files() close right away. No locks are held, the path already sleeps, close() does the same thing already. Kernel threads can just keep deferring. ->flush() and ->release() now run before exit_fs() and disassociate_ctty() which should be fine.

Quoted 5 lines
Quoted 1 line

I think close on exec handling could use the same treatment.

do_close_on_exec() runs under cred_guard_mutex and would introduce new lock ordering. So dropping should move out from under that mutex which introduces additional complexity.

Which is a bug in my patch as well. Thanks for pointing me to this.

#16 lore raw
In reply to Christian Brauner
Quoted 25 lines · Christian Brauner
Quoted 23 lines · Mateusz Guzik
Quoted 21 lines · Christian Brauner

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 first patch is somewhat unrelated but without it the code would have to become so ugly to the point of being unacceptable so it's a stylistic prerequisite imho.

In the first patch we make exit_files() synchronous and stop shunting all files onto task work only to run task work right after. For tasks exiting with a very 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.

So let close_files() close right away. No locks are held, the path already sleeps, close() does the same thing already. Kernel threads can just keep deferring. ->flush() and ->release() now run before exit_fs() and disassociate_ctty() which should be fine.

Quoted 5 lines
Quoted 1 line

I think close on exec handling could use the same treatment.

do_close_on_exec() runs under cred_guard_mutex and would introduce new lock ordering. So dropping should move out from under that mutex which introduces additional complexity.

This bit should be easy to address from conceptual standpoint, I don't know about resulting churn. Even if fd table processing can't move, the linkage in struct file can be used for a local non-atomic list and which would be drained after the lock is dropped. This would bring almost all of the benefit.