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