ovl: consistent behavior for immutable/append-only inodes
[linux-2.6-microblaze.git] / fs / overlayfs / inode.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *
4  * Copyright (C) 2011 Novell Inc.
5  */
6
7 #include <linux/fs.h>
8 #include <linux/slab.h>
9 #include <linux/cred.h>
10 #include <linux/xattr.h>
11 #include <linux/posix_acl.h>
12 #include <linux/ratelimit.h>
13 #include <linux/fiemap.h>
14 #include <linux/fileattr.h>
15 #include <linux/security.h>
16 #include "overlayfs.h"
17
18
19 int ovl_setattr(struct user_namespace *mnt_userns, struct dentry *dentry,
20                 struct iattr *attr)
21 {
22         int err;
23         bool full_copy_up = false;
24         struct dentry *upperdentry;
25         const struct cred *old_cred;
26
27         err = setattr_prepare(&init_user_ns, dentry, attr);
28         if (err)
29                 return err;
30
31         err = ovl_want_write(dentry);
32         if (err)
33                 goto out;
34
35         if (attr->ia_valid & ATTR_SIZE) {
36                 struct inode *realinode = d_inode(ovl_dentry_real(dentry));
37
38                 err = -ETXTBSY;
39                 if (atomic_read(&realinode->i_writecount) < 0)
40                         goto out_drop_write;
41
42                 /* Truncate should trigger data copy up as well */
43                 full_copy_up = true;
44         }
45
46         if (!full_copy_up)
47                 err = ovl_copy_up(dentry);
48         else
49                 err = ovl_copy_up_with_data(dentry);
50         if (!err) {
51                 struct inode *winode = NULL;
52
53                 upperdentry = ovl_dentry_upper(dentry);
54
55                 if (attr->ia_valid & ATTR_SIZE) {
56                         winode = d_inode(upperdentry);
57                         err = get_write_access(winode);
58                         if (err)
59                                 goto out_drop_write;
60                 }
61
62                 if (attr->ia_valid & (ATTR_KILL_SUID|ATTR_KILL_SGID))
63                         attr->ia_valid &= ~ATTR_MODE;
64
65                 /*
66                  * We might have to translate ovl file into real file object
67                  * once use cases emerge.  For now, simply don't let underlying
68                  * filesystem rely on attr->ia_file
69                  */
70                 attr->ia_valid &= ~ATTR_FILE;
71
72                 /*
73                  * If open(O_TRUNC) is done, VFS calls ->setattr with ATTR_OPEN
74                  * set.  Overlayfs does not pass O_TRUNC flag to underlying
75                  * filesystem during open -> do not pass ATTR_OPEN.  This
76                  * disables optimization in fuse which assumes open(O_TRUNC)
77                  * already set file size to 0.  But we never passed O_TRUNC to
78                  * fuse.  So by clearing ATTR_OPEN, fuse will be forced to send
79                  * setattr request to server.
80                  */
81                 attr->ia_valid &= ~ATTR_OPEN;
82
83                 inode_lock(upperdentry->d_inode);
84                 old_cred = ovl_override_creds(dentry->d_sb);
85                 err = notify_change(&init_user_ns, upperdentry, attr, NULL);
86                 revert_creds(old_cred);
87                 if (!err)
88                         ovl_copyattr(upperdentry->d_inode, dentry->d_inode);
89                 inode_unlock(upperdentry->d_inode);
90
91                 if (winode)
92                         put_write_access(winode);
93         }
94 out_drop_write:
95         ovl_drop_write(dentry);
96 out:
97         return err;
98 }
99
100 static void ovl_map_dev_ino(struct dentry *dentry, struct kstat *stat, int fsid)
101 {
102         bool samefs = ovl_same_fs(dentry->d_sb);
103         unsigned int xinobits = ovl_xino_bits(dentry->d_sb);
104         unsigned int xinoshift = 64 - xinobits;
105
106         if (samefs) {
107                 /*
108                  * When all layers are on the same fs, all real inode
109                  * number are unique, so we use the overlay st_dev,
110                  * which is friendly to du -x.
111                  */
112                 stat->dev = dentry->d_sb->s_dev;
113                 return;
114         } else if (xinobits) {
115                 /*
116                  * All inode numbers of underlying fs should not be using the
117                  * high xinobits, so we use high xinobits to partition the
118                  * overlay st_ino address space. The high bits holds the fsid
119                  * (upper fsid is 0). The lowest xinobit is reserved for mapping
120                  * the non-persistent inode numbers range in case of overflow.
121                  * This way all overlay inode numbers are unique and use the
122                  * overlay st_dev.
123                  */
124                 if (likely(!(stat->ino >> xinoshift))) {
125                         stat->ino |= ((u64)fsid) << (xinoshift + 1);
126                         stat->dev = dentry->d_sb->s_dev;
127                         return;
128                 } else if (ovl_xino_warn(dentry->d_sb)) {
129                         pr_warn_ratelimited("inode number too big (%pd2, ino=%llu, xinobits=%d)\n",
130                                             dentry, stat->ino, xinobits);
131                 }
132         }
133
134         /* The inode could not be mapped to a unified st_ino address space */
135         if (S_ISDIR(dentry->d_inode->i_mode)) {
136                 /*
137                  * Always use the overlay st_dev for directories, so 'find
138                  * -xdev' will scan the entire overlay mount and won't cross the
139                  * overlay mount boundaries.
140                  *
141                  * If not all layers are on the same fs the pair {real st_ino;
142                  * overlay st_dev} is not unique, so use the non persistent
143                  * overlay st_ino for directories.
144                  */
145                 stat->dev = dentry->d_sb->s_dev;
146                 stat->ino = dentry->d_inode->i_ino;
147         } else {
148                 /*
149                  * For non-samefs setup, if we cannot map all layers st_ino
150                  * to a unified address space, we need to make sure that st_dev
151                  * is unique per underlying fs, so we use the unique anonymous
152                  * bdev assigned to the underlying fs.
153                  */
154                 stat->dev = OVL_FS(dentry->d_sb)->fs[fsid].pseudo_dev;
155         }
156 }
157
158 int ovl_getattr(struct user_namespace *mnt_userns, const struct path *path,
159                 struct kstat *stat, u32 request_mask, unsigned int flags)
160 {
161         struct dentry *dentry = path->dentry;
162         enum ovl_path_type type;
163         struct path realpath;
164         const struct cred *old_cred;
165         struct inode *inode = d_inode(dentry);
166         bool is_dir = S_ISDIR(inode->i_mode);
167         int fsid = 0;
168         int err;
169         bool metacopy_blocks = false;
170
171         metacopy_blocks = ovl_is_metacopy_dentry(dentry);
172
173         type = ovl_path_real(dentry, &realpath);
174         old_cred = ovl_override_creds(dentry->d_sb);
175         err = vfs_getattr(&realpath, stat, request_mask, flags);
176         if (err)
177                 goto out;
178
179         /* Report the effective immutable/append-only STATX flags */
180         generic_fill_statx_attr(inode, stat);
181
182         /*
183          * For non-dir or same fs, we use st_ino of the copy up origin.
184          * This guaranties constant st_dev/st_ino across copy up.
185          * With xino feature and non-samefs, we use st_ino of the copy up
186          * origin masked with high bits that represent the layer id.
187          *
188          * If lower filesystem supports NFS file handles, this also guaranties
189          * persistent st_ino across mount cycle.
190          */
191         if (!is_dir || ovl_same_dev(dentry->d_sb)) {
192                 if (!OVL_TYPE_UPPER(type)) {
193                         fsid = ovl_layer_lower(dentry)->fsid;
194                 } else if (OVL_TYPE_ORIGIN(type)) {
195                         struct kstat lowerstat;
196                         u32 lowermask = STATX_INO | STATX_BLOCKS |
197                                         (!is_dir ? STATX_NLINK : 0);
198
199                         ovl_path_lower(dentry, &realpath);
200                         err = vfs_getattr(&realpath, &lowerstat,
201                                           lowermask, flags);
202                         if (err)
203                                 goto out;
204
205                         /*
206                          * Lower hardlinks may be broken on copy up to different
207                          * upper files, so we cannot use the lower origin st_ino
208                          * for those different files, even for the same fs case.
209                          *
210                          * Similarly, several redirected dirs can point to the
211                          * same dir on a lower layer. With the "verify_lower"
212                          * feature, we do not use the lower origin st_ino, if
213                          * we haven't verified that this redirect is unique.
214                          *
215                          * With inodes index enabled, it is safe to use st_ino
216                          * of an indexed origin. The index validates that the
217                          * upper hardlink is not broken and that a redirected
218                          * dir is the only redirect to that origin.
219                          */
220                         if (ovl_test_flag(OVL_INDEX, d_inode(dentry)) ||
221                             (!ovl_verify_lower(dentry->d_sb) &&
222                              (is_dir || lowerstat.nlink == 1))) {
223                                 fsid = ovl_layer_lower(dentry)->fsid;
224                                 stat->ino = lowerstat.ino;
225                         }
226
227                         /*
228                          * If we are querying a metacopy dentry and lower
229                          * dentry is data dentry, then use the blocks we
230                          * queried just now. We don't have to do additional
231                          * vfs_getattr(). If lower itself is metacopy, then
232                          * additional vfs_getattr() is unavoidable.
233                          */
234                         if (metacopy_blocks &&
235                             realpath.dentry == ovl_dentry_lowerdata(dentry)) {
236                                 stat->blocks = lowerstat.blocks;
237                                 metacopy_blocks = false;
238                         }
239                 }
240
241                 if (metacopy_blocks) {
242                         /*
243                          * If lower is not same as lowerdata or if there was
244                          * no origin on upper, we can end up here.
245                          */
246                         struct kstat lowerdatastat;
247                         u32 lowermask = STATX_BLOCKS;
248
249                         ovl_path_lowerdata(dentry, &realpath);
250                         err = vfs_getattr(&realpath, &lowerdatastat,
251                                           lowermask, flags);
252                         if (err)
253                                 goto out;
254                         stat->blocks = lowerdatastat.blocks;
255                 }
256         }
257
258         ovl_map_dev_ino(dentry, stat, fsid);
259
260         /*
261          * It's probably not worth it to count subdirs to get the
262          * correct link count.  nlink=1 seems to pacify 'find' and
263          * other utilities.
264          */
265         if (is_dir && OVL_TYPE_MERGE(type))
266                 stat->nlink = 1;
267
268         /*
269          * Return the overlay inode nlinks for indexed upper inodes.
270          * Overlay inode nlink counts the union of the upper hardlinks
271          * and non-covered lower hardlinks. It does not include the upper
272          * index hardlink.
273          */
274         if (!is_dir && ovl_test_flag(OVL_INDEX, d_inode(dentry)))
275                 stat->nlink = dentry->d_inode->i_nlink;
276
277 out:
278         revert_creds(old_cred);
279
280         return err;
281 }
282
283 int ovl_permission(struct user_namespace *mnt_userns,
284                    struct inode *inode, int mask)
285 {
286         struct inode *upperinode = ovl_inode_upper(inode);
287         struct inode *realinode = upperinode ?: ovl_inode_lower(inode);
288         const struct cred *old_cred;
289         int err;
290
291         /* Careful in RCU walk mode */
292         if (!realinode) {
293                 WARN_ON(!(mask & MAY_NOT_BLOCK));
294                 return -ECHILD;
295         }
296
297         /*
298          * Check overlay inode with the creds of task and underlying inode
299          * with creds of mounter
300          */
301         err = generic_permission(&init_user_ns, inode, mask);
302         if (err)
303                 return err;
304
305         old_cred = ovl_override_creds(inode->i_sb);
306         if (!upperinode &&
307             !special_file(realinode->i_mode) && mask & MAY_WRITE) {
308                 mask &= ~(MAY_WRITE | MAY_APPEND);
309                 /* Make sure mounter can read file for copy up later */
310                 mask |= MAY_READ;
311         }
312         err = inode_permission(&init_user_ns, realinode, mask);
313         revert_creds(old_cred);
314
315         return err;
316 }
317
318 static const char *ovl_get_link(struct dentry *dentry,
319                                 struct inode *inode,
320                                 struct delayed_call *done)
321 {
322         const struct cred *old_cred;
323         const char *p;
324
325         if (!dentry)
326                 return ERR_PTR(-ECHILD);
327
328         old_cred = ovl_override_creds(dentry->d_sb);
329         p = vfs_get_link(ovl_dentry_real(dentry), done);
330         revert_creds(old_cred);
331         return p;
332 }
333
334 bool ovl_is_private_xattr(struct super_block *sb, const char *name)
335 {
336         struct ovl_fs *ofs = sb->s_fs_info;
337
338         if (ofs->config.userxattr)
339                 return strncmp(name, OVL_XATTR_USER_PREFIX,
340                                sizeof(OVL_XATTR_USER_PREFIX) - 1) == 0;
341         else
342                 return strncmp(name, OVL_XATTR_TRUSTED_PREFIX,
343                                sizeof(OVL_XATTR_TRUSTED_PREFIX) - 1) == 0;
344 }
345
346 int ovl_xattr_set(struct dentry *dentry, struct inode *inode, const char *name,
347                   const void *value, size_t size, int flags)
348 {
349         int err;
350         struct dentry *upperdentry = ovl_i_dentry_upper(inode);
351         struct dentry *realdentry = upperdentry ?: ovl_dentry_lower(dentry);
352         const struct cred *old_cred;
353
354         err = ovl_want_write(dentry);
355         if (err)
356                 goto out;
357
358         if (!value && !upperdentry) {
359                 old_cred = ovl_override_creds(dentry->d_sb);
360                 err = vfs_getxattr(&init_user_ns, realdentry, name, NULL, 0);
361                 revert_creds(old_cred);
362                 if (err < 0)
363                         goto out_drop_write;
364         }
365
366         if (!upperdentry) {
367                 err = ovl_copy_up(dentry);
368                 if (err)
369                         goto out_drop_write;
370
371                 realdentry = ovl_dentry_upper(dentry);
372         }
373
374         old_cred = ovl_override_creds(dentry->d_sb);
375         if (value)
376                 err = vfs_setxattr(&init_user_ns, realdentry, name, value, size,
377                                    flags);
378         else {
379                 WARN_ON(flags != XATTR_REPLACE);
380                 err = vfs_removexattr(&init_user_ns, realdentry, name);
381         }
382         revert_creds(old_cred);
383
384         /* copy c/mtime */
385         ovl_copyattr(d_inode(realdentry), inode);
386
387 out_drop_write:
388         ovl_drop_write(dentry);
389 out:
390         return err;
391 }
392
393 int ovl_xattr_get(struct dentry *dentry, struct inode *inode, const char *name,
394                   void *value, size_t size)
395 {
396         ssize_t res;
397         const struct cred *old_cred;
398         struct dentry *realdentry =
399                 ovl_i_dentry_upper(inode) ?: ovl_dentry_lower(dentry);
400
401         old_cred = ovl_override_creds(dentry->d_sb);
402         res = vfs_getxattr(&init_user_ns, realdentry, name, value, size);
403         revert_creds(old_cred);
404         return res;
405 }
406
407 static bool ovl_can_list(struct super_block *sb, const char *s)
408 {
409         /* Never list private (.overlay) */
410         if (ovl_is_private_xattr(sb, s))
411                 return false;
412
413         /* List all non-trusted xattrs */
414         if (strncmp(s, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) != 0)
415                 return true;
416
417         /* list other trusted for superuser only */
418         return ns_capable_noaudit(&init_user_ns, CAP_SYS_ADMIN);
419 }
420
421 ssize_t ovl_listxattr(struct dentry *dentry, char *list, size_t size)
422 {
423         struct dentry *realdentry = ovl_dentry_real(dentry);
424         ssize_t res;
425         size_t len;
426         char *s;
427         const struct cred *old_cred;
428
429         old_cred = ovl_override_creds(dentry->d_sb);
430         res = vfs_listxattr(realdentry, list, size);
431         revert_creds(old_cred);
432         if (res <= 0 || size == 0)
433                 return res;
434
435         /* filter out private xattrs */
436         for (s = list, len = res; len;) {
437                 size_t slen = strnlen(s, len) + 1;
438
439                 /* underlying fs providing us with an broken xattr list? */
440                 if (WARN_ON(slen > len))
441                         return -EIO;
442
443                 len -= slen;
444                 if (!ovl_can_list(dentry->d_sb, s)) {
445                         res -= slen;
446                         memmove(s, s + slen, len);
447                 } else {
448                         s += slen;
449                 }
450         }
451
452         return res;
453 }
454
455 struct posix_acl *ovl_get_acl(struct inode *inode, int type)
456 {
457         struct inode *realinode = ovl_inode_real(inode);
458         const struct cred *old_cred;
459         struct posix_acl *acl;
460
461         if (!IS_ENABLED(CONFIG_FS_POSIX_ACL) || !IS_POSIXACL(realinode))
462                 return NULL;
463
464         old_cred = ovl_override_creds(inode->i_sb);
465         acl = get_acl(realinode, type);
466         revert_creds(old_cred);
467
468         return acl;
469 }
470
471 int ovl_update_time(struct inode *inode, struct timespec64 *ts, int flags)
472 {
473         if (flags & S_ATIME) {
474                 struct ovl_fs *ofs = inode->i_sb->s_fs_info;
475                 struct path upperpath = {
476                         .mnt = ovl_upper_mnt(ofs),
477                         .dentry = ovl_upperdentry_dereference(OVL_I(inode)),
478                 };
479
480                 if (upperpath.dentry) {
481                         touch_atime(&upperpath);
482                         inode->i_atime = d_inode(upperpath.dentry)->i_atime;
483                 }
484         }
485         return 0;
486 }
487
488 static int ovl_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
489                       u64 start, u64 len)
490 {
491         int err;
492         struct inode *realinode = ovl_inode_realdata(inode);
493         const struct cred *old_cred;
494
495         if (!realinode->i_op->fiemap)
496                 return -EOPNOTSUPP;
497
498         old_cred = ovl_override_creds(inode->i_sb);
499         err = realinode->i_op->fiemap(realinode, fieinfo, start, len);
500         revert_creds(old_cred);
501
502         return err;
503 }
504
505 /*
506  * Work around the fact that security_file_ioctl() takes a file argument.
507  * Introducing security_inode_fileattr_get/set() hooks would solve this issue
508  * properly.
509  */
510 static int ovl_security_fileattr(struct path *realpath, struct fileattr *fa,
511                                  bool set)
512 {
513         struct file *file;
514         unsigned int cmd;
515         int err;
516
517         file = dentry_open(realpath, O_RDONLY, current_cred());
518         if (IS_ERR(file))
519                 return PTR_ERR(file);
520
521         if (set)
522                 cmd = fa->fsx_valid ? FS_IOC_FSSETXATTR : FS_IOC_SETFLAGS;
523         else
524                 cmd = fa->fsx_valid ? FS_IOC_FSGETXATTR : FS_IOC_GETFLAGS;
525
526         err = security_file_ioctl(file, cmd, 0);
527         fput(file);
528
529         return err;
530 }
531
532 int ovl_real_fileattr_set(struct path *realpath, struct fileattr *fa)
533 {
534         int err;
535
536         err = ovl_security_fileattr(realpath, fa, true);
537         if (err)
538                 return err;
539
540         return vfs_fileattr_set(&init_user_ns, realpath->dentry, fa);
541 }
542
543 int ovl_fileattr_set(struct user_namespace *mnt_userns,
544                      struct dentry *dentry, struct fileattr *fa)
545 {
546         struct inode *inode = d_inode(dentry);
547         struct path upperpath;
548         const struct cred *old_cred;
549         unsigned int flags;
550         int err;
551
552         err = ovl_want_write(dentry);
553         if (err)
554                 goto out;
555
556         err = ovl_copy_up(dentry);
557         if (!err) {
558                 ovl_path_real(dentry, &upperpath);
559
560                 old_cred = ovl_override_creds(inode->i_sb);
561                 /*
562                  * Store immutable/append-only flags in xattr and clear them
563                  * in upper fileattr (in case they were set by older kernel)
564                  * so children of "ovl-immutable" directories lower aliases of
565                  * "ovl-immutable" hardlinks could be copied up.
566                  * Clear xattr when flags are cleared.
567                  */
568                 err = ovl_set_protattr(inode, upperpath.dentry, fa);
569                 if (!err)
570                         err = ovl_real_fileattr_set(&upperpath, fa);
571                 revert_creds(old_cred);
572
573                 /*
574                  * Merge real inode flags with inode flags read from
575                  * overlay.protattr xattr
576                  */
577                 flags = ovl_inode_real(inode)->i_flags & OVL_COPY_I_FLAGS_MASK;
578
579                 BUILD_BUG_ON(OVL_PROT_I_FLAGS_MASK & ~OVL_COPY_I_FLAGS_MASK);
580                 flags |= inode->i_flags & OVL_PROT_I_FLAGS_MASK;
581                 inode_set_flags(inode, flags, OVL_COPY_I_FLAGS_MASK);
582         }
583         ovl_drop_write(dentry);
584 out:
585         return err;
586 }
587
588 /* Convert inode protection flags to fileattr flags */
589 static void ovl_fileattr_prot_flags(struct inode *inode, struct fileattr *fa)
590 {
591         BUILD_BUG_ON(OVL_PROT_FS_FLAGS_MASK & ~FS_COMMON_FL);
592         BUILD_BUG_ON(OVL_PROT_FSX_FLAGS_MASK & ~FS_XFLAG_COMMON);
593
594         if (inode->i_flags & S_APPEND) {
595                 fa->flags |= FS_APPEND_FL;
596                 fa->fsx_xflags |= FS_XFLAG_APPEND;
597         }
598         if (inode->i_flags & S_IMMUTABLE) {
599                 fa->flags |= FS_IMMUTABLE_FL;
600                 fa->fsx_xflags |= FS_XFLAG_IMMUTABLE;
601         }
602 }
603
604 int ovl_real_fileattr_get(struct path *realpath, struct fileattr *fa)
605 {
606         int err;
607
608         err = ovl_security_fileattr(realpath, fa, false);
609         if (err)
610                 return err;
611
612         return vfs_fileattr_get(realpath->dentry, fa);
613 }
614
615 int ovl_fileattr_get(struct dentry *dentry, struct fileattr *fa)
616 {
617         struct inode *inode = d_inode(dentry);
618         struct path realpath;
619         const struct cred *old_cred;
620         int err;
621
622         ovl_path_real(dentry, &realpath);
623
624         old_cred = ovl_override_creds(inode->i_sb);
625         err = ovl_real_fileattr_get(&realpath, fa);
626         ovl_fileattr_prot_flags(inode, fa);
627         revert_creds(old_cred);
628
629         return err;
630 }
631
632 static const struct inode_operations ovl_file_inode_operations = {
633         .setattr        = ovl_setattr,
634         .permission     = ovl_permission,
635         .getattr        = ovl_getattr,
636         .listxattr      = ovl_listxattr,
637         .get_acl        = ovl_get_acl,
638         .update_time    = ovl_update_time,
639         .fiemap         = ovl_fiemap,
640         .fileattr_get   = ovl_fileattr_get,
641         .fileattr_set   = ovl_fileattr_set,
642 };
643
644 static const struct inode_operations ovl_symlink_inode_operations = {
645         .setattr        = ovl_setattr,
646         .get_link       = ovl_get_link,
647         .getattr        = ovl_getattr,
648         .listxattr      = ovl_listxattr,
649         .update_time    = ovl_update_time,
650 };
651
652 static const struct inode_operations ovl_special_inode_operations = {
653         .setattr        = ovl_setattr,
654         .permission     = ovl_permission,
655         .getattr        = ovl_getattr,
656         .listxattr      = ovl_listxattr,
657         .get_acl        = ovl_get_acl,
658         .update_time    = ovl_update_time,
659 };
660
661 static const struct address_space_operations ovl_aops = {
662         /* For O_DIRECT dentry_open() checks f_mapping->a_ops->direct_IO */
663         .direct_IO              = noop_direct_IO,
664 };
665
666 /*
667  * It is possible to stack overlayfs instance on top of another
668  * overlayfs instance as lower layer. We need to annotate the
669  * stackable i_mutex locks according to stack level of the super
670  * block instance. An overlayfs instance can never be in stack
671  * depth 0 (there is always a real fs below it).  An overlayfs
672  * inode lock will use the lockdep annotation ovl_i_mutex_key[depth].
673  *
674  * For example, here is a snip from /proc/lockdep_chains after
675  * dir_iterate of nested overlayfs:
676  *
677  * [...] &ovl_i_mutex_dir_key[depth]   (stack_depth=2)
678  * [...] &ovl_i_mutex_dir_key[depth]#2 (stack_depth=1)
679  * [...] &type->i_mutex_dir_key        (stack_depth=0)
680  *
681  * Locking order w.r.t ovl_want_write() is important for nested overlayfs.
682  *
683  * This chain is valid:
684  * - inode->i_rwsem                     (inode_lock[2])
685  * - upper_mnt->mnt_sb->s_writers       (ovl_want_write[0])
686  * - OVL_I(inode)->lock                 (ovl_inode_lock[2])
687  * - OVL_I(lowerinode)->lock            (ovl_inode_lock[1])
688  *
689  * And this chain is valid:
690  * - inode->i_rwsem                     (inode_lock[2])
691  * - OVL_I(inode)->lock                 (ovl_inode_lock[2])
692  * - lowerinode->i_rwsem                (inode_lock[1])
693  * - OVL_I(lowerinode)->lock            (ovl_inode_lock[1])
694  *
695  * But lowerinode->i_rwsem SHOULD NOT be acquired while ovl_want_write() is
696  * held, because it is in reverse order of the non-nested case using the same
697  * upper fs:
698  * - inode->i_rwsem                     (inode_lock[1])
699  * - upper_mnt->mnt_sb->s_writers       (ovl_want_write[0])
700  * - OVL_I(inode)->lock                 (ovl_inode_lock[1])
701  */
702 #define OVL_MAX_NESTING FILESYSTEM_MAX_STACK_DEPTH
703
704 static inline void ovl_lockdep_annotate_inode_mutex_key(struct inode *inode)
705 {
706 #ifdef CONFIG_LOCKDEP
707         static struct lock_class_key ovl_i_mutex_key[OVL_MAX_NESTING];
708         static struct lock_class_key ovl_i_mutex_dir_key[OVL_MAX_NESTING];
709         static struct lock_class_key ovl_i_lock_key[OVL_MAX_NESTING];
710
711         int depth = inode->i_sb->s_stack_depth - 1;
712
713         if (WARN_ON_ONCE(depth < 0 || depth >= OVL_MAX_NESTING))
714                 depth = 0;
715
716         if (S_ISDIR(inode->i_mode))
717                 lockdep_set_class(&inode->i_rwsem, &ovl_i_mutex_dir_key[depth]);
718         else
719                 lockdep_set_class(&inode->i_rwsem, &ovl_i_mutex_key[depth]);
720
721         lockdep_set_class(&OVL_I(inode)->lock, &ovl_i_lock_key[depth]);
722 #endif
723 }
724
725 static void ovl_next_ino(struct inode *inode)
726 {
727         struct ovl_fs *ofs = inode->i_sb->s_fs_info;
728
729         inode->i_ino = atomic_long_inc_return(&ofs->last_ino);
730         if (unlikely(!inode->i_ino))
731                 inode->i_ino = atomic_long_inc_return(&ofs->last_ino);
732 }
733
734 static void ovl_map_ino(struct inode *inode, unsigned long ino, int fsid)
735 {
736         int xinobits = ovl_xino_bits(inode->i_sb);
737         unsigned int xinoshift = 64 - xinobits;
738
739         /*
740          * When d_ino is consistent with st_ino (samefs or i_ino has enough
741          * bits to encode layer), set the same value used for st_ino to i_ino,
742          * so inode number exposed via /proc/locks and a like will be
743          * consistent with d_ino and st_ino values. An i_ino value inconsistent
744          * with d_ino also causes nfsd readdirplus to fail.
745          */
746         inode->i_ino = ino;
747         if (ovl_same_fs(inode->i_sb)) {
748                 return;
749         } else if (xinobits && likely(!(ino >> xinoshift))) {
750                 inode->i_ino |= (unsigned long)fsid << (xinoshift + 1);
751                 return;
752         }
753
754         /*
755          * For directory inodes on non-samefs with xino disabled or xino
756          * overflow, we allocate a non-persistent inode number, to be used for
757          * resolving st_ino collisions in ovl_map_dev_ino().
758          *
759          * To avoid ino collision with legitimate xino values from upper
760          * layer (fsid 0), use the lowest xinobit to map the non
761          * persistent inode numbers to the unified st_ino address space.
762          */
763         if (S_ISDIR(inode->i_mode)) {
764                 ovl_next_ino(inode);
765                 if (xinobits) {
766                         inode->i_ino &= ~0UL >> xinobits;
767                         inode->i_ino |= 1UL << xinoshift;
768                 }
769         }
770 }
771
772 void ovl_inode_init(struct inode *inode, struct ovl_inode_params *oip,
773                     unsigned long ino, int fsid)
774 {
775         struct inode *realinode;
776
777         if (oip->upperdentry)
778                 OVL_I(inode)->__upperdentry = oip->upperdentry;
779         if (oip->lowerpath && oip->lowerpath->dentry)
780                 OVL_I(inode)->lower = igrab(d_inode(oip->lowerpath->dentry));
781         if (oip->lowerdata)
782                 OVL_I(inode)->lowerdata = igrab(d_inode(oip->lowerdata));
783
784         realinode = ovl_inode_real(inode);
785         ovl_copyattr(realinode, inode);
786         ovl_copyflags(realinode, inode);
787         ovl_map_ino(inode, ino, fsid);
788 }
789
790 static void ovl_fill_inode(struct inode *inode, umode_t mode, dev_t rdev)
791 {
792         inode->i_mode = mode;
793         inode->i_flags |= S_NOCMTIME;
794 #ifdef CONFIG_FS_POSIX_ACL
795         inode->i_acl = inode->i_default_acl = ACL_DONT_CACHE;
796 #endif
797
798         ovl_lockdep_annotate_inode_mutex_key(inode);
799
800         switch (mode & S_IFMT) {
801         case S_IFREG:
802                 inode->i_op = &ovl_file_inode_operations;
803                 inode->i_fop = &ovl_file_operations;
804                 inode->i_mapping->a_ops = &ovl_aops;
805                 break;
806
807         case S_IFDIR:
808                 inode->i_op = &ovl_dir_inode_operations;
809                 inode->i_fop = &ovl_dir_operations;
810                 break;
811
812         case S_IFLNK:
813                 inode->i_op = &ovl_symlink_inode_operations;
814                 break;
815
816         default:
817                 inode->i_op = &ovl_special_inode_operations;
818                 init_special_inode(inode, mode, rdev);
819                 break;
820         }
821 }
822
823 /*
824  * With inodes index enabled, an overlay inode nlink counts the union of upper
825  * hardlinks and non-covered lower hardlinks. During the lifetime of a non-pure
826  * upper inode, the following nlink modifying operations can happen:
827  *
828  * 1. Lower hardlink copy up
829  * 2. Upper hardlink created, unlinked or renamed over
830  * 3. Lower hardlink whiteout or renamed over
831  *
832  * For the first, copy up case, the union nlink does not change, whether the
833  * operation succeeds or fails, but the upper inode nlink may change.
834  * Therefore, before copy up, we store the union nlink value relative to the
835  * lower inode nlink in the index inode xattr .overlay.nlink.
836  *
837  * For the second, upper hardlink case, the union nlink should be incremented
838  * or decremented IFF the operation succeeds, aligned with nlink change of the
839  * upper inode. Therefore, before link/unlink/rename, we store the union nlink
840  * value relative to the upper inode nlink in the index inode.
841  *
842  * For the last, lower cover up case, we simplify things by preceding the
843  * whiteout or cover up with copy up. This makes sure that there is an index
844  * upper inode where the nlink xattr can be stored before the copied up upper
845  * entry is unlink.
846  */
847 #define OVL_NLINK_ADD_UPPER     (1 << 0)
848
849 /*
850  * On-disk format for indexed nlink:
851  *
852  * nlink relative to the upper inode - "U[+-]NUM"
853  * nlink relative to the lower inode - "L[+-]NUM"
854  */
855
856 static int ovl_set_nlink_common(struct dentry *dentry,
857                                 struct dentry *realdentry, const char *format)
858 {
859         struct inode *inode = d_inode(dentry);
860         struct inode *realinode = d_inode(realdentry);
861         char buf[13];
862         int len;
863
864         len = snprintf(buf, sizeof(buf), format,
865                        (int) (inode->i_nlink - realinode->i_nlink));
866
867         if (WARN_ON(len >= sizeof(buf)))
868                 return -EIO;
869
870         return ovl_do_setxattr(OVL_FS(inode->i_sb), ovl_dentry_upper(dentry),
871                                OVL_XATTR_NLINK, buf, len);
872 }
873
874 int ovl_set_nlink_upper(struct dentry *dentry)
875 {
876         return ovl_set_nlink_common(dentry, ovl_dentry_upper(dentry), "U%+i");
877 }
878
879 int ovl_set_nlink_lower(struct dentry *dentry)
880 {
881         return ovl_set_nlink_common(dentry, ovl_dentry_lower(dentry), "L%+i");
882 }
883
884 unsigned int ovl_get_nlink(struct ovl_fs *ofs, struct dentry *lowerdentry,
885                            struct dentry *upperdentry,
886                            unsigned int fallback)
887 {
888         int nlink_diff;
889         int nlink;
890         char buf[13];
891         int err;
892
893         if (!lowerdentry || !upperdentry || d_inode(lowerdentry)->i_nlink == 1)
894                 return fallback;
895
896         err = ovl_do_getxattr(ofs, upperdentry, OVL_XATTR_NLINK,
897                               &buf, sizeof(buf) - 1);
898         if (err < 0)
899                 goto fail;
900
901         buf[err] = '\0';
902         if ((buf[0] != 'L' && buf[0] != 'U') ||
903             (buf[1] != '+' && buf[1] != '-'))
904                 goto fail;
905
906         err = kstrtoint(buf + 1, 10, &nlink_diff);
907         if (err < 0)
908                 goto fail;
909
910         nlink = d_inode(buf[0] == 'L' ? lowerdentry : upperdentry)->i_nlink;
911         nlink += nlink_diff;
912
913         if (nlink <= 0)
914                 goto fail;
915
916         return nlink;
917
918 fail:
919         pr_warn_ratelimited("failed to get index nlink (%pd2, err=%i)\n",
920                             upperdentry, err);
921         return fallback;
922 }
923
924 struct inode *ovl_new_inode(struct super_block *sb, umode_t mode, dev_t rdev)
925 {
926         struct inode *inode;
927
928         inode = new_inode(sb);
929         if (inode)
930                 ovl_fill_inode(inode, mode, rdev);
931
932         return inode;
933 }
934
935 static int ovl_inode_test(struct inode *inode, void *data)
936 {
937         return inode->i_private == data;
938 }
939
940 static int ovl_inode_set(struct inode *inode, void *data)
941 {
942         inode->i_private = data;
943         return 0;
944 }
945
946 static bool ovl_verify_inode(struct inode *inode, struct dentry *lowerdentry,
947                              struct dentry *upperdentry, bool strict)
948 {
949         /*
950          * For directories, @strict verify from lookup path performs consistency
951          * checks, so NULL lower/upper in dentry must match NULL lower/upper in
952          * inode. Non @strict verify from NFS handle decode path passes NULL for
953          * 'unknown' lower/upper.
954          */
955         if (S_ISDIR(inode->i_mode) && strict) {
956                 /* Real lower dir moved to upper layer under us? */
957                 if (!lowerdentry && ovl_inode_lower(inode))
958                         return false;
959
960                 /* Lookup of an uncovered redirect origin? */
961                 if (!upperdentry && ovl_inode_upper(inode))
962                         return false;
963         }
964
965         /*
966          * Allow non-NULL lower inode in ovl_inode even if lowerdentry is NULL.
967          * This happens when finding a copied up overlay inode for a renamed
968          * or hardlinked overlay dentry and lower dentry cannot be followed
969          * by origin because lower fs does not support file handles.
970          */
971         if (lowerdentry && ovl_inode_lower(inode) != d_inode(lowerdentry))
972                 return false;
973
974         /*
975          * Allow non-NULL __upperdentry in inode even if upperdentry is NULL.
976          * This happens when finding a lower alias for a copied up hard link.
977          */
978         if (upperdentry && ovl_inode_upper(inode) != d_inode(upperdentry))
979                 return false;
980
981         return true;
982 }
983
984 struct inode *ovl_lookup_inode(struct super_block *sb, struct dentry *real,
985                                bool is_upper)
986 {
987         struct inode *inode, *key = d_inode(real);
988
989         inode = ilookup5(sb, (unsigned long) key, ovl_inode_test, key);
990         if (!inode)
991                 return NULL;
992
993         if (!ovl_verify_inode(inode, is_upper ? NULL : real,
994                               is_upper ? real : NULL, false)) {
995                 iput(inode);
996                 return ERR_PTR(-ESTALE);
997         }
998
999         return inode;
1000 }
1001
1002 bool ovl_lookup_trap_inode(struct super_block *sb, struct dentry *dir)
1003 {
1004         struct inode *key = d_inode(dir);
1005         struct inode *trap;
1006         bool res;
1007
1008         trap = ilookup5(sb, (unsigned long) key, ovl_inode_test, key);
1009         if (!trap)
1010                 return false;
1011
1012         res = IS_DEADDIR(trap) && !ovl_inode_upper(trap) &&
1013                                   !ovl_inode_lower(trap);
1014
1015         iput(trap);
1016         return res;
1017 }
1018
1019 /*
1020  * Create an inode cache entry for layer root dir, that will intentionally
1021  * fail ovl_verify_inode(), so any lookup that will find some layer root
1022  * will fail.
1023  */
1024 struct inode *ovl_get_trap_inode(struct super_block *sb, struct dentry *dir)
1025 {
1026         struct inode *key = d_inode(dir);
1027         struct inode *trap;
1028
1029         if (!d_is_dir(dir))
1030                 return ERR_PTR(-ENOTDIR);
1031
1032         trap = iget5_locked(sb, (unsigned long) key, ovl_inode_test,
1033                             ovl_inode_set, key);
1034         if (!trap)
1035                 return ERR_PTR(-ENOMEM);
1036
1037         if (!(trap->i_state & I_NEW)) {
1038                 /* Conflicting layer roots? */
1039                 iput(trap);
1040                 return ERR_PTR(-ELOOP);
1041         }
1042
1043         trap->i_mode = S_IFDIR;
1044         trap->i_flags = S_DEAD;
1045         unlock_new_inode(trap);
1046
1047         return trap;
1048 }
1049
1050 /*
1051  * Does overlay inode need to be hashed by lower inode?
1052  */
1053 static bool ovl_hash_bylower(struct super_block *sb, struct dentry *upper,
1054                              struct dentry *lower, bool index)
1055 {
1056         struct ovl_fs *ofs = sb->s_fs_info;
1057
1058         /* No, if pure upper */
1059         if (!lower)
1060                 return false;
1061
1062         /* Yes, if already indexed */
1063         if (index)
1064                 return true;
1065
1066         /* Yes, if won't be copied up */
1067         if (!ovl_upper_mnt(ofs))
1068                 return true;
1069
1070         /* No, if lower hardlink is or will be broken on copy up */
1071         if ((upper || !ovl_indexdir(sb)) &&
1072             !d_is_dir(lower) && d_inode(lower)->i_nlink > 1)
1073                 return false;
1074
1075         /* No, if non-indexed upper with NFS export */
1076         if (sb->s_export_op && upper)
1077                 return false;
1078
1079         /* Otherwise, hash by lower inode for fsnotify */
1080         return true;
1081 }
1082
1083 static struct inode *ovl_iget5(struct super_block *sb, struct inode *newinode,
1084                                struct inode *key)
1085 {
1086         return newinode ? inode_insert5(newinode, (unsigned long) key,
1087                                          ovl_inode_test, ovl_inode_set, key) :
1088                           iget5_locked(sb, (unsigned long) key,
1089                                        ovl_inode_test, ovl_inode_set, key);
1090 }
1091
1092 struct inode *ovl_get_inode(struct super_block *sb,
1093                             struct ovl_inode_params *oip)
1094 {
1095         struct ovl_fs *ofs = OVL_FS(sb);
1096         struct dentry *upperdentry = oip->upperdentry;
1097         struct ovl_path *lowerpath = oip->lowerpath;
1098         struct inode *realinode = upperdentry ? d_inode(upperdentry) : NULL;
1099         struct inode *inode;
1100         struct dentry *lowerdentry = lowerpath ? lowerpath->dentry : NULL;
1101         bool bylower = ovl_hash_bylower(sb, upperdentry, lowerdentry,
1102                                         oip->index);
1103         int fsid = bylower ? lowerpath->layer->fsid : 0;
1104         bool is_dir;
1105         unsigned long ino = 0;
1106         int err = oip->newinode ? -EEXIST : -ENOMEM;
1107
1108         if (!realinode)
1109                 realinode = d_inode(lowerdentry);
1110
1111         /*
1112          * Copy up origin (lower) may exist for non-indexed upper, but we must
1113          * not use lower as hash key if this is a broken hardlink.
1114          */
1115         is_dir = S_ISDIR(realinode->i_mode);
1116         if (upperdentry || bylower) {
1117                 struct inode *key = d_inode(bylower ? lowerdentry :
1118                                                       upperdentry);
1119                 unsigned int nlink = is_dir ? 1 : realinode->i_nlink;
1120
1121                 inode = ovl_iget5(sb, oip->newinode, key);
1122                 if (!inode)
1123                         goto out_err;
1124                 if (!(inode->i_state & I_NEW)) {
1125                         /*
1126                          * Verify that the underlying files stored in the inode
1127                          * match those in the dentry.
1128                          */
1129                         if (!ovl_verify_inode(inode, lowerdentry, upperdentry,
1130                                               true)) {
1131                                 iput(inode);
1132                                 err = -ESTALE;
1133                                 goto out_err;
1134                         }
1135
1136                         dput(upperdentry);
1137                         kfree(oip->redirect);
1138                         goto out;
1139                 }
1140
1141                 /* Recalculate nlink for non-dir due to indexing */
1142                 if (!is_dir)
1143                         nlink = ovl_get_nlink(ofs, lowerdentry, upperdentry,
1144                                               nlink);
1145                 set_nlink(inode, nlink);
1146                 ino = key->i_ino;
1147         } else {
1148                 /* Lower hardlink that will be broken on copy up */
1149                 inode = new_inode(sb);
1150                 if (!inode) {
1151                         err = -ENOMEM;
1152                         goto out_err;
1153                 }
1154                 ino = realinode->i_ino;
1155                 fsid = lowerpath->layer->fsid;
1156         }
1157         ovl_fill_inode(inode, realinode->i_mode, realinode->i_rdev);
1158         ovl_inode_init(inode, oip, ino, fsid);
1159
1160         if (upperdentry && ovl_is_impuredir(sb, upperdentry))
1161                 ovl_set_flag(OVL_IMPURE, inode);
1162
1163         if (oip->index)
1164                 ovl_set_flag(OVL_INDEX, inode);
1165
1166         OVL_I(inode)->redirect = oip->redirect;
1167
1168         if (bylower)
1169                 ovl_set_flag(OVL_CONST_INO, inode);
1170
1171         /* Check for non-merge dir that may have whiteouts */
1172         if (is_dir) {
1173                 if (((upperdentry && lowerdentry) || oip->numlower > 1) ||
1174                     ovl_check_origin_xattr(ofs, upperdentry ?: lowerdentry)) {
1175                         ovl_set_flag(OVL_WHITEOUTS, inode);
1176                 }
1177         }
1178
1179         /* Check for immutable/append-only inode flags in xattr */
1180         if (upperdentry)
1181                 ovl_check_protattr(inode, upperdentry);
1182
1183         if (inode->i_state & I_NEW)
1184                 unlock_new_inode(inode);
1185 out:
1186         return inode;
1187
1188 out_err:
1189         pr_warn_ratelimited("failed to get inode (%i)\n", err);
1190         inode = ERR_PTR(err);
1191         goto out;
1192 }