xref: /linux/fs/overlayfs/copy_up.c (revision c8b90d40d5bba8e6fba457b8a7c10d3c0d467e37)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *
4  * Copyright (C) 2011 Novell Inc.
5  */
6 
7 #include <linux/module.h>
8 #include <linux/fs.h>
9 #include <linux/slab.h>
10 #include <linux/file.h>
11 #include <linux/fileattr.h>
12 #include <linux/splice.h>
13 #include <linux/xattr.h>
14 #include <linux/security.h>
15 #include <linux/uaccess.h>
16 #include <linux/sched/signal.h>
17 #include <linux/cred.h>
18 #include <linux/namei.h>
19 #include <linux/ratelimit.h>
20 #include <linux/exportfs.h>
21 #include "overlayfs.h"
22 
23 #define OVL_COPY_UP_CHUNK_SIZE (1 << 20)
24 
25 static int ovl_ccup_set(const char *buf, const struct kernel_param *param)
26 {
27 	pr_warn("\"check_copy_up\" module option is obsolete\n");
28 	return 0;
29 }
30 
31 static int ovl_ccup_get(char *buf, const struct kernel_param *param)
32 {
33 	return sprintf(buf, "N\n");
34 }
35 
36 module_param_call(check_copy_up, ovl_ccup_set, ovl_ccup_get, NULL, 0644);
37 MODULE_PARM_DESC(check_copy_up, "Obsolete; does nothing");
38 
39 static bool ovl_must_copy_xattr(const char *name)
40 {
41 	return !strcmp(name, XATTR_POSIX_ACL_ACCESS) ||
42 	       !strcmp(name, XATTR_POSIX_ACL_DEFAULT) ||
43 	       !strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN);
44 }
45 
46 static int ovl_copy_acl(struct ovl_fs *ofs, const struct path *path,
47 			struct dentry *dentry, const char *acl_name)
48 {
49 	int err;
50 	struct posix_acl *clone, *real_acl = NULL;
51 
52 	real_acl = ovl_get_acl_path(path, acl_name, false);
53 	if (!real_acl)
54 		return 0;
55 
56 	if (IS_ERR(real_acl)) {
57 		err = PTR_ERR(real_acl);
58 		if (err == -ENODATA || err == -EOPNOTSUPP)
59 			return 0;
60 		return err;
61 	}
62 
63 	clone = posix_acl_clone(real_acl, GFP_KERNEL);
64 	posix_acl_release(real_acl); /* release original acl */
65 	if (!clone)
66 		return -ENOMEM;
67 
68 	err = ovl_do_set_acl(ofs, dentry, acl_name, clone);
69 
70 	/* release cloned acl */
71 	posix_acl_release(clone);
72 	return err;
73 }
74 
75 int ovl_copy_xattr(struct super_block *sb, const struct path *oldpath, struct dentry *new)
76 {
77 	struct dentry *old = oldpath->dentry;
78 	ssize_t list_size, size, value_size = 0;
79 	char *buf, *name, *value = NULL;
80 	int error = 0;
81 	size_t slen;
82 
83 	if (!old->d_inode->i_op->listxattr || !new->d_inode->i_op->listxattr)
84 		return 0;
85 
86 	list_size = vfs_listxattr(old, NULL, 0);
87 	if (list_size <= 0) {
88 		if (list_size == -EOPNOTSUPP)
89 			return 0;
90 		return list_size;
91 	}
92 
93 	buf = kvzalloc(list_size, GFP_KERNEL);
94 	if (!buf)
95 		return -ENOMEM;
96 
97 	list_size = vfs_listxattr(old, buf, list_size);
98 	if (list_size <= 0) {
99 		error = list_size;
100 		goto out;
101 	}
102 
103 	for (name = buf; list_size; name += slen) {
104 		slen = strnlen(name, list_size) + 1;
105 
106 		/* underlying fs providing us with an broken xattr list? */
107 		if (WARN_ON(slen > list_size)) {
108 			error = -EIO;
109 			break;
110 		}
111 		list_size -= slen;
112 
113 		if (ovl_is_private_xattr(sb, name))
114 			continue;
115 
116 		error = security_inode_copy_up_xattr(old, name);
117 		if (error == -ECANCELED) {
118 			error = 0;
119 			continue; /* Discard */
120 		}
121 		if (error < 0 && error != -EOPNOTSUPP)
122 			break;
123 
124 		if (is_posix_acl_xattr(name)) {
125 			error = ovl_copy_acl(OVL_FS(sb), oldpath, new, name);
126 			if (!error)
127 				continue;
128 			/* POSIX ACLs must be copied. */
129 			break;
130 		}
131 
132 retry:
133 		size = ovl_do_getxattr(oldpath, name, value, value_size);
134 		if (size == -ERANGE)
135 			size = ovl_do_getxattr(oldpath, name, NULL, 0);
136 
137 		if (size < 0) {
138 			error = size;
139 			break;
140 		}
141 
142 		if (size > value_size) {
143 			void *new;
144 
145 			new = kvmalloc(size, GFP_KERNEL);
146 			if (!new) {
147 				error = -ENOMEM;
148 				break;
149 			}
150 			kvfree(value);
151 			value = new;
152 			value_size = size;
153 			goto retry;
154 		}
155 
156 		error = ovl_do_setxattr(OVL_FS(sb), new, name, value, size, 0);
157 		if (error) {
158 			if (error != -EOPNOTSUPP || ovl_must_copy_xattr(name))
159 				break;
160 
161 			/* Ignore failure to copy unknown xattrs */
162 			error = 0;
163 		}
164 	}
165 	kvfree(value);
166 out:
167 	kvfree(buf);
168 	return error;
169 }
170 
171 static int ovl_copy_fileattr(struct inode *inode, const struct path *old,
172 			     const struct path *new)
173 {
174 	struct fileattr oldfa = { .flags_valid = true };
175 	struct fileattr newfa = { .flags_valid = true };
176 	int err;
177 
178 	err = ovl_real_fileattr_get(old, &oldfa);
179 	if (err) {
180 		/* Ntfs-3g returns -EINVAL for "no fileattr support" */
181 		if (err == -ENOTTY || err == -EINVAL)
182 			return 0;
183 		pr_warn("failed to retrieve lower fileattr (%pd2, err=%i)\n",
184 			old->dentry, err);
185 		return err;
186 	}
187 
188 	/*
189 	 * We cannot set immutable and append-only flags on upper inode,
190 	 * because we would not be able to link upper inode to upper dir
191 	 * not set overlay private xattr on upper inode.
192 	 * Store these flags in overlay.protattr xattr instead.
193 	 */
194 	if (oldfa.flags & OVL_PROT_FS_FLAGS_MASK) {
195 		err = ovl_set_protattr(inode, new->dentry, &oldfa);
196 		if (err == -EPERM)
197 			pr_warn_once("copying fileattr: no xattr on upper\n");
198 		else if (err)
199 			return err;
200 	}
201 
202 	/* Don't bother copying flags if none are set */
203 	if (!(oldfa.flags & OVL_COPY_FS_FLAGS_MASK))
204 		return 0;
205 
206 	err = ovl_real_fileattr_get(new, &newfa);
207 	if (err) {
208 		/*
209 		 * Returning an error if upper doesn't support fileattr will
210 		 * result in a regression, so revert to the old behavior.
211 		 */
212 		if (err == -ENOTTY || err == -EINVAL) {
213 			pr_warn_once("copying fileattr: no support on upper\n");
214 			return 0;
215 		}
216 		pr_warn("failed to retrieve upper fileattr (%pd2, err=%i)\n",
217 			new->dentry, err);
218 		return err;
219 	}
220 
221 	BUILD_BUG_ON(OVL_COPY_FS_FLAGS_MASK & ~FS_COMMON_FL);
222 	newfa.flags &= ~OVL_COPY_FS_FLAGS_MASK;
223 	newfa.flags |= (oldfa.flags & OVL_COPY_FS_FLAGS_MASK);
224 
225 	BUILD_BUG_ON(OVL_COPY_FSX_FLAGS_MASK & ~FS_XFLAG_COMMON);
226 	newfa.fsx_xflags &= ~OVL_COPY_FSX_FLAGS_MASK;
227 	newfa.fsx_xflags |= (oldfa.fsx_xflags & OVL_COPY_FSX_FLAGS_MASK);
228 
229 	return ovl_real_fileattr_set(new, &newfa);
230 }
231 
232 static int ovl_verify_area(loff_t pos, loff_t pos2, loff_t len, loff_t totlen)
233 {
234 	loff_t tmp;
235 
236 	if (pos != pos2)
237 		return -EIO;
238 	if (pos < 0 || len < 0 || totlen < 0)
239 		return -EIO;
240 	if (check_add_overflow(pos, len, &tmp))
241 		return -EIO;
242 	return 0;
243 }
244 
245 static int ovl_sync_file(struct path *path)
246 {
247 	struct file *new_file;
248 	int err;
249 
250 	new_file = ovl_path_open(path, O_LARGEFILE | O_RDONLY);
251 	if (IS_ERR(new_file))
252 		return PTR_ERR(new_file);
253 
254 	err = vfs_fsync(new_file, 0);
255 	fput(new_file);
256 
257 	return err;
258 }
259 
260 static int ovl_copy_up_file(struct ovl_fs *ofs, struct dentry *dentry,
261 			    struct file *new_file, loff_t len,
262 			    bool datasync)
263 {
264 	struct path datapath;
265 	struct file *old_file;
266 	loff_t old_pos = 0;
267 	loff_t new_pos = 0;
268 	loff_t cloned;
269 	loff_t data_pos = -1;
270 	loff_t hole_len;
271 	bool skip_hole = false;
272 	int error = 0;
273 
274 	ovl_path_lowerdata(dentry, &datapath);
275 	if (WARN_ON_ONCE(datapath.dentry == NULL) ||
276 	    WARN_ON_ONCE(len < 0))
277 		return -EIO;
278 
279 	old_file = ovl_path_open(&datapath, O_LARGEFILE | O_RDONLY);
280 	if (IS_ERR(old_file))
281 		return PTR_ERR(old_file);
282 
283 	/* Try to use clone_file_range to clone up within the same fs */
284 	cloned = vfs_clone_file_range(old_file, 0, new_file, 0, len, 0);
285 	if (cloned == len)
286 		goto out_fput;
287 
288 	/* Couldn't clone, so now we try to copy the data */
289 	error = rw_verify_area(READ, old_file, &old_pos, len);
290 	if (!error)
291 		error = rw_verify_area(WRITE, new_file, &new_pos, len);
292 	if (error)
293 		goto out_fput;
294 
295 	/* Check if lower fs supports seek operation */
296 	if (old_file->f_mode & FMODE_LSEEK)
297 		skip_hole = true;
298 
299 	while (len) {
300 		size_t this_len = OVL_COPY_UP_CHUNK_SIZE;
301 		ssize_t bytes;
302 
303 		if (len < this_len)
304 			this_len = len;
305 
306 		if (signal_pending_state(TASK_KILLABLE, current)) {
307 			error = -EINTR;
308 			break;
309 		}
310 
311 		/*
312 		 * Fill zero for hole will cost unnecessary disk space
313 		 * and meanwhile slow down the copy-up speed, so we do
314 		 * an optimization for hole during copy-up, it relies
315 		 * on SEEK_DATA implementation in lower fs so if lower
316 		 * fs does not support it, copy-up will behave as before.
317 		 *
318 		 * Detail logic of hole detection as below:
319 		 * When we detect next data position is larger than current
320 		 * position we will skip that hole, otherwise we copy
321 		 * data in the size of OVL_COPY_UP_CHUNK_SIZE. Actually,
322 		 * it may not recognize all kind of holes and sometimes
323 		 * only skips partial of hole area. However, it will be
324 		 * enough for most of the use cases.
325 		 *
326 		 * We do not hold upper sb_writers throughout the loop to avert
327 		 * lockdep warning with llseek of lower file in nested overlay:
328 		 * - upper sb_writers
329 		 * -- lower ovl_inode_lock (ovl_llseek)
330 		 */
331 		if (skip_hole && data_pos < old_pos) {
332 			data_pos = vfs_llseek(old_file, old_pos, SEEK_DATA);
333 			if (data_pos > old_pos) {
334 				hole_len = data_pos - old_pos;
335 				len -= hole_len;
336 				old_pos = new_pos = data_pos;
337 				continue;
338 			} else if (data_pos == -ENXIO) {
339 				break;
340 			} else if (data_pos < 0) {
341 				skip_hole = false;
342 			}
343 		}
344 
345 		error = ovl_verify_area(old_pos, new_pos, this_len, len);
346 		if (error)
347 			break;
348 
349 		bytes = do_splice_direct(old_file, &old_pos,
350 					 new_file, &new_pos,
351 					 this_len, SPLICE_F_MOVE);
352 		if (bytes <= 0) {
353 			error = bytes;
354 			break;
355 		}
356 		WARN_ON(old_pos != new_pos);
357 
358 		len -= bytes;
359 	}
360 	/* call fsync once, either now or later along with metadata */
361 	if (!error && ovl_should_sync(ofs) && datasync)
362 		error = vfs_fsync(new_file, 0);
363 out_fput:
364 	fput(old_file);
365 	return error;
366 }
367 
368 static int ovl_set_size(struct ovl_fs *ofs,
369 			struct dentry *upperdentry, struct kstat *stat)
370 {
371 	struct iattr attr = {
372 		.ia_valid = ATTR_SIZE,
373 		.ia_size = stat->size,
374 	};
375 
376 	return ovl_do_notify_change(ofs, upperdentry, &attr);
377 }
378 
379 static int ovl_set_timestamps(struct ovl_fs *ofs, struct dentry *upperdentry,
380 			      struct kstat *stat)
381 {
382 	struct iattr attr = {
383 		.ia_valid =
384 		     ATTR_ATIME | ATTR_MTIME | ATTR_ATIME_SET | ATTR_MTIME_SET | ATTR_CTIME,
385 		.ia_atime = stat->atime,
386 		.ia_mtime = stat->mtime,
387 	};
388 
389 	return ovl_do_notify_change(ofs, upperdentry, &attr);
390 }
391 
392 int ovl_set_attr(struct ovl_fs *ofs, struct dentry *upperdentry,
393 		 struct kstat *stat)
394 {
395 	int err = 0;
396 
397 	if (!S_ISLNK(stat->mode)) {
398 		struct iattr attr = {
399 			.ia_valid = ATTR_MODE,
400 			.ia_mode = stat->mode,
401 		};
402 		err = ovl_do_notify_change(ofs, upperdentry, &attr);
403 	}
404 	if (!err) {
405 		struct iattr attr = {
406 			.ia_valid = ATTR_UID | ATTR_GID,
407 			.ia_vfsuid = VFSUIDT_INIT(stat->uid),
408 			.ia_vfsgid = VFSGIDT_INIT(stat->gid),
409 		};
410 		err = ovl_do_notify_change(ofs, upperdentry, &attr);
411 	}
412 	if (!err)
413 		ovl_set_timestamps(ofs, upperdentry, stat);
414 
415 	return err;
416 }
417 
418 struct ovl_fh *ovl_encode_real_fh(struct ovl_fs *ofs, struct dentry *real,
419 				  bool is_upper)
420 {
421 	struct ovl_fh *fh;
422 	int fh_type, dwords;
423 	int buflen = MAX_HANDLE_SZ;
424 	uuid_t *uuid = &real->d_sb->s_uuid;
425 	int err;
426 
427 	/* Make sure the real fid stays 32bit aligned */
428 	BUILD_BUG_ON(OVL_FH_FID_OFFSET % 4);
429 	BUILD_BUG_ON(MAX_HANDLE_SZ + OVL_FH_FID_OFFSET > 255);
430 
431 	fh = kzalloc(buflen + OVL_FH_FID_OFFSET, GFP_KERNEL);
432 	if (!fh)
433 		return ERR_PTR(-ENOMEM);
434 
435 	/*
436 	 * We encode a non-connectable file handle for non-dir, because we
437 	 * only need to find the lower inode number and we don't want to pay
438 	 * the price or reconnecting the dentry.
439 	 */
440 	dwords = buflen >> 2;
441 	fh_type = exportfs_encode_fh(real, (void *)fh->fb.fid, &dwords, 0);
442 	buflen = (dwords << 2);
443 
444 	err = -EIO;
445 	if (fh_type < 0 || fh_type == FILEID_INVALID ||
446 	    WARN_ON(buflen > MAX_HANDLE_SZ))
447 		goto out_err;
448 
449 	fh->fb.version = OVL_FH_VERSION;
450 	fh->fb.magic = OVL_FH_MAGIC;
451 	fh->fb.type = fh_type;
452 	fh->fb.flags = OVL_FH_FLAG_CPU_ENDIAN;
453 	/*
454 	 * When we will want to decode an overlay dentry from this handle
455 	 * and all layers are on the same fs, if we get a disconncted real
456 	 * dentry when we decode fid, the only way to tell if we should assign
457 	 * it to upperdentry or to lowerstack is by checking this flag.
458 	 */
459 	if (is_upper)
460 		fh->fb.flags |= OVL_FH_FLAG_PATH_UPPER;
461 	fh->fb.len = sizeof(fh->fb) + buflen;
462 	if (ovl_origin_uuid(ofs))
463 		fh->fb.uuid = *uuid;
464 
465 	return fh;
466 
467 out_err:
468 	kfree(fh);
469 	return ERR_PTR(err);
470 }
471 
472 struct ovl_fh *ovl_get_origin_fh(struct ovl_fs *ofs, struct dentry *origin)
473 {
474 	/*
475 	 * When lower layer doesn't support export operations store a 'null' fh,
476 	 * so we can use the overlay.origin xattr to distignuish between a copy
477 	 * up and a pure upper inode.
478 	 */
479 	if (!ovl_can_decode_fh(origin->d_sb))
480 		return NULL;
481 
482 	return ovl_encode_real_fh(ofs, origin, false);
483 }
484 
485 int ovl_set_origin_fh(struct ovl_fs *ofs, const struct ovl_fh *fh,
486 		      struct dentry *upper)
487 {
488 	int err;
489 
490 	/*
491 	 * Do not fail when upper doesn't support xattrs.
492 	 */
493 	err = ovl_check_setxattr(ofs, upper, OVL_XATTR_ORIGIN, fh->buf,
494 				 fh ? fh->fb.len : 0, 0);
495 
496 	/* Ignore -EPERM from setting "user.*" on symlink/special */
497 	return err == -EPERM ? 0 : err;
498 }
499 
500 /* Store file handle of @upper dir in @index dir entry */
501 static int ovl_set_upper_fh(struct ovl_fs *ofs, struct dentry *upper,
502 			    struct dentry *index)
503 {
504 	const struct ovl_fh *fh;
505 	int err;
506 
507 	fh = ovl_encode_real_fh(ofs, upper, true);
508 	if (IS_ERR(fh))
509 		return PTR_ERR(fh);
510 
511 	err = ovl_setxattr(ofs, index, OVL_XATTR_UPPER, fh->buf, fh->fb.len);
512 
513 	kfree(fh);
514 	return err;
515 }
516 
517 /*
518  * Create and install index entry.
519  *
520  * Caller must hold i_mutex on indexdir.
521  */
522 static int ovl_create_index(struct dentry *dentry, const struct ovl_fh *fh,
523 			    struct dentry *upper)
524 {
525 	struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
526 	struct dentry *indexdir = ovl_indexdir(dentry->d_sb);
527 	struct inode *dir = d_inode(indexdir);
528 	struct dentry *index = NULL;
529 	struct dentry *temp = NULL;
530 	struct qstr name = { };
531 	int err;
532 
533 	/*
534 	 * For now this is only used for creating index entry for directories,
535 	 * because non-dir are copied up directly to index and then hardlinked
536 	 * to upper dir.
537 	 *
538 	 * TODO: implement create index for non-dir, so we can call it when
539 	 * encoding file handle for non-dir in case index does not exist.
540 	 */
541 	if (WARN_ON(!d_is_dir(dentry)))
542 		return -EIO;
543 
544 	/* Directory not expected to be indexed before copy up */
545 	if (WARN_ON(ovl_test_flag(OVL_INDEX, d_inode(dentry))))
546 		return -EIO;
547 
548 	err = ovl_get_index_name_fh(fh, &name);
549 	if (err)
550 		return err;
551 
552 	temp = ovl_create_temp(ofs, indexdir, OVL_CATTR(S_IFDIR | 0));
553 	err = PTR_ERR(temp);
554 	if (IS_ERR(temp))
555 		goto free_name;
556 
557 	err = ovl_set_upper_fh(ofs, upper, temp);
558 	if (err)
559 		goto out;
560 
561 	index = ovl_lookup_upper(ofs, name.name, indexdir, name.len);
562 	if (IS_ERR(index)) {
563 		err = PTR_ERR(index);
564 	} else {
565 		err = ovl_do_rename(ofs, dir, temp, dir, index, 0);
566 		dput(index);
567 	}
568 out:
569 	if (err)
570 		ovl_cleanup(ofs, dir, temp);
571 	dput(temp);
572 free_name:
573 	kfree(name.name);
574 	return err;
575 }
576 
577 struct ovl_copy_up_ctx {
578 	struct dentry *parent;
579 	struct dentry *dentry;
580 	struct path lowerpath;
581 	struct kstat stat;
582 	struct kstat pstat;
583 	const char *link;
584 	struct dentry *destdir;
585 	struct qstr destname;
586 	struct dentry *workdir;
587 	const struct ovl_fh *origin_fh;
588 	bool origin;
589 	bool indexed;
590 	bool metacopy;
591 	bool metacopy_digest;
592 	bool metadata_fsync;
593 };
594 
595 static int ovl_link_up(struct ovl_copy_up_ctx *c)
596 {
597 	int err;
598 	struct dentry *upper;
599 	struct dentry *upperdir = ovl_dentry_upper(c->parent);
600 	struct ovl_fs *ofs = OVL_FS(c->dentry->d_sb);
601 	struct inode *udir = d_inode(upperdir);
602 
603 	ovl_start_write(c->dentry);
604 
605 	/* Mark parent "impure" because it may now contain non-pure upper */
606 	err = ovl_set_impure(c->parent, upperdir);
607 	if (err)
608 		goto out;
609 
610 	err = ovl_set_nlink_lower(c->dentry);
611 	if (err)
612 		goto out;
613 
614 	inode_lock_nested(udir, I_MUTEX_PARENT);
615 	upper = ovl_lookup_upper(ofs, c->dentry->d_name.name, upperdir,
616 				 c->dentry->d_name.len);
617 	err = PTR_ERR(upper);
618 	if (!IS_ERR(upper)) {
619 		err = ovl_do_link(ofs, ovl_dentry_upper(c->dentry), udir, upper);
620 		dput(upper);
621 
622 		if (!err) {
623 			/* Restore timestamps on parent (best effort) */
624 			ovl_set_timestamps(ofs, upperdir, &c->pstat);
625 			ovl_dentry_set_upper_alias(c->dentry);
626 			ovl_dentry_update_reval(c->dentry, upper);
627 		}
628 	}
629 	inode_unlock(udir);
630 	if (err)
631 		goto out;
632 
633 	err = ovl_set_nlink_upper(c->dentry);
634 
635 out:
636 	ovl_end_write(c->dentry);
637 	return err;
638 }
639 
640 static int ovl_copy_up_data(struct ovl_copy_up_ctx *c, const struct path *temp)
641 {
642 	struct ovl_fs *ofs = OVL_FS(c->dentry->d_sb);
643 	struct file *new_file;
644 	int err;
645 
646 	if (!S_ISREG(c->stat.mode) || c->metacopy || !c->stat.size)
647 		return 0;
648 
649 	new_file = ovl_path_open(temp, O_LARGEFILE | O_WRONLY);
650 	if (IS_ERR(new_file))
651 		return PTR_ERR(new_file);
652 
653 	err = ovl_copy_up_file(ofs, c->dentry, new_file, c->stat.size,
654 			       !c->metadata_fsync);
655 	fput(new_file);
656 
657 	return err;
658 }
659 
660 static int ovl_copy_up_metadata(struct ovl_copy_up_ctx *c, struct dentry *temp)
661 {
662 	struct ovl_fs *ofs = OVL_FS(c->dentry->d_sb);
663 	struct inode *inode = d_inode(c->dentry);
664 	struct path upperpath = { .mnt = ovl_upper_mnt(ofs), .dentry = temp };
665 	int err;
666 
667 	err = ovl_copy_xattr(c->dentry->d_sb, &c->lowerpath, temp);
668 	if (err)
669 		return err;
670 
671 	if (inode->i_flags & OVL_COPY_I_FLAGS_MASK &&
672 	    (S_ISREG(c->stat.mode) || S_ISDIR(c->stat.mode))) {
673 		/*
674 		 * Copy the fileattr inode flags that are the source of already
675 		 * copied i_flags
676 		 */
677 		err = ovl_copy_fileattr(inode, &c->lowerpath, &upperpath);
678 		if (err)
679 			return err;
680 	}
681 
682 	/*
683 	 * Store identifier of lower inode in upper inode xattr to
684 	 * allow lookup of the copy up origin inode.
685 	 *
686 	 * Don't set origin when we are breaking the association with a lower
687 	 * hard link.
688 	 */
689 	if (c->origin) {
690 		err = ovl_set_origin_fh(ofs, c->origin_fh, temp);
691 		if (err)
692 			return err;
693 	}
694 
695 	if (c->metacopy) {
696 		struct path lowerdatapath;
697 		struct ovl_metacopy metacopy_data = OVL_METACOPY_INIT;
698 
699 		ovl_path_lowerdata(c->dentry, &lowerdatapath);
700 		if (WARN_ON_ONCE(lowerdatapath.dentry == NULL))
701 			return -EIO;
702 		err = ovl_get_verity_digest(ofs, &lowerdatapath, &metacopy_data);
703 		if (err)
704 			return err;
705 
706 		if (metacopy_data.digest_algo)
707 			c->metacopy_digest = true;
708 
709 		err = ovl_set_metacopy_xattr(ofs, temp, &metacopy_data);
710 		if (err)
711 			return err;
712 	}
713 
714 	inode_lock(temp->d_inode);
715 	if (S_ISREG(c->stat.mode))
716 		err = ovl_set_size(ofs, temp, &c->stat);
717 	if (!err)
718 		err = ovl_set_attr(ofs, temp, &c->stat);
719 	inode_unlock(temp->d_inode);
720 
721 	/* fsync metadata before moving it into upper dir */
722 	if (!err && ovl_should_sync(ofs) && c->metadata_fsync)
723 		err = ovl_sync_file(&upperpath);
724 
725 	return err;
726 }
727 
728 struct ovl_cu_creds {
729 	const struct cred *old;
730 	struct cred *new;
731 };
732 
733 static int ovl_prep_cu_creds(struct dentry *dentry, struct ovl_cu_creds *cc)
734 {
735 	int err;
736 
737 	cc->old = cc->new = NULL;
738 	err = security_inode_copy_up(dentry, &cc->new);
739 	if (err < 0)
740 		return err;
741 
742 	if (cc->new)
743 		cc->old = override_creds(cc->new);
744 
745 	return 0;
746 }
747 
748 static void ovl_revert_cu_creds(struct ovl_cu_creds *cc)
749 {
750 	if (cc->new) {
751 		revert_creds(cc->old);
752 		put_cred(cc->new);
753 	}
754 }
755 
756 /*
757  * Copyup using workdir to prepare temp file.  Used when copying up directories,
758  * special files or when upper fs doesn't support O_TMPFILE.
759  */
760 static int ovl_copy_up_workdir(struct ovl_copy_up_ctx *c)
761 {
762 	struct ovl_fs *ofs = OVL_FS(c->dentry->d_sb);
763 	struct inode *inode;
764 	struct inode *udir = d_inode(c->destdir), *wdir = d_inode(c->workdir);
765 	struct path path = { .mnt = ovl_upper_mnt(ofs) };
766 	struct dentry *temp, *upper, *trap;
767 	struct ovl_cu_creds cc;
768 	int err;
769 	struct ovl_cattr cattr = {
770 		/* Can't properly set mode on creation because of the umask */
771 		.mode = c->stat.mode & S_IFMT,
772 		.rdev = c->stat.rdev,
773 		.link = c->link
774 	};
775 
776 	err = ovl_prep_cu_creds(c->dentry, &cc);
777 	if (err)
778 		return err;
779 
780 	ovl_start_write(c->dentry);
781 	inode_lock(wdir);
782 	temp = ovl_create_temp(ofs, c->workdir, &cattr);
783 	inode_unlock(wdir);
784 	ovl_end_write(c->dentry);
785 	ovl_revert_cu_creds(&cc);
786 
787 	if (IS_ERR(temp))
788 		return PTR_ERR(temp);
789 
790 	/*
791 	 * Copy up data first and then xattrs. Writing data after
792 	 * xattrs will remove security.capability xattr automatically.
793 	 */
794 	path.dentry = temp;
795 	err = ovl_copy_up_data(c, &path);
796 	/*
797 	 * We cannot hold lock_rename() throughout this helper, because of
798 	 * lock ordering with sb_writers, which shouldn't be held when calling
799 	 * ovl_copy_up_data(), so lock workdir and destdir and make sure that
800 	 * temp wasn't moved before copy up completion or cleanup.
801 	 */
802 	ovl_start_write(c->dentry);
803 	trap = lock_rename(c->workdir, c->destdir);
804 	if (trap || temp->d_parent != c->workdir) {
805 		/* temp or workdir moved underneath us? abort without cleanup */
806 		dput(temp);
807 		err = -EIO;
808 		if (IS_ERR(trap))
809 			goto out;
810 		goto unlock;
811 	} else if (err) {
812 		goto cleanup;
813 	}
814 
815 	err = ovl_copy_up_metadata(c, temp);
816 	if (err)
817 		goto cleanup;
818 
819 	if (S_ISDIR(c->stat.mode) && c->indexed) {
820 		err = ovl_create_index(c->dentry, c->origin_fh, temp);
821 		if (err)
822 			goto cleanup;
823 	}
824 
825 	upper = ovl_lookup_upper(ofs, c->destname.name, c->destdir,
826 				 c->destname.len);
827 	err = PTR_ERR(upper);
828 	if (IS_ERR(upper))
829 		goto cleanup;
830 
831 	err = ovl_do_rename(ofs, wdir, temp, udir, upper, 0);
832 	dput(upper);
833 	if (err)
834 		goto cleanup;
835 
836 	inode = d_inode(c->dentry);
837 	if (c->metacopy_digest)
838 		ovl_set_flag(OVL_HAS_DIGEST, inode);
839 	else
840 		ovl_clear_flag(OVL_HAS_DIGEST, inode);
841 	ovl_clear_flag(OVL_VERIFIED_DIGEST, inode);
842 
843 	if (!c->metacopy)
844 		ovl_set_upperdata(inode);
845 	ovl_inode_update(inode, temp);
846 	if (S_ISDIR(inode->i_mode))
847 		ovl_set_flag(OVL_WHITEOUTS, inode);
848 unlock:
849 	unlock_rename(c->workdir, c->destdir);
850 out:
851 	ovl_end_write(c->dentry);
852 
853 	return err;
854 
855 cleanup:
856 	ovl_cleanup(ofs, wdir, temp);
857 	dput(temp);
858 	goto unlock;
859 }
860 
861 /* Copyup using O_TMPFILE which does not require cross dir locking */
862 static int ovl_copy_up_tmpfile(struct ovl_copy_up_ctx *c)
863 {
864 	struct ovl_fs *ofs = OVL_FS(c->dentry->d_sb);
865 	struct inode *udir = d_inode(c->destdir);
866 	struct dentry *temp, *upper;
867 	struct file *tmpfile;
868 	struct ovl_cu_creds cc;
869 	int err;
870 
871 	err = ovl_prep_cu_creds(c->dentry, &cc);
872 	if (err)
873 		return err;
874 
875 	ovl_start_write(c->dentry);
876 	tmpfile = ovl_do_tmpfile(ofs, c->workdir, c->stat.mode);
877 	ovl_end_write(c->dentry);
878 	ovl_revert_cu_creds(&cc);
879 	if (IS_ERR(tmpfile))
880 		return PTR_ERR(tmpfile);
881 
882 	temp = tmpfile->f_path.dentry;
883 	if (!c->metacopy && c->stat.size) {
884 		err = ovl_copy_up_file(ofs, c->dentry, tmpfile, c->stat.size,
885 				       !c->metadata_fsync);
886 		if (err)
887 			goto out_fput;
888 	}
889 
890 	ovl_start_write(c->dentry);
891 
892 	err = ovl_copy_up_metadata(c, temp);
893 	if (err)
894 		goto out;
895 
896 	inode_lock_nested(udir, I_MUTEX_PARENT);
897 
898 	upper = ovl_lookup_upper(ofs, c->destname.name, c->destdir,
899 				 c->destname.len);
900 	err = PTR_ERR(upper);
901 	if (!IS_ERR(upper)) {
902 		err = ovl_do_link(ofs, temp, udir, upper);
903 		dput(upper);
904 	}
905 	inode_unlock(udir);
906 
907 	if (err)
908 		goto out;
909 
910 	if (c->metacopy_digest)
911 		ovl_set_flag(OVL_HAS_DIGEST, d_inode(c->dentry));
912 	else
913 		ovl_clear_flag(OVL_HAS_DIGEST, d_inode(c->dentry));
914 	ovl_clear_flag(OVL_VERIFIED_DIGEST, d_inode(c->dentry));
915 
916 	if (!c->metacopy)
917 		ovl_set_upperdata(d_inode(c->dentry));
918 	ovl_inode_update(d_inode(c->dentry), dget(temp));
919 
920 out:
921 	ovl_end_write(c->dentry);
922 out_fput:
923 	fput(tmpfile);
924 	return err;
925 }
926 
927 /*
928  * Copy up a single dentry
929  *
930  * All renames start with copy up of source if necessary.  The actual
931  * rename will only proceed once the copy up was successful.  Copy up uses
932  * upper parent i_mutex for exclusion.  Since rename can change d_parent it
933  * is possible that the copy up will lock the old parent.  At that point
934  * the file will have already been copied up anyway.
935  */
936 static int ovl_do_copy_up(struct ovl_copy_up_ctx *c)
937 {
938 	int err;
939 	struct ovl_fs *ofs = OVL_FS(c->dentry->d_sb);
940 	struct dentry *origin = c->lowerpath.dentry;
941 	struct ovl_fh *fh = NULL;
942 	bool to_index = false;
943 
944 	/*
945 	 * Indexed non-dir is copied up directly to the index entry and then
946 	 * hardlinked to upper dir. Indexed dir is copied up to indexdir,
947 	 * then index entry is created and then copied up dir installed.
948 	 * Copying dir up to indexdir instead of workdir simplifies locking.
949 	 */
950 	if (ovl_need_index(c->dentry)) {
951 		c->indexed = true;
952 		if (S_ISDIR(c->stat.mode))
953 			c->workdir = ovl_indexdir(c->dentry->d_sb);
954 		else
955 			to_index = true;
956 	}
957 
958 	if (S_ISDIR(c->stat.mode) || c->stat.nlink == 1 || to_index) {
959 		fh = ovl_get_origin_fh(ofs, origin);
960 		if (IS_ERR(fh))
961 			return PTR_ERR(fh);
962 
963 		/* origin_fh may be NULL */
964 		c->origin_fh = fh;
965 		c->origin = true;
966 	}
967 
968 	if (to_index) {
969 		c->destdir = ovl_indexdir(c->dentry->d_sb);
970 		err = ovl_get_index_name(ofs, origin, &c->destname);
971 		if (err)
972 			goto out_free_fh;
973 	} else if (WARN_ON(!c->parent)) {
974 		/* Disconnected dentry must be copied up to index dir */
975 		err = -EIO;
976 		goto out_free_fh;
977 	} else {
978 		/*
979 		 * c->dentry->d_name is stabilzed by ovl_copy_up_start(),
980 		 * because if we got here, it means that c->dentry has no upper
981 		 * alias and changing ->d_name means going through ovl_rename()
982 		 * that will call ovl_copy_up() on source and target dentry.
983 		 */
984 		c->destname = c->dentry->d_name;
985 		/*
986 		 * Mark parent "impure" because it may now contain non-pure
987 		 * upper
988 		 */
989 		ovl_start_write(c->dentry);
990 		err = ovl_set_impure(c->parent, c->destdir);
991 		ovl_end_write(c->dentry);
992 		if (err)
993 			goto out_free_fh;
994 	}
995 
996 	/* Should we copyup with O_TMPFILE or with workdir? */
997 	if (S_ISREG(c->stat.mode) && ofs->tmpfile)
998 		err = ovl_copy_up_tmpfile(c);
999 	else
1000 		err = ovl_copy_up_workdir(c);
1001 	if (err)
1002 		goto out;
1003 
1004 	if (c->indexed)
1005 		ovl_set_flag(OVL_INDEX, d_inode(c->dentry));
1006 
1007 	ovl_start_write(c->dentry);
1008 	if (to_index) {
1009 		/* Initialize nlink for copy up of disconnected dentry */
1010 		err = ovl_set_nlink_upper(c->dentry);
1011 	} else {
1012 		struct inode *udir = d_inode(c->destdir);
1013 
1014 		/* Restore timestamps on parent (best effort) */
1015 		inode_lock(udir);
1016 		ovl_set_timestamps(ofs, c->destdir, &c->pstat);
1017 		inode_unlock(udir);
1018 
1019 		ovl_dentry_set_upper_alias(c->dentry);
1020 		ovl_dentry_update_reval(c->dentry, ovl_dentry_upper(c->dentry));
1021 	}
1022 	ovl_end_write(c->dentry);
1023 
1024 out:
1025 	if (to_index)
1026 		kfree(c->destname.name);
1027 out_free_fh:
1028 	kfree(fh);
1029 	return err;
1030 }
1031 
1032 static bool ovl_need_meta_copy_up(struct dentry *dentry, umode_t mode,
1033 				  int flags)
1034 {
1035 	struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
1036 
1037 	if (!ofs->config.metacopy)
1038 		return false;
1039 
1040 	if (!S_ISREG(mode))
1041 		return false;
1042 
1043 	if (flags && ((OPEN_FMODE(flags) & FMODE_WRITE) || (flags & O_TRUNC)))
1044 		return false;
1045 
1046 	/* Fall back to full copy if no fsverity on source data and we require verity */
1047 	if (ofs->config.verity_mode == OVL_VERITY_REQUIRE) {
1048 		struct path lowerdata;
1049 
1050 		ovl_path_lowerdata(dentry, &lowerdata);
1051 
1052 		if (WARN_ON_ONCE(lowerdata.dentry == NULL) ||
1053 		    ovl_ensure_verity_loaded(&lowerdata) ||
1054 		    !fsverity_active(d_inode(lowerdata.dentry))) {
1055 			return false;
1056 		}
1057 	}
1058 
1059 	return true;
1060 }
1061 
1062 static ssize_t ovl_getxattr_value(const struct path *path, char *name, char **value)
1063 {
1064 	ssize_t res;
1065 	char *buf;
1066 
1067 	res = ovl_do_getxattr(path, name, NULL, 0);
1068 	if (res == -ENODATA || res == -EOPNOTSUPP)
1069 		res = 0;
1070 
1071 	if (res > 0) {
1072 		buf = kzalloc(res, GFP_KERNEL);
1073 		if (!buf)
1074 			return -ENOMEM;
1075 
1076 		res = ovl_do_getxattr(path, name, buf, res);
1077 		if (res < 0)
1078 			kfree(buf);
1079 		else
1080 			*value = buf;
1081 	}
1082 	return res;
1083 }
1084 
1085 /* Copy up data of an inode which was copied up metadata only in the past. */
1086 static int ovl_copy_up_meta_inode_data(struct ovl_copy_up_ctx *c)
1087 {
1088 	struct ovl_fs *ofs = OVL_FS(c->dentry->d_sb);
1089 	struct path upperpath;
1090 	int err;
1091 	char *capability = NULL;
1092 	ssize_t cap_size;
1093 
1094 	ovl_path_upper(c->dentry, &upperpath);
1095 	if (WARN_ON(upperpath.dentry == NULL))
1096 		return -EIO;
1097 
1098 	if (c->stat.size) {
1099 		err = cap_size = ovl_getxattr_value(&upperpath, XATTR_NAME_CAPS,
1100 						    &capability);
1101 		if (cap_size < 0)
1102 			goto out;
1103 	}
1104 
1105 	err = ovl_copy_up_data(c, &upperpath);
1106 	if (err)
1107 		goto out_free;
1108 
1109 	/*
1110 	 * Writing to upper file will clear security.capability xattr. We
1111 	 * don't want that to happen for normal copy-up operation.
1112 	 */
1113 	ovl_start_write(c->dentry);
1114 	if (capability) {
1115 		err = ovl_do_setxattr(ofs, upperpath.dentry, XATTR_NAME_CAPS,
1116 				      capability, cap_size, 0);
1117 	}
1118 	if (!err) {
1119 		err = ovl_removexattr(ofs, upperpath.dentry,
1120 				      OVL_XATTR_METACOPY);
1121 	}
1122 	ovl_end_write(c->dentry);
1123 	if (err)
1124 		goto out_free;
1125 
1126 	ovl_clear_flag(OVL_HAS_DIGEST, d_inode(c->dentry));
1127 	ovl_clear_flag(OVL_VERIFIED_DIGEST, d_inode(c->dentry));
1128 	ovl_set_upperdata(d_inode(c->dentry));
1129 out_free:
1130 	kfree(capability);
1131 out:
1132 	return err;
1133 }
1134 
1135 static int ovl_copy_up_one(struct dentry *parent, struct dentry *dentry,
1136 			   int flags)
1137 {
1138 	int err;
1139 	DEFINE_DELAYED_CALL(done);
1140 	struct path parentpath;
1141 	struct ovl_copy_up_ctx ctx = {
1142 		.parent = parent,
1143 		.dentry = dentry,
1144 		.workdir = ovl_workdir(dentry),
1145 	};
1146 
1147 	if (WARN_ON(!ctx.workdir))
1148 		return -EROFS;
1149 
1150 	ovl_path_lower(dentry, &ctx.lowerpath);
1151 	err = vfs_getattr(&ctx.lowerpath, &ctx.stat,
1152 			  STATX_BASIC_STATS, AT_STATX_SYNC_AS_STAT);
1153 	if (err)
1154 		return err;
1155 
1156 	if (!kuid_has_mapping(current_user_ns(), ctx.stat.uid) ||
1157 	    !kgid_has_mapping(current_user_ns(), ctx.stat.gid))
1158 		return -EOVERFLOW;
1159 
1160 	/*
1161 	 * With metacopy disabled, we fsync after final metadata copyup, for
1162 	 * both regular files and directories to get atomic copyup semantics
1163 	 * on filesystems that do not use strict metadata ordering (e.g. ubifs).
1164 	 *
1165 	 * With metacopy enabled we want to avoid fsync on all meta copyup
1166 	 * that will hurt performance of workloads such as chown -R, so we
1167 	 * only fsync on data copyup as legacy behavior.
1168 	 */
1169 	ctx.metadata_fsync = !OVL_FS(dentry->d_sb)->config.metacopy &&
1170 			     (S_ISREG(ctx.stat.mode) || S_ISDIR(ctx.stat.mode));
1171 	ctx.metacopy = ovl_need_meta_copy_up(dentry, ctx.stat.mode, flags);
1172 
1173 	if (parent) {
1174 		ovl_path_upper(parent, &parentpath);
1175 		ctx.destdir = parentpath.dentry;
1176 
1177 		err = vfs_getattr(&parentpath, &ctx.pstat,
1178 				  STATX_ATIME | STATX_MTIME,
1179 				  AT_STATX_SYNC_AS_STAT);
1180 		if (err)
1181 			return err;
1182 	}
1183 
1184 	/* maybe truncate regular file. this has no effect on dirs */
1185 	if (flags & O_TRUNC)
1186 		ctx.stat.size = 0;
1187 
1188 	if (S_ISLNK(ctx.stat.mode)) {
1189 		ctx.link = vfs_get_link(ctx.lowerpath.dentry, &done);
1190 		if (IS_ERR(ctx.link))
1191 			return PTR_ERR(ctx.link);
1192 	}
1193 
1194 	err = ovl_copy_up_start(dentry, flags);
1195 	/* err < 0: interrupted, err > 0: raced with another copy-up */
1196 	if (unlikely(err)) {
1197 		if (err > 0)
1198 			err = 0;
1199 	} else {
1200 		if (!ovl_dentry_upper(dentry))
1201 			err = ovl_do_copy_up(&ctx);
1202 		if (!err && parent && !ovl_dentry_has_upper_alias(dentry))
1203 			err = ovl_link_up(&ctx);
1204 		if (!err && ovl_dentry_needs_data_copy_up_locked(dentry, flags))
1205 			err = ovl_copy_up_meta_inode_data(&ctx);
1206 		ovl_copy_up_end(dentry);
1207 	}
1208 	do_delayed_call(&done);
1209 
1210 	return err;
1211 }
1212 
1213 static int ovl_copy_up_flags(struct dentry *dentry, int flags)
1214 {
1215 	int err = 0;
1216 	const struct cred *old_cred;
1217 	bool disconnected = (dentry->d_flags & DCACHE_DISCONNECTED);
1218 
1219 	/*
1220 	 * With NFS export, copy up can get called for a disconnected non-dir.
1221 	 * In this case, we will copy up lower inode to index dir without
1222 	 * linking it to upper dir.
1223 	 */
1224 	if (WARN_ON(disconnected && d_is_dir(dentry)))
1225 		return -EIO;
1226 
1227 	/*
1228 	 * We may not need lowerdata if we are only doing metacopy up, but it is
1229 	 * not very important to optimize this case, so do lazy lowerdata lookup
1230 	 * before any copy up, so we can do it before taking ovl_inode_lock().
1231 	 */
1232 	err = ovl_verify_lowerdata(dentry);
1233 	if (err)
1234 		return err;
1235 
1236 	old_cred = ovl_override_creds(dentry->d_sb);
1237 	while (!err) {
1238 		struct dentry *next;
1239 		struct dentry *parent = NULL;
1240 
1241 		if (ovl_already_copied_up(dentry, flags))
1242 			break;
1243 
1244 		next = dget(dentry);
1245 		/* find the topmost dentry not yet copied up */
1246 		for (; !disconnected;) {
1247 			parent = dget_parent(next);
1248 
1249 			if (ovl_dentry_upper(parent))
1250 				break;
1251 
1252 			dput(next);
1253 			next = parent;
1254 		}
1255 
1256 		err = ovl_copy_up_one(parent, next, flags);
1257 
1258 		dput(parent);
1259 		dput(next);
1260 	}
1261 	ovl_revert_creds(old_cred);
1262 
1263 	return err;
1264 }
1265 
1266 static bool ovl_open_need_copy_up(struct dentry *dentry, int flags)
1267 {
1268 	/* Copy up of disconnected dentry does not set upper alias */
1269 	if (ovl_already_copied_up(dentry, flags))
1270 		return false;
1271 
1272 	if (special_file(d_inode(dentry)->i_mode))
1273 		return false;
1274 
1275 	if (!ovl_open_flags_need_copy_up(flags))
1276 		return false;
1277 
1278 	return true;
1279 }
1280 
1281 int ovl_maybe_copy_up(struct dentry *dentry, int flags)
1282 {
1283 	if (!ovl_open_need_copy_up(dentry, flags))
1284 		return 0;
1285 
1286 	return ovl_copy_up_flags(dentry, flags);
1287 }
1288 
1289 int ovl_copy_up_with_data(struct dentry *dentry)
1290 {
1291 	return ovl_copy_up_flags(dentry, O_WRONLY);
1292 }
1293 
1294 int ovl_copy_up(struct dentry *dentry)
1295 {
1296 	return ovl_copy_up_flags(dentry, 0);
1297 }
1298