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