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