Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux
1
fork

Configure Feed

Select the types of activity you want to include in your feed.

fs/file: optimize close_range() complexity from O(N) to O(Sparse)

In close_range(), the kernel traditionally performs a linear scan over the
[fd, max_fd] range, resulting in O(N) complexity where N is the range size.
For processes with sparse FD tables, this is inefficient as it checks many
unallocated slots.

This patch optimizes __range_close() by using find_next_bit() on the
open_fds bitmap to skip holes. This shifts the algorithmic complexity from
O(Range Size) to O(Active FDs), providing a significant performance boost
for large-range close operations on sparse file descriptor tables.

Signed-off-by: Qiliang Yuan <realwujing@gmail.com>
Signed-off-by: Qiliang Yuan <yuanql9@chinatelecom.cn>
Link: https://patch.msgid.link/20260123081221.659125-1-realwujing@gmail.com
Signed-off-by: Christian Brauner <brauner@kernel.org>

authored by

Qiliang Yuan and committed by
Christian Brauner
fc94368b 6cbfdf89

+8 -2
+8 -2
fs/file.c
··· 777 777 unsigned int max_fd) 778 778 { 779 779 struct file *file; 780 + struct fdtable *fdt; 780 781 unsigned n; 781 782 782 783 spin_lock(&files->file_lock); 783 - n = last_fd(files_fdtable(files)); 784 + fdt = files_fdtable(files); 785 + n = last_fd(fdt); 784 786 max_fd = min(max_fd, n); 785 787 786 - for (; fd <= max_fd; fd++) { 788 + for (fd = find_next_bit(fdt->open_fds, max_fd + 1, fd); 789 + fd <= max_fd; 790 + fd = find_next_bit(fdt->open_fds, max_fd + 1, fd + 1)) { 787 791 file = file_close_fd_locked(files, fd); 788 792 if (file) { 789 793 spin_unlock(&files->file_lock); 790 794 filp_close(file, files); 791 795 cond_resched(); 792 796 spin_lock(&files->file_lock); 797 + fdt = files_fdtable(files); 793 798 } else if (need_resched()) { 794 799 spin_unlock(&files->file_lock); 795 800 cond_resched(); 796 801 spin_lock(&files->file_lock); 802 + fdt = files_fdtable(files); 797 803 } 798 804 } 799 805 spin_unlock(&files->file_lock);