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