ovl: update of dentry revalidate flags after copy up
[platform/kernel/linux-starfive.git] / fs / overlayfs / util.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2011 Novell Inc.
4  * Copyright (C) 2016 Red Hat, Inc.
5  */
6
7 #include <linux/fs.h>
8 #include <linux/mount.h>
9 #include <linux/slab.h>
10 #include <linux/cred.h>
11 #include <linux/xattr.h>
12 #include <linux/exportfs.h>
13 #include <linux/fileattr.h>
14 #include <linux/uuid.h>
15 #include <linux/namei.h>
16 #include <linux/ratelimit.h>
17 #include "overlayfs.h"
18
19 int ovl_want_write(struct dentry *dentry)
20 {
21         struct ovl_fs *ofs = dentry->d_sb->s_fs_info;
22         return mnt_want_write(ovl_upper_mnt(ofs));
23 }
24
25 void ovl_drop_write(struct dentry *dentry)
26 {
27         struct ovl_fs *ofs = dentry->d_sb->s_fs_info;
28         mnt_drop_write(ovl_upper_mnt(ofs));
29 }
30
31 struct dentry *ovl_workdir(struct dentry *dentry)
32 {
33         struct ovl_fs *ofs = dentry->d_sb->s_fs_info;
34         return ofs->workdir;
35 }
36
37 const struct cred *ovl_override_creds(struct super_block *sb)
38 {
39         struct ovl_fs *ofs = sb->s_fs_info;
40
41         return override_creds(ofs->creator_cred);
42 }
43
44 /*
45  * Check if underlying fs supports file handles and try to determine encoding
46  * type, in order to deduce maximum inode number used by fs.
47  *
48  * Return 0 if file handles are not supported.
49  * Return 1 (FILEID_INO32_GEN) if fs uses the default 32bit inode encoding.
50  * Return -1 if fs uses a non default encoding with unknown inode size.
51  */
52 int ovl_can_decode_fh(struct super_block *sb)
53 {
54         if (!capable(CAP_DAC_READ_SEARCH))
55                 return 0;
56
57         if (!sb->s_export_op || !sb->s_export_op->fh_to_dentry)
58                 return 0;
59
60         return sb->s_export_op->encode_fh ? -1 : FILEID_INO32_GEN;
61 }
62
63 struct dentry *ovl_indexdir(struct super_block *sb)
64 {
65         struct ovl_fs *ofs = sb->s_fs_info;
66
67         return ofs->indexdir;
68 }
69
70 /* Index all files on copy up. For now only enabled for NFS export */
71 bool ovl_index_all(struct super_block *sb)
72 {
73         struct ovl_fs *ofs = sb->s_fs_info;
74
75         return ofs->config.nfs_export && ofs->config.index;
76 }
77
78 /* Verify lower origin on lookup. For now only enabled for NFS export */
79 bool ovl_verify_lower(struct super_block *sb)
80 {
81         struct ovl_fs *ofs = sb->s_fs_info;
82
83         return ofs->config.nfs_export && ofs->config.index;
84 }
85
86 struct ovl_entry *ovl_alloc_entry(unsigned int numlower)
87 {
88         size_t size = offsetof(struct ovl_entry, lowerstack[numlower]);
89         struct ovl_entry *oe = kzalloc(size, GFP_KERNEL);
90
91         if (oe)
92                 oe->numlower = numlower;
93
94         return oe;
95 }
96
97 #define OVL_D_REVALIDATE (DCACHE_OP_REVALIDATE | DCACHE_OP_WEAK_REVALIDATE)
98
99 bool ovl_dentry_remote(struct dentry *dentry)
100 {
101         return dentry->d_flags & OVL_D_REVALIDATE;
102 }
103
104 void ovl_dentry_update_reval(struct dentry *dentry, struct dentry *realdentry)
105 {
106         if (!ovl_dentry_remote(realdentry))
107                 return;
108
109         spin_lock(&dentry->d_lock);
110         dentry->d_flags |= realdentry->d_flags & OVL_D_REVALIDATE;
111         spin_unlock(&dentry->d_lock);
112 }
113
114 void ovl_dentry_init_reval(struct dentry *dentry, struct dentry *upperdentry)
115 {
116         return ovl_dentry_init_flags(dentry, upperdentry, OVL_D_REVALIDATE);
117 }
118
119 void ovl_dentry_init_flags(struct dentry *dentry, struct dentry *upperdentry,
120                            unsigned int mask)
121 {
122         struct ovl_entry *oe = OVL_E(dentry);
123         unsigned int i, flags = 0;
124
125         if (upperdentry)
126                 flags |= upperdentry->d_flags;
127         for (i = 0; i < oe->numlower; i++)
128                 flags |= oe->lowerstack[i].dentry->d_flags;
129
130         spin_lock(&dentry->d_lock);
131         dentry->d_flags &= ~mask;
132         dentry->d_flags |= flags & mask;
133         spin_unlock(&dentry->d_lock);
134 }
135
136 bool ovl_dentry_weird(struct dentry *dentry)
137 {
138         return dentry->d_flags & (DCACHE_NEED_AUTOMOUNT |
139                                   DCACHE_MANAGE_TRANSIT |
140                                   DCACHE_OP_HASH |
141                                   DCACHE_OP_COMPARE);
142 }
143
144 enum ovl_path_type ovl_path_type(struct dentry *dentry)
145 {
146         struct ovl_entry *oe = dentry->d_fsdata;
147         enum ovl_path_type type = 0;
148
149         if (ovl_dentry_upper(dentry)) {
150                 type = __OVL_PATH_UPPER;
151
152                 /*
153                  * Non-dir dentry can hold lower dentry of its copy up origin.
154                  */
155                 if (oe->numlower) {
156                         if (ovl_test_flag(OVL_CONST_INO, d_inode(dentry)))
157                                 type |= __OVL_PATH_ORIGIN;
158                         if (d_is_dir(dentry) ||
159                             !ovl_has_upperdata(d_inode(dentry)))
160                                 type |= __OVL_PATH_MERGE;
161                 }
162         } else {
163                 if (oe->numlower > 1)
164                         type |= __OVL_PATH_MERGE;
165         }
166         return type;
167 }
168
169 void ovl_path_upper(struct dentry *dentry, struct path *path)
170 {
171         struct ovl_fs *ofs = dentry->d_sb->s_fs_info;
172
173         path->mnt = ovl_upper_mnt(ofs);
174         path->dentry = ovl_dentry_upper(dentry);
175 }
176
177 void ovl_path_lower(struct dentry *dentry, struct path *path)
178 {
179         struct ovl_entry *oe = dentry->d_fsdata;
180
181         if (oe->numlower) {
182                 path->mnt = oe->lowerstack[0].layer->mnt;
183                 path->dentry = oe->lowerstack[0].dentry;
184         } else {
185                 *path = (struct path) { };
186         }
187 }
188
189 void ovl_path_lowerdata(struct dentry *dentry, struct path *path)
190 {
191         struct ovl_entry *oe = dentry->d_fsdata;
192
193         if (oe->numlower) {
194                 path->mnt = oe->lowerstack[oe->numlower - 1].layer->mnt;
195                 path->dentry = oe->lowerstack[oe->numlower - 1].dentry;
196         } else {
197                 *path = (struct path) { };
198         }
199 }
200
201 enum ovl_path_type ovl_path_real(struct dentry *dentry, struct path *path)
202 {
203         enum ovl_path_type type = ovl_path_type(dentry);
204
205         if (!OVL_TYPE_UPPER(type))
206                 ovl_path_lower(dentry, path);
207         else
208                 ovl_path_upper(dentry, path);
209
210         return type;
211 }
212
213 enum ovl_path_type ovl_path_realdata(struct dentry *dentry, struct path *path)
214 {
215         enum ovl_path_type type = ovl_path_type(dentry);
216
217         WARN_ON_ONCE(d_is_dir(dentry));
218
219         if (!OVL_TYPE_UPPER(type) || OVL_TYPE_MERGE(type))
220                 ovl_path_lowerdata(dentry, path);
221         else
222                 ovl_path_upper(dentry, path);
223
224         return type;
225 }
226
227 struct dentry *ovl_dentry_upper(struct dentry *dentry)
228 {
229         return ovl_upperdentry_dereference(OVL_I(d_inode(dentry)));
230 }
231
232 struct dentry *ovl_dentry_lower(struct dentry *dentry)
233 {
234         struct ovl_entry *oe = dentry->d_fsdata;
235
236         return oe->numlower ? oe->lowerstack[0].dentry : NULL;
237 }
238
239 const struct ovl_layer *ovl_layer_lower(struct dentry *dentry)
240 {
241         struct ovl_entry *oe = dentry->d_fsdata;
242
243         return oe->numlower ? oe->lowerstack[0].layer : NULL;
244 }
245
246 /*
247  * ovl_dentry_lower() could return either a data dentry or metacopy dentry
248  * depending on what is stored in lowerstack[0]. At times we need to find
249  * lower dentry which has data (and not metacopy dentry). This helper
250  * returns the lower data dentry.
251  */
252 struct dentry *ovl_dentry_lowerdata(struct dentry *dentry)
253 {
254         struct ovl_entry *oe = dentry->d_fsdata;
255
256         return oe->numlower ? oe->lowerstack[oe->numlower - 1].dentry : NULL;
257 }
258
259 struct dentry *ovl_dentry_real(struct dentry *dentry)
260 {
261         return ovl_dentry_upper(dentry) ?: ovl_dentry_lower(dentry);
262 }
263
264 struct dentry *ovl_i_dentry_upper(struct inode *inode)
265 {
266         return ovl_upperdentry_dereference(OVL_I(inode));
267 }
268
269 void ovl_i_path_real(struct inode *inode, struct path *path)
270 {
271         path->dentry = ovl_i_dentry_upper(inode);
272         if (!path->dentry) {
273                 path->dentry = OVL_I(inode)->lowerpath.dentry;
274                 path->mnt = OVL_I(inode)->lowerpath.layer->mnt;
275         } else {
276                 path->mnt = ovl_upper_mnt(OVL_FS(inode->i_sb));
277         }
278 }
279
280 struct inode *ovl_inode_upper(struct inode *inode)
281 {
282         struct dentry *upperdentry = ovl_i_dentry_upper(inode);
283
284         return upperdentry ? d_inode(upperdentry) : NULL;
285 }
286
287 struct inode *ovl_inode_lower(struct inode *inode)
288 {
289         struct dentry *lowerdentry = OVL_I(inode)->lowerpath.dentry;
290
291         return lowerdentry ? d_inode(lowerdentry) : NULL;
292 }
293
294 struct inode *ovl_inode_real(struct inode *inode)
295 {
296         return ovl_inode_upper(inode) ?: ovl_inode_lower(inode);
297 }
298
299 /* Return inode which contains lower data. Do not return metacopy */
300 struct inode *ovl_inode_lowerdata(struct inode *inode)
301 {
302         if (WARN_ON(!S_ISREG(inode->i_mode)))
303                 return NULL;
304
305         return OVL_I(inode)->lowerdata ?: ovl_inode_lower(inode);
306 }
307
308 /* Return real inode which contains data. Does not return metacopy inode */
309 struct inode *ovl_inode_realdata(struct inode *inode)
310 {
311         struct inode *upperinode;
312
313         upperinode = ovl_inode_upper(inode);
314         if (upperinode && ovl_has_upperdata(inode))
315                 return upperinode;
316
317         return ovl_inode_lowerdata(inode);
318 }
319
320 struct ovl_dir_cache *ovl_dir_cache(struct inode *inode)
321 {
322         return OVL_I(inode)->cache;
323 }
324
325 void ovl_set_dir_cache(struct inode *inode, struct ovl_dir_cache *cache)
326 {
327         OVL_I(inode)->cache = cache;
328 }
329
330 void ovl_dentry_set_flag(unsigned long flag, struct dentry *dentry)
331 {
332         set_bit(flag, &OVL_E(dentry)->flags);
333 }
334
335 void ovl_dentry_clear_flag(unsigned long flag, struct dentry *dentry)
336 {
337         clear_bit(flag, &OVL_E(dentry)->flags);
338 }
339
340 bool ovl_dentry_test_flag(unsigned long flag, struct dentry *dentry)
341 {
342         return test_bit(flag, &OVL_E(dentry)->flags);
343 }
344
345 bool ovl_dentry_is_opaque(struct dentry *dentry)
346 {
347         return ovl_dentry_test_flag(OVL_E_OPAQUE, dentry);
348 }
349
350 bool ovl_dentry_is_whiteout(struct dentry *dentry)
351 {
352         return !dentry->d_inode && ovl_dentry_is_opaque(dentry);
353 }
354
355 void ovl_dentry_set_opaque(struct dentry *dentry)
356 {
357         ovl_dentry_set_flag(OVL_E_OPAQUE, dentry);
358 }
359
360 /*
361  * For hard links and decoded file handles, it's possible for ovl_dentry_upper()
362  * to return positive, while there's no actual upper alias for the inode.
363  * Copy up code needs to know about the existence of the upper alias, so it
364  * can't use ovl_dentry_upper().
365  */
366 bool ovl_dentry_has_upper_alias(struct dentry *dentry)
367 {
368         return ovl_dentry_test_flag(OVL_E_UPPER_ALIAS, dentry);
369 }
370
371 void ovl_dentry_set_upper_alias(struct dentry *dentry)
372 {
373         ovl_dentry_set_flag(OVL_E_UPPER_ALIAS, dentry);
374 }
375
376 static bool ovl_should_check_upperdata(struct inode *inode)
377 {
378         if (!S_ISREG(inode->i_mode))
379                 return false;
380
381         if (!ovl_inode_lower(inode))
382                 return false;
383
384         return true;
385 }
386
387 bool ovl_has_upperdata(struct inode *inode)
388 {
389         if (!ovl_should_check_upperdata(inode))
390                 return true;
391
392         if (!ovl_test_flag(OVL_UPPERDATA, inode))
393                 return false;
394         /*
395          * Pairs with smp_wmb() in ovl_set_upperdata(). Main user of
396          * ovl_has_upperdata() is ovl_copy_up_meta_inode_data(). Make sure
397          * if setting of OVL_UPPERDATA is visible, then effects of writes
398          * before that are visible too.
399          */
400         smp_rmb();
401         return true;
402 }
403
404 void ovl_set_upperdata(struct inode *inode)
405 {
406         /*
407          * Pairs with smp_rmb() in ovl_has_upperdata(). Make sure
408          * if OVL_UPPERDATA flag is visible, then effects of write operations
409          * before it are visible as well.
410          */
411         smp_wmb();
412         ovl_set_flag(OVL_UPPERDATA, inode);
413 }
414
415 /* Caller should hold ovl_inode->lock */
416 bool ovl_dentry_needs_data_copy_up_locked(struct dentry *dentry, int flags)
417 {
418         if (!ovl_open_flags_need_copy_up(flags))
419                 return false;
420
421         return !ovl_test_flag(OVL_UPPERDATA, d_inode(dentry));
422 }
423
424 bool ovl_dentry_needs_data_copy_up(struct dentry *dentry, int flags)
425 {
426         if (!ovl_open_flags_need_copy_up(flags))
427                 return false;
428
429         return !ovl_has_upperdata(d_inode(dentry));
430 }
431
432 bool ovl_redirect_dir(struct super_block *sb)
433 {
434         struct ovl_fs *ofs = sb->s_fs_info;
435
436         return ofs->config.redirect_dir && !ofs->noxattr;
437 }
438
439 const char *ovl_dentry_get_redirect(struct dentry *dentry)
440 {
441         return OVL_I(d_inode(dentry))->redirect;
442 }
443
444 void ovl_dentry_set_redirect(struct dentry *dentry, const char *redirect)
445 {
446         struct ovl_inode *oi = OVL_I(d_inode(dentry));
447
448         kfree(oi->redirect);
449         oi->redirect = redirect;
450 }
451
452 void ovl_inode_update(struct inode *inode, struct dentry *upperdentry)
453 {
454         struct inode *upperinode = d_inode(upperdentry);
455
456         WARN_ON(OVL_I(inode)->__upperdentry);
457
458         /*
459          * Make sure upperdentry is consistent before making it visible
460          */
461         smp_wmb();
462         OVL_I(inode)->__upperdentry = upperdentry;
463         if (inode_unhashed(inode)) {
464                 inode->i_private = upperinode;
465                 __insert_inode_hash(inode, (unsigned long) upperinode);
466         }
467 }
468
469 static void ovl_dir_version_inc(struct dentry *dentry, bool impurity)
470 {
471         struct inode *inode = d_inode(dentry);
472
473         WARN_ON(!inode_is_locked(inode));
474         WARN_ON(!d_is_dir(dentry));
475         /*
476          * Version is used by readdir code to keep cache consistent.
477          * For merge dirs (or dirs with origin) all changes need to be noted.
478          * For non-merge dirs, cache contains only impure entries (i.e. ones
479          * which have been copied up and have origins), so only need to note
480          * changes to impure entries.
481          */
482         if (!ovl_dir_is_real(dentry) || impurity)
483                 OVL_I(inode)->version++;
484 }
485
486 void ovl_dir_modified(struct dentry *dentry, bool impurity)
487 {
488         /* Copy mtime/ctime */
489         ovl_copyattr(d_inode(dentry));
490
491         ovl_dir_version_inc(dentry, impurity);
492 }
493
494 u64 ovl_dentry_version_get(struct dentry *dentry)
495 {
496         struct inode *inode = d_inode(dentry);
497
498         WARN_ON(!inode_is_locked(inode));
499         return OVL_I(inode)->version;
500 }
501
502 bool ovl_is_whiteout(struct dentry *dentry)
503 {
504         struct inode *inode = dentry->d_inode;
505
506         return inode && IS_WHITEOUT(inode);
507 }
508
509 struct file *ovl_path_open(const struct path *path, int flags)
510 {
511         struct inode *inode = d_inode(path->dentry);
512         struct user_namespace *real_mnt_userns = mnt_user_ns(path->mnt);
513         int err, acc_mode;
514
515         if (flags & ~(O_ACCMODE | O_LARGEFILE))
516                 BUG();
517
518         switch (flags & O_ACCMODE) {
519         case O_RDONLY:
520                 acc_mode = MAY_READ;
521                 break;
522         case O_WRONLY:
523                 acc_mode = MAY_WRITE;
524                 break;
525         default:
526                 BUG();
527         }
528
529         err = inode_permission(real_mnt_userns, inode, acc_mode | MAY_OPEN);
530         if (err)
531                 return ERR_PTR(err);
532
533         /* O_NOATIME is an optimization, don't fail if not permitted */
534         if (inode_owner_or_capable(real_mnt_userns, inode))
535                 flags |= O_NOATIME;
536
537         return dentry_open(path, flags, current_cred());
538 }
539
540 /* Caller should hold ovl_inode->lock */
541 static bool ovl_already_copied_up_locked(struct dentry *dentry, int flags)
542 {
543         bool disconnected = dentry->d_flags & DCACHE_DISCONNECTED;
544
545         if (ovl_dentry_upper(dentry) &&
546             (ovl_dentry_has_upper_alias(dentry) || disconnected) &&
547             !ovl_dentry_needs_data_copy_up_locked(dentry, flags))
548                 return true;
549
550         return false;
551 }
552
553 bool ovl_already_copied_up(struct dentry *dentry, int flags)
554 {
555         bool disconnected = dentry->d_flags & DCACHE_DISCONNECTED;
556
557         /*
558          * Check if copy-up has happened as well as for upper alias (in
559          * case of hard links) is there.
560          *
561          * Both checks are lockless:
562          *  - false negatives: will recheck under oi->lock
563          *  - false positives:
564          *    + ovl_dentry_upper() uses memory barriers to ensure the
565          *      upper dentry is up-to-date
566          *    + ovl_dentry_has_upper_alias() relies on locking of
567          *      upper parent i_rwsem to prevent reordering copy-up
568          *      with rename.
569          */
570         if (ovl_dentry_upper(dentry) &&
571             (ovl_dentry_has_upper_alias(dentry) || disconnected) &&
572             !ovl_dentry_needs_data_copy_up(dentry, flags))
573                 return true;
574
575         return false;
576 }
577
578 int ovl_copy_up_start(struct dentry *dentry, int flags)
579 {
580         struct inode *inode = d_inode(dentry);
581         int err;
582
583         err = ovl_inode_lock_interruptible(inode);
584         if (!err && ovl_already_copied_up_locked(dentry, flags)) {
585                 err = 1; /* Already copied up */
586                 ovl_inode_unlock(inode);
587         }
588
589         return err;
590 }
591
592 void ovl_copy_up_end(struct dentry *dentry)
593 {
594         ovl_inode_unlock(d_inode(dentry));
595 }
596
597 bool ovl_path_check_origin_xattr(struct ovl_fs *ofs, const struct path *path)
598 {
599         int res;
600
601         res = ovl_path_getxattr(ofs, path, OVL_XATTR_ORIGIN, NULL, 0);
602
603         /* Zero size value means "copied up but origin unknown" */
604         if (res >= 0)
605                 return true;
606
607         return false;
608 }
609
610 bool ovl_path_check_dir_xattr(struct ovl_fs *ofs, const struct path *path,
611                                enum ovl_xattr ox)
612 {
613         int res;
614         char val;
615
616         if (!d_is_dir(path->dentry))
617                 return false;
618
619         res = ovl_path_getxattr(ofs, path, ox, &val, 1);
620         if (res == 1 && val == 'y')
621                 return true;
622
623         return false;
624 }
625
626 #define OVL_XATTR_OPAQUE_POSTFIX        "opaque"
627 #define OVL_XATTR_REDIRECT_POSTFIX      "redirect"
628 #define OVL_XATTR_ORIGIN_POSTFIX        "origin"
629 #define OVL_XATTR_IMPURE_POSTFIX        "impure"
630 #define OVL_XATTR_NLINK_POSTFIX         "nlink"
631 #define OVL_XATTR_UPPER_POSTFIX         "upper"
632 #define OVL_XATTR_METACOPY_POSTFIX      "metacopy"
633 #define OVL_XATTR_PROTATTR_POSTFIX      "protattr"
634
635 #define OVL_XATTR_TAB_ENTRY(x) \
636         [x] = { [false] = OVL_XATTR_TRUSTED_PREFIX x ## _POSTFIX, \
637                 [true] = OVL_XATTR_USER_PREFIX x ## _POSTFIX }
638
639 const char *const ovl_xattr_table[][2] = {
640         OVL_XATTR_TAB_ENTRY(OVL_XATTR_OPAQUE),
641         OVL_XATTR_TAB_ENTRY(OVL_XATTR_REDIRECT),
642         OVL_XATTR_TAB_ENTRY(OVL_XATTR_ORIGIN),
643         OVL_XATTR_TAB_ENTRY(OVL_XATTR_IMPURE),
644         OVL_XATTR_TAB_ENTRY(OVL_XATTR_NLINK),
645         OVL_XATTR_TAB_ENTRY(OVL_XATTR_UPPER),
646         OVL_XATTR_TAB_ENTRY(OVL_XATTR_METACOPY),
647         OVL_XATTR_TAB_ENTRY(OVL_XATTR_PROTATTR),
648 };
649
650 int ovl_check_setxattr(struct ovl_fs *ofs, struct dentry *upperdentry,
651                        enum ovl_xattr ox, const void *value, size_t size,
652                        int xerr)
653 {
654         int err;
655
656         if (ofs->noxattr)
657                 return xerr;
658
659         err = ovl_setxattr(ofs, upperdentry, ox, value, size);
660
661         if (err == -EOPNOTSUPP) {
662                 pr_warn("cannot set %s xattr on upper\n", ovl_xattr(ofs, ox));
663                 ofs->noxattr = true;
664                 return xerr;
665         }
666
667         return err;
668 }
669
670 int ovl_set_impure(struct dentry *dentry, struct dentry *upperdentry)
671 {
672         struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
673         int err;
674
675         if (ovl_test_flag(OVL_IMPURE, d_inode(dentry)))
676                 return 0;
677
678         /*
679          * Do not fail when upper doesn't support xattrs.
680          * Upper inodes won't have origin nor redirect xattr anyway.
681          */
682         err = ovl_check_setxattr(ofs, upperdentry, OVL_XATTR_IMPURE, "y", 1, 0);
683         if (!err)
684                 ovl_set_flag(OVL_IMPURE, d_inode(dentry));
685
686         return err;
687 }
688
689
690 #define OVL_PROTATTR_MAX 32 /* Reserved for future flags */
691
692 void ovl_check_protattr(struct inode *inode, struct dentry *upper)
693 {
694         struct ovl_fs *ofs = OVL_FS(inode->i_sb);
695         u32 iflags = inode->i_flags & OVL_PROT_I_FLAGS_MASK;
696         char buf[OVL_PROTATTR_MAX+1];
697         int res, n;
698
699         res = ovl_getxattr_upper(ofs, upper, OVL_XATTR_PROTATTR, buf,
700                                  OVL_PROTATTR_MAX);
701         if (res < 0)
702                 return;
703
704         /*
705          * Initialize inode flags from overlay.protattr xattr and upper inode
706          * flags.  If upper inode has those fileattr flags set (i.e. from old
707          * kernel), we do not clear them on ovl_get_inode(), but we will clear
708          * them on next fileattr_set().
709          */
710         for (n = 0; n < res; n++) {
711                 if (buf[n] == 'a')
712                         iflags |= S_APPEND;
713                 else if (buf[n] == 'i')
714                         iflags |= S_IMMUTABLE;
715                 else
716                         break;
717         }
718
719         if (!res || n < res) {
720                 pr_warn_ratelimited("incompatible overlay.protattr format (%pd2, len=%d)\n",
721                                     upper, res);
722         } else {
723                 inode_set_flags(inode, iflags, OVL_PROT_I_FLAGS_MASK);
724         }
725 }
726
727 int ovl_set_protattr(struct inode *inode, struct dentry *upper,
728                       struct fileattr *fa)
729 {
730         struct ovl_fs *ofs = OVL_FS(inode->i_sb);
731         char buf[OVL_PROTATTR_MAX];
732         int len = 0, err = 0;
733         u32 iflags = 0;
734
735         BUILD_BUG_ON(HWEIGHT32(OVL_PROT_FS_FLAGS_MASK) > OVL_PROTATTR_MAX);
736
737         if (fa->flags & FS_APPEND_FL) {
738                 buf[len++] = 'a';
739                 iflags |= S_APPEND;
740         }
741         if (fa->flags & FS_IMMUTABLE_FL) {
742                 buf[len++] = 'i';
743                 iflags |= S_IMMUTABLE;
744         }
745
746         /*
747          * Do not allow to set protection flags when upper doesn't support
748          * xattrs, because we do not set those fileattr flags on upper inode.
749          * Remove xattr if it exist and all protection flags are cleared.
750          */
751         if (len) {
752                 err = ovl_check_setxattr(ofs, upper, OVL_XATTR_PROTATTR,
753                                          buf, len, -EPERM);
754         } else if (inode->i_flags & OVL_PROT_I_FLAGS_MASK) {
755                 err = ovl_removexattr(ofs, upper, OVL_XATTR_PROTATTR);
756                 if (err == -EOPNOTSUPP || err == -ENODATA)
757                         err = 0;
758         }
759         if (err)
760                 return err;
761
762         inode_set_flags(inode, iflags, OVL_PROT_I_FLAGS_MASK);
763
764         /* Mask out the fileattr flags that should not be set in upper inode */
765         fa->flags &= ~OVL_PROT_FS_FLAGS_MASK;
766         fa->fsx_xflags &= ~OVL_PROT_FSX_FLAGS_MASK;
767
768         return 0;
769 }
770
771 /**
772  * Caller must hold a reference to inode to prevent it from being freed while
773  * it is marked inuse.
774  */
775 bool ovl_inuse_trylock(struct dentry *dentry)
776 {
777         struct inode *inode = d_inode(dentry);
778         bool locked = false;
779
780         spin_lock(&inode->i_lock);
781         if (!(inode->i_state & I_OVL_INUSE)) {
782                 inode->i_state |= I_OVL_INUSE;
783                 locked = true;
784         }
785         spin_unlock(&inode->i_lock);
786
787         return locked;
788 }
789
790 void ovl_inuse_unlock(struct dentry *dentry)
791 {
792         if (dentry) {
793                 struct inode *inode = d_inode(dentry);
794
795                 spin_lock(&inode->i_lock);
796                 WARN_ON(!(inode->i_state & I_OVL_INUSE));
797                 inode->i_state &= ~I_OVL_INUSE;
798                 spin_unlock(&inode->i_lock);
799         }
800 }
801
802 bool ovl_is_inuse(struct dentry *dentry)
803 {
804         struct inode *inode = d_inode(dentry);
805         bool inuse;
806
807         spin_lock(&inode->i_lock);
808         inuse = (inode->i_state & I_OVL_INUSE);
809         spin_unlock(&inode->i_lock);
810
811         return inuse;
812 }
813
814 /*
815  * Does this overlay dentry need to be indexed on copy up?
816  */
817 bool ovl_need_index(struct dentry *dentry)
818 {
819         struct dentry *lower = ovl_dentry_lower(dentry);
820
821         if (!lower || !ovl_indexdir(dentry->d_sb))
822                 return false;
823
824         /* Index all files for NFS export and consistency verification */
825         if (ovl_index_all(dentry->d_sb))
826                 return true;
827
828         /* Index only lower hardlinks on copy up */
829         if (!d_is_dir(lower) && d_inode(lower)->i_nlink > 1)
830                 return true;
831
832         return false;
833 }
834
835 /* Caller must hold OVL_I(inode)->lock */
836 static void ovl_cleanup_index(struct dentry *dentry)
837 {
838         struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
839         struct dentry *indexdir = ovl_indexdir(dentry->d_sb);
840         struct inode *dir = indexdir->d_inode;
841         struct dentry *lowerdentry = ovl_dentry_lower(dentry);
842         struct dentry *upperdentry = ovl_dentry_upper(dentry);
843         struct dentry *index = NULL;
844         struct inode *inode;
845         struct qstr name = { };
846         int err;
847
848         err = ovl_get_index_name(ofs, lowerdentry, &name);
849         if (err)
850                 goto fail;
851
852         inode = d_inode(upperdentry);
853         if (!S_ISDIR(inode->i_mode) && inode->i_nlink != 1) {
854                 pr_warn_ratelimited("cleanup linked index (%pd2, ino=%lu, nlink=%u)\n",
855                                     upperdentry, inode->i_ino, inode->i_nlink);
856                 /*
857                  * We either have a bug with persistent union nlink or a lower
858                  * hardlink was added while overlay is mounted. Adding a lower
859                  * hardlink and then unlinking all overlay hardlinks would drop
860                  * overlay nlink to zero before all upper inodes are unlinked.
861                  * As a safety measure, when that situation is detected, set
862                  * the overlay nlink to the index inode nlink minus one for the
863                  * index entry itself.
864                  */
865                 set_nlink(d_inode(dentry), inode->i_nlink - 1);
866                 ovl_set_nlink_upper(dentry);
867                 goto out;
868         }
869
870         inode_lock_nested(dir, I_MUTEX_PARENT);
871         index = ovl_lookup_upper(ofs, name.name, indexdir, name.len);
872         err = PTR_ERR(index);
873         if (IS_ERR(index)) {
874                 index = NULL;
875         } else if (ovl_index_all(dentry->d_sb)) {
876                 /* Whiteout orphan index to block future open by handle */
877                 err = ovl_cleanup_and_whiteout(OVL_FS(dentry->d_sb),
878                                                dir, index);
879         } else {
880                 /* Cleanup orphan index entries */
881                 err = ovl_cleanup(ofs, dir, index);
882         }
883
884         inode_unlock(dir);
885         if (err)
886                 goto fail;
887
888 out:
889         kfree(name.name);
890         dput(index);
891         return;
892
893 fail:
894         pr_err("cleanup index of '%pd2' failed (%i)\n", dentry, err);
895         goto out;
896 }
897
898 /*
899  * Operations that change overlay inode and upper inode nlink need to be
900  * synchronized with copy up for persistent nlink accounting.
901  */
902 int ovl_nlink_start(struct dentry *dentry)
903 {
904         struct inode *inode = d_inode(dentry);
905         const struct cred *old_cred;
906         int err;
907
908         if (WARN_ON(!inode))
909                 return -ENOENT;
910
911         /*
912          * With inodes index is enabled, we store the union overlay nlink
913          * in an xattr on the index inode. When whiting out an indexed lower,
914          * we need to decrement the overlay persistent nlink, but before the
915          * first copy up, we have no upper index inode to store the xattr.
916          *
917          * As a workaround, before whiteout/rename over an indexed lower,
918          * copy up to create the upper index. Creating the upper index will
919          * initialize the overlay nlink, so it could be dropped if unlink
920          * or rename succeeds.
921          *
922          * TODO: implement metadata only index copy up when called with
923          *       ovl_copy_up_flags(dentry, O_PATH).
924          */
925         if (ovl_need_index(dentry) && !ovl_dentry_has_upper_alias(dentry)) {
926                 err = ovl_copy_up(dentry);
927                 if (err)
928                         return err;
929         }
930
931         err = ovl_inode_lock_interruptible(inode);
932         if (err)
933                 return err;
934
935         if (d_is_dir(dentry) || !ovl_test_flag(OVL_INDEX, inode))
936                 goto out;
937
938         old_cred = ovl_override_creds(dentry->d_sb);
939         /*
940          * The overlay inode nlink should be incremented/decremented IFF the
941          * upper operation succeeds, along with nlink change of upper inode.
942          * Therefore, before link/unlink/rename, we store the union nlink
943          * value relative to the upper inode nlink in an upper inode xattr.
944          */
945         err = ovl_set_nlink_upper(dentry);
946         revert_creds(old_cred);
947
948 out:
949         if (err)
950                 ovl_inode_unlock(inode);
951
952         return err;
953 }
954
955 void ovl_nlink_end(struct dentry *dentry)
956 {
957         struct inode *inode = d_inode(dentry);
958
959         if (ovl_test_flag(OVL_INDEX, inode) && inode->i_nlink == 0) {
960                 const struct cred *old_cred;
961
962                 old_cred = ovl_override_creds(dentry->d_sb);
963                 ovl_cleanup_index(dentry);
964                 revert_creds(old_cred);
965         }
966
967         ovl_inode_unlock(inode);
968 }
969
970 int ovl_lock_rename_workdir(struct dentry *workdir, struct dentry *upperdir)
971 {
972         /* Workdir should not be the same as upperdir */
973         if (workdir == upperdir)
974                 goto err;
975
976         /* Workdir should not be subdir of upperdir and vice versa */
977         if (lock_rename(workdir, upperdir) != NULL)
978                 goto err_unlock;
979
980         return 0;
981
982 err_unlock:
983         unlock_rename(workdir, upperdir);
984 err:
985         pr_err("failed to lock workdir+upperdir\n");
986         return -EIO;
987 }
988
989 /* err < 0, 0 if no metacopy xattr, 1 if metacopy xattr found */
990 int ovl_check_metacopy_xattr(struct ovl_fs *ofs, const struct path *path)
991 {
992         int res;
993
994         /* Only regular files can have metacopy xattr */
995         if (!S_ISREG(d_inode(path->dentry)->i_mode))
996                 return 0;
997
998         res = ovl_path_getxattr(ofs, path, OVL_XATTR_METACOPY, NULL, 0);
999         if (res < 0) {
1000                 if (res == -ENODATA || res == -EOPNOTSUPP)
1001                         return 0;
1002                 /*
1003                  * getxattr on user.* may fail with EACCES in case there's no
1004                  * read permission on the inode.  Not much we can do, other than
1005                  * tell the caller that this is not a metacopy inode.
1006                  */
1007                 if (ofs->config.userxattr && res == -EACCES)
1008                         return 0;
1009                 goto out;
1010         }
1011
1012         return 1;
1013 out:
1014         pr_warn_ratelimited("failed to get metacopy (%i)\n", res);
1015         return res;
1016 }
1017
1018 bool ovl_is_metacopy_dentry(struct dentry *dentry)
1019 {
1020         struct ovl_entry *oe = dentry->d_fsdata;
1021
1022         if (!d_is_reg(dentry))
1023                 return false;
1024
1025         if (ovl_dentry_upper(dentry)) {
1026                 if (!ovl_has_upperdata(d_inode(dentry)))
1027                         return true;
1028                 return false;
1029         }
1030
1031         return (oe->numlower > 1);
1032 }
1033
1034 char *ovl_get_redirect_xattr(struct ovl_fs *ofs, const struct path *path, int padding)
1035 {
1036         int res;
1037         char *s, *next, *buf = NULL;
1038
1039         res = ovl_path_getxattr(ofs, path, OVL_XATTR_REDIRECT, NULL, 0);
1040         if (res == -ENODATA || res == -EOPNOTSUPP)
1041                 return NULL;
1042         if (res < 0)
1043                 goto fail;
1044         if (res == 0)
1045                 goto invalid;
1046
1047         buf = kzalloc(res + padding + 1, GFP_KERNEL);
1048         if (!buf)
1049                 return ERR_PTR(-ENOMEM);
1050
1051         res = ovl_path_getxattr(ofs, path, OVL_XATTR_REDIRECT, buf, res);
1052         if (res < 0)
1053                 goto fail;
1054         if (res == 0)
1055                 goto invalid;
1056
1057         if (buf[0] == '/') {
1058                 for (s = buf; *s++ == '/'; s = next) {
1059                         next = strchrnul(s, '/');
1060                         if (s == next)
1061                                 goto invalid;
1062                 }
1063         } else {
1064                 if (strchr(buf, '/') != NULL)
1065                         goto invalid;
1066         }
1067
1068         return buf;
1069 invalid:
1070         pr_warn_ratelimited("invalid redirect (%s)\n", buf);
1071         res = -EINVAL;
1072         goto err_free;
1073 fail:
1074         pr_warn_ratelimited("failed to get redirect (%i)\n", res);
1075 err_free:
1076         kfree(buf);
1077         return ERR_PTR(res);
1078 }
1079
1080 /*
1081  * ovl_sync_status() - Check fs sync status for volatile mounts
1082  *
1083  * Returns 1 if this is not a volatile mount and a real sync is required.
1084  *
1085  * Returns 0 if syncing can be skipped because mount is volatile, and no errors
1086  * have occurred on the upperdir since the mount.
1087  *
1088  * Returns -errno if it is a volatile mount, and the error that occurred since
1089  * the last mount. If the error code changes, it'll return the latest error
1090  * code.
1091  */
1092
1093 int ovl_sync_status(struct ovl_fs *ofs)
1094 {
1095         struct vfsmount *mnt;
1096
1097         if (ovl_should_sync(ofs))
1098                 return 1;
1099
1100         mnt = ovl_upper_mnt(ofs);
1101         if (!mnt)
1102                 return 0;
1103
1104         return errseq_check(&mnt->mnt_sb->s_wb_err, ofs->errseq);
1105 }
1106
1107 /*
1108  * ovl_copyattr() - copy inode attributes from layer to ovl inode
1109  *
1110  * When overlay copies inode information from an upper or lower layer to the
1111  * relevant overlay inode it will apply the idmapping of the upper or lower
1112  * layer when doing so ensuring that the ovl inode ownership will correctly
1113  * reflect the ownership of the idmapped upper or lower layer. For example, an
1114  * idmapped upper or lower layer mapping id 1001 to id 1000 will take care to
1115  * map any lower or upper inode owned by id 1001 to id 1000. These mapping
1116  * helpers are nops when the relevant layer isn't idmapped.
1117  */
1118 void ovl_copyattr(struct inode *inode)
1119 {
1120         struct path realpath;
1121         struct inode *realinode;
1122         struct user_namespace *real_mnt_userns;
1123
1124         ovl_i_path_real(inode, &realpath);
1125         realinode = d_inode(realpath.dentry);
1126         real_mnt_userns = mnt_user_ns(realpath.mnt);
1127
1128         inode->i_uid = i_uid_into_mnt(real_mnt_userns, realinode);
1129         inode->i_gid = i_gid_into_mnt(real_mnt_userns, realinode);
1130         inode->i_mode = realinode->i_mode;
1131         inode->i_atime = realinode->i_atime;
1132         inode->i_mtime = realinode->i_mtime;
1133         inode->i_ctime = realinode->i_ctime;
1134         i_size_write(inode, i_size_read(realinode));
1135 }