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