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