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