xref: /linux/fs/overlayfs/readdir.c (revision f16d85cd3de9d0c761b74155b4cbe2f20d3dcf80)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *
4  * Copyright (C) 2011 Novell Inc.
5  */
6 
7 #include <linux/fs.h>
8 #include <linux/slab.h>
9 #include <linux/namei.h>
10 #include <linux/file.h>
11 #include <linux/filelock.h>
12 #include <linux/xattr.h>
13 #include <linux/rbtree.h>
14 #include <linux/security.h>
15 #include <linux/cred.h>
16 #include <linux/ratelimit.h>
17 #include <linux/overflow.h>
18 #include "overlayfs.h"
19 
20 struct ovl_cache_entry {
21 	unsigned int len;
22 	unsigned int type;
23 	u64 real_ino;
24 	u64 ino;
25 	struct list_head l_node;
26 	struct rb_node node;
27 	struct ovl_cache_entry *next_maybe_whiteout;
28 	bool is_upper;
29 	bool is_whiteout;
30 	bool check_xwhiteout;
31 	const char *c_name;
32 	int c_len;
33 	char name[];
34 };
35 
36 struct ovl_dir_cache {
37 	long refcount;
38 	u64 version;
39 	bool is_refcounted;
40 	struct list_head entries;
41 	struct rb_root root;
42 };
43 
44 struct ovl_readdir_data {
45 	struct dir_context ctx;
46 	const struct file *user_file;
47 	struct dentry *dentry;
48 	bool is_lowest;
49 	struct rb_root *root;
50 	struct list_head *list;
51 	struct list_head middle;
52 	struct ovl_cache_entry *first_maybe_whiteout;
53 	struct unicode_map *map;
54 	int count;
55 	int err;
56 	bool is_upper;
57 	bool d_type_supported;
58 	bool in_xwhiteouts_dir;
59 };
60 
61 struct ovl_dir_file {
62 	bool is_real;
63 	bool is_upper;
64 	struct ovl_dir_cache *cache;
65 	struct list_head *cursor;
66 	struct file *realfile;
67 	struct file *upperfile;
68 };
69 
70 static struct ovl_cache_entry *ovl_cache_entry_from_node(struct rb_node *n)
71 {
72 	return rb_entry(n, struct ovl_cache_entry, node);
73 }
74 
75 static int ovl_casefold(struct ovl_readdir_data *rdd, const char *str, int len,
76 			char **dst)
77 {
78 	const struct qstr qstr = { .name = str, .len = len };
79 	char *cf_name;
80 	int cf_len;
81 
82 	if (!IS_ENABLED(CONFIG_UNICODE) || !rdd->map ||
83 	    name_is_dot_dotdot(str, len))
84 		return 0;
85 
86 	cf_name = kmalloc(NAME_MAX + 1, GFP_KERNEL);
87 	if (!cf_name) {
88 		rdd->err = -ENOMEM;
89 		return -ENOMEM;
90 	}
91 
92 	cf_len = utf8_casefold(rdd->map, &qstr, cf_name, NAME_MAX + 1);
93 	if (cf_len > 0)
94 		*dst = cf_name;
95 	else
96 		kfree(cf_name);
97 
98 	return cf_len;
99 }
100 
101 static bool ovl_cache_entry_find_link(const char *name, int len,
102 				      struct rb_node ***link,
103 				      struct rb_node **parent)
104 {
105 	bool found = false;
106 	struct rb_node **newp = *link;
107 
108 	while (!found && *newp) {
109 		int cmp;
110 		struct ovl_cache_entry *tmp;
111 
112 		*parent = *newp;
113 		tmp = ovl_cache_entry_from_node(*newp);
114 		cmp = strncmp(name, tmp->c_name, len);
115 		if (cmp > 0)
116 			newp = &tmp->node.rb_right;
117 		else if (cmp < 0 || len < tmp->c_len)
118 			newp = &tmp->node.rb_left;
119 		else
120 			found = true;
121 	}
122 	*link = newp;
123 
124 	return found;
125 }
126 
127 static struct ovl_cache_entry *ovl_cache_entry_find(struct rb_root *root,
128 						    const char *name, int len)
129 {
130 	struct rb_node *node = root->rb_node;
131 	int cmp;
132 
133 	while (node) {
134 		struct ovl_cache_entry *p = ovl_cache_entry_from_node(node);
135 
136 		cmp = strncmp(name, p->c_name, len);
137 		if (cmp > 0)
138 			node = p->node.rb_right;
139 		else if (cmp < 0 || len < p->c_len)
140 			node = p->node.rb_left;
141 		else
142 			return p;
143 	}
144 
145 	return NULL;
146 }
147 
148 static bool ovl_calc_d_ino(struct ovl_readdir_data *rdd,
149 			   struct ovl_cache_entry *p)
150 {
151 	/* Don't care if not doing ovl_iter() */
152 	if (!rdd->dentry)
153 		return false;
154 
155 	/* Always recalc d_ino when remapping lower inode numbers */
156 	if (ovl_xino_bits(OVL_FS(rdd->dentry->d_sb)))
157 		return true;
158 
159 	/* Always recalc d_ino for parent */
160 	if (name_is_dotdot(p->name, p->len))
161 		return true;
162 
163 	/* If this is lower, then native d_ino will do */
164 	if (!rdd->is_upper)
165 		return false;
166 
167 	/*
168 	 * Recalc d_ino for '.' and for all entries if dir is impure (contains
169 	 * copied up entries)
170 	 */
171 	if (name_is_dot(p->name, p->len) ||
172 	    ovl_test_flag(OVL_IMPURE, d_inode(rdd->dentry)))
173 		return true;
174 
175 	return false;
176 }
177 
178 static struct ovl_cache_entry *ovl_cache_entry_new(struct ovl_readdir_data *rdd,
179 						   const char *name, int len,
180 						   const char *c_name, int c_len,
181 						   u64 ino, unsigned int d_type)
182 {
183 	struct ovl_cache_entry *p;
184 
185 	p = kmalloc_flex(*p, name, len + 1);
186 	if (!p)
187 		return NULL;
188 
189 	memcpy(p->name, name, len);
190 	p->name[len] = '\0';
191 	p->len = len;
192 	p->type = d_type;
193 	p->real_ino = ino;
194 	p->ino = ino;
195 	/* Defer setting d_ino for upper entry to ovl_iterate() */
196 	if (ovl_calc_d_ino(rdd, p))
197 		p->ino = 0;
198 	p->is_upper = rdd->is_upper;
199 	p->is_whiteout = false;
200 	/* Defer check for overlay.whiteout to ovl_iterate() */
201 	p->check_xwhiteout = rdd->in_xwhiteouts_dir && d_type == DT_REG;
202 
203 	if (c_name && c_name != name) {
204 		p->c_name = c_name;
205 		p->c_len = c_len;
206 	} else {
207 		p->c_name = p->name;
208 		p->c_len = len;
209 	}
210 
211 	if (d_type == DT_CHR) {
212 		p->next_maybe_whiteout = rdd->first_maybe_whiteout;
213 		rdd->first_maybe_whiteout = p;
214 	}
215 	return p;
216 }
217 
218 /* Return 0 for found, 1 for added, <0 for error */
219 static int ovl_cache_entry_add_rb(struct ovl_readdir_data *rdd,
220 				  const char *name, int len,
221 				  const char *c_name, int c_len,
222 				  u64 ino,
223 				  unsigned int d_type)
224 {
225 	struct rb_node **newp = &rdd->root->rb_node;
226 	struct rb_node *parent = NULL;
227 	struct ovl_cache_entry *p;
228 
229 	if (ovl_cache_entry_find_link(c_name, c_len, &newp, &parent))
230 		return 0;
231 
232 	p = ovl_cache_entry_new(rdd, name, len, c_name, c_len, ino, d_type);
233 	if (p == NULL) {
234 		rdd->err = -ENOMEM;
235 		return -ENOMEM;
236 	}
237 
238 	list_add_tail(&p->l_node, rdd->list);
239 	rb_link_node(&p->node, parent, newp);
240 	rb_insert_color(&p->node, rdd->root);
241 
242 	return 1;
243 }
244 
245 /* Return 0 for found, 1 for added, <0 for error */
246 static int ovl_fill_lowest(struct ovl_readdir_data *rdd,
247 			   const char *name, int namelen,
248 			   const char *c_name, int c_len,
249 			   loff_t offset, u64 ino, unsigned int d_type)
250 {
251 	struct ovl_cache_entry *p;
252 
253 	p = ovl_cache_entry_find(rdd->root, c_name, c_len);
254 	if (p) {
255 		list_move_tail(&p->l_node, &rdd->middle);
256 		return 0;
257 	} else {
258 		p = ovl_cache_entry_new(rdd, name, namelen, c_name, c_len,
259 					ino, d_type);
260 		if (p == NULL)
261 			rdd->err = -ENOMEM;
262 		else
263 			list_add_tail(&p->l_node, &rdd->middle);
264 	}
265 
266 	return rdd->err ?: 1;
267 }
268 
269 static void ovl_cache_entry_free(struct ovl_cache_entry *p)
270 {
271 	if (p->c_name != p->name)
272 		kfree(p->c_name);
273 	kfree(p);
274 }
275 
276 void ovl_cache_free(struct list_head *list)
277 {
278 	struct ovl_cache_entry *p;
279 	struct ovl_cache_entry *n;
280 
281 	list_for_each_entry_safe(p, n, list, l_node)
282 		ovl_cache_entry_free(p);
283 
284 	INIT_LIST_HEAD(list);
285 }
286 
287 void ovl_dir_cache_free(struct inode *inode)
288 {
289 	struct ovl_dir_cache *cache = ovl_dir_cache(inode);
290 
291 	if (cache) {
292 		ovl_cache_free(&cache->entries);
293 		kfree(cache);
294 	}
295 }
296 
297 static void ovl_cache_put(struct ovl_dir_file *od, struct inode *inode)
298 {
299 	struct ovl_dir_cache *cache = od->cache;
300 
301 	WARN_ON(cache->refcount <= 0);
302 	cache->refcount--;
303 	if (!cache->refcount) {
304 		if (ovl_dir_cache(inode) == cache)
305 			ovl_set_dir_cache(inode, NULL);
306 
307 		ovl_cache_free(&cache->entries);
308 		kfree(cache);
309 	}
310 }
311 
312 static bool ovl_fill_merge(struct dir_context *ctx, const char *name,
313 			  int namelen, loff_t offset, u64 ino,
314 			  unsigned int d_type)
315 {
316 	struct ovl_readdir_data *rdd =
317 		container_of(ctx, struct ovl_readdir_data, ctx);
318 	struct ovl_fs *ofs = OVL_FS(rdd->dentry->d_sb);
319 	const char *c_name = NULL;
320 	char *cf_name = NULL;
321 	int c_len = 0, ret;
322 
323 	if (ofs->casefold)
324 		c_len = ovl_casefold(rdd, name, namelen, &cf_name);
325 
326 	if (rdd->err)
327 		return false;
328 
329 	if (c_len <= 0) {
330 		c_name = name;
331 		c_len = namelen;
332 	} else {
333 		c_name = cf_name;
334 	}
335 
336 	rdd->count++;
337 	if (!rdd->is_lowest)
338 		ret = ovl_cache_entry_add_rb(rdd, name, namelen, c_name, c_len, ino, d_type);
339 	else
340 		ret = ovl_fill_lowest(rdd, name, namelen, c_name, c_len, offset, ino, d_type);
341 
342 	/*
343 	 * If ret == 1, that means that c_name is being used as part of struct
344 	 * ovl_cache_entry and will be freed at ovl_cache_free(). Otherwise,
345 	 * c_name was found in the rb-tree so we can free it here.
346 	 */
347 	if (ret != 1 && c_name != name)
348 		kfree(c_name);
349 
350 	return ret >= 0;
351 }
352 
353 static int ovl_check_whiteouts(const struct path *path, struct ovl_readdir_data *rdd)
354 {
355 	struct dentry *dentry, *dir = path->dentry;
356 
357 	while (rdd->first_maybe_whiteout) {
358 		struct ovl_cache_entry *p =
359 			rdd->first_maybe_whiteout;
360 		rdd->first_maybe_whiteout = p->next_maybe_whiteout;
361 		dentry = lookup_one_positive_killable(mnt_idmap(path->mnt),
362 						      &QSTR_LEN(p->name, p->len),
363 						      dir);
364 		if (!IS_ERR(dentry)) {
365 			p->is_whiteout = ovl_is_whiteout(dentry);
366 			dput(dentry);
367 		} else if (PTR_ERR(dentry) == -EINTR) {
368 			return -EINTR;
369 		}
370 	}
371 
372 	return 0;
373 }
374 
375 static inline int ovl_dir_read(const struct path *realpath,
376 			       struct ovl_readdir_data *rdd)
377 {
378 	struct file *realfile;
379 	int err;
380 
381 	realfile = ovl_path_open_realfile(rdd->user_file, realpath,
382 					  O_RDONLY | O_LARGEFILE);
383 	if (IS_ERR(realfile))
384 		return PTR_ERR(realfile);
385 
386 	rdd->first_maybe_whiteout = NULL;
387 	rdd->ctx.pos = 0;
388 	do {
389 		rdd->count = 0;
390 		rdd->err = 0;
391 		err = iterate_dir(realfile, &rdd->ctx);
392 		if (err >= 0)
393 			err = rdd->err;
394 	} while (!err && rdd->count);
395 
396 	if (!err && rdd->first_maybe_whiteout && rdd->dentry)
397 		err = ovl_check_whiteouts(realpath, rdd);
398 
399 	fput(realfile);
400 
401 	return err;
402 }
403 
404 static void ovl_dir_reset(struct file *file)
405 {
406 	struct ovl_dir_file *od = file->private_data;
407 	struct ovl_dir_cache *cache = od->cache;
408 	struct inode *inode = file_inode(file);
409 	bool is_real;
410 
411 	if (cache && ovl_inode_version_get(inode) != cache->version) {
412 		ovl_cache_put(od, inode);
413 		od->cache = NULL;
414 		od->cursor = NULL;
415 	}
416 	is_real = ovl_dir_is_real(inode);
417 	if (od->is_real != is_real) {
418 		/* is_real can only become false when dir is copied up */
419 		if (WARN_ON(is_real))
420 			return;
421 		od->is_real = false;
422 	}
423 }
424 
425 static int ovl_dir_read_merged(struct dentry *dentry, struct list_head *list,
426 	struct rb_root *root, const struct file *user_file)
427 {
428 	int err;
429 	struct path realpath;
430 	struct ovl_readdir_data rdd = {
431 		.ctx.actor = ovl_fill_merge,
432 		.ctx.count = INT_MAX,
433 		.user_file = user_file,
434 		.dentry = dentry,
435 		.list = list,
436 		.root = root,
437 		.is_lowest = false,
438 		.map = NULL,
439 	};
440 	int idx, next;
441 	const struct ovl_layer *layer;
442 	struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
443 
444 	for (idx = 0; idx != -1; idx = next) {
445 		next = ovl_path_next(idx, dentry, &realpath, &layer);
446 
447 		if (ofs->casefold)
448 			rdd.map = sb_encoding(realpath.dentry->d_sb);
449 
450 		rdd.is_upper = ovl_dentry_upper(dentry) == realpath.dentry;
451 		rdd.in_xwhiteouts_dir = layer->has_xwhiteouts &&
452 					ovl_dentry_has_xwhiteouts(dentry);
453 
454 		if (next != -1) {
455 			err = ovl_dir_read(&realpath, &rdd);
456 			if (err)
457 				break;
458 		} else {
459 			/*
460 			 * Insert lowest layer entries before upper ones, this
461 			 * allows offsets to be reasonably constant
462 			 */
463 			list_add(&rdd.middle, rdd.list);
464 			rdd.is_lowest = true;
465 			err = ovl_dir_read(&realpath, &rdd);
466 			list_del(&rdd.middle);
467 		}
468 	}
469 	return err;
470 }
471 
472 static void ovl_seek_cursor(struct ovl_dir_file *od, loff_t pos)
473 {
474 	struct list_head *p;
475 	loff_t off = 0;
476 
477 	list_for_each(p, &od->cache->entries) {
478 		if (off >= pos)
479 			break;
480 		off++;
481 	}
482 	/* Cursor is safe since the cache is stable */
483 	od->cursor = p;
484 }
485 
486 /*
487  * Merged (refcounted) and impure (not refcounted) caches are never
488  * expected to be mixed. On mismatch, detach the cache from the inode
489  * and leak it rather than misuse it. A merged cache is still freed by
490  * its last ovl_cache_put().
491  */
492 static struct ovl_dir_cache *ovl_dir_cache_check(struct inode *inode,
493 						 bool is_refcounted)
494 {
495 	struct ovl_dir_cache *cache = ovl_dir_cache(inode);
496 
497 	if (cache && WARN_ON(cache->is_refcounted != is_refcounted)) {
498 		ovl_set_dir_cache(inode, NULL);
499 		return NULL;
500 	}
501 	return cache;
502 }
503 
504 static struct ovl_dir_cache *ovl_dir_cache_get(struct file *file)
505 {
506 	int res;
507 	struct dentry *dentry = file->f_path.dentry;
508 	struct ovl_dir_cache *cache;
509 	struct inode *inode = d_inode(dentry);
510 
511 	cache = ovl_dir_cache_check(inode, true);
512 	if (cache && ovl_inode_version_get(inode) == cache->version) {
513 		WARN_ON(!cache->refcount);
514 		cache->refcount++;
515 		return cache;
516 	}
517 	ovl_set_dir_cache(d_inode(dentry), NULL);
518 
519 	cache = kzalloc_obj(struct ovl_dir_cache);
520 	if (!cache)
521 		return ERR_PTR(-ENOMEM);
522 
523 	cache->refcount = 1;
524 	cache->is_refcounted = true;
525 	INIT_LIST_HEAD(&cache->entries);
526 	cache->root = RB_ROOT;
527 
528 	res = ovl_dir_read_merged(dentry, &cache->entries, &cache->root, file);
529 	if (res) {
530 		ovl_cache_free(&cache->entries);
531 		kfree(cache);
532 		return ERR_PTR(res);
533 	}
534 
535 	cache->version = ovl_inode_version_get(inode);
536 	ovl_set_dir_cache(inode, cache);
537 
538 	return cache;
539 }
540 
541 /* Map inode number to lower fs unique range */
542 static u64 ovl_remap_lower_ino(u64 ino, int xinobits, int fsid,
543 			       const char *name, int namelen, bool warn)
544 {
545 	unsigned int xinoshift = 64 - xinobits;
546 
547 	if (unlikely(ino >> xinoshift)) {
548 		if (warn) {
549 			pr_warn_ratelimited("d_ino too big (%.*s, ino=%llu, xinobits=%d)\n",
550 					    namelen, name, ino, xinobits);
551 		}
552 		return ino;
553 	}
554 
555 	/*
556 	 * The lowest xinobit is reserved for mapping the non-peresistent inode
557 	 * numbers range, but this range is only exposed via st_ino, not here.
558 	 */
559 	return ino | ((u64)fsid) << (xinoshift + 1);
560 }
561 
562 /*
563  * Set d_ino for upper entries if needed. Non-upper entries should always report
564  * the uppermost real inode ino and should not call this function.
565  *
566  * When not all layer are on same fs, report real ino also for upper.
567  *
568  * When all layers are on the same fs, and upper has a reference to
569  * copy up origin, call vfs_getattr() on the overlay entry to make
570  * sure that d_ino will be consistent with st_ino from stat(2).
571  *
572  * Also checks the overlay.whiteout xattr by doing a full lookup which will return
573  * negative in this case.
574  */
575 static int ovl_cache_update(const struct path *path, struct ovl_cache_entry *p, bool update_ino)
576 
577 {
578 	struct dentry *dir = path->dentry;
579 	struct ovl_fs *ofs = OVL_FS(dir->d_sb);
580 	struct dentry *this = NULL;
581 	enum ovl_path_type type;
582 	u64 ino = p->real_ino;
583 	int xinobits = ovl_xino_bits(ofs);
584 	int err = 0;
585 
586 	if (!ovl_same_dev(ofs) && !p->check_xwhiteout)
587 		goto out;
588 
589 	if (name_is_dot_dotdot(p->name, p->len)) {
590 		if (p->len == 1) {
591 			this = dget(dir);
592 			goto get;
593 		}
594 		if (p->len == 2) {
595 			/* d_splice_alias() can move even a locked dir */
596 			this = dget_parent(dir);
597 			goto get;
598 		}
599 	}
600 	/* This checks also for xwhiteouts */
601 	this = lookup_one(mnt_idmap(path->mnt), &QSTR_LEN(p->name, p->len), dir);
602 	if (IS_ERR_OR_NULL(this) || !this->d_inode) {
603 		/* Mark a stale entry */
604 		p->is_whiteout = true;
605 		if (IS_ERR(this)) {
606 			err = PTR_ERR(this);
607 			this = NULL;
608 			goto fail;
609 		}
610 		goto out;
611 	}
612 
613 get:
614 	if (!ovl_same_dev(ofs) || !update_ino)
615 		goto out;
616 
617 	type = ovl_path_type(this);
618 	if (OVL_TYPE_ORIGIN(type)) {
619 		struct kstat stat;
620 		struct path statpath = *path;
621 
622 		statpath.dentry = this;
623 		err = vfs_getattr(&statpath, &stat, STATX_INO, 0);
624 		if (err)
625 			goto fail;
626 
627 		/*
628 		 * Directory inode is always on overlay st_dev.
629 		 * Non-dir with ovl_same_dev() could be on pseudo st_dev in case
630 		 * of xino bits overflow.
631 		 */
632 		WARN_ON_ONCE(S_ISDIR(stat.mode) &&
633 			     dir->d_sb->s_dev != stat.dev);
634 		ino = stat.ino;
635 	} else if (xinobits && !OVL_TYPE_UPPER(type)) {
636 		ino = ovl_remap_lower_ino(ino, xinobits,
637 					  ovl_layer_lower(this)->fsid,
638 					  p->name, p->len,
639 					  ovl_xino_warn(ofs));
640 	}
641 
642 out:
643 	p->ino = ino;
644 	dput(this);
645 	return err;
646 
647 fail:
648 	pr_warn_ratelimited("failed to look up (%s) for ino (%i)\n",
649 			    p->name, err);
650 	goto out;
651 }
652 
653 static bool ovl_fill_plain(struct dir_context *ctx, const char *name,
654 			  int namelen, loff_t offset, u64 ino,
655 			  unsigned int d_type)
656 {
657 	struct ovl_cache_entry *p;
658 	struct ovl_readdir_data *rdd =
659 		container_of(ctx, struct ovl_readdir_data, ctx);
660 
661 	rdd->count++;
662 	p = ovl_cache_entry_new(rdd, name, namelen, NULL, 0, ino, d_type);
663 	if (p == NULL) {
664 		rdd->err = -ENOMEM;
665 		return false;
666 	}
667 	list_add_tail(&p->l_node, rdd->list);
668 
669 	return true;
670 }
671 
672 static int ovl_dir_read_impure(const struct path *path, struct list_head *list,
673 			       struct rb_root *root, const struct file *user_file)
674 {
675 	int err;
676 	struct path realpath;
677 	struct ovl_cache_entry *p, *n;
678 	struct ovl_readdir_data rdd = {
679 		.ctx.actor = ovl_fill_plain,
680 		.ctx.count = INT_MAX,
681 		.user_file = user_file,
682 		.list = list,
683 		.root = root,
684 	};
685 
686 	INIT_LIST_HEAD(list);
687 	*root = RB_ROOT;
688 	ovl_path_upper(path->dentry, &realpath);
689 
690 	err = ovl_dir_read(&realpath, &rdd);
691 	if (err)
692 		return err;
693 
694 	list_for_each_entry_safe(p, n, list, l_node) {
695 		if (!name_is_dot_dotdot(p->name, p->len)) {
696 			err = ovl_cache_update(path, p, true);
697 			if (err)
698 				return err;
699 		}
700 		if (p->ino == p->real_ino) {
701 			list_del(&p->l_node);
702 			ovl_cache_entry_free(p);
703 		} else {
704 			struct rb_node **newp = &root->rb_node;
705 			struct rb_node *parent = NULL;
706 
707 			if (WARN_ON(ovl_cache_entry_find_link(p->name, p->len,
708 							      &newp, &parent)))
709 				return -EIO;
710 
711 			rb_link_node(&p->node, parent, newp);
712 			rb_insert_color(&p->node, root);
713 		}
714 	}
715 	return 0;
716 }
717 
718 static struct ovl_dir_cache *ovl_cache_get_impure(struct file *file)
719 {
720 	int res;
721 	const struct path *path = &file->f_path;
722 	struct dentry *dentry = path->dentry;
723 	struct inode *inode = d_inode(dentry);
724 	struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
725 	struct ovl_dir_cache *cache;
726 
727 	cache = ovl_dir_cache_check(inode, false);
728 	if (cache && ovl_inode_version_get(inode) == cache->version)
729 		return cache;
730 
731 	/* Impure cache is not refcounted, free it here */
732 	ovl_dir_cache_free(inode);
733 	ovl_set_dir_cache(inode, NULL);
734 
735 	cache = kzalloc_obj(struct ovl_dir_cache);
736 	if (!cache)
737 		return ERR_PTR(-ENOMEM);
738 
739 	cache->is_refcounted = false;
740 	res = ovl_dir_read_impure(path, &cache->entries, &cache->root, file);
741 	if (res) {
742 		ovl_cache_free(&cache->entries);
743 		kfree(cache);
744 		return ERR_PTR(res);
745 	}
746 	if (list_empty(&cache->entries)) {
747 		/*
748 		 * A good opportunity to get rid of an unneeded "impure" flag.
749 		 * Removing the "impure" xattr is best effort.
750 		 */
751 		if (!ovl_want_write(dentry)) {
752 			ovl_removexattr(ofs, ovl_dentry_upper(dentry),
753 					OVL_XATTR_IMPURE);
754 			ovl_drop_write(dentry);
755 		}
756 		ovl_clear_flag(OVL_IMPURE, inode);
757 		kfree(cache);
758 		return NULL;
759 	}
760 
761 	cache->version = ovl_inode_version_get(inode);
762 	ovl_set_dir_cache(inode, cache);
763 
764 	return cache;
765 }
766 
767 struct ovl_readdir_translate {
768 	struct dir_context *orig_ctx;
769 	struct ovl_dir_cache *cache;
770 	struct dir_context ctx;
771 	u64 parent_ino;
772 	int fsid;
773 	int xinobits;
774 	bool xinowarn;
775 };
776 
777 static bool ovl_fill_real(struct dir_context *ctx, const char *name,
778 			   int namelen, loff_t offset, u64 ino,
779 			   unsigned int d_type)
780 {
781 	struct ovl_readdir_translate *rdt =
782 		container_of(ctx, struct ovl_readdir_translate, ctx);
783 	struct dir_context *orig_ctx = rdt->orig_ctx;
784 	bool res;
785 
786 	if (rdt->parent_ino && name_is_dotdot(name, namelen)) {
787 		ino = rdt->parent_ino;
788 	} else if (rdt->cache) {
789 		struct ovl_cache_entry *p;
790 
791 		p = ovl_cache_entry_find(&rdt->cache->root, name, namelen);
792 		if (p)
793 			ino = p->ino;
794 	} else if (rdt->xinobits) {
795 		ino = ovl_remap_lower_ino(ino, rdt->xinobits, rdt->fsid,
796 					  name, namelen, rdt->xinowarn);
797 	}
798 
799 	res = orig_ctx->actor(orig_ctx, name, namelen, offset, ino, d_type);
800 	ctx->count = orig_ctx->count;
801 
802 	return res;
803 }
804 
805 static bool ovl_is_impure_dir(struct file *file)
806 {
807 	struct ovl_dir_file *od = file->private_data;
808 	struct inode *dir = file_inode(file);
809 
810 	/*
811 	 * Only upper dir can be impure, but if we are in the middle of
812 	 * iterating a lower real dir, dir could be copied up and marked
813 	 * impure. We only want the impure cache if we started iterating
814 	 * a real upper dir to begin with.
815 	 */
816 	return od->is_upper && ovl_test_flag(OVL_IMPURE, dir);
817 
818 }
819 
820 static int ovl_iterate_real(struct file *file, struct dir_context *ctx)
821 {
822 	int err;
823 	struct ovl_dir_file *od = file->private_data;
824 	struct dentry *dir = file->f_path.dentry;
825 	struct ovl_fs *ofs = OVL_FS(dir->d_sb);
826 	const struct ovl_layer *lower_layer = ovl_layer_lower(dir);
827 	struct dentry *parent;
828 	struct ovl_readdir_translate rdt = {
829 		.ctx.actor = ovl_fill_real,
830 		.ctx.count = ctx->count,
831 		.orig_ctx = ctx,
832 		.xinobits = ovl_xino_bits(ofs),
833 		.xinowarn = ovl_xino_warn(ofs),
834 	};
835 
836 	if (rdt.xinobits && lower_layer)
837 		rdt.fsid = lower_layer->fsid;
838 
839 	/*
840 	 * The lock on dir does not stop d_splice_alias() from moving it to
841 	 * another parent, which drops the reference dir holds on this one.
842 	 */
843 	parent = dget_parent(dir);
844 	if (OVL_TYPE_MERGE(ovl_path_type(parent))) {
845 		struct kstat stat;
846 		struct path statpath = file->f_path;
847 
848 		statpath.dentry = parent;
849 		err = vfs_getattr(&statpath, &stat, STATX_INO, 0);
850 		if (err) {
851 			dput(parent);
852 			return err;
853 		}
854 
855 		WARN_ON_ONCE(dir->d_sb->s_dev != stat.dev);
856 		rdt.parent_ino = stat.ino;
857 	}
858 	dput(parent);
859 
860 	if (ovl_is_impure_dir(file)) {
861 		rdt.cache = ovl_cache_get_impure(file);
862 		if (IS_ERR(rdt.cache))
863 			return PTR_ERR(rdt.cache);
864 	}
865 
866 	err = iterate_dir(od->realfile, &rdt.ctx);
867 	ctx->pos = rdt.ctx.pos;
868 
869 	return err;
870 }
871 
872 static int ovl_iterate_merged(struct file *file, struct dir_context *ctx)
873 {
874 	struct ovl_dir_file *od = file->private_data;
875 	struct ovl_cache_entry *p;
876 	int err;
877 
878 	if (!od->cache) {
879 		struct ovl_dir_cache *cache;
880 
881 		cache = ovl_dir_cache_get(file);
882 		if (IS_ERR(cache))
883 			return PTR_ERR(cache);
884 
885 		od->cache = cache;
886 		ovl_seek_cursor(od, ctx->pos);
887 	}
888 
889 	while (od->cursor != &od->cache->entries) {
890 		p = list_entry(od->cursor, struct ovl_cache_entry, l_node);
891 		if (!p->is_whiteout) {
892 			if (!p->ino || p->check_xwhiteout) {
893 				err = ovl_cache_update(&file->f_path, p, !p->ino);
894 				if (err)
895 					return err;
896 			}
897 		}
898 		/* ovl_cache_update() sets is_whiteout on stale entry */
899 		if (!p->is_whiteout) {
900 			if (!dir_emit(ctx, p->name, p->len, p->ino, p->type))
901 				break;
902 		}
903 		od->cursor = p->l_node.next;
904 		ctx->pos++;
905 	}
906 	return 0;
907 }
908 
909 static bool ovl_need_adjust_d_ino(struct file *file)
910 {
911 	struct dentry *dentry = file->f_path.dentry;
912 	struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
913 	struct dentry *parent;
914 	enum ovl_path_type type;
915 
916 	/* With xino, need to map real d_ino to the unified overlay ino space */
917 	if (ovl_xino_bits(ofs))
918 		return true;
919 
920 	/* Can't do consistent inode numbering */
921 	if (!ovl_same_fs(ofs))
922 		return false;
923 
924 	/* If dir is impure then need to adjust d_ino for copied up entries */
925 	if (ovl_is_impure_dir(file))
926 		return true;
927 
928 	/* If parent is merge, then need to adjust d_ino for '..' */
929 	parent = dget_parent(dentry);
930 	type = ovl_path_type(parent);
931 	dput(parent);
932 	if (OVL_TYPE_MERGE(type))
933 		return true;
934 
935 	/* Pure: no need to adjust d_ino */
936 	return false;
937 }
938 
939 
940 static int ovl_iterate(struct file *file, struct dir_context *ctx)
941 {
942 	struct ovl_dir_file *od = file->private_data;
943 
944 	if (!ctx->pos)
945 		ovl_dir_reset(file);
946 
947 	with_ovl_creds(file_dentry(file)->d_sb) {
948 		if (!od->is_real)
949 			return ovl_iterate_merged(file, ctx);
950 
951 		if (ovl_need_adjust_d_ino(file))
952 			return ovl_iterate_real(file, ctx);
953 
954 		return iterate_dir(od->realfile, ctx);
955 	}
956 }
957 
958 static loff_t ovl_dir_llseek(struct file *file, loff_t offset, int origin)
959 {
960 	loff_t res;
961 	struct ovl_dir_file *od = file->private_data;
962 
963 	inode_lock(file_inode(file));
964 	if (!file->f_pos)
965 		ovl_dir_reset(file);
966 
967 	if (od->is_real) {
968 		res = vfs_llseek(od->realfile, offset, origin);
969 		file->f_pos = od->realfile->f_pos;
970 	} else {
971 		res = -EINVAL;
972 
973 		switch (origin) {
974 		case SEEK_CUR:
975 			offset += file->f_pos;
976 			break;
977 		case SEEK_SET:
978 			break;
979 		default:
980 			goto out_unlock;
981 		}
982 		if (offset < 0)
983 			goto out_unlock;
984 
985 		if (offset != file->f_pos) {
986 			file->f_pos = offset;
987 			if (od->cache)
988 				ovl_seek_cursor(od, offset);
989 		}
990 		res = offset;
991 	}
992 out_unlock:
993 	inode_unlock(file_inode(file));
994 
995 	return res;
996 }
997 
998 static struct file *ovl_dir_open_realfile(const struct file *file,
999 					  const struct path *realpath)
1000 {
1001 	with_ovl_creds(file_inode(file)->i_sb)
1002 		return ovl_path_open_realfile(file, realpath,
1003 					      O_RDONLY | (file->f_flags & O_LARGEFILE));
1004 }
1005 
1006 /*
1007  * Like ovl_real_fdget(), returns upperfile if dir was copied up since open.
1008  * Unlike ovl_real_fdget(), this caches upperfile in file->private_data.
1009  *
1010  * TODO: use same abstract type for file->private_data of dir and file so
1011  * upperfile could also be cached for files as well.
1012  */
1013 struct file *ovl_dir_real_file(const struct file *file, bool want_upper)
1014 {
1015 
1016 	struct ovl_dir_file *od = file->private_data;
1017 	struct dentry *dentry = file->f_path.dentry;
1018 	struct file *old, *realfile = od->realfile;
1019 
1020 	if (!OVL_TYPE_UPPER(ovl_path_type(dentry)))
1021 		return want_upper ? NULL : realfile;
1022 
1023 	/*
1024 	 * Need to check if we started out being a lower dir, but got copied up
1025 	 */
1026 	if (!od->is_upper) {
1027 		realfile = READ_ONCE(od->upperfile);
1028 		if (!realfile) {
1029 			struct path upperpath;
1030 
1031 			ovl_path_upper(dentry, &upperpath);
1032 			realfile = ovl_dir_open_realfile(file, &upperpath);
1033 			if (IS_ERR(realfile))
1034 				return realfile;
1035 
1036 			old = cmpxchg_release(&od->upperfile, NULL, realfile);
1037 			if (old) {
1038 				fput(realfile);
1039 				realfile = old;
1040 			}
1041 		}
1042 	}
1043 
1044 	return realfile;
1045 }
1046 
1047 static int ovl_dir_fsync(struct file *file, loff_t start, loff_t end,
1048 			 int datasync)
1049 {
1050 	struct file *realfile;
1051 	int err;
1052 
1053 	err = ovl_sync_status(OVL_FS(file_inode(file)->i_sb));
1054 	if (err <= 0)
1055 		return err;
1056 
1057 	realfile = ovl_dir_real_file(file, true);
1058 	err = PTR_ERR_OR_ZERO(realfile);
1059 
1060 	/* Nothing to sync for lower */
1061 	if (!realfile || err)
1062 		return err;
1063 
1064 	return vfs_fsync_range(realfile, start, end, datasync);
1065 }
1066 
1067 static int ovl_dir_release(struct inode *inode, struct file *file)
1068 {
1069 	struct ovl_dir_file *od = file->private_data;
1070 
1071 	if (od->cache) {
1072 		inode_lock(inode);
1073 		ovl_cache_put(od, inode);
1074 		inode_unlock(inode);
1075 	}
1076 	fput(od->realfile);
1077 	if (od->upperfile)
1078 		fput(od->upperfile);
1079 	kfree(od);
1080 
1081 	return 0;
1082 }
1083 
1084 static int ovl_dir_open(struct inode *inode, struct file *file)
1085 {
1086 	struct path realpath;
1087 	struct file *realfile;
1088 	struct ovl_dir_file *od;
1089 	enum ovl_path_type type;
1090 
1091 	od = kzalloc_obj(struct ovl_dir_file);
1092 	if (!od)
1093 		return -ENOMEM;
1094 
1095 	type = ovl_path_real(file->f_path.dentry, &realpath);
1096 	realfile = ovl_dir_open_realfile(file, &realpath);
1097 	if (IS_ERR(realfile)) {
1098 		kfree(od);
1099 		return PTR_ERR(realfile);
1100 	}
1101 	od->realfile = realfile;
1102 	od->is_real = !OVL_TYPE_MERGE(type) &&
1103 		      !ovl_test_flag(OVL_WHITEOUTS, inode);
1104 	od->is_upper = OVL_TYPE_UPPER(type);
1105 	file->private_data = od;
1106 
1107 	return 0;
1108 }
1109 
1110 WRAP_DIR_ITER(ovl_iterate) // FIXME!
1111 const struct file_operations ovl_dir_operations = {
1112 	.read		= generic_read_dir,
1113 	.open		= ovl_dir_open,
1114 	.iterate_shared	= shared_ovl_iterate,
1115 	.llseek		= ovl_dir_llseek,
1116 	.fsync		= ovl_dir_fsync,
1117 	.release	= ovl_dir_release,
1118 	.setlease	= generic_setlease,
1119 };
1120 
1121 int ovl_check_empty_dir(struct dentry *dentry, struct list_head *list)
1122 {
1123 	int err;
1124 	struct ovl_cache_entry *p, *n;
1125 	struct rb_root root = RB_ROOT;
1126 
1127 	with_ovl_creds(dentry->d_sb)
1128 		err = ovl_dir_read_merged(dentry, list, &root, NULL);
1129 	if (err)
1130 		return err;
1131 
1132 	err = 0;
1133 
1134 	list_for_each_entry_safe(p, n, list, l_node) {
1135 		/*
1136 		 * Select whiteouts in upperdir, they should
1137 		 * be cleared when deleting this directory.
1138 		 */
1139 		if (p->is_whiteout) {
1140 			if (p->is_upper)
1141 				continue;
1142 			goto del_entry;
1143 		}
1144 
1145 		if (name_is_dot_dotdot(p->name, p->len))
1146 			goto del_entry;
1147 		err = -ENOTEMPTY;
1148 		break;
1149 
1150 del_entry:
1151 		list_del(&p->l_node);
1152 		ovl_cache_entry_free(p);
1153 	}
1154 
1155 	return err;
1156 }
1157 
1158 void ovl_cleanup_whiteouts(struct ovl_fs *ofs, struct dentry *upper,
1159 			   struct list_head *list)
1160 {
1161 	struct ovl_cache_entry *p;
1162 
1163 	list_for_each_entry(p, list, l_node) {
1164 		struct dentry *dentry;
1165 
1166 		if (WARN_ON(!p->is_whiteout || !p->is_upper))
1167 			continue;
1168 
1169 		dentry = ovl_lookup_upper_unlocked(ofs, p->name, upper, p->len);
1170 		if (IS_ERR(dentry)) {
1171 			pr_err("lookup '%s/%.*s' failed (%i)\n",
1172 			       upper->d_name.name, p->len, p->name,
1173 			       (int) PTR_ERR(dentry));
1174 			continue;
1175 		}
1176 		if (dentry->d_inode)
1177 			ovl_cleanup(ofs, upper, dentry);
1178 		dput(dentry);
1179 	}
1180 }
1181 
1182 static bool ovl_check_d_type(struct dir_context *ctx, const char *name,
1183 			  int namelen, loff_t offset, u64 ino,
1184 			  unsigned int d_type)
1185 {
1186 	struct ovl_readdir_data *rdd =
1187 		container_of(ctx, struct ovl_readdir_data, ctx);
1188 
1189 	/* Even if d_type is not supported, DT_DIR is returned for . and .. */
1190 	if (name_is_dot_dotdot(name, namelen))
1191 		return true;
1192 
1193 	if (d_type != DT_UNKNOWN)
1194 		rdd->d_type_supported = true;
1195 
1196 	return true;
1197 }
1198 
1199 /*
1200  * Returns 1 if d_type is supported, 0 not supported/unknown. Negative values
1201  * if error is encountered.
1202  */
1203 int ovl_check_d_type_supported(const struct path *realpath)
1204 {
1205 	int err;
1206 	struct ovl_readdir_data rdd = {
1207 		.ctx.actor = ovl_check_d_type,
1208 		.ctx.count = INT_MAX,
1209 		.d_type_supported = false,
1210 	};
1211 
1212 	err = ovl_dir_read(realpath, &rdd);
1213 	if (err)
1214 		return err;
1215 
1216 	return rdd.d_type_supported;
1217 }
1218 
1219 #define OVL_INCOMPATDIR_NAME "incompat"
1220 
1221 static int ovl_workdir_cleanup_recurse(struct ovl_fs *ofs, const struct path *path,
1222 				       int level)
1223 {
1224 	int err;
1225 	LIST_HEAD(list);
1226 	struct ovl_cache_entry *p;
1227 	struct ovl_readdir_data rdd = {
1228 		.ctx.actor = ovl_fill_plain,
1229 		.ctx.count = INT_MAX,
1230 		.list = &list,
1231 	};
1232 	bool incompat = false;
1233 
1234 	/*
1235 	 * The "work/incompat" directory is treated specially - if it is not
1236 	 * empty, instead of printing a generic error and mounting read-only,
1237 	 * we will error about incompat features and fail the mount.
1238 	 *
1239 	 * When called from ovl_indexdir_cleanup(), path->dentry->d_name.name
1240 	 * starts with '#'.
1241 	 */
1242 	if (level == 2 &&
1243 	    !strcmp(path->dentry->d_name.name, OVL_INCOMPATDIR_NAME))
1244 		incompat = true;
1245 
1246 	err = ovl_dir_read(path, &rdd);
1247 	if (err)
1248 		goto out;
1249 
1250 	list_for_each_entry(p, &list, l_node) {
1251 		struct dentry *dentry;
1252 
1253 		if (name_is_dot_dotdot(p->name, p->len)) {
1254 			continue;
1255 		} else if (incompat) {
1256 			pr_err("overlay with incompat feature '%s' cannot be mounted\n",
1257 				p->name);
1258 			err = -EINVAL;
1259 			break;
1260 		}
1261 		dentry = ovl_lookup_upper_unlocked(ofs, p->name, path->dentry, p->len);
1262 		if (IS_ERR(dentry))
1263 			continue;
1264 		if (dentry->d_inode)
1265 			err = ovl_workdir_cleanup(ofs, path->dentry, path->mnt,
1266 						  dentry, level);
1267 		dput(dentry);
1268 		if (err)
1269 			break;
1270 	}
1271 out:
1272 	ovl_cache_free(&list);
1273 	return err;
1274 }
1275 
1276 int ovl_workdir_cleanup(struct ovl_fs *ofs, struct dentry *parent,
1277 			struct vfsmount *mnt, struct dentry *dentry, int level)
1278 {
1279 	int err;
1280 
1281 	if (!d_is_dir(dentry) || level > 1)
1282 		return ovl_cleanup(ofs, parent, dentry);
1283 
1284 	dentry = start_removing_dentry(parent, dentry);
1285 	if (IS_ERR(dentry))
1286 		return PTR_ERR(dentry);
1287 	err = ovl_do_rmdir(ofs, parent->d_inode, dentry);
1288 	end_removing(dentry);
1289 	if (err) {
1290 		struct path path = { .mnt = mnt, .dentry = dentry };
1291 
1292 		err = ovl_workdir_cleanup_recurse(ofs, &path, level + 1);
1293 		if (!err)
1294 			err = ovl_cleanup(ofs, parent, dentry);
1295 	}
1296 
1297 	return err;
1298 }
1299 
1300 int ovl_indexdir_cleanup(struct ovl_fs *ofs)
1301 {
1302 	int err;
1303 	struct dentry *indexdir = ofs->workdir;
1304 	struct dentry *index = NULL;
1305 	struct path path = { .mnt = ovl_upper_mnt(ofs), .dentry = indexdir };
1306 	LIST_HEAD(list);
1307 	struct ovl_cache_entry *p;
1308 	struct ovl_readdir_data rdd = {
1309 		.ctx.actor = ovl_fill_plain,
1310 		.ctx.count = INT_MAX,
1311 		.list = &list,
1312 	};
1313 
1314 	err = ovl_dir_read(&path, &rdd);
1315 	if (err)
1316 		goto out;
1317 
1318 	list_for_each_entry(p, &list, l_node) {
1319 		if (name_is_dot_dotdot(p->name, p->len))
1320 			continue;
1321 		index = ovl_lookup_upper_unlocked(ofs, p->name, indexdir, p->len);
1322 		if (IS_ERR(index)) {
1323 			err = PTR_ERR(index);
1324 			index = NULL;
1325 			break;
1326 		}
1327 		/* Cleanup leftover from index create/cleanup attempt */
1328 		if (index->d_name.name[0] == '#') {
1329 			err = ovl_workdir_cleanup(ofs, indexdir, path.mnt, index, 1);
1330 			if (err)
1331 				break;
1332 			goto next;
1333 		}
1334 		err = ovl_verify_index(ofs, index);
1335 		if (!err) {
1336 			goto next;
1337 		} else if (err == -ESTALE) {
1338 			/* Cleanup stale index entries */
1339 			err = ovl_cleanup(ofs, indexdir, index);
1340 		} else if (err != -ENOENT) {
1341 			/*
1342 			 * Abort mount to avoid corrupting the index if
1343 			 * an incompatible index entry was found or on out
1344 			 * of memory.
1345 			 */
1346 			break;
1347 		} else if (ofs->config.nfs_export) {
1348 			/*
1349 			 * Whiteout orphan index to block future open by
1350 			 * handle after overlay nlink dropped to zero.
1351 			 */
1352 			err = ovl_cleanup_and_whiteout(ofs, indexdir, index,
1353 						       &QSTR_LEN(p->name, p->len));
1354 		} else {
1355 			/* Cleanup orphan index entries */
1356 			err = ovl_cleanup(ofs, indexdir, index);
1357 		}
1358 
1359 		if (err)
1360 			break;
1361 
1362 next:
1363 		dput(index);
1364 		index = NULL;
1365 	}
1366 	dput(index);
1367 out:
1368 	ovl_cache_free(&list);
1369 	if (err)
1370 		pr_err("failed index dir cleanup (%i)\n", err);
1371 	return err;
1372 }
1373