fuse: use readdir result to shortcut negative lookups
Subsystems (2)
cover fuse: use readdir result to shortcut negative lookups
FUSE servers can respond to LOOKUP requests with {OK, nodeID=0} to indicate an entry is not present, and the negative entry can be cached for a specified interval. This helps reduce the number of LOOKUP calls, but it is still problematic: each negative dentry still costs a roundtrip. Since the universe of non-existing files is unlimited, in practice we must still do many roundtrips.
We can do better: once the kernel has read directory contents (through READDIRPLUS), the server has specified which positive dentries exist. In most file systems, this means that all other lookups in the directory should yield negative results, and we can spare ourselves the roundtrips.
In this patch series, we collect filename hashes from directory reads, and use them to populate a Bloom filter once the read is finished. Then, on lookup, if we don't find the name in the Bloom filter, we skip the roundtrip and return a negative result immediately.
The Bloom filter is space efficient, while still allowing efficient updates when entries are added through MKDIR/CREATE/LINK operations.
The TTL of the Bloom filter is derived from the entry TTL of the "." entry, if specified, or the minimum TTL of the positive entries. We use READDIRPLUS rather than READDIR, because the latter has no channel to signal a TTL.
Once the filter is in place, the server should rarely get lookups in the directory. If the server does get lookups, this can mean two things:
1) the filter has expired
2) it was a false positive from the Bloom filter
To address case 1), the server should be able to trigger repopulating the filter, but because of 2), issuing a normal readdir unconditionally is expensive, and the server may not have access to the mountpoint anyway.
To solve this, we add a new notify method, which can return EALREADY (the filter is still valid; no further side effect) or OK (there is no filter; trigger a new READDIRPLUS to populate the filter again). The notify does not wait for the server, so it can be sent from the LOOKUP handler itself.
The kernel reads the directory from a work item, with synchronous OPENDIR, READDIRPLUS and RELEASEDIR requests made on behalf of no process. The work items run on a workqueue per connection, so a server that does not reply only holds up its own reads, and at most 8 run per connection; further notifications fail with EBUSY.
The notification also lets a server preemptively load a directory:
READDIRPLUS is attractive because a single roundtrip can load many entries, reducing overhead, but many programs (eg. GCC) only cause single file lookups, and never issue readdir.
Unfortunately, virtiofs currently does not support notifications in general, so the latter benefits are not available for virtiofs.
The series is organized as follows:
* patch 1 fixes lookup references leaked on READDIRPLUS errors. It is independent of the rest.
* patch 2 adds the Bloom filter machinery
* patch 3 populates the filter from READDIRPLUS results (FOPEN_COMPLETE_DIR)
* patches 4-6 prepare for reading a directory from a work item, without functional change: readdir without a struct file, requests on behalf of no process, and opening and releasing a file for the kernel itself
* patch 7 adds the notify method.
To support this feature in userspace, the server only needs to reply with FOPEN_COMPLETE_DIR flag for the OPENDIR opcode. I did this in Go-FUSE, and added tests and benchmarks for the feature. Tests ran against a kernel with debug/paranoia settings. Benchmark against a kernel with production settings.[1]
An i5-8350U pinned at 2 GHz yields the following performance numbers, in median ns/op over 11 runs:
ReadDirEntCompleteDir (per entry) 2,281
ReaddirplusHint (per entry) 1,801
NegStatUncached (LOOKUP round trip) 22,192
NegStatCached (dcache hit) 797
NegStatUncachedDir (Bloom filter) 1,587
This was a synthetic, in-memory file system serving a directory with 500 entries, using the Go-FUSE high-level API running against /dev/fuse, measured with single threaded access to the mountpoint, and GOMAXPROCS=2. ReaddirplusHint drops the filter with FUSE_NOTIFY_INVAL_INODE and has the kernel read the directory again with the new notification; it is cheaper per entry than getdents(), as no entries are copied to userspace.
The bloom filter is sized to 10 bits per entry, but then rounded to a power of 2. For 500 entries, this yields 8192 (16.4 bits per entry), with an expected false positive rate of 0.0006/op; the benchmark sees 0.0004/op.
So, the Bloom filter yields a 14x speed up on uncached negative lookups, at the cost of a full directory read. This pays off if
size-of-dir < (cost_LOOKUP - cost_BLOOM)/cost_DIRENT * unique-negative-lookups
= 9 * unique-negative-lookups
As a practical one-point sample: one of my open source C++ projects (lilypond) shows that a single G++ invocation gets ENOENT for 145 unique names under /usr/include/libpng16, a directory with 3 entries, so scenarios where this is a win are easy to find.
This code was written and reviewed with Claude Opus 5.5. The plan is included in [1].
It may be interesting to lift the Bloom filter into the VFS, for two reasons:
- other filesystems could benefit from this performance optimization, if the negative lookup is expensive. In particular: NFS, CephFS and overlayfs.
- the Bloom filter uses little memory, and makes negative dentries cheap to recreate. This could justify a more aggressive reclaim policy for them.
However, unlike the FUSE case, there is no way for a server to request a readdir, so it would need kernel-side heuristics to guess when this pays off.
Open questions:
- Where should the filter TTL come from? The entry timeout of "." is convenient because of backward compatibility, but it feels like a hack. Alternatively, we could extend fuse_open_out (or repurpose the space for backing_id in case of directories). This has the added advantage that we could populate the negative filter from READDIR as well. Then again, READDIRPLUS is better overall because it also loads positive entries with little overhead.
- Should filters be reclaimed under memory pressure, and if so, how? The filter costs ~2 bytes per file name, which seems little, but can grow to 512kb for a large directory.
- Should filter use be tracked? A referenced bit (set on the first negative answer) would let a shrinker drop unused filters first, and would tell whether re-listing a directory paid off. Hit counters per filter would contend between parallel lookups, so observability may be better served by tracepoints, or per-cpu counters per connection in fusectl.
- For the background read, can we use a kernel thread and leave it and its buffer unaccounted for? An earlier version used a background request, scheduling follow-on requests from the end callbacks, but it looked more complicated.
- what level of self-tests is appropriate for this change? The simplest test I can think of is a file system that runs the notify, waits for the readdir, and then checks that stat() calls don't trigger LOOKUP.
[1] https://github.com/hanwen/go-fuse/tree/complete-dir
Han-Wen Nienhuys (7):
fuse: forget READDIRPLUS entries that were not linked
fuse: add a negative lookup cache for directories
fuse: fill the negative lookup cache from complete READDIRPLUS passes
fuse: split readdir requests from struct file
fuse: allow requests on behalf of no process
fuse: open and release files for the kernel itself
fuse: let the server ask for a directory to be read in the background
fs/fuse/Makefile | 2 +- fs/fuse/args.h | 2 + fs/fuse/dir.c | 35 ++- fs/fuse/dir_names.c | 274 +++++++++++++++++ fs/fuse/file.c | 48 ++- fs/fuse/fuse_i.h | 66 ++++ fs/fuse/inode.c | 18 +- fs/fuse/notify.c | 23 ++ fs/fuse/readdir.c | 613 ++++++++++++++++++++++++++++++++++---- fs/fuse/req.c | 7 + fs/fuse/virtio_fs.c | 1 + include/uapi/linux/fuse.h | 45 ++- 12 files changed, 1054 insertions(+), 80 deletions(-) create mode 100644 fs/fuse/dir_names.c
Signature · 1 line
2.56.0
PATCH 1/7 fuse: forget READDIRPLUS entries that were not linked
The server takes a lookup reference for every entry of a READDIRPLUS reply that has a nodeid, other than "." and "..", and the kernel drops it with FORGET if it does not link the entry. Two error paths drop the rest of the reply without doing so, leaking the references on the server:
- parse_dirplusfile() returns -EIO at an entry with a bad name length or a '/' in its name, skipping the entries from there.
- If vm_map_ram() fails, the reply is not parsed at all. Before the reply buffer was backed by pages, its allocation failed before the request was sent.
Send FORGET for the entries from where parsing stopped. The reply is read from the pages without mapping them, to also cover the second case. An entry with a bad name length ends the walk, as the size of the rest cannot be known. fuse_force_forget() now takes an inode, as the walk has no file.
--- fs/fuse/readdir.c | 76 ++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 68 insertions(+), 8 deletions(-)
fs/fuse/readdir.c +68 -8
@@ -265,9 +265,8 @@ static int fuse_direntplus_link(struct file *file,return 0 ; } -static void fuse_force_forget (struct file *file,u64 nodeid) +static void fuse_force_forget (struct inode *inode,u64 nodeid) { -struct inode *inode =file_inode (file);struct fuse_mount *fm =get_fuse_mount (inode);struct fuse_forget_in inarg;FUSE_ARGS (args);
@@ -286,10 +285,60 @@ static void fuse_force_forget(struct file *file, u64 nodeid)/* ignore errors */ } +static void fuse_readdir_copy (struct page **pages,size_t off,void *dst, +size_t len) +{ +while (len) { +size_t n =min (len,PAGE_SIZE -offset_in_page (off)); + +memcpy_from_page (dst, pages[off >>PAGE_SHIFT ], +offset_in_page (off), n); + dst += n; + off += n; + len -= n; + } +} + +/* +* Forget the entries from @off to @end. The pages are not mapped, as this +* also follows a failure of vm_map_ram(). +*/ +static void fuse_direntplus_forget (struct inode *dir,struct page **pages, +size_t off,size_t end) +{ +while (end - off >=FUSE_NAME_OFFSET_DIRENTPLUS ) { +struct fuse_direntplus direntplus; +struct fuse_dirent *dirent = &direntplus.dirent; +char name[2 ]; +size_t reclen; + +fuse_readdir_copy (pages, off, &direntplus, +FUSE_NAME_OFFSET_DIRENTPLUS ); +if (!dirent->namelen || dirent->namelen >FUSE_NAME_MAX ) +break ; + reclen =FUSE_DIRENTPLUS_SIZE (&direntplus); +if (reclen > end - off) +break ; + +fuse_readdir_copy (pages, off +FUSE_NAME_OFFSET_DIRENTPLUS , name, +min_t (size_t, dirent->namelen,sizeof (name))); +if (direntplus.entry_out.nodeid && + !name_is_dot_dotdot (name, dirent->namelen)) +fuse_force_forget (dir, direntplus.entry_out.nodeid); + + off += reclen; + } +} + +/* +* On error, returns in @parsed the offset of the first entry that was not +* linked. +*/ static int parse_dirplusfile (char *buf,size_t nbytes,struct file *file,struct dir_context *ctx,u64 attr_version, -u64 evict_ctr) +u64 evict_ctr,size_t *parsed) { +char *start = buf;struct fuse_direntplus *direntplus;struct fuse_dirent *dirent;size_t reclen;
@@ -302,11 +351,11 @@ static int parse_dirplusfile(char *buf, size_t nbytes, struct file *file, reclen =FUSE_DIRENTPLUS_SIZE (direntplus);if (!dirent->namelen || dirent->namelen >FUSE_NAME_MAX ) -return -EIO ; + goto err;if (reclen > nbytes)break ;if (memchr (dirent->name,'/' , dirent->namelen) !=NULL ) -return -EIO ; + goto err;if (!over) {/* We fill entries into dstbuf only as much as
@@ -325,10 +374,15 @@ static int parse_dirplusfile(char *buf, size_t nbytes, struct file *file, ret =fuse_direntplus_link (file, direntplus, attr_version, evict_ctr);if (ret) -fuse_force_forget (file, direntplus->entry_out.nodeid); +fuse_force_forget (file_inode (file), + direntplus->entry_out.nodeid); }return 0 ; + +err: + *parsed = buf - start; +return -EIO ; }static struct page **fuse_readdir_alloc_buf (struct fuse_args_pages *ap,size_t *bufsize)
@@ -380,6 +434,7 @@ static int fuse_readdir_uncached(struct file *file, struct dir_context *ctx)void *buf;size_t bufsize =clamp ((unsigned int ) ctx->count,PAGE_SIZE , fc->max_pages <<PAGE_SHIFT );u64 attr_version =0 , evict_ctr =0 ; +size_t nbytes, parsed =0 ;bool locked;struct page **pages =fuse_readdir_alloc_buf (ap, &bufsize);
@@ -408,17 +463,22 @@ static int fuse_readdir_uncached(struct file *file, struct dir_context *ctx) goto out; } + nbytes = res; buf =vm_map_ram (pages, ap->num_folios,-1 );if (!buf) { res = -ENOMEM ; }else {if (plus) - res =parse_dirplusfile (buf, res, file, ctx, attr_version, evict_ctr); + res =parse_dirplusfile (buf, nbytes, file, ctx, attr_version, + evict_ctr, &parsed);else - res =parse_dirfile (buf, res, file, ctx); + res =parse_dirfile (buf, nbytes, file, ctx);vm_unmap_ram (buf, ap->num_folios); } +/* The server took lookup references also for entries not linked */ +if (plus && res <0 ) +fuse_direntplus_forget (inode, pages, parsed, nbytes); out:kfree (ap->folios);release_pages (pages, ap->num_folios);
Signature · 1 line
2.56.0
PATCH 2/7 fuse: add a negative lookup cache for directories
In reply to Han-Wen NienhuysWorkloads that probe for names that do not exist (search paths, build systems) send a FUSE_LOOKUP per probe, and negative dentries only help from the second probe of each name. If the kernel knows all names in a directory, it can answer these lookups itself.
Add a per-directory Bloom filter of names, consulted in ->lookup(): a name that is not in it gets a negative dentry without a request, valid until the filter expires. A false positive only costs the FUSE_LOOKUP that would have been sent anyway. The dcache cannot hold this record, as a reclaimed dentry looks like an absent name, and the readdir cache is optional and evictable. The filter takes about 10 bits per name, with probe positions derived from a 64-bit siphash of the name. The filter is not consulted for LOOKUP_REVAL, with which the VFS retries a walk after ESTALE to have the server asked, as for negative dentries. Nothing installs a filter yet.
The filter is kept correct as follows:
- Create, mknod, mkdir, symlink, link and rename add the new name, also when the request fails, as it may have been applied before an interruption. Removals are not applied: a stale name costs a lookup. The filter is dropped once additions reach 1.5 times the count it was sized for, at about 5% false positives; names it already reports do not count.
- FUSE_NOTIFY_INVAL_ENTRY adds the name, whether or not it has a dentry, so that announcing a remote addition keeps the filter. FUSE_NOTIFY_INVAL_INODE on the directory drops it, and an epoch bump invalidates it.
- Every local modification bumps a generation counter. A listing is only installed if the counter is unchanged since the listing was started, so it need not be collected under a lock.
Negative dentries made from the filter get its expiry. A server that adds a name remotely must send FUSE_NOTIFY_INVAL_ENTRY for it, the same contract as for negative LOOKUP replies. A filter that expired or is from an old epoch is freed by the next lookup that finds it.
--- fs/fuse/Makefile | 2 +- fs/fuse/dir.c | 34 +++++- fs/fuse/dir_names.c | 260 ++++++++++++++++++++++++++++++++++++++++++++ fs/fuse/fuse_i.h | 37 +++++++ fs/fuse/inode.c | 5 + 5 files changed, 332 insertions(+), 6 deletions(-) create mode 100644 fs/fuse/dir_names.c
fs/fuse/Makefile +1 -1
@@ -12,7 +12,7 @@ obj-$(CONFIG_VIRTIO_FS) += virtiofs.o fuse-y := trace.o # put trace.o first so we see ftrace errors sooner fuse-y += dev.o dir.o file.o inode.o control.o xattr.o acl.o readdir.o ioctl.o req_timeout.o req.o -fuse-y += poll.o notify.o +fuse-y += poll.o notify.o dir_names.o fuse-y += iomode.o fuse-$(CONFIG_FUSE_VDAX) += dax.o fuse-$(CONFIG_FUSE_PASSTHROUGH) += passthrough.o backing.o ext_map.o
fs/fuse/dir.c +29 -5
@@ -326,6 +326,7 @@ static void fuse_dir_changed(struct inode *dir) {fuse_invalidate_attr_mask (dir,FUSE_STATX_MODDIR );inode_maybe_inc_iversion (dir, false); +fuse_dir_names_changed (dir); }/*
@@ -622,6 +623,7 @@ static struct dentry *fuse_lookup(struct inode *dir, struct dentry *entry,int err, epoch;bool outarg_valid = true;bool locked; +u64 neg_time =0 ;if (fuse_is_bad (dir))return ERR_PTR (-EIO );
@@ -629,10 +631,17 @@ static struct dentry *fuse_lookup(struct inode *dir, struct dentry *entry, fc =get_fuse_conn_super (dir->i_sb); epoch =atomic_read (&fc->epoch); - locked =fuse_lock_inode (dir); - err =fuse_lookup_name (dir->i_sb,get_node_id (dir), &entry->d_name, - &outarg, &inode); -fuse_unlock_inode (dir, locked); +/* After ESTALE, the VFS retries with LOOKUP_REVAL to ask the server */ +if (!(flags &LOOKUP_REVAL ) && entry->d_name.len <= fc->name_max && +fuse_dir_names_absent (dir, &entry->d_name, &neg_time)) { + inode =NULL ; + err = -ENOENT ; + }else { + locked =fuse_lock_inode (dir); + err =fuse_lookup_name (dir->i_sb,get_node_id (dir), + &entry->d_name, &outarg, &inode); +fuse_unlock_inode (dir, locked); + }if (err == -ENOENT ) { outarg_valid = false; err =0 ;
@@ -651,7 +660,9 @@ static struct dentry *fuse_lookup(struct inode *dir, struct dentry *entry, entry = newent ? newent : entry;fuse_dentry_set_epoch (entry, epoch); -if (outarg_valid) +if (neg_time) +fuse_dentry_settime (entry, neg_time); +else if (outarg_valid)fuse_change_entry_timeout (entry, &outarg);else fuse_invalidate_entry_cache (entry);
@@ -886,6 +897,9 @@ static int fuse_create_open(struct mnt_idmap *idmap, struct inode *dir, err =fuse_simple_idmap_request (idmap, fm, &args);free_ext_value (&args); +/* Also on error: an interrupted request may still have created it */ +if (opcode ==FUSE_CREATE ) +fuse_dir_names_add (dir, &entry->d_name);if (err <0 ) goto out_free_ff;
@@ -1014,6 +1028,8 @@ static struct dentry *create_new_entry(struct mnt_idmap *idmap, struct fuse_moun err =fuse_simple_idmap_request (idmap, fm, args);free_ext_value (args); +/* Also on error, see fuse_create_open() */ +fuse_dir_names_add (dir, &entry->d_name);if (err) goto out_put_forget_req;
@@ -1278,6 +1294,8 @@ static int fuse_rename_common(struct mnt_idmap *idmap, struct inode *olddir, str args.in_args[2 ].size = newent->d_name.len +1 ; args.in_args[2 ].value = newent->d_name.name; err =fuse_simple_idmap_request (idmap, fm, &args); +/* Also on error, see fuse_create_open() */ +fuse_dir_names_add (newdir, &newent->d_name);if (!err) {/* ctime changes */ fuse_update_ctime (d_inode (oldent));
@@ -1613,6 +1631,10 @@ int fuse_reverse_inval_entry(struct fuse_conn *fc, u64 parent_nodeid,if (!S_ISDIR (parent->i_mode)) goto unlock; +/* Not for deletions; a new name has no dentry */ +if (!child_nodeid) +fuse_dir_names_add (parent, name); + err = -ENOENT ; dir =d_find_alias (parent);if (!dir)
@@ -2485,6 +2507,8 @@ void fuse_init_dir(struct inode *inode) fi->rdc.size =0 ; fi->rdc.pos =0 ; fi->rdc.version =0 ; +RCU_INIT_POINTER (fi->rdc.names,NULL ); + fi->rdc.names_gen =0 ; }static int fuse_symlink_read_folio (struct file *null,struct folio *folio)
fs/fuse/dir_names.c new file +260 -0
260 lines not on this page · raw message
fs/fuse/fuse_i.h +37 -0
@@ -33,6 +33,7 @@#include <linux/refcount.h> #include <linux/user_namespace.h> #include <linux/rhashtable-types.h> +#include <linux/siphash.h> /** Default max number of pages that can be used in a single read request */ #define FUSE_DEFAULT_MAX_PAGES_PER_REQ 32
@@ -229,6 +230,18 @@ struct fuse_inode {*/ u64 iversion; +/** +* @names: Bloom filter of the names, for negative +* lookups, RCU protected +*/ +struct fuse_dir_names __rcu *names; + +/** +* @names_gen: incremented on local modifications, to +* detect incomplete listings +*/ +u64 names_gen; +/** @lock: protects above fields */ spinlock_t lock; } rdc;
@@ -653,6 +666,9 @@ struct fuse_conn {/** @readdirplus_auto: Does the filesystem want adaptive readdirplus? */ unsigned readdirplus_auto:1; +/** @names_key: Key for hashing names in directory name filters */ +siphash_key_t names_key; +/** * @async_dio: Does the filesystem support asynchronous direct-IO * submission?
@@ -1259,6 +1275,27 @@ int fuse_set_acl(struct mnt_idmap *, struct dentry *dentry,/* readdir.c */ int fuse_readdir (struct file *file,struct dir_context *ctx); +/* dir_names.c */ + +/* Largest listing that gets a name filter */ +#define FUSE_DIR_NAMES_MAX (1U << 18) + +u64 fuse_dir_name_hash (struct fuse_conn *fc,const char *name, +unsigned int len); +struct fuse_dir_names *fuse_dir_names_alloc (unsigned int count,u64 expires, +int epoch); +void fuse_dir_names_insert (struct fuse_dir_names *names,u64 hash); +void fuse_dir_names_discard (struct fuse_dir_names *names); +u64 fuse_dir_names_gen (struct inode *dir); +bool fuse_dir_names_publish (struct inode *dir,struct fuse_dir_names *names, +u64 gen); +void fuse_dir_names_changed (struct inode *dir); +void fuse_dir_names_add (struct inode *dir,const struct qstr *name); +void fuse_dir_names_invalidate (struct inode *dir); +void fuse_dir_names_free (struct inode *dir); +bool fuse_dir_names_absent (struct inode *dir,const struct qstr *name, +u64 *expires); +void fuse_free_conn (struct fuse_conn *fc);/* dax.c */
fs/fuse/inode.c +5 -0
@@ -121,6 +121,8 @@ static void fuse_free_inode(struct inode *inode)mutex_destroy (&fi->mutex);kfree (fi->forget); +if (S_ISDIR (inode->i_mode)) +fuse_dir_names_free (inode);#ifdef CONFIG_FUSE_VDAX kfree (fi->vdax);#endif
@@ -570,6 +572,8 @@ int fuse_reverse_inval_inode(struct fuse_conn *fc, u64 nodeid,fuse_invalidate_attr (inode);forget_all_cached_acls (inode); +if (S_ISDIR (inode->i_mode)) +fuse_dir_names_invalidate (inode);if (offset >=0 ) { pg_start = offset >>PAGE_SHIFT ;if (len <=0 )
@@ -983,6 +987,7 @@ void fuse_conn_init(struct fuse_conn *fc, struct fuse_mount *fm,refcount_set (&fc->count,1 );atomic_set (&fc->epoch,1 );INIT_WORK (&fc->epoch_work, fuse_epoch_work); +get_random_bytes (&fc->names_key,sizeof (fc->names_key));INIT_LIST_HEAD (&fc->entry); fc->congestion_threshold =FUSE_DEFAULT_CONGESTION_THRESHOLD ;atomic64_set (&fc->khctr,0 );
Signature · 1 line
2.56.0
PATCH 3/7 fuse: fill the negative lookup cache from complete READDIRPLUS passes
In reply to Han-Wen NienhuysAdd FOPEN_COMPLETE_DIR, with which the server marks a directory at OPENDIR, promising to announce remote additions with FUSE_NOTIFY_INVAL_ENTRY. When such a directory is read with READDIRPLUS from offset 0 to EOF, build its name filter from the returned names. This needs no extra transfer. Readdir holds the directory lock only per request, so local modifications in between are caught by the names generation, sampled at offset 0. The flag is per OPENDIR, as READDIRPLUS replies have no header to carry it.
The filter expires with the entry timeout of ".", which is otherwise unused, so the server can choose it, also for an empty directory. If "." has no nodeid, the smallest timeout of the other entries with a nodeid is used, so that no negative answer outlives a positive one the server handed out. Without any timeout, no filter is built.
Names are collected per struct fuse_file, as hashes in a temporary array, since their number is only known at EOF. The collection is abandoned on a seek, an error, or more than 2^18 names. While collecting, READDIRPLUS is forced, as READDIR carries no timeouts. A pass served from the readdir cache (FOPEN_CACHE_DIR) collects nothing, so an expired filter is not rebuilt until the cache is.
--- fs/fuse/dir.c | 1 + fs/fuse/fuse_i.h | 3 + fs/fuse/inode.c | 2 +- fs/fuse/readdir.c | 146 ++++++++++++++++++++++++++++++++++++-- include/uapi/linux/fuse.h | 16 ++++- 5 files changed, 162 insertions(+), 6 deletions(-)
fs/fuse/dir.c +1 -0
@@ -1951,6 +1951,7 @@ static int fuse_dir_open(struct inode *inode, struct file *file)static int fuse_dir_release (struct inode *inode,struct file *file) { +fuse_readdir_names_release (file->private_data);fuse_release_common (file, true);return 0 ;
fs/fuse/fuse_i.h +3 -0
@@ -343,6 +343,8 @@ struct fuse_file {/** @version: Version of cache we are reading */ u64 version; +/** @names: listing being collected for FOPEN_COMPLETE_DIR */ +struct fuse_dir_names_builder *names; } readdir;/** @polled_node: RB node to be linked on fuse_conn->polled_files */
@@ -1274,6 +1276,7 @@ int fuse_set_acl(struct mnt_idmap *, struct dentry *dentry,/* readdir.c */ int fuse_readdir (struct file *file,struct dir_context *ctx); +void fuse_readdir_names_release (struct fuse_file *ff);/* dir_names.c */
fs/fuse/inode.c +1 -1
@@ -1508,7 +1508,7 @@ static struct fuse_init_args *fuse_new_init(struct fuse_mount *fm)FUSE_SECURITY_CTX |FUSE_CREATE_SUPP_GROUP |FUSE_HAS_EXPIRE_ONLY |FUSE_DIRECT_IO_ALLOW_MMAP |FUSE_NO_EXPORT_SUPPORT |FUSE_HAS_RESEND |FUSE_ALLOW_IDMAP | -FUSE_REQUEST_TIMEOUT ; +FUSE_REQUEST_TIMEOUT |FUSE_HAS_COMPLETE_DIR ;#ifdef CONFIG_FUSE_VDAX if (fm->fc->vdax) flags |=FUSE_MAP_ALIGNMENT ;
fs/fuse/readdir.c +142 -4
189 lines not on this page · raw message
include/uapi/linux/fuse.h +15 -1
@@ -257,6 +257,9 @@* - add backing_id_64 to fuse_open_out * - add FUSE_NOTIFY_BACKING_MAP, fuse_notify_backing_map_out, fuse_extent * - add FUSE_BACKING_MAP_CREATE, FUSE_BACKING_MAP_CYCLIC +* +* 7.48 +* - add FOPEN_COMPLETE_DIR and FUSE_HAS_COMPLETE_DIR */ #ifndef _LINUX_FUSE_H
@@ -292,7 +295,7 @@#define FUSE_KERNEL_VERSION 7/** Minor version number of this interface */ -#define FUSE_KERNEL_MINOR_VERSION 47 +#define FUSE_KERNEL_MINOR_VERSION 48/** The node ID of the root inode */ #define FUSE_ROOT_ID 1
@@ -406,6 +409,14 @@ struct fuse_file_lock {* (FUSE_URING_ZERO_COPY) and the request carries page * payload. Otherwise reads/writes fall back to * copying. +* FOPEN_COMPLETE_DIR: a complete READDIRPLUS listing of this directory is +* authoritative: names not in it are looked up as +* negative without sending FUSE_LOOKUP. This holds +* until the entry timeout of "." expires, or if "." has +* nodeid 0, the smallest entry timeout of the entries +* with a nonzero nodeid. "." does not count as a +* lookup. LOOKUP must only resolve names in the +* listing, byte for byte (eg. no case folding). */ #define FOPEN_DIRECT_IO (1 << 0)#define FOPEN_KEEP_CACHE (1 << 1)
@@ -416,6 +427,7 @@ struct fuse_file_lock {#define FOPEN_PARALLEL_DIRECT_WRITES (1 << 6)#define FOPEN_PASSTHROUGH (1 << 7)#define FOPEN_IO_URING_ZERO_COPY (1 << 8) +#define FOPEN_COMPLETE_DIR (1 << 9)/* * INIT request/reply flags
@@ -480,6 +492,7 @@ struct fuse_file_lock {* privilege that mounting virtiofs or fuseblk requires). * Insufficiently privileged servers ignore it. * FUSE_PASSTHROUGH_V2: use 64 bit server allocated backing ID +* FUSE_HAS_COMPLETE_DIR: kernel supports FOPEN_COMPLETE_DIR */ #define FUSE_ASYNC_READ (1 << 0)#define FUSE_POSIX_LOCKS (1 << 1)
@@ -530,6 +543,7 @@ struct fuse_file_lock {#define FUSE_HAS_IO_URING_BUFPOOL (1ULL << 43)#define FUSE_HAS_SYNCFS (1ULL << 44)#define FUSE_PASSTHROUGH_V2 (1ULL << 45) +#define FUSE_HAS_COMPLETE_DIR (1ULL << 46)/* * CUSE INIT request/reply flags
Signature · 1 line
2.56.0
Re: [PATCH 3/7] fuse: fill the negative lookup cache from complete READDIRPLUS passes
Quoted 10 lines · Han-Wen Nienhuys
Add
FOPEN_COMPLETE_DIR, with which the server marks a directory at OPENDIR, promising to announce remote additions withFUSE_NOTIFY_INVAL_ENTRY. When such a directory is read with READDIRPLUS from offset 0 to EOF, build its name filter from the returned names. This needs no extra transfer. Readdir holds the directory lock only per request, so local modifications in between are caught by the names generation, sampled at offset 0. The flag is per OPENDIR, as READDIRPLUS replies have no header to carry it.
Quoted 8 lines
The filter expires with the entry timeout of ".", which is otherwise unused, so the server can choose it, also for an empty directory. If "." has no nodeid, the smallest timeout of the other entries with a nodeid is used, so that no negative answer outlives a positive one the server handed out. Without any timeout, no filter is built.
Names are collected per struct
fuse_file, as hashes in a temporary array, since their number is only known at EOF. The collection is
Since the server is communicating TTL in "." entry, how about letting it communicate the expected collection size in st_size or st_blocks of directory?
This is generally what directory size means and many filesystems can have this number ready to publish without a full readdir. Not sure if the contract of FOPEN_COMPLETE_DIR should include this or not.
Quoted 326 lines
abandoned on a seek, an error, or more than 2^18 names. While collecting, READDIRPLUS is forced, as READDIR carries no timeouts. A pass served from the readdir cache (
FOPEN_CACHE_DIR) collects nothing, so an expired filter is not rebuilt until the cache is.Signed-off-by Han-Wen Nienhuys <[email protected]>Assisted-by Claude:claude-opus-5-5--- fs/fuse/dir.c | 1 + fs/fuse/fuse_i.h | 3 + fs/fuse/inode.c | 2 +- fs/fuse/readdir.c | 146 ++++++++++++++++++++++++++++++++++++-- include/uapi/linux/fuse.h | 16 ++++- 5 files changed, 162 insertions(+), 6 deletions(-)fs/fuse/dir.c +1
-0@@ -1951,6 +1951,7 @@ static int fuse_dir_open(struct inode *inode, struct file *file)static int fuse_dir_release (struct inode *inode,struct file *file) { +fuse_readdir_names_release (file->private_data);fuse_release_common (file, true);return 0 ;fs/fuse/fuse_i.h +3
-0@@ -343,6 +343,8 @@ struct fuse_file {/** @version: Version of cache we are reading */ u64 version; +/** @names: listing being collected for FOPEN_COMPLETE_DIR */ +struct fuse_dir_names_builder *names; } readdir;/** @polled_node: RB node to be linked on fuse_conn->polled_files */ @@ -1274,6 +1276,7 @@ int fuse_set_acl(struct mnt_idmap *, struct dentry *dentry,/* readdir.c */ int fuse_readdir (struct file *file,struct dir_context *ctx); +void fuse_readdir_names_release (struct fuse_file *ff);/* dir_names.c */ fs/fuse/inode.c +1
-1@@ -1508,7 +1508,7 @@ static struct fuse_init_args *fuse_new_init(struct fuse_mount *fm)FUSE_SECURITY_CTX |FUSE_CREATE_SUPP_GROUP |FUSE_HAS_EXPIRE_ONLY |FUSE_DIRECT_IO_ALLOW_MMAP |FUSE_NO_EXPORT_SUPPORT |FUSE_HAS_RESEND |FUSE_ALLOW_IDMAP | -FUSE_REQUEST_TIMEOUT ; +FUSE_REQUEST_TIMEOUT |FUSE_HAS_COMPLETE_DIR ;#ifdef CONFIG_FUSE_VDAX if (fm->fc->vdax) flags |=FUSE_MAP_ALIGNMENT ;fs/fuse/readdir.c +142
-4@@ -13,6 +13,125 @@#include <linux/vmalloc.h> #include <linux/namei.h> +/* +* Names of a listing that is being read with FOPEN_COMPLETE_DIR. The number of +* names is only known at EOF, so the filter is built from these hashes then. +*/ +struct fuse_dir_names_builder { +u64 *hash; +unsigned int count; +unsigned int size; +/* entry timeouts of ".", and the smallest of the others; or U64_MAX */ +u64 dot_expires; +u64 expires; +int epoch; +/* names generation when the listing was started */ +u64 gen; +/* ctx->pos expected by the next getdents call */ +loff_t pos; +}; + +void fuse_readdir_names_release (struct fuse_file *ff) +{ +struct fuse_dir_names_builder *nb = ff->readdir.names; + +if (!nb) +return ; +kvfree (nb->hash); +kfree (nb); + ff->readdir.names =NULL ; +} + +static void fuse_readdir_names_start (struct file *file) +{ +struct fuse_file *ff = file->private_data; +struct inode *inode =file_inode (file); +struct fuse_dir_names_builder *nb; + +fuse_readdir_names_release (ff); + + nb =kzalloc_obj (*nb,GFP_KERNEL_ACCOUNT ); +if (!nb) +return ; + nb->dot_expires =U64_MAX ; + nb->expires =U64_MAX ; + nb->epoch =atomic_read (&get_fuse_conn (inode)->epoch); + nb->gen =fuse_dir_names_gen (inode); + ff->readdir.names = nb; +} + +static void fuse_readdir_names_collect (struct file *file, +struct fuse_direntplus *direntplus) +{ +struct fuse_file *ff = file->private_data; +struct fuse_dir_names_builder *nb = ff->readdir.names; +struct fuse_conn *fc =get_fuse_conn (file_inode (file)); +struct fuse_dirent *dirent = &direntplus->dirent; +struct fuse_entry_out *o = &direntplus->entry_out; + +if (!nb) +return ; + +if (o->nodeid) { +u64 expires =fuse_time_to_jiffies (o->entry_valid, + o->entry_valid_nsec); + +if (dirent->namelen ==1 && dirent->name[0 ] =='.' ) + nb->dot_expires = expires; +else + nb->expires =min (nb->expires, expires); + } + +if (name_is_dot_dotdot (dirent->name, dirent->namelen)) +return ; + +if (nb->count == nb->size) { +unsigned int size =max (nb->size *2 ,64U ); +u64 *hash; + +if (size >FUSE_DIR_NAMES_MAX ) + goto abort; + hash =kvrealloc (nb->hash, size *sizeof (*hash), +GFP_KERNEL_ACCOUNT ); +if (!hash) + goto abort; + nb->hash = hash; + nb->size = size; + } + nb->hash[nb->count++] =fuse_dir_name_hash (fc, dirent->name, + dirent->namelen); +return ; + +abort: +fuse_readdir_names_release (ff); +} + +static void fuse_readdir_names_publish (struct file *file) +{ +struct fuse_file *ff = file->private_data; +struct fuse_dir_names_builder *nb = ff->readdir.names; +struct fuse_dir_names *names; +unsigned int i; +u64 expires; + +if (!nb) +return ; + +/* "." is never looked up, so its timeout is for the listing */ + expires = nb->dot_expires !=U64_MAX ? nb->dot_expires : nb->expires; +if (expires ==U64_MAX ) + goto out; + + names =fuse_dir_names_alloc (nb->count, expires, nb->epoch); +if (!names) + goto out; +for (i =0 ; i < nb->count; i++) +fuse_dir_names_insert (names, nb->hash[i]); +fuse_dir_names_publish (file_inode (file), names, nb->gen); +out: +fuse_readdir_names_release (ff); +} +static bool fuse_use_readdirplus (struct inode *dir,struct dir_context *ctx) {struct fuse_conn *fc =get_fuse_conn (dir);@@ -365,8 +484,14 @@ static int parse_dirplusfile(char *buf, size_t nbytes, struct file *file,which we did not link. */ over = !fuse_emit (file, ctx, dirent); -if (!over) +if (!over) { ctx->pos = dirent->off; +/* +* Only names the caller takes: the rest of the +* reply is sent again by the next request. +*/ +fuse_readdir_names_collect (file, direntplus); + } } buf += reclen;@@ -426,9 +551,12 @@ static int fuse_readdir_uncached(struct file *file, struct dir_context *ctx) {int plus;ssize_t res; +struct fuse_file *ff = file->private_data;struct inode *inode =file_inode (file);struct fuse_mount *fm =get_fuse_mount (inode);struct fuse_conn *fc = fm->fc; +bool complete = fc->do_readdirplus && + (ff->open_flags &FOPEN_COMPLETE_DIR );struct fuse_io_args ia = {};struct fuse_args_pages *ap = &ia.ap;void *buf;@@ -441,7 +569,14 @@ static int fuse_readdir_uncached(struct file *file, struct dir_context *ctx)if (!pages)return -ENOMEM ; - plus =fuse_use_readdirplus (inode, ctx); +if (complete && !ctx->pos) +fuse_readdir_names_start (file); +else if (ff->readdir.names && ff->readdir.names->pos != ctx->pos) +fuse_readdir_names_release (ff); + +/* Collecting needs entry timeouts */ + plus = (complete && ff->readdir.names) || +fuse_use_readdirplus (inode, ctx);if (plus) { attr_version =fuse_get_attr_version (fm->fc); evict_ctr =fuse_get_evict_ctr (fm->fc);@@ -456,10 +591,9 @@ static int fuse_readdir_uncached(struct file *file, struct dir_context *ctx) goto out;if (!res) { -struct fuse_file *ff = file->private_data; -if (ff->open_flags &FOPEN_CACHE_DIR )fuse_readdir_cache_end (file, ctx->pos); +fuse_readdir_names_publish (file); goto out; }@@ -479,7 +613,11 @@ static int fuse_readdir_uncached(struct file *file, struct dir_context *ctx)/* The server took lookup references also for entries not linked */ if (plus && res <0 )fuse_direntplus_forget (inode, pages, parsed, nbytes); +if (!res && ff->readdir.names) + ff->readdir.names->pos = ctx->pos; out: +if (res <0 ) +fuse_readdir_names_release (ff);kfree (ap->folios);release_pages (pages, ap->num_folios);kfree (pages);include/uapi/linux/fuse.h +15
-2@@ -257,6 +257,9 @@* - add backing_id_64 to fuse_open_out * - add FUSE_NOTIFY_BACKING_MAP, fuse_notify_backing_map_out, fuse_extent * - add FUSE_BACKING_MAP_CREATE, FUSE_BACKING_MAP_CYCLIC +* +* 7.48 +* - add FOPEN_COMPLETE_DIR and FUSE_HAS_COMPLETE_DIR */ #ifndef _LINUX_FUSE_H@@ -292,7 +295,7 @@#define FUSE_KERNEL_VERSION 7/** Minor version number of this interface */ -#define FUSE_KERNEL_MINOR_VERSION 47 +#define FUSE_KERNEL_MINOR_VERSION 48/** The node ID of the root inode */ #define FUSE_ROOT_ID 1@@ -406,6 +409,14 @@ struct fuse_file_lock {* (FUSE_URING_ZERO_COPY) and the request carries page * payload. Otherwise reads/writes fall back to * copying. +* FOPEN_COMPLETE_DIR: a complete READDIRPLUS listing of this directory is +* authoritative: names not in it are looked up as +* negative without sending FUSE_LOOKUP. This holds +* until the entry timeout of "." expires, or if "." has +* nodeid 0, the smallest entry timeout of the entries +* with a nonzero nodeid. "." does not count as a +* lookup. LOOKUP must only resolve names in the +* listing, byte for byte (eg. no case folding). */ #define FOPEN_DIRECT_IO (1 << 0)#define FOPEN_KEEP_CACHE (1 << 1)@@ -416,6 +427,7 @@ struct fuse_file_lock {#define FOPEN_PARALLEL_DIRECT_WRITES (1 << 6)#define FOPEN_PASSTHROUGH (1 << 7)#define FOPEN_IO_URING_ZERO_COPY (1 << 8) +#define FOPEN_COMPLETE_DIR (1 << 9)/* * INIT request/reply flags @@ -480,6 +492,7 @@ struct fuse_file_lock {* privilege that mounting virtiofs or fuseblk requires). * Insufficiently privileged servers ignore it. * FUSE_PASSTHROUGH_V2: use 64 bit server allocated backing ID +* FUSE_HAS_COMPLETE_DIR: kernel supports FOPEN_COMPLETE_DIR */ #define FUSE_ASYNC_READ (1 << 0)#define FUSE_POSIX_LOCKS (1 << 1)@@ -530,6 +543,7 @@ struct fuse_file_lock {#define FUSE_HAS_IO_URING_BUFPOOL (1ULL << 43)#define FUSE_HAS_SYNCFS (1ULL << 44)#define FUSE_PASSTHROUGH_V2 (1ULL << 45) +#define FUSE_HAS_COMPLETE_DIR (1ULL << 46)/* * CUSE INIT request/reply flags -- 2.56.0
Re: [PATCH 3/7] fuse: fill the negative lookup cache from complete READDIRPLUS passes
thanks for your review!
Quoted 9 lines · Amir Goldstein
Quoted 2 lines
Names are collected per struct
fuse_file, as hashes in a temporary array, since their number is only known at EOF. The collection isSince the server is communicating TTL in "." entry, how about letting it communicate the expected collection size in
st_sizeorst_blocksof directory?This is generally what directory size means and many filesystems can have this number ready to publish without a full readdir. Not sure if the contract of
FOPEN_COMPLETE_DIRshould include this or not.
We could add this, but I think we'd have to do something sensible if the size isn't set, so it doesn't save complexity. The memory savings are transient (while the dir is open) and not that large (54 bits per entry). Also, what happens if the server sets the size incorrectly (ie. too small)? Do we just accept filling a bloom filter that is useless? How would the server know they made a mistake?
altogether, I think we'd better size the filter automatically.
Signature · 1 line
Han-Wen Nienhuys - [email protected] - http://www.xs4all.nl/~hanwen
Re: [PATCH 3/7] fuse: fill the negative lookup cache from complete READDIRPLUS passes
Quoted 14 lines · Han-Wen Nienhuys
thanks for your review!
Quoted 9 lines · Amir Goldstein
Quoted 2 lines
Names are collected per struct
fuse_file, as hashes in a temporary array, since their number is only known at EOF. The collection isSince the server is communicating TTL in "." entry, how about letting it communicate the expected collection size in
st_sizeorst_blocksof directory?This is generally what directory size means and many filesystems can have this number ready to publish without a full readdir. Not sure if the contract of
FOPEN_COMPLETE_DIRshould include this or not.
Quoted 8 lines
We could add this, but I think we'd have to do something sensible if the size isn't set, so it doesn't save complexity. The memory savings are transient (while the dir is open) and not that large (54 bits per entry). Also, what happens if the server sets the size incorrectly (ie. too small)? Do we just accept filling a bloom filter that is useless? How would the server know they made a mistake?
altogether, I think we'd better size the filter automatically.
Yes we need to support a dynamically sized directory, but if the server knows the number of entries in advance and could communicate them reliably to the kernel that could save all the intermediate building of the list and could be a lot more efficient, especially with very large directories.
But it's an optimization so no need to do it now.
Thanks,
Amir.
PATCH 4/7 fuse: split readdir requests from struct file
In reply to Han-Wen NienhuysMake the readdir code work on a struct fuse_file and the dentry of the directory instead of a struct file, and split the request into setting up its arguments, sending it, and processing the reply. A following change reads a directory with background requests, which have no struct file, and process their replies in a work item.
fuse_file_read_args_fill() is fuse_read_args_fill() for a fuse_file and the open flags. fuse_readdir_args_end() reports whether the end of the directory was reached, which the getdents path does not need.
No functional change.
--- fs/fuse/file.c | 15 +++- fs/fuse/fuse_i.h | 3 + fs/fuse/readdir.c | 190 ++++++++++++++++++++++++++++------------------ 3 files changed, 130 insertions(+), 78 deletions(-)
fs/fuse/file.c +11 -4
@@ -606,16 +606,16 @@ static int fuse_fsync(struct file *file, loff_t start, loff_t end,return err; } -void fuse_read_args_fill (struct fuse_io_args *ia,struct file *file,loff_t pos, -size_t count,int opcode) +void fuse_file_read_args_fill (struct fuse_io_args *ia,struct fuse_file *ff, +unsigned int f_flags,loff_t pos,size_t count, +int opcode) { -struct fuse_file *ff = file->private_data;struct fuse_args *args = &ia->ap.args; ia->read.in.fh = ff->fh; ia->read.in.offset = pos; ia->read.in.size = count; - ia->read.in.flags = file->f_flags; + ia->read.in.flags = f_flags; args->opcode = opcode; args->nodeid = ff->nodeid; args->in_numargs =1 ;
@@ -627,6 +627,13 @@ void fuse_read_args_fill(struct fuse_io_args *ia, struct file *file, loff_t pos, args->zero_copy = ff->open_flags &FOPEN_IO_URING_ZERO_COPY ; } +void fuse_read_args_fill (struct fuse_io_args *ia,struct file *file,loff_t pos, +size_t count,int opcode) +{ +fuse_file_read_args_fill (ia, file->private_data, file->f_flags, pos, + count, opcode); +} +static void fuse_release_user_pages (struct fuse_args_pages *ap,ssize_t nres,bool should_dirty) {
fs/fuse/fuse_i.h +3 -0
@@ -999,6 +999,9 @@ struct fuse_io_args {struct fuse_file *ff; }; +void fuse_file_read_args_fill (struct fuse_io_args *ia,struct fuse_file *ff, +unsigned int f_flags,loff_t pos,size_t count, +int opcode);void fuse_read_args_fill (struct fuse_io_args *ia,struct file *file,loff_t pos,size_t count,int opcode);
fs/fuse/readdir.c +116 -74
346 lines not on this page · raw message
Signature · 1 line
2.56.0
PATCH 5/7 fuse: allow requests on behalf of no process
In reply to Han-Wen NienhuysRequests made by the kernel on its own account, rather than for a process, have no meaningful credentials: a kworker would send root, or fail to map into the server's user namespace, and a process that triggered the request indirectly may not map either.
Add args->no_caller, with which a request carries FUSE_INVALID_UIDGID as uid and gid, as on idmapped mounts, and pid 0. Servers already have to handle these ids for idmapped mounts.
--- fs/fuse/args.h | 2 ++ fs/fuse/req.c | 7 +++++++ 2 files changed, 9 insertions(+)
fs/fuse/args.h +2 -0
@@ -31,6 +31,8 @@ struct fuse_args { bool force:1; bool noreply:1; bool nocreds:1; +/* send no pid, uid or gid */ + bool no_caller:1; bool in_pages:1; bool out_pages:1; bool user_pages:1;
fs/fuse/req.c +7 -0
@@ -13,6 +13,13 @@ static int fuse_fill_creds(struct fuse_mount *fm, struct fuse_args *args, structif (args->nocreds)return 0 ; +if (args->no_caller) { + args->pid =0 ; + args->uid =FUSE_INVALID_UIDGID ; + args->gid =FUSE_INVALID_UIDGID ; +return 0 ; + } + args->pid =pid_nr_ns (task_pid (current), fc->pid_ns);if (args->force) {
Signature · 1 line
2.56.0
PATCH 6/7 fuse: open and release files for the kernel itself
In reply to Han-Wen NienhuysA following change reads a directory from a work item, on behalf of no process. Add __fuse_file_open(), which can mark the OPEN or OPENDIR request with args->no_caller, and __fuse_file_release(), which takes whether to wait for the server to process the release, rather than deriving it from the connection.
No functional change.
--- fs/fuse/file.c | 33 ++++++++++++++++++++++++++------- fs/fuse/fuse_i.h | 6 ++++++ 2 files changed, 32 insertions(+), 7 deletions(-)
fs/fuse/file.c +26 -7
@@ -23,7 +23,7 @@#include <linux/iomap.h> static int fuse_send_open (struct fuse_mount *fm,u64 nodeid, -unsigned int open_flags,int opcode, +unsigned int open_flags,int opcode,bool no_caller,struct fuse_open_out *outargp) {struct fuse_open_in inarg;
@@ -49,6 +49,7 @@ static int fuse_send_open(struct fuse_mount *fm, u64 nodeid, args.out_argvar = true;/* compat */ args.out_args[0 ].size =sizeof (*outargp); args.out_args[0 ].value = outargp; + args.no_caller = no_caller; res =fuse_simple_request (fm, &args);
@@ -134,8 +135,10 @@ static void fuse_file_put(struct fuse_file *ff, bool sync) } } -struct fuse_file *fuse_file_open (struct fuse_mount *fm,u64 nodeid, -unsigned int open_flags,bool isdir) +/* Open @nodeid. If @no_caller, the request is made on behalf of no process. */ +struct fuse_file *__fuse_file_open (struct fuse_mount *fm,u64 nodeid, +unsigned int open_flags,bool isdir, +bool no_caller) {struct fuse_conn *fc = fm->fc;struct fuse_file *ff;
@@ -163,7 +166,8 @@ struct fuse_file *fuse_file_open(struct fuse_mount *fm, u64 nodeid,struct fuse_open_out *outargp = &ff->args->open_outarg;int err; - err =fuse_send_open (fm, nodeid, open_flags, opcode, outargp); + err =fuse_send_open (fm, nodeid, open_flags, opcode, no_caller, + outargp);if (!err) { ff->fh = outargp->fh; ff->open_flags = outargp->open_flags;
@@ -190,6 +194,12 @@ struct fuse_file *fuse_file_open(struct fuse_mount *fm, u64 nodeid,return ff; } +struct fuse_file *fuse_file_open (struct fuse_mount *fm,u64 nodeid, +unsigned int open_flags,bool isdir) +{ +return __fuse_file_open (fm, nodeid, open_flags, isdir, false); +} +int fuse_do_open (struct fuse_mount *fm,u64 nodeid,struct file *file,bool isdir) {
@@ -358,8 +368,10 @@ static void fuse_prepare_release(struct fuse_inode *fi, struct fuse_file *ff, ra->inode = sync ?NULL :igrab (&fi->inode); } -void fuse_file_release (struct inode *inode,struct fuse_file *ff, -unsigned int open_flags,fl_owner_t id,bool isdir) +/* Release @ff. If @sync, wait for the server to process the release. */ +void __fuse_file_release (struct inode *inode,struct fuse_file *ff, +unsigned int open_flags,fl_owner_t id,bool isdir, +bool sync) {struct fuse_inode *fi =get_fuse_inode (inode);struct fuse_release_args *ra = &ff->args->release_args;
@@ -372,6 +384,12 @@ void fuse_file_release(struct inode *inode, struct fuse_file *ff, ra->inarg.lock_owner =fuse_lock_owner_id (ff->fm->fc, id); } +fuse_file_put (ff, sync); +} + +void fuse_file_release (struct inode *inode,struct fuse_file *ff, +unsigned int open_flags,fl_owner_t id,bool isdir) +{/* * Normally this will send the RELEASE request, however if * some asynchronous READ or WRITE requests are outstanding,
@@ -393,7 +411,8 @@ void fuse_file_release(struct inode *inode, struct fuse_file *ff,* before commencing with fs shutdown doesn't work if submounts are * used. */ -fuse_file_put (ff, ff->fm->fc->auto_submounts); +__fuse_file_release (inode, ff, open_flags, id, isdir, + ff->fm->fc->auto_submounts); }void fuse_release_common (struct file *file,bool isdir)
fs/fuse/fuse_i.h +6 -0
@@ -1352,8 +1352,14 @@ int fuse_file_io_open(struct file *file, struct inode *inode);void fuse_file_io_release (struct fuse_file *ff,struct inode *inode);/* file.c */ +struct fuse_file *__fuse_file_open (struct fuse_mount *fm,u64 nodeid, +unsigned int open_flags,bool isdir, +bool no_caller);struct fuse_file *fuse_file_open (struct fuse_mount *fm,u64 nodeid,unsigned int open_flags,bool isdir); +void __fuse_file_release (struct inode *inode,struct fuse_file *ff, +unsigned int open_flags,fl_owner_t id,bool isdir, +bool sync);void fuse_file_release (struct inode *inode,struct fuse_file *ff,unsigned int open_flags,fl_owner_t id,bool isdir);
Signature · 1 line
2.56.0
PATCH 7/7 fuse: let the server ask for a directory to be read in the background
In reply to Han-Wen NienhuysThe name filter is only built when something lists the directory, but many probes come from programs that never do, such as compilers searching include paths. Add FUSE_NOTIFY_READDIRPLUS, with which the server asks the kernel for a complete READDIRPLUS pass of a directory, as if it was opened with FOPEN_COMPLETE_DIR.
Having the kernel do the reads keeps lookup counts and race detection as for any READDIRPLUS pass; pushing the listing in a notification would need new rules for both. The cost is the round trips of OPENDIR, READDIRPLUS and RELEASEDIR.
The natural trigger is a negative LOOKUP reply. The server cannot tell a false positive of the filter from a lookup in an unlisted directory, so the hint fails with EALREADY if the directory has a valid filter or a pass is running. The server can then send it after every negative LOOKUP without keeping state. The directory is read after the notification returns, which does not wait for the server, so the hint can be sent from the LOOKUP handler itself.
The pass is a work item that sends its requests synchronously. Each READDIRPLUS and the processing of its reply run under the shared directory lock, and are skipped for a removed directory, as iterate_dir() does for getdents. The lock is not held in between; the names generation catches modifications there. The work items run on a workqueue per connection, allocated on first use, so that a server that does not reply only holds up its own passes. As each pass holds a dentry and a reply buffer, a connection runs at most 8 passes, which is also the max_active of the workqueue. Further hints fail with EBUSY.
The readdir cache is not filled, as it assumes reads through a file, nor reset for a server that returns no FOPEN_KEEP_CACHE on OPENDIR.
The requests are made on behalf of no process: OPENDIR and READDIRPLUS carry FUSE_INVALID_UIDGID, as on idmapped mounts. The kworker's credentials would make them root, or fail to map in a user namespace, and the notifier's may not map either if the device fd was passed across namespaces, failing the requests silently, so they are sent with args->no_caller. As there is no struct file, the pass is not seen by LSM file hooks or fsnotify; its dentries still go through d_splice_alias() and security_d_instantiate(). The work runs under the memcg of the server that sent the hint, so that the entries it instantiates are charged as they would be to a reader. As for getdents(), the reply buffers are not charged.
The dentry is pinned when the hint arrives, so a hint for an inode without a dentry fails with ENOENT. Unmount waits for the mount's
passes: before FUSE_DESTROY if one is sent, as no request may follow it, and otherwise after aborting the connection. A pass releases the directory synchronously for the same reason. Passes are only queued under fc->killsb while the mount is on the connection.
As for the other notifications, support is indicated by the minor version.
--- fs/fuse/dir_names.c | 14 +++ fs/fuse/fuse_i.h | 17 +++ fs/fuse/inode.c | 11 +- fs/fuse/notify.c | 23 ++++ fs/fuse/readdir.c | 253 ++++++++++++++++++++++++++++++++++++++ fs/fuse/virtio_fs.c | 1 + include/uapi/linux/fuse.h | 29 +++++ 7 files changed, 347 insertions(+), 1 deletion(-)
fs/fuse/dir_names.c +14 -0
@@ -227,6 +227,20 @@ static void fuse_dir_names_drop_stale(struct fuse_inode *fi,kvfree_rcu (names, rcu); } +/* Does @dir have a filter that can answer lookups? */ +bool fuse_dir_names_valid (struct inode *dir) +{ +struct fuse_inode *fi =get_fuse_inode (dir); +bool valid; + +rcu_read_lock (); + valid =fuse_dir_names_current (get_fuse_conn (dir), +rcu_dereference (fi->rdc.names)); +rcu_read_unlock (); + +return valid; +} +/* * Is @name known not to exist in @dir? If so, return the time until which * this is valid in @expires.
fs/fuse/fuse_i.h +17 -0
@@ -298,6 +298,8 @@ enum {* or the fuse server has an exclusive "lease" on distributed fs */ FUSE_I_EXCLUSIVE , +/* A background READDIRPLUS pass is queued or running */ + FUSE_I_READDIRPLUS_HINT, };struct fuse_conn ;
@@ -671,6 +673,12 @@ struct fuse_conn {/** @names_key: Key for hashing names in directory name filters */ siphash_key_t names_key; +/** @num_readdir_hints: background READDIRPLUS passes queued or running */ +atomic_t num_readdir_hints; + +/** @readdir_wq: Workqueue of the passes, allocated on first use */ +struct workqueue_struct *readdir_wq; +/** * @async_dio: Does the filesystem support asynchronous direct-IO * submission?
@@ -847,6 +855,12 @@ struct fuse_mount {/* Entry on fc->mounts */ struct list_head fc_entry; + +/* Background READDIRPLUS passes queued or running */ +atomic_t num_readdir_hints; +/* Set at unmount, to end the passes early */ +bool readdir_hints_stop; +struct rcu_head rcu; };
@@ -1280,6 +1294,8 @@ int fuse_set_acl(struct mnt_idmap *, struct dentry *dentry,/* readdir.c */ int fuse_readdir (struct file *file,struct dir_context *ctx);void fuse_readdir_names_release (struct fuse_file *ff); +int fuse_readdir_hint (struct fuse_conn *fc,u64 nodeid); +void fuse_readdir_hint_drain (struct fuse_mount *fm);/* dir_names.c */
@@ -1299,6 +1315,7 @@ void fuse_dir_names_changed(struct inode *dir);void fuse_dir_names_add (struct inode *dir,const struct qstr *name);void fuse_dir_names_invalidate (struct inode *dir);void fuse_dir_names_free (struct inode *dir); +bool fuse_dir_names_valid (struct inode *dir);bool fuse_dir_names_absent (struct inode *dir,const struct qstr *name,u64 *expires);
fs/fuse/inode.c +10 -1
@@ -1033,6 +1033,8 @@ void fuse_conn_put(struct fuse_conn *fc)if (IS_ENABLED (CONFIG_FUSE_VDAX ))fuse_vdax_conn_free (fc);cancel_work_sync (&fc->epoch_work); +if (fc->readdir_wq) +destroy_workqueue (fc->readdir_wq);fuse_chan_release (fc->chan);put_pid_ns (fc->pid_ns); bucket =rcu_dereference_protected (fc->curr_bucket,1 );
@@ -2009,8 +2011,14 @@ void fuse_conn_destroy(struct fuse_mount *fm) {struct fuse_conn *fc = fm->fc; -if (fc->destroy) +if (fc->destroy) { +/* +* No request may follow FUSE_DESTROY. It waits for the server +* anyway, so the passes can be waited for first. +*/ +fuse_readdir_hint_drain (fm);fuse_send_destroy (fm); + }fuse_chan_abort (fc->chan, false);fuse_chan_wait_aborted (fc->chan);
@@ -2033,6 +2041,7 @@ static void fuse_sb_destroy(struct super_block *sb) last =fuse_mount_remove (fm);if (last)fuse_conn_destroy (fm); +fuse_readdir_hint_drain (fm); } }
fs/fuse/notify.c +23 -0
@@ -478,6 +478,26 @@ static int fuse_notify_map(struct fuse_conn *fc, unsigned int size,return fuse_ext_map_populate (fc, &outarg, ext); } +static int fuse_notify_readdirplus (struct fuse_conn *fc,unsigned int size, +struct fuse_copy_state *cs) +{ +struct fuse_notify_readdirplus_out outarg; +int err; + +if (size !=sizeof (outarg)) +return -EINVAL ; + + err =fuse_copy_one (cs, &outarg,sizeof (outarg)); +if (err) +return err; +fuse_copy_finish (cs); + +if (outarg.flags || outarg.padding) +return -EINVAL ; + +return fuse_readdir_hint (fc, outarg.nodeid); +} +int fuse_notify (struct fuse_conn *fc,enum fuse_notify_code code,unsigned int size,struct fuse_copy_state *cs) {
@@ -515,6 +535,9 @@ int fuse_notify(struct fuse_conn *fc, enum fuse_notify_code code,case FUSE_NOTIFY_BACKING_MAP :return fuse_notify_map (fc, size, cs); +case FUSE_NOTIFY_READDIRPLUS : +return fuse_notify_readdirplus (fc, size, cs); +default :return -EINVAL ; }
fs/fuse/readdir.c +253 -0
265 lines not on this page · raw message
fs/fuse/virtio_fs.c +1 -0
@@ -1693,6 +1693,7 @@ static void virtio_kill_sb(struct super_block *sb) last =fuse_mount_remove (fm);if (last)virtio_fs_conn_destroy (fm); +fuse_readdir_hint_drain (fm); }kill_anon_super (sb);fuse_mount_destroy (fm);
include/uapi/linux/fuse.h +29 -0
@@ -260,6 +260,7 @@* * 7.48 * - add FOPEN_COMPLETE_DIR and FUSE_HAS_COMPLETE_DIR +* - add FUSE_NOTIFY_READDIRPLUS and struct fuse_notify_readdirplus_out */ #ifndef _LINUX_FUSE_H
@@ -733,6 +734,7 @@ enum fuse_notify_code {FUSE_NOTIFY_PRUNE =9 ,FUSE_NOTIFY_BACKING_REMOVE =10 ,FUSE_NOTIFY_BACKING_MAP =11 , + FUSE_NOTIFY_READDIRPLUS = 12, };/* The read buffer is required to be at least 8k, but may be much larger */
@@ -1178,6 +1180,33 @@ struct fuse_notify_prune_out {uint64_t spare; }; +/* +* Ask the kernel to read directory @nodeid in the background, with OPENDIR, +* READDIRPLUS until the end and RELEASEDIR, as if FOPEN_COMPLETE_DIR was set +* for it. Fails with EBUSY if the kernel is already reading other +* directories this way. +* +* The requests are not made on behalf of any process: OPENDIR and READDIRPLUS +* carry FUSE_INVALID_UIDGID as uid and gid, and pid 0. A server that checks +* permissions must allow these requests, eg. by recognizing these ids, or no +* listing is made. As for every release, RELEASEDIR carries uid and gid 0. +* +* Fails with EALREADY, and does nothing, if the directory already has a valid +* listing or is being read, so it can be sent after every negative LOOKUP. +* Fails with ENOENT if the kernel has no inode for @nodeid, or no dentry for +* it (eg. after the dentry cache was shrunk), and with EOPNOTSUPP if +* READDIRPLUS is not enabled. +* +* The directory is read after this returns, so it does not wait for the +* server, and may be sent from a request handler, eg. when handling a LOOKUP +* in the directory. +*/ +struct fuse_notify_readdirplus_out { +uint64_t nodeid; +uint32_t flags; +uint32_t padding; +}; +struct fuse_backing_map {int32_t fd;uint32_t flags;
Signature · 1 line
2.56.0
Quoted 138 lines · Han-Wen Nienhuys
FUSE servers can respond to LOOKUP requests with {OK, nodeID=0} to indicate an entry is not present, and the negative entry can be cached for a specified interval. This helps reduce the number of LOOKUP calls, but it is still problematic: each negative dentry still costs a roundtrip. Since the universe of non-existing files is unlimited, in practice we must still do many roundtrips.
We can do better: once the kernel has read directory contents (through READDIRPLUS), the server has specified which positive dentries exist. In most file systems, this means that all other lookups in the directory should yield negative results, and we can spare ourselves the roundtrips.
In this patch series, we collect filename hashes from directory reads, and use them to populate a Bloom filter once the read is finished. Then, on lookup, if we don't find the name in the Bloom filter, we skip the roundtrip and return a negative result immediately.
The Bloom filter is space efficient, while still allowing efficient updates when entries are added through MKDIR/CREATE/LINK operations.
The TTL of the Bloom filter is derived from the entry TTL of the "." entry, if specified, or the minimum TTL of the positive entries. We use READDIRPLUS rather than READDIR, because the latter has no channel to signal a TTL.
Once the filter is in place, the server should rarely get lookups in the directory. If the server does get lookups, this can mean two things:
1) the filter has expired
2) it was a false positive from the Bloom filterTo address case 1), the server should be able to trigger repopulating the filter, but because of 2), issuing a normal readdir unconditionally is expensive, and the server may not have access to the mountpoint anyway.
To solve this, we add a new notify method, which can return EALREADY (the filter is still valid; no further side effect) or OK (there is no filter; trigger a new READDIRPLUS to populate the filter again). The notify does not wait for the server, so it can be sent from the LOOKUP handler itself.
The kernel reads the directory from a work item, with synchronous OPENDIR, READDIRPLUS and RELEASEDIR requests made on behalf of no process. The work items run on a workqueue per connection, so a server that does not reply only holds up its own reads, and at most 8 run per connection; further notifications fail with EBUSY.
The notification also lets a server preemptively load a directory:
READDIRPLUS is attractive because a single roundtrip can load many entries, reducing overhead, but many programs (eg. GCC) only cause single file lookups, and never issue readdir.Unfortunately, virtiofs currently does not support notifications in general, so the latter benefits are not available for virtiofs.
The series is organized as follows:
* patch 1 fixes lookup references leaked on READDIRPLUS errors. It is independent of the rest.
* patch 2 adds the Bloom filter machinery
* patch 3 populates the filter from READDIRPLUS results (FOPEN_COMPLETE_DIR)
* patches 4-6 prepare for reading a directory from a work item, without functional change: readdir without a struct file, requests on behalf of no process, and opening and releasing a file for the kernel itself
* patch 7 adds the notify method.To support this feature in userspace, the server only needs to reply with
FOPEN_COMPLETE_DIRflag for the OPENDIR opcode. I did this in Go-FUSE, and added tests and benchmarks for the feature. Tests ran against a kernel with debug/paranoia settings. Benchmark against a kernel with production settings.[1]An i5-8350U pinned at 2 GHz yields the following performance numbers, in median ns/op over 11 runs:
ReadDirEntCompleteDir (per entry) 2,281
ReaddirplusHint (per entry) 1,801
NegStatUncached (LOOKUP round trip) 22,192
NegStatCached (dcache hit) 797
NegStatUncachedDir (Bloom filter) 1,587This was a synthetic, in-memory file system serving a directory with 500 entries, using the Go-FUSE high-level API running against
/dev/fuse, measured with single threaded access to the mountpoint, and GOMAXPROCS=2. ReaddirplusHint drops the filter withFUSE_NOTIFY_INVAL_INODEand has the kernel read the directory again with the new notification; it is cheaper per entry thangetdents(), as no entries are copied to userspace.The bloom filter is sized to 10 bits per entry, but then rounded to a power of 2. For 500 entries, this yields 8192 (16.4 bits per entry), with an expected false positive rate of 0.0006/op; the benchmark sees 0.0004/op.
So, the Bloom filter yields a 14x speed up on uncached negative lookups, at the cost of a full directory read. This pays off if
size-of-dir < (
cost_LOOKUP- cost_BLOOM)/cost_DIRENT * unique-negative-lookups
= 9 * unique-negative-lookupsAs a practical one-point sample: one of my open source C++ projects (lilypond) shows that a single G++ invocation gets ENOENT for 145 unique names under
/usr/include/libpng16, a directory with 3 entries, so scenarios where this is a win are easy to find.This code was written and reviewed with Claude Opus 5.5. The plan is included in [1].
It may be interesting to lift the Bloom filter into the VFS, for two reasons:
- other filesystems could benefit from this performance optimization, if the negative lookup is expensive. In particular: NFS, CephFS and overlayfs.
- the Bloom filter uses little memory, and makes negative dentries cheap to recreate. This could justify a more aggressive reclaim policy for them.
However, unlike the FUSE case, there is no way for a server to request a readdir, so it would need kernel-side heuristics to guess when this pays off.
Open questions:
- Where should the filter TTL come from? The entry timeout of "." is convenient because of backward compatibility, but it feels like a hack. Alternatively, we could extend
fuse_open_out(or repurpose the space forbacking_idin case of directories). This has the added advantage that we could populate the negative filter from READDIR as well. Then again, READDIRPLUS is better overall because it also loads positive entries with little overhead.
Quoted 3 lines
- Should filters be reclaimed under memory pressure, and if so, how? The filter costs ~2 bytes per file name, which seems little, but can grow to 512kb for a large directory.
Thinking out loud.
Is it really important to support FOPEN_COMPLETE_DIR without FOPEN_CACHE_DIR? The two feature seems to have correlated use cases.
Bloom filter is built at EOF, so it could be built at the end offset of the readdir cache buffer.
I also think it may be worth having a mode that invalidates the bloom filter along with readdir cache on mtime change.
This is a lower bar for servers that don't want to notify on all dir changes. In this case, the lifetimes of the readdir and bloom filter are aligned and truncating the page cache gets rid of them both.
Not having to deal with custom memory shrinkers seems like an advantage for the first release.
Is this making any sense?
Thanks,
Amir.
Quoted 8 lines · Amir Goldstein
Thinking out loud.
Is it really important to support
FOPEN_COMPLETE_DIRwithoutFOPEN_CACHE_DIR? The two feature seems to have correlated use cases.Bloom filter is built at EOF, so it could be built at the end offset of the readdir cache buffer.
Isn't the readdir cache dropped as soon as there is a namespace operation in the directory? That would severely limit the usefulness of the bloom filter in writable directories.
Signature · 1 line
Han-Wen Nienhuys - [email protected] - http://www.xs4all.nl/~hanwen
Quoted 9 lines · Han-Wen Nienhuys
Quoted 6 lines · Amir Goldstein
Thinking out loud.
Is it really important to support
FOPEN_COMPLETE_DIRwithoutFOPEN_CACHE_DIR? The two feature seems to have correlated use cases.
Quoted 6 lines
Quoted 2 lines
Bloom filter is built at EOF, so it could be built at the end offset of the readdir cache buffer.
Isn't the readdir cache dropped as soon as there is a namespace operation in the directory? That would severely limit the usefulness of the bloom filter in writable directories.
Good point.
Thanks,
Amir.