xref: /linux/fs/fuse/readdir.c (revision ae932b1f5727004f585d603e0cbab7e0725c04cf)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3   FUSE: Filesystem in Userspace
4   Copyright (C) 2001-2018  Miklos Szeredi <miklos@szeredi.hu>
5 */
6 
7 
8 #include "fuse_i.h"
9 #include <linux/iversion.h>
10 #include <linux/posix_acl.h>
11 #include <linux/pagemap.h>
12 #include <linux/highmem.h>
13 #include <linux/vmalloc.h>
14 #include <linux/namei.h>
15 
16 static bool fuse_use_readdirplus(struct inode *dir, struct dir_context *ctx)
17 {
18 	struct fuse_conn *fc = get_fuse_conn(dir);
19 	struct fuse_inode *fi = get_fuse_inode(dir);
20 
21 	if (!fc->do_readdirplus)
22 		return false;
23 	if (!fc->readdirplus_auto)
24 		return true;
25 	if (test_and_clear_bit(FUSE_I_ADVISE_RDPLUS, &fi->state))
26 		return true;
27 	if (ctx->pos == 0)
28 		return true;
29 	return false;
30 }
31 
32 static void fuse_add_dirent_to_cache(struct file *file,
33 				     struct fuse_dirent *dirent, loff_t pos)
34 {
35 	struct fuse_inode *fi = get_fuse_inode(file_inode(file));
36 	size_t reclen = FUSE_DIRENT_SIZE(dirent);
37 	pgoff_t index;
38 	struct folio *folio;
39 	loff_t size;
40 	u64 version;
41 	unsigned int offset;
42 	size_t folio_offset;
43 
44 	/* Dirent doesn't fit in readdir cache page?  Skip caching. */
45 	if (reclen > PAGE_SIZE)
46 		return;
47 
48 	spin_lock(&fi->rdc.lock);
49 	/*
50 	 * Is cache already completed?  Or this entry does not go at the end of
51 	 * cache?
52 	 */
53 	if (fi->rdc.cached || pos != fi->rdc.pos) {
54 		spin_unlock(&fi->rdc.lock);
55 		return;
56 	}
57 	version = fi->rdc.version;
58 	size = fi->rdc.size;
59 	offset = offset_in_page(size);
60 	index = size >> PAGE_SHIFT;
61 	/* Dirent doesn't fit in current page?  Jump to next page. */
62 	if (offset + reclen > PAGE_SIZE) {
63 		index++;
64 		offset = 0;
65 	}
66 	spin_unlock(&fi->rdc.lock);
67 
68 	if (offset)
69 		folio = filemap_lock_folio(file->f_mapping, index);
70 	else
71 		folio = filemap_grab_folio(file->f_mapping, index);
72 	if (IS_ERR(folio))
73 		return;
74 
75 	spin_lock(&fi->rdc.lock);
76 	/* Raced with another readdir */
77 	if (fi->rdc.version != version || fi->rdc.size != size ||
78 	    WARN_ON(fi->rdc.pos != pos))
79 		goto unlock;
80 
81 	folio_offset = offset_in_folio(folio, (index << PAGE_SHIFT) + offset);
82 	if (!offset) {
83 		folio_fill_tail(folio, folio_offset, (const char *)dirent,
84 				reclen);
85 		folio_mark_uptodate(folio);
86 	} else {
87 		memcpy_to_folio(folio, folio_offset, (const char *)dirent,
88 				reclen);
89 	}
90 	fi->rdc.size = (index << PAGE_SHIFT) + offset + reclen;
91 	fi->rdc.pos = dirent->off;
92 unlock:
93 	spin_unlock(&fi->rdc.lock);
94 	folio_unlock(folio);
95 	folio_put(folio);
96 }
97 
98 static void fuse_readdir_cache_end(struct file *file, loff_t pos)
99 {
100 	struct fuse_inode *fi = get_fuse_inode(file_inode(file));
101 	loff_t end;
102 
103 	spin_lock(&fi->rdc.lock);
104 	/* does cache end position match current position? */
105 	if (fi->rdc.pos != pos) {
106 		spin_unlock(&fi->rdc.lock);
107 		return;
108 	}
109 
110 	fi->rdc.cached = true;
111 	end = ALIGN(fi->rdc.size, PAGE_SIZE);
112 	spin_unlock(&fi->rdc.lock);
113 
114 	/* truncate unused tail of cache */
115 	truncate_inode_pages(file->f_mapping, end);
116 }
117 
118 static bool fuse_emit(struct file *file, struct dir_context *ctx,
119 		      struct fuse_dirent *dirent)
120 {
121 	struct fuse_file *ff = file->private_data;
122 
123 	if (ff->open_flags & FOPEN_CACHE_DIR)
124 		fuse_add_dirent_to_cache(file, dirent, ctx->pos);
125 
126 	return dir_emit(ctx, dirent->name, dirent->namelen, dirent->ino,
127 			dirent->type | FILLDIR_FLAG_NOINTR);
128 }
129 
130 static int parse_dirfile(char *buf, size_t nbytes, struct file *file,
131 			 struct dir_context *ctx)
132 {
133 	while (nbytes >= FUSE_NAME_OFFSET) {
134 		struct fuse_dirent *dirent = (struct fuse_dirent *) buf;
135 		size_t reclen = FUSE_DIRENT_SIZE(dirent);
136 		if (!dirent->namelen || dirent->namelen > FUSE_NAME_MAX)
137 			return -EIO;
138 		if (reclen > nbytes)
139 			break;
140 		if (memchr(dirent->name, '/', dirent->namelen) != NULL)
141 			return -EIO;
142 
143 		if (!fuse_emit(file, ctx, dirent))
144 			break;
145 
146 		buf += reclen;
147 		nbytes -= reclen;
148 		ctx->pos = dirent->off;
149 	}
150 
151 	return 0;
152 }
153 
154 static int fuse_direntplus_link(struct file *file,
155 				struct fuse_direntplus *direntplus,
156 				u64 attr_version, u64 evict_ctr)
157 {
158 	struct fuse_entry_out *o = &direntplus->entry_out;
159 	struct fuse_dirent *dirent = &direntplus->dirent;
160 	struct dentry *parent = file->f_path.dentry;
161 	struct qstr name = QSTR_INIT(dirent->name, dirent->namelen);
162 	struct dentry *dentry;
163 	struct dentry *alias;
164 	struct inode *dir = d_inode(parent);
165 	struct fuse_conn *fc;
166 	struct inode *inode;
167 	int epoch;
168 
169 	if (!o->nodeid) {
170 		/*
171 		 * Unlike in the case of fuse_lookup, zero nodeid does not mean
172 		 * ENOENT. Instead, it only means the userspace filesystem did
173 		 * not want to return attributes/handle for this entry.
174 		 *
175 		 * So do nothing.
176 		 */
177 		return 0;
178 	}
179 
180 	if (name.name[0] == '.') {
181 		/*
182 		 * We could potentially refresh the attributes of the directory
183 		 * and its parent?
184 		 */
185 		if (name.len == 1)
186 			return 0;
187 		if (name.name[1] == '.' && name.len == 2)
188 			return 0;
189 	}
190 
191 	if (invalid_nodeid(o->nodeid))
192 		return -EIO;
193 	if (fuse_invalid_attr(&o->attr))
194 		return -EIO;
195 	if (memchr(name.name, '\0', name.len))
196 		return -EIO;
197 
198 	fc = get_fuse_conn(dir);
199 	epoch = atomic_read(&fc->epoch);
200 
201 retry:
202 	dentry = d_alloc_trylock(parent, &name);
203 	if (IS_ERR(dentry))
204 		return PTR_ERR(dentry);
205 
206 	if (!d_in_lookup(dentry)) {
207 		struct fuse_inode *fi;
208 		inode = d_inode(dentry);
209 		if (inode && get_node_id(inode) != o->nodeid)
210 			inode = NULL;
211 		if (!inode ||
212 		    fuse_stale_inode(inode, o->generation, &o->attr)) {
213 			if (inode)
214 				fuse_make_bad(inode);
215 			d_invalidate(dentry);
216 			dput(dentry);
217 			goto retry;
218 		}
219 		if (fuse_is_bad(inode)) {
220 			dput(dentry);
221 			return -EIO;
222 		}
223 
224 		fi = get_fuse_inode(inode);
225 		spin_lock(&fi->lock);
226 		fi->nlookup++;
227 		spin_unlock(&fi->lock);
228 
229 		forget_all_cached_acls(inode);
230 		fuse_change_attributes(inode, &o->attr, NULL,
231 				       ATTR_TIMEOUT(o),
232 				       attr_version);
233 		fuse_dentry_set_epoch(dentry, epoch);
234 		/*
235 		 * The other branch comes via fuse_iget()
236 		 * which bumps nlookup inside
237 		 */
238 	} else {
239 		inode = fuse_iget(dir->i_sb, o->nodeid, o->generation,
240 				  &o->attr, ATTR_TIMEOUT(o),
241 				  attr_version, evict_ctr);
242 		if (!inode) {
243 			d_lookup_done(dentry);
244 			dput(dentry);
245 			return -ENOMEM;
246 		}
247 
248 		fuse_dentry_set_epoch(dentry, epoch);
249 		ihold(inode); /* d_splice_alias() eats a reference */
250 		alias = d_splice_alias(inode, dentry);
251 		d_lookup_done(dentry);
252 		if (alias) {
253 			dput(dentry);
254 			dentry = alias;
255 		}
256 		if (IS_ERR(dentry)) {
257 			struct fuse_inode *fi = get_fuse_inode(inode);
258 
259 			spin_lock(&fi->lock);
260 			fi->nlookup--;
261 			spin_unlock(&fi->lock);
262 			iput(inode);
263 			return PTR_ERR(dentry);
264 		}
265 		if (alias)
266 			fuse_dentry_set_epoch(dentry, epoch);
267 		iput(inode);
268 	}
269 	if (fc->readdirplus_auto)
270 		set_bit(FUSE_I_INIT_RDPLUS, &get_fuse_inode(inode)->state);
271 	fuse_change_entry_timeout(dentry, o);
272 
273 	dput(dentry);
274 	return 0;
275 }
276 
277 static void fuse_force_forget(struct file *file, u64 nodeid)
278 {
279 	struct inode *inode = file_inode(file);
280 	struct fuse_mount *fm = get_fuse_mount(inode);
281 	struct fuse_forget_in inarg;
282 	FUSE_ARGS(args);
283 
284 	memset(&inarg, 0, sizeof(inarg));
285 	inarg.nlookup = 1;
286 	args.opcode = FUSE_FORGET;
287 	args.nodeid = nodeid;
288 	args.in_numargs = 1;
289 	args.in_args[0].size = sizeof(inarg);
290 	args.in_args[0].value = &inarg;
291 	args.force = true;
292 	args.noreply = true;
293 
294 	fuse_simple_request(fm, &args);
295 	/* ignore errors */
296 }
297 
298 static int parse_dirplusfile(char *buf, size_t nbytes, struct file *file,
299 			     struct dir_context *ctx, u64 attr_version,
300 			     u64 evict_ctr)
301 {
302 	struct fuse_direntplus *direntplus;
303 	struct fuse_dirent *dirent;
304 	size_t reclen;
305 	int over = 0;
306 	int ret;
307 
308 	while (nbytes >= FUSE_NAME_OFFSET_DIRENTPLUS) {
309 		direntplus = (struct fuse_direntplus *) buf;
310 		dirent = &direntplus->dirent;
311 		reclen = FUSE_DIRENTPLUS_SIZE(direntplus);
312 
313 		if (!dirent->namelen || dirent->namelen > FUSE_NAME_MAX)
314 			return -EIO;
315 		if (reclen > nbytes)
316 			break;
317 		if (memchr(dirent->name, '/', dirent->namelen) != NULL)
318 			return -EIO;
319 
320 		if (!over) {
321 			/* We fill entries into dstbuf only as much as
322 			   it can hold. But we still continue iterating
323 			   over remaining entries to link them. If not,
324 			   we need to send a FORGET for each of those
325 			   which we did not link.
326 			*/
327 			over = !fuse_emit(file, ctx, dirent);
328 			if (!over)
329 				ctx->pos = dirent->off;
330 		}
331 
332 		buf += reclen;
333 		nbytes -= reclen;
334 
335 		ret = fuse_direntplus_link(file, direntplus, attr_version, evict_ctr);
336 		if (ret)
337 			fuse_force_forget(file, direntplus->entry_out.nodeid);
338 	}
339 
340 	return 0;
341 }
342 
343 static struct page **fuse_readdir_alloc_buf(struct fuse_args_pages *ap, size_t *bufsize)
344 {
345 	unsigned int i, nr_alloc, nr_pages = DIV_ROUND_UP(*bufsize, PAGE_SIZE);
346 	struct page **pages = kzalloc_objs(*pages, nr_pages);
347 
348 	if (!pages)
349 		return NULL;
350 
351 	nr_alloc = alloc_pages_bulk(GFP_KERNEL, nr_pages, pages);
352 	if (!nr_alloc)
353 		goto free_array;
354 
355 	if (nr_alloc < nr_pages) {
356 		nr_pages = nr_alloc;
357 		*bufsize = (size_t) nr_pages << PAGE_SHIFT;
358 	}
359 
360 	ap->folios = fuse_folios_alloc(nr_pages, GFP_KERNEL, &ap->descs);
361 	if (!ap->folios)
362 		goto release_pages;
363 
364 	for (i = 0; i < nr_pages; i++) {
365 		ap->folios[i] = page_folio(pages[i]);
366 		ap->descs[i].length = min_t(size_t, *bufsize - (size_t)i * PAGE_SIZE, PAGE_SIZE);
367 	}
368 	ap->num_folios = nr_pages;
369 	ap->args.out_pages = true;
370 
371 	return pages;
372 
373 release_pages:
374 	release_pages(pages, nr_pages);
375 free_array:
376 	kfree(pages);
377 	return NULL;
378 }
379 
380 static int fuse_readdir_uncached(struct file *file, struct dir_context *ctx)
381 {
382 	int plus;
383 	ssize_t res;
384 	struct inode *inode = file_inode(file);
385 	struct fuse_mount *fm = get_fuse_mount(inode);
386 	struct fuse_conn *fc = fm->fc;
387 	struct fuse_io_args ia = {};
388 	struct fuse_args_pages *ap = &ia.ap;
389 	void *buf;
390 	size_t bufsize = clamp((unsigned int) ctx->count, PAGE_SIZE, fc->max_pages << PAGE_SHIFT);
391 	u64 attr_version = 0, evict_ctr = 0;
392 	bool locked;
393 	struct page **pages = fuse_readdir_alloc_buf(ap, &bufsize);
394 
395 	if (!pages)
396 		return -ENOMEM;
397 
398 	plus = fuse_use_readdirplus(inode, ctx);
399 	if (plus) {
400 		attr_version = fuse_get_attr_version(fm->fc);
401 		evict_ctr = fuse_get_evict_ctr(fm->fc);
402 		fuse_read_args_fill(&ia, file, ctx->pos, bufsize, FUSE_READDIRPLUS);
403 	} else {
404 		fuse_read_args_fill(&ia, file, ctx->pos, bufsize, FUSE_READDIR);
405 	}
406 	locked = fuse_lock_inode(inode);
407 	res = fuse_simple_request(fm, &ap->args);
408 	fuse_unlock_inode(inode, locked);
409 	if (res < 0)
410 		goto out;
411 
412 	if (!res) {
413 		struct fuse_file *ff = file->private_data;
414 
415 		if (ff->open_flags & FOPEN_CACHE_DIR)
416 			fuse_readdir_cache_end(file, ctx->pos);
417 		goto out;
418 	}
419 
420 	buf = vm_map_ram(pages, ap->num_folios, -1);
421 	if (!buf) {
422 		res = -ENOMEM;
423 	} else {
424 		if (plus)
425 			res = parse_dirplusfile(buf, res, file, ctx, attr_version, evict_ctr);
426 		else
427 			res = parse_dirfile(buf, res, file, ctx);
428 
429 		vm_unmap_ram(buf, ap->num_folios);
430 	}
431 out:
432 	kfree(ap->folios);
433 	release_pages(pages, ap->num_folios);
434 	kfree(pages);
435 
436 	fuse_invalidate_atime(inode);
437 
438 	return res;
439 }
440 
441 enum fuse_parse_result {
442 	FOUND_ERR = -1,
443 	FOUND_NONE = 0,
444 	FOUND_SOME,
445 	FOUND_ALL,
446 };
447 
448 static enum fuse_parse_result fuse_parse_cache(struct fuse_file *ff,
449 					       void *addr, unsigned int size,
450 					       struct dir_context *ctx)
451 {
452 	unsigned int offset = offset_in_page(ff->readdir.cache_off);
453 	enum fuse_parse_result res = FOUND_NONE;
454 
455 	WARN_ON(offset >= size);
456 
457 	for (;;) {
458 		struct fuse_dirent *dirent = addr + offset;
459 		unsigned int nbytes = size - offset;
460 		size_t reclen;
461 
462 		if (nbytes < FUSE_NAME_OFFSET || !dirent->namelen)
463 			break;
464 
465 		reclen = FUSE_DIRENT_SIZE(dirent); /* derefs ->namelen */
466 
467 		if (WARN_ON(dirent->namelen > FUSE_NAME_MAX))
468 			return FOUND_ERR;
469 		if (WARN_ON(reclen > nbytes))
470 			return FOUND_ERR;
471 		if (WARN_ON(memchr(dirent->name, '/', dirent->namelen) != NULL))
472 			return FOUND_ERR;
473 
474 		if (ff->readdir.pos == ctx->pos) {
475 			res = FOUND_SOME;
476 			if (!dir_emit(ctx, dirent->name, dirent->namelen,
477 				      dirent->ino, dirent->type | FILLDIR_FLAG_NOINTR))
478 				return FOUND_ALL;
479 			ctx->pos = dirent->off;
480 		}
481 		ff->readdir.pos = dirent->off;
482 		ff->readdir.cache_off += reclen;
483 
484 		offset += reclen;
485 	}
486 
487 	return res;
488 }
489 
490 static void fuse_rdc_reset(struct inode *inode)
491 {
492 	struct fuse_inode *fi = get_fuse_inode(inode);
493 
494 	fi->rdc.cached = false;
495 	fi->rdc.version++;
496 	fi->rdc.size = 0;
497 	fi->rdc.pos = 0;
498 	fi->rdc.epoch = 0;
499 }
500 
501 #define UNCACHED 1
502 
503 static int fuse_readdir_cached(struct file *file, struct dir_context *ctx)
504 {
505 	struct fuse_file *ff = file->private_data;
506 	struct inode *inode = file_inode(file);
507 	struct fuse_conn *fc = get_fuse_conn(inode);
508 	struct fuse_inode *fi = get_fuse_inode(inode);
509 	enum fuse_parse_result res;
510 	pgoff_t index;
511 	unsigned int size;
512 	struct folio *folio;
513 	void *addr;
514 
515 	/* Seeked?  If so, reset the cache stream */
516 	if (ff->readdir.pos != ctx->pos) {
517 		ff->readdir.pos = 0;
518 		ff->readdir.cache_off = 0;
519 	}
520 
521 	/*
522 	 * We're just about to start reading into the cache or reading the
523 	 * cache; both cases require an up-to-date mtime value.
524 	 */
525 	if (!ctx->pos && fc->auto_inval_data) {
526 		int err = fuse_update_attributes(inode, file, STATX_MTIME);
527 
528 		if (err)
529 			return err;
530 	}
531 
532 retry:
533 	spin_lock(&fi->rdc.lock);
534 retry_locked:
535 	if (!fi->rdc.cached) {
536 		/* Starting cache? Set cache mtime. */
537 		if (!ctx->pos && !fi->rdc.size) {
538 			fi->rdc.mtime = inode_get_mtime(inode);
539 			fi->rdc.iversion = inode_query_iversion(inode);
540 			fi->rdc.epoch = atomic_read(&fc->epoch);
541 		}
542 		spin_unlock(&fi->rdc.lock);
543 		return UNCACHED;
544 	}
545 	/*
546 	 * When at the beginning of the directory (i.e. just after opendir(3) or
547 	 * rewinddir(3)), then need to check whether directory contents have
548 	 * changed, and reset the cache if so.
549 	 */
550 	if (!ctx->pos) {
551 		struct timespec64 mtime = inode_get_mtime(inode);
552 
553 		if (inode_peek_iversion(inode) != fi->rdc.iversion ||
554 		    !timespec64_equal(&fi->rdc.mtime, &mtime) ||
555 		    fi->rdc.epoch != atomic_read(&fc->epoch)) {
556 			fuse_rdc_reset(inode);
557 			goto retry_locked;
558 		}
559 	}
560 
561 	/*
562 	 * If cache version changed since the last getdents() call, then reset
563 	 * the cache stream.
564 	 */
565 	if (ff->readdir.version != fi->rdc.version) {
566 		ff->readdir.pos = 0;
567 		ff->readdir.cache_off = 0;
568 	}
569 	/*
570 	 * If at the beginning of the cache, than reset version to
571 	 * current.
572 	 */
573 	if (ff->readdir.pos == 0)
574 		ff->readdir.version = fi->rdc.version;
575 
576 	WARN_ON(fi->rdc.size < ff->readdir.cache_off);
577 
578 	index = ff->readdir.cache_off >> PAGE_SHIFT;
579 
580 	if (index == (fi->rdc.size >> PAGE_SHIFT))
581 		size = offset_in_page(fi->rdc.size);
582 	else
583 		size = PAGE_SIZE;
584 	spin_unlock(&fi->rdc.lock);
585 
586 	/* EOF? */
587 	if (offset_in_page(ff->readdir.cache_off) == size)
588 		return 0;
589 
590 	folio = __filemap_get_folio(file->f_mapping, index,
591 				    FGP_ACCESSED | FGP_LOCK, 0);
592 	if (IS_ERR(folio))
593 		folio = NULL;
594 	/* Folio gone missing, then re-added to cache, but not initialized? */
595 	if (folio && !folio_test_uptodate(folio)) {
596 		folio_unlock(folio);
597 		folio_put(folio);
598 		folio = NULL;
599 	}
600 	spin_lock(&fi->rdc.lock);
601 	if (!folio) {
602 		/*
603 		 * Uh-oh: folio gone missing, cache is useless
604 		 */
605 		if (fi->rdc.version == ff->readdir.version)
606 			fuse_rdc_reset(inode);
607 		goto retry_locked;
608 	}
609 
610 	/* Make sure it's still the same version after getting the folio. */
611 	if (ff->readdir.version != fi->rdc.version) {
612 		spin_unlock(&fi->rdc.lock);
613 		folio_unlock(folio);
614 		folio_put(folio);
615 		goto retry;
616 	}
617 	spin_unlock(&fi->rdc.lock);
618 
619 	/*
620 	 * Contents of the folio are now protected against changing by holding
621 	 * the folio lock.
622 	 */
623 	addr = kmap_local_folio(folio, 0);
624 	res = fuse_parse_cache(ff, addr, size, ctx);
625 	kunmap_local(addr);
626 	folio_unlock(folio);
627 	folio_put(folio);
628 
629 	if (res == FOUND_ERR)
630 		return -EIO;
631 
632 	if (res == FOUND_ALL)
633 		return 0;
634 
635 	if (size == PAGE_SIZE) {
636 		/* We hit end of page: skip to next page. */
637 		ff->readdir.cache_off = ALIGN(ff->readdir.cache_off, PAGE_SIZE);
638 		goto retry;
639 	}
640 
641 	/*
642 	 * End of cache reached.  If found position, then we are done, otherwise
643 	 * need to fall back to uncached, since the position we were looking for
644 	 * wasn't in the cache.
645 	 */
646 	return res == FOUND_SOME ? 0 : UNCACHED;
647 }
648 
649 int fuse_readdir(struct file *file, struct dir_context *ctx)
650 {
651 	struct fuse_file *ff = file->private_data;
652 	struct inode *inode = file_inode(file);
653 	int err;
654 
655 	if (fuse_is_bad(inode))
656 		return -EIO;
657 
658 	err = UNCACHED;
659 	if (ff->open_flags & FOPEN_CACHE_DIR)
660 		err = fuse_readdir_cached(file, ctx);
661 	if (err == UNCACHED)
662 		err = fuse_readdir_uncached(file, ctx);
663 
664 	return err;
665 }
666