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