xref: /openbmc/linux/fs/overlayfs/util.c (revision 4609e1f1)
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/fileattr.h>
14 #include <linux/uuid.h>
15 #include <linux/namei.h>
16 #include <linux/ratelimit.h>
17 #include "overlayfs.h"
18 
19 int ovl_want_write(struct dentry *dentry)
20 {
21 	struct ovl_fs *ofs = dentry->d_sb->s_fs_info;
22 	return mnt_want_write(ovl_upper_mnt(ofs));
23 }
24 
25 void ovl_drop_write(struct dentry *dentry)
26 {
27 	struct ovl_fs *ofs = dentry->d_sb->s_fs_info;
28 	mnt_drop_write(ovl_upper_mnt(ofs));
29 }
30 
31 struct dentry *ovl_workdir(struct dentry *dentry)
32 {
33 	struct ovl_fs *ofs = dentry->d_sb->s_fs_info;
34 	return ofs->workdir;
35 }
36 
37 const struct cred *ovl_override_creds(struct super_block *sb)
38 {
39 	struct ovl_fs *ofs = sb->s_fs_info;
40 
41 	return override_creds(ofs->creator_cred);
42 }
43 
44 /*
45  * Check if underlying fs supports file handles and try to determine encoding
46  * type, in order to deduce maximum inode number used by fs.
47  *
48  * Return 0 if file handles are not supported.
49  * Return 1 (FILEID_INO32_GEN) if fs uses the default 32bit inode encoding.
50  * Return -1 if fs uses a non default encoding with unknown inode size.
51  */
52 int ovl_can_decode_fh(struct super_block *sb)
53 {
54 	if (!capable(CAP_DAC_READ_SEARCH))
55 		return 0;
56 
57 	if (!sb->s_export_op || !sb->s_export_op->fh_to_dentry)
58 		return 0;
59 
60 	return sb->s_export_op->encode_fh ? -1 : FILEID_INO32_GEN;
61 }
62 
63 struct dentry *ovl_indexdir(struct super_block *sb)
64 {
65 	struct ovl_fs *ofs = sb->s_fs_info;
66 
67 	return ofs->indexdir;
68 }
69 
70 /* Index all files on copy up. For now only enabled for NFS export */
71 bool ovl_index_all(struct super_block *sb)
72 {
73 	struct ovl_fs *ofs = sb->s_fs_info;
74 
75 	return ofs->config.nfs_export && ofs->config.index;
76 }
77 
78 /* Verify lower origin on lookup. For now only enabled for NFS export */
79 bool ovl_verify_lower(struct super_block *sb)
80 {
81 	struct ovl_fs *ofs = sb->s_fs_info;
82 
83 	return ofs->config.nfs_export && ofs->config.index;
84 }
85 
86 struct ovl_entry *ovl_alloc_entry(unsigned int numlower)
87 {
88 	size_t size = offsetof(struct ovl_entry, lowerstack[numlower]);
89 	struct ovl_entry *oe = kzalloc(size, GFP_KERNEL);
90 
91 	if (oe)
92 		oe->numlower = numlower;
93 
94 	return oe;
95 }
96 
97 bool ovl_dentry_remote(struct dentry *dentry)
98 {
99 	return dentry->d_flags &
100 		(DCACHE_OP_REVALIDATE | DCACHE_OP_WEAK_REVALIDATE);
101 }
102 
103 void ovl_dentry_update_reval(struct dentry *dentry, struct dentry *upperdentry,
104 			     unsigned int mask)
105 {
106 	struct ovl_entry *oe = OVL_E(dentry);
107 	unsigned int i, flags = 0;
108 
109 	if (upperdentry)
110 		flags |= upperdentry->d_flags;
111 	for (i = 0; i < oe->numlower; i++)
112 		flags |= oe->lowerstack[i].dentry->d_flags;
113 
114 	spin_lock(&dentry->d_lock);
115 	dentry->d_flags &= ~mask;
116 	dentry->d_flags |= flags & mask;
117 	spin_unlock(&dentry->d_lock);
118 }
119 
120 bool ovl_dentry_weird(struct dentry *dentry)
121 {
122 	return dentry->d_flags & (DCACHE_NEED_AUTOMOUNT |
123 				  DCACHE_MANAGE_TRANSIT |
124 				  DCACHE_OP_HASH |
125 				  DCACHE_OP_COMPARE);
126 }
127 
128 enum ovl_path_type ovl_path_type(struct dentry *dentry)
129 {
130 	struct ovl_entry *oe = dentry->d_fsdata;
131 	enum ovl_path_type type = 0;
132 
133 	if (ovl_dentry_upper(dentry)) {
134 		type = __OVL_PATH_UPPER;
135 
136 		/*
137 		 * Non-dir dentry can hold lower dentry of its copy up origin.
138 		 */
139 		if (oe->numlower) {
140 			if (ovl_test_flag(OVL_CONST_INO, d_inode(dentry)))
141 				type |= __OVL_PATH_ORIGIN;
142 			if (d_is_dir(dentry) ||
143 			    !ovl_has_upperdata(d_inode(dentry)))
144 				type |= __OVL_PATH_MERGE;
145 		}
146 	} else {
147 		if (oe->numlower > 1)
148 			type |= __OVL_PATH_MERGE;
149 	}
150 	return type;
151 }
152 
153 void ovl_path_upper(struct dentry *dentry, struct path *path)
154 {
155 	struct ovl_fs *ofs = dentry->d_sb->s_fs_info;
156 
157 	path->mnt = ovl_upper_mnt(ofs);
158 	path->dentry = ovl_dentry_upper(dentry);
159 }
160 
161 void ovl_path_lower(struct dentry *dentry, struct path *path)
162 {
163 	struct ovl_entry *oe = dentry->d_fsdata;
164 
165 	if (oe->numlower) {
166 		path->mnt = oe->lowerstack[0].layer->mnt;
167 		path->dentry = oe->lowerstack[0].dentry;
168 	} else {
169 		*path = (struct path) { };
170 	}
171 }
172 
173 void ovl_path_lowerdata(struct dentry *dentry, struct path *path)
174 {
175 	struct ovl_entry *oe = dentry->d_fsdata;
176 
177 	if (oe->numlower) {
178 		path->mnt = oe->lowerstack[oe->numlower - 1].layer->mnt;
179 		path->dentry = oe->lowerstack[oe->numlower - 1].dentry;
180 	} else {
181 		*path = (struct path) { };
182 	}
183 }
184 
185 enum ovl_path_type ovl_path_real(struct dentry *dentry, struct path *path)
186 {
187 	enum ovl_path_type type = ovl_path_type(dentry);
188 
189 	if (!OVL_TYPE_UPPER(type))
190 		ovl_path_lower(dentry, path);
191 	else
192 		ovl_path_upper(dentry, path);
193 
194 	return type;
195 }
196 
197 enum ovl_path_type ovl_path_realdata(struct dentry *dentry, struct path *path)
198 {
199 	enum ovl_path_type type = ovl_path_type(dentry);
200 
201 	WARN_ON_ONCE(d_is_dir(dentry));
202 
203 	if (!OVL_TYPE_UPPER(type) || OVL_TYPE_MERGE(type))
204 		ovl_path_lowerdata(dentry, path);
205 	else
206 		ovl_path_upper(dentry, path);
207 
208 	return type;
209 }
210 
211 struct dentry *ovl_dentry_upper(struct dentry *dentry)
212 {
213 	return ovl_upperdentry_dereference(OVL_I(d_inode(dentry)));
214 }
215 
216 struct dentry *ovl_dentry_lower(struct dentry *dentry)
217 {
218 	struct ovl_entry *oe = dentry->d_fsdata;
219 
220 	return oe->numlower ? oe->lowerstack[0].dentry : NULL;
221 }
222 
223 const struct ovl_layer *ovl_layer_lower(struct dentry *dentry)
224 {
225 	struct ovl_entry *oe = dentry->d_fsdata;
226 
227 	return oe->numlower ? oe->lowerstack[0].layer : NULL;
228 }
229 
230 /*
231  * ovl_dentry_lower() could return either a data dentry or metacopy dentry
232  * depending on what is stored in lowerstack[0]. At times we need to find
233  * lower dentry which has data (and not metacopy dentry). This helper
234  * returns the lower data dentry.
235  */
236 struct dentry *ovl_dentry_lowerdata(struct dentry *dentry)
237 {
238 	struct ovl_entry *oe = dentry->d_fsdata;
239 
240 	return oe->numlower ? oe->lowerstack[oe->numlower - 1].dentry : NULL;
241 }
242 
243 struct dentry *ovl_dentry_real(struct dentry *dentry)
244 {
245 	return ovl_dentry_upper(dentry) ?: ovl_dentry_lower(dentry);
246 }
247 
248 struct dentry *ovl_i_dentry_upper(struct inode *inode)
249 {
250 	return ovl_upperdentry_dereference(OVL_I(inode));
251 }
252 
253 void ovl_i_path_real(struct inode *inode, struct path *path)
254 {
255 	path->dentry = ovl_i_dentry_upper(inode);
256 	if (!path->dentry) {
257 		path->dentry = OVL_I(inode)->lowerpath.dentry;
258 		path->mnt = OVL_I(inode)->lowerpath.layer->mnt;
259 	} else {
260 		path->mnt = ovl_upper_mnt(OVL_FS(inode->i_sb));
261 	}
262 }
263 
264 struct inode *ovl_inode_upper(struct inode *inode)
265 {
266 	struct dentry *upperdentry = ovl_i_dentry_upper(inode);
267 
268 	return upperdentry ? d_inode(upperdentry) : NULL;
269 }
270 
271 struct inode *ovl_inode_lower(struct inode *inode)
272 {
273 	struct dentry *lowerdentry = OVL_I(inode)->lowerpath.dentry;
274 
275 	return lowerdentry ? d_inode(lowerdentry) : NULL;
276 }
277 
278 struct inode *ovl_inode_real(struct inode *inode)
279 {
280 	return ovl_inode_upper(inode) ?: ovl_inode_lower(inode);
281 }
282 
283 /* Return inode which contains lower data. Do not return metacopy */
284 struct inode *ovl_inode_lowerdata(struct inode *inode)
285 {
286 	if (WARN_ON(!S_ISREG(inode->i_mode)))
287 		return NULL;
288 
289 	return OVL_I(inode)->lowerdata ?: ovl_inode_lower(inode);
290 }
291 
292 /* Return real inode which contains data. Does not return metacopy inode */
293 struct inode *ovl_inode_realdata(struct inode *inode)
294 {
295 	struct inode *upperinode;
296 
297 	upperinode = ovl_inode_upper(inode);
298 	if (upperinode && ovl_has_upperdata(inode))
299 		return upperinode;
300 
301 	return ovl_inode_lowerdata(inode);
302 }
303 
304 struct ovl_dir_cache *ovl_dir_cache(struct inode *inode)
305 {
306 	return OVL_I(inode)->cache;
307 }
308 
309 void ovl_set_dir_cache(struct inode *inode, struct ovl_dir_cache *cache)
310 {
311 	OVL_I(inode)->cache = cache;
312 }
313 
314 void ovl_dentry_set_flag(unsigned long flag, struct dentry *dentry)
315 {
316 	set_bit(flag, &OVL_E(dentry)->flags);
317 }
318 
319 void ovl_dentry_clear_flag(unsigned long flag, struct dentry *dentry)
320 {
321 	clear_bit(flag, &OVL_E(dentry)->flags);
322 }
323 
324 bool ovl_dentry_test_flag(unsigned long flag, struct dentry *dentry)
325 {
326 	return test_bit(flag, &OVL_E(dentry)->flags);
327 }
328 
329 bool ovl_dentry_is_opaque(struct dentry *dentry)
330 {
331 	return ovl_dentry_test_flag(OVL_E_OPAQUE, dentry);
332 }
333 
334 bool ovl_dentry_is_whiteout(struct dentry *dentry)
335 {
336 	return !dentry->d_inode && ovl_dentry_is_opaque(dentry);
337 }
338 
339 void ovl_dentry_set_opaque(struct dentry *dentry)
340 {
341 	ovl_dentry_set_flag(OVL_E_OPAQUE, dentry);
342 }
343 
344 /*
345  * For hard links and decoded file handles, it's possible for ovl_dentry_upper()
346  * to return positive, while there's no actual upper alias for the inode.
347  * Copy up code needs to know about the existence of the upper alias, so it
348  * can't use ovl_dentry_upper().
349  */
350 bool ovl_dentry_has_upper_alias(struct dentry *dentry)
351 {
352 	return ovl_dentry_test_flag(OVL_E_UPPER_ALIAS, dentry);
353 }
354 
355 void ovl_dentry_set_upper_alias(struct dentry *dentry)
356 {
357 	ovl_dentry_set_flag(OVL_E_UPPER_ALIAS, dentry);
358 }
359 
360 static bool ovl_should_check_upperdata(struct inode *inode)
361 {
362 	if (!S_ISREG(inode->i_mode))
363 		return false;
364 
365 	if (!ovl_inode_lower(inode))
366 		return false;
367 
368 	return true;
369 }
370 
371 bool ovl_has_upperdata(struct inode *inode)
372 {
373 	if (!ovl_should_check_upperdata(inode))
374 		return true;
375 
376 	if (!ovl_test_flag(OVL_UPPERDATA, inode))
377 		return false;
378 	/*
379 	 * Pairs with smp_wmb() in ovl_set_upperdata(). Main user of
380 	 * ovl_has_upperdata() is ovl_copy_up_meta_inode_data(). Make sure
381 	 * if setting of OVL_UPPERDATA is visible, then effects of writes
382 	 * before that are visible too.
383 	 */
384 	smp_rmb();
385 	return true;
386 }
387 
388 void ovl_set_upperdata(struct inode *inode)
389 {
390 	/*
391 	 * Pairs with smp_rmb() in ovl_has_upperdata(). Make sure
392 	 * if OVL_UPPERDATA flag is visible, then effects of write operations
393 	 * before it are visible as well.
394 	 */
395 	smp_wmb();
396 	ovl_set_flag(OVL_UPPERDATA, inode);
397 }
398 
399 /* Caller should hold ovl_inode->lock */
400 bool ovl_dentry_needs_data_copy_up_locked(struct dentry *dentry, int flags)
401 {
402 	if (!ovl_open_flags_need_copy_up(flags))
403 		return false;
404 
405 	return !ovl_test_flag(OVL_UPPERDATA, d_inode(dentry));
406 }
407 
408 bool ovl_dentry_needs_data_copy_up(struct dentry *dentry, int flags)
409 {
410 	if (!ovl_open_flags_need_copy_up(flags))
411 		return false;
412 
413 	return !ovl_has_upperdata(d_inode(dentry));
414 }
415 
416 bool ovl_redirect_dir(struct super_block *sb)
417 {
418 	struct ovl_fs *ofs = sb->s_fs_info;
419 
420 	return ofs->config.redirect_dir && !ofs->noxattr;
421 }
422 
423 const char *ovl_dentry_get_redirect(struct dentry *dentry)
424 {
425 	return OVL_I(d_inode(dentry))->redirect;
426 }
427 
428 void ovl_dentry_set_redirect(struct dentry *dentry, const char *redirect)
429 {
430 	struct ovl_inode *oi = OVL_I(d_inode(dentry));
431 
432 	kfree(oi->redirect);
433 	oi->redirect = redirect;
434 }
435 
436 void ovl_inode_update(struct inode *inode, struct dentry *upperdentry)
437 {
438 	struct inode *upperinode = d_inode(upperdentry);
439 
440 	WARN_ON(OVL_I(inode)->__upperdentry);
441 
442 	/*
443 	 * Make sure upperdentry is consistent before making it visible
444 	 */
445 	smp_wmb();
446 	OVL_I(inode)->__upperdentry = upperdentry;
447 	if (inode_unhashed(inode)) {
448 		inode->i_private = upperinode;
449 		__insert_inode_hash(inode, (unsigned long) upperinode);
450 	}
451 }
452 
453 static void ovl_dir_version_inc(struct dentry *dentry, bool impurity)
454 {
455 	struct inode *inode = d_inode(dentry);
456 
457 	WARN_ON(!inode_is_locked(inode));
458 	WARN_ON(!d_is_dir(dentry));
459 	/*
460 	 * Version is used by readdir code to keep cache consistent.
461 	 * For merge dirs (or dirs with origin) all changes need to be noted.
462 	 * For non-merge dirs, cache contains only impure entries (i.e. ones
463 	 * which have been copied up and have origins), so only need to note
464 	 * changes to impure entries.
465 	 */
466 	if (!ovl_dir_is_real(inode) || impurity)
467 		OVL_I(inode)->version++;
468 }
469 
470 void ovl_dir_modified(struct dentry *dentry, bool impurity)
471 {
472 	/* Copy mtime/ctime */
473 	ovl_copyattr(d_inode(dentry));
474 
475 	ovl_dir_version_inc(dentry, impurity);
476 }
477 
478 u64 ovl_inode_version_get(struct inode *inode)
479 {
480 	WARN_ON(!inode_is_locked(inode));
481 	return OVL_I(inode)->version;
482 }
483 
484 bool ovl_is_whiteout(struct dentry *dentry)
485 {
486 	struct inode *inode = dentry->d_inode;
487 
488 	return inode && IS_WHITEOUT(inode);
489 }
490 
491 struct file *ovl_path_open(const struct path *path, int flags)
492 {
493 	struct inode *inode = d_inode(path->dentry);
494 	struct mnt_idmap *real_idmap = mnt_idmap(path->mnt);
495 	struct user_namespace *real_mnt_userns = mnt_idmap_owner(real_idmap);
496 	int err, acc_mode;
497 
498 	if (flags & ~(O_ACCMODE | O_LARGEFILE))
499 		BUG();
500 
501 	switch (flags & O_ACCMODE) {
502 	case O_RDONLY:
503 		acc_mode = MAY_READ;
504 		break;
505 	case O_WRONLY:
506 		acc_mode = MAY_WRITE;
507 		break;
508 	default:
509 		BUG();
510 	}
511 
512 	err = inode_permission(real_idmap, inode, acc_mode | MAY_OPEN);
513 	if (err)
514 		return ERR_PTR(err);
515 
516 	/* O_NOATIME is an optimization, don't fail if not permitted */
517 	if (inode_owner_or_capable(real_mnt_userns, inode))
518 		flags |= O_NOATIME;
519 
520 	return dentry_open(path, flags, current_cred());
521 }
522 
523 /* Caller should hold ovl_inode->lock */
524 static bool ovl_already_copied_up_locked(struct dentry *dentry, int flags)
525 {
526 	bool disconnected = dentry->d_flags & DCACHE_DISCONNECTED;
527 
528 	if (ovl_dentry_upper(dentry) &&
529 	    (ovl_dentry_has_upper_alias(dentry) || disconnected) &&
530 	    !ovl_dentry_needs_data_copy_up_locked(dentry, flags))
531 		return true;
532 
533 	return false;
534 }
535 
536 bool ovl_already_copied_up(struct dentry *dentry, int flags)
537 {
538 	bool disconnected = dentry->d_flags & DCACHE_DISCONNECTED;
539 
540 	/*
541 	 * Check if copy-up has happened as well as for upper alias (in
542 	 * case of hard links) is there.
543 	 *
544 	 * Both checks are lockless:
545 	 *  - false negatives: will recheck under oi->lock
546 	 *  - false positives:
547 	 *    + ovl_dentry_upper() uses memory barriers to ensure the
548 	 *      upper dentry is up-to-date
549 	 *    + ovl_dentry_has_upper_alias() relies on locking of
550 	 *      upper parent i_rwsem to prevent reordering copy-up
551 	 *      with rename.
552 	 */
553 	if (ovl_dentry_upper(dentry) &&
554 	    (ovl_dentry_has_upper_alias(dentry) || disconnected) &&
555 	    !ovl_dentry_needs_data_copy_up(dentry, flags))
556 		return true;
557 
558 	return false;
559 }
560 
561 int ovl_copy_up_start(struct dentry *dentry, int flags)
562 {
563 	struct inode *inode = d_inode(dentry);
564 	int err;
565 
566 	err = ovl_inode_lock_interruptible(inode);
567 	if (!err && ovl_already_copied_up_locked(dentry, flags)) {
568 		err = 1; /* Already copied up */
569 		ovl_inode_unlock(inode);
570 	}
571 
572 	return err;
573 }
574 
575 void ovl_copy_up_end(struct dentry *dentry)
576 {
577 	ovl_inode_unlock(d_inode(dentry));
578 }
579 
580 bool ovl_path_check_origin_xattr(struct ovl_fs *ofs, const struct path *path)
581 {
582 	int res;
583 
584 	res = ovl_path_getxattr(ofs, path, OVL_XATTR_ORIGIN, NULL, 0);
585 
586 	/* Zero size value means "copied up but origin unknown" */
587 	if (res >= 0)
588 		return true;
589 
590 	return false;
591 }
592 
593 bool ovl_path_check_dir_xattr(struct ovl_fs *ofs, const struct path *path,
594 			       enum ovl_xattr ox)
595 {
596 	int res;
597 	char val;
598 
599 	if (!d_is_dir(path->dentry))
600 		return false;
601 
602 	res = ovl_path_getxattr(ofs, path, ox, &val, 1);
603 	if (res == 1 && val == 'y')
604 		return true;
605 
606 	return false;
607 }
608 
609 #define OVL_XATTR_OPAQUE_POSTFIX	"opaque"
610 #define OVL_XATTR_REDIRECT_POSTFIX	"redirect"
611 #define OVL_XATTR_ORIGIN_POSTFIX	"origin"
612 #define OVL_XATTR_IMPURE_POSTFIX	"impure"
613 #define OVL_XATTR_NLINK_POSTFIX		"nlink"
614 #define OVL_XATTR_UPPER_POSTFIX		"upper"
615 #define OVL_XATTR_METACOPY_POSTFIX	"metacopy"
616 #define OVL_XATTR_PROTATTR_POSTFIX	"protattr"
617 
618 #define OVL_XATTR_TAB_ENTRY(x) \
619 	[x] = { [false] = OVL_XATTR_TRUSTED_PREFIX x ## _POSTFIX, \
620 		[true] = OVL_XATTR_USER_PREFIX x ## _POSTFIX }
621 
622 const char *const ovl_xattr_table[][2] = {
623 	OVL_XATTR_TAB_ENTRY(OVL_XATTR_OPAQUE),
624 	OVL_XATTR_TAB_ENTRY(OVL_XATTR_REDIRECT),
625 	OVL_XATTR_TAB_ENTRY(OVL_XATTR_ORIGIN),
626 	OVL_XATTR_TAB_ENTRY(OVL_XATTR_IMPURE),
627 	OVL_XATTR_TAB_ENTRY(OVL_XATTR_NLINK),
628 	OVL_XATTR_TAB_ENTRY(OVL_XATTR_UPPER),
629 	OVL_XATTR_TAB_ENTRY(OVL_XATTR_METACOPY),
630 	OVL_XATTR_TAB_ENTRY(OVL_XATTR_PROTATTR),
631 };
632 
633 int ovl_check_setxattr(struct ovl_fs *ofs, struct dentry *upperdentry,
634 		       enum ovl_xattr ox, const void *value, size_t size,
635 		       int xerr)
636 {
637 	int err;
638 
639 	if (ofs->noxattr)
640 		return xerr;
641 
642 	err = ovl_setxattr(ofs, upperdentry, ox, value, size);
643 
644 	if (err == -EOPNOTSUPP) {
645 		pr_warn("cannot set %s xattr on upper\n", ovl_xattr(ofs, ox));
646 		ofs->noxattr = true;
647 		return xerr;
648 	}
649 
650 	return err;
651 }
652 
653 int ovl_set_impure(struct dentry *dentry, struct dentry *upperdentry)
654 {
655 	struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
656 	int err;
657 
658 	if (ovl_test_flag(OVL_IMPURE, d_inode(dentry)))
659 		return 0;
660 
661 	/*
662 	 * Do not fail when upper doesn't support xattrs.
663 	 * Upper inodes won't have origin nor redirect xattr anyway.
664 	 */
665 	err = ovl_check_setxattr(ofs, upperdentry, OVL_XATTR_IMPURE, "y", 1, 0);
666 	if (!err)
667 		ovl_set_flag(OVL_IMPURE, d_inode(dentry));
668 
669 	return err;
670 }
671 
672 
673 #define OVL_PROTATTR_MAX 32 /* Reserved for future flags */
674 
675 void ovl_check_protattr(struct inode *inode, struct dentry *upper)
676 {
677 	struct ovl_fs *ofs = OVL_FS(inode->i_sb);
678 	u32 iflags = inode->i_flags & OVL_PROT_I_FLAGS_MASK;
679 	char buf[OVL_PROTATTR_MAX+1];
680 	int res, n;
681 
682 	res = ovl_getxattr_upper(ofs, upper, OVL_XATTR_PROTATTR, buf,
683 				 OVL_PROTATTR_MAX);
684 	if (res < 0)
685 		return;
686 
687 	/*
688 	 * Initialize inode flags from overlay.protattr xattr and upper inode
689 	 * flags.  If upper inode has those fileattr flags set (i.e. from old
690 	 * kernel), we do not clear them on ovl_get_inode(), but we will clear
691 	 * them on next fileattr_set().
692 	 */
693 	for (n = 0; n < res; n++) {
694 		if (buf[n] == 'a')
695 			iflags |= S_APPEND;
696 		else if (buf[n] == 'i')
697 			iflags |= S_IMMUTABLE;
698 		else
699 			break;
700 	}
701 
702 	if (!res || n < res) {
703 		pr_warn_ratelimited("incompatible overlay.protattr format (%pd2, len=%d)\n",
704 				    upper, res);
705 	} else {
706 		inode_set_flags(inode, iflags, OVL_PROT_I_FLAGS_MASK);
707 	}
708 }
709 
710 int ovl_set_protattr(struct inode *inode, struct dentry *upper,
711 		      struct fileattr *fa)
712 {
713 	struct ovl_fs *ofs = OVL_FS(inode->i_sb);
714 	char buf[OVL_PROTATTR_MAX];
715 	int len = 0, err = 0;
716 	u32 iflags = 0;
717 
718 	BUILD_BUG_ON(HWEIGHT32(OVL_PROT_FS_FLAGS_MASK) > OVL_PROTATTR_MAX);
719 
720 	if (fa->flags & FS_APPEND_FL) {
721 		buf[len++] = 'a';
722 		iflags |= S_APPEND;
723 	}
724 	if (fa->flags & FS_IMMUTABLE_FL) {
725 		buf[len++] = 'i';
726 		iflags |= S_IMMUTABLE;
727 	}
728 
729 	/*
730 	 * Do not allow to set protection flags when upper doesn't support
731 	 * xattrs, because we do not set those fileattr flags on upper inode.
732 	 * Remove xattr if it exist and all protection flags are cleared.
733 	 */
734 	if (len) {
735 		err = ovl_check_setxattr(ofs, upper, OVL_XATTR_PROTATTR,
736 					 buf, len, -EPERM);
737 	} else if (inode->i_flags & OVL_PROT_I_FLAGS_MASK) {
738 		err = ovl_removexattr(ofs, upper, OVL_XATTR_PROTATTR);
739 		if (err == -EOPNOTSUPP || err == -ENODATA)
740 			err = 0;
741 	}
742 	if (err)
743 		return err;
744 
745 	inode_set_flags(inode, iflags, OVL_PROT_I_FLAGS_MASK);
746 
747 	/* Mask out the fileattr flags that should not be set in upper inode */
748 	fa->flags &= ~OVL_PROT_FS_FLAGS_MASK;
749 	fa->fsx_xflags &= ~OVL_PROT_FSX_FLAGS_MASK;
750 
751 	return 0;
752 }
753 
754 /**
755  * Caller must hold a reference to inode to prevent it from being freed while
756  * it is marked inuse.
757  */
758 bool ovl_inuse_trylock(struct dentry *dentry)
759 {
760 	struct inode *inode = d_inode(dentry);
761 	bool locked = false;
762 
763 	spin_lock(&inode->i_lock);
764 	if (!(inode->i_state & I_OVL_INUSE)) {
765 		inode->i_state |= I_OVL_INUSE;
766 		locked = true;
767 	}
768 	spin_unlock(&inode->i_lock);
769 
770 	return locked;
771 }
772 
773 void ovl_inuse_unlock(struct dentry *dentry)
774 {
775 	if (dentry) {
776 		struct inode *inode = d_inode(dentry);
777 
778 		spin_lock(&inode->i_lock);
779 		WARN_ON(!(inode->i_state & I_OVL_INUSE));
780 		inode->i_state &= ~I_OVL_INUSE;
781 		spin_unlock(&inode->i_lock);
782 	}
783 }
784 
785 bool ovl_is_inuse(struct dentry *dentry)
786 {
787 	struct inode *inode = d_inode(dentry);
788 	bool inuse;
789 
790 	spin_lock(&inode->i_lock);
791 	inuse = (inode->i_state & I_OVL_INUSE);
792 	spin_unlock(&inode->i_lock);
793 
794 	return inuse;
795 }
796 
797 /*
798  * Does this overlay dentry need to be indexed on copy up?
799  */
800 bool ovl_need_index(struct dentry *dentry)
801 {
802 	struct dentry *lower = ovl_dentry_lower(dentry);
803 
804 	if (!lower || !ovl_indexdir(dentry->d_sb))
805 		return false;
806 
807 	/* Index all files for NFS export and consistency verification */
808 	if (ovl_index_all(dentry->d_sb))
809 		return true;
810 
811 	/* Index only lower hardlinks on copy up */
812 	if (!d_is_dir(lower) && d_inode(lower)->i_nlink > 1)
813 		return true;
814 
815 	return false;
816 }
817 
818 /* Caller must hold OVL_I(inode)->lock */
819 static void ovl_cleanup_index(struct dentry *dentry)
820 {
821 	struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
822 	struct dentry *indexdir = ovl_indexdir(dentry->d_sb);
823 	struct inode *dir = indexdir->d_inode;
824 	struct dentry *lowerdentry = ovl_dentry_lower(dentry);
825 	struct dentry *upperdentry = ovl_dentry_upper(dentry);
826 	struct dentry *index = NULL;
827 	struct inode *inode;
828 	struct qstr name = { };
829 	int err;
830 
831 	err = ovl_get_index_name(ofs, lowerdentry, &name);
832 	if (err)
833 		goto fail;
834 
835 	inode = d_inode(upperdentry);
836 	if (!S_ISDIR(inode->i_mode) && inode->i_nlink != 1) {
837 		pr_warn_ratelimited("cleanup linked index (%pd2, ino=%lu, nlink=%u)\n",
838 				    upperdentry, inode->i_ino, inode->i_nlink);
839 		/*
840 		 * We either have a bug with persistent union nlink or a lower
841 		 * hardlink was added while overlay is mounted. Adding a lower
842 		 * hardlink and then unlinking all overlay hardlinks would drop
843 		 * overlay nlink to zero before all upper inodes are unlinked.
844 		 * As a safety measure, when that situation is detected, set
845 		 * the overlay nlink to the index inode nlink minus one for the
846 		 * index entry itself.
847 		 */
848 		set_nlink(d_inode(dentry), inode->i_nlink - 1);
849 		ovl_set_nlink_upper(dentry);
850 		goto out;
851 	}
852 
853 	inode_lock_nested(dir, I_MUTEX_PARENT);
854 	index = ovl_lookup_upper(ofs, name.name, indexdir, name.len);
855 	err = PTR_ERR(index);
856 	if (IS_ERR(index)) {
857 		index = NULL;
858 	} else if (ovl_index_all(dentry->d_sb)) {
859 		/* Whiteout orphan index to block future open by handle */
860 		err = ovl_cleanup_and_whiteout(OVL_FS(dentry->d_sb),
861 					       dir, index);
862 	} else {
863 		/* Cleanup orphan index entries */
864 		err = ovl_cleanup(ofs, dir, index);
865 	}
866 
867 	inode_unlock(dir);
868 	if (err)
869 		goto fail;
870 
871 out:
872 	kfree(name.name);
873 	dput(index);
874 	return;
875 
876 fail:
877 	pr_err("cleanup index of '%pd2' failed (%i)\n", dentry, err);
878 	goto out;
879 }
880 
881 /*
882  * Operations that change overlay inode and upper inode nlink need to be
883  * synchronized with copy up for persistent nlink accounting.
884  */
885 int ovl_nlink_start(struct dentry *dentry)
886 {
887 	struct inode *inode = d_inode(dentry);
888 	const struct cred *old_cred;
889 	int err;
890 
891 	if (WARN_ON(!inode))
892 		return -ENOENT;
893 
894 	/*
895 	 * With inodes index is enabled, we store the union overlay nlink
896 	 * in an xattr on the index inode. When whiting out an indexed lower,
897 	 * we need to decrement the overlay persistent nlink, but before the
898 	 * first copy up, we have no upper index inode to store the xattr.
899 	 *
900 	 * As a workaround, before whiteout/rename over an indexed lower,
901 	 * copy up to create the upper index. Creating the upper index will
902 	 * initialize the overlay nlink, so it could be dropped if unlink
903 	 * or rename succeeds.
904 	 *
905 	 * TODO: implement metadata only index copy up when called with
906 	 *       ovl_copy_up_flags(dentry, O_PATH).
907 	 */
908 	if (ovl_need_index(dentry) && !ovl_dentry_has_upper_alias(dentry)) {
909 		err = ovl_copy_up(dentry);
910 		if (err)
911 			return err;
912 	}
913 
914 	err = ovl_inode_lock_interruptible(inode);
915 	if (err)
916 		return err;
917 
918 	if (d_is_dir(dentry) || !ovl_test_flag(OVL_INDEX, inode))
919 		goto out;
920 
921 	old_cred = ovl_override_creds(dentry->d_sb);
922 	/*
923 	 * The overlay inode nlink should be incremented/decremented IFF the
924 	 * upper operation succeeds, along with nlink change of upper inode.
925 	 * Therefore, before link/unlink/rename, we store the union nlink
926 	 * value relative to the upper inode nlink in an upper inode xattr.
927 	 */
928 	err = ovl_set_nlink_upper(dentry);
929 	revert_creds(old_cred);
930 
931 out:
932 	if (err)
933 		ovl_inode_unlock(inode);
934 
935 	return err;
936 }
937 
938 void ovl_nlink_end(struct dentry *dentry)
939 {
940 	struct inode *inode = d_inode(dentry);
941 
942 	if (ovl_test_flag(OVL_INDEX, inode) && inode->i_nlink == 0) {
943 		const struct cred *old_cred;
944 
945 		old_cred = ovl_override_creds(dentry->d_sb);
946 		ovl_cleanup_index(dentry);
947 		revert_creds(old_cred);
948 	}
949 
950 	ovl_inode_unlock(inode);
951 }
952 
953 int ovl_lock_rename_workdir(struct dentry *workdir, struct dentry *upperdir)
954 {
955 	/* Workdir should not be the same as upperdir */
956 	if (workdir == upperdir)
957 		goto err;
958 
959 	/* Workdir should not be subdir of upperdir and vice versa */
960 	if (lock_rename(workdir, upperdir) != NULL)
961 		goto err_unlock;
962 
963 	return 0;
964 
965 err_unlock:
966 	unlock_rename(workdir, upperdir);
967 err:
968 	pr_err("failed to lock workdir+upperdir\n");
969 	return -EIO;
970 }
971 
972 /* err < 0, 0 if no metacopy xattr, 1 if metacopy xattr found */
973 int ovl_check_metacopy_xattr(struct ovl_fs *ofs, const struct path *path)
974 {
975 	int res;
976 
977 	/* Only regular files can have metacopy xattr */
978 	if (!S_ISREG(d_inode(path->dentry)->i_mode))
979 		return 0;
980 
981 	res = ovl_path_getxattr(ofs, path, OVL_XATTR_METACOPY, NULL, 0);
982 	if (res < 0) {
983 		if (res == -ENODATA || res == -EOPNOTSUPP)
984 			return 0;
985 		/*
986 		 * getxattr on user.* may fail with EACCES in case there's no
987 		 * read permission on the inode.  Not much we can do, other than
988 		 * tell the caller that this is not a metacopy inode.
989 		 */
990 		if (ofs->config.userxattr && res == -EACCES)
991 			return 0;
992 		goto out;
993 	}
994 
995 	return 1;
996 out:
997 	pr_warn_ratelimited("failed to get metacopy (%i)\n", res);
998 	return res;
999 }
1000 
1001 bool ovl_is_metacopy_dentry(struct dentry *dentry)
1002 {
1003 	struct ovl_entry *oe = dentry->d_fsdata;
1004 
1005 	if (!d_is_reg(dentry))
1006 		return false;
1007 
1008 	if (ovl_dentry_upper(dentry)) {
1009 		if (!ovl_has_upperdata(d_inode(dentry)))
1010 			return true;
1011 		return false;
1012 	}
1013 
1014 	return (oe->numlower > 1);
1015 }
1016 
1017 char *ovl_get_redirect_xattr(struct ovl_fs *ofs, const struct path *path, int padding)
1018 {
1019 	int res;
1020 	char *s, *next, *buf = NULL;
1021 
1022 	res = ovl_path_getxattr(ofs, path, OVL_XATTR_REDIRECT, NULL, 0);
1023 	if (res == -ENODATA || res == -EOPNOTSUPP)
1024 		return NULL;
1025 	if (res < 0)
1026 		goto fail;
1027 	if (res == 0)
1028 		goto invalid;
1029 
1030 	buf = kzalloc(res + padding + 1, GFP_KERNEL);
1031 	if (!buf)
1032 		return ERR_PTR(-ENOMEM);
1033 
1034 	res = ovl_path_getxattr(ofs, path, OVL_XATTR_REDIRECT, buf, res);
1035 	if (res < 0)
1036 		goto fail;
1037 	if (res == 0)
1038 		goto invalid;
1039 
1040 	if (buf[0] == '/') {
1041 		for (s = buf; *s++ == '/'; s = next) {
1042 			next = strchrnul(s, '/');
1043 			if (s == next)
1044 				goto invalid;
1045 		}
1046 	} else {
1047 		if (strchr(buf, '/') != NULL)
1048 			goto invalid;
1049 	}
1050 
1051 	return buf;
1052 invalid:
1053 	pr_warn_ratelimited("invalid redirect (%s)\n", buf);
1054 	res = -EINVAL;
1055 	goto err_free;
1056 fail:
1057 	pr_warn_ratelimited("failed to get redirect (%i)\n", res);
1058 err_free:
1059 	kfree(buf);
1060 	return ERR_PTR(res);
1061 }
1062 
1063 /*
1064  * ovl_sync_status() - Check fs sync status for volatile mounts
1065  *
1066  * Returns 1 if this is not a volatile mount and a real sync is required.
1067  *
1068  * Returns 0 if syncing can be skipped because mount is volatile, and no errors
1069  * have occurred on the upperdir since the mount.
1070  *
1071  * Returns -errno if it is a volatile mount, and the error that occurred since
1072  * the last mount. If the error code changes, it'll return the latest error
1073  * code.
1074  */
1075 
1076 int ovl_sync_status(struct ovl_fs *ofs)
1077 {
1078 	struct vfsmount *mnt;
1079 
1080 	if (ovl_should_sync(ofs))
1081 		return 1;
1082 
1083 	mnt = ovl_upper_mnt(ofs);
1084 	if (!mnt)
1085 		return 0;
1086 
1087 	return errseq_check(&mnt->mnt_sb->s_wb_err, ofs->errseq);
1088 }
1089 
1090 /*
1091  * ovl_copyattr() - copy inode attributes from layer to ovl inode
1092  *
1093  * When overlay copies inode information from an upper or lower layer to the
1094  * relevant overlay inode it will apply the idmapping of the upper or lower
1095  * layer when doing so ensuring that the ovl inode ownership will correctly
1096  * reflect the ownership of the idmapped upper or lower layer. For example, an
1097  * idmapped upper or lower layer mapping id 1001 to id 1000 will take care to
1098  * map any lower or upper inode owned by id 1001 to id 1000. These mapping
1099  * helpers are nops when the relevant layer isn't idmapped.
1100  */
1101 void ovl_copyattr(struct inode *inode)
1102 {
1103 	struct path realpath;
1104 	struct inode *realinode;
1105 	struct user_namespace *real_mnt_userns;
1106 	vfsuid_t vfsuid;
1107 	vfsgid_t vfsgid;
1108 
1109 	ovl_i_path_real(inode, &realpath);
1110 	realinode = d_inode(realpath.dentry);
1111 	real_mnt_userns = mnt_user_ns(realpath.mnt);
1112 
1113 	vfsuid = i_uid_into_vfsuid(real_mnt_userns, realinode);
1114 	vfsgid = i_gid_into_vfsgid(real_mnt_userns, realinode);
1115 
1116 	inode->i_uid = vfsuid_into_kuid(vfsuid);
1117 	inode->i_gid = vfsgid_into_kgid(vfsgid);
1118 	inode->i_mode = realinode->i_mode;
1119 	inode->i_atime = realinode->i_atime;
1120 	inode->i_mtime = realinode->i_mtime;
1121 	inode->i_ctime = realinode->i_ctime;
1122 	i_size_write(inode, i_size_read(realinode));
1123 }
1124