ovl: Fix ovl_getattr() to get number of blocks from lower
[linux-2.6-microblaze.git] / fs / overlayfs / inode.c
1 /*
2  *
3  * Copyright (C) 2011 Novell Inc.
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 as published by
7  * the Free Software Foundation.
8  */
9
10 #include <linux/fs.h>
11 #include <linux/slab.h>
12 #include <linux/cred.h>
13 #include <linux/xattr.h>
14 #include <linux/posix_acl.h>
15 #include <linux/ratelimit.h>
16 #include "overlayfs.h"
17
18
19 int ovl_setattr(struct dentry *dentry, struct iattr *attr)
20 {
21         int err;
22         struct dentry *upperdentry;
23         const struct cred *old_cred;
24
25         err = setattr_prepare(dentry, attr);
26         if (err)
27                 return err;
28
29         err = ovl_want_write(dentry);
30         if (err)
31                 goto out;
32
33         if (attr->ia_valid & ATTR_SIZE) {
34                 struct inode *realinode = d_inode(ovl_dentry_real(dentry));
35
36                 err = -ETXTBSY;
37                 if (atomic_read(&realinode->i_writecount) < 0)
38                         goto out_drop_write;
39         }
40
41         err = ovl_copy_up(dentry);
42         if (!err) {
43                 struct inode *winode = NULL;
44
45                 upperdentry = ovl_dentry_upper(dentry);
46
47                 if (attr->ia_valid & ATTR_SIZE) {
48                         winode = d_inode(upperdentry);
49                         err = get_write_access(winode);
50                         if (err)
51                                 goto out_drop_write;
52                 }
53
54                 if (attr->ia_valid & (ATTR_KILL_SUID|ATTR_KILL_SGID))
55                         attr->ia_valid &= ~ATTR_MODE;
56
57                 inode_lock(upperdentry->d_inode);
58                 old_cred = ovl_override_creds(dentry->d_sb);
59                 err = notify_change(upperdentry, attr, NULL);
60                 revert_creds(old_cred);
61                 if (!err)
62                         ovl_copyattr(upperdentry->d_inode, dentry->d_inode);
63                 inode_unlock(upperdentry->d_inode);
64
65                 if (winode)
66                         put_write_access(winode);
67         }
68 out_drop_write:
69         ovl_drop_write(dentry);
70 out:
71         return err;
72 }
73
74 static int ovl_map_dev_ino(struct dentry *dentry, struct kstat *stat,
75                            struct ovl_layer *lower_layer)
76 {
77         bool samefs = ovl_same_sb(dentry->d_sb);
78         unsigned int xinobits = ovl_xino_bits(dentry->d_sb);
79
80         if (samefs) {
81                 /*
82                  * When all layers are on the same fs, all real inode
83                  * number are unique, so we use the overlay st_dev,
84                  * which is friendly to du -x.
85                  */
86                 stat->dev = dentry->d_sb->s_dev;
87                 return 0;
88         } else if (xinobits) {
89                 unsigned int shift = 64 - xinobits;
90                 /*
91                  * All inode numbers of underlying fs should not be using the
92                  * high xinobits, so we use high xinobits to partition the
93                  * overlay st_ino address space. The high bits holds the fsid
94                  * (upper fsid is 0). This way overlay inode numbers are unique
95                  * and all inodes use overlay st_dev. Inode numbers are also
96                  * persistent for a given layer configuration.
97                  */
98                 if (stat->ino >> shift) {
99                         pr_warn_ratelimited("overlayfs: inode number too big (%pd2, ino=%llu, xinobits=%d)\n",
100                                             dentry, stat->ino, xinobits);
101                 } else {
102                         if (lower_layer)
103                                 stat->ino |= ((u64)lower_layer->fsid) << shift;
104
105                         stat->dev = dentry->d_sb->s_dev;
106                         return 0;
107                 }
108         }
109
110         /* The inode could not be mapped to a unified st_ino address space */
111         if (S_ISDIR(dentry->d_inode->i_mode)) {
112                 /*
113                  * Always use the overlay st_dev for directories, so 'find
114                  * -xdev' will scan the entire overlay mount and won't cross the
115                  * overlay mount boundaries.
116                  *
117                  * If not all layers are on the same fs the pair {real st_ino;
118                  * overlay st_dev} is not unique, so use the non persistent
119                  * overlay st_ino for directories.
120                  */
121                 stat->dev = dentry->d_sb->s_dev;
122                 stat->ino = dentry->d_inode->i_ino;
123         } else if (lower_layer && lower_layer->fsid) {
124                 /*
125                  * For non-samefs setup, if we cannot map all layers st_ino
126                  * to a unified address space, we need to make sure that st_dev
127                  * is unique per lower fs. Upper layer uses real st_dev and
128                  * lower layers use the unique anonymous bdev assigned to the
129                  * lower fs.
130                  */
131                 stat->dev = lower_layer->fs->pseudo_dev;
132         }
133
134         return 0;
135 }
136
137 int ovl_getattr(const struct path *path, struct kstat *stat,
138                 u32 request_mask, unsigned int flags)
139 {
140         struct dentry *dentry = path->dentry;
141         enum ovl_path_type type;
142         struct path realpath;
143         const struct cred *old_cred;
144         bool is_dir = S_ISDIR(dentry->d_inode->i_mode);
145         bool samefs = ovl_same_sb(dentry->d_sb);
146         struct ovl_layer *lower_layer = NULL;
147         int err;
148         bool metacopy_blocks = false;
149
150         metacopy_blocks = ovl_is_metacopy_dentry(dentry);
151
152         type = ovl_path_real(dentry, &realpath);
153         old_cred = ovl_override_creds(dentry->d_sb);
154         err = vfs_getattr(&realpath, stat, request_mask, flags);
155         if (err)
156                 goto out;
157
158         /*
159          * For non-dir or same fs, we use st_ino of the copy up origin.
160          * This guaranties constant st_dev/st_ino across copy up.
161          * With xino feature and non-samefs, we use st_ino of the copy up
162          * origin masked with high bits that represent the layer id.
163          *
164          * If lower filesystem supports NFS file handles, this also guaranties
165          * persistent st_ino across mount cycle.
166          */
167         if (!is_dir || samefs || ovl_xino_bits(dentry->d_sb)) {
168                 if (!OVL_TYPE_UPPER(type)) {
169                         lower_layer = ovl_layer_lower(dentry);
170                 } else if (OVL_TYPE_ORIGIN(type)) {
171                         struct kstat lowerstat;
172                         u32 lowermask = STATX_INO | STATX_BLOCKS |
173                                         (!is_dir ? STATX_NLINK : 0);
174
175                         ovl_path_lower(dentry, &realpath);
176                         err = vfs_getattr(&realpath, &lowerstat,
177                                           lowermask, flags);
178                         if (err)
179                                 goto out;
180
181                         /*
182                          * Lower hardlinks may be broken on copy up to different
183                          * upper files, so we cannot use the lower origin st_ino
184                          * for those different files, even for the same fs case.
185                          *
186                          * Similarly, several redirected dirs can point to the
187                          * same dir on a lower layer. With the "verify_lower"
188                          * feature, we do not use the lower origin st_ino, if
189                          * we haven't verified that this redirect is unique.
190                          *
191                          * With inodes index enabled, it is safe to use st_ino
192                          * of an indexed origin. The index validates that the
193                          * upper hardlink is not broken and that a redirected
194                          * dir is the only redirect to that origin.
195                          */
196                         if (ovl_test_flag(OVL_INDEX, d_inode(dentry)) ||
197                             (!ovl_verify_lower(dentry->d_sb) &&
198                              (is_dir || lowerstat.nlink == 1))) {
199                                 stat->ino = lowerstat.ino;
200                                 lower_layer = ovl_layer_lower(dentry);
201                         }
202
203                         /*
204                          * If we are querying a metacopy dentry and lower
205                          * dentry is data dentry, then use the blocks we
206                          * queried just now. We don't have to do additional
207                          * vfs_getattr(). If lower itself is metacopy, then
208                          * additional vfs_getattr() is unavoidable.
209                          */
210                         if (metacopy_blocks &&
211                             realpath.dentry == ovl_dentry_lowerdata(dentry)) {
212                                 stat->blocks = lowerstat.blocks;
213                                 metacopy_blocks = false;
214                         }
215                 }
216
217                 if (metacopy_blocks) {
218                         /*
219                          * If lower is not same as lowerdata or if there was
220                          * no origin on upper, we can end up here.
221                          */
222                         struct kstat lowerdatastat;
223                         u32 lowermask = STATX_BLOCKS;
224
225                         ovl_path_lowerdata(dentry, &realpath);
226                         err = vfs_getattr(&realpath, &lowerdatastat,
227                                           lowermask, flags);
228                         if (err)
229                                 goto out;
230                         stat->blocks = lowerdatastat.blocks;
231                 }
232         }
233
234         err = ovl_map_dev_ino(dentry, stat, lower_layer);
235         if (err)
236                 goto out;
237
238         /*
239          * It's probably not worth it to count subdirs to get the
240          * correct link count.  nlink=1 seems to pacify 'find' and
241          * other utilities.
242          */
243         if (is_dir && OVL_TYPE_MERGE(type))
244                 stat->nlink = 1;
245
246         /*
247          * Return the overlay inode nlinks for indexed upper inodes.
248          * Overlay inode nlink counts the union of the upper hardlinks
249          * and non-covered lower hardlinks. It does not include the upper
250          * index hardlink.
251          */
252         if (!is_dir && ovl_test_flag(OVL_INDEX, d_inode(dentry)))
253                 stat->nlink = dentry->d_inode->i_nlink;
254
255 out:
256         revert_creds(old_cred);
257
258         return err;
259 }
260
261 int ovl_permission(struct inode *inode, int mask)
262 {
263         struct inode *upperinode = ovl_inode_upper(inode);
264         struct inode *realinode = upperinode ?: ovl_inode_lower(inode);
265         const struct cred *old_cred;
266         int err;
267
268         /* Careful in RCU walk mode */
269         if (!realinode) {
270                 WARN_ON(!(mask & MAY_NOT_BLOCK));
271                 return -ECHILD;
272         }
273
274         /*
275          * Check overlay inode with the creds of task and underlying inode
276          * with creds of mounter
277          */
278         err = generic_permission(inode, mask);
279         if (err)
280                 return err;
281
282         old_cred = ovl_override_creds(inode->i_sb);
283         if (!upperinode &&
284             !special_file(realinode->i_mode) && mask & MAY_WRITE) {
285                 mask &= ~(MAY_WRITE | MAY_APPEND);
286                 /* Make sure mounter can read file for copy up later */
287                 mask |= MAY_READ;
288         }
289         err = inode_permission(realinode, mask);
290         revert_creds(old_cred);
291
292         return err;
293 }
294
295 static const char *ovl_get_link(struct dentry *dentry,
296                                 struct inode *inode,
297                                 struct delayed_call *done)
298 {
299         const struct cred *old_cred;
300         const char *p;
301
302         if (!dentry)
303                 return ERR_PTR(-ECHILD);
304
305         old_cred = ovl_override_creds(dentry->d_sb);
306         p = vfs_get_link(ovl_dentry_real(dentry), done);
307         revert_creds(old_cred);
308         return p;
309 }
310
311 bool ovl_is_private_xattr(const char *name)
312 {
313         return strncmp(name, OVL_XATTR_PREFIX,
314                        sizeof(OVL_XATTR_PREFIX) - 1) == 0;
315 }
316
317 int ovl_xattr_set(struct dentry *dentry, struct inode *inode, const char *name,
318                   const void *value, size_t size, int flags)
319 {
320         int err;
321         struct dentry *upperdentry = ovl_i_dentry_upper(inode);
322         struct dentry *realdentry = upperdentry ?: ovl_dentry_lower(dentry);
323         const struct cred *old_cred;
324
325         err = ovl_want_write(dentry);
326         if (err)
327                 goto out;
328
329         if (!value && !upperdentry) {
330                 err = vfs_getxattr(realdentry, name, NULL, 0);
331                 if (err < 0)
332                         goto out_drop_write;
333         }
334
335         if (!upperdentry) {
336                 err = ovl_copy_up(dentry);
337                 if (err)
338                         goto out_drop_write;
339
340                 realdentry = ovl_dentry_upper(dentry);
341         }
342
343         old_cred = ovl_override_creds(dentry->d_sb);
344         if (value)
345                 err = vfs_setxattr(realdentry, name, value, size, flags);
346         else {
347                 WARN_ON(flags != XATTR_REPLACE);
348                 err = vfs_removexattr(realdentry, name);
349         }
350         revert_creds(old_cred);
351
352         /* copy c/mtime */
353         ovl_copyattr(d_inode(realdentry), inode);
354
355 out_drop_write:
356         ovl_drop_write(dentry);
357 out:
358         return err;
359 }
360
361 int ovl_xattr_get(struct dentry *dentry, struct inode *inode, const char *name,
362                   void *value, size_t size)
363 {
364         ssize_t res;
365         const struct cred *old_cred;
366         struct dentry *realdentry =
367                 ovl_i_dentry_upper(inode) ?: ovl_dentry_lower(dentry);
368
369         old_cred = ovl_override_creds(dentry->d_sb);
370         res = vfs_getxattr(realdentry, name, value, size);
371         revert_creds(old_cred);
372         return res;
373 }
374
375 static bool ovl_can_list(const char *s)
376 {
377         /* List all non-trusted xatts */
378         if (strncmp(s, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) != 0)
379                 return true;
380
381         /* Never list trusted.overlay, list other trusted for superuser only */
382         return !ovl_is_private_xattr(s) && capable(CAP_SYS_ADMIN);
383 }
384
385 ssize_t ovl_listxattr(struct dentry *dentry, char *list, size_t size)
386 {
387         struct dentry *realdentry = ovl_dentry_real(dentry);
388         ssize_t res;
389         size_t len;
390         char *s;
391         const struct cred *old_cred;
392
393         old_cred = ovl_override_creds(dentry->d_sb);
394         res = vfs_listxattr(realdentry, list, size);
395         revert_creds(old_cred);
396         if (res <= 0 || size == 0)
397                 return res;
398
399         /* filter out private xattrs */
400         for (s = list, len = res; len;) {
401                 size_t slen = strnlen(s, len) + 1;
402
403                 /* underlying fs providing us with an broken xattr list? */
404                 if (WARN_ON(slen > len))
405                         return -EIO;
406
407                 len -= slen;
408                 if (!ovl_can_list(s)) {
409                         res -= slen;
410                         memmove(s, s + slen, len);
411                 } else {
412                         s += slen;
413                 }
414         }
415
416         return res;
417 }
418
419 struct posix_acl *ovl_get_acl(struct inode *inode, int type)
420 {
421         struct inode *realinode = ovl_inode_real(inode);
422         const struct cred *old_cred;
423         struct posix_acl *acl;
424
425         if (!IS_ENABLED(CONFIG_FS_POSIX_ACL) || !IS_POSIXACL(realinode))
426                 return NULL;
427
428         old_cred = ovl_override_creds(inode->i_sb);
429         acl = get_acl(realinode, type);
430         revert_creds(old_cred);
431
432         return acl;
433 }
434
435 int ovl_update_time(struct inode *inode, struct timespec64 *ts, int flags)
436 {
437         if (flags & S_ATIME) {
438                 struct ovl_fs *ofs = inode->i_sb->s_fs_info;
439                 struct path upperpath = {
440                         .mnt = ofs->upper_mnt,
441                         .dentry = ovl_upperdentry_dereference(OVL_I(inode)),
442                 };
443
444                 if (upperpath.dentry) {
445                         touch_atime(&upperpath);
446                         inode->i_atime = d_inode(upperpath.dentry)->i_atime;
447                 }
448         }
449         return 0;
450 }
451
452 static int ovl_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
453                       u64 start, u64 len)
454 {
455         int err;
456         struct inode *realinode = ovl_inode_real(inode);
457         const struct cred *old_cred;
458
459         if (!realinode->i_op->fiemap)
460                 return -EOPNOTSUPP;
461
462         old_cred = ovl_override_creds(inode->i_sb);
463         err = realinode->i_op->fiemap(realinode, fieinfo, start, len);
464         revert_creds(old_cred);
465
466         return err;
467 }
468
469 static const struct inode_operations ovl_file_inode_operations = {
470         .setattr        = ovl_setattr,
471         .permission     = ovl_permission,
472         .getattr        = ovl_getattr,
473         .listxattr      = ovl_listxattr,
474         .get_acl        = ovl_get_acl,
475         .update_time    = ovl_update_time,
476         .fiemap         = ovl_fiemap,
477 };
478
479 static const struct inode_operations ovl_symlink_inode_operations = {
480         .setattr        = ovl_setattr,
481         .get_link       = ovl_get_link,
482         .getattr        = ovl_getattr,
483         .listxattr      = ovl_listxattr,
484         .update_time    = ovl_update_time,
485 };
486
487 static const struct inode_operations ovl_special_inode_operations = {
488         .setattr        = ovl_setattr,
489         .permission     = ovl_permission,
490         .getattr        = ovl_getattr,
491         .listxattr      = ovl_listxattr,
492         .get_acl        = ovl_get_acl,
493         .update_time    = ovl_update_time,
494 };
495
496 /*
497  * It is possible to stack overlayfs instance on top of another
498  * overlayfs instance as lower layer. We need to annonate the
499  * stackable i_mutex locks according to stack level of the super
500  * block instance. An overlayfs instance can never be in stack
501  * depth 0 (there is always a real fs below it).  An overlayfs
502  * inode lock will use the lockdep annotaion ovl_i_mutex_key[depth].
503  *
504  * For example, here is a snip from /proc/lockdep_chains after
505  * dir_iterate of nested overlayfs:
506  *
507  * [...] &ovl_i_mutex_dir_key[depth]   (stack_depth=2)
508  * [...] &ovl_i_mutex_dir_key[depth]#2 (stack_depth=1)
509  * [...] &type->i_mutex_dir_key        (stack_depth=0)
510  */
511 #define OVL_MAX_NESTING FILESYSTEM_MAX_STACK_DEPTH
512
513 static inline void ovl_lockdep_annotate_inode_mutex_key(struct inode *inode)
514 {
515 #ifdef CONFIG_LOCKDEP
516         static struct lock_class_key ovl_i_mutex_key[OVL_MAX_NESTING];
517         static struct lock_class_key ovl_i_mutex_dir_key[OVL_MAX_NESTING];
518         static struct lock_class_key ovl_i_lock_key[OVL_MAX_NESTING];
519
520         int depth = inode->i_sb->s_stack_depth - 1;
521
522         if (WARN_ON_ONCE(depth < 0 || depth >= OVL_MAX_NESTING))
523                 depth = 0;
524
525         if (S_ISDIR(inode->i_mode))
526                 lockdep_set_class(&inode->i_rwsem, &ovl_i_mutex_dir_key[depth]);
527         else
528                 lockdep_set_class(&inode->i_rwsem, &ovl_i_mutex_key[depth]);
529
530         lockdep_set_class(&OVL_I(inode)->lock, &ovl_i_lock_key[depth]);
531 #endif
532 }
533
534 static void ovl_fill_inode(struct inode *inode, umode_t mode, dev_t rdev,
535                            unsigned long ino, int fsid)
536 {
537         int xinobits = ovl_xino_bits(inode->i_sb);
538
539         /*
540          * When NFS export is enabled and d_ino is consistent with st_ino
541          * (samefs or i_ino has enough bits to encode layer), set the same
542          * value used for d_ino to i_ino, because nfsd readdirplus compares
543          * d_ino values to i_ino values of child entries. When called from
544          * ovl_new_inode(), ino arg is 0, so i_ino will be updated to real
545          * upper inode i_ino on ovl_inode_init() or ovl_inode_update().
546          */
547         if (inode->i_sb->s_export_op &&
548             (ovl_same_sb(inode->i_sb) || xinobits)) {
549                 inode->i_ino = ino;
550                 if (xinobits && fsid && !(ino >> (64 - xinobits)))
551                         inode->i_ino |= (unsigned long)fsid << (64 - xinobits);
552         } else {
553                 inode->i_ino = get_next_ino();
554         }
555         inode->i_mode = mode;
556         inode->i_flags |= S_NOCMTIME;
557 #ifdef CONFIG_FS_POSIX_ACL
558         inode->i_acl = inode->i_default_acl = ACL_DONT_CACHE;
559 #endif
560
561         ovl_lockdep_annotate_inode_mutex_key(inode);
562
563         switch (mode & S_IFMT) {
564         case S_IFREG:
565                 inode->i_op = &ovl_file_inode_operations;
566                 inode->i_fop = &ovl_file_operations;
567                 break;
568
569         case S_IFDIR:
570                 inode->i_op = &ovl_dir_inode_operations;
571                 inode->i_fop = &ovl_dir_operations;
572                 break;
573
574         case S_IFLNK:
575                 inode->i_op = &ovl_symlink_inode_operations;
576                 break;
577
578         default:
579                 inode->i_op = &ovl_special_inode_operations;
580                 init_special_inode(inode, mode, rdev);
581                 break;
582         }
583 }
584
585 /*
586  * With inodes index enabled, an overlay inode nlink counts the union of upper
587  * hardlinks and non-covered lower hardlinks. During the lifetime of a non-pure
588  * upper inode, the following nlink modifying operations can happen:
589  *
590  * 1. Lower hardlink copy up
591  * 2. Upper hardlink created, unlinked or renamed over
592  * 3. Lower hardlink whiteout or renamed over
593  *
594  * For the first, copy up case, the union nlink does not change, whether the
595  * operation succeeds or fails, but the upper inode nlink may change.
596  * Therefore, before copy up, we store the union nlink value relative to the
597  * lower inode nlink in the index inode xattr trusted.overlay.nlink.
598  *
599  * For the second, upper hardlink case, the union nlink should be incremented
600  * or decremented IFF the operation succeeds, aligned with nlink change of the
601  * upper inode. Therefore, before link/unlink/rename, we store the union nlink
602  * value relative to the upper inode nlink in the index inode.
603  *
604  * For the last, lower cover up case, we simplify things by preceding the
605  * whiteout or cover up with copy up. This makes sure that there is an index
606  * upper inode where the nlink xattr can be stored before the copied up upper
607  * entry is unlink.
608  */
609 #define OVL_NLINK_ADD_UPPER     (1 << 0)
610
611 /*
612  * On-disk format for indexed nlink:
613  *
614  * nlink relative to the upper inode - "U[+-]NUM"
615  * nlink relative to the lower inode - "L[+-]NUM"
616  */
617
618 static int ovl_set_nlink_common(struct dentry *dentry,
619                                 struct dentry *realdentry, const char *format)
620 {
621         struct inode *inode = d_inode(dentry);
622         struct inode *realinode = d_inode(realdentry);
623         char buf[13];
624         int len;
625
626         len = snprintf(buf, sizeof(buf), format,
627                        (int) (inode->i_nlink - realinode->i_nlink));
628
629         if (WARN_ON(len >= sizeof(buf)))
630                 return -EIO;
631
632         return ovl_do_setxattr(ovl_dentry_upper(dentry),
633                                OVL_XATTR_NLINK, buf, len, 0);
634 }
635
636 int ovl_set_nlink_upper(struct dentry *dentry)
637 {
638         return ovl_set_nlink_common(dentry, ovl_dentry_upper(dentry), "U%+i");
639 }
640
641 int ovl_set_nlink_lower(struct dentry *dentry)
642 {
643         return ovl_set_nlink_common(dentry, ovl_dentry_lower(dentry), "L%+i");
644 }
645
646 unsigned int ovl_get_nlink(struct dentry *lowerdentry,
647                            struct dentry *upperdentry,
648                            unsigned int fallback)
649 {
650         int nlink_diff;
651         int nlink;
652         char buf[13];
653         int err;
654
655         if (!lowerdentry || !upperdentry || d_inode(lowerdentry)->i_nlink == 1)
656                 return fallback;
657
658         err = vfs_getxattr(upperdentry, OVL_XATTR_NLINK, &buf, sizeof(buf) - 1);
659         if (err < 0)
660                 goto fail;
661
662         buf[err] = '\0';
663         if ((buf[0] != 'L' && buf[0] != 'U') ||
664             (buf[1] != '+' && buf[1] != '-'))
665                 goto fail;
666
667         err = kstrtoint(buf + 1, 10, &nlink_diff);
668         if (err < 0)
669                 goto fail;
670
671         nlink = d_inode(buf[0] == 'L' ? lowerdentry : upperdentry)->i_nlink;
672         nlink += nlink_diff;
673
674         if (nlink <= 0)
675                 goto fail;
676
677         return nlink;
678
679 fail:
680         pr_warn_ratelimited("overlayfs: failed to get index nlink (%pd2, err=%i)\n",
681                             upperdentry, err);
682         return fallback;
683 }
684
685 struct inode *ovl_new_inode(struct super_block *sb, umode_t mode, dev_t rdev)
686 {
687         struct inode *inode;
688
689         inode = new_inode(sb);
690         if (inode)
691                 ovl_fill_inode(inode, mode, rdev, 0, 0);
692
693         return inode;
694 }
695
696 static int ovl_inode_test(struct inode *inode, void *data)
697 {
698         return inode->i_private == data;
699 }
700
701 static int ovl_inode_set(struct inode *inode, void *data)
702 {
703         inode->i_private = data;
704         return 0;
705 }
706
707 static bool ovl_verify_inode(struct inode *inode, struct dentry *lowerdentry,
708                              struct dentry *upperdentry, bool strict)
709 {
710         /*
711          * For directories, @strict verify from lookup path performs consistency
712          * checks, so NULL lower/upper in dentry must match NULL lower/upper in
713          * inode. Non @strict verify from NFS handle decode path passes NULL for
714          * 'unknown' lower/upper.
715          */
716         if (S_ISDIR(inode->i_mode) && strict) {
717                 /* Real lower dir moved to upper layer under us? */
718                 if (!lowerdentry && ovl_inode_lower(inode))
719                         return false;
720
721                 /* Lookup of an uncovered redirect origin? */
722                 if (!upperdentry && ovl_inode_upper(inode))
723                         return false;
724         }
725
726         /*
727          * Allow non-NULL lower inode in ovl_inode even if lowerdentry is NULL.
728          * This happens when finding a copied up overlay inode for a renamed
729          * or hardlinked overlay dentry and lower dentry cannot be followed
730          * by origin because lower fs does not support file handles.
731          */
732         if (lowerdentry && ovl_inode_lower(inode) != d_inode(lowerdentry))
733                 return false;
734
735         /*
736          * Allow non-NULL __upperdentry in inode even if upperdentry is NULL.
737          * This happens when finding a lower alias for a copied up hard link.
738          */
739         if (upperdentry && ovl_inode_upper(inode) != d_inode(upperdentry))
740                 return false;
741
742         return true;
743 }
744
745 struct inode *ovl_lookup_inode(struct super_block *sb, struct dentry *real,
746                                bool is_upper)
747 {
748         struct inode *inode, *key = d_inode(real);
749
750         inode = ilookup5(sb, (unsigned long) key, ovl_inode_test, key);
751         if (!inode)
752                 return NULL;
753
754         if (!ovl_verify_inode(inode, is_upper ? NULL : real,
755                               is_upper ? real : NULL, false)) {
756                 iput(inode);
757                 return ERR_PTR(-ESTALE);
758         }
759
760         return inode;
761 }
762
763 /*
764  * Does overlay inode need to be hashed by lower inode?
765  */
766 static bool ovl_hash_bylower(struct super_block *sb, struct dentry *upper,
767                              struct dentry *lower, struct dentry *index)
768 {
769         struct ovl_fs *ofs = sb->s_fs_info;
770
771         /* No, if pure upper */
772         if (!lower)
773                 return false;
774
775         /* Yes, if already indexed */
776         if (index)
777                 return true;
778
779         /* Yes, if won't be copied up */
780         if (!ofs->upper_mnt)
781                 return true;
782
783         /* No, if lower hardlink is or will be broken on copy up */
784         if ((upper || !ovl_indexdir(sb)) &&
785             !d_is_dir(lower) && d_inode(lower)->i_nlink > 1)
786                 return false;
787
788         /* No, if non-indexed upper with NFS export */
789         if (sb->s_export_op && upper)
790                 return false;
791
792         /* Otherwise, hash by lower inode for fsnotify */
793         return true;
794 }
795
796 static struct inode *ovl_iget5(struct super_block *sb, struct inode *newinode,
797                                struct inode *key)
798 {
799         return newinode ? inode_insert5(newinode, (unsigned long) key,
800                                          ovl_inode_test, ovl_inode_set, key) :
801                           iget5_locked(sb, (unsigned long) key,
802                                        ovl_inode_test, ovl_inode_set, key);
803 }
804
805 struct inode *ovl_get_inode(struct super_block *sb,
806                             struct ovl_inode_params *oip)
807 {
808         struct dentry *upperdentry = oip->upperdentry;
809         struct ovl_path *lowerpath = oip->lowerpath;
810         struct inode *realinode = upperdentry ? d_inode(upperdentry) : NULL;
811         struct inode *inode;
812         struct dentry *lowerdentry = lowerpath ? lowerpath->dentry : NULL;
813         bool bylower = ovl_hash_bylower(sb, upperdentry, lowerdentry,
814                                         oip->index);
815         int fsid = bylower ? oip->lowerpath->layer->fsid : 0;
816         bool is_dir, metacopy = false;
817         unsigned long ino = 0;
818         int err = -ENOMEM;
819
820         if (!realinode)
821                 realinode = d_inode(lowerdentry);
822
823         /*
824          * Copy up origin (lower) may exist for non-indexed upper, but we must
825          * not use lower as hash key if this is a broken hardlink.
826          */
827         is_dir = S_ISDIR(realinode->i_mode);
828         if (upperdentry || bylower) {
829                 struct inode *key = d_inode(bylower ? lowerdentry :
830                                                       upperdentry);
831                 unsigned int nlink = is_dir ? 1 : realinode->i_nlink;
832
833                 inode = ovl_iget5(sb, oip->newinode, key);
834                 if (!inode)
835                         goto out_err;
836                 if (!(inode->i_state & I_NEW)) {
837                         /*
838                          * Verify that the underlying files stored in the inode
839                          * match those in the dentry.
840                          */
841                         if (!ovl_verify_inode(inode, lowerdentry, upperdentry,
842                                               true)) {
843                                 iput(inode);
844                                 err = -ESTALE;
845                                 goto out_err;
846                         }
847
848                         dput(upperdentry);
849                         kfree(oip->redirect);
850                         goto out;
851                 }
852
853                 /* Recalculate nlink for non-dir due to indexing */
854                 if (!is_dir)
855                         nlink = ovl_get_nlink(lowerdentry, upperdentry, nlink);
856                 set_nlink(inode, nlink);
857                 ino = key->i_ino;
858         } else {
859                 /* Lower hardlink that will be broken on copy up */
860                 inode = new_inode(sb);
861                 if (!inode) {
862                         err = -ENOMEM;
863                         goto out_err;
864                 }
865         }
866         ovl_fill_inode(inode, realinode->i_mode, realinode->i_rdev, ino, fsid);
867         ovl_inode_init(inode, upperdentry, lowerdentry);
868
869         if (upperdentry && ovl_is_impuredir(upperdentry))
870                 ovl_set_flag(OVL_IMPURE, inode);
871
872         if (oip->index)
873                 ovl_set_flag(OVL_INDEX, inode);
874
875         if (upperdentry) {
876                 err = ovl_check_metacopy_xattr(upperdentry);
877                 if (err < 0)
878                         goto out_err;
879                 metacopy = err;
880                 if (!metacopy)
881                         ovl_set_flag(OVL_UPPERDATA, inode);
882         }
883
884         OVL_I(inode)->redirect = oip->redirect;
885
886         /* Check for non-merge dir that may have whiteouts */
887         if (is_dir) {
888                 if (((upperdentry && lowerdentry) || oip->numlower > 1) ||
889                     ovl_check_origin_xattr(upperdentry ?: lowerdentry)) {
890                         ovl_set_flag(OVL_WHITEOUTS, inode);
891                 }
892         }
893
894         if (inode->i_state & I_NEW)
895                 unlock_new_inode(inode);
896 out:
897         return inode;
898
899 out_err:
900         inode = ERR_PTR(err);
901         goto out;
902 }