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