ovl: introduce new "uuid=off" option for inodes index feature
[linux-2.6-block.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 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 ovl_fs *ofs, struct dentry *real,
279                                   bool is_upper)
280 {
281         struct ovl_fh *fh;
282         int fh_type, dwords;
283         int buflen = MAX_HANDLE_SZ;
284         uuid_t *uuid = &real->d_sb->s_uuid;
285         int err;
286
287         /* Make sure the real fid stays 32bit aligned */
288         BUILD_BUG_ON(OVL_FH_FID_OFFSET % 4);
289         BUILD_BUG_ON(MAX_HANDLE_SZ + OVL_FH_FID_OFFSET > 255);
290
291         fh = kzalloc(buflen + OVL_FH_FID_OFFSET, GFP_KERNEL);
292         if (!fh)
293                 return ERR_PTR(-ENOMEM);
294
295         /*
296          * We encode a non-connectable file handle for non-dir, because we
297          * only need to find the lower inode number and we don't want to pay
298          * the price or reconnecting the dentry.
299          */
300         dwords = buflen >> 2;
301         fh_type = exportfs_encode_fh(real, (void *)fh->fb.fid, &dwords, 0);
302         buflen = (dwords << 2);
303
304         err = -EIO;
305         if (WARN_ON(fh_type < 0) ||
306             WARN_ON(buflen > MAX_HANDLE_SZ) ||
307             WARN_ON(fh_type == FILEID_INVALID))
308                 goto out_err;
309
310         fh->fb.version = OVL_FH_VERSION;
311         fh->fb.magic = OVL_FH_MAGIC;
312         fh->fb.type = fh_type;
313         fh->fb.flags = OVL_FH_FLAG_CPU_ENDIAN;
314         /*
315          * When we will want to decode an overlay dentry from this handle
316          * and all layers are on the same fs, if we get a disconncted real
317          * dentry when we decode fid, the only way to tell if we should assign
318          * it to upperdentry or to lowerstack is by checking this flag.
319          */
320         if (is_upper)
321                 fh->fb.flags |= OVL_FH_FLAG_PATH_UPPER;
322         fh->fb.len = sizeof(fh->fb) + buflen;
323         if (ofs->config.uuid)
324                 fh->fb.uuid = *uuid;
325
326         return fh;
327
328 out_err:
329         kfree(fh);
330         return ERR_PTR(err);
331 }
332
333 int ovl_set_origin(struct ovl_fs *ofs, struct dentry *dentry,
334                    struct dentry *lower, struct dentry *upper)
335 {
336         const struct ovl_fh *fh = NULL;
337         int err;
338
339         /*
340          * When lower layer doesn't support export operations store a 'null' fh,
341          * so we can use the overlay.origin xattr to distignuish between a copy
342          * up and a pure upper inode.
343          */
344         if (ovl_can_decode_fh(lower->d_sb)) {
345                 fh = ovl_encode_real_fh(ofs, lower, false);
346                 if (IS_ERR(fh))
347                         return PTR_ERR(fh);
348         }
349
350         /*
351          * Do not fail when upper doesn't support xattrs.
352          */
353         err = ovl_check_setxattr(dentry, upper, OVL_XATTR_ORIGIN, fh->buf,
354                                  fh ? fh->fb.len : 0, 0);
355         kfree(fh);
356
357         return err;
358 }
359
360 /* Store file handle of @upper dir in @index dir entry */
361 static int ovl_set_upper_fh(struct ovl_fs *ofs, struct dentry *upper,
362                             struct dentry *index)
363 {
364         const struct ovl_fh *fh;
365         int err;
366
367         fh = ovl_encode_real_fh(ofs, upper, true);
368         if (IS_ERR(fh))
369                 return PTR_ERR(fh);
370
371         err = ovl_do_setxattr(ofs, index, OVL_XATTR_UPPER, fh->buf, fh->fb.len);
372
373         kfree(fh);
374         return err;
375 }
376
377 /*
378  * Create and install index entry.
379  *
380  * Caller must hold i_mutex on indexdir.
381  */
382 static int ovl_create_index(struct dentry *dentry, struct dentry *origin,
383                             struct dentry *upper)
384 {
385         struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
386         struct dentry *indexdir = ovl_indexdir(dentry->d_sb);
387         struct inode *dir = d_inode(indexdir);
388         struct dentry *index = NULL;
389         struct dentry *temp = NULL;
390         struct qstr name = { };
391         int err;
392
393         /*
394          * For now this is only used for creating index entry for directories,
395          * because non-dir are copied up directly to index and then hardlinked
396          * to upper dir.
397          *
398          * TODO: implement create index for non-dir, so we can call it when
399          * encoding file handle for non-dir in case index does not exist.
400          */
401         if (WARN_ON(!d_is_dir(dentry)))
402                 return -EIO;
403
404         /* Directory not expected to be indexed before copy up */
405         if (WARN_ON(ovl_test_flag(OVL_INDEX, d_inode(dentry))))
406                 return -EIO;
407
408         err = ovl_get_index_name(ofs, origin, &name);
409         if (err)
410                 return err;
411
412         temp = ovl_create_temp(indexdir, OVL_CATTR(S_IFDIR | 0));
413         err = PTR_ERR(temp);
414         if (IS_ERR(temp))
415                 goto free_name;
416
417         err = ovl_set_upper_fh(ofs, upper, temp);
418         if (err)
419                 goto out;
420
421         index = lookup_one_len(name.name, indexdir, name.len);
422         if (IS_ERR(index)) {
423                 err = PTR_ERR(index);
424         } else {
425                 err = ovl_do_rename(dir, temp, dir, index, 0);
426                 dput(index);
427         }
428 out:
429         if (err)
430                 ovl_cleanup(dir, temp);
431         dput(temp);
432 free_name:
433         kfree(name.name);
434         return err;
435 }
436
437 struct ovl_copy_up_ctx {
438         struct dentry *parent;
439         struct dentry *dentry;
440         struct path lowerpath;
441         struct kstat stat;
442         struct kstat pstat;
443         const char *link;
444         struct dentry *destdir;
445         struct qstr destname;
446         struct dentry *workdir;
447         bool origin;
448         bool indexed;
449         bool metacopy;
450 };
451
452 static int ovl_link_up(struct ovl_copy_up_ctx *c)
453 {
454         int err;
455         struct dentry *upper;
456         struct dentry *upperdir = ovl_dentry_upper(c->parent);
457         struct inode *udir = d_inode(upperdir);
458
459         /* Mark parent "impure" because it may now contain non-pure upper */
460         err = ovl_set_impure(c->parent, upperdir);
461         if (err)
462                 return err;
463
464         err = ovl_set_nlink_lower(c->dentry);
465         if (err)
466                 return err;
467
468         inode_lock_nested(udir, I_MUTEX_PARENT);
469         upper = lookup_one_len(c->dentry->d_name.name, upperdir,
470                                c->dentry->d_name.len);
471         err = PTR_ERR(upper);
472         if (!IS_ERR(upper)) {
473                 err = ovl_do_link(ovl_dentry_upper(c->dentry), udir, upper);
474                 dput(upper);
475
476                 if (!err) {
477                         /* Restore timestamps on parent (best effort) */
478                         ovl_set_timestamps(upperdir, &c->pstat);
479                         ovl_dentry_set_upper_alias(c->dentry);
480                 }
481         }
482         inode_unlock(udir);
483         if (err)
484                 return err;
485
486         err = ovl_set_nlink_upper(c->dentry);
487
488         return err;
489 }
490
491 static int ovl_copy_up_inode(struct ovl_copy_up_ctx *c, struct dentry *temp)
492 {
493         struct ovl_fs *ofs = OVL_FS(c->dentry->d_sb);
494         int err;
495
496         /*
497          * Copy up data first and then xattrs. Writing data after
498          * xattrs will remove security.capability xattr automatically.
499          */
500         if (S_ISREG(c->stat.mode) && !c->metacopy) {
501                 struct path upperpath, datapath;
502
503                 ovl_path_upper(c->dentry, &upperpath);
504                 if (WARN_ON(upperpath.dentry != NULL))
505                         return -EIO;
506                 upperpath.dentry = temp;
507
508                 ovl_path_lowerdata(c->dentry, &datapath);
509                 err = ovl_copy_up_data(ofs, &datapath, &upperpath,
510                                        c->stat.size);
511                 if (err)
512                         return err;
513         }
514
515         err = ovl_copy_xattr(c->dentry->d_sb, c->lowerpath.dentry, temp);
516         if (err)
517                 return err;
518
519         /*
520          * Store identifier of lower inode in upper inode xattr to
521          * allow lookup of the copy up origin inode.
522          *
523          * Don't set origin when we are breaking the association with a lower
524          * hard link.
525          */
526         if (c->origin) {
527                 err = ovl_set_origin(ofs, c->dentry, c->lowerpath.dentry, temp);
528                 if (err)
529                         return err;
530         }
531
532         if (c->metacopy) {
533                 err = ovl_check_setxattr(c->dentry, temp, OVL_XATTR_METACOPY,
534                                          NULL, 0, -EOPNOTSUPP);
535                 if (err)
536                         return err;
537         }
538
539         inode_lock(temp->d_inode);
540         if (S_ISREG(c->stat.mode))
541                 err = ovl_set_size(temp, &c->stat);
542         if (!err)
543                 err = ovl_set_attr(temp, &c->stat);
544         inode_unlock(temp->d_inode);
545
546         return err;
547 }
548
549 struct ovl_cu_creds {
550         const struct cred *old;
551         struct cred *new;
552 };
553
554 static int ovl_prep_cu_creds(struct dentry *dentry, struct ovl_cu_creds *cc)
555 {
556         int err;
557
558         cc->old = cc->new = NULL;
559         err = security_inode_copy_up(dentry, &cc->new);
560         if (err < 0)
561                 return err;
562
563         if (cc->new)
564                 cc->old = override_creds(cc->new);
565
566         return 0;
567 }
568
569 static void ovl_revert_cu_creds(struct ovl_cu_creds *cc)
570 {
571         if (cc->new) {
572                 revert_creds(cc->old);
573                 put_cred(cc->new);
574         }
575 }
576
577 /*
578  * Copyup using workdir to prepare temp file.  Used when copying up directories,
579  * special files or when upper fs doesn't support O_TMPFILE.
580  */
581 static int ovl_copy_up_workdir(struct ovl_copy_up_ctx *c)
582 {
583         struct inode *inode;
584         struct inode *udir = d_inode(c->destdir), *wdir = d_inode(c->workdir);
585         struct dentry *temp, *upper;
586         struct ovl_cu_creds cc;
587         int err;
588         struct ovl_cattr cattr = {
589                 /* Can't properly set mode on creation because of the umask */
590                 .mode = c->stat.mode & S_IFMT,
591                 .rdev = c->stat.rdev,
592                 .link = c->link
593         };
594
595         /* workdir and destdir could be the same when copying up to indexdir */
596         err = -EIO;
597         if (lock_rename(c->workdir, c->destdir) != NULL)
598                 goto unlock;
599
600         err = ovl_prep_cu_creds(c->dentry, &cc);
601         if (err)
602                 goto unlock;
603
604         temp = ovl_create_temp(c->workdir, &cattr);
605         ovl_revert_cu_creds(&cc);
606
607         err = PTR_ERR(temp);
608         if (IS_ERR(temp))
609                 goto unlock;
610
611         err = ovl_copy_up_inode(c, temp);
612         if (err)
613                 goto cleanup;
614
615         if (S_ISDIR(c->stat.mode) && c->indexed) {
616                 err = ovl_create_index(c->dentry, c->lowerpath.dentry, temp);
617                 if (err)
618                         goto cleanup;
619         }
620
621         upper = lookup_one_len(c->destname.name, c->destdir, c->destname.len);
622         err = PTR_ERR(upper);
623         if (IS_ERR(upper))
624                 goto cleanup;
625
626         err = ovl_do_rename(wdir, temp, udir, upper, 0);
627         dput(upper);
628         if (err)
629                 goto cleanup;
630
631         if (!c->metacopy)
632                 ovl_set_upperdata(d_inode(c->dentry));
633         inode = d_inode(c->dentry);
634         ovl_inode_update(inode, temp);
635         if (S_ISDIR(inode->i_mode))
636                 ovl_set_flag(OVL_WHITEOUTS, inode);
637 unlock:
638         unlock_rename(c->workdir, c->destdir);
639
640         return err;
641
642 cleanup:
643         ovl_cleanup(wdir, temp);
644         dput(temp);
645         goto unlock;
646 }
647
648 /* Copyup using O_TMPFILE which does not require cross dir locking */
649 static int ovl_copy_up_tmpfile(struct ovl_copy_up_ctx *c)
650 {
651         struct inode *udir = d_inode(c->destdir);
652         struct dentry *temp, *upper;
653         struct ovl_cu_creds cc;
654         int err;
655
656         err = ovl_prep_cu_creds(c->dentry, &cc);
657         if (err)
658                 return err;
659
660         temp = ovl_do_tmpfile(c->workdir, c->stat.mode);
661         ovl_revert_cu_creds(&cc);
662
663         if (IS_ERR(temp))
664                 return PTR_ERR(temp);
665
666         err = ovl_copy_up_inode(c, temp);
667         if (err)
668                 goto out_dput;
669
670         inode_lock_nested(udir, I_MUTEX_PARENT);
671
672         upper = lookup_one_len(c->destname.name, c->destdir, c->destname.len);
673         err = PTR_ERR(upper);
674         if (!IS_ERR(upper)) {
675                 err = ovl_do_link(temp, udir, upper);
676                 dput(upper);
677         }
678         inode_unlock(udir);
679
680         if (err)
681                 goto out_dput;
682
683         if (!c->metacopy)
684                 ovl_set_upperdata(d_inode(c->dentry));
685         ovl_inode_update(d_inode(c->dentry), temp);
686
687         return 0;
688
689 out_dput:
690         dput(temp);
691         return err;
692 }
693
694 /*
695  * Copy up a single dentry
696  *
697  * All renames start with copy up of source if necessary.  The actual
698  * rename will only proceed once the copy up was successful.  Copy up uses
699  * upper parent i_mutex for exclusion.  Since rename can change d_parent it
700  * is possible that the copy up will lock the old parent.  At that point
701  * the file will have already been copied up anyway.
702  */
703 static int ovl_do_copy_up(struct ovl_copy_up_ctx *c)
704 {
705         int err;
706         struct ovl_fs *ofs = OVL_FS(c->dentry->d_sb);
707         bool to_index = false;
708
709         /*
710          * Indexed non-dir is copied up directly to the index entry and then
711          * hardlinked to upper dir. Indexed dir is copied up to indexdir,
712          * then index entry is created and then copied up dir installed.
713          * Copying dir up to indexdir instead of workdir simplifies locking.
714          */
715         if (ovl_need_index(c->dentry)) {
716                 c->indexed = true;
717                 if (S_ISDIR(c->stat.mode))
718                         c->workdir = ovl_indexdir(c->dentry->d_sb);
719                 else
720                         to_index = true;
721         }
722
723         if (S_ISDIR(c->stat.mode) || c->stat.nlink == 1 || to_index)
724                 c->origin = true;
725
726         if (to_index) {
727                 c->destdir = ovl_indexdir(c->dentry->d_sb);
728                 err = ovl_get_index_name(ofs, c->lowerpath.dentry, &c->destname);
729                 if (err)
730                         return err;
731         } else if (WARN_ON(!c->parent)) {
732                 /* Disconnected dentry must be copied up to index dir */
733                 return -EIO;
734         } else {
735                 /*
736                  * Mark parent "impure" because it may now contain non-pure
737                  * upper
738                  */
739                 err = ovl_set_impure(c->parent, c->destdir);
740                 if (err)
741                         return err;
742         }
743
744         /* Should we copyup with O_TMPFILE or with workdir? */
745         if (S_ISREG(c->stat.mode) && ofs->tmpfile)
746                 err = ovl_copy_up_tmpfile(c);
747         else
748                 err = ovl_copy_up_workdir(c);
749         if (err)
750                 goto out;
751
752         if (c->indexed)
753                 ovl_set_flag(OVL_INDEX, d_inode(c->dentry));
754
755         if (to_index) {
756                 /* Initialize nlink for copy up of disconnected dentry */
757                 err = ovl_set_nlink_upper(c->dentry);
758         } else {
759                 struct inode *udir = d_inode(c->destdir);
760
761                 /* Restore timestamps on parent (best effort) */
762                 inode_lock(udir);
763                 ovl_set_timestamps(c->destdir, &c->pstat);
764                 inode_unlock(udir);
765
766                 ovl_dentry_set_upper_alias(c->dentry);
767         }
768
769 out:
770         if (to_index)
771                 kfree(c->destname.name);
772         return err;
773 }
774
775 static bool ovl_need_meta_copy_up(struct dentry *dentry, umode_t mode,
776                                   int flags)
777 {
778         struct ovl_fs *ofs = dentry->d_sb->s_fs_info;
779
780         if (!ofs->config.metacopy)
781                 return false;
782
783         if (!S_ISREG(mode))
784                 return false;
785
786         if (flags && ((OPEN_FMODE(flags) & FMODE_WRITE) || (flags & O_TRUNC)))
787                 return false;
788
789         return true;
790 }
791
792 static ssize_t ovl_getxattr(struct dentry *dentry, char *name, char **value)
793 {
794         ssize_t res;
795         char *buf;
796
797         res = vfs_getxattr(dentry, name, NULL, 0);
798         if (res == -ENODATA || res == -EOPNOTSUPP)
799                 res = 0;
800
801         if (res > 0) {
802                 buf = kzalloc(res, GFP_KERNEL);
803                 if (!buf)
804                         return -ENOMEM;
805
806                 res = vfs_getxattr(dentry, name, buf, res);
807                 if (res < 0)
808                         kfree(buf);
809                 else
810                         *value = buf;
811         }
812         return res;
813 }
814
815 /* Copy up data of an inode which was copied up metadata only in the past. */
816 static int ovl_copy_up_meta_inode_data(struct ovl_copy_up_ctx *c)
817 {
818         struct ovl_fs *ofs = OVL_FS(c->dentry->d_sb);
819         struct path upperpath, datapath;
820         int err;
821         char *capability = NULL;
822         ssize_t cap_size;
823
824         ovl_path_upper(c->dentry, &upperpath);
825         if (WARN_ON(upperpath.dentry == NULL))
826                 return -EIO;
827
828         ovl_path_lowerdata(c->dentry, &datapath);
829         if (WARN_ON(datapath.dentry == NULL))
830                 return -EIO;
831
832         if (c->stat.size) {
833                 err = cap_size = ovl_getxattr(upperpath.dentry, XATTR_NAME_CAPS,
834                                               &capability);
835                 if (cap_size < 0)
836                         goto out;
837         }
838
839         err = ovl_copy_up_data(ofs, &datapath, &upperpath, c->stat.size);
840         if (err)
841                 goto out_free;
842
843         /*
844          * Writing to upper file will clear security.capability xattr. We
845          * don't want that to happen for normal copy-up operation.
846          */
847         if (capability) {
848                 err = vfs_setxattr(upperpath.dentry, XATTR_NAME_CAPS,
849                                    capability, cap_size, 0);
850                 if (err)
851                         goto out_free;
852         }
853
854
855         err = ovl_do_removexattr(ofs, upperpath.dentry, OVL_XATTR_METACOPY);
856         if (err)
857                 goto out_free;
858
859         ovl_set_upperdata(d_inode(c->dentry));
860 out_free:
861         kfree(capability);
862 out:
863         return err;
864 }
865
866 static int ovl_copy_up_one(struct dentry *parent, struct dentry *dentry,
867                            int flags)
868 {
869         int err;
870         DEFINE_DELAYED_CALL(done);
871         struct path parentpath;
872         struct ovl_copy_up_ctx ctx = {
873                 .parent = parent,
874                 .dentry = dentry,
875                 .workdir = ovl_workdir(dentry),
876         };
877
878         if (WARN_ON(!ctx.workdir))
879                 return -EROFS;
880
881         ovl_path_lower(dentry, &ctx.lowerpath);
882         err = vfs_getattr(&ctx.lowerpath, &ctx.stat,
883                           STATX_BASIC_STATS, AT_STATX_SYNC_AS_STAT);
884         if (err)
885                 return err;
886
887         ctx.metacopy = ovl_need_meta_copy_up(dentry, ctx.stat.mode, flags);
888
889         if (parent) {
890                 ovl_path_upper(parent, &parentpath);
891                 ctx.destdir = parentpath.dentry;
892                 ctx.destname = dentry->d_name;
893
894                 err = vfs_getattr(&parentpath, &ctx.pstat,
895                                   STATX_ATIME | STATX_MTIME,
896                                   AT_STATX_SYNC_AS_STAT);
897                 if (err)
898                         return err;
899         }
900
901         /* maybe truncate regular file. this has no effect on dirs */
902         if (flags & O_TRUNC)
903                 ctx.stat.size = 0;
904
905         if (S_ISLNK(ctx.stat.mode)) {
906                 ctx.link = vfs_get_link(ctx.lowerpath.dentry, &done);
907                 if (IS_ERR(ctx.link))
908                         return PTR_ERR(ctx.link);
909         }
910
911         err = ovl_copy_up_start(dentry, flags);
912         /* err < 0: interrupted, err > 0: raced with another copy-up */
913         if (unlikely(err)) {
914                 if (err > 0)
915                         err = 0;
916         } else {
917                 if (!ovl_dentry_upper(dentry))
918                         err = ovl_do_copy_up(&ctx);
919                 if (!err && parent && !ovl_dentry_has_upper_alias(dentry))
920                         err = ovl_link_up(&ctx);
921                 if (!err && ovl_dentry_needs_data_copy_up_locked(dentry, flags))
922                         err = ovl_copy_up_meta_inode_data(&ctx);
923                 ovl_copy_up_end(dentry);
924         }
925         do_delayed_call(&done);
926
927         return err;
928 }
929
930 static int ovl_copy_up_flags(struct dentry *dentry, int flags)
931 {
932         int err = 0;
933         const struct cred *old_cred = ovl_override_creds(dentry->d_sb);
934         bool disconnected = (dentry->d_flags & DCACHE_DISCONNECTED);
935
936         /*
937          * With NFS export, copy up can get called for a disconnected non-dir.
938          * In this case, we will copy up lower inode to index dir without
939          * linking it to upper dir.
940          */
941         if (WARN_ON(disconnected && d_is_dir(dentry)))
942                 return -EIO;
943
944         while (!err) {
945                 struct dentry *next;
946                 struct dentry *parent = NULL;
947
948                 if (ovl_already_copied_up(dentry, flags))
949                         break;
950
951                 next = dget(dentry);
952                 /* find the topmost dentry not yet copied up */
953                 for (; !disconnected;) {
954                         parent = dget_parent(next);
955
956                         if (ovl_dentry_upper(parent))
957                                 break;
958
959                         dput(next);
960                         next = parent;
961                 }
962
963                 err = ovl_copy_up_one(parent, next, flags);
964
965                 dput(parent);
966                 dput(next);
967         }
968         revert_creds(old_cred);
969
970         return err;
971 }
972
973 static bool ovl_open_need_copy_up(struct dentry *dentry, int flags)
974 {
975         /* Copy up of disconnected dentry does not set upper alias */
976         if (ovl_already_copied_up(dentry, flags))
977                 return false;
978
979         if (special_file(d_inode(dentry)->i_mode))
980                 return false;
981
982         if (!ovl_open_flags_need_copy_up(flags))
983                 return false;
984
985         return true;
986 }
987
988 int ovl_maybe_copy_up(struct dentry *dentry, int flags)
989 {
990         int err = 0;
991
992         if (ovl_open_need_copy_up(dentry, flags)) {
993                 err = ovl_want_write(dentry);
994                 if (!err) {
995                         err = ovl_copy_up_flags(dentry, flags);
996                         ovl_drop_write(dentry);
997                 }
998         }
999
1000         return err;
1001 }
1002
1003 int ovl_copy_up_with_data(struct dentry *dentry)
1004 {
1005         return ovl_copy_up_flags(dentry, O_WRONLY);
1006 }
1007
1008 int ovl_copy_up(struct dentry *dentry)
1009 {
1010         return ovl_copy_up_flags(dentry, 0);
1011 }