ovl: Always reevaluate the file signature for IMA
[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 struct inode *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         return path->dentry ? d_inode_rcu(path->dentry) : NULL;
280 }
281
282 struct inode *ovl_inode_upper(struct inode *inode)
283 {
284         struct dentry *upperdentry = ovl_i_dentry_upper(inode);
285
286         return upperdentry ? d_inode(upperdentry) : NULL;
287 }
288
289 struct inode *ovl_inode_lower(struct inode *inode)
290 {
291         struct dentry *lowerdentry = OVL_I(inode)->lowerpath.dentry;
292
293         return lowerdentry ? d_inode(lowerdentry) : NULL;
294 }
295
296 struct inode *ovl_inode_real(struct inode *inode)
297 {
298         return ovl_inode_upper(inode) ?: ovl_inode_lower(inode);
299 }
300
301 /* Return inode which contains lower data. Do not return metacopy */
302 struct inode *ovl_inode_lowerdata(struct inode *inode)
303 {
304         if (WARN_ON(!S_ISREG(inode->i_mode)))
305                 return NULL;
306
307         return OVL_I(inode)->lowerdata ?: ovl_inode_lower(inode);
308 }
309
310 /* Return real inode which contains data. Does not return metacopy inode */
311 struct inode *ovl_inode_realdata(struct inode *inode)
312 {
313         struct inode *upperinode;
314
315         upperinode = ovl_inode_upper(inode);
316         if (upperinode && ovl_has_upperdata(inode))
317                 return upperinode;
318
319         return ovl_inode_lowerdata(inode);
320 }
321
322 struct ovl_dir_cache *ovl_dir_cache(struct inode *inode)
323 {
324         return OVL_I(inode)->cache;
325 }
326
327 void ovl_set_dir_cache(struct inode *inode, struct ovl_dir_cache *cache)
328 {
329         OVL_I(inode)->cache = cache;
330 }
331
332 void ovl_dentry_set_flag(unsigned long flag, struct dentry *dentry)
333 {
334         set_bit(flag, &OVL_E(dentry)->flags);
335 }
336
337 void ovl_dentry_clear_flag(unsigned long flag, struct dentry *dentry)
338 {
339         clear_bit(flag, &OVL_E(dentry)->flags);
340 }
341
342 bool ovl_dentry_test_flag(unsigned long flag, struct dentry *dentry)
343 {
344         return test_bit(flag, &OVL_E(dentry)->flags);
345 }
346
347 bool ovl_dentry_is_opaque(struct dentry *dentry)
348 {
349         return ovl_dentry_test_flag(OVL_E_OPAQUE, dentry);
350 }
351
352 bool ovl_dentry_is_whiteout(struct dentry *dentry)
353 {
354         return !dentry->d_inode && ovl_dentry_is_opaque(dentry);
355 }
356
357 void ovl_dentry_set_opaque(struct dentry *dentry)
358 {
359         ovl_dentry_set_flag(OVL_E_OPAQUE, dentry);
360 }
361
362 /*
363  * For hard links and decoded file handles, it's possible for ovl_dentry_upper()
364  * to return positive, while there's no actual upper alias for the inode.
365  * Copy up code needs to know about the existence of the upper alias, so it
366  * can't use ovl_dentry_upper().
367  */
368 bool ovl_dentry_has_upper_alias(struct dentry *dentry)
369 {
370         return ovl_dentry_test_flag(OVL_E_UPPER_ALIAS, dentry);
371 }
372
373 void ovl_dentry_set_upper_alias(struct dentry *dentry)
374 {
375         ovl_dentry_set_flag(OVL_E_UPPER_ALIAS, dentry);
376 }
377
378 static bool ovl_should_check_upperdata(struct inode *inode)
379 {
380         if (!S_ISREG(inode->i_mode))
381                 return false;
382
383         if (!ovl_inode_lower(inode))
384                 return false;
385
386         return true;
387 }
388
389 bool ovl_has_upperdata(struct inode *inode)
390 {
391         if (!ovl_should_check_upperdata(inode))
392                 return true;
393
394         if (!ovl_test_flag(OVL_UPPERDATA, inode))
395                 return false;
396         /*
397          * Pairs with smp_wmb() in ovl_set_upperdata(). Main user of
398          * ovl_has_upperdata() is ovl_copy_up_meta_inode_data(). Make sure
399          * if setting of OVL_UPPERDATA is visible, then effects of writes
400          * before that are visible too.
401          */
402         smp_rmb();
403         return true;
404 }
405
406 void ovl_set_upperdata(struct inode *inode)
407 {
408         /*
409          * Pairs with smp_rmb() in ovl_has_upperdata(). Make sure
410          * if OVL_UPPERDATA flag is visible, then effects of write operations
411          * before it are visible as well.
412          */
413         smp_wmb();
414         ovl_set_flag(OVL_UPPERDATA, inode);
415 }
416
417 /* Caller should hold ovl_inode->lock */
418 bool ovl_dentry_needs_data_copy_up_locked(struct dentry *dentry, int flags)
419 {
420         if (!ovl_open_flags_need_copy_up(flags))
421                 return false;
422
423         return !ovl_test_flag(OVL_UPPERDATA, d_inode(dentry));
424 }
425
426 bool ovl_dentry_needs_data_copy_up(struct dentry *dentry, int flags)
427 {
428         if (!ovl_open_flags_need_copy_up(flags))
429                 return false;
430
431         return !ovl_has_upperdata(d_inode(dentry));
432 }
433
434 bool ovl_redirect_dir(struct super_block *sb)
435 {
436         struct ovl_fs *ofs = sb->s_fs_info;
437
438         return ofs->config.redirect_dir && !ofs->noxattr;
439 }
440
441 const char *ovl_dentry_get_redirect(struct dentry *dentry)
442 {
443         return OVL_I(d_inode(dentry))->redirect;
444 }
445
446 void ovl_dentry_set_redirect(struct dentry *dentry, const char *redirect)
447 {
448         struct ovl_inode *oi = OVL_I(d_inode(dentry));
449
450         kfree(oi->redirect);
451         oi->redirect = redirect;
452 }
453
454 void ovl_inode_update(struct inode *inode, struct dentry *upperdentry)
455 {
456         struct inode *upperinode = d_inode(upperdentry);
457
458         WARN_ON(OVL_I(inode)->__upperdentry);
459
460         /*
461          * Make sure upperdentry is consistent before making it visible
462          */
463         smp_wmb();
464         OVL_I(inode)->__upperdentry = upperdentry;
465         if (inode_unhashed(inode)) {
466                 inode->i_private = upperinode;
467                 __insert_inode_hash(inode, (unsigned long) upperinode);
468         }
469 }
470
471 static void ovl_dir_version_inc(struct dentry *dentry, bool impurity)
472 {
473         struct inode *inode = d_inode(dentry);
474
475         WARN_ON(!inode_is_locked(inode));
476         WARN_ON(!d_is_dir(dentry));
477         /*
478          * Version is used by readdir code to keep cache consistent.
479          * For merge dirs (or dirs with origin) all changes need to be noted.
480          * For non-merge dirs, cache contains only impure entries (i.e. ones
481          * which have been copied up and have origins), so only need to note
482          * changes to impure entries.
483          */
484         if (!ovl_dir_is_real(dentry) || impurity)
485                 OVL_I(inode)->version++;
486 }
487
488 void ovl_dir_modified(struct dentry *dentry, bool impurity)
489 {
490         /* Copy mtime/ctime */
491         ovl_copyattr(d_inode(dentry));
492
493         ovl_dir_version_inc(dentry, impurity);
494 }
495
496 u64 ovl_dentry_version_get(struct dentry *dentry)
497 {
498         struct inode *inode = d_inode(dentry);
499
500         WARN_ON(!inode_is_locked(inode));
501         return OVL_I(inode)->version;
502 }
503
504 bool ovl_is_whiteout(struct dentry *dentry)
505 {
506         struct inode *inode = dentry->d_inode;
507
508         return inode && IS_WHITEOUT(inode);
509 }
510
511 struct file *ovl_path_open(const struct path *path, int flags)
512 {
513         struct inode *inode = d_inode(path->dentry);
514         struct user_namespace *real_mnt_userns = mnt_user_ns(path->mnt);
515         int err, acc_mode;
516
517         if (flags & ~(O_ACCMODE | O_LARGEFILE))
518                 BUG();
519
520         switch (flags & O_ACCMODE) {
521         case O_RDONLY:
522                 acc_mode = MAY_READ;
523                 break;
524         case O_WRONLY:
525                 acc_mode = MAY_WRITE;
526                 break;
527         default:
528                 BUG();
529         }
530
531         err = inode_permission(real_mnt_userns, inode, acc_mode | MAY_OPEN);
532         if (err)
533                 return ERR_PTR(err);
534
535         /* O_NOATIME is an optimization, don't fail if not permitted */
536         if (inode_owner_or_capable(real_mnt_userns, inode))
537                 flags |= O_NOATIME;
538
539         return dentry_open(path, flags, current_cred());
540 }
541
542 /* Caller should hold ovl_inode->lock */
543 static bool ovl_already_copied_up_locked(struct dentry *dentry, int flags)
544 {
545         bool disconnected = dentry->d_flags & DCACHE_DISCONNECTED;
546
547         if (ovl_dentry_upper(dentry) &&
548             (ovl_dentry_has_upper_alias(dentry) || disconnected) &&
549             !ovl_dentry_needs_data_copy_up_locked(dentry, flags))
550                 return true;
551
552         return false;
553 }
554
555 bool ovl_already_copied_up(struct dentry *dentry, int flags)
556 {
557         bool disconnected = dentry->d_flags & DCACHE_DISCONNECTED;
558
559         /*
560          * Check if copy-up has happened as well as for upper alias (in
561          * case of hard links) is there.
562          *
563          * Both checks are lockless:
564          *  - false negatives: will recheck under oi->lock
565          *  - false positives:
566          *    + ovl_dentry_upper() uses memory barriers to ensure the
567          *      upper dentry is up-to-date
568          *    + ovl_dentry_has_upper_alias() relies on locking of
569          *      upper parent i_rwsem to prevent reordering copy-up
570          *      with rename.
571          */
572         if (ovl_dentry_upper(dentry) &&
573             (ovl_dentry_has_upper_alias(dentry) || disconnected) &&
574             !ovl_dentry_needs_data_copy_up(dentry, flags))
575                 return true;
576
577         return false;
578 }
579
580 int ovl_copy_up_start(struct dentry *dentry, int flags)
581 {
582         struct inode *inode = d_inode(dentry);
583         int err;
584
585         err = ovl_inode_lock_interruptible(inode);
586         if (!err && ovl_already_copied_up_locked(dentry, flags)) {
587                 err = 1; /* Already copied up */
588                 ovl_inode_unlock(inode);
589         }
590
591         return err;
592 }
593
594 void ovl_copy_up_end(struct dentry *dentry)
595 {
596         ovl_inode_unlock(d_inode(dentry));
597 }
598
599 bool ovl_path_check_origin_xattr(struct ovl_fs *ofs, const struct path *path)
600 {
601         int res;
602
603         res = ovl_path_getxattr(ofs, path, OVL_XATTR_ORIGIN, NULL, 0);
604
605         /* Zero size value means "copied up but origin unknown" */
606         if (res >= 0)
607                 return true;
608
609         return false;
610 }
611
612 bool ovl_path_check_dir_xattr(struct ovl_fs *ofs, const struct path *path,
613                                enum ovl_xattr ox)
614 {
615         int res;
616         char val;
617
618         if (!d_is_dir(path->dentry))
619                 return false;
620
621         res = ovl_path_getxattr(ofs, path, ox, &val, 1);
622         if (res == 1 && val == 'y')
623                 return true;
624
625         return false;
626 }
627
628 #define OVL_XATTR_OPAQUE_POSTFIX        "opaque"
629 #define OVL_XATTR_REDIRECT_POSTFIX      "redirect"
630 #define OVL_XATTR_ORIGIN_POSTFIX        "origin"
631 #define OVL_XATTR_IMPURE_POSTFIX        "impure"
632 #define OVL_XATTR_NLINK_POSTFIX         "nlink"
633 #define OVL_XATTR_UPPER_POSTFIX         "upper"
634 #define OVL_XATTR_METACOPY_POSTFIX      "metacopy"
635 #define OVL_XATTR_PROTATTR_POSTFIX      "protattr"
636
637 #define OVL_XATTR_TAB_ENTRY(x) \
638         [x] = { [false] = OVL_XATTR_TRUSTED_PREFIX x ## _POSTFIX, \
639                 [true] = OVL_XATTR_USER_PREFIX x ## _POSTFIX }
640
641 const char *const ovl_xattr_table[][2] = {
642         OVL_XATTR_TAB_ENTRY(OVL_XATTR_OPAQUE),
643         OVL_XATTR_TAB_ENTRY(OVL_XATTR_REDIRECT),
644         OVL_XATTR_TAB_ENTRY(OVL_XATTR_ORIGIN),
645         OVL_XATTR_TAB_ENTRY(OVL_XATTR_IMPURE),
646         OVL_XATTR_TAB_ENTRY(OVL_XATTR_NLINK),
647         OVL_XATTR_TAB_ENTRY(OVL_XATTR_UPPER),
648         OVL_XATTR_TAB_ENTRY(OVL_XATTR_METACOPY),
649         OVL_XATTR_TAB_ENTRY(OVL_XATTR_PROTATTR),
650 };
651
652 int ovl_check_setxattr(struct ovl_fs *ofs, struct dentry *upperdentry,
653                        enum ovl_xattr ox, const void *value, size_t size,
654                        int xerr)
655 {
656         int err;
657
658         if (ofs->noxattr)
659                 return xerr;
660
661         err = ovl_setxattr(ofs, upperdentry, ox, value, size);
662
663         if (err == -EOPNOTSUPP) {
664                 pr_warn("cannot set %s xattr on upper\n", ovl_xattr(ofs, ox));
665                 ofs->noxattr = true;
666                 return xerr;
667         }
668
669         return err;
670 }
671
672 int ovl_set_impure(struct dentry *dentry, struct dentry *upperdentry)
673 {
674         struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
675         int err;
676
677         if (ovl_test_flag(OVL_IMPURE, d_inode(dentry)))
678                 return 0;
679
680         /*
681          * Do not fail when upper doesn't support xattrs.
682          * Upper inodes won't have origin nor redirect xattr anyway.
683          */
684         err = ovl_check_setxattr(ofs, upperdentry, OVL_XATTR_IMPURE, "y", 1, 0);
685         if (!err)
686                 ovl_set_flag(OVL_IMPURE, d_inode(dentry));
687
688         return err;
689 }
690
691
692 #define OVL_PROTATTR_MAX 32 /* Reserved for future flags */
693
694 void ovl_check_protattr(struct inode *inode, struct dentry *upper)
695 {
696         struct ovl_fs *ofs = OVL_FS(inode->i_sb);
697         u32 iflags = inode->i_flags & OVL_PROT_I_FLAGS_MASK;
698         char buf[OVL_PROTATTR_MAX+1];
699         int res, n;
700
701         res = ovl_getxattr_upper(ofs, upper, OVL_XATTR_PROTATTR, buf,
702                                  OVL_PROTATTR_MAX);
703         if (res < 0)
704                 return;
705
706         /*
707          * Initialize inode flags from overlay.protattr xattr and upper inode
708          * flags.  If upper inode has those fileattr flags set (i.e. from old
709          * kernel), we do not clear them on ovl_get_inode(), but we will clear
710          * them on next fileattr_set().
711          */
712         for (n = 0; n < res; n++) {
713                 if (buf[n] == 'a')
714                         iflags |= S_APPEND;
715                 else if (buf[n] == 'i')
716                         iflags |= S_IMMUTABLE;
717                 else
718                         break;
719         }
720
721         if (!res || n < res) {
722                 pr_warn_ratelimited("incompatible overlay.protattr format (%pd2, len=%d)\n",
723                                     upper, res);
724         } else {
725                 inode_set_flags(inode, iflags, OVL_PROT_I_FLAGS_MASK);
726         }
727 }
728
729 int ovl_set_protattr(struct inode *inode, struct dentry *upper,
730                       struct fileattr *fa)
731 {
732         struct ovl_fs *ofs = OVL_FS(inode->i_sb);
733         char buf[OVL_PROTATTR_MAX];
734         int len = 0, err = 0;
735         u32 iflags = 0;
736
737         BUILD_BUG_ON(HWEIGHT32(OVL_PROT_FS_FLAGS_MASK) > OVL_PROTATTR_MAX);
738
739         if (fa->flags & FS_APPEND_FL) {
740                 buf[len++] = 'a';
741                 iflags |= S_APPEND;
742         }
743         if (fa->flags & FS_IMMUTABLE_FL) {
744                 buf[len++] = 'i';
745                 iflags |= S_IMMUTABLE;
746         }
747
748         /*
749          * Do not allow to set protection flags when upper doesn't support
750          * xattrs, because we do not set those fileattr flags on upper inode.
751          * Remove xattr if it exist and all protection flags are cleared.
752          */
753         if (len) {
754                 err = ovl_check_setxattr(ofs, upper, OVL_XATTR_PROTATTR,
755                                          buf, len, -EPERM);
756         } else if (inode->i_flags & OVL_PROT_I_FLAGS_MASK) {
757                 err = ovl_removexattr(ofs, upper, OVL_XATTR_PROTATTR);
758                 if (err == -EOPNOTSUPP || err == -ENODATA)
759                         err = 0;
760         }
761         if (err)
762                 return err;
763
764         inode_set_flags(inode, iflags, OVL_PROT_I_FLAGS_MASK);
765
766         /* Mask out the fileattr flags that should not be set in upper inode */
767         fa->flags &= ~OVL_PROT_FS_FLAGS_MASK;
768         fa->fsx_xflags &= ~OVL_PROT_FSX_FLAGS_MASK;
769
770         return 0;
771 }
772
773 /**
774  * Caller must hold a reference to inode to prevent it from being freed while
775  * it is marked inuse.
776  */
777 bool ovl_inuse_trylock(struct dentry *dentry)
778 {
779         struct inode *inode = d_inode(dentry);
780         bool locked = false;
781
782         spin_lock(&inode->i_lock);
783         if (!(inode->i_state & I_OVL_INUSE)) {
784                 inode->i_state |= I_OVL_INUSE;
785                 locked = true;
786         }
787         spin_unlock(&inode->i_lock);
788
789         return locked;
790 }
791
792 void ovl_inuse_unlock(struct dentry *dentry)
793 {
794         if (dentry) {
795                 struct inode *inode = d_inode(dentry);
796
797                 spin_lock(&inode->i_lock);
798                 WARN_ON(!(inode->i_state & I_OVL_INUSE));
799                 inode->i_state &= ~I_OVL_INUSE;
800                 spin_unlock(&inode->i_lock);
801         }
802 }
803
804 bool ovl_is_inuse(struct dentry *dentry)
805 {
806         struct inode *inode = d_inode(dentry);
807         bool inuse;
808
809         spin_lock(&inode->i_lock);
810         inuse = (inode->i_state & I_OVL_INUSE);
811         spin_unlock(&inode->i_lock);
812
813         return inuse;
814 }
815
816 /*
817  * Does this overlay dentry need to be indexed on copy up?
818  */
819 bool ovl_need_index(struct dentry *dentry)
820 {
821         struct dentry *lower = ovl_dentry_lower(dentry);
822
823         if (!lower || !ovl_indexdir(dentry->d_sb))
824                 return false;
825
826         /* Index all files for NFS export and consistency verification */
827         if (ovl_index_all(dentry->d_sb))
828                 return true;
829
830         /* Index only lower hardlinks on copy up */
831         if (!d_is_dir(lower) && d_inode(lower)->i_nlink > 1)
832                 return true;
833
834         return false;
835 }
836
837 /* Caller must hold OVL_I(inode)->lock */
838 static void ovl_cleanup_index(struct dentry *dentry)
839 {
840         struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
841         struct dentry *indexdir = ovl_indexdir(dentry->d_sb);
842         struct inode *dir = indexdir->d_inode;
843         struct dentry *lowerdentry = ovl_dentry_lower(dentry);
844         struct dentry *upperdentry = ovl_dentry_upper(dentry);
845         struct dentry *index = NULL;
846         struct inode *inode;
847         struct qstr name = { };
848         int err;
849
850         err = ovl_get_index_name(ofs, lowerdentry, &name);
851         if (err)
852                 goto fail;
853
854         inode = d_inode(upperdentry);
855         if (!S_ISDIR(inode->i_mode) && inode->i_nlink != 1) {
856                 pr_warn_ratelimited("cleanup linked index (%pd2, ino=%lu, nlink=%u)\n",
857                                     upperdentry, inode->i_ino, inode->i_nlink);
858                 /*
859                  * We either have a bug with persistent union nlink or a lower
860                  * hardlink was added while overlay is mounted. Adding a lower
861                  * hardlink and then unlinking all overlay hardlinks would drop
862                  * overlay nlink to zero before all upper inodes are unlinked.
863                  * As a safety measure, when that situation is detected, set
864                  * the overlay nlink to the index inode nlink minus one for the
865                  * index entry itself.
866                  */
867                 set_nlink(d_inode(dentry), inode->i_nlink - 1);
868                 ovl_set_nlink_upper(dentry);
869                 goto out;
870         }
871
872         inode_lock_nested(dir, I_MUTEX_PARENT);
873         index = ovl_lookup_upper(ofs, name.name, indexdir, name.len);
874         err = PTR_ERR(index);
875         if (IS_ERR(index)) {
876                 index = NULL;
877         } else if (ovl_index_all(dentry->d_sb)) {
878                 /* Whiteout orphan index to block future open by handle */
879                 err = ovl_cleanup_and_whiteout(OVL_FS(dentry->d_sb),
880                                                dir, index);
881         } else {
882                 /* Cleanup orphan index entries */
883                 err = ovl_cleanup(ofs, dir, index);
884         }
885
886         inode_unlock(dir);
887         if (err)
888                 goto fail;
889
890 out:
891         kfree(name.name);
892         dput(index);
893         return;
894
895 fail:
896         pr_err("cleanup index of '%pd2' failed (%i)\n", dentry, err);
897         goto out;
898 }
899
900 /*
901  * Operations that change overlay inode and upper inode nlink need to be
902  * synchronized with copy up for persistent nlink accounting.
903  */
904 int ovl_nlink_start(struct dentry *dentry)
905 {
906         struct inode *inode = d_inode(dentry);
907         const struct cred *old_cred;
908         int err;
909
910         if (WARN_ON(!inode))
911                 return -ENOENT;
912
913         /*
914          * With inodes index is enabled, we store the union overlay nlink
915          * in an xattr on the index inode. When whiting out an indexed lower,
916          * we need to decrement the overlay persistent nlink, but before the
917          * first copy up, we have no upper index inode to store the xattr.
918          *
919          * As a workaround, before whiteout/rename over an indexed lower,
920          * copy up to create the upper index. Creating the upper index will
921          * initialize the overlay nlink, so it could be dropped if unlink
922          * or rename succeeds.
923          *
924          * TODO: implement metadata only index copy up when called with
925          *       ovl_copy_up_flags(dentry, O_PATH).
926          */
927         if (ovl_need_index(dentry) && !ovl_dentry_has_upper_alias(dentry)) {
928                 err = ovl_copy_up(dentry);
929                 if (err)
930                         return err;
931         }
932
933         err = ovl_inode_lock_interruptible(inode);
934         if (err)
935                 return err;
936
937         if (d_is_dir(dentry) || !ovl_test_flag(OVL_INDEX, inode))
938                 goto out;
939
940         old_cred = ovl_override_creds(dentry->d_sb);
941         /*
942          * The overlay inode nlink should be incremented/decremented IFF the
943          * upper operation succeeds, along with nlink change of upper inode.
944          * Therefore, before link/unlink/rename, we store the union nlink
945          * value relative to the upper inode nlink in an upper inode xattr.
946          */
947         err = ovl_set_nlink_upper(dentry);
948         revert_creds(old_cred);
949
950 out:
951         if (err)
952                 ovl_inode_unlock(inode);
953
954         return err;
955 }
956
957 void ovl_nlink_end(struct dentry *dentry)
958 {
959         struct inode *inode = d_inode(dentry);
960
961         if (ovl_test_flag(OVL_INDEX, inode) && inode->i_nlink == 0) {
962                 const struct cred *old_cred;
963
964                 old_cred = ovl_override_creds(dentry->d_sb);
965                 ovl_cleanup_index(dentry);
966                 revert_creds(old_cred);
967         }
968
969         ovl_inode_unlock(inode);
970 }
971
972 int ovl_lock_rename_workdir(struct dentry *workdir, struct dentry *upperdir)
973 {
974         /* Workdir should not be the same as upperdir */
975         if (workdir == upperdir)
976                 goto err;
977
978         /* Workdir should not be subdir of upperdir and vice versa */
979         if (lock_rename(workdir, upperdir) != NULL)
980                 goto err_unlock;
981
982         return 0;
983
984 err_unlock:
985         unlock_rename(workdir, upperdir);
986 err:
987         pr_err("failed to lock workdir+upperdir\n");
988         return -EIO;
989 }
990
991 /* err < 0, 0 if no metacopy xattr, 1 if metacopy xattr found */
992 int ovl_check_metacopy_xattr(struct ovl_fs *ofs, const struct path *path)
993 {
994         int res;
995
996         /* Only regular files can have metacopy xattr */
997         if (!S_ISREG(d_inode(path->dentry)->i_mode))
998                 return 0;
999
1000         res = ovl_path_getxattr(ofs, path, OVL_XATTR_METACOPY, NULL, 0);
1001         if (res < 0) {
1002                 if (res == -ENODATA || res == -EOPNOTSUPP)
1003                         return 0;
1004                 /*
1005                  * getxattr on user.* may fail with EACCES in case there's no
1006                  * read permission on the inode.  Not much we can do, other than
1007                  * tell the caller that this is not a metacopy inode.
1008                  */
1009                 if (ofs->config.userxattr && res == -EACCES)
1010                         return 0;
1011                 goto out;
1012         }
1013
1014         return 1;
1015 out:
1016         pr_warn_ratelimited("failed to get metacopy (%i)\n", res);
1017         return res;
1018 }
1019
1020 bool ovl_is_metacopy_dentry(struct dentry *dentry)
1021 {
1022         struct ovl_entry *oe = dentry->d_fsdata;
1023
1024         if (!d_is_reg(dentry))
1025                 return false;
1026
1027         if (ovl_dentry_upper(dentry)) {
1028                 if (!ovl_has_upperdata(d_inode(dentry)))
1029                         return true;
1030                 return false;
1031         }
1032
1033         return (oe->numlower > 1);
1034 }
1035
1036 char *ovl_get_redirect_xattr(struct ovl_fs *ofs, const struct path *path, int padding)
1037 {
1038         int res;
1039         char *s, *next, *buf = NULL;
1040
1041         res = ovl_path_getxattr(ofs, path, OVL_XATTR_REDIRECT, NULL, 0);
1042         if (res == -ENODATA || res == -EOPNOTSUPP)
1043                 return NULL;
1044         if (res < 0)
1045                 goto fail;
1046         if (res == 0)
1047                 goto invalid;
1048
1049         buf = kzalloc(res + padding + 1, GFP_KERNEL);
1050         if (!buf)
1051                 return ERR_PTR(-ENOMEM);
1052
1053         res = ovl_path_getxattr(ofs, path, OVL_XATTR_REDIRECT, buf, res);
1054         if (res < 0)
1055                 goto fail;
1056         if (res == 0)
1057                 goto invalid;
1058
1059         if (buf[0] == '/') {
1060                 for (s = buf; *s++ == '/'; s = next) {
1061                         next = strchrnul(s, '/');
1062                         if (s == next)
1063                                 goto invalid;
1064                 }
1065         } else {
1066                 if (strchr(buf, '/') != NULL)
1067                         goto invalid;
1068         }
1069
1070         return buf;
1071 invalid:
1072         pr_warn_ratelimited("invalid redirect (%s)\n", buf);
1073         res = -EINVAL;
1074         goto err_free;
1075 fail:
1076         pr_warn_ratelimited("failed to get redirect (%i)\n", res);
1077 err_free:
1078         kfree(buf);
1079         return ERR_PTR(res);
1080 }
1081
1082 /*
1083  * ovl_sync_status() - Check fs sync status for volatile mounts
1084  *
1085  * Returns 1 if this is not a volatile mount and a real sync is required.
1086  *
1087  * Returns 0 if syncing can be skipped because mount is volatile, and no errors
1088  * have occurred on the upperdir since the mount.
1089  *
1090  * Returns -errno if it is a volatile mount, and the error that occurred since
1091  * the last mount. If the error code changes, it'll return the latest error
1092  * code.
1093  */
1094
1095 int ovl_sync_status(struct ovl_fs *ofs)
1096 {
1097         struct vfsmount *mnt;
1098
1099         if (ovl_should_sync(ofs))
1100                 return 1;
1101
1102         mnt = ovl_upper_mnt(ofs);
1103         if (!mnt)
1104                 return 0;
1105
1106         return errseq_check(&mnt->mnt_sb->s_wb_err, ofs->errseq);
1107 }
1108
1109 /*
1110  * ovl_copyattr() - copy inode attributes from layer to ovl inode
1111  *
1112  * When overlay copies inode information from an upper or lower layer to the
1113  * relevant overlay inode it will apply the idmapping of the upper or lower
1114  * layer when doing so ensuring that the ovl inode ownership will correctly
1115  * reflect the ownership of the idmapped upper or lower layer. For example, an
1116  * idmapped upper or lower layer mapping id 1001 to id 1000 will take care to
1117  * map any lower or upper inode owned by id 1001 to id 1000. These mapping
1118  * helpers are nops when the relevant layer isn't idmapped.
1119  */
1120 void ovl_copyattr(struct inode *inode)
1121 {
1122         struct path realpath;
1123         struct inode *realinode;
1124         struct user_namespace *real_mnt_userns;
1125
1126         realinode = ovl_i_path_real(inode, &realpath);
1127         real_mnt_userns = mnt_user_ns(realpath.mnt);
1128
1129         inode->i_uid = i_uid_into_mnt(real_mnt_userns, realinode);
1130         inode->i_gid = i_gid_into_mnt(real_mnt_userns, realinode);
1131         inode->i_mode = realinode->i_mode;
1132         inode->i_atime = realinode->i_atime;
1133         inode->i_mtime = realinode->i_mtime;
1134         inode->i_ctime = realinode->i_ctime;
1135         i_size_write(inode, i_size_read(realinode));
1136 }