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