xref: /linux/fs/overlayfs/util.c (revision 323899b4ed233d5b6e2fc160c16fbf39cf0317da)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2011 Novell Inc.
4  * Copyright (C) 2016 Red Hat, Inc.
5  */
6 
7 #include <linux/fs.h>
8 #include <linux/mount.h>
9 #include <linux/slab.h>
10 #include <linux/cred.h>
11 #include <linux/xattr.h>
12 #include <linux/exportfs.h>
13 #include <linux/file.h>
14 #include <linux/fileattr.h>
15 #include <linux/uuid.h>
16 #include <linux/namei.h>
17 #include <linux/ratelimit.h>
18 #include <linux/overflow.h>
19 #include "overlayfs.h"
20 
21 /* Get write access to upper mnt - may fail if upper sb was remounted ro */
22 int ovl_get_write_access(struct dentry *dentry)
23 {
24 	struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
25 	return mnt_get_write_access(ovl_upper_mnt(ofs));
26 }
27 
28 /* Get write access to upper sb - may block if upper sb is frozen */
29 void ovl_start_write(struct dentry *dentry)
30 {
31 	struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
32 	sb_start_write(ovl_upper_mnt(ofs)->mnt_sb);
33 }
34 
35 int ovl_want_write(struct dentry *dentry)
36 {
37 	struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
38 	return mnt_want_write(ovl_upper_mnt(ofs));
39 }
40 
41 void ovl_put_write_access(struct dentry *dentry)
42 {
43 	struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
44 	mnt_put_write_access(ovl_upper_mnt(ofs));
45 }
46 
47 void ovl_end_write(struct dentry *dentry)
48 {
49 	struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
50 	sb_end_write(ovl_upper_mnt(ofs)->mnt_sb);
51 }
52 
53 void ovl_drop_write(struct dentry *dentry)
54 {
55 	struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
56 	mnt_drop_write(ovl_upper_mnt(ofs));
57 }
58 
59 struct dentry *ovl_workdir(struct dentry *dentry)
60 {
61 	struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
62 	return ofs->workdir;
63 }
64 
65 const struct cred *ovl_override_creds(struct super_block *sb)
66 {
67 	struct ovl_fs *ofs = OVL_FS(sb);
68 
69 	return override_creds(ofs->creator_cred);
70 }
71 
72 /*
73  * Check if underlying fs supports file handles and try to determine encoding
74  * type, in order to deduce maximum inode number used by fs.
75  *
76  * Return 0 if file handles are not supported.
77  * Return 1 (FILEID_INO32_GEN) if fs uses the default 32bit inode encoding.
78  * Return -1 if fs uses a non default encoding with unknown inode size.
79  */
80 int ovl_can_decode_fh(struct super_block *sb)
81 {
82 	if (!capable(CAP_DAC_READ_SEARCH))
83 		return 0;
84 
85 	if (!exportfs_can_decode_fh(sb->s_export_op))
86 		return 0;
87 
88 	if (sb->s_export_op->encode_fh == generic_encode_ino32_fh)
89 		return FILEID_INO32_GEN;
90 
91 	return -1;
92 }
93 
94 struct dentry *ovl_indexdir(struct super_block *sb)
95 {
96 	struct ovl_fs *ofs = OVL_FS(sb);
97 
98 	return ofs->config.index ? ofs->workdir : NULL;
99 }
100 
101 /* Index all files on copy up. For now only enabled for NFS export */
102 bool ovl_index_all(struct super_block *sb)
103 {
104 	struct ovl_fs *ofs = OVL_FS(sb);
105 
106 	return ofs->config.nfs_export && ofs->config.index;
107 }
108 
109 /* Verify lower origin on lookup. For now only enabled for NFS export */
110 bool ovl_verify_lower(struct super_block *sb)
111 {
112 	struct ovl_fs *ofs = OVL_FS(sb);
113 
114 	return ofs->config.nfs_export && ofs->config.index;
115 }
116 
117 struct ovl_path *ovl_stack_alloc(unsigned int n)
118 {
119 	return kzalloc_objs(struct ovl_path, n);
120 }
121 
122 void ovl_stack_cpy(struct ovl_path *dst, struct ovl_path *src, unsigned int n)
123 {
124 	unsigned int i;
125 
126 	memcpy(dst, src, sizeof(struct ovl_path) * n);
127 	for (i = 0; i < n; i++)
128 		dget(src[i].dentry);
129 }
130 
131 void ovl_stack_put(struct ovl_path *stack, unsigned int n)
132 {
133 	unsigned int i;
134 
135 	for (i = 0; stack && i < n; i++)
136 		dput(stack[i].dentry);
137 }
138 
139 void ovl_stack_free(struct ovl_path *stack, unsigned int n)
140 {
141 	ovl_stack_put(stack, n);
142 	kfree(stack);
143 }
144 
145 struct ovl_entry *ovl_alloc_entry(unsigned int numlower)
146 {
147 	struct ovl_entry *oe;
148 
149 	oe = kzalloc_flex(*oe, __lowerstack, numlower);
150 	if (oe)
151 		oe->__numlower = numlower;
152 
153 	return oe;
154 }
155 
156 void ovl_free_entry(struct ovl_entry *oe)
157 {
158 	ovl_stack_put(ovl_lowerstack(oe), ovl_numlower(oe));
159 	kfree(oe);
160 }
161 
162 #define OVL_D_REVALIDATE (DCACHE_OP_REVALIDATE | DCACHE_OP_WEAK_REVALIDATE)
163 
164 bool ovl_dentry_remote(struct dentry *dentry)
165 {
166 	return dentry->d_flags & OVL_D_REVALIDATE;
167 }
168 
169 void ovl_dentry_update_reval(struct dentry *dentry, struct dentry *realdentry)
170 {
171 	if (!ovl_dentry_remote(realdentry))
172 		return;
173 
174 	spin_lock(&dentry->d_lock);
175 	dentry->d_flags |= realdentry->d_flags & OVL_D_REVALIDATE;
176 	spin_unlock(&dentry->d_lock);
177 }
178 
179 void ovl_dentry_init_reval(struct dentry *dentry, struct dentry *upperdentry,
180 			   struct ovl_entry *oe)
181 {
182 	return ovl_dentry_init_flags(dentry, upperdentry, oe, OVL_D_REVALIDATE);
183 }
184 
185 void ovl_dentry_init_flags(struct dentry *dentry, struct dentry *upperdentry,
186 			   struct ovl_entry *oe, unsigned int mask)
187 {
188 	struct ovl_path *lowerstack = ovl_lowerstack(oe);
189 	unsigned int i, flags = 0;
190 
191 	if (upperdentry)
192 		flags |= upperdentry->d_flags;
193 	for (i = 0; i < ovl_numlower(oe) && lowerstack[i].dentry; i++)
194 		flags |= lowerstack[i].dentry->d_flags;
195 
196 	spin_lock(&dentry->d_lock);
197 	dentry->d_flags &= ~mask;
198 	dentry->d_flags |= flags & mask;
199 	spin_unlock(&dentry->d_lock);
200 }
201 
202 bool ovl_dentry_weird(struct dentry *dentry)
203 {
204 	if (!d_can_lookup(dentry) && !d_is_file(dentry) && !d_is_symlink(dentry))
205 		return true;
206 
207 	if (dentry->d_flags & (DCACHE_NEED_AUTOMOUNT | DCACHE_MANAGE_TRANSIT))
208 		return true;
209 
210 	/*
211 	 * Exceptionally for layers with casefold, we accept that they have
212 	 * their own hash and compare operations
213 	 */
214 	if (sb_has_encoding(dentry->d_sb))
215 		return false;
216 
217 	return dentry->d_flags & (DCACHE_OP_HASH | DCACHE_OP_COMPARE);
218 }
219 
220 enum ovl_path_type ovl_path_type(struct dentry *dentry)
221 {
222 	struct ovl_entry *oe = OVL_E(dentry);
223 	enum ovl_path_type type = 0;
224 
225 	if (ovl_dentry_upper(dentry)) {
226 		type = __OVL_PATH_UPPER;
227 
228 		/*
229 		 * Non-dir dentry can hold lower dentry of its copy up origin.
230 		 */
231 		if (ovl_numlower(oe)) {
232 			if (ovl_test_flag(OVL_CONST_INO, d_inode(dentry)))
233 				type |= __OVL_PATH_ORIGIN;
234 			if (d_is_dir(dentry) ||
235 			    !ovl_has_upperdata(d_inode(dentry)))
236 				type |= __OVL_PATH_MERGE;
237 		}
238 	} else {
239 		if (ovl_numlower(oe) > 1)
240 			type |= __OVL_PATH_MERGE;
241 	}
242 	return type;
243 }
244 
245 void ovl_path_upper(struct dentry *dentry, struct path *path)
246 {
247 	struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
248 
249 	path->mnt = ovl_upper_mnt(ofs);
250 	path->dentry = ovl_dentry_upper(dentry);
251 }
252 
253 void ovl_path_lower(struct dentry *dentry, struct path *path)
254 {
255 	struct ovl_entry *oe = OVL_E(dentry);
256 	struct ovl_path *lowerpath = ovl_lowerstack(oe);
257 
258 	if (ovl_numlower(oe)) {
259 		path->mnt = lowerpath->layer->mnt;
260 		path->dentry = lowerpath->dentry;
261 	} else {
262 		*path = (struct path) { };
263 	}
264 }
265 
266 void ovl_path_lowerdata(struct dentry *dentry, struct path *path)
267 {
268 	struct ovl_entry *oe = OVL_E(dentry);
269 	struct ovl_path *lowerdata = ovl_lowerdata(oe);
270 	struct dentry *lowerdata_dentry = ovl_lowerdata_dentry(oe);
271 
272 	if (lowerdata_dentry) {
273 		path->dentry = lowerdata_dentry;
274 		/*
275 		 * Pairs with smp_wmb() in ovl_dentry_set_lowerdata().
276 		 * Make sure that if lowerdata->dentry is visible, then
277 		 * datapath->layer is visible as well.
278 		 */
279 		smp_rmb();
280 		path->mnt = READ_ONCE(lowerdata->layer)->mnt;
281 	} else {
282 		*path = (struct path) { };
283 	}
284 }
285 
286 enum ovl_path_type ovl_path_real(struct dentry *dentry, struct path *path)
287 {
288 	enum ovl_path_type type = ovl_path_type(dentry);
289 
290 	if (!OVL_TYPE_UPPER(type))
291 		ovl_path_lower(dentry, path);
292 	else
293 		ovl_path_upper(dentry, path);
294 
295 	return type;
296 }
297 
298 enum ovl_path_type ovl_path_realdata(struct dentry *dentry, struct path *path)
299 {
300 	enum ovl_path_type type = ovl_path_type(dentry);
301 
302 	WARN_ON_ONCE(d_is_dir(dentry));
303 
304 	if (!OVL_TYPE_UPPER(type) || OVL_TYPE_MERGE(type))
305 		ovl_path_lowerdata(dentry, path);
306 	else
307 		ovl_path_upper(dentry, path);
308 
309 	return type;
310 }
311 
312 struct dentry *ovl_dentry_upper(struct dentry *dentry)
313 {
314 	struct inode *inode = d_inode(dentry);
315 
316 	return inode ? ovl_upperdentry_dereference(OVL_I(inode)) : NULL;
317 }
318 
319 struct dentry *ovl_dentry_lower(struct dentry *dentry)
320 {
321 	struct ovl_entry *oe = OVL_E(dentry);
322 
323 	return ovl_numlower(oe) ? ovl_lowerstack(oe)->dentry : NULL;
324 }
325 
326 const struct ovl_layer *ovl_layer_lower(struct dentry *dentry)
327 {
328 	struct ovl_entry *oe = OVL_E(dentry);
329 
330 	return ovl_numlower(oe) ? ovl_lowerstack(oe)->layer : NULL;
331 }
332 
333 /*
334  * ovl_dentry_lower() could return either a data dentry or metacopy dentry
335  * depending on what is stored in lowerstack[0]. At times we need to find
336  * lower dentry which has data (and not metacopy dentry). This helper
337  * returns the lower data dentry.
338  */
339 struct dentry *ovl_dentry_lowerdata(struct dentry *dentry)
340 {
341 	return ovl_lowerdata_dentry(OVL_E(dentry));
342 }
343 
344 int ovl_dentry_set_lowerdata(struct dentry *dentry, struct ovl_path *datapath)
345 {
346 	struct ovl_entry *oe = OVL_E(dentry);
347 	struct ovl_path *lowerdata = ovl_lowerdata(oe);
348 	struct dentry *datadentry = datapath->dentry;
349 
350 	if (WARN_ON_ONCE(ovl_numlower(oe) <= 1))
351 		return -EIO;
352 
353 	WRITE_ONCE(lowerdata->layer, datapath->layer);
354 	/*
355 	 * Pairs with smp_rmb() in ovl_path_lowerdata().
356 	 * Make sure that if lowerdata->dentry is visible, then
357 	 * lowerdata->layer is visible as well.
358 	 */
359 	smp_wmb();
360 	WRITE_ONCE(lowerdata->dentry, dget(datadentry));
361 
362 	ovl_dentry_update_reval(dentry, datadentry);
363 
364 	return 0;
365 }
366 
367 struct dentry *ovl_dentry_real(struct dentry *dentry)
368 {
369 	return ovl_dentry_upper(dentry) ?: ovl_dentry_lower(dentry);
370 }
371 
372 struct dentry *ovl_i_dentry_upper(struct inode *inode)
373 {
374 	return ovl_upperdentry_dereference(OVL_I(inode));
375 }
376 
377 struct inode *ovl_i_path_real(struct inode *inode, struct path *path)
378 {
379 	struct ovl_path *lowerpath = ovl_lowerpath(OVL_I_E(inode));
380 
381 	path->dentry = ovl_i_dentry_upper(inode);
382 	if (!path->dentry) {
383 		path->dentry = lowerpath->dentry;
384 		path->mnt = lowerpath->layer->mnt;
385 	} else {
386 		path->mnt = ovl_upper_mnt(OVL_FS(inode->i_sb));
387 	}
388 
389 	return path->dentry ? d_inode_rcu(path->dentry) : NULL;
390 }
391 
392 struct inode *ovl_inode_upper(struct inode *inode)
393 {
394 	struct dentry *upperdentry = ovl_i_dentry_upper(inode);
395 
396 	return upperdentry ? d_inode(upperdentry) : NULL;
397 }
398 
399 struct inode *ovl_inode_lower(struct inode *inode)
400 {
401 	struct ovl_path *lowerpath = ovl_lowerpath(OVL_I_E(inode));
402 
403 	return lowerpath ? d_inode(lowerpath->dentry) : NULL;
404 }
405 
406 struct inode *ovl_inode_real(struct inode *inode)
407 {
408 	return ovl_inode_upper(inode) ?: ovl_inode_lower(inode);
409 }
410 
411 /* Return inode which contains lower data. Do not return metacopy */
412 struct inode *ovl_inode_lowerdata(struct inode *inode)
413 {
414 	struct dentry *lowerdata = ovl_lowerdata_dentry(OVL_I_E(inode));
415 
416 	if (WARN_ON(!S_ISREG(inode->i_mode)))
417 		return NULL;
418 
419 	return lowerdata ? d_inode(lowerdata) : NULL;
420 }
421 
422 /* Return real inode which contains data. Does not return metacopy inode */
423 struct inode *ovl_inode_realdata(struct inode *inode)
424 {
425 	struct inode *upperinode;
426 
427 	upperinode = ovl_inode_upper(inode);
428 	if (upperinode && ovl_has_upperdata(inode))
429 		return upperinode;
430 
431 	return ovl_inode_lowerdata(inode);
432 }
433 
434 const char *ovl_lowerdata_redirect(struct inode *inode)
435 {
436 	return inode && S_ISREG(inode->i_mode) ?
437 		OVL_I(inode)->lowerdata_redirect : NULL;
438 }
439 
440 struct ovl_dir_cache *ovl_dir_cache(struct inode *inode)
441 {
442 	return inode && S_ISDIR(inode->i_mode) ? OVL_I(inode)->cache : NULL;
443 }
444 
445 void ovl_set_dir_cache(struct inode *inode, struct ovl_dir_cache *cache)
446 {
447 	OVL_I(inode)->cache = cache;
448 }
449 
450 void ovl_dentry_set_flag(unsigned long flag, struct dentry *dentry)
451 {
452 	set_bit(flag, OVL_E_FLAGS(dentry));
453 }
454 
455 void ovl_dentry_clear_flag(unsigned long flag, struct dentry *dentry)
456 {
457 	clear_bit(flag, OVL_E_FLAGS(dentry));
458 }
459 
460 bool ovl_dentry_test_flag(unsigned long flag, struct dentry *dentry)
461 {
462 	return test_bit(flag, OVL_E_FLAGS(dentry));
463 }
464 
465 bool ovl_dentry_is_opaque(struct dentry *dentry)
466 {
467 	return ovl_dentry_test_flag(OVL_E_OPAQUE, dentry);
468 }
469 
470 bool ovl_dentry_is_whiteout(struct dentry *dentry)
471 {
472 	return !dentry->d_inode && ovl_dentry_is_opaque(dentry);
473 }
474 
475 void ovl_dentry_set_opaque(struct dentry *dentry)
476 {
477 	ovl_dentry_set_flag(OVL_E_OPAQUE, dentry);
478 }
479 
480 bool ovl_dentry_has_xwhiteouts(struct dentry *dentry)
481 {
482 	return ovl_dentry_test_flag(OVL_E_XWHITEOUTS, dentry);
483 }
484 
485 void ovl_dentry_set_xwhiteouts(struct dentry *dentry)
486 {
487 	ovl_dentry_set_flag(OVL_E_XWHITEOUTS, dentry);
488 }
489 
490 /*
491  * ovl_layer_set_xwhiteouts() is called before adding the overlay dir
492  * dentry to dcache, while readdir of that same directory happens after
493  * the overlay dir dentry is in dcache, so if some cpu observes that
494  * ovl_dentry_is_xwhiteouts(), it will also observe layer->has_xwhiteouts
495  * for the layers where xwhiteouts marker was found in that merge dir.
496  */
497 void ovl_layer_set_xwhiteouts(struct ovl_fs *ofs,
498 			      const struct ovl_layer *layer)
499 {
500 	if (layer->has_xwhiteouts)
501 		return;
502 
503 	/* Write once to read-mostly layer properties */
504 	ofs->layers[layer->idx].has_xwhiteouts = true;
505 }
506 
507 /*
508  * For hard links and decoded file handles, it's possible for ovl_dentry_upper()
509  * to return positive, while there's no actual upper alias for the inode.
510  * Copy up code needs to know about the existence of the upper alias, so it
511  * can't use ovl_dentry_upper().
512  */
513 bool ovl_dentry_has_upper_alias(struct dentry *dentry)
514 {
515 	return ovl_dentry_test_flag(OVL_E_UPPER_ALIAS, dentry);
516 }
517 
518 void ovl_dentry_set_upper_alias(struct dentry *dentry)
519 {
520 	ovl_dentry_set_flag(OVL_E_UPPER_ALIAS, dentry);
521 }
522 
523 static bool ovl_should_check_upperdata(struct inode *inode)
524 {
525 	if (!S_ISREG(inode->i_mode))
526 		return false;
527 
528 	if (!ovl_inode_lower(inode))
529 		return false;
530 
531 	return true;
532 }
533 
534 bool ovl_has_upperdata(struct inode *inode)
535 {
536 	if (!ovl_should_check_upperdata(inode))
537 		return true;
538 
539 	if (!ovl_test_flag(OVL_UPPERDATA, inode))
540 		return false;
541 	/*
542 	 * Pairs with smp_wmb() in ovl_set_upperdata(). Main user of
543 	 * ovl_has_upperdata() is ovl_copy_up_meta_inode_data(). Make sure
544 	 * if setting of OVL_UPPERDATA is visible, then effects of writes
545 	 * before that are visible too.
546 	 */
547 	smp_rmb();
548 	return true;
549 }
550 
551 void ovl_set_upperdata(struct inode *inode)
552 {
553 	/*
554 	 * Pairs with smp_rmb() in ovl_has_upperdata(). Make sure
555 	 * if OVL_UPPERDATA flag is visible, then effects of write operations
556 	 * before it are visible as well.
557 	 */
558 	smp_wmb();
559 	ovl_set_flag(OVL_UPPERDATA, inode);
560 }
561 
562 /* Caller should hold ovl_inode->lock */
563 bool ovl_dentry_needs_data_copy_up_locked(struct dentry *dentry, int flags)
564 {
565 	if (!ovl_open_flags_need_copy_up(flags))
566 		return false;
567 
568 	return !ovl_test_flag(OVL_UPPERDATA, d_inode(dentry));
569 }
570 
571 bool ovl_dentry_needs_data_copy_up(struct dentry *dentry, int flags)
572 {
573 	if (!ovl_open_flags_need_copy_up(flags))
574 		return false;
575 
576 	return !ovl_has_upperdata(d_inode(dentry));
577 }
578 
579 const char *ovl_dentry_get_redirect(struct dentry *dentry)
580 {
581 	return OVL_I(d_inode(dentry))->redirect;
582 }
583 
584 void ovl_dentry_set_redirect(struct dentry *dentry, const char *redirect)
585 {
586 	struct ovl_inode *oi = OVL_I(d_inode(dentry));
587 
588 	kfree(oi->redirect);
589 	oi->redirect = redirect;
590 }
591 
592 void ovl_inode_update(struct inode *inode, struct dentry *upperdentry)
593 {
594 	struct inode *upperinode = d_inode(upperdentry);
595 
596 	WARN_ON(OVL_I(inode)->__upperdentry);
597 
598 	/*
599 	 * Make sure upperdentry is consistent before making it visible
600 	 */
601 	smp_wmb();
602 	OVL_I(inode)->__upperdentry = upperdentry;
603 	if (inode_unhashed(inode)) {
604 		inode->i_private = upperinode;
605 		__insert_inode_hash(inode, (unsigned long) upperinode);
606 	}
607 }
608 
609 static void ovl_dir_version_inc(struct dentry *dentry, bool impurity)
610 {
611 	struct inode *inode = d_inode(dentry);
612 
613 	WARN_ON(!inode_is_locked(inode));
614 	WARN_ON(!d_is_dir(dentry));
615 	/*
616 	 * Version is used by readdir code to keep cache consistent.
617 	 * For merge dirs (or dirs with origin) all changes need to be noted.
618 	 * For non-merge dirs, cache contains only impure entries (i.e. ones
619 	 * which have been copied up and have origins), so only need to note
620 	 * changes to impure entries.
621 	 */
622 	if (!ovl_dir_is_real(inode) || impurity)
623 		OVL_I(inode)->version++;
624 }
625 
626 void ovl_dir_modified(struct dentry *dentry, bool impurity)
627 {
628 	/* Copy mtime/ctime */
629 	ovl_copyattr(d_inode(dentry));
630 
631 	ovl_dir_version_inc(dentry, impurity);
632 }
633 
634 u64 ovl_inode_version_get(struct inode *inode)
635 {
636 	WARN_ON(!inode_is_locked(inode));
637 	return OVL_I(inode)->version;
638 }
639 
640 bool ovl_is_whiteout(struct dentry *dentry)
641 {
642 	struct inode *inode = dentry->d_inode;
643 
644 	return inode && IS_WHITEOUT(inode);
645 }
646 
647 /*
648  * Use this over ovl_is_whiteout for upper and lower files, as it also
649  * handles overlay.whiteout xattr whiteout files.
650  */
651 bool ovl_path_is_whiteout(struct ovl_fs *ofs, const struct path *path)
652 {
653 	return ovl_is_whiteout(path->dentry) ||
654 		ovl_path_check_xwhiteout_xattr(ofs, path);
655 }
656 
657 struct file *ovl_path_open_realfile(const struct file *user_file,
658 				    const struct path *path, int flags)
659 {
660 	struct inode *inode = d_inode(path->dentry);
661 	const struct mnt_idmap *real_idmap = mnt_idmap(path->mnt);
662 	int err, acc_mode;
663 
664 	if (flags & ~(O_ACCMODE | O_LARGEFILE))
665 		BUG();
666 
667 	switch (flags & O_ACCMODE) {
668 	case O_RDONLY:
669 		acc_mode = MAY_READ;
670 		break;
671 	case O_WRONLY:
672 		acc_mode = MAY_WRITE;
673 		break;
674 	default:
675 		BUG();
676 	}
677 
678 	err = inode_permission(real_idmap, inode, acc_mode | MAY_OPEN);
679 	if (err)
680 		return ERR_PTR(err);
681 
682 	/* O_NOATIME is an optimization, don't fail if not permitted */
683 	if (inode_owner_or_capable(real_idmap, inode))
684 		flags |= O_NOATIME;
685 
686 	/*
687 	 * Directory opens use dentry_open() here, not backing_file_open().
688 	 * Inherit FMODE_NONOTIFY from a fanotify permission fd so a listener
689 	 * that also watches the real filesystem does not deadlock.
690 	 */
691 	if (user_file && FMODE_FSNOTIFY_NONE(user_file->f_mode))
692 		return dentry_open_nonotify(path, flags, current_cred());
693 
694 	return dentry_open(path, flags, current_cred());
695 }
696 
697 /* Caller should hold ovl_inode->lock */
698 static bool ovl_already_copied_up_locked(struct dentry *dentry, int flags)
699 {
700 	bool disconnected = dentry->d_flags & DCACHE_DISCONNECTED;
701 
702 	if (ovl_dentry_upper(dentry) &&
703 	    (ovl_dentry_has_upper_alias(dentry) || disconnected) &&
704 	    !ovl_dentry_needs_data_copy_up_locked(dentry, flags))
705 		return true;
706 
707 	return false;
708 }
709 
710 bool ovl_already_copied_up(struct dentry *dentry, int flags)
711 {
712 	bool disconnected = dentry->d_flags & DCACHE_DISCONNECTED;
713 
714 	/*
715 	 * Check if copy-up has happened as well as for upper alias (in
716 	 * case of hard links) is there.
717 	 *
718 	 * Both checks are lockless:
719 	 *  - false negatives: will recheck under oi->lock
720 	 *  - false positives:
721 	 *    + ovl_dentry_upper() uses memory barriers to ensure the
722 	 *      upper dentry is up-to-date
723 	 *    + ovl_dentry_has_upper_alias() relies on locking of
724 	 *      upper parent i_rwsem to prevent reordering copy-up
725 	 *      with rename.
726 	 */
727 	if (ovl_dentry_upper(dentry) &&
728 	    (ovl_dentry_has_upper_alias(dentry) || disconnected) &&
729 	    !ovl_dentry_needs_data_copy_up(dentry, flags))
730 		return true;
731 
732 	return false;
733 }
734 
735 /*
736  * The copy up "transaction" keeps an elevated mnt write count on upper mnt,
737  * but leaves taking freeze protection on upper sb to lower level helpers.
738  */
739 int ovl_copy_up_start(struct dentry *dentry, int flags)
740 {
741 	struct inode *inode = d_inode(dentry);
742 	int err;
743 
744 	err = ovl_inode_lock_interruptible(inode);
745 	if (err)
746 		return err;
747 
748 	if (ovl_already_copied_up_locked(dentry, flags))
749 		err = 1; /* Already copied up */
750 	else
751 		err = ovl_get_write_access(dentry);
752 	if (err)
753 		goto out_unlock;
754 
755 	return 0;
756 
757 out_unlock:
758 	ovl_inode_unlock(inode);
759 	return err;
760 }
761 
762 void ovl_copy_up_end(struct dentry *dentry)
763 {
764 	ovl_put_write_access(dentry);
765 	ovl_inode_unlock(d_inode(dentry));
766 }
767 
768 bool ovl_path_check_origin_xattr(struct ovl_fs *ofs, const struct path *path)
769 {
770 	int res;
771 
772 	res = ovl_path_getxattr(ofs, path, OVL_XATTR_ORIGIN, NULL, 0);
773 
774 	/* Zero size value means "copied up but origin unknown" */
775 	if (res >= 0)
776 		return true;
777 
778 	return false;
779 }
780 
781 bool ovl_path_check_xwhiteout_xattr(struct ovl_fs *ofs, const struct path *path)
782 {
783 	struct dentry *dentry = path->dentry;
784 	int res;
785 
786 	/* xattr.whiteout must be a zero size regular file */
787 	if (!d_is_reg(dentry) || i_size_read(d_inode(dentry)) != 0)
788 		return false;
789 
790 	res = ovl_path_getxattr(ofs, path, OVL_XATTR_XWHITEOUT, NULL, 0);
791 	return res >= 0;
792 }
793 
794 /*
795  * Load persistent uuid from xattr into s_uuid if found, or store a new
796  * random generated value in s_uuid and in xattr.
797  */
798 bool ovl_init_uuid_xattr(struct super_block *sb, struct ovl_fs *ofs,
799 			 const struct path *upperpath)
800 {
801 	bool set = false;
802 	uuid_t uuid;
803 	int res;
804 
805 	/* Try to load existing persistent uuid */
806 	res = ovl_path_getxattr(ofs, upperpath, OVL_XATTR_UUID, uuid.b,
807 				UUID_SIZE);
808 	if (res == UUID_SIZE)
809 		goto set_uuid;
810 
811 	if (res != -ENODATA)
812 		goto fail;
813 
814 	/*
815 	 * With uuid=auto, if uuid xattr is found, it will be used.
816 	 * If uuid xattrs is not found, generate a persistent uuid only on mount
817 	 * of new overlays where upper root dir is not yet marked as impure.
818 	 * An upper dir is marked as impure on copy up or lookup of its subdirs.
819 	 */
820 	if (ofs->config.uuid == OVL_UUID_AUTO) {
821 		res = ovl_path_getxattr(ofs, upperpath, OVL_XATTR_IMPURE, NULL,
822 					0);
823 		if (res > 0) {
824 			/* Any mount of old overlay - downgrade to uuid=null */
825 			ofs->config.uuid = OVL_UUID_NULL;
826 			return true;
827 		} else if (res == -ENODATA) {
828 			/* First mount of new overlay - upgrade to uuid=on */
829 			ofs->config.uuid = OVL_UUID_ON;
830 		} else if (res < 0) {
831 			goto fail;
832 		}
833 
834 	}
835 
836 	/* Generate overlay instance uuid */
837 	uuid_gen(&uuid);
838 
839 	/* Try to store persistent uuid */
840 	set = true;
841 	res = ovl_setxattr(ofs, upperpath->dentry, OVL_XATTR_UUID, uuid.b,
842 			   UUID_SIZE);
843 	if (res)
844 		goto fail;
845 
846 set_uuid:
847 	super_set_uuid(sb, uuid.b, sizeof(uuid));
848 	return true;
849 
850 fail:
851 	ofs->config.uuid = OVL_UUID_NULL;
852 	pr_warn("failed to %s uuid (%pd2, err=%i); falling back to uuid=null.\n",
853 		set ? "set" : "get", upperpath->dentry, res);
854 	return false;
855 }
856 
857 char ovl_get_dir_xattr_val(struct ovl_fs *ofs, const struct path *path,
858 			   enum ovl_xattr ox)
859 {
860 	int res;
861 	char val;
862 
863 	if (!d_is_dir(path->dentry))
864 		return 0;
865 
866 	res = ovl_path_getxattr(ofs, path, ox, &val, 1);
867 	return res == 1 ? val : 0;
868 }
869 
870 #define OVL_XATTR_OPAQUE_POSTFIX	"opaque"
871 #define OVL_XATTR_REDIRECT_POSTFIX	"redirect"
872 #define OVL_XATTR_ORIGIN_POSTFIX	"origin"
873 #define OVL_XATTR_IMPURE_POSTFIX	"impure"
874 #define OVL_XATTR_NLINK_POSTFIX		"nlink"
875 #define OVL_XATTR_UPPER_POSTFIX		"upper"
876 #define OVL_XATTR_UUID_POSTFIX		"uuid"
877 #define OVL_XATTR_METACOPY_POSTFIX	"metacopy"
878 #define OVL_XATTR_PROTATTR_POSTFIX	"protattr"
879 #define OVL_XATTR_XWHITEOUT_POSTFIX	"whiteout"
880 
881 #define OVL_XATTR_TAB_ENTRY(x) \
882 	[x] = { [false] = OVL_XATTR_TRUSTED_PREFIX x ## _POSTFIX, \
883 		[true] = OVL_XATTR_USER_PREFIX x ## _POSTFIX }
884 
885 const char *const ovl_xattr_table[][2] = {
886 	OVL_XATTR_TAB_ENTRY(OVL_XATTR_OPAQUE),
887 	OVL_XATTR_TAB_ENTRY(OVL_XATTR_REDIRECT),
888 	OVL_XATTR_TAB_ENTRY(OVL_XATTR_ORIGIN),
889 	OVL_XATTR_TAB_ENTRY(OVL_XATTR_IMPURE),
890 	OVL_XATTR_TAB_ENTRY(OVL_XATTR_NLINK),
891 	OVL_XATTR_TAB_ENTRY(OVL_XATTR_UPPER),
892 	OVL_XATTR_TAB_ENTRY(OVL_XATTR_UUID),
893 	OVL_XATTR_TAB_ENTRY(OVL_XATTR_METACOPY),
894 	OVL_XATTR_TAB_ENTRY(OVL_XATTR_PROTATTR),
895 	OVL_XATTR_TAB_ENTRY(OVL_XATTR_XWHITEOUT),
896 };
897 
898 int ovl_check_setxattr(struct ovl_fs *ofs, struct dentry *upperdentry,
899 		       enum ovl_xattr ox, const void *value, size_t size,
900 		       int xerr)
901 {
902 	int err;
903 
904 	if (ofs->noxattr)
905 		return xerr;
906 
907 	err = ovl_setxattr(ofs, upperdentry, ox, value, size);
908 
909 	if (err == -EOPNOTSUPP) {
910 		pr_warn("cannot set %s xattr on upper\n", ovl_xattr(ofs, ox));
911 		ofs->noxattr = true;
912 		return xerr;
913 	}
914 
915 	return err;
916 }
917 
918 int ovl_set_impure(struct dentry *dentry, struct dentry *upperdentry)
919 {
920 	struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
921 	int err;
922 
923 	if (ovl_test_flag(OVL_IMPURE, d_inode(dentry)))
924 		return 0;
925 
926 	/*
927 	 * Do not fail when upper doesn't support xattrs.
928 	 * Upper inodes won't have origin nor redirect xattr anyway.
929 	 */
930 	err = ovl_check_setxattr(ofs, upperdentry, OVL_XATTR_IMPURE, "y", 1, 0);
931 	if (!err)
932 		ovl_set_flag(OVL_IMPURE, d_inode(dentry));
933 
934 	return err;
935 }
936 
937 
938 #define OVL_PROTATTR_MAX 32 /* Reserved for future flags */
939 
940 void ovl_check_protattr(struct inode *inode, struct dentry *upper)
941 {
942 	struct ovl_fs *ofs = OVL_FS(inode->i_sb);
943 	u32 iflags = inode->i_flags & OVL_PROT_I_FLAGS_MASK;
944 	char buf[OVL_PROTATTR_MAX+1];
945 	int res, n;
946 
947 	res = ovl_getxattr_upper(ofs, upper, OVL_XATTR_PROTATTR, buf,
948 				 OVL_PROTATTR_MAX);
949 	if (res < 0)
950 		return;
951 
952 	/*
953 	 * Initialize inode flags from overlay.protattr xattr and upper inode
954 	 * flags.  If upper inode has those fileattr flags set (i.e. from old
955 	 * kernel), we do not clear them on ovl_get_inode(), but we will clear
956 	 * them on next fileattr_set().
957 	 */
958 	for (n = 0; n < res; n++) {
959 		if (buf[n] == 'a')
960 			iflags |= S_APPEND;
961 		else if (buf[n] == 'i')
962 			iflags |= S_IMMUTABLE;
963 		else
964 			break;
965 	}
966 
967 	if (!res || n < res) {
968 		pr_warn_ratelimited("incompatible overlay.protattr format (%pd2, len=%d)\n",
969 				    upper, res);
970 	} else {
971 		inode_set_flags(inode, iflags, OVL_PROT_I_FLAGS_MASK);
972 	}
973 }
974 
975 int ovl_set_protattr(struct inode *inode, struct dentry *upper,
976 		      struct file_kattr *fa)
977 {
978 	struct ovl_fs *ofs = OVL_FS(inode->i_sb);
979 	char buf[OVL_PROTATTR_MAX];
980 	int len = 0, err = 0;
981 	u32 iflags = 0;
982 
983 	BUILD_BUG_ON(HWEIGHT32(OVL_PROT_FS_FLAGS_MASK) > OVL_PROTATTR_MAX);
984 
985 	if (fa->flags & FS_APPEND_FL) {
986 		buf[len++] = 'a';
987 		iflags |= S_APPEND;
988 	}
989 	if (fa->flags & FS_IMMUTABLE_FL) {
990 		buf[len++] = 'i';
991 		iflags |= S_IMMUTABLE;
992 	}
993 
994 	/*
995 	 * Do not allow to set protection flags when upper doesn't support
996 	 * xattrs, because we do not set those fileattr flags on upper inode.
997 	 * Remove xattr if it exist and all protection flags are cleared.
998 	 */
999 	if (len) {
1000 		err = ovl_check_setxattr(ofs, upper, OVL_XATTR_PROTATTR,
1001 					 buf, len, -EPERM);
1002 	} else if (inode->i_flags & OVL_PROT_I_FLAGS_MASK) {
1003 		err = ovl_removexattr(ofs, upper, OVL_XATTR_PROTATTR);
1004 		if (err == -EOPNOTSUPP || err == -ENODATA)
1005 			err = 0;
1006 	}
1007 	if (err)
1008 		return err;
1009 
1010 	inode_set_flags(inode, iflags, OVL_PROT_I_FLAGS_MASK);
1011 
1012 	/* Mask out the fileattr flags that should not be set in upper inode */
1013 	fa->flags &= ~OVL_PROT_FS_FLAGS_MASK;
1014 	fa->fsx_xflags &= ~OVL_PROT_FSX_FLAGS_MASK;
1015 
1016 	return 0;
1017 }
1018 
1019 /*
1020  * Caller must hold a reference to inode to prevent it from being freed while
1021  * it is marked inuse.
1022  */
1023 bool ovl_inuse_trylock(struct dentry *dentry)
1024 {
1025 	struct inode *inode = d_inode(dentry);
1026 	bool locked = false;
1027 
1028 	spin_lock(&inode->i_lock);
1029 	if (!(inode_state_read(inode) & I_OVL_INUSE)) {
1030 		inode_state_set(inode, I_OVL_INUSE);
1031 		locked = true;
1032 	}
1033 	spin_unlock(&inode->i_lock);
1034 
1035 	return locked;
1036 }
1037 
1038 void ovl_inuse_unlock(struct dentry *dentry)
1039 {
1040 	if (dentry) {
1041 		struct inode *inode = d_inode(dentry);
1042 
1043 		spin_lock(&inode->i_lock);
1044 		WARN_ON(!(inode_state_read(inode) & I_OVL_INUSE));
1045 		inode_state_clear(inode, I_OVL_INUSE);
1046 		spin_unlock(&inode->i_lock);
1047 	}
1048 }
1049 
1050 bool ovl_is_inuse(struct dentry *dentry)
1051 {
1052 	struct inode *inode = d_inode(dentry);
1053 	bool inuse;
1054 
1055 	spin_lock(&inode->i_lock);
1056 	inuse = (inode_state_read(inode) & I_OVL_INUSE);
1057 	spin_unlock(&inode->i_lock);
1058 
1059 	return inuse;
1060 }
1061 
1062 /*
1063  * Does this overlay dentry need to be indexed on copy up?
1064  */
1065 bool ovl_need_index(struct dentry *dentry)
1066 {
1067 	struct dentry *lower = ovl_dentry_lower(dentry);
1068 
1069 	if (!lower || !ovl_indexdir(dentry->d_sb))
1070 		return false;
1071 
1072 	/* Index all files for NFS export and consistency verification */
1073 	if (ovl_index_all(dentry->d_sb))
1074 		return true;
1075 
1076 	/* Index only lower hardlinks on copy up */
1077 	if (!d_is_dir(lower) && d_inode(lower)->i_nlink > 1)
1078 		return true;
1079 
1080 	return false;
1081 }
1082 
1083 /* Caller must hold OVL_I(inode)->lock */
1084 static void ovl_cleanup_index(struct dentry *dentry)
1085 {
1086 	struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
1087 	struct dentry *indexdir = ovl_indexdir(dentry->d_sb);
1088 	struct dentry *lowerdentry = ovl_dentry_lower(dentry);
1089 	struct dentry *upperdentry = ovl_dentry_upper(dentry);
1090 	struct dentry *index = NULL;
1091 	struct inode *inode;
1092 	struct qstr name = { };
1093 	bool got_write = false;
1094 	int err;
1095 
1096 	err = ovl_get_index_name(ofs, lowerdentry, &name);
1097 	if (err)
1098 		goto fail;
1099 
1100 	err = ovl_want_write(dentry);
1101 	if (err)
1102 		goto fail;
1103 
1104 	got_write = true;
1105 	inode = d_inode(upperdentry);
1106 	if (!S_ISDIR(inode->i_mode) && inode->i_nlink != 1) {
1107 		pr_warn_ratelimited("cleanup linked index (%pd2, ino=%llu, nlink=%u)\n",
1108 				    upperdentry, inode->i_ino, inode->i_nlink);
1109 		/*
1110 		 * We either have a bug with persistent union nlink or a lower
1111 		 * hardlink was added while overlay is mounted. Adding a lower
1112 		 * hardlink and then unlinking all overlay hardlinks would drop
1113 		 * overlay nlink to zero before all upper inodes are unlinked.
1114 		 * As a safety measure, when that situation is detected, set
1115 		 * the overlay nlink to the index inode nlink minus one for the
1116 		 * index entry itself.
1117 		 */
1118 		set_nlink(d_inode(dentry), inode->i_nlink - 1);
1119 		ovl_set_nlink_upper(dentry);
1120 		goto out;
1121 	}
1122 
1123 	index = ovl_lookup_upper_unlocked(ofs, name.name, indexdir, name.len);
1124 	err = PTR_ERR(index);
1125 	if (IS_ERR(index)) {
1126 		index = NULL;
1127 	} else if (ovl_index_all(dentry->d_sb)) {
1128 		/* Whiteout orphan index to block future open by handle */
1129 		err = ovl_cleanup_and_whiteout(OVL_FS(dentry->d_sb),
1130 					       indexdir, index, &name);
1131 	} else {
1132 		/* Cleanup orphan index entries */
1133 		err = ovl_cleanup(ofs, indexdir, index);
1134 	}
1135 	if (err)
1136 		goto fail;
1137 
1138 out:
1139 	if (got_write)
1140 		ovl_drop_write(dentry);
1141 	kfree(name.name);
1142 	dput(index);
1143 	return;
1144 
1145 fail:
1146 	pr_err("cleanup index of '%pd2' failed (%i)\n", dentry, err);
1147 	goto out;
1148 }
1149 
1150 /*
1151  * Operations that change overlay inode and upper inode nlink need to be
1152  * synchronized with copy up for persistent nlink accounting.
1153  */
1154 int ovl_nlink_start(struct dentry *dentry)
1155 {
1156 	struct inode *inode = d_inode(dentry);
1157 	int err;
1158 
1159 	if (WARN_ON(!inode))
1160 		return -ENOENT;
1161 
1162 	/*
1163 	 * With inodes index is enabled, we store the union overlay nlink
1164 	 * in an xattr on the index inode. When whiting out an indexed lower,
1165 	 * we need to decrement the overlay persistent nlink, but before the
1166 	 * first copy up, we have no upper index inode to store the xattr.
1167 	 *
1168 	 * As a workaround, before whiteout/rename over an indexed lower,
1169 	 * copy up to create the upper index. Creating the upper index will
1170 	 * initialize the overlay nlink, so it could be dropped if unlink
1171 	 * or rename succeeds.
1172 	 *
1173 	 * TODO: implement metadata only index copy up when called with
1174 	 *       ovl_copy_up_flags(dentry, O_PATH).
1175 	 */
1176 	if (ovl_need_index(dentry) && !ovl_dentry_has_upper_alias(dentry)) {
1177 		err = ovl_copy_up(dentry);
1178 		if (err)
1179 			return err;
1180 	}
1181 
1182 	err = ovl_inode_lock_interruptible(inode);
1183 	if (err)
1184 		return err;
1185 
1186 	err = ovl_want_write(dentry);
1187 	if (err)
1188 		goto out_unlock;
1189 
1190 	if (d_is_dir(dentry) || !ovl_test_flag(OVL_INDEX, inode))
1191 		return 0;
1192 
1193 	/*
1194 	 * The overlay inode nlink should be incremented/decremented IFF the
1195 	 * upper operation succeeds, along with nlink change of upper inode.
1196 	 * Therefore, before link/unlink/rename, we store the union nlink
1197 	 * value relative to the upper inode nlink in an upper inode xattr.
1198 	 */
1199 	with_ovl_creds(dentry->d_sb)
1200 		err = ovl_set_nlink_upper(dentry);
1201 	if (err)
1202 		goto out_drop_write;
1203 
1204 	return 0;
1205 
1206 out_drop_write:
1207 	ovl_drop_write(dentry);
1208 out_unlock:
1209 	ovl_inode_unlock(inode);
1210 
1211 	return err;
1212 }
1213 
1214 void ovl_nlink_end(struct dentry *dentry)
1215 {
1216 	struct inode *inode = d_inode(dentry);
1217 
1218 	ovl_drop_write(dentry);
1219 
1220 	if (ovl_test_flag(OVL_INDEX, inode) && inode->i_nlink == 0) {
1221 		with_ovl_creds(dentry->d_sb)
1222 			ovl_cleanup_index(dentry);
1223 	}
1224 
1225 	ovl_inode_unlock(inode);
1226 }
1227 
1228 /*
1229  * err < 0, 0 if no metacopy xattr, metacopy data size if xattr found.
1230  * an empty xattr returns OVL_METACOPY_MIN_SIZE to distinguish from no xattr value.
1231  */
1232 int ovl_check_metacopy_xattr(struct ovl_fs *ofs, const struct path *path,
1233 			     struct ovl_metacopy *data)
1234 {
1235 	int res;
1236 
1237 	/* Only regular files can have metacopy xattr */
1238 	if (!S_ISREG(d_inode(path->dentry)->i_mode))
1239 		return 0;
1240 
1241 	res = ovl_path_getxattr(ofs, path, OVL_XATTR_METACOPY,
1242 				data, data ? OVL_METACOPY_MAX_SIZE : 0);
1243 	if (res < 0) {
1244 		if (res == -ENODATA || res == -EOPNOTSUPP)
1245 			return 0;
1246 		/*
1247 		 * getxattr on user.* may fail with EACCES in case there's no
1248 		 * read permission on the inode.  Not much we can do, other than
1249 		 * tell the caller that this is not a metacopy inode.
1250 		 */
1251 		if (ofs->config.userxattr && res == -EACCES)
1252 			return 0;
1253 		goto out;
1254 	}
1255 
1256 	if (res == 0) {
1257 		/* Emulate empty data for zero size metacopy xattr */
1258 		res = OVL_METACOPY_MIN_SIZE;
1259 		if (data) {
1260 			memset(data, 0, res);
1261 			data->len = res;
1262 		}
1263 	} else if (res < OVL_METACOPY_MIN_SIZE) {
1264 		pr_warn_ratelimited("metacopy file '%pd' has too small xattr\n",
1265 				    path->dentry);
1266 		return -EIO;
1267 	} else if (data) {
1268 		if (data->version != 0) {
1269 			pr_warn_ratelimited("metacopy file '%pd' has unsupported version\n",
1270 					    path->dentry);
1271 			return -EIO;
1272 		}
1273 		if (res != data->len) {
1274 			pr_warn_ratelimited("metacopy file '%pd' has invalid xattr size\n",
1275 					    path->dentry);
1276 			return -EIO;
1277 		}
1278 	}
1279 
1280 	return res;
1281 out:
1282 	pr_warn_ratelimited("failed to get metacopy (%i)\n", res);
1283 	return res;
1284 }
1285 
1286 int ovl_set_metacopy_xattr(struct ovl_fs *ofs, struct dentry *d, struct ovl_metacopy *metacopy)
1287 {
1288 	size_t len = metacopy->len;
1289 
1290 	/* If no flags or digest fall back to empty metacopy file */
1291 	if (metacopy->version == 0 && metacopy->flags == 0 && metacopy->digest_algo == 0)
1292 		len = 0;
1293 
1294 	return ovl_check_setxattr(ofs, d, OVL_XATTR_METACOPY,
1295 				  metacopy, len, -EOPNOTSUPP);
1296 }
1297 
1298 bool ovl_is_metacopy_dentry(struct dentry *dentry)
1299 {
1300 	struct ovl_entry *oe = OVL_E(dentry);
1301 
1302 	if (!d_is_reg(dentry))
1303 		return false;
1304 
1305 	if (ovl_dentry_upper(dentry)) {
1306 		if (!ovl_has_upperdata(d_inode(dentry)))
1307 			return true;
1308 		return false;
1309 	}
1310 
1311 	return (ovl_numlower(oe) > 1);
1312 }
1313 
1314 char *ovl_get_redirect_xattr(struct ovl_fs *ofs, const struct path *path, int padding)
1315 {
1316 	int res;
1317 	char *s, *next, *buf = NULL;
1318 
1319 	res = ovl_path_getxattr(ofs, path, OVL_XATTR_REDIRECT, NULL, 0);
1320 	if (res == -ENODATA || res == -EOPNOTSUPP)
1321 		return NULL;
1322 	if (res < 0)
1323 		goto fail;
1324 	if (res == 0)
1325 		goto invalid;
1326 
1327 	buf = kzalloc(res + padding + 1, GFP_KERNEL);
1328 	if (!buf)
1329 		return ERR_PTR(-ENOMEM);
1330 
1331 	res = ovl_path_getxattr(ofs, path, OVL_XATTR_REDIRECT, buf, res);
1332 	if (res < 0)
1333 		goto fail;
1334 	if (res == 0)
1335 		goto invalid;
1336 
1337 	if (buf[0] == '/') {
1338 		for (s = buf; *s++ == '/'; s = next) {
1339 			next = strchrnul(s, '/');
1340 			if (s == next)
1341 				goto invalid;
1342 		}
1343 	} else {
1344 		if (strchr(buf, '/') != NULL)
1345 			goto invalid;
1346 	}
1347 
1348 	return buf;
1349 invalid:
1350 	pr_warn_ratelimited("invalid redirect (%s)\n", buf);
1351 	res = -EINVAL;
1352 	goto err_free;
1353 fail:
1354 	pr_warn_ratelimited("failed to get redirect (%i)\n", res);
1355 err_free:
1356 	kfree(buf);
1357 	return ERR_PTR(res);
1358 }
1359 
1360 /* Call with mounter creds as it may open the file */
1361 int ovl_ensure_verity_loaded(const struct path *datapath)
1362 {
1363 	struct inode *inode = d_inode(datapath->dentry);
1364 	struct file *filp;
1365 
1366 	if (IS_VERITY(inode) && fsverity_get_info(inode) == NULL) {
1367 		/*
1368 		 * If this inode was not yet opened, the verity info hasn't been
1369 		 * loaded yet, so we need to do that here to force it into memory.
1370 		 */
1371 		filp = kernel_file_open(datapath, O_RDONLY, current_cred());
1372 		if (IS_ERR(filp))
1373 			return PTR_ERR(filp);
1374 		fput(filp);
1375 	}
1376 
1377 	return 0;
1378 }
1379 
1380 int ovl_validate_verity(struct ovl_fs *ofs,
1381 			const struct path *metapath,
1382 			const struct path *datapath)
1383 {
1384 	struct ovl_metacopy metacopy_data;
1385 	u8 actual_digest[FS_VERITY_MAX_DIGEST_SIZE];
1386 	int xattr_digest_size, digest_size;
1387 	int xattr_size, err;
1388 	u8 verity_algo;
1389 
1390 	if (!ofs->config.verity_mode ||
1391 	    /* Verity only works on regular files */
1392 	    !S_ISREG(d_inode(metapath->dentry)->i_mode))
1393 		return 0;
1394 
1395 	xattr_size = ovl_check_metacopy_xattr(ofs, metapath, &metacopy_data);
1396 	if (xattr_size < 0)
1397 		return xattr_size;
1398 
1399 	if (!xattr_size || !metacopy_data.digest_algo) {
1400 		if (ofs->config.verity_mode == OVL_VERITY_REQUIRE) {
1401 			pr_warn_ratelimited("metacopy file '%pd' has no digest specified\n",
1402 					    metapath->dentry);
1403 			return -EIO;
1404 		}
1405 		return 0;
1406 	}
1407 
1408 	xattr_digest_size = ovl_metadata_digest_size(&metacopy_data);
1409 
1410 	err = ovl_ensure_verity_loaded(datapath);
1411 	if (err < 0) {
1412 		pr_warn_ratelimited("lower file '%pd' failed to load fs-verity info\n",
1413 				    datapath->dentry);
1414 		return -EIO;
1415 	}
1416 
1417 	digest_size = fsverity_get_digest(d_inode(datapath->dentry), actual_digest,
1418 					  &verity_algo, NULL);
1419 	if (digest_size == 0) {
1420 		pr_warn_ratelimited("lower file '%pd' has no fs-verity digest\n", datapath->dentry);
1421 		return -EIO;
1422 	}
1423 
1424 	if (xattr_digest_size != digest_size ||
1425 	    metacopy_data.digest_algo != verity_algo ||
1426 	    memcmp(metacopy_data.digest, actual_digest, xattr_digest_size) != 0) {
1427 		pr_warn_ratelimited("lower file '%pd' has the wrong fs-verity digest\n",
1428 				    datapath->dentry);
1429 		return -EIO;
1430 	}
1431 
1432 	return 0;
1433 }
1434 
1435 int ovl_get_verity_digest(struct ovl_fs *ofs, const struct path *src,
1436 			  struct ovl_metacopy *metacopy)
1437 {
1438 	int err, digest_size;
1439 
1440 	if (!ofs->config.verity_mode || !S_ISREG(d_inode(src->dentry)->i_mode))
1441 		return 0;
1442 
1443 	err = ovl_ensure_verity_loaded(src);
1444 	if (err < 0) {
1445 		pr_warn_ratelimited("lower file '%pd' failed to load fs-verity info\n",
1446 				    src->dentry);
1447 		return -EIO;
1448 	}
1449 
1450 	digest_size = fsverity_get_digest(d_inode(src->dentry),
1451 					  metacopy->digest, &metacopy->digest_algo, NULL);
1452 	if (digest_size == 0 ||
1453 	    WARN_ON_ONCE(digest_size > FS_VERITY_MAX_DIGEST_SIZE)) {
1454 		if (ofs->config.verity_mode == OVL_VERITY_REQUIRE) {
1455 			pr_warn_ratelimited("lower file '%pd' has no fs-verity digest\n",
1456 					    src->dentry);
1457 			return -EIO;
1458 		}
1459 		return 0;
1460 	}
1461 
1462 	metacopy->len += digest_size;
1463 	return 0;
1464 }
1465 
1466 /*
1467  * ovl_sync_status() - Check fs sync status for volatile mounts
1468  *
1469  * Returns 1 if this is not a volatile mount and a real sync is required.
1470  *
1471  * Returns 0 if syncing can be skipped because mount is volatile, and no errors
1472  * have occurred on the upperdir since the mount.
1473  *
1474  * Returns -errno if it is a volatile mount, and the error that occurred since
1475  * the last mount. If the error code changes, it'll return the latest error
1476  * code.
1477  */
1478 
1479 int ovl_sync_status(struct ovl_fs *ofs)
1480 {
1481 	struct vfsmount *mnt;
1482 
1483 	if (ovl_should_sync(ofs))
1484 		return 1;
1485 
1486 	mnt = ovl_upper_mnt(ofs);
1487 	if (!mnt)
1488 		return 0;
1489 
1490 	return errseq_check(&mnt->mnt_sb->s_wb_err, ofs->errseq);
1491 }
1492 
1493 /*
1494  * ovl_copyattr() - copy inode attributes from layer to ovl inode
1495  *
1496  * When overlay copies inode information from an upper or lower layer to the
1497  * relevant overlay inode it will apply the idmapping of the upper or lower
1498  * layer when doing so ensuring that the ovl inode ownership will correctly
1499  * reflect the ownership of the idmapped upper or lower layer. For example, an
1500  * idmapped upper or lower layer mapping id 1001 to id 1000 will take care to
1501  * map any lower or upper inode owned by id 1001 to id 1000. These mapping
1502  * helpers are nops when the relevant layer isn't idmapped.
1503  */
1504 void ovl_copyattr(struct inode *inode)
1505 {
1506 	struct path realpath;
1507 	struct inode *realinode;
1508 	const struct mnt_idmap *real_idmap;
1509 	vfsuid_t vfsuid;
1510 	vfsgid_t vfsgid;
1511 
1512 	realinode = ovl_i_path_real(inode, &realpath);
1513 	real_idmap = mnt_idmap(realpath.mnt);
1514 
1515 	spin_lock(&inode->i_lock);
1516 	vfsuid = i_uid_into_vfsuid(real_idmap, realinode);
1517 	vfsgid = i_gid_into_vfsgid(real_idmap, realinode);
1518 
1519 	inode->i_uid = vfsuid_into_kuid(vfsuid);
1520 	inode->i_gid = vfsgid_into_kgid(vfsgid);
1521 	inode->i_mode = realinode->i_mode;
1522 	inode_set_atime_to_ts(inode, inode_get_atime(realinode));
1523 	inode_set_mtime_to_ts(inode, inode_get_mtime(realinode));
1524 	inode_set_ctime_to_ts(inode, inode_get_ctime(realinode));
1525 	i_size_write(inode, i_size_read(realinode));
1526 	spin_unlock(&inode->i_lock);
1527 }
1528