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