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