GNU Linux-libre 5.15.137-gnu
[releases.git] / fs / namei.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  linux/fs/namei.c
4  *
5  *  Copyright (C) 1991, 1992  Linus Torvalds
6  */
7
8 /*
9  * Some corrections by tytso.
10  */
11
12 /* [Feb 1997 T. Schoebel-Theuer] Complete rewrite of the pathname
13  * lookup logic.
14  */
15 /* [Feb-Apr 2000, AV] Rewrite to the new namespace architecture.
16  */
17
18 #include <linux/init.h>
19 #include <linux/export.h>
20 #include <linux/kernel.h>
21 #include <linux/slab.h>
22 #include <linux/fs.h>
23 #include <linux/namei.h>
24 #include <linux/pagemap.h>
25 #include <linux/fsnotify.h>
26 #include <linux/personality.h>
27 #include <linux/security.h>
28 #include <linux/ima.h>
29 #include <linux/syscalls.h>
30 #include <linux/mount.h>
31 #include <linux/audit.h>
32 #include <linux/capability.h>
33 #include <linux/file.h>
34 #include <linux/fcntl.h>
35 #include <linux/device_cgroup.h>
36 #include <linux/fs_struct.h>
37 #include <linux/posix_acl.h>
38 #include <linux/hash.h>
39 #include <linux/bitops.h>
40 #include <linux/init_task.h>
41 #include <linux/uaccess.h>
42
43 #include "internal.h"
44 #include "mount.h"
45
46 /* [Feb-1997 T. Schoebel-Theuer]
47  * Fundamental changes in the pathname lookup mechanisms (namei)
48  * were necessary because of omirr.  The reason is that omirr needs
49  * to know the _real_ pathname, not the user-supplied one, in case
50  * of symlinks (and also when transname replacements occur).
51  *
52  * The new code replaces the old recursive symlink resolution with
53  * an iterative one (in case of non-nested symlink chains).  It does
54  * this with calls to <fs>_follow_link().
55  * As a side effect, dir_namei(), _namei() and follow_link() are now 
56  * replaced with a single function lookup_dentry() that can handle all 
57  * the special cases of the former code.
58  *
59  * With the new dcache, the pathname is stored at each inode, at least as
60  * long as the refcount of the inode is positive.  As a side effect, the
61  * size of the dcache depends on the inode cache and thus is dynamic.
62  *
63  * [29-Apr-1998 C. Scott Ananian] Updated above description of symlink
64  * resolution to correspond with current state of the code.
65  *
66  * Note that the symlink resolution is not *completely* iterative.
67  * There is still a significant amount of tail- and mid- recursion in
68  * the algorithm.  Also, note that <fs>_readlink() is not used in
69  * lookup_dentry(): lookup_dentry() on the result of <fs>_readlink()
70  * may return different results than <fs>_follow_link().  Many virtual
71  * filesystems (including /proc) exhibit this behavior.
72  */
73
74 /* [24-Feb-97 T. Schoebel-Theuer] Side effects caused by new implementation:
75  * New symlink semantics: when open() is called with flags O_CREAT | O_EXCL
76  * and the name already exists in form of a symlink, try to create the new
77  * name indicated by the symlink. The old code always complained that the
78  * name already exists, due to not following the symlink even if its target
79  * is nonexistent.  The new semantics affects also mknod() and link() when
80  * the name is a symlink pointing to a non-existent name.
81  *
82  * I don't know which semantics is the right one, since I have no access
83  * to standards. But I found by trial that HP-UX 9.0 has the full "new"
84  * semantics implemented, while SunOS 4.1.1 and Solaris (SunOS 5.4) have the
85  * "old" one. Personally, I think the new semantics is much more logical.
86  * Note that "ln old new" where "new" is a symlink pointing to a non-existing
87  * file does succeed in both HP-UX and SunOs, but not in Solaris
88  * and in the old Linux semantics.
89  */
90
91 /* [16-Dec-97 Kevin Buhr] For security reasons, we change some symlink
92  * semantics.  See the comments in "open_namei" and "do_link" below.
93  *
94  * [10-Sep-98 Alan Modra] Another symlink change.
95  */
96
97 /* [Feb-Apr 2000 AV] Complete rewrite. Rules for symlinks:
98  *      inside the path - always follow.
99  *      in the last component in creation/removal/renaming - never follow.
100  *      if LOOKUP_FOLLOW passed - follow.
101  *      if the pathname has trailing slashes - follow.
102  *      otherwise - don't follow.
103  * (applied in that order).
104  *
105  * [Jun 2000 AV] Inconsistent behaviour of open() in case if flags==O_CREAT
106  * restored for 2.4. This is the last surviving part of old 4.2BSD bug.
107  * During the 2.4 we need to fix the userland stuff depending on it -
108  * hopefully we will be able to get rid of that wart in 2.5. So far only
109  * XEmacs seems to be relying on it...
110  */
111 /*
112  * [Sep 2001 AV] Single-semaphore locking scheme (kudos to David Holland)
113  * implemented.  Let's see if raised priority of ->s_vfs_rename_mutex gives
114  * any extra contention...
115  */
116
117 /* In order to reduce some races, while at the same time doing additional
118  * checking and hopefully speeding things up, we copy filenames to the
119  * kernel data space before using them..
120  *
121  * POSIX.1 2.4: an empty pathname is invalid (ENOENT).
122  * PATH_MAX includes the nul terminator --RR.
123  */
124
125 #define EMBEDDED_NAME_MAX       (PATH_MAX - offsetof(struct filename, iname))
126
127 struct filename *
128 getname_flags(const char __user *filename, int flags, int *empty)
129 {
130         struct filename *result;
131         char *kname;
132         int len;
133
134         result = audit_reusename(filename);
135         if (result)
136                 return result;
137
138         result = __getname();
139         if (unlikely(!result))
140                 return ERR_PTR(-ENOMEM);
141
142         /*
143          * First, try to embed the struct filename inside the names_cache
144          * allocation
145          */
146         kname = (char *)result->iname;
147         result->name = kname;
148
149         len = strncpy_from_user(kname, filename, EMBEDDED_NAME_MAX);
150         if (unlikely(len < 0)) {
151                 __putname(result);
152                 return ERR_PTR(len);
153         }
154
155         /*
156          * Uh-oh. We have a name that's approaching PATH_MAX. Allocate a
157          * separate struct filename so we can dedicate the entire
158          * names_cache allocation for the pathname, and re-do the copy from
159          * userland.
160          */
161         if (unlikely(len == EMBEDDED_NAME_MAX)) {
162                 const size_t size = offsetof(struct filename, iname[1]);
163                 kname = (char *)result;
164
165                 /*
166                  * size is chosen that way we to guarantee that
167                  * result->iname[0] is within the same object and that
168                  * kname can't be equal to result->iname, no matter what.
169                  */
170                 result = kzalloc(size, GFP_KERNEL);
171                 if (unlikely(!result)) {
172                         __putname(kname);
173                         return ERR_PTR(-ENOMEM);
174                 }
175                 result->name = kname;
176                 len = strncpy_from_user(kname, filename, PATH_MAX);
177                 if (unlikely(len < 0)) {
178                         __putname(kname);
179                         kfree(result);
180                         return ERR_PTR(len);
181                 }
182                 if (unlikely(len == PATH_MAX)) {
183                         __putname(kname);
184                         kfree(result);
185                         return ERR_PTR(-ENAMETOOLONG);
186                 }
187         }
188
189         result->refcnt = 1;
190         /* The empty path is special. */
191         if (unlikely(!len)) {
192                 if (empty)
193                         *empty = 1;
194                 if (!(flags & LOOKUP_EMPTY)) {
195                         putname(result);
196                         return ERR_PTR(-ENOENT);
197                 }
198         }
199
200         result->uptr = filename;
201         result->aname = NULL;
202         audit_getname(result);
203         return result;
204 }
205
206 struct filename *
207 getname_uflags(const char __user *filename, int uflags)
208 {
209         int flags = (uflags & AT_EMPTY_PATH) ? LOOKUP_EMPTY : 0;
210
211         return getname_flags(filename, flags, NULL);
212 }
213
214 struct filename *
215 getname(const char __user * filename)
216 {
217         return getname_flags(filename, 0, NULL);
218 }
219
220 struct filename *
221 getname_kernel(const char * filename)
222 {
223         struct filename *result;
224         int len = strlen(filename) + 1;
225
226         result = __getname();
227         if (unlikely(!result))
228                 return ERR_PTR(-ENOMEM);
229
230         if (len <= EMBEDDED_NAME_MAX) {
231                 result->name = (char *)result->iname;
232         } else if (len <= PATH_MAX) {
233                 const size_t size = offsetof(struct filename, iname[1]);
234                 struct filename *tmp;
235
236                 tmp = kmalloc(size, GFP_KERNEL);
237                 if (unlikely(!tmp)) {
238                         __putname(result);
239                         return ERR_PTR(-ENOMEM);
240                 }
241                 tmp->name = (char *)result;
242                 result = tmp;
243         } else {
244                 __putname(result);
245                 return ERR_PTR(-ENAMETOOLONG);
246         }
247         memcpy((char *)result->name, filename, len);
248         result->uptr = NULL;
249         result->aname = NULL;
250         result->refcnt = 1;
251         audit_getname(result);
252
253         return result;
254 }
255
256 void putname(struct filename *name)
257 {
258         if (IS_ERR(name))
259                 return;
260
261         BUG_ON(name->refcnt <= 0);
262
263         if (--name->refcnt > 0)
264                 return;
265
266         if (name->name != name->iname) {
267                 __putname(name->name);
268                 kfree(name);
269         } else
270                 __putname(name);
271 }
272
273 /**
274  * check_acl - perform ACL permission checking
275  * @mnt_userns: user namespace of the mount the inode was found from
276  * @inode:      inode to check permissions on
277  * @mask:       right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
278  *
279  * This function performs the ACL permission checking. Since this function
280  * retrieve POSIX acls it needs to know whether it is called from a blocking or
281  * non-blocking context and thus cares about the MAY_NOT_BLOCK bit.
282  *
283  * If the inode has been found through an idmapped mount the user namespace of
284  * the vfsmount must be passed through @mnt_userns. This function will then take
285  * care to map the inode according to @mnt_userns before checking permissions.
286  * On non-idmapped mounts or if permission checking is to be performed on the
287  * raw inode simply passs init_user_ns.
288  */
289 static int check_acl(struct user_namespace *mnt_userns,
290                      struct inode *inode, int mask)
291 {
292 #ifdef CONFIG_FS_POSIX_ACL
293         struct posix_acl *acl;
294
295         if (mask & MAY_NOT_BLOCK) {
296                 acl = get_cached_acl_rcu(inode, ACL_TYPE_ACCESS);
297                 if (!acl)
298                         return -EAGAIN;
299                 /* no ->get_acl() calls in RCU mode... */
300                 if (is_uncached_acl(acl))
301                         return -ECHILD;
302                 return posix_acl_permission(mnt_userns, inode, acl, mask);
303         }
304
305         acl = get_acl(inode, ACL_TYPE_ACCESS);
306         if (IS_ERR(acl))
307                 return PTR_ERR(acl);
308         if (acl) {
309                 int error = posix_acl_permission(mnt_userns, inode, acl, mask);
310                 posix_acl_release(acl);
311                 return error;
312         }
313 #endif
314
315         return -EAGAIN;
316 }
317
318 /**
319  * acl_permission_check - perform basic UNIX permission checking
320  * @mnt_userns: user namespace of the mount the inode was found from
321  * @inode:      inode to check permissions on
322  * @mask:       right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
323  *
324  * This function performs the basic UNIX permission checking. Since this
325  * function may retrieve POSIX acls it needs to know whether it is called from a
326  * blocking or non-blocking context and thus cares about the MAY_NOT_BLOCK bit.
327  *
328  * If the inode has been found through an idmapped mount the user namespace of
329  * the vfsmount must be passed through @mnt_userns. This function will then take
330  * care to map the inode according to @mnt_userns before checking permissions.
331  * On non-idmapped mounts or if permission checking is to be performed on the
332  * raw inode simply passs init_user_ns.
333  */
334 static int acl_permission_check(struct user_namespace *mnt_userns,
335                                 struct inode *inode, int mask)
336 {
337         unsigned int mode = inode->i_mode;
338         kuid_t i_uid;
339
340         /* Are we the owner? If so, ACL's don't matter */
341         i_uid = i_uid_into_mnt(mnt_userns, inode);
342         if (likely(uid_eq(current_fsuid(), i_uid))) {
343                 mask &= 7;
344                 mode >>= 6;
345                 return (mask & ~mode) ? -EACCES : 0;
346         }
347
348         /* Do we have ACL's? */
349         if (IS_POSIXACL(inode) && (mode & S_IRWXG)) {
350                 int error = check_acl(mnt_userns, inode, mask);
351                 if (error != -EAGAIN)
352                         return error;
353         }
354
355         /* Only RWX matters for group/other mode bits */
356         mask &= 7;
357
358         /*
359          * Are the group permissions different from
360          * the other permissions in the bits we care
361          * about? Need to check group ownership if so.
362          */
363         if (mask & (mode ^ (mode >> 3))) {
364                 kgid_t kgid = i_gid_into_mnt(mnt_userns, inode);
365                 if (in_group_p(kgid))
366                         mode >>= 3;
367         }
368
369         /* Bits in 'mode' clear that we require? */
370         return (mask & ~mode) ? -EACCES : 0;
371 }
372
373 /**
374  * generic_permission -  check for access rights on a Posix-like filesystem
375  * @mnt_userns: user namespace of the mount the inode was found from
376  * @inode:      inode to check access rights for
377  * @mask:       right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC,
378  *              %MAY_NOT_BLOCK ...)
379  *
380  * Used to check for read/write/execute permissions on a file.
381  * We use "fsuid" for this, letting us set arbitrary permissions
382  * for filesystem access without changing the "normal" uids which
383  * are used for other things.
384  *
385  * generic_permission is rcu-walk aware. It returns -ECHILD in case an rcu-walk
386  * request cannot be satisfied (eg. requires blocking or too much complexity).
387  * It would then be called again in ref-walk mode.
388  *
389  * If the inode has been found through an idmapped mount the user namespace of
390  * the vfsmount must be passed through @mnt_userns. This function will then take
391  * care to map the inode according to @mnt_userns before checking permissions.
392  * On non-idmapped mounts or if permission checking is to be performed on the
393  * raw inode simply passs init_user_ns.
394  */
395 int generic_permission(struct user_namespace *mnt_userns, struct inode *inode,
396                        int mask)
397 {
398         int ret;
399
400         /*
401          * Do the basic permission checks.
402          */
403         ret = acl_permission_check(mnt_userns, inode, mask);
404         if (ret != -EACCES)
405                 return ret;
406
407         if (S_ISDIR(inode->i_mode)) {
408                 /* DACs are overridable for directories */
409                 if (!(mask & MAY_WRITE))
410                         if (capable_wrt_inode_uidgid(mnt_userns, inode,
411                                                      CAP_DAC_READ_SEARCH))
412                                 return 0;
413                 if (capable_wrt_inode_uidgid(mnt_userns, inode,
414                                              CAP_DAC_OVERRIDE))
415                         return 0;
416                 return -EACCES;
417         }
418
419         /*
420          * Searching includes executable on directories, else just read.
421          */
422         mask &= MAY_READ | MAY_WRITE | MAY_EXEC;
423         if (mask == MAY_READ)
424                 if (capable_wrt_inode_uidgid(mnt_userns, inode,
425                                              CAP_DAC_READ_SEARCH))
426                         return 0;
427         /*
428          * Read/write DACs are always overridable.
429          * Executable DACs are overridable when there is
430          * at least one exec bit set.
431          */
432         if (!(mask & MAY_EXEC) || (inode->i_mode & S_IXUGO))
433                 if (capable_wrt_inode_uidgid(mnt_userns, inode,
434                                              CAP_DAC_OVERRIDE))
435                         return 0;
436
437         return -EACCES;
438 }
439 EXPORT_SYMBOL(generic_permission);
440
441 /**
442  * do_inode_permission - UNIX permission checking
443  * @mnt_userns: user namespace of the mount the inode was found from
444  * @inode:      inode to check permissions on
445  * @mask:       right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
446  *
447  * We _really_ want to just do "generic_permission()" without
448  * even looking at the inode->i_op values. So we keep a cache
449  * flag in inode->i_opflags, that says "this has not special
450  * permission function, use the fast case".
451  */
452 static inline int do_inode_permission(struct user_namespace *mnt_userns,
453                                       struct inode *inode, int mask)
454 {
455         if (unlikely(!(inode->i_opflags & IOP_FASTPERM))) {
456                 if (likely(inode->i_op->permission))
457                         return inode->i_op->permission(mnt_userns, inode, mask);
458
459                 /* This gets set once for the inode lifetime */
460                 spin_lock(&inode->i_lock);
461                 inode->i_opflags |= IOP_FASTPERM;
462                 spin_unlock(&inode->i_lock);
463         }
464         return generic_permission(mnt_userns, inode, mask);
465 }
466
467 /**
468  * sb_permission - Check superblock-level permissions
469  * @sb: Superblock of inode to check permission on
470  * @inode: Inode to check permission on
471  * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
472  *
473  * Separate out file-system wide checks from inode-specific permission checks.
474  */
475 static int sb_permission(struct super_block *sb, struct inode *inode, int mask)
476 {
477         if (unlikely(mask & MAY_WRITE)) {
478                 umode_t mode = inode->i_mode;
479
480                 /* Nobody gets write access to a read-only fs. */
481                 if (sb_rdonly(sb) && (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode)))
482                         return -EROFS;
483         }
484         return 0;
485 }
486
487 /**
488  * inode_permission - Check for access rights to a given inode
489  * @mnt_userns: User namespace of the mount the inode was found from
490  * @inode:      Inode to check permission on
491  * @mask:       Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
492  *
493  * Check for read/write/execute permissions on an inode.  We use fs[ug]id for
494  * this, letting us set arbitrary permissions for filesystem access without
495  * changing the "normal" UIDs which are used for other things.
496  *
497  * When checking for MAY_APPEND, MAY_WRITE must also be set in @mask.
498  */
499 int inode_permission(struct user_namespace *mnt_userns,
500                      struct inode *inode, int mask)
501 {
502         int retval;
503
504         retval = sb_permission(inode->i_sb, inode, mask);
505         if (retval)
506                 return retval;
507
508         if (unlikely(mask & MAY_WRITE)) {
509                 /*
510                  * Nobody gets write access to an immutable file.
511                  */
512                 if (IS_IMMUTABLE(inode))
513                         return -EPERM;
514
515                 /*
516                  * Updating mtime will likely cause i_uid and i_gid to be
517                  * written back improperly if their true value is unknown
518                  * to the vfs.
519                  */
520                 if (HAS_UNMAPPED_ID(mnt_userns, inode))
521                         return -EACCES;
522         }
523
524         retval = do_inode_permission(mnt_userns, inode, mask);
525         if (retval)
526                 return retval;
527
528         retval = devcgroup_inode_permission(inode, mask);
529         if (retval)
530                 return retval;
531
532         return security_inode_permission(inode, mask);
533 }
534 EXPORT_SYMBOL(inode_permission);
535
536 /**
537  * path_get - get a reference to a path
538  * @path: path to get the reference to
539  *
540  * Given a path increment the reference count to the dentry and the vfsmount.
541  */
542 void path_get(const struct path *path)
543 {
544         mntget(path->mnt);
545         dget(path->dentry);
546 }
547 EXPORT_SYMBOL(path_get);
548
549 /**
550  * path_put - put a reference to a path
551  * @path: path to put the reference to
552  *
553  * Given a path decrement the reference count to the dentry and the vfsmount.
554  */
555 void path_put(const struct path *path)
556 {
557         dput(path->dentry);
558         mntput(path->mnt);
559 }
560 EXPORT_SYMBOL(path_put);
561
562 #define EMBEDDED_LEVELS 2
563 struct nameidata {
564         struct path     path;
565         struct qstr     last;
566         struct path     root;
567         struct inode    *inode; /* path.dentry.d_inode */
568         unsigned int    flags, state;
569         unsigned        seq, m_seq, r_seq;
570         int             last_type;
571         unsigned        depth;
572         int             total_link_count;
573         struct saved {
574                 struct path link;
575                 struct delayed_call done;
576                 const char *name;
577                 unsigned seq;
578         } *stack, internal[EMBEDDED_LEVELS];
579         struct filename *name;
580         struct nameidata *saved;
581         unsigned        root_seq;
582         int             dfd;
583         kuid_t          dir_uid;
584         umode_t         dir_mode;
585 } __randomize_layout;
586
587 #define ND_ROOT_PRESET 1
588 #define ND_ROOT_GRABBED 2
589 #define ND_JUMPED 4
590
591 static void __set_nameidata(struct nameidata *p, int dfd, struct filename *name)
592 {
593         struct nameidata *old = current->nameidata;
594         p->stack = p->internal;
595         p->depth = 0;
596         p->dfd = dfd;
597         p->name = name;
598         p->path.mnt = NULL;
599         p->path.dentry = NULL;
600         p->total_link_count = old ? old->total_link_count : 0;
601         p->saved = old;
602         current->nameidata = p;
603 }
604
605 static inline void set_nameidata(struct nameidata *p, int dfd, struct filename *name,
606                           const struct path *root)
607 {
608         __set_nameidata(p, dfd, name);
609         p->state = 0;
610         if (unlikely(root)) {
611                 p->state = ND_ROOT_PRESET;
612                 p->root = *root;
613         }
614 }
615
616 static void restore_nameidata(void)
617 {
618         struct nameidata *now = current->nameidata, *old = now->saved;
619
620         current->nameidata = old;
621         if (old)
622                 old->total_link_count = now->total_link_count;
623         if (now->stack != now->internal)
624                 kfree(now->stack);
625 }
626
627 static bool nd_alloc_stack(struct nameidata *nd)
628 {
629         struct saved *p;
630
631         p= kmalloc_array(MAXSYMLINKS, sizeof(struct saved),
632                          nd->flags & LOOKUP_RCU ? GFP_ATOMIC : GFP_KERNEL);
633         if (unlikely(!p))
634                 return false;
635         memcpy(p, nd->internal, sizeof(nd->internal));
636         nd->stack = p;
637         return true;
638 }
639
640 /**
641  * path_connected - Verify that a dentry is below mnt.mnt_root
642  *
643  * Rename can sometimes move a file or directory outside of a bind
644  * mount, path_connected allows those cases to be detected.
645  */
646 static bool path_connected(struct vfsmount *mnt, struct dentry *dentry)
647 {
648         struct super_block *sb = mnt->mnt_sb;
649
650         /* Bind mounts can have disconnected paths */
651         if (mnt->mnt_root == sb->s_root)
652                 return true;
653
654         return is_subdir(dentry, mnt->mnt_root);
655 }
656
657 static void drop_links(struct nameidata *nd)
658 {
659         int i = nd->depth;
660         while (i--) {
661                 struct saved *last = nd->stack + i;
662                 do_delayed_call(&last->done);
663                 clear_delayed_call(&last->done);
664         }
665 }
666
667 static void terminate_walk(struct nameidata *nd)
668 {
669         drop_links(nd);
670         if (!(nd->flags & LOOKUP_RCU)) {
671                 int i;
672                 path_put(&nd->path);
673                 for (i = 0; i < nd->depth; i++)
674                         path_put(&nd->stack[i].link);
675                 if (nd->state & ND_ROOT_GRABBED) {
676                         path_put(&nd->root);
677                         nd->state &= ~ND_ROOT_GRABBED;
678                 }
679         } else {
680                 nd->flags &= ~LOOKUP_RCU;
681                 rcu_read_unlock();
682         }
683         nd->depth = 0;
684         nd->path.mnt = NULL;
685         nd->path.dentry = NULL;
686 }
687
688 /* path_put is needed afterwards regardless of success or failure */
689 static bool __legitimize_path(struct path *path, unsigned seq, unsigned mseq)
690 {
691         int res = __legitimize_mnt(path->mnt, mseq);
692         if (unlikely(res)) {
693                 if (res > 0)
694                         path->mnt = NULL;
695                 path->dentry = NULL;
696                 return false;
697         }
698         if (unlikely(!lockref_get_not_dead(&path->dentry->d_lockref))) {
699                 path->dentry = NULL;
700                 return false;
701         }
702         return !read_seqcount_retry(&path->dentry->d_seq, seq);
703 }
704
705 static inline bool legitimize_path(struct nameidata *nd,
706                             struct path *path, unsigned seq)
707 {
708         return __legitimize_path(path, seq, nd->m_seq);
709 }
710
711 static bool legitimize_links(struct nameidata *nd)
712 {
713         int i;
714         if (unlikely(nd->flags & LOOKUP_CACHED)) {
715                 drop_links(nd);
716                 nd->depth = 0;
717                 return false;
718         }
719         for (i = 0; i < nd->depth; i++) {
720                 struct saved *last = nd->stack + i;
721                 if (unlikely(!legitimize_path(nd, &last->link, last->seq))) {
722                         drop_links(nd);
723                         nd->depth = i + 1;
724                         return false;
725                 }
726         }
727         return true;
728 }
729
730 static bool legitimize_root(struct nameidata *nd)
731 {
732         /*
733          * For scoped-lookups (where nd->root has been zeroed), we need to
734          * restart the whole lookup from scratch -- because set_root() is wrong
735          * for these lookups (nd->dfd is the root, not the filesystem root).
736          */
737         if (!nd->root.mnt && (nd->flags & LOOKUP_IS_SCOPED))
738                 return false;
739         /* Nothing to do if nd->root is zero or is managed by the VFS user. */
740         if (!nd->root.mnt || (nd->state & ND_ROOT_PRESET))
741                 return true;
742         nd->state |= ND_ROOT_GRABBED;
743         return legitimize_path(nd, &nd->root, nd->root_seq);
744 }
745
746 /*
747  * Path walking has 2 modes, rcu-walk and ref-walk (see
748  * Documentation/filesystems/path-lookup.txt).  In situations when we can't
749  * continue in RCU mode, we attempt to drop out of rcu-walk mode and grab
750  * normal reference counts on dentries and vfsmounts to transition to ref-walk
751  * mode.  Refcounts are grabbed at the last known good point before rcu-walk
752  * got stuck, so ref-walk may continue from there. If this is not successful
753  * (eg. a seqcount has changed), then failure is returned and it's up to caller
754  * to restart the path walk from the beginning in ref-walk mode.
755  */
756
757 /**
758  * try_to_unlazy - try to switch to ref-walk mode.
759  * @nd: nameidata pathwalk data
760  * Returns: true on success, false on failure
761  *
762  * try_to_unlazy attempts to legitimize the current nd->path and nd->root
763  * for ref-walk mode.
764  * Must be called from rcu-walk context.
765  * Nothing should touch nameidata between try_to_unlazy() failure and
766  * terminate_walk().
767  */
768 static bool try_to_unlazy(struct nameidata *nd)
769 {
770         struct dentry *parent = nd->path.dentry;
771
772         BUG_ON(!(nd->flags & LOOKUP_RCU));
773
774         nd->flags &= ~LOOKUP_RCU;
775         if (unlikely(!legitimize_links(nd)))
776                 goto out1;
777         if (unlikely(!legitimize_path(nd, &nd->path, nd->seq)))
778                 goto out;
779         if (unlikely(!legitimize_root(nd)))
780                 goto out;
781         rcu_read_unlock();
782         BUG_ON(nd->inode != parent->d_inode);
783         return true;
784
785 out1:
786         nd->path.mnt = NULL;
787         nd->path.dentry = NULL;
788 out:
789         rcu_read_unlock();
790         return false;
791 }
792
793 /**
794  * try_to_unlazy_next - try to switch to ref-walk mode.
795  * @nd: nameidata pathwalk data
796  * @dentry: next dentry to step into
797  * @seq: seq number to check @dentry against
798  * Returns: true on success, false on failure
799  *
800  * Similar to to try_to_unlazy(), but here we have the next dentry already
801  * picked by rcu-walk and want to legitimize that in addition to the current
802  * nd->path and nd->root for ref-walk mode.  Must be called from rcu-walk context.
803  * Nothing should touch nameidata between try_to_unlazy_next() failure and
804  * terminate_walk().
805  */
806 static bool try_to_unlazy_next(struct nameidata *nd, struct dentry *dentry, unsigned seq)
807 {
808         BUG_ON(!(nd->flags & LOOKUP_RCU));
809
810         nd->flags &= ~LOOKUP_RCU;
811         if (unlikely(!legitimize_links(nd)))
812                 goto out2;
813         if (unlikely(!legitimize_mnt(nd->path.mnt, nd->m_seq)))
814                 goto out2;
815         if (unlikely(!lockref_get_not_dead(&nd->path.dentry->d_lockref)))
816                 goto out1;
817
818         /*
819          * We need to move both the parent and the dentry from the RCU domain
820          * to be properly refcounted. And the sequence number in the dentry
821          * validates *both* dentry counters, since we checked the sequence
822          * number of the parent after we got the child sequence number. So we
823          * know the parent must still be valid if the child sequence number is
824          */
825         if (unlikely(!lockref_get_not_dead(&dentry->d_lockref)))
826                 goto out;
827         if (unlikely(read_seqcount_retry(&dentry->d_seq, seq)))
828                 goto out_dput;
829         /*
830          * Sequence counts matched. Now make sure that the root is
831          * still valid and get it if required.
832          */
833         if (unlikely(!legitimize_root(nd)))
834                 goto out_dput;
835         rcu_read_unlock();
836         return true;
837
838 out2:
839         nd->path.mnt = NULL;
840 out1:
841         nd->path.dentry = NULL;
842 out:
843         rcu_read_unlock();
844         return false;
845 out_dput:
846         rcu_read_unlock();
847         dput(dentry);
848         return false;
849 }
850
851 static inline int d_revalidate(struct dentry *dentry, unsigned int flags)
852 {
853         if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE))
854                 return dentry->d_op->d_revalidate(dentry, flags);
855         else
856                 return 1;
857 }
858
859 /**
860  * complete_walk - successful completion of path walk
861  * @nd:  pointer nameidata
862  *
863  * If we had been in RCU mode, drop out of it and legitimize nd->path.
864  * Revalidate the final result, unless we'd already done that during
865  * the path walk or the filesystem doesn't ask for it.  Return 0 on
866  * success, -error on failure.  In case of failure caller does not
867  * need to drop nd->path.
868  */
869 static int complete_walk(struct nameidata *nd)
870 {
871         struct dentry *dentry = nd->path.dentry;
872         int status;
873
874         if (nd->flags & LOOKUP_RCU) {
875                 /*
876                  * We don't want to zero nd->root for scoped-lookups or
877                  * externally-managed nd->root.
878                  */
879                 if (!(nd->state & ND_ROOT_PRESET))
880                         if (!(nd->flags & LOOKUP_IS_SCOPED))
881                                 nd->root.mnt = NULL;
882                 nd->flags &= ~LOOKUP_CACHED;
883                 if (!try_to_unlazy(nd))
884                         return -ECHILD;
885         }
886
887         if (unlikely(nd->flags & LOOKUP_IS_SCOPED)) {
888                 /*
889                  * While the guarantee of LOOKUP_IS_SCOPED is (roughly) "don't
890                  * ever step outside the root during lookup" and should already
891                  * be guaranteed by the rest of namei, we want to avoid a namei
892                  * BUG resulting in userspace being given a path that was not
893                  * scoped within the root at some point during the lookup.
894                  *
895                  * So, do a final sanity-check to make sure that in the
896                  * worst-case scenario (a complete bypass of LOOKUP_IS_SCOPED)
897                  * we won't silently return an fd completely outside of the
898                  * requested root to userspace.
899                  *
900                  * Userspace could move the path outside the root after this
901                  * check, but as discussed elsewhere this is not a concern (the
902                  * resolved file was inside the root at some point).
903                  */
904                 if (!path_is_under(&nd->path, &nd->root))
905                         return -EXDEV;
906         }
907
908         if (likely(!(nd->state & ND_JUMPED)))
909                 return 0;
910
911         if (likely(!(dentry->d_flags & DCACHE_OP_WEAK_REVALIDATE)))
912                 return 0;
913
914         status = dentry->d_op->d_weak_revalidate(dentry, nd->flags);
915         if (status > 0)
916                 return 0;
917
918         if (!status)
919                 status = -ESTALE;
920
921         return status;
922 }
923
924 static int set_root(struct nameidata *nd)
925 {
926         struct fs_struct *fs = current->fs;
927
928         /*
929          * Jumping to the real root in a scoped-lookup is a BUG in namei, but we
930          * still have to ensure it doesn't happen because it will cause a breakout
931          * from the dirfd.
932          */
933         if (WARN_ON(nd->flags & LOOKUP_IS_SCOPED))
934                 return -ENOTRECOVERABLE;
935
936         if (nd->flags & LOOKUP_RCU) {
937                 unsigned seq;
938
939                 do {
940                         seq = read_seqcount_begin(&fs->seq);
941                         nd->root = fs->root;
942                         nd->root_seq = __read_seqcount_begin(&nd->root.dentry->d_seq);
943                 } while (read_seqcount_retry(&fs->seq, seq));
944         } else {
945                 get_fs_root(fs, &nd->root);
946                 nd->state |= ND_ROOT_GRABBED;
947         }
948         return 0;
949 }
950
951 static int nd_jump_root(struct nameidata *nd)
952 {
953         if (unlikely(nd->flags & LOOKUP_BENEATH))
954                 return -EXDEV;
955         if (unlikely(nd->flags & LOOKUP_NO_XDEV)) {
956                 /* Absolute path arguments to path_init() are allowed. */
957                 if (nd->path.mnt != NULL && nd->path.mnt != nd->root.mnt)
958                         return -EXDEV;
959         }
960         if (!nd->root.mnt) {
961                 int error = set_root(nd);
962                 if (error)
963                         return error;
964         }
965         if (nd->flags & LOOKUP_RCU) {
966                 struct dentry *d;
967                 nd->path = nd->root;
968                 d = nd->path.dentry;
969                 nd->inode = d->d_inode;
970                 nd->seq = nd->root_seq;
971                 if (unlikely(read_seqcount_retry(&d->d_seq, nd->seq)))
972                         return -ECHILD;
973         } else {
974                 path_put(&nd->path);
975                 nd->path = nd->root;
976                 path_get(&nd->path);
977                 nd->inode = nd->path.dentry->d_inode;
978         }
979         nd->state |= ND_JUMPED;
980         return 0;
981 }
982
983 /*
984  * Helper to directly jump to a known parsed path from ->get_link,
985  * caller must have taken a reference to path beforehand.
986  */
987 int nd_jump_link(struct path *path)
988 {
989         int error = -ELOOP;
990         struct nameidata *nd = current->nameidata;
991
992         if (unlikely(nd->flags & LOOKUP_NO_MAGICLINKS))
993                 goto err;
994
995         error = -EXDEV;
996         if (unlikely(nd->flags & LOOKUP_NO_XDEV)) {
997                 if (nd->path.mnt != path->mnt)
998                         goto err;
999         }
1000         /* Not currently safe for scoped-lookups. */
1001         if (unlikely(nd->flags & LOOKUP_IS_SCOPED))
1002                 goto err;
1003
1004         path_put(&nd->path);
1005         nd->path = *path;
1006         nd->inode = nd->path.dentry->d_inode;
1007         nd->state |= ND_JUMPED;
1008         return 0;
1009
1010 err:
1011         path_put(path);
1012         return error;
1013 }
1014
1015 static inline void put_link(struct nameidata *nd)
1016 {
1017         struct saved *last = nd->stack + --nd->depth;
1018         do_delayed_call(&last->done);
1019         if (!(nd->flags & LOOKUP_RCU))
1020                 path_put(&last->link);
1021 }
1022
1023 int sysctl_protected_symlinks __read_mostly = 0;
1024 int sysctl_protected_hardlinks __read_mostly = 0;
1025 int sysctl_protected_fifos __read_mostly;
1026 int sysctl_protected_regular __read_mostly;
1027
1028 /**
1029  * may_follow_link - Check symlink following for unsafe situations
1030  * @nd: nameidata pathwalk data
1031  *
1032  * In the case of the sysctl_protected_symlinks sysctl being enabled,
1033  * CAP_DAC_OVERRIDE needs to be specifically ignored if the symlink is
1034  * in a sticky world-writable directory. This is to protect privileged
1035  * processes from failing races against path names that may change out
1036  * from under them by way of other users creating malicious symlinks.
1037  * It will permit symlinks to be followed only when outside a sticky
1038  * world-writable directory, or when the uid of the symlink and follower
1039  * match, or when the directory owner matches the symlink's owner.
1040  *
1041  * Returns 0 if following the symlink is allowed, -ve on error.
1042  */
1043 static inline int may_follow_link(struct nameidata *nd, const struct inode *inode)
1044 {
1045         struct user_namespace *mnt_userns;
1046         kuid_t i_uid;
1047
1048         if (!sysctl_protected_symlinks)
1049                 return 0;
1050
1051         mnt_userns = mnt_user_ns(nd->path.mnt);
1052         i_uid = i_uid_into_mnt(mnt_userns, inode);
1053         /* Allowed if owner and follower match. */
1054         if (uid_eq(current_cred()->fsuid, i_uid))
1055                 return 0;
1056
1057         /* Allowed if parent directory not sticky and world-writable. */
1058         if ((nd->dir_mode & (S_ISVTX|S_IWOTH)) != (S_ISVTX|S_IWOTH))
1059                 return 0;
1060
1061         /* Allowed if parent directory and link owner match. */
1062         if (uid_valid(nd->dir_uid) && uid_eq(nd->dir_uid, i_uid))
1063                 return 0;
1064
1065         if (nd->flags & LOOKUP_RCU)
1066                 return -ECHILD;
1067
1068         audit_inode(nd->name, nd->stack[0].link.dentry, 0);
1069         audit_log_path_denied(AUDIT_ANOM_LINK, "follow_link");
1070         return -EACCES;
1071 }
1072
1073 /**
1074  * safe_hardlink_source - Check for safe hardlink conditions
1075  * @mnt_userns: user namespace of the mount the inode was found from
1076  * @inode: the source inode to hardlink from
1077  *
1078  * Return false if at least one of the following conditions:
1079  *    - inode is not a regular file
1080  *    - inode is setuid
1081  *    - inode is setgid and group-exec
1082  *    - access failure for read and write
1083  *
1084  * Otherwise returns true.
1085  */
1086 static bool safe_hardlink_source(struct user_namespace *mnt_userns,
1087                                  struct inode *inode)
1088 {
1089         umode_t mode = inode->i_mode;
1090
1091         /* Special files should not get pinned to the filesystem. */
1092         if (!S_ISREG(mode))
1093                 return false;
1094
1095         /* Setuid files should not get pinned to the filesystem. */
1096         if (mode & S_ISUID)
1097                 return false;
1098
1099         /* Executable setgid files should not get pinned to the filesystem. */
1100         if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP))
1101                 return false;
1102
1103         /* Hardlinking to unreadable or unwritable sources is dangerous. */
1104         if (inode_permission(mnt_userns, inode, MAY_READ | MAY_WRITE))
1105                 return false;
1106
1107         return true;
1108 }
1109
1110 /**
1111  * may_linkat - Check permissions for creating a hardlink
1112  * @mnt_userns: user namespace of the mount the inode was found from
1113  * @link: the source to hardlink from
1114  *
1115  * Block hardlink when all of:
1116  *  - sysctl_protected_hardlinks enabled
1117  *  - fsuid does not match inode
1118  *  - hardlink source is unsafe (see safe_hardlink_source() above)
1119  *  - not CAP_FOWNER in a namespace with the inode owner uid mapped
1120  *
1121  * If the inode has been found through an idmapped mount the user namespace of
1122  * the vfsmount must be passed through @mnt_userns. This function will then take
1123  * care to map the inode according to @mnt_userns before checking permissions.
1124  * On non-idmapped mounts or if permission checking is to be performed on the
1125  * raw inode simply passs init_user_ns.
1126  *
1127  * Returns 0 if successful, -ve on error.
1128  */
1129 int may_linkat(struct user_namespace *mnt_userns, struct path *link)
1130 {
1131         struct inode *inode = link->dentry->d_inode;
1132
1133         /* Inode writeback is not safe when the uid or gid are invalid. */
1134         if (!uid_valid(i_uid_into_mnt(mnt_userns, inode)) ||
1135             !gid_valid(i_gid_into_mnt(mnt_userns, inode)))
1136                 return -EOVERFLOW;
1137
1138         if (!sysctl_protected_hardlinks)
1139                 return 0;
1140
1141         /* Source inode owner (or CAP_FOWNER) can hardlink all they like,
1142          * otherwise, it must be a safe source.
1143          */
1144         if (safe_hardlink_source(mnt_userns, inode) ||
1145             inode_owner_or_capable(mnt_userns, inode))
1146                 return 0;
1147
1148         audit_log_path_denied(AUDIT_ANOM_LINK, "linkat");
1149         return -EPERM;
1150 }
1151
1152 /**
1153  * may_create_in_sticky - Check whether an O_CREAT open in a sticky directory
1154  *                        should be allowed, or not, on files that already
1155  *                        exist.
1156  * @mnt_userns: user namespace of the mount the inode was found from
1157  * @nd: nameidata pathwalk data
1158  * @inode: the inode of the file to open
1159  *
1160  * Block an O_CREAT open of a FIFO (or a regular file) when:
1161  *   - sysctl_protected_fifos (or sysctl_protected_regular) is enabled
1162  *   - the file already exists
1163  *   - we are in a sticky directory
1164  *   - we don't own the file
1165  *   - the owner of the directory doesn't own the file
1166  *   - the directory is world writable
1167  * If the sysctl_protected_fifos (or sysctl_protected_regular) is set to 2
1168  * the directory doesn't have to be world writable: being group writable will
1169  * be enough.
1170  *
1171  * If the inode has been found through an idmapped mount the user namespace of
1172  * the vfsmount must be passed through @mnt_userns. This function will then take
1173  * care to map the inode according to @mnt_userns before checking permissions.
1174  * On non-idmapped mounts or if permission checking is to be performed on the
1175  * raw inode simply passs init_user_ns.
1176  *
1177  * Returns 0 if the open is allowed, -ve on error.
1178  */
1179 static int may_create_in_sticky(struct user_namespace *mnt_userns,
1180                                 struct nameidata *nd, struct inode *const inode)
1181 {
1182         umode_t dir_mode = nd->dir_mode;
1183         kuid_t dir_uid = nd->dir_uid;
1184
1185         if ((!sysctl_protected_fifos && S_ISFIFO(inode->i_mode)) ||
1186             (!sysctl_protected_regular && S_ISREG(inode->i_mode)) ||
1187             likely(!(dir_mode & S_ISVTX)) ||
1188             uid_eq(i_uid_into_mnt(mnt_userns, inode), dir_uid) ||
1189             uid_eq(current_fsuid(), i_uid_into_mnt(mnt_userns, inode)))
1190                 return 0;
1191
1192         if (likely(dir_mode & 0002) ||
1193             (dir_mode & 0020 &&
1194              ((sysctl_protected_fifos >= 2 && S_ISFIFO(inode->i_mode)) ||
1195               (sysctl_protected_regular >= 2 && S_ISREG(inode->i_mode))))) {
1196                 const char *operation = S_ISFIFO(inode->i_mode) ?
1197                                         "sticky_create_fifo" :
1198                                         "sticky_create_regular";
1199                 audit_log_path_denied(AUDIT_ANOM_CREAT, operation);
1200                 return -EACCES;
1201         }
1202         return 0;
1203 }
1204
1205 /*
1206  * follow_up - Find the mountpoint of path's vfsmount
1207  *
1208  * Given a path, find the mountpoint of its source file system.
1209  * Replace @path with the path of the mountpoint in the parent mount.
1210  * Up is towards /.
1211  *
1212  * Return 1 if we went up a level and 0 if we were already at the
1213  * root.
1214  */
1215 int follow_up(struct path *path)
1216 {
1217         struct mount *mnt = real_mount(path->mnt);
1218         struct mount *parent;
1219         struct dentry *mountpoint;
1220
1221         read_seqlock_excl(&mount_lock);
1222         parent = mnt->mnt_parent;
1223         if (parent == mnt) {
1224                 read_sequnlock_excl(&mount_lock);
1225                 return 0;
1226         }
1227         mntget(&parent->mnt);
1228         mountpoint = dget(mnt->mnt_mountpoint);
1229         read_sequnlock_excl(&mount_lock);
1230         dput(path->dentry);
1231         path->dentry = mountpoint;
1232         mntput(path->mnt);
1233         path->mnt = &parent->mnt;
1234         return 1;
1235 }
1236 EXPORT_SYMBOL(follow_up);
1237
1238 static bool choose_mountpoint_rcu(struct mount *m, const struct path *root,
1239                                   struct path *path, unsigned *seqp)
1240 {
1241         while (mnt_has_parent(m)) {
1242                 struct dentry *mountpoint = m->mnt_mountpoint;
1243
1244                 m = m->mnt_parent;
1245                 if (unlikely(root->dentry == mountpoint &&
1246                              root->mnt == &m->mnt))
1247                         break;
1248                 if (mountpoint != m->mnt.mnt_root) {
1249                         path->mnt = &m->mnt;
1250                         path->dentry = mountpoint;
1251                         *seqp = read_seqcount_begin(&mountpoint->d_seq);
1252                         return true;
1253                 }
1254         }
1255         return false;
1256 }
1257
1258 static bool choose_mountpoint(struct mount *m, const struct path *root,
1259                               struct path *path)
1260 {
1261         bool found;
1262
1263         rcu_read_lock();
1264         while (1) {
1265                 unsigned seq, mseq = read_seqbegin(&mount_lock);
1266
1267                 found = choose_mountpoint_rcu(m, root, path, &seq);
1268                 if (unlikely(!found)) {
1269                         if (!read_seqretry(&mount_lock, mseq))
1270                                 break;
1271                 } else {
1272                         if (likely(__legitimize_path(path, seq, mseq)))
1273                                 break;
1274                         rcu_read_unlock();
1275                         path_put(path);
1276                         rcu_read_lock();
1277                 }
1278         }
1279         rcu_read_unlock();
1280         return found;
1281 }
1282
1283 /*
1284  * Perform an automount
1285  * - return -EISDIR to tell follow_managed() to stop and return the path we
1286  *   were called with.
1287  */
1288 static int follow_automount(struct path *path, int *count, unsigned lookup_flags)
1289 {
1290         struct dentry *dentry = path->dentry;
1291
1292         /* We don't want to mount if someone's just doing a stat -
1293          * unless they're stat'ing a directory and appended a '/' to
1294          * the name.
1295          *
1296          * We do, however, want to mount if someone wants to open or
1297          * create a file of any type under the mountpoint, wants to
1298          * traverse through the mountpoint or wants to open the
1299          * mounted directory.  Also, autofs may mark negative dentries
1300          * as being automount points.  These will need the attentions
1301          * of the daemon to instantiate them before they can be used.
1302          */
1303         if (!(lookup_flags & (LOOKUP_PARENT | LOOKUP_DIRECTORY |
1304                            LOOKUP_OPEN | LOOKUP_CREATE | LOOKUP_AUTOMOUNT)) &&
1305             dentry->d_inode)
1306                 return -EISDIR;
1307
1308         if (count && (*count)++ >= MAXSYMLINKS)
1309                 return -ELOOP;
1310
1311         return finish_automount(dentry->d_op->d_automount(path), path);
1312 }
1313
1314 /*
1315  * mount traversal - out-of-line part.  One note on ->d_flags accesses -
1316  * dentries are pinned but not locked here, so negative dentry can go
1317  * positive right under us.  Use of smp_load_acquire() provides a barrier
1318  * sufficient for ->d_inode and ->d_flags consistency.
1319  */
1320 static int __traverse_mounts(struct path *path, unsigned flags, bool *jumped,
1321                              int *count, unsigned lookup_flags)
1322 {
1323         struct vfsmount *mnt = path->mnt;
1324         bool need_mntput = false;
1325         int ret = 0;
1326
1327         while (flags & DCACHE_MANAGED_DENTRY) {
1328                 /* Allow the filesystem to manage the transit without i_mutex
1329                  * being held. */
1330                 if (flags & DCACHE_MANAGE_TRANSIT) {
1331                         ret = path->dentry->d_op->d_manage(path, false);
1332                         flags = smp_load_acquire(&path->dentry->d_flags);
1333                         if (ret < 0)
1334                                 break;
1335                 }
1336
1337                 if (flags & DCACHE_MOUNTED) {   // something's mounted on it..
1338                         struct vfsmount *mounted = lookup_mnt(path);
1339                         if (mounted) {          // ... in our namespace
1340                                 dput(path->dentry);
1341                                 if (need_mntput)
1342                                         mntput(path->mnt);
1343                                 path->mnt = mounted;
1344                                 path->dentry = dget(mounted->mnt_root);
1345                                 // here we know it's positive
1346                                 flags = path->dentry->d_flags;
1347                                 need_mntput = true;
1348                                 continue;
1349                         }
1350                 }
1351
1352                 if (!(flags & DCACHE_NEED_AUTOMOUNT))
1353                         break;
1354
1355                 // uncovered automount point
1356                 ret = follow_automount(path, count, lookup_flags);
1357                 flags = smp_load_acquire(&path->dentry->d_flags);
1358                 if (ret < 0)
1359                         break;
1360         }
1361
1362         if (ret == -EISDIR)
1363                 ret = 0;
1364         // possible if you race with several mount --move
1365         if (need_mntput && path->mnt == mnt)
1366                 mntput(path->mnt);
1367         if (!ret && unlikely(d_flags_negative(flags)))
1368                 ret = -ENOENT;
1369         *jumped = need_mntput;
1370         return ret;
1371 }
1372
1373 static inline int traverse_mounts(struct path *path, bool *jumped,
1374                                   int *count, unsigned lookup_flags)
1375 {
1376         unsigned flags = smp_load_acquire(&path->dentry->d_flags);
1377
1378         /* fastpath */
1379         if (likely(!(flags & DCACHE_MANAGED_DENTRY))) {
1380                 *jumped = false;
1381                 if (unlikely(d_flags_negative(flags)))
1382                         return -ENOENT;
1383                 return 0;
1384         }
1385         return __traverse_mounts(path, flags, jumped, count, lookup_flags);
1386 }
1387
1388 int follow_down_one(struct path *path)
1389 {
1390         struct vfsmount *mounted;
1391
1392         mounted = lookup_mnt(path);
1393         if (mounted) {
1394                 dput(path->dentry);
1395                 mntput(path->mnt);
1396                 path->mnt = mounted;
1397                 path->dentry = dget(mounted->mnt_root);
1398                 return 1;
1399         }
1400         return 0;
1401 }
1402 EXPORT_SYMBOL(follow_down_one);
1403
1404 /*
1405  * Follow down to the covering mount currently visible to userspace.  At each
1406  * point, the filesystem owning that dentry may be queried as to whether the
1407  * caller is permitted to proceed or not.
1408  */
1409 int follow_down(struct path *path)
1410 {
1411         struct vfsmount *mnt = path->mnt;
1412         bool jumped;
1413         int ret = traverse_mounts(path, &jumped, NULL, 0);
1414
1415         if (path->mnt != mnt)
1416                 mntput(mnt);
1417         return ret;
1418 }
1419 EXPORT_SYMBOL(follow_down);
1420
1421 /*
1422  * Try to skip to top of mountpoint pile in rcuwalk mode.  Fail if
1423  * we meet a managed dentry that would need blocking.
1424  */
1425 static bool __follow_mount_rcu(struct nameidata *nd, struct path *path,
1426                                struct inode **inode, unsigned *seqp)
1427 {
1428         struct dentry *dentry = path->dentry;
1429         unsigned int flags = dentry->d_flags;
1430
1431         if (likely(!(flags & DCACHE_MANAGED_DENTRY)))
1432                 return true;
1433
1434         if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1435                 return false;
1436
1437         for (;;) {
1438                 /*
1439                  * Don't forget we might have a non-mountpoint managed dentry
1440                  * that wants to block transit.
1441                  */
1442                 if (unlikely(flags & DCACHE_MANAGE_TRANSIT)) {
1443                         int res = dentry->d_op->d_manage(path, true);
1444                         if (res)
1445                                 return res == -EISDIR;
1446                         flags = dentry->d_flags;
1447                 }
1448
1449                 if (flags & DCACHE_MOUNTED) {
1450                         struct mount *mounted = __lookup_mnt(path->mnt, dentry);
1451                         if (mounted) {
1452                                 path->mnt = &mounted->mnt;
1453                                 dentry = path->dentry = mounted->mnt.mnt_root;
1454                                 nd->state |= ND_JUMPED;
1455                                 *seqp = read_seqcount_begin(&dentry->d_seq);
1456                                 *inode = dentry->d_inode;
1457                                 /*
1458                                  * We don't need to re-check ->d_seq after this
1459                                  * ->d_inode read - there will be an RCU delay
1460                                  * between mount hash removal and ->mnt_root
1461                                  * becoming unpinned.
1462                                  */
1463                                 flags = dentry->d_flags;
1464                                 if (read_seqretry(&mount_lock, nd->m_seq))
1465                                         return false;
1466                                 continue;
1467                         }
1468                         if (read_seqretry(&mount_lock, nd->m_seq))
1469                                 return false;
1470                 }
1471                 return !(flags & DCACHE_NEED_AUTOMOUNT);
1472         }
1473 }
1474
1475 static inline int handle_mounts(struct nameidata *nd, struct dentry *dentry,
1476                           struct path *path, struct inode **inode,
1477                           unsigned int *seqp)
1478 {
1479         bool jumped;
1480         int ret;
1481
1482         path->mnt = nd->path.mnt;
1483         path->dentry = dentry;
1484         if (nd->flags & LOOKUP_RCU) {
1485                 unsigned int seq = *seqp;
1486                 if (unlikely(!*inode))
1487                         return -ENOENT;
1488                 if (likely(__follow_mount_rcu(nd, path, inode, seqp)))
1489                         return 0;
1490                 if (!try_to_unlazy_next(nd, dentry, seq))
1491                         return -ECHILD;
1492                 // *path might've been clobbered by __follow_mount_rcu()
1493                 path->mnt = nd->path.mnt;
1494                 path->dentry = dentry;
1495         }
1496         ret = traverse_mounts(path, &jumped, &nd->total_link_count, nd->flags);
1497         if (jumped) {
1498                 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1499                         ret = -EXDEV;
1500                 else
1501                         nd->state |= ND_JUMPED;
1502         }
1503         if (unlikely(ret)) {
1504                 dput(path->dentry);
1505                 if (path->mnt != nd->path.mnt)
1506                         mntput(path->mnt);
1507         } else {
1508                 *inode = d_backing_inode(path->dentry);
1509                 *seqp = 0; /* out of RCU mode, so the value doesn't matter */
1510         }
1511         return ret;
1512 }
1513
1514 /*
1515  * This looks up the name in dcache and possibly revalidates the found dentry.
1516  * NULL is returned if the dentry does not exist in the cache.
1517  */
1518 static struct dentry *lookup_dcache(const struct qstr *name,
1519                                     struct dentry *dir,
1520                                     unsigned int flags)
1521 {
1522         struct dentry *dentry = d_lookup(dir, name);
1523         if (dentry) {
1524                 int error = d_revalidate(dentry, flags);
1525                 if (unlikely(error <= 0)) {
1526                         if (!error)
1527                                 d_invalidate(dentry);
1528                         dput(dentry);
1529                         return ERR_PTR(error);
1530                 }
1531         }
1532         return dentry;
1533 }
1534
1535 /*
1536  * Parent directory has inode locked exclusive.  This is one
1537  * and only case when ->lookup() gets called on non in-lookup
1538  * dentries - as the matter of fact, this only gets called
1539  * when directory is guaranteed to have no in-lookup children
1540  * at all.
1541  */
1542 static struct dentry *__lookup_hash(const struct qstr *name,
1543                 struct dentry *base, unsigned int flags)
1544 {
1545         struct dentry *dentry = lookup_dcache(name, base, flags);
1546         struct dentry *old;
1547         struct inode *dir = base->d_inode;
1548
1549         if (dentry)
1550                 return dentry;
1551
1552         /* Don't create child dentry for a dead directory. */
1553         if (unlikely(IS_DEADDIR(dir)))
1554                 return ERR_PTR(-ENOENT);
1555
1556         dentry = d_alloc(base, name);
1557         if (unlikely(!dentry))
1558                 return ERR_PTR(-ENOMEM);
1559
1560         old = dir->i_op->lookup(dir, dentry, flags);
1561         if (unlikely(old)) {
1562                 dput(dentry);
1563                 dentry = old;
1564         }
1565         return dentry;
1566 }
1567
1568 static struct dentry *lookup_fast(struct nameidata *nd,
1569                                   struct inode **inode,
1570                                   unsigned *seqp)
1571 {
1572         struct dentry *dentry, *parent = nd->path.dentry;
1573         int status = 1;
1574
1575         /*
1576          * Rename seqlock is not required here because in the off chance
1577          * of a false negative due to a concurrent rename, the caller is
1578          * going to fall back to non-racy lookup.
1579          */
1580         if (nd->flags & LOOKUP_RCU) {
1581                 unsigned seq;
1582                 dentry = __d_lookup_rcu(parent, &nd->last, &seq);
1583                 if (unlikely(!dentry)) {
1584                         if (!try_to_unlazy(nd))
1585                                 return ERR_PTR(-ECHILD);
1586                         return NULL;
1587                 }
1588
1589                 /*
1590                  * This sequence count validates that the inode matches
1591                  * the dentry name information from lookup.
1592                  */
1593                 *inode = d_backing_inode(dentry);
1594                 if (unlikely(read_seqcount_retry(&dentry->d_seq, seq)))
1595                         return ERR_PTR(-ECHILD);
1596
1597                 /*
1598                  * This sequence count validates that the parent had no
1599                  * changes while we did the lookup of the dentry above.
1600                  *
1601                  * The memory barrier in read_seqcount_begin of child is
1602                  *  enough, we can use __read_seqcount_retry here.
1603                  */
1604                 if (unlikely(__read_seqcount_retry(&parent->d_seq, nd->seq)))
1605                         return ERR_PTR(-ECHILD);
1606
1607                 *seqp = seq;
1608                 status = d_revalidate(dentry, nd->flags);
1609                 if (likely(status > 0))
1610                         return dentry;
1611                 if (!try_to_unlazy_next(nd, dentry, seq))
1612                         return ERR_PTR(-ECHILD);
1613                 if (status == -ECHILD)
1614                         /* we'd been told to redo it in non-rcu mode */
1615                         status = d_revalidate(dentry, nd->flags);
1616         } else {
1617                 dentry = __d_lookup(parent, &nd->last);
1618                 if (unlikely(!dentry))
1619                         return NULL;
1620                 status = d_revalidate(dentry, nd->flags);
1621         }
1622         if (unlikely(status <= 0)) {
1623                 if (!status)
1624                         d_invalidate(dentry);
1625                 dput(dentry);
1626                 return ERR_PTR(status);
1627         }
1628         return dentry;
1629 }
1630
1631 /* Fast lookup failed, do it the slow way */
1632 static struct dentry *__lookup_slow(const struct qstr *name,
1633                                     struct dentry *dir,
1634                                     unsigned int flags)
1635 {
1636         struct dentry *dentry, *old;
1637         struct inode *inode = dir->d_inode;
1638         DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
1639
1640         /* Don't go there if it's already dead */
1641         if (unlikely(IS_DEADDIR(inode)))
1642                 return ERR_PTR(-ENOENT);
1643 again:
1644         dentry = d_alloc_parallel(dir, name, &wq);
1645         if (IS_ERR(dentry))
1646                 return dentry;
1647         if (unlikely(!d_in_lookup(dentry))) {
1648                 int error = d_revalidate(dentry, flags);
1649                 if (unlikely(error <= 0)) {
1650                         if (!error) {
1651                                 d_invalidate(dentry);
1652                                 dput(dentry);
1653                                 goto again;
1654                         }
1655                         dput(dentry);
1656                         dentry = ERR_PTR(error);
1657                 }
1658         } else {
1659                 old = inode->i_op->lookup(inode, dentry, flags);
1660                 d_lookup_done(dentry);
1661                 if (unlikely(old)) {
1662                         dput(dentry);
1663                         dentry = old;
1664                 }
1665         }
1666         return dentry;
1667 }
1668
1669 static struct dentry *lookup_slow(const struct qstr *name,
1670                                   struct dentry *dir,
1671                                   unsigned int flags)
1672 {
1673         struct inode *inode = dir->d_inode;
1674         struct dentry *res;
1675         inode_lock_shared(inode);
1676         res = __lookup_slow(name, dir, flags);
1677         inode_unlock_shared(inode);
1678         return res;
1679 }
1680
1681 static inline int may_lookup(struct user_namespace *mnt_userns,
1682                              struct nameidata *nd)
1683 {
1684         if (nd->flags & LOOKUP_RCU) {
1685                 int err = inode_permission(mnt_userns, nd->inode, MAY_EXEC|MAY_NOT_BLOCK);
1686                 if (err != -ECHILD || !try_to_unlazy(nd))
1687                         return err;
1688         }
1689         return inode_permission(mnt_userns, nd->inode, MAY_EXEC);
1690 }
1691
1692 static int reserve_stack(struct nameidata *nd, struct path *link, unsigned seq)
1693 {
1694         if (unlikely(nd->total_link_count++ >= MAXSYMLINKS))
1695                 return -ELOOP;
1696
1697         if (likely(nd->depth != EMBEDDED_LEVELS))
1698                 return 0;
1699         if (likely(nd->stack != nd->internal))
1700                 return 0;
1701         if (likely(nd_alloc_stack(nd)))
1702                 return 0;
1703
1704         if (nd->flags & LOOKUP_RCU) {
1705                 // we need to grab link before we do unlazy.  And we can't skip
1706                 // unlazy even if we fail to grab the link - cleanup needs it
1707                 bool grabbed_link = legitimize_path(nd, link, seq);
1708
1709                 if (!try_to_unlazy(nd) != 0 || !grabbed_link)
1710                         return -ECHILD;
1711
1712                 if (nd_alloc_stack(nd))
1713                         return 0;
1714         }
1715         return -ENOMEM;
1716 }
1717
1718 enum {WALK_TRAILING = 1, WALK_MORE = 2, WALK_NOFOLLOW = 4};
1719
1720 static const char *pick_link(struct nameidata *nd, struct path *link,
1721                      struct inode *inode, unsigned seq, int flags)
1722 {
1723         struct saved *last;
1724         const char *res;
1725         int error = reserve_stack(nd, link, seq);
1726
1727         if (unlikely(error)) {
1728                 if (!(nd->flags & LOOKUP_RCU))
1729                         path_put(link);
1730                 return ERR_PTR(error);
1731         }
1732         last = nd->stack + nd->depth++;
1733         last->link = *link;
1734         clear_delayed_call(&last->done);
1735         last->seq = seq;
1736
1737         if (flags & WALK_TRAILING) {
1738                 error = may_follow_link(nd, inode);
1739                 if (unlikely(error))
1740                         return ERR_PTR(error);
1741         }
1742
1743         if (unlikely(nd->flags & LOOKUP_NO_SYMLINKS) ||
1744                         unlikely(link->mnt->mnt_flags & MNT_NOSYMFOLLOW))
1745                 return ERR_PTR(-ELOOP);
1746
1747         if (!(nd->flags & LOOKUP_RCU)) {
1748                 touch_atime(&last->link);
1749                 cond_resched();
1750         } else if (atime_needs_update(&last->link, inode)) {
1751                 if (!try_to_unlazy(nd))
1752                         return ERR_PTR(-ECHILD);
1753                 touch_atime(&last->link);
1754         }
1755
1756         error = security_inode_follow_link(link->dentry, inode,
1757                                            nd->flags & LOOKUP_RCU);
1758         if (unlikely(error))
1759                 return ERR_PTR(error);
1760
1761         res = READ_ONCE(inode->i_link);
1762         if (!res) {
1763                 const char * (*get)(struct dentry *, struct inode *,
1764                                 struct delayed_call *);
1765                 get = inode->i_op->get_link;
1766                 if (nd->flags & LOOKUP_RCU) {
1767                         res = get(NULL, inode, &last->done);
1768                         if (res == ERR_PTR(-ECHILD) && try_to_unlazy(nd))
1769                                 res = get(link->dentry, inode, &last->done);
1770                 } else {
1771                         res = get(link->dentry, inode, &last->done);
1772                 }
1773                 if (!res)
1774                         goto all_done;
1775                 if (IS_ERR(res))
1776                         return res;
1777         }
1778         if (*res == '/') {
1779                 error = nd_jump_root(nd);
1780                 if (unlikely(error))
1781                         return ERR_PTR(error);
1782                 while (unlikely(*++res == '/'))
1783                         ;
1784         }
1785         if (*res)
1786                 return res;
1787 all_done: // pure jump
1788         put_link(nd);
1789         return NULL;
1790 }
1791
1792 /*
1793  * Do we need to follow links? We _really_ want to be able
1794  * to do this check without having to look at inode->i_op,
1795  * so we keep a cache of "no, this doesn't need follow_link"
1796  * for the common case.
1797  */
1798 static const char *step_into(struct nameidata *nd, int flags,
1799                      struct dentry *dentry, struct inode *inode, unsigned seq)
1800 {
1801         struct path path;
1802         int err = handle_mounts(nd, dentry, &path, &inode, &seq);
1803
1804         if (err < 0)
1805                 return ERR_PTR(err);
1806         if (likely(!d_is_symlink(path.dentry)) ||
1807            ((flags & WALK_TRAILING) && !(nd->flags & LOOKUP_FOLLOW)) ||
1808            (flags & WALK_NOFOLLOW)) {
1809                 /* not a symlink or should not follow */
1810                 if (!(nd->flags & LOOKUP_RCU)) {
1811                         dput(nd->path.dentry);
1812                         if (nd->path.mnt != path.mnt)
1813                                 mntput(nd->path.mnt);
1814                 }
1815                 nd->path = path;
1816                 nd->inode = inode;
1817                 nd->seq = seq;
1818                 return NULL;
1819         }
1820         if (nd->flags & LOOKUP_RCU) {
1821                 /* make sure that d_is_symlink above matches inode */
1822                 if (read_seqcount_retry(&path.dentry->d_seq, seq))
1823                         return ERR_PTR(-ECHILD);
1824         } else {
1825                 if (path.mnt == nd->path.mnt)
1826                         mntget(path.mnt);
1827         }
1828         return pick_link(nd, &path, inode, seq, flags);
1829 }
1830
1831 static struct dentry *follow_dotdot_rcu(struct nameidata *nd,
1832                                         struct inode **inodep,
1833                                         unsigned *seqp)
1834 {
1835         struct dentry *parent, *old;
1836
1837         if (path_equal(&nd->path, &nd->root))
1838                 goto in_root;
1839         if (unlikely(nd->path.dentry == nd->path.mnt->mnt_root)) {
1840                 struct path path;
1841                 unsigned seq;
1842                 if (!choose_mountpoint_rcu(real_mount(nd->path.mnt),
1843                                            &nd->root, &path, &seq))
1844                         goto in_root;
1845                 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1846                         return ERR_PTR(-ECHILD);
1847                 nd->path = path;
1848                 nd->inode = path.dentry->d_inode;
1849                 nd->seq = seq;
1850                 if (unlikely(read_seqretry(&mount_lock, nd->m_seq)))
1851                         return ERR_PTR(-ECHILD);
1852                 /* we know that mountpoint was pinned */
1853         }
1854         old = nd->path.dentry;
1855         parent = old->d_parent;
1856         *inodep = parent->d_inode;
1857         *seqp = read_seqcount_begin(&parent->d_seq);
1858         if (unlikely(read_seqcount_retry(&old->d_seq, nd->seq)))
1859                 return ERR_PTR(-ECHILD);
1860         if (unlikely(!path_connected(nd->path.mnt, parent)))
1861                 return ERR_PTR(-ECHILD);
1862         return parent;
1863 in_root:
1864         if (unlikely(read_seqretry(&mount_lock, nd->m_seq)))
1865                 return ERR_PTR(-ECHILD);
1866         if (unlikely(nd->flags & LOOKUP_BENEATH))
1867                 return ERR_PTR(-ECHILD);
1868         return NULL;
1869 }
1870
1871 static struct dentry *follow_dotdot(struct nameidata *nd,
1872                                  struct inode **inodep,
1873                                  unsigned *seqp)
1874 {
1875         struct dentry *parent;
1876
1877         if (path_equal(&nd->path, &nd->root))
1878                 goto in_root;
1879         if (unlikely(nd->path.dentry == nd->path.mnt->mnt_root)) {
1880                 struct path path;
1881
1882                 if (!choose_mountpoint(real_mount(nd->path.mnt),
1883                                        &nd->root, &path))
1884                         goto in_root;
1885                 path_put(&nd->path);
1886                 nd->path = path;
1887                 nd->inode = path.dentry->d_inode;
1888                 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1889                         return ERR_PTR(-EXDEV);
1890         }
1891         /* rare case of legitimate dget_parent()... */
1892         parent = dget_parent(nd->path.dentry);
1893         if (unlikely(!path_connected(nd->path.mnt, parent))) {
1894                 dput(parent);
1895                 return ERR_PTR(-ENOENT);
1896         }
1897         *seqp = 0;
1898         *inodep = parent->d_inode;
1899         return parent;
1900
1901 in_root:
1902         if (unlikely(nd->flags & LOOKUP_BENEATH))
1903                 return ERR_PTR(-EXDEV);
1904         dget(nd->path.dentry);
1905         return NULL;
1906 }
1907
1908 static const char *handle_dots(struct nameidata *nd, int type)
1909 {
1910         if (type == LAST_DOTDOT) {
1911                 const char *error = NULL;
1912                 struct dentry *parent;
1913                 struct inode *inode;
1914                 unsigned seq;
1915
1916                 if (!nd->root.mnt) {
1917                         error = ERR_PTR(set_root(nd));
1918                         if (error)
1919                                 return error;
1920                 }
1921                 if (nd->flags & LOOKUP_RCU)
1922                         parent = follow_dotdot_rcu(nd, &inode, &seq);
1923                 else
1924                         parent = follow_dotdot(nd, &inode, &seq);
1925                 if (IS_ERR(parent))
1926                         return ERR_CAST(parent);
1927                 if (unlikely(!parent))
1928                         error = step_into(nd, WALK_NOFOLLOW,
1929                                          nd->path.dentry, nd->inode, nd->seq);
1930                 else
1931                         error = step_into(nd, WALK_NOFOLLOW,
1932                                          parent, inode, seq);
1933                 if (unlikely(error))
1934                         return error;
1935
1936                 if (unlikely(nd->flags & LOOKUP_IS_SCOPED)) {
1937                         /*
1938                          * If there was a racing rename or mount along our
1939                          * path, then we can't be sure that ".." hasn't jumped
1940                          * above nd->root (and so userspace should retry or use
1941                          * some fallback).
1942                          */
1943                         smp_rmb();
1944                         if (unlikely(__read_seqcount_retry(&mount_lock.seqcount, nd->m_seq)))
1945                                 return ERR_PTR(-EAGAIN);
1946                         if (unlikely(__read_seqcount_retry(&rename_lock.seqcount, nd->r_seq)))
1947                                 return ERR_PTR(-EAGAIN);
1948                 }
1949         }
1950         return NULL;
1951 }
1952
1953 static const char *walk_component(struct nameidata *nd, int flags)
1954 {
1955         struct dentry *dentry;
1956         struct inode *inode;
1957         unsigned seq;
1958         /*
1959          * "." and ".." are special - ".." especially so because it has
1960          * to be able to know about the current root directory and
1961          * parent relationships.
1962          */
1963         if (unlikely(nd->last_type != LAST_NORM)) {
1964                 if (!(flags & WALK_MORE) && nd->depth)
1965                         put_link(nd);
1966                 return handle_dots(nd, nd->last_type);
1967         }
1968         dentry = lookup_fast(nd, &inode, &seq);
1969         if (IS_ERR(dentry))
1970                 return ERR_CAST(dentry);
1971         if (unlikely(!dentry)) {
1972                 dentry = lookup_slow(&nd->last, nd->path.dentry, nd->flags);
1973                 if (IS_ERR(dentry))
1974                         return ERR_CAST(dentry);
1975         }
1976         if (!(flags & WALK_MORE) && nd->depth)
1977                 put_link(nd);
1978         return step_into(nd, flags, dentry, inode, seq);
1979 }
1980
1981 /*
1982  * We can do the critical dentry name comparison and hashing
1983  * operations one word at a time, but we are limited to:
1984  *
1985  * - Architectures with fast unaligned word accesses. We could
1986  *   do a "get_unaligned()" if this helps and is sufficiently
1987  *   fast.
1988  *
1989  * - non-CONFIG_DEBUG_PAGEALLOC configurations (so that we
1990  *   do not trap on the (extremely unlikely) case of a page
1991  *   crossing operation.
1992  *
1993  * - Furthermore, we need an efficient 64-bit compile for the
1994  *   64-bit case in order to generate the "number of bytes in
1995  *   the final mask". Again, that could be replaced with a
1996  *   efficient population count instruction or similar.
1997  */
1998 #ifdef CONFIG_DCACHE_WORD_ACCESS
1999
2000 #include <asm/word-at-a-time.h>
2001
2002 #ifdef HASH_MIX
2003
2004 /* Architecture provides HASH_MIX and fold_hash() in <asm/hash.h> */
2005
2006 #elif defined(CONFIG_64BIT)
2007 /*
2008  * Register pressure in the mixing function is an issue, particularly
2009  * on 32-bit x86, but almost any function requires one state value and
2010  * one temporary.  Instead, use a function designed for two state values
2011  * and no temporaries.
2012  *
2013  * This function cannot create a collision in only two iterations, so
2014  * we have two iterations to achieve avalanche.  In those two iterations,
2015  * we have six layers of mixing, which is enough to spread one bit's
2016  * influence out to 2^6 = 64 state bits.
2017  *
2018  * Rotate constants are scored by considering either 64 one-bit input
2019  * deltas or 64*63/2 = 2016 two-bit input deltas, and finding the
2020  * probability of that delta causing a change to each of the 128 output
2021  * bits, using a sample of random initial states.
2022  *
2023  * The Shannon entropy of the computed probabilities is then summed
2024  * to produce a score.  Ideally, any input change has a 50% chance of
2025  * toggling any given output bit.
2026  *
2027  * Mixing scores (in bits) for (12,45):
2028  * Input delta: 1-bit      2-bit
2029  * 1 round:     713.3    42542.6
2030  * 2 rounds:   2753.7   140389.8
2031  * 3 rounds:   5954.1   233458.2
2032  * 4 rounds:   7862.6   256672.2
2033  * Perfect:    8192     258048
2034  *            (64*128) (64*63/2 * 128)
2035  */
2036 #define HASH_MIX(x, y, a)       \
2037         (       x ^= (a),       \
2038         y ^= x, x = rol64(x,12),\
2039         x += y, y = rol64(y,45),\
2040         y *= 9                  )
2041
2042 /*
2043  * Fold two longs into one 32-bit hash value.  This must be fast, but
2044  * latency isn't quite as critical, as there is a fair bit of additional
2045  * work done before the hash value is used.
2046  */
2047 static inline unsigned int fold_hash(unsigned long x, unsigned long y)
2048 {
2049         y ^= x * GOLDEN_RATIO_64;
2050         y *= GOLDEN_RATIO_64;
2051         return y >> 32;
2052 }
2053
2054 #else   /* 32-bit case */
2055
2056 /*
2057  * Mixing scores (in bits) for (7,20):
2058  * Input delta: 1-bit      2-bit
2059  * 1 round:     330.3     9201.6
2060  * 2 rounds:   1246.4    25475.4
2061  * 3 rounds:   1907.1    31295.1
2062  * 4 rounds:   2042.3    31718.6
2063  * Perfect:    2048      31744
2064  *            (32*64)   (32*31/2 * 64)
2065  */
2066 #define HASH_MIX(x, y, a)       \
2067         (       x ^= (a),       \
2068         y ^= x, x = rol32(x, 7),\
2069         x += y, y = rol32(y,20),\
2070         y *= 9                  )
2071
2072 static inline unsigned int fold_hash(unsigned long x, unsigned long y)
2073 {
2074         /* Use arch-optimized multiply if one exists */
2075         return __hash_32(y ^ __hash_32(x));
2076 }
2077
2078 #endif
2079
2080 /*
2081  * Return the hash of a string of known length.  This is carfully
2082  * designed to match hash_name(), which is the more critical function.
2083  * In particular, we must end by hashing a final word containing 0..7
2084  * payload bytes, to match the way that hash_name() iterates until it
2085  * finds the delimiter after the name.
2086  */
2087 unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
2088 {
2089         unsigned long a, x = 0, y = (unsigned long)salt;
2090
2091         for (;;) {
2092                 if (!len)
2093                         goto done;
2094                 a = load_unaligned_zeropad(name);
2095                 if (len < sizeof(unsigned long))
2096                         break;
2097                 HASH_MIX(x, y, a);
2098                 name += sizeof(unsigned long);
2099                 len -= sizeof(unsigned long);
2100         }
2101         x ^= a & bytemask_from_count(len);
2102 done:
2103         return fold_hash(x, y);
2104 }
2105 EXPORT_SYMBOL(full_name_hash);
2106
2107 /* Return the "hash_len" (hash and length) of a null-terminated string */
2108 u64 hashlen_string(const void *salt, const char *name)
2109 {
2110         unsigned long a = 0, x = 0, y = (unsigned long)salt;
2111         unsigned long adata, mask, len;
2112         const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2113
2114         len = 0;
2115         goto inside;
2116
2117         do {
2118                 HASH_MIX(x, y, a);
2119                 len += sizeof(unsigned long);
2120 inside:
2121                 a = load_unaligned_zeropad(name+len);
2122         } while (!has_zero(a, &adata, &constants));
2123
2124         adata = prep_zero_mask(a, adata, &constants);
2125         mask = create_zero_mask(adata);
2126         x ^= a & zero_bytemask(mask);
2127
2128         return hashlen_create(fold_hash(x, y), len + find_zero(mask));
2129 }
2130 EXPORT_SYMBOL(hashlen_string);
2131
2132 /*
2133  * Calculate the length and hash of the path component, and
2134  * return the "hash_len" as the result.
2135  */
2136 static inline u64 hash_name(const void *salt, const char *name)
2137 {
2138         unsigned long a = 0, b, x = 0, y = (unsigned long)salt;
2139         unsigned long adata, bdata, mask, len;
2140         const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2141
2142         len = 0;
2143         goto inside;
2144
2145         do {
2146                 HASH_MIX(x, y, a);
2147                 len += sizeof(unsigned long);
2148 inside:
2149                 a = load_unaligned_zeropad(name+len);
2150                 b = a ^ REPEAT_BYTE('/');
2151         } while (!(has_zero(a, &adata, &constants) | has_zero(b, &bdata, &constants)));
2152
2153         adata = prep_zero_mask(a, adata, &constants);
2154         bdata = prep_zero_mask(b, bdata, &constants);
2155         mask = create_zero_mask(adata | bdata);
2156         x ^= a & zero_bytemask(mask);
2157
2158         return hashlen_create(fold_hash(x, y), len + find_zero(mask));
2159 }
2160
2161 #else   /* !CONFIG_DCACHE_WORD_ACCESS: Slow, byte-at-a-time version */
2162
2163 /* Return the hash of a string of known length */
2164 unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
2165 {
2166         unsigned long hash = init_name_hash(salt);
2167         while (len--)
2168                 hash = partial_name_hash((unsigned char)*name++, hash);
2169         return end_name_hash(hash);
2170 }
2171 EXPORT_SYMBOL(full_name_hash);
2172
2173 /* Return the "hash_len" (hash and length) of a null-terminated string */
2174 u64 hashlen_string(const void *salt, const char *name)
2175 {
2176         unsigned long hash = init_name_hash(salt);
2177         unsigned long len = 0, c;
2178
2179         c = (unsigned char)*name;
2180         while (c) {
2181                 len++;
2182                 hash = partial_name_hash(c, hash);
2183                 c = (unsigned char)name[len];
2184         }
2185         return hashlen_create(end_name_hash(hash), len);
2186 }
2187 EXPORT_SYMBOL(hashlen_string);
2188
2189 /*
2190  * We know there's a real path component here of at least
2191  * one character.
2192  */
2193 static inline u64 hash_name(const void *salt, const char *name)
2194 {
2195         unsigned long hash = init_name_hash(salt);
2196         unsigned long len = 0, c;
2197
2198         c = (unsigned char)*name;
2199         do {
2200                 len++;
2201                 hash = partial_name_hash(c, hash);
2202                 c = (unsigned char)name[len];
2203         } while (c && c != '/');
2204         return hashlen_create(end_name_hash(hash), len);
2205 }
2206
2207 #endif
2208
2209 /*
2210  * Name resolution.
2211  * This is the basic name resolution function, turning a pathname into
2212  * the final dentry. We expect 'base' to be positive and a directory.
2213  *
2214  * Returns 0 and nd will have valid dentry and mnt on success.
2215  * Returns error and drops reference to input namei data on failure.
2216  */
2217 static int link_path_walk(const char *name, struct nameidata *nd)
2218 {
2219         int depth = 0; // depth <= nd->depth
2220         int err;
2221
2222         nd->last_type = LAST_ROOT;
2223         nd->flags |= LOOKUP_PARENT;
2224         if (IS_ERR(name))
2225                 return PTR_ERR(name);
2226         while (*name=='/')
2227                 name++;
2228         if (!*name) {
2229                 nd->dir_mode = 0; // short-circuit the 'hardening' idiocy
2230                 return 0;
2231         }
2232
2233         /* At this point we know we have a real path component. */
2234         for(;;) {
2235                 struct user_namespace *mnt_userns;
2236                 const char *link;
2237                 u64 hash_len;
2238                 int type;
2239
2240                 mnt_userns = mnt_user_ns(nd->path.mnt);
2241                 err = may_lookup(mnt_userns, nd);
2242                 if (err)
2243                         return err;
2244
2245                 hash_len = hash_name(nd->path.dentry, name);
2246
2247                 type = LAST_NORM;
2248                 if (name[0] == '.') switch (hashlen_len(hash_len)) {
2249                         case 2:
2250                                 if (name[1] == '.') {
2251                                         type = LAST_DOTDOT;
2252                                         nd->state |= ND_JUMPED;
2253                                 }
2254                                 break;
2255                         case 1:
2256                                 type = LAST_DOT;
2257                 }
2258                 if (likely(type == LAST_NORM)) {
2259                         struct dentry *parent = nd->path.dentry;
2260                         nd->state &= ~ND_JUMPED;
2261                         if (unlikely(parent->d_flags & DCACHE_OP_HASH)) {
2262                                 struct qstr this = { { .hash_len = hash_len }, .name = name };
2263                                 err = parent->d_op->d_hash(parent, &this);
2264                                 if (err < 0)
2265                                         return err;
2266                                 hash_len = this.hash_len;
2267                                 name = this.name;
2268                         }
2269                 }
2270
2271                 nd->last.hash_len = hash_len;
2272                 nd->last.name = name;
2273                 nd->last_type = type;
2274
2275                 name += hashlen_len(hash_len);
2276                 if (!*name)
2277                         goto OK;
2278                 /*
2279                  * If it wasn't NUL, we know it was '/'. Skip that
2280                  * slash, and continue until no more slashes.
2281                  */
2282                 do {
2283                         name++;
2284                 } while (unlikely(*name == '/'));
2285                 if (unlikely(!*name)) {
2286 OK:
2287                         /* pathname or trailing symlink, done */
2288                         if (!depth) {
2289                                 nd->dir_uid = i_uid_into_mnt(mnt_userns, nd->inode);
2290                                 nd->dir_mode = nd->inode->i_mode;
2291                                 nd->flags &= ~LOOKUP_PARENT;
2292                                 return 0;
2293                         }
2294                         /* last component of nested symlink */
2295                         name = nd->stack[--depth].name;
2296                         link = walk_component(nd, 0);
2297                 } else {
2298                         /* not the last component */
2299                         link = walk_component(nd, WALK_MORE);
2300                 }
2301                 if (unlikely(link)) {
2302                         if (IS_ERR(link))
2303                                 return PTR_ERR(link);
2304                         /* a symlink to follow */
2305                         nd->stack[depth++].name = name;
2306                         name = link;
2307                         continue;
2308                 }
2309                 if (unlikely(!d_can_lookup(nd->path.dentry))) {
2310                         if (nd->flags & LOOKUP_RCU) {
2311                                 if (!try_to_unlazy(nd))
2312                                         return -ECHILD;
2313                         }
2314                         return -ENOTDIR;
2315                 }
2316         }
2317 }
2318
2319 /* must be paired with terminate_walk() */
2320 static const char *path_init(struct nameidata *nd, unsigned flags)
2321 {
2322         int error;
2323         const char *s = nd->name->name;
2324
2325         /* LOOKUP_CACHED requires RCU, ask caller to retry */
2326         if ((flags & (LOOKUP_RCU | LOOKUP_CACHED)) == LOOKUP_CACHED)
2327                 return ERR_PTR(-EAGAIN);
2328
2329         if (!*s)
2330                 flags &= ~LOOKUP_RCU;
2331         if (flags & LOOKUP_RCU)
2332                 rcu_read_lock();
2333
2334         nd->flags = flags;
2335         nd->state |= ND_JUMPED;
2336
2337         nd->m_seq = __read_seqcount_begin(&mount_lock.seqcount);
2338         nd->r_seq = __read_seqcount_begin(&rename_lock.seqcount);
2339         smp_rmb();
2340
2341         if (nd->state & ND_ROOT_PRESET) {
2342                 struct dentry *root = nd->root.dentry;
2343                 struct inode *inode = root->d_inode;
2344                 if (*s && unlikely(!d_can_lookup(root)))
2345                         return ERR_PTR(-ENOTDIR);
2346                 nd->path = nd->root;
2347                 nd->inode = inode;
2348                 if (flags & LOOKUP_RCU) {
2349                         nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
2350                         nd->root_seq = nd->seq;
2351                 } else {
2352                         path_get(&nd->path);
2353                 }
2354                 return s;
2355         }
2356
2357         nd->root.mnt = NULL;
2358
2359         /* Absolute pathname -- fetch the root (LOOKUP_IN_ROOT uses nd->dfd). */
2360         if (*s == '/' && !(flags & LOOKUP_IN_ROOT)) {
2361                 error = nd_jump_root(nd);
2362                 if (unlikely(error))
2363                         return ERR_PTR(error);
2364                 return s;
2365         }
2366
2367         /* Relative pathname -- get the starting-point it is relative to. */
2368         if (nd->dfd == AT_FDCWD) {
2369                 if (flags & LOOKUP_RCU) {
2370                         struct fs_struct *fs = current->fs;
2371                         unsigned seq;
2372
2373                         do {
2374                                 seq = read_seqcount_begin(&fs->seq);
2375                                 nd->path = fs->pwd;
2376                                 nd->inode = nd->path.dentry->d_inode;
2377                                 nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
2378                         } while (read_seqcount_retry(&fs->seq, seq));
2379                 } else {
2380                         get_fs_pwd(current->fs, &nd->path);
2381                         nd->inode = nd->path.dentry->d_inode;
2382                 }
2383         } else {
2384                 /* Caller must check execute permissions on the starting path component */
2385                 struct fd f = fdget_raw(nd->dfd);
2386                 struct dentry *dentry;
2387
2388                 if (!f.file)
2389                         return ERR_PTR(-EBADF);
2390
2391                 dentry = f.file->f_path.dentry;
2392
2393                 if (*s && unlikely(!d_can_lookup(dentry))) {
2394                         fdput(f);
2395                         return ERR_PTR(-ENOTDIR);
2396                 }
2397
2398                 nd->path = f.file->f_path;
2399                 if (flags & LOOKUP_RCU) {
2400                         nd->inode = nd->path.dentry->d_inode;
2401                         nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
2402                 } else {
2403                         path_get(&nd->path);
2404                         nd->inode = nd->path.dentry->d_inode;
2405                 }
2406                 fdput(f);
2407         }
2408
2409         /* For scoped-lookups we need to set the root to the dirfd as well. */
2410         if (flags & LOOKUP_IS_SCOPED) {
2411                 nd->root = nd->path;
2412                 if (flags & LOOKUP_RCU) {
2413                         nd->root_seq = nd->seq;
2414                 } else {
2415                         path_get(&nd->root);
2416                         nd->state |= ND_ROOT_GRABBED;
2417                 }
2418         }
2419         return s;
2420 }
2421
2422 static inline const char *lookup_last(struct nameidata *nd)
2423 {
2424         if (nd->last_type == LAST_NORM && nd->last.name[nd->last.len])
2425                 nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
2426
2427         return walk_component(nd, WALK_TRAILING);
2428 }
2429
2430 static int handle_lookup_down(struct nameidata *nd)
2431 {
2432         if (!(nd->flags & LOOKUP_RCU))
2433                 dget(nd->path.dentry);
2434         return PTR_ERR(step_into(nd, WALK_NOFOLLOW,
2435                         nd->path.dentry, nd->inode, nd->seq));
2436 }
2437
2438 /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
2439 static int path_lookupat(struct nameidata *nd, unsigned flags, struct path *path)
2440 {
2441         const char *s = path_init(nd, flags);
2442         int err;
2443
2444         if (unlikely(flags & LOOKUP_DOWN) && !IS_ERR(s)) {
2445                 err = handle_lookup_down(nd);
2446                 if (unlikely(err < 0))
2447                         s = ERR_PTR(err);
2448         }
2449
2450         while (!(err = link_path_walk(s, nd)) &&
2451                (s = lookup_last(nd)) != NULL)
2452                 ;
2453         if (!err && unlikely(nd->flags & LOOKUP_MOUNTPOINT)) {
2454                 err = handle_lookup_down(nd);
2455                 nd->state &= ~ND_JUMPED; // no d_weak_revalidate(), please...
2456         }
2457         if (!err)
2458                 err = complete_walk(nd);
2459
2460         if (!err && nd->flags & LOOKUP_DIRECTORY)
2461                 if (!d_can_lookup(nd->path.dentry))
2462                         err = -ENOTDIR;
2463         if (!err) {
2464                 *path = nd->path;
2465                 nd->path.mnt = NULL;
2466                 nd->path.dentry = NULL;
2467         }
2468         terminate_walk(nd);
2469         return err;
2470 }
2471
2472 int filename_lookup(int dfd, struct filename *name, unsigned flags,
2473                     struct path *path, struct path *root)
2474 {
2475         int retval;
2476         struct nameidata nd;
2477         if (IS_ERR(name))
2478                 return PTR_ERR(name);
2479         set_nameidata(&nd, dfd, name, root);
2480         retval = path_lookupat(&nd, flags | LOOKUP_RCU, path);
2481         if (unlikely(retval == -ECHILD))
2482                 retval = path_lookupat(&nd, flags, path);
2483         if (unlikely(retval == -ESTALE))
2484                 retval = path_lookupat(&nd, flags | LOOKUP_REVAL, path);
2485
2486         if (likely(!retval))
2487                 audit_inode(name, path->dentry,
2488                             flags & LOOKUP_MOUNTPOINT ? AUDIT_INODE_NOEVAL : 0);
2489         restore_nameidata();
2490         return retval;
2491 }
2492
2493 /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
2494 static int path_parentat(struct nameidata *nd, unsigned flags,
2495                                 struct path *parent)
2496 {
2497         const char *s = path_init(nd, flags);
2498         int err = link_path_walk(s, nd);
2499         if (!err)
2500                 err = complete_walk(nd);
2501         if (!err) {
2502                 *parent = nd->path;
2503                 nd->path.mnt = NULL;
2504                 nd->path.dentry = NULL;
2505         }
2506         terminate_walk(nd);
2507         return err;
2508 }
2509
2510 /* Note: this does not consume "name" */
2511 static int filename_parentat(int dfd, struct filename *name,
2512                              unsigned int flags, struct path *parent,
2513                              struct qstr *last, int *type)
2514 {
2515         int retval;
2516         struct nameidata nd;
2517
2518         if (IS_ERR(name))
2519                 return PTR_ERR(name);
2520         set_nameidata(&nd, dfd, name, NULL);
2521         retval = path_parentat(&nd, flags | LOOKUP_RCU, parent);
2522         if (unlikely(retval == -ECHILD))
2523                 retval = path_parentat(&nd, flags, parent);
2524         if (unlikely(retval == -ESTALE))
2525                 retval = path_parentat(&nd, flags | LOOKUP_REVAL, parent);
2526         if (likely(!retval)) {
2527                 *last = nd.last;
2528                 *type = nd.last_type;
2529                 audit_inode(name, parent->dentry, AUDIT_INODE_PARENT);
2530         }
2531         restore_nameidata();
2532         return retval;
2533 }
2534
2535 /* does lookup, returns the object with parent locked */
2536 static struct dentry *__kern_path_locked(struct filename *name, struct path *path)
2537 {
2538         struct dentry *d;
2539         struct qstr last;
2540         int type, error;
2541
2542         error = filename_parentat(AT_FDCWD, name, 0, path, &last, &type);
2543         if (error)
2544                 return ERR_PTR(error);
2545         if (unlikely(type != LAST_NORM)) {
2546                 path_put(path);
2547                 return ERR_PTR(-EINVAL);
2548         }
2549         inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
2550         d = __lookup_hash(&last, path->dentry, 0);
2551         if (IS_ERR(d)) {
2552                 inode_unlock(path->dentry->d_inode);
2553                 path_put(path);
2554         }
2555         return d;
2556 }
2557
2558 struct dentry *kern_path_locked(const char *name, struct path *path)
2559 {
2560         struct filename *filename = getname_kernel(name);
2561         struct dentry *res = __kern_path_locked(filename, path);
2562
2563         putname(filename);
2564         return res;
2565 }
2566
2567 int kern_path(const char *name, unsigned int flags, struct path *path)
2568 {
2569         struct filename *filename = getname_kernel(name);
2570         int ret = filename_lookup(AT_FDCWD, filename, flags, path, NULL);
2571
2572         putname(filename);
2573         return ret;
2574
2575 }
2576 EXPORT_SYMBOL(kern_path);
2577
2578 /**
2579  * vfs_path_lookup - lookup a file path relative to a dentry-vfsmount pair
2580  * @dentry:  pointer to dentry of the base directory
2581  * @mnt: pointer to vfs mount of the base directory
2582  * @name: pointer to file name
2583  * @flags: lookup flags
2584  * @path: pointer to struct path to fill
2585  */
2586 int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt,
2587                     const char *name, unsigned int flags,
2588                     struct path *path)
2589 {
2590         struct filename *filename;
2591         struct path root = {.mnt = mnt, .dentry = dentry};
2592         int ret;
2593
2594         filename = getname_kernel(name);
2595         /* the first argument of filename_lookup() is ignored with root */
2596         ret = filename_lookup(AT_FDCWD, filename, flags, path, &root);
2597         putname(filename);
2598         return ret;
2599 }
2600 EXPORT_SYMBOL(vfs_path_lookup);
2601
2602 static int lookup_one_common(struct user_namespace *mnt_userns,
2603                              const char *name, struct dentry *base, int len,
2604                              struct qstr *this)
2605 {
2606         this->name = name;
2607         this->len = len;
2608         this->hash = full_name_hash(base, name, len);
2609         if (!len)
2610                 return -EACCES;
2611
2612         if (unlikely(name[0] == '.')) {
2613                 if (len < 2 || (len == 2 && name[1] == '.'))
2614                         return -EACCES;
2615         }
2616
2617         while (len--) {
2618                 unsigned int c = *(const unsigned char *)name++;
2619                 if (c == '/' || c == '\0')
2620                         return -EACCES;
2621         }
2622         /*
2623          * See if the low-level filesystem might want
2624          * to use its own hash..
2625          */
2626         if (base->d_flags & DCACHE_OP_HASH) {
2627                 int err = base->d_op->d_hash(base, this);
2628                 if (err < 0)
2629                         return err;
2630         }
2631
2632         return inode_permission(mnt_userns, base->d_inode, MAY_EXEC);
2633 }
2634
2635 /**
2636  * try_lookup_one_len - filesystem helper to lookup single pathname component
2637  * @name:       pathname component to lookup
2638  * @base:       base directory to lookup from
2639  * @len:        maximum length @len should be interpreted to
2640  *
2641  * Look up a dentry by name in the dcache, returning NULL if it does not
2642  * currently exist.  The function does not try to create a dentry.
2643  *
2644  * Note that this routine is purely a helper for filesystem usage and should
2645  * not be called by generic code.
2646  *
2647  * The caller must hold base->i_mutex.
2648  */
2649 struct dentry *try_lookup_one_len(const char *name, struct dentry *base, int len)
2650 {
2651         struct qstr this;
2652         int err;
2653
2654         WARN_ON_ONCE(!inode_is_locked(base->d_inode));
2655
2656         err = lookup_one_common(&init_user_ns, name, base, len, &this);
2657         if (err)
2658                 return ERR_PTR(err);
2659
2660         return lookup_dcache(&this, base, 0);
2661 }
2662 EXPORT_SYMBOL(try_lookup_one_len);
2663
2664 /**
2665  * lookup_one_len - filesystem helper to lookup single pathname component
2666  * @name:       pathname component to lookup
2667  * @base:       base directory to lookup from
2668  * @len:        maximum length @len should be interpreted to
2669  *
2670  * Note that this routine is purely a helper for filesystem usage and should
2671  * not be called by generic code.
2672  *
2673  * The caller must hold base->i_mutex.
2674  */
2675 struct dentry *lookup_one_len(const char *name, struct dentry *base, int len)
2676 {
2677         struct dentry *dentry;
2678         struct qstr this;
2679         int err;
2680
2681         WARN_ON_ONCE(!inode_is_locked(base->d_inode));
2682
2683         err = lookup_one_common(&init_user_ns, name, base, len, &this);
2684         if (err)
2685                 return ERR_PTR(err);
2686
2687         dentry = lookup_dcache(&this, base, 0);
2688         return dentry ? dentry : __lookup_slow(&this, base, 0);
2689 }
2690 EXPORT_SYMBOL(lookup_one_len);
2691
2692 /**
2693  * lookup_one - filesystem helper to lookup single pathname component
2694  * @mnt_userns: user namespace of the mount the lookup is performed from
2695  * @name:       pathname component to lookup
2696  * @base:       base directory to lookup from
2697  * @len:        maximum length @len should be interpreted to
2698  *
2699  * Note that this routine is purely a helper for filesystem usage and should
2700  * not be called by generic code.
2701  *
2702  * The caller must hold base->i_mutex.
2703  */
2704 struct dentry *lookup_one(struct user_namespace *mnt_userns, const char *name,
2705                           struct dentry *base, int len)
2706 {
2707         struct dentry *dentry;
2708         struct qstr this;
2709         int err;
2710
2711         WARN_ON_ONCE(!inode_is_locked(base->d_inode));
2712
2713         err = lookup_one_common(mnt_userns, name, base, len, &this);
2714         if (err)
2715                 return ERR_PTR(err);
2716
2717         dentry = lookup_dcache(&this, base, 0);
2718         return dentry ? dentry : __lookup_slow(&this, base, 0);
2719 }
2720 EXPORT_SYMBOL(lookup_one);
2721
2722 /**
2723  * lookup_one_unlocked - filesystem helper to lookup single pathname component
2724  * @mnt_userns: idmapping of the mount the lookup is performed from
2725  * @name:       pathname component to lookup
2726  * @base:       base directory to lookup from
2727  * @len:        maximum length @len should be interpreted to
2728  *
2729  * Note that this routine is purely a helper for filesystem usage and should
2730  * not be called by generic code.
2731  *
2732  * Unlike lookup_one_len, it should be called without the parent
2733  * i_mutex held, and will take the i_mutex itself if necessary.
2734  */
2735 struct dentry *lookup_one_unlocked(struct user_namespace *mnt_userns,
2736                                    const char *name, struct dentry *base,
2737                                    int len)
2738 {
2739         struct qstr this;
2740         int err;
2741         struct dentry *ret;
2742
2743         err = lookup_one_common(mnt_userns, name, base, len, &this);
2744         if (err)
2745                 return ERR_PTR(err);
2746
2747         ret = lookup_dcache(&this, base, 0);
2748         if (!ret)
2749                 ret = lookup_slow(&this, base, 0);
2750         return ret;
2751 }
2752 EXPORT_SYMBOL(lookup_one_unlocked);
2753
2754 /**
2755  * lookup_one_positive_unlocked - filesystem helper to lookup single
2756  *                                pathname component
2757  * @mnt_userns: idmapping of the mount the lookup is performed from
2758  * @name:       pathname component to lookup
2759  * @base:       base directory to lookup from
2760  * @len:        maximum length @len should be interpreted to
2761  *
2762  * This helper will yield ERR_PTR(-ENOENT) on negatives. The helper returns
2763  * known positive or ERR_PTR(). This is what most of the users want.
2764  *
2765  * Note that pinned negative with unlocked parent _can_ become positive at any
2766  * time, so callers of lookup_one_unlocked() need to be very careful; pinned
2767  * positives have >d_inode stable, so this one avoids such problems.
2768  *
2769  * Note that this routine is purely a helper for filesystem usage and should
2770  * not be called by generic code.
2771  *
2772  * The helper should be called without i_mutex held.
2773  */
2774 struct dentry *lookup_one_positive_unlocked(struct user_namespace *mnt_userns,
2775                                             const char *name,
2776                                             struct dentry *base, int len)
2777 {
2778         struct dentry *ret = lookup_one_unlocked(mnt_userns, name, base, len);
2779
2780         if (!IS_ERR(ret) && d_flags_negative(smp_load_acquire(&ret->d_flags))) {
2781                 dput(ret);
2782                 ret = ERR_PTR(-ENOENT);
2783         }
2784         return ret;
2785 }
2786 EXPORT_SYMBOL(lookup_one_positive_unlocked);
2787
2788 /**
2789  * lookup_one_len_unlocked - filesystem helper to lookup single pathname component
2790  * @name:       pathname component to lookup
2791  * @base:       base directory to lookup from
2792  * @len:        maximum length @len should be interpreted to
2793  *
2794  * Note that this routine is purely a helper for filesystem usage and should
2795  * not be called by generic code.
2796  *
2797  * Unlike lookup_one_len, it should be called without the parent
2798  * i_mutex held, and will take the i_mutex itself if necessary.
2799  */
2800 struct dentry *lookup_one_len_unlocked(const char *name,
2801                                        struct dentry *base, int len)
2802 {
2803         return lookup_one_unlocked(&init_user_ns, name, base, len);
2804 }
2805 EXPORT_SYMBOL(lookup_one_len_unlocked);
2806
2807 /*
2808  * Like lookup_one_len_unlocked(), except that it yields ERR_PTR(-ENOENT)
2809  * on negatives.  Returns known positive or ERR_PTR(); that's what
2810  * most of the users want.  Note that pinned negative with unlocked parent
2811  * _can_ become positive at any time, so callers of lookup_one_len_unlocked()
2812  * need to be very careful; pinned positives have ->d_inode stable, so
2813  * this one avoids such problems.
2814  */
2815 struct dentry *lookup_positive_unlocked(const char *name,
2816                                        struct dentry *base, int len)
2817 {
2818         return lookup_one_positive_unlocked(&init_user_ns, name, base, len);
2819 }
2820 EXPORT_SYMBOL(lookup_positive_unlocked);
2821
2822 #ifdef CONFIG_UNIX98_PTYS
2823 int path_pts(struct path *path)
2824 {
2825         /* Find something mounted on "pts" in the same directory as
2826          * the input path.
2827          */
2828         struct dentry *parent = dget_parent(path->dentry);
2829         struct dentry *child;
2830         struct qstr this = QSTR_INIT("pts", 3);
2831
2832         if (unlikely(!path_connected(path->mnt, parent))) {
2833                 dput(parent);
2834                 return -ENOENT;
2835         }
2836         dput(path->dentry);
2837         path->dentry = parent;
2838         child = d_hash_and_lookup(parent, &this);
2839         if (IS_ERR_OR_NULL(child))
2840                 return -ENOENT;
2841
2842         path->dentry = child;
2843         dput(parent);
2844         follow_down(path);
2845         return 0;
2846 }
2847 #endif
2848
2849 int user_path_at_empty(int dfd, const char __user *name, unsigned flags,
2850                  struct path *path, int *empty)
2851 {
2852         struct filename *filename = getname_flags(name, flags, empty);
2853         int ret = filename_lookup(dfd, filename, flags, path, NULL);
2854
2855         putname(filename);
2856         return ret;
2857 }
2858 EXPORT_SYMBOL(user_path_at_empty);
2859
2860 int __check_sticky(struct user_namespace *mnt_userns, struct inode *dir,
2861                    struct inode *inode)
2862 {
2863         kuid_t fsuid = current_fsuid();
2864
2865         if (uid_eq(i_uid_into_mnt(mnt_userns, inode), fsuid))
2866                 return 0;
2867         if (uid_eq(i_uid_into_mnt(mnt_userns, dir), fsuid))
2868                 return 0;
2869         return !capable_wrt_inode_uidgid(mnt_userns, inode, CAP_FOWNER);
2870 }
2871 EXPORT_SYMBOL(__check_sticky);
2872
2873 /*
2874  *      Check whether we can remove a link victim from directory dir, check
2875  *  whether the type of victim is right.
2876  *  1. We can't do it if dir is read-only (done in permission())
2877  *  2. We should have write and exec permissions on dir
2878  *  3. We can't remove anything from append-only dir
2879  *  4. We can't do anything with immutable dir (done in permission())
2880  *  5. If the sticky bit on dir is set we should either
2881  *      a. be owner of dir, or
2882  *      b. be owner of victim, or
2883  *      c. have CAP_FOWNER capability
2884  *  6. If the victim is append-only or immutable we can't do antyhing with
2885  *     links pointing to it.
2886  *  7. If the victim has an unknown uid or gid we can't change the inode.
2887  *  8. If we were asked to remove a directory and victim isn't one - ENOTDIR.
2888  *  9. If we were asked to remove a non-directory and victim isn't one - EISDIR.
2889  * 10. We can't remove a root or mountpoint.
2890  * 11. We don't allow removal of NFS sillyrenamed files; it's handled by
2891  *     nfs_async_unlink().
2892  */
2893 static int may_delete(struct user_namespace *mnt_userns, struct inode *dir,
2894                       struct dentry *victim, bool isdir)
2895 {
2896         struct inode *inode = d_backing_inode(victim);
2897         int error;
2898
2899         if (d_is_negative(victim))
2900                 return -ENOENT;
2901         BUG_ON(!inode);
2902
2903         BUG_ON(victim->d_parent->d_inode != dir);
2904
2905         /* Inode writeback is not safe when the uid or gid are invalid. */
2906         if (!uid_valid(i_uid_into_mnt(mnt_userns, inode)) ||
2907             !gid_valid(i_gid_into_mnt(mnt_userns, inode)))
2908                 return -EOVERFLOW;
2909
2910         audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
2911
2912         error = inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
2913         if (error)
2914                 return error;
2915         if (IS_APPEND(dir))
2916                 return -EPERM;
2917
2918         if (check_sticky(mnt_userns, dir, inode) || IS_APPEND(inode) ||
2919             IS_IMMUTABLE(inode) || IS_SWAPFILE(inode) ||
2920             HAS_UNMAPPED_ID(mnt_userns, inode))
2921                 return -EPERM;
2922         if (isdir) {
2923                 if (!d_is_dir(victim))
2924                         return -ENOTDIR;
2925                 if (IS_ROOT(victim))
2926                         return -EBUSY;
2927         } else if (d_is_dir(victim))
2928                 return -EISDIR;
2929         if (IS_DEADDIR(dir))
2930                 return -ENOENT;
2931         if (victim->d_flags & DCACHE_NFSFS_RENAMED)
2932                 return -EBUSY;
2933         return 0;
2934 }
2935
2936 /*      Check whether we can create an object with dentry child in directory
2937  *  dir.
2938  *  1. We can't do it if child already exists (open has special treatment for
2939  *     this case, but since we are inlined it's OK)
2940  *  2. We can't do it if dir is read-only (done in permission())
2941  *  3. We can't do it if the fs can't represent the fsuid or fsgid.
2942  *  4. We should have write and exec permissions on dir
2943  *  5. We can't do it if dir is immutable (done in permission())
2944  */
2945 static inline int may_create(struct user_namespace *mnt_userns,
2946                              struct inode *dir, struct dentry *child)
2947 {
2948         audit_inode_child(dir, child, AUDIT_TYPE_CHILD_CREATE);
2949         if (child->d_inode)
2950                 return -EEXIST;
2951         if (IS_DEADDIR(dir))
2952                 return -ENOENT;
2953         if (!fsuidgid_has_mapping(dir->i_sb, mnt_userns))
2954                 return -EOVERFLOW;
2955
2956         return inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
2957 }
2958
2959 /*
2960  * p1 and p2 should be directories on the same fs.
2961  */
2962 struct dentry *lock_rename(struct dentry *p1, struct dentry *p2)
2963 {
2964         struct dentry *p;
2965
2966         if (p1 == p2) {
2967                 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
2968                 return NULL;
2969         }
2970
2971         mutex_lock(&p1->d_sb->s_vfs_rename_mutex);
2972
2973         p = d_ancestor(p2, p1);
2974         if (p) {
2975                 inode_lock_nested(p2->d_inode, I_MUTEX_PARENT);
2976                 inode_lock_nested(p1->d_inode, I_MUTEX_CHILD);
2977                 return p;
2978         }
2979
2980         p = d_ancestor(p1, p2);
2981         if (p) {
2982                 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
2983                 inode_lock_nested(p2->d_inode, I_MUTEX_CHILD);
2984                 return p;
2985         }
2986
2987         lock_two_inodes(p1->d_inode, p2->d_inode,
2988                         I_MUTEX_PARENT, I_MUTEX_PARENT2);
2989         return NULL;
2990 }
2991 EXPORT_SYMBOL(lock_rename);
2992
2993 void unlock_rename(struct dentry *p1, struct dentry *p2)
2994 {
2995         inode_unlock(p1->d_inode);
2996         if (p1 != p2) {
2997                 inode_unlock(p2->d_inode);
2998                 mutex_unlock(&p1->d_sb->s_vfs_rename_mutex);
2999         }
3000 }
3001 EXPORT_SYMBOL(unlock_rename);
3002
3003 /**
3004  * mode_strip_umask - handle vfs umask stripping
3005  * @dir:        parent directory of the new inode
3006  * @mode:       mode of the new inode to be created in @dir
3007  *
3008  * Umask stripping depends on whether or not the filesystem supports POSIX
3009  * ACLs. If the filesystem doesn't support it umask stripping is done directly
3010  * in here. If the filesystem does support POSIX ACLs umask stripping is
3011  * deferred until the filesystem calls posix_acl_create().
3012  *
3013  * Returns: mode
3014  */
3015 static inline umode_t mode_strip_umask(const struct inode *dir, umode_t mode)
3016 {
3017         if (!IS_POSIXACL(dir))
3018                 mode &= ~current_umask();
3019         return mode;
3020 }
3021
3022 /**
3023  * vfs_prepare_mode - prepare the mode to be used for a new inode
3024  * @mnt_userns:         user namespace of the mount the inode was found from
3025  * @dir:        parent directory of the new inode
3026  * @mode:       mode of the new inode
3027  * @mask_perms: allowed permission by the vfs
3028  * @type:       type of file to be created
3029  *
3030  * This helper consolidates and enforces vfs restrictions on the @mode of a new
3031  * object to be created.
3032  *
3033  * Umask stripping depends on whether the filesystem supports POSIX ACLs (see
3034  * the kernel documentation for mode_strip_umask()). Moving umask stripping
3035  * after setgid stripping allows the same ordering for both non-POSIX ACL and
3036  * POSIX ACL supporting filesystems.
3037  *
3038  * Note that it's currently valid for @type to be 0 if a directory is created.
3039  * Filesystems raise that flag individually and we need to check whether each
3040  * filesystem can deal with receiving S_IFDIR from the vfs before we enforce a
3041  * non-zero type.
3042  *
3043  * Returns: mode to be passed to the filesystem
3044  */
3045 static inline umode_t vfs_prepare_mode(struct user_namespace *mnt_userns,
3046                                        const struct inode *dir, umode_t mode,
3047                                        umode_t mask_perms, umode_t type)
3048 {
3049         mode = mode_strip_sgid(mnt_userns, dir, mode);
3050         mode = mode_strip_umask(dir, mode);
3051
3052         /*
3053          * Apply the vfs mandated allowed permission mask and set the type of
3054          * file to be created before we call into the filesystem.
3055          */
3056         mode &= (mask_perms & ~S_IFMT);
3057         mode |= (type & S_IFMT);
3058
3059         return mode;
3060 }
3061
3062 /**
3063  * vfs_create - create new file
3064  * @mnt_userns: user namespace of the mount the inode was found from
3065  * @dir:        inode of @dentry
3066  * @dentry:     pointer to dentry of the base directory
3067  * @mode:       mode of the new file
3068  * @want_excl:  whether the file must not yet exist
3069  *
3070  * Create a new file.
3071  *
3072  * If the inode has been found through an idmapped mount the user namespace of
3073  * the vfsmount must be passed through @mnt_userns. This function will then take
3074  * care to map the inode according to @mnt_userns before checking permissions.
3075  * On non-idmapped mounts or if permission checking is to be performed on the
3076  * raw inode simply passs init_user_ns.
3077  */
3078 int vfs_create(struct user_namespace *mnt_userns, struct inode *dir,
3079                struct dentry *dentry, umode_t mode, bool want_excl)
3080 {
3081         int error = may_create(mnt_userns, dir, dentry);
3082         if (error)
3083                 return error;
3084
3085         if (!dir->i_op->create)
3086                 return -EACCES; /* shouldn't it be ENOSYS? */
3087
3088         mode = vfs_prepare_mode(mnt_userns, dir, mode, S_IALLUGO, S_IFREG);
3089         error = security_inode_create(dir, dentry, mode);
3090         if (error)
3091                 return error;
3092         error = dir->i_op->create(mnt_userns, dir, dentry, mode, want_excl);
3093         if (!error)
3094                 fsnotify_create(dir, dentry);
3095         return error;
3096 }
3097 EXPORT_SYMBOL(vfs_create);
3098
3099 int vfs_mkobj(struct dentry *dentry, umode_t mode,
3100                 int (*f)(struct dentry *, umode_t, void *),
3101                 void *arg)
3102 {
3103         struct inode *dir = dentry->d_parent->d_inode;
3104         int error = may_create(&init_user_ns, dir, dentry);
3105         if (error)
3106                 return error;
3107
3108         mode &= S_IALLUGO;
3109         mode |= S_IFREG;
3110         error = security_inode_create(dir, dentry, mode);
3111         if (error)
3112                 return error;
3113         error = f(dentry, mode, arg);
3114         if (!error)
3115                 fsnotify_create(dir, dentry);
3116         return error;
3117 }
3118 EXPORT_SYMBOL(vfs_mkobj);
3119
3120 bool may_open_dev(const struct path *path)
3121 {
3122         return !(path->mnt->mnt_flags & MNT_NODEV) &&
3123                 !(path->mnt->mnt_sb->s_iflags & SB_I_NODEV);
3124 }
3125
3126 static int may_open(struct user_namespace *mnt_userns, const struct path *path,
3127                     int acc_mode, int flag)
3128 {
3129         struct dentry *dentry = path->dentry;
3130         struct inode *inode = dentry->d_inode;
3131         int error;
3132
3133         if (!inode)
3134                 return -ENOENT;
3135
3136         switch (inode->i_mode & S_IFMT) {
3137         case S_IFLNK:
3138                 return -ELOOP;
3139         case S_IFDIR:
3140                 if (acc_mode & MAY_WRITE)
3141                         return -EISDIR;
3142                 if (acc_mode & MAY_EXEC)
3143                         return -EACCES;
3144                 break;
3145         case S_IFBLK:
3146         case S_IFCHR:
3147                 if (!may_open_dev(path))
3148                         return -EACCES;
3149                 fallthrough;
3150         case S_IFIFO:
3151         case S_IFSOCK:
3152                 if (acc_mode & MAY_EXEC)
3153                         return -EACCES;
3154                 flag &= ~O_TRUNC;
3155                 break;
3156         case S_IFREG:
3157                 if ((acc_mode & MAY_EXEC) && path_noexec(path))
3158                         return -EACCES;
3159                 break;
3160         }
3161
3162         error = inode_permission(mnt_userns, inode, MAY_OPEN | acc_mode);
3163         if (error)
3164                 return error;
3165
3166         /*
3167          * An append-only file must be opened in append mode for writing.
3168          */
3169         if (IS_APPEND(inode)) {
3170                 if  ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND))
3171                         return -EPERM;
3172                 if (flag & O_TRUNC)
3173                         return -EPERM;
3174         }
3175
3176         /* O_NOATIME can only be set by the owner or superuser */
3177         if (flag & O_NOATIME && !inode_owner_or_capable(mnt_userns, inode))
3178                 return -EPERM;
3179
3180         return 0;
3181 }
3182
3183 static int handle_truncate(struct user_namespace *mnt_userns, struct file *filp)
3184 {
3185         const struct path *path = &filp->f_path;
3186         struct inode *inode = path->dentry->d_inode;
3187         int error = get_write_access(inode);
3188         if (error)
3189                 return error;
3190         /*
3191          * Refuse to truncate files with mandatory locks held on them.
3192          */
3193         error = security_path_truncate(path);
3194         if (!error) {
3195                 error = do_truncate(mnt_userns, path->dentry, 0,
3196                                     ATTR_MTIME|ATTR_CTIME|ATTR_OPEN,
3197                                     filp);
3198         }
3199         put_write_access(inode);
3200         return error;
3201 }
3202
3203 static inline int open_to_namei_flags(int flag)
3204 {
3205         if ((flag & O_ACCMODE) == 3)
3206                 flag--;
3207         return flag;
3208 }
3209
3210 static int may_o_create(struct user_namespace *mnt_userns,
3211                         const struct path *dir, struct dentry *dentry,
3212                         umode_t mode)
3213 {
3214         int error = security_path_mknod(dir, dentry, mode, 0);
3215         if (error)
3216                 return error;
3217
3218         if (!fsuidgid_has_mapping(dir->dentry->d_sb, mnt_userns))
3219                 return -EOVERFLOW;
3220
3221         error = inode_permission(mnt_userns, dir->dentry->d_inode,
3222                                  MAY_WRITE | MAY_EXEC);
3223         if (error)
3224                 return error;
3225
3226         return security_inode_create(dir->dentry->d_inode, dentry, mode);
3227 }
3228
3229 /*
3230  * Attempt to atomically look up, create and open a file from a negative
3231  * dentry.
3232  *
3233  * Returns 0 if successful.  The file will have been created and attached to
3234  * @file by the filesystem calling finish_open().
3235  *
3236  * If the file was looked up only or didn't need creating, FMODE_OPENED won't
3237  * be set.  The caller will need to perform the open themselves.  @path will
3238  * have been updated to point to the new dentry.  This may be negative.
3239  *
3240  * Returns an error code otherwise.
3241  */
3242 static struct dentry *atomic_open(struct nameidata *nd, struct dentry *dentry,
3243                                   struct file *file,
3244                                   int open_flag, umode_t mode)
3245 {
3246         struct dentry *const DENTRY_NOT_SET = (void *) -1UL;
3247         struct inode *dir =  nd->path.dentry->d_inode;
3248         int error;
3249
3250         if (nd->flags & LOOKUP_DIRECTORY)
3251                 open_flag |= O_DIRECTORY;
3252
3253         file->f_path.dentry = DENTRY_NOT_SET;
3254         file->f_path.mnt = nd->path.mnt;
3255         error = dir->i_op->atomic_open(dir, dentry, file,
3256                                        open_to_namei_flags(open_flag), mode);
3257         d_lookup_done(dentry);
3258         if (!error) {
3259                 if (file->f_mode & FMODE_OPENED) {
3260                         if (unlikely(dentry != file->f_path.dentry)) {
3261                                 dput(dentry);
3262                                 dentry = dget(file->f_path.dentry);
3263                         }
3264                 } else if (WARN_ON(file->f_path.dentry == DENTRY_NOT_SET)) {
3265                         error = -EIO;
3266                 } else {
3267                         if (file->f_path.dentry) {
3268                                 dput(dentry);
3269                                 dentry = file->f_path.dentry;
3270                         }
3271                         if (unlikely(d_is_negative(dentry)))
3272                                 error = -ENOENT;
3273                 }
3274         }
3275         if (error) {
3276                 dput(dentry);
3277                 dentry = ERR_PTR(error);
3278         }
3279         return dentry;
3280 }
3281
3282 /*
3283  * Look up and maybe create and open the last component.
3284  *
3285  * Must be called with parent locked (exclusive in O_CREAT case).
3286  *
3287  * Returns 0 on success, that is, if
3288  *  the file was successfully atomically created (if necessary) and opened, or
3289  *  the file was not completely opened at this time, though lookups and
3290  *  creations were performed.
3291  * These case are distinguished by presence of FMODE_OPENED on file->f_mode.
3292  * In the latter case dentry returned in @path might be negative if O_CREAT
3293  * hadn't been specified.
3294  *
3295  * An error code is returned on failure.
3296  */
3297 static struct dentry *lookup_open(struct nameidata *nd, struct file *file,
3298                                   const struct open_flags *op,
3299                                   bool got_write)
3300 {
3301         struct user_namespace *mnt_userns;
3302         struct dentry *dir = nd->path.dentry;
3303         struct inode *dir_inode = dir->d_inode;
3304         int open_flag = op->open_flag;
3305         struct dentry *dentry;
3306         int error, create_error = 0;
3307         umode_t mode = op->mode;
3308         DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
3309
3310         if (unlikely(IS_DEADDIR(dir_inode)))
3311                 return ERR_PTR(-ENOENT);
3312
3313         file->f_mode &= ~FMODE_CREATED;
3314         dentry = d_lookup(dir, &nd->last);
3315         for (;;) {
3316                 if (!dentry) {
3317                         dentry = d_alloc_parallel(dir, &nd->last, &wq);
3318                         if (IS_ERR(dentry))
3319                                 return dentry;
3320                 }
3321                 if (d_in_lookup(dentry))
3322                         break;
3323
3324                 error = d_revalidate(dentry, nd->flags);
3325                 if (likely(error > 0))
3326                         break;
3327                 if (error)
3328                         goto out_dput;
3329                 d_invalidate(dentry);
3330                 dput(dentry);
3331                 dentry = NULL;
3332         }
3333         if (dentry->d_inode) {
3334                 /* Cached positive dentry: will open in f_op->open */
3335                 return dentry;
3336         }
3337
3338         /*
3339          * Checking write permission is tricky, bacuse we don't know if we are
3340          * going to actually need it: O_CREAT opens should work as long as the
3341          * file exists.  But checking existence breaks atomicity.  The trick is
3342          * to check access and if not granted clear O_CREAT from the flags.
3343          *
3344          * Another problem is returing the "right" error value (e.g. for an
3345          * O_EXCL open we want to return EEXIST not EROFS).
3346          */
3347         if (unlikely(!got_write))
3348                 open_flag &= ~O_TRUNC;
3349         mnt_userns = mnt_user_ns(nd->path.mnt);
3350         if (open_flag & O_CREAT) {
3351                 if (open_flag & O_EXCL)
3352                         open_flag &= ~O_TRUNC;
3353                 mode = vfs_prepare_mode(mnt_userns, dir->d_inode, mode, mode, mode);
3354                 if (likely(got_write))
3355                         create_error = may_o_create(mnt_userns, &nd->path,
3356                                                     dentry, mode);
3357                 else
3358                         create_error = -EROFS;
3359         }
3360         if (create_error)
3361                 open_flag &= ~O_CREAT;
3362         if (dir_inode->i_op->atomic_open) {
3363                 dentry = atomic_open(nd, dentry, file, open_flag, mode);
3364                 if (unlikely(create_error) && dentry == ERR_PTR(-ENOENT))
3365                         dentry = ERR_PTR(create_error);
3366                 return dentry;
3367         }
3368
3369         if (d_in_lookup(dentry)) {
3370                 struct dentry *res = dir_inode->i_op->lookup(dir_inode, dentry,
3371                                                              nd->flags);
3372                 d_lookup_done(dentry);
3373                 if (unlikely(res)) {
3374                         if (IS_ERR(res)) {
3375                                 error = PTR_ERR(res);
3376                                 goto out_dput;
3377                         }
3378                         dput(dentry);
3379                         dentry = res;
3380                 }
3381         }
3382
3383         /* Negative dentry, just create the file */
3384         if (!dentry->d_inode && (open_flag & O_CREAT)) {
3385                 file->f_mode |= FMODE_CREATED;
3386                 audit_inode_child(dir_inode, dentry, AUDIT_TYPE_CHILD_CREATE);
3387                 if (!dir_inode->i_op->create) {
3388                         error = -EACCES;
3389                         goto out_dput;
3390                 }
3391
3392                 error = dir_inode->i_op->create(mnt_userns, dir_inode, dentry,
3393                                                 mode, open_flag & O_EXCL);
3394                 if (error)
3395                         goto out_dput;
3396         }
3397         if (unlikely(create_error) && !dentry->d_inode) {
3398                 error = create_error;
3399                 goto out_dput;
3400         }
3401         return dentry;
3402
3403 out_dput:
3404         dput(dentry);
3405         return ERR_PTR(error);
3406 }
3407
3408 static const char *open_last_lookups(struct nameidata *nd,
3409                    struct file *file, const struct open_flags *op)
3410 {
3411         struct dentry *dir = nd->path.dentry;
3412         int open_flag = op->open_flag;
3413         bool got_write = false;
3414         unsigned seq;
3415         struct inode *inode;
3416         struct dentry *dentry;
3417         const char *res;
3418
3419         nd->flags |= op->intent;
3420
3421         if (nd->last_type != LAST_NORM) {
3422                 if (nd->depth)
3423                         put_link(nd);
3424                 return handle_dots(nd, nd->last_type);
3425         }
3426
3427         if (!(open_flag & O_CREAT)) {
3428                 if (nd->last.name[nd->last.len])
3429                         nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
3430                 /* we _can_ be in RCU mode here */
3431                 dentry = lookup_fast(nd, &inode, &seq);
3432                 if (IS_ERR(dentry))
3433                         return ERR_CAST(dentry);
3434                 if (likely(dentry))
3435                         goto finish_lookup;
3436
3437                 BUG_ON(nd->flags & LOOKUP_RCU);
3438         } else {
3439                 /* create side of things */
3440                 if (nd->flags & LOOKUP_RCU) {
3441                         if (!try_to_unlazy(nd))
3442                                 return ERR_PTR(-ECHILD);
3443                 }
3444                 audit_inode(nd->name, dir, AUDIT_INODE_PARENT);
3445                 /* trailing slashes? */
3446                 if (unlikely(nd->last.name[nd->last.len]))
3447                         return ERR_PTR(-EISDIR);
3448         }
3449
3450         if (open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) {
3451                 got_write = !mnt_want_write(nd->path.mnt);
3452                 /*
3453                  * do _not_ fail yet - we might not need that or fail with
3454                  * a different error; let lookup_open() decide; we'll be
3455                  * dropping this one anyway.
3456                  */
3457         }
3458         if (open_flag & O_CREAT)
3459                 inode_lock(dir->d_inode);
3460         else
3461                 inode_lock_shared(dir->d_inode);
3462         dentry = lookup_open(nd, file, op, got_write);
3463         if (!IS_ERR(dentry) && (file->f_mode & FMODE_CREATED))
3464                 fsnotify_create(dir->d_inode, dentry);
3465         if (open_flag & O_CREAT)
3466                 inode_unlock(dir->d_inode);
3467         else
3468                 inode_unlock_shared(dir->d_inode);
3469
3470         if (got_write)
3471                 mnt_drop_write(nd->path.mnt);
3472
3473         if (IS_ERR(dentry))
3474                 return ERR_CAST(dentry);
3475
3476         if (file->f_mode & (FMODE_OPENED | FMODE_CREATED)) {
3477                 dput(nd->path.dentry);
3478                 nd->path.dentry = dentry;
3479                 return NULL;
3480         }
3481
3482 finish_lookup:
3483         if (nd->depth)
3484                 put_link(nd);
3485         res = step_into(nd, WALK_TRAILING, dentry, inode, seq);
3486         if (unlikely(res))
3487                 nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL);
3488         return res;
3489 }
3490
3491 /*
3492  * Handle the last step of open()
3493  */
3494 static int do_open(struct nameidata *nd,
3495                    struct file *file, const struct open_flags *op)
3496 {
3497         struct user_namespace *mnt_userns;
3498         int open_flag = op->open_flag;
3499         bool do_truncate;
3500         int acc_mode;
3501         int error;
3502
3503         if (!(file->f_mode & (FMODE_OPENED | FMODE_CREATED))) {
3504                 error = complete_walk(nd);
3505                 if (error)
3506                         return error;
3507         }
3508         if (!(file->f_mode & FMODE_CREATED))
3509                 audit_inode(nd->name, nd->path.dentry, 0);
3510         mnt_userns = mnt_user_ns(nd->path.mnt);
3511         if (open_flag & O_CREAT) {
3512                 if ((open_flag & O_EXCL) && !(file->f_mode & FMODE_CREATED))
3513                         return -EEXIST;
3514                 if (d_is_dir(nd->path.dentry))
3515                         return -EISDIR;
3516                 error = may_create_in_sticky(mnt_userns, nd,
3517                                              d_backing_inode(nd->path.dentry));
3518                 if (unlikely(error))
3519                         return error;
3520         }
3521         if ((nd->flags & LOOKUP_DIRECTORY) && !d_can_lookup(nd->path.dentry))
3522                 return -ENOTDIR;
3523
3524         do_truncate = false;
3525         acc_mode = op->acc_mode;
3526         if (file->f_mode & FMODE_CREATED) {
3527                 /* Don't check for write permission, don't truncate */
3528                 open_flag &= ~O_TRUNC;
3529                 acc_mode = 0;
3530         } else if (d_is_reg(nd->path.dentry) && open_flag & O_TRUNC) {
3531                 error = mnt_want_write(nd->path.mnt);
3532                 if (error)
3533                         return error;
3534                 do_truncate = true;
3535         }
3536         error = may_open(mnt_userns, &nd->path, acc_mode, open_flag);
3537         if (!error && !(file->f_mode & FMODE_OPENED))
3538                 error = vfs_open(&nd->path, file);
3539         if (!error)
3540                 error = ima_file_check(file, op->acc_mode);
3541         if (!error && do_truncate)
3542                 error = handle_truncate(mnt_userns, file);
3543         if (unlikely(error > 0)) {
3544                 WARN_ON(1);
3545                 error = -EINVAL;
3546         }
3547         if (do_truncate)
3548                 mnt_drop_write(nd->path.mnt);
3549         return error;
3550 }
3551
3552 /**
3553  * vfs_tmpfile - create tmpfile
3554  * @mnt_userns: user namespace of the mount the inode was found from
3555  * @dentry:     pointer to dentry of the base directory
3556  * @mode:       mode of the new tmpfile
3557  * @open_flag:  flags
3558  *
3559  * Create a temporary file.
3560  *
3561  * If the inode has been found through an idmapped mount the user namespace of
3562  * the vfsmount must be passed through @mnt_userns. This function will then take
3563  * care to map the inode according to @mnt_userns before checking permissions.
3564  * On non-idmapped mounts or if permission checking is to be performed on the
3565  * raw inode simply passs init_user_ns.
3566  */
3567 struct dentry *vfs_tmpfile(struct user_namespace *mnt_userns,
3568                            struct dentry *dentry, umode_t mode, int open_flag)
3569 {
3570         struct dentry *child = NULL;
3571         struct inode *dir = dentry->d_inode;
3572         struct inode *inode;
3573         int error;
3574
3575         /* we want directory to be writable */
3576         error = inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
3577         if (error)
3578                 goto out_err;
3579         error = -EOPNOTSUPP;
3580         if (!dir->i_op->tmpfile)
3581                 goto out_err;
3582         error = -ENOMEM;
3583         child = d_alloc(dentry, &slash_name);
3584         if (unlikely(!child))
3585                 goto out_err;
3586         mode = vfs_prepare_mode(mnt_userns, dir, mode, mode, mode);
3587         error = dir->i_op->tmpfile(mnt_userns, dir, child, mode);
3588         if (error)
3589                 goto out_err;
3590         error = -ENOENT;
3591         inode = child->d_inode;
3592         if (unlikely(!inode))
3593                 goto out_err;
3594         if (!(open_flag & O_EXCL)) {
3595                 spin_lock(&inode->i_lock);
3596                 inode->i_state |= I_LINKABLE;
3597                 spin_unlock(&inode->i_lock);
3598         }
3599         ima_post_create_tmpfile(mnt_userns, inode);
3600         return child;
3601
3602 out_err:
3603         dput(child);
3604         return ERR_PTR(error);
3605 }
3606 EXPORT_SYMBOL(vfs_tmpfile);
3607
3608 static int do_tmpfile(struct nameidata *nd, unsigned flags,
3609                 const struct open_flags *op,
3610                 struct file *file)
3611 {
3612         struct user_namespace *mnt_userns;
3613         struct dentry *child;
3614         struct path path;
3615         int error = path_lookupat(nd, flags | LOOKUP_DIRECTORY, &path);
3616         if (unlikely(error))
3617                 return error;
3618         error = mnt_want_write(path.mnt);
3619         if (unlikely(error))
3620                 goto out;
3621         mnt_userns = mnt_user_ns(path.mnt);
3622         child = vfs_tmpfile(mnt_userns, path.dentry, op->mode, op->open_flag);
3623         error = PTR_ERR(child);
3624         if (IS_ERR(child))
3625                 goto out2;
3626         dput(path.dentry);
3627         path.dentry = child;
3628         audit_inode(nd->name, child, 0);
3629         /* Don't check for other permissions, the inode was just created */
3630         error = may_open(mnt_userns, &path, 0, op->open_flag);
3631         if (!error)
3632                 error = vfs_open(&path, file);
3633 out2:
3634         mnt_drop_write(path.mnt);
3635 out:
3636         path_put(&path);
3637         return error;
3638 }
3639
3640 static int do_o_path(struct nameidata *nd, unsigned flags, struct file *file)
3641 {
3642         struct path path;
3643         int error = path_lookupat(nd, flags, &path);
3644         if (!error) {
3645                 audit_inode(nd->name, path.dentry, 0);
3646                 error = vfs_open(&path, file);
3647                 path_put(&path);
3648         }
3649         return error;
3650 }
3651
3652 static struct file *path_openat(struct nameidata *nd,
3653                         const struct open_flags *op, unsigned flags)
3654 {
3655         struct file *file;
3656         int error;
3657
3658         file = alloc_empty_file(op->open_flag, current_cred());
3659         if (IS_ERR(file))
3660                 return file;
3661
3662         if (unlikely(file->f_flags & __O_TMPFILE)) {
3663                 error = do_tmpfile(nd, flags, op, file);
3664         } else if (unlikely(file->f_flags & O_PATH)) {
3665                 error = do_o_path(nd, flags, file);
3666         } else {
3667                 const char *s = path_init(nd, flags);
3668                 while (!(error = link_path_walk(s, nd)) &&
3669                        (s = open_last_lookups(nd, file, op)) != NULL)
3670                         ;
3671                 if (!error)
3672                         error = do_open(nd, file, op);
3673                 terminate_walk(nd);
3674         }
3675         if (likely(!error)) {
3676                 if (likely(file->f_mode & FMODE_OPENED))
3677                         return file;
3678                 WARN_ON(1);
3679                 error = -EINVAL;
3680         }
3681         fput(file);
3682         if (error == -EOPENSTALE) {
3683                 if (flags & LOOKUP_RCU)
3684                         error = -ECHILD;
3685                 else
3686                         error = -ESTALE;
3687         }
3688         return ERR_PTR(error);
3689 }
3690
3691 struct file *do_filp_open(int dfd, struct filename *pathname,
3692                 const struct open_flags *op)
3693 {
3694         struct nameidata nd;
3695         int flags = op->lookup_flags;
3696         struct file *filp;
3697
3698         set_nameidata(&nd, dfd, pathname, NULL);
3699         filp = path_openat(&nd, op, flags | LOOKUP_RCU);
3700         if (unlikely(filp == ERR_PTR(-ECHILD)))
3701                 filp = path_openat(&nd, op, flags);
3702         if (unlikely(filp == ERR_PTR(-ESTALE)))
3703                 filp = path_openat(&nd, op, flags | LOOKUP_REVAL);
3704         restore_nameidata();
3705         return filp;
3706 }
3707
3708 struct file *do_file_open_root(const struct path *root,
3709                 const char *name, const struct open_flags *op)
3710 {
3711         struct nameidata nd;
3712         struct file *file;
3713         struct filename *filename;
3714         int flags = op->lookup_flags;
3715
3716         if (d_is_symlink(root->dentry) && op->intent & LOOKUP_OPEN)
3717                 return ERR_PTR(-ELOOP);
3718
3719         filename = getname_kernel(name);
3720         if (IS_ERR(filename))
3721                 return ERR_CAST(filename);
3722
3723         set_nameidata(&nd, -1, filename, root);
3724         file = path_openat(&nd, op, flags | LOOKUP_RCU);
3725         if (unlikely(file == ERR_PTR(-ECHILD)))
3726                 file = path_openat(&nd, op, flags);
3727         if (unlikely(file == ERR_PTR(-ESTALE)))
3728                 file = path_openat(&nd, op, flags | LOOKUP_REVAL);
3729         restore_nameidata();
3730         putname(filename);
3731         return file;
3732 }
3733
3734 static struct dentry *filename_create(int dfd, struct filename *name,
3735                                       struct path *path, unsigned int lookup_flags)
3736 {
3737         struct dentry *dentry = ERR_PTR(-EEXIST);
3738         struct qstr last;
3739         bool want_dir = lookup_flags & LOOKUP_DIRECTORY;
3740         unsigned int reval_flag = lookup_flags & LOOKUP_REVAL;
3741         unsigned int create_flags = LOOKUP_CREATE | LOOKUP_EXCL;
3742         int type;
3743         int err2;
3744         int error;
3745
3746         error = filename_parentat(dfd, name, reval_flag, path, &last, &type);
3747         if (error)
3748                 return ERR_PTR(error);
3749
3750         /*
3751          * Yucky last component or no last component at all?
3752          * (foo/., foo/.., /////)
3753          */
3754         if (unlikely(type != LAST_NORM))
3755                 goto out;
3756
3757         /* don't fail immediately if it's r/o, at least try to report other errors */
3758         err2 = mnt_want_write(path->mnt);
3759         /*
3760          * Do the final lookup.  Suppress 'create' if there is a trailing
3761          * '/', and a directory wasn't requested.
3762          */
3763         if (last.name[last.len] && !want_dir)
3764                 create_flags = 0;
3765         inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
3766         dentry = __lookup_hash(&last, path->dentry, reval_flag | create_flags);
3767         if (IS_ERR(dentry))
3768                 goto unlock;
3769
3770         error = -EEXIST;
3771         if (d_is_positive(dentry))
3772                 goto fail;
3773
3774         /*
3775          * Special case - lookup gave negative, but... we had foo/bar/
3776          * From the vfs_mknod() POV we just have a negative dentry -
3777          * all is fine. Let's be bastards - you had / on the end, you've
3778          * been asking for (non-existent) directory. -ENOENT for you.
3779          */
3780         if (unlikely(!create_flags)) {
3781                 error = -ENOENT;
3782                 goto fail;
3783         }
3784         if (unlikely(err2)) {
3785                 error = err2;
3786                 goto fail;
3787         }
3788         return dentry;
3789 fail:
3790         dput(dentry);
3791         dentry = ERR_PTR(error);
3792 unlock:
3793         inode_unlock(path->dentry->d_inode);
3794         if (!err2)
3795                 mnt_drop_write(path->mnt);
3796 out:
3797         path_put(path);
3798         return dentry;
3799 }
3800
3801 struct dentry *kern_path_create(int dfd, const char *pathname,
3802                                 struct path *path, unsigned int lookup_flags)
3803 {
3804         struct filename *filename = getname_kernel(pathname);
3805         struct dentry *res = filename_create(dfd, filename, path, lookup_flags);
3806
3807         putname(filename);
3808         return res;
3809 }
3810 EXPORT_SYMBOL(kern_path_create);
3811
3812 void done_path_create(struct path *path, struct dentry *dentry)
3813 {
3814         dput(dentry);
3815         inode_unlock(path->dentry->d_inode);
3816         mnt_drop_write(path->mnt);
3817         path_put(path);
3818 }
3819 EXPORT_SYMBOL(done_path_create);
3820
3821 inline struct dentry *user_path_create(int dfd, const char __user *pathname,
3822                                 struct path *path, unsigned int lookup_flags)
3823 {
3824         struct filename *filename = getname(pathname);
3825         struct dentry *res = filename_create(dfd, filename, path, lookup_flags);
3826
3827         putname(filename);
3828         return res;
3829 }
3830 EXPORT_SYMBOL(user_path_create);
3831
3832 /**
3833  * vfs_mknod - create device node or file
3834  * @mnt_userns: user namespace of the mount the inode was found from
3835  * @dir:        inode of @dentry
3836  * @dentry:     pointer to dentry of the base directory
3837  * @mode:       mode of the new device node or file
3838  * @dev:        device number of device to create
3839  *
3840  * Create a device node or file.
3841  *
3842  * If the inode has been found through an idmapped mount the user namespace of
3843  * the vfsmount must be passed through @mnt_userns. This function will then take
3844  * care to map the inode according to @mnt_userns before checking permissions.
3845  * On non-idmapped mounts or if permission checking is to be performed on the
3846  * raw inode simply passs init_user_ns.
3847  */
3848 int vfs_mknod(struct user_namespace *mnt_userns, struct inode *dir,
3849               struct dentry *dentry, umode_t mode, dev_t dev)
3850 {
3851         bool is_whiteout = S_ISCHR(mode) && dev == WHITEOUT_DEV;
3852         int error = may_create(mnt_userns, dir, dentry);
3853
3854         if (error)
3855                 return error;
3856
3857         if ((S_ISCHR(mode) || S_ISBLK(mode)) && !is_whiteout &&
3858             !capable(CAP_MKNOD))
3859                 return -EPERM;
3860
3861         if (!dir->i_op->mknod)
3862                 return -EPERM;
3863
3864         mode = vfs_prepare_mode(mnt_userns, dir, mode, mode, mode);
3865         error = devcgroup_inode_mknod(mode, dev);
3866         if (error)
3867                 return error;
3868
3869         error = security_inode_mknod(dir, dentry, mode, dev);
3870         if (error)
3871                 return error;
3872
3873         error = dir->i_op->mknod(mnt_userns, dir, dentry, mode, dev);
3874         if (!error)
3875                 fsnotify_create(dir, dentry);
3876         return error;
3877 }
3878 EXPORT_SYMBOL(vfs_mknod);
3879
3880 static int may_mknod(umode_t mode)
3881 {
3882         switch (mode & S_IFMT) {
3883         case S_IFREG:
3884         case S_IFCHR:
3885         case S_IFBLK:
3886         case S_IFIFO:
3887         case S_IFSOCK:
3888         case 0: /* zero mode translates to S_IFREG */
3889                 return 0;
3890         case S_IFDIR:
3891                 return -EPERM;
3892         default:
3893                 return -EINVAL;
3894         }
3895 }
3896
3897 static int do_mknodat(int dfd, struct filename *name, umode_t mode,
3898                 unsigned int dev)
3899 {
3900         struct user_namespace *mnt_userns;
3901         struct dentry *dentry;
3902         struct path path;
3903         int error;
3904         unsigned int lookup_flags = 0;
3905
3906         error = may_mknod(mode);
3907         if (error)
3908                 goto out1;
3909 retry:
3910         dentry = filename_create(dfd, name, &path, lookup_flags);
3911         error = PTR_ERR(dentry);
3912         if (IS_ERR(dentry))
3913                 goto out1;
3914
3915         error = security_path_mknod(&path, dentry,
3916                         mode_strip_umask(path.dentry->d_inode, mode), dev);
3917         if (error)
3918                 goto out2;
3919
3920         mnt_userns = mnt_user_ns(path.mnt);
3921         switch (mode & S_IFMT) {
3922                 case 0: case S_IFREG:
3923                         error = vfs_create(mnt_userns, path.dentry->d_inode,
3924                                            dentry, mode, true);
3925                         if (!error)
3926                                 ima_post_path_mknod(mnt_userns, dentry);
3927                         break;
3928                 case S_IFCHR: case S_IFBLK:
3929                         error = vfs_mknod(mnt_userns, path.dentry->d_inode,
3930                                           dentry, mode, new_decode_dev(dev));
3931                         break;
3932                 case S_IFIFO: case S_IFSOCK:
3933                         error = vfs_mknod(mnt_userns, path.dentry->d_inode,
3934                                           dentry, mode, 0);
3935                         break;
3936         }
3937 out2:
3938         done_path_create(&path, dentry);
3939         if (retry_estale(error, lookup_flags)) {
3940                 lookup_flags |= LOOKUP_REVAL;
3941                 goto retry;
3942         }
3943 out1:
3944         putname(name);
3945         return error;
3946 }
3947
3948 SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, umode_t, mode,
3949                 unsigned int, dev)
3950 {
3951         return do_mknodat(dfd, getname(filename), mode, dev);
3952 }
3953
3954 SYSCALL_DEFINE3(mknod, const char __user *, filename, umode_t, mode, unsigned, dev)
3955 {
3956         return do_mknodat(AT_FDCWD, getname(filename), mode, dev);
3957 }
3958
3959 /**
3960  * vfs_mkdir - create directory
3961  * @mnt_userns: user namespace of the mount the inode was found from
3962  * @dir:        inode of @dentry
3963  * @dentry:     pointer to dentry of the base directory
3964  * @mode:       mode of the new directory
3965  *
3966  * Create a directory.
3967  *
3968  * If the inode has been found through an idmapped mount the user namespace of
3969  * the vfsmount must be passed through @mnt_userns. This function will then take
3970  * care to map the inode according to @mnt_userns before checking permissions.
3971  * On non-idmapped mounts or if permission checking is to be performed on the
3972  * raw inode simply passs init_user_ns.
3973  */
3974 int vfs_mkdir(struct user_namespace *mnt_userns, struct inode *dir,
3975               struct dentry *dentry, umode_t mode)
3976 {
3977         int error = may_create(mnt_userns, dir, dentry);
3978         unsigned max_links = dir->i_sb->s_max_links;
3979
3980         if (error)
3981                 return error;
3982
3983         if (!dir->i_op->mkdir)
3984                 return -EPERM;
3985
3986         mode = vfs_prepare_mode(mnt_userns, dir, mode, S_IRWXUGO | S_ISVTX, 0);
3987         error = security_inode_mkdir(dir, dentry, mode);
3988         if (error)
3989                 return error;
3990
3991         if (max_links && dir->i_nlink >= max_links)
3992                 return -EMLINK;
3993
3994         error = dir->i_op->mkdir(mnt_userns, dir, dentry, mode);
3995         if (!error)
3996                 fsnotify_mkdir(dir, dentry);
3997         return error;
3998 }
3999 EXPORT_SYMBOL(vfs_mkdir);
4000
4001 int do_mkdirat(int dfd, struct filename *name, umode_t mode)
4002 {
4003         struct dentry *dentry;
4004         struct path path;
4005         int error;
4006         unsigned int lookup_flags = LOOKUP_DIRECTORY;
4007
4008 retry:
4009         dentry = filename_create(dfd, name, &path, lookup_flags);
4010         error = PTR_ERR(dentry);
4011         if (IS_ERR(dentry))
4012                 goto out_putname;
4013
4014         error = security_path_mkdir(&path, dentry,
4015                         mode_strip_umask(path.dentry->d_inode, mode));
4016         if (!error) {
4017                 struct user_namespace *mnt_userns;
4018                 mnt_userns = mnt_user_ns(path.mnt);
4019                 error = vfs_mkdir(mnt_userns, path.dentry->d_inode, dentry,
4020                                   mode);
4021         }
4022         done_path_create(&path, dentry);
4023         if (retry_estale(error, lookup_flags)) {
4024                 lookup_flags |= LOOKUP_REVAL;
4025                 goto retry;
4026         }
4027 out_putname:
4028         putname(name);
4029         return error;
4030 }
4031
4032 SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, umode_t, mode)
4033 {
4034         return do_mkdirat(dfd, getname(pathname), mode);
4035 }
4036
4037 SYSCALL_DEFINE2(mkdir, const char __user *, pathname, umode_t, mode)
4038 {
4039         return do_mkdirat(AT_FDCWD, getname(pathname), mode);
4040 }
4041
4042 /**
4043  * vfs_rmdir - remove directory
4044  * @mnt_userns: user namespace of the mount the inode was found from
4045  * @dir:        inode of @dentry
4046  * @dentry:     pointer to dentry of the base directory
4047  *
4048  * Remove a directory.
4049  *
4050  * If the inode has been found through an idmapped mount the user namespace of
4051  * the vfsmount must be passed through @mnt_userns. This function will then take
4052  * care to map the inode according to @mnt_userns before checking permissions.
4053  * On non-idmapped mounts or if permission checking is to be performed on the
4054  * raw inode simply passs init_user_ns.
4055  */
4056 int vfs_rmdir(struct user_namespace *mnt_userns, struct inode *dir,
4057                      struct dentry *dentry)
4058 {
4059         int error = may_delete(mnt_userns, dir, dentry, 1);
4060
4061         if (error)
4062                 return error;
4063
4064         if (!dir->i_op->rmdir)
4065                 return -EPERM;
4066
4067         dget(dentry);
4068         inode_lock(dentry->d_inode);
4069
4070         error = -EBUSY;
4071         if (is_local_mountpoint(dentry))
4072                 goto out;
4073
4074         error = security_inode_rmdir(dir, dentry);
4075         if (error)
4076                 goto out;
4077
4078         error = dir->i_op->rmdir(dir, dentry);
4079         if (error)
4080                 goto out;
4081
4082         shrink_dcache_parent(dentry);
4083         dentry->d_inode->i_flags |= S_DEAD;
4084         dont_mount(dentry);
4085         detach_mounts(dentry);
4086
4087 out:
4088         inode_unlock(dentry->d_inode);
4089         dput(dentry);
4090         if (!error)
4091                 d_delete_notify(dir, dentry);
4092         return error;
4093 }
4094 EXPORT_SYMBOL(vfs_rmdir);
4095
4096 int do_rmdir(int dfd, struct filename *name)
4097 {
4098         struct user_namespace *mnt_userns;
4099         int error;
4100         struct dentry *dentry;
4101         struct path path;
4102         struct qstr last;
4103         int type;
4104         unsigned int lookup_flags = 0;
4105 retry:
4106         error = filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
4107         if (error)
4108                 goto exit1;
4109
4110         switch (type) {
4111         case LAST_DOTDOT:
4112                 error = -ENOTEMPTY;
4113                 goto exit2;
4114         case LAST_DOT:
4115                 error = -EINVAL;
4116                 goto exit2;
4117         case LAST_ROOT:
4118                 error = -EBUSY;
4119                 goto exit2;
4120         }
4121
4122         error = mnt_want_write(path.mnt);
4123         if (error)
4124                 goto exit2;
4125
4126         inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
4127         dentry = __lookup_hash(&last, path.dentry, lookup_flags);
4128         error = PTR_ERR(dentry);
4129         if (IS_ERR(dentry))
4130                 goto exit3;
4131         if (!dentry->d_inode) {
4132                 error = -ENOENT;
4133                 goto exit4;
4134         }
4135         error = security_path_rmdir(&path, dentry);
4136         if (error)
4137                 goto exit4;
4138         mnt_userns = mnt_user_ns(path.mnt);
4139         error = vfs_rmdir(mnt_userns, path.dentry->d_inode, dentry);
4140 exit4:
4141         dput(dentry);
4142 exit3:
4143         inode_unlock(path.dentry->d_inode);
4144         mnt_drop_write(path.mnt);
4145 exit2:
4146         path_put(&path);
4147         if (retry_estale(error, lookup_flags)) {
4148                 lookup_flags |= LOOKUP_REVAL;
4149                 goto retry;
4150         }
4151 exit1:
4152         putname(name);
4153         return error;
4154 }
4155
4156 SYSCALL_DEFINE1(rmdir, const char __user *, pathname)
4157 {
4158         return do_rmdir(AT_FDCWD, getname(pathname));
4159 }
4160
4161 /**
4162  * vfs_unlink - unlink a filesystem object
4163  * @mnt_userns: user namespace of the mount the inode was found from
4164  * @dir:        parent directory
4165  * @dentry:     victim
4166  * @delegated_inode: returns victim inode, if the inode is delegated.
4167  *
4168  * The caller must hold dir->i_mutex.
4169  *
4170  * If vfs_unlink discovers a delegation, it will return -EWOULDBLOCK and
4171  * return a reference to the inode in delegated_inode.  The caller
4172  * should then break the delegation on that inode and retry.  Because
4173  * breaking a delegation may take a long time, the caller should drop
4174  * dir->i_mutex before doing so.
4175  *
4176  * Alternatively, a caller may pass NULL for delegated_inode.  This may
4177  * be appropriate for callers that expect the underlying filesystem not
4178  * to be NFS exported.
4179  *
4180  * If the inode has been found through an idmapped mount the user namespace of
4181  * the vfsmount must be passed through @mnt_userns. This function will then take
4182  * care to map the inode according to @mnt_userns before checking permissions.
4183  * On non-idmapped mounts or if permission checking is to be performed on the
4184  * raw inode simply passs init_user_ns.
4185  */
4186 int vfs_unlink(struct user_namespace *mnt_userns, struct inode *dir,
4187                struct dentry *dentry, struct inode **delegated_inode)
4188 {
4189         struct inode *target = dentry->d_inode;
4190         int error = may_delete(mnt_userns, dir, dentry, 0);
4191
4192         if (error)
4193                 return error;
4194
4195         if (!dir->i_op->unlink)
4196                 return -EPERM;
4197
4198         inode_lock(target);
4199         if (IS_SWAPFILE(target))
4200                 error = -EPERM;
4201         else if (is_local_mountpoint(dentry))
4202                 error = -EBUSY;
4203         else {
4204                 error = security_inode_unlink(dir, dentry);
4205                 if (!error) {
4206                         error = try_break_deleg(target, delegated_inode);
4207                         if (error)
4208                                 goto out;
4209                         error = dir->i_op->unlink(dir, dentry);
4210                         if (!error) {
4211                                 dont_mount(dentry);
4212                                 detach_mounts(dentry);
4213                         }
4214                 }
4215         }
4216 out:
4217         inode_unlock(target);
4218
4219         /* We don't d_delete() NFS sillyrenamed files--they still exist. */
4220         if (!error && dentry->d_flags & DCACHE_NFSFS_RENAMED) {
4221                 fsnotify_unlink(dir, dentry);
4222         } else if (!error) {
4223                 fsnotify_link_count(target);
4224                 d_delete_notify(dir, dentry);
4225         }
4226
4227         return error;
4228 }
4229 EXPORT_SYMBOL(vfs_unlink);
4230
4231 /*
4232  * Make sure that the actual truncation of the file will occur outside its
4233  * directory's i_mutex.  Truncate can take a long time if there is a lot of
4234  * writeout happening, and we don't want to prevent access to the directory
4235  * while waiting on the I/O.
4236  */
4237 int do_unlinkat(int dfd, struct filename *name)
4238 {
4239         int error;
4240         struct dentry *dentry;
4241         struct path path;
4242         struct qstr last;
4243         int type;
4244         struct inode *inode = NULL;
4245         struct inode *delegated_inode = NULL;
4246         unsigned int lookup_flags = 0;
4247 retry:
4248         error = filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
4249         if (error)
4250                 goto exit1;
4251
4252         error = -EISDIR;
4253         if (type != LAST_NORM)
4254                 goto exit2;
4255
4256         error = mnt_want_write(path.mnt);
4257         if (error)
4258                 goto exit2;
4259 retry_deleg:
4260         inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
4261         dentry = __lookup_hash(&last, path.dentry, lookup_flags);
4262         error = PTR_ERR(dentry);
4263         if (!IS_ERR(dentry)) {
4264                 struct user_namespace *mnt_userns;
4265
4266                 /* Why not before? Because we want correct error value */
4267                 if (last.name[last.len])
4268                         goto slashes;
4269                 inode = dentry->d_inode;
4270                 if (d_is_negative(dentry))
4271                         goto slashes;
4272                 ihold(inode);
4273                 error = security_path_unlink(&path, dentry);
4274                 if (error)
4275                         goto exit3;
4276                 mnt_userns = mnt_user_ns(path.mnt);
4277                 error = vfs_unlink(mnt_userns, path.dentry->d_inode, dentry,
4278                                    &delegated_inode);
4279 exit3:
4280                 dput(dentry);
4281         }
4282         inode_unlock(path.dentry->d_inode);
4283         if (inode)
4284                 iput(inode);    /* truncate the inode here */
4285         inode = NULL;
4286         if (delegated_inode) {
4287                 error = break_deleg_wait(&delegated_inode);
4288                 if (!error)
4289                         goto retry_deleg;
4290         }
4291         mnt_drop_write(path.mnt);
4292 exit2:
4293         path_put(&path);
4294         if (retry_estale(error, lookup_flags)) {
4295                 lookup_flags |= LOOKUP_REVAL;
4296                 inode = NULL;
4297                 goto retry;
4298         }
4299 exit1:
4300         putname(name);
4301         return error;
4302
4303 slashes:
4304         if (d_is_negative(dentry))
4305                 error = -ENOENT;
4306         else if (d_is_dir(dentry))
4307                 error = -EISDIR;
4308         else
4309                 error = -ENOTDIR;
4310         goto exit3;
4311 }
4312
4313 SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag)
4314 {
4315         if ((flag & ~AT_REMOVEDIR) != 0)
4316                 return -EINVAL;
4317
4318         if (flag & AT_REMOVEDIR)
4319                 return do_rmdir(dfd, getname(pathname));
4320         return do_unlinkat(dfd, getname(pathname));
4321 }
4322
4323 SYSCALL_DEFINE1(unlink, const char __user *, pathname)
4324 {
4325         return do_unlinkat(AT_FDCWD, getname(pathname));
4326 }
4327
4328 /**
4329  * vfs_symlink - create symlink
4330  * @mnt_userns: user namespace of the mount the inode was found from
4331  * @dir:        inode of @dentry
4332  * @dentry:     pointer to dentry of the base directory
4333  * @oldname:    name of the file to link to
4334  *
4335  * Create a symlink.
4336  *
4337  * If the inode has been found through an idmapped mount the user namespace of
4338  * the vfsmount must be passed through @mnt_userns. This function will then take
4339  * care to map the inode according to @mnt_userns before checking permissions.
4340  * On non-idmapped mounts or if permission checking is to be performed on the
4341  * raw inode simply passs init_user_ns.
4342  */
4343 int vfs_symlink(struct user_namespace *mnt_userns, struct inode *dir,
4344                 struct dentry *dentry, const char *oldname)
4345 {
4346         int error = may_create(mnt_userns, dir, dentry);
4347
4348         if (error)
4349                 return error;
4350
4351         if (!dir->i_op->symlink)
4352                 return -EPERM;
4353
4354         error = security_inode_symlink(dir, dentry, oldname);
4355         if (error)
4356                 return error;
4357
4358         error = dir->i_op->symlink(mnt_userns, dir, dentry, oldname);
4359         if (!error)
4360                 fsnotify_create(dir, dentry);
4361         return error;
4362 }
4363 EXPORT_SYMBOL(vfs_symlink);
4364
4365 int do_symlinkat(struct filename *from, int newdfd, struct filename *to)
4366 {
4367         int error;
4368         struct dentry *dentry;
4369         struct path path;
4370         unsigned int lookup_flags = 0;
4371
4372         if (IS_ERR(from)) {
4373                 error = PTR_ERR(from);
4374                 goto out_putnames;
4375         }
4376 retry:
4377         dentry = filename_create(newdfd, to, &path, lookup_flags);
4378         error = PTR_ERR(dentry);
4379         if (IS_ERR(dentry))
4380                 goto out_putnames;
4381
4382         error = security_path_symlink(&path, dentry, from->name);
4383         if (!error) {
4384                 struct user_namespace *mnt_userns;
4385
4386                 mnt_userns = mnt_user_ns(path.mnt);
4387                 error = vfs_symlink(mnt_userns, path.dentry->d_inode, dentry,
4388                                     from->name);
4389         }
4390         done_path_create(&path, dentry);
4391         if (retry_estale(error, lookup_flags)) {
4392                 lookup_flags |= LOOKUP_REVAL;
4393                 goto retry;
4394         }
4395 out_putnames:
4396         putname(to);
4397         putname(from);
4398         return error;
4399 }
4400
4401 SYSCALL_DEFINE3(symlinkat, const char __user *, oldname,
4402                 int, newdfd, const char __user *, newname)
4403 {
4404         return do_symlinkat(getname(oldname), newdfd, getname(newname));
4405 }
4406
4407 SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname)
4408 {
4409         return do_symlinkat(getname(oldname), AT_FDCWD, getname(newname));
4410 }
4411
4412 /**
4413  * vfs_link - create a new link
4414  * @old_dentry: object to be linked
4415  * @mnt_userns: the user namespace of the mount
4416  * @dir:        new parent
4417  * @new_dentry: where to create the new link
4418  * @delegated_inode: returns inode needing a delegation break
4419  *
4420  * The caller must hold dir->i_mutex
4421  *
4422  * If vfs_link discovers a delegation on the to-be-linked file in need
4423  * of breaking, it will return -EWOULDBLOCK and return a reference to the
4424  * inode in delegated_inode.  The caller should then break the delegation
4425  * and retry.  Because breaking a delegation may take a long time, the
4426  * caller should drop the i_mutex before doing so.
4427  *
4428  * Alternatively, a caller may pass NULL for delegated_inode.  This may
4429  * be appropriate for callers that expect the underlying filesystem not
4430  * to be NFS exported.
4431  *
4432  * If the inode has been found through an idmapped mount the user namespace of
4433  * the vfsmount must be passed through @mnt_userns. This function will then take
4434  * care to map the inode according to @mnt_userns before checking permissions.
4435  * On non-idmapped mounts or if permission checking is to be performed on the
4436  * raw inode simply passs init_user_ns.
4437  */
4438 int vfs_link(struct dentry *old_dentry, struct user_namespace *mnt_userns,
4439              struct inode *dir, struct dentry *new_dentry,
4440              struct inode **delegated_inode)
4441 {
4442         struct inode *inode = old_dentry->d_inode;
4443         unsigned max_links = dir->i_sb->s_max_links;
4444         int error;
4445
4446         if (!inode)
4447                 return -ENOENT;
4448
4449         error = may_create(mnt_userns, dir, new_dentry);
4450         if (error)
4451                 return error;
4452
4453         if (dir->i_sb != inode->i_sb)
4454                 return -EXDEV;
4455
4456         /*
4457          * A link to an append-only or immutable file cannot be created.
4458          */
4459         if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
4460                 return -EPERM;
4461         /*
4462          * Updating the link count will likely cause i_uid and i_gid to
4463          * be writen back improperly if their true value is unknown to
4464          * the vfs.
4465          */
4466         if (HAS_UNMAPPED_ID(mnt_userns, inode))
4467                 return -EPERM;
4468         if (!dir->i_op->link)
4469                 return -EPERM;
4470         if (S_ISDIR(inode->i_mode))
4471                 return -EPERM;
4472
4473         error = security_inode_link(old_dentry, dir, new_dentry);
4474         if (error)
4475                 return error;
4476
4477         inode_lock(inode);
4478         /* Make sure we don't allow creating hardlink to an unlinked file */
4479         if (inode->i_nlink == 0 && !(inode->i_state & I_LINKABLE))
4480                 error =  -ENOENT;
4481         else if (max_links && inode->i_nlink >= max_links)
4482                 error = -EMLINK;
4483         else {
4484                 error = try_break_deleg(inode, delegated_inode);
4485                 if (!error)
4486                         error = dir->i_op->link(old_dentry, dir, new_dentry);
4487         }
4488
4489         if (!error && (inode->i_state & I_LINKABLE)) {
4490                 spin_lock(&inode->i_lock);
4491                 inode->i_state &= ~I_LINKABLE;
4492                 spin_unlock(&inode->i_lock);
4493         }
4494         inode_unlock(inode);
4495         if (!error)
4496                 fsnotify_link(dir, inode, new_dentry);
4497         return error;
4498 }
4499 EXPORT_SYMBOL(vfs_link);
4500
4501 /*
4502  * Hardlinks are often used in delicate situations.  We avoid
4503  * security-related surprises by not following symlinks on the
4504  * newname.  --KAB
4505  *
4506  * We don't follow them on the oldname either to be compatible
4507  * with linux 2.0, and to avoid hard-linking to directories
4508  * and other special files.  --ADM
4509  */
4510 int do_linkat(int olddfd, struct filename *old, int newdfd,
4511               struct filename *new, int flags)
4512 {
4513         struct user_namespace *mnt_userns;
4514         struct dentry *new_dentry;
4515         struct path old_path, new_path;
4516         struct inode *delegated_inode = NULL;
4517         int how = 0;
4518         int error;
4519
4520         if ((flags & ~(AT_SYMLINK_FOLLOW | AT_EMPTY_PATH)) != 0) {
4521                 error = -EINVAL;
4522                 goto out_putnames;
4523         }
4524         /*
4525          * To use null names we require CAP_DAC_READ_SEARCH
4526          * This ensures that not everyone will be able to create
4527          * handlink using the passed filedescriptor.
4528          */
4529         if (flags & AT_EMPTY_PATH && !capable(CAP_DAC_READ_SEARCH)) {
4530                 error = -ENOENT;
4531                 goto out_putnames;
4532         }
4533
4534         if (flags & AT_SYMLINK_FOLLOW)
4535                 how |= LOOKUP_FOLLOW;
4536 retry:
4537         error = filename_lookup(olddfd, old, how, &old_path, NULL);
4538         if (error)
4539                 goto out_putnames;
4540
4541         new_dentry = filename_create(newdfd, new, &new_path,
4542                                         (how & LOOKUP_REVAL));
4543         error = PTR_ERR(new_dentry);
4544         if (IS_ERR(new_dentry))
4545                 goto out_putpath;
4546
4547         error = -EXDEV;
4548         if (old_path.mnt != new_path.mnt)
4549                 goto out_dput;
4550         mnt_userns = mnt_user_ns(new_path.mnt);
4551         error = may_linkat(mnt_userns, &old_path);
4552         if (unlikely(error))
4553                 goto out_dput;
4554         error = security_path_link(old_path.dentry, &new_path, new_dentry);
4555         if (error)
4556                 goto out_dput;
4557         error = vfs_link(old_path.dentry, mnt_userns, new_path.dentry->d_inode,
4558                          new_dentry, &delegated_inode);
4559 out_dput:
4560         done_path_create(&new_path, new_dentry);
4561         if (delegated_inode) {
4562                 error = break_deleg_wait(&delegated_inode);
4563                 if (!error) {
4564                         path_put(&old_path);
4565                         goto retry;
4566                 }
4567         }
4568         if (retry_estale(error, how)) {
4569                 path_put(&old_path);
4570                 how |= LOOKUP_REVAL;
4571                 goto retry;
4572         }
4573 out_putpath:
4574         path_put(&old_path);
4575 out_putnames:
4576         putname(old);
4577         putname(new);
4578
4579         return error;
4580 }
4581
4582 SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname,
4583                 int, newdfd, const char __user *, newname, int, flags)
4584 {
4585         return do_linkat(olddfd, getname_uflags(oldname, flags),
4586                 newdfd, getname(newname), flags);
4587 }
4588
4589 SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname)
4590 {
4591         return do_linkat(AT_FDCWD, getname(oldname), AT_FDCWD, getname(newname), 0);
4592 }
4593
4594 /**
4595  * vfs_rename - rename a filesystem object
4596  * @rd:         pointer to &struct renamedata info
4597  *
4598  * The caller must hold multiple mutexes--see lock_rename()).
4599  *
4600  * If vfs_rename discovers a delegation in need of breaking at either
4601  * the source or destination, it will return -EWOULDBLOCK and return a
4602  * reference to the inode in delegated_inode.  The caller should then
4603  * break the delegation and retry.  Because breaking a delegation may
4604  * take a long time, the caller should drop all locks before doing
4605  * so.
4606  *
4607  * Alternatively, a caller may pass NULL for delegated_inode.  This may
4608  * be appropriate for callers that expect the underlying filesystem not
4609  * to be NFS exported.
4610  *
4611  * The worst of all namespace operations - renaming directory. "Perverted"
4612  * doesn't even start to describe it. Somebody in UCB had a heck of a trip...
4613  * Problems:
4614  *
4615  *      a) we can get into loop creation.
4616  *      b) race potential - two innocent renames can create a loop together.
4617  *         That's where 4.4 screws up. Current fix: serialization on
4618  *         sb->s_vfs_rename_mutex. We might be more accurate, but that's another
4619  *         story.
4620  *      c) we have to lock _four_ objects - parents and victim (if it exists),
4621  *         and source.
4622  *         And that - after we got ->i_mutex on parents (until then we don't know
4623  *         whether the target exists).  Solution: try to be smart with locking
4624  *         order for inodes.  We rely on the fact that tree topology may change
4625  *         only under ->s_vfs_rename_mutex _and_ that parent of the object we
4626  *         move will be locked.  Thus we can rank directories by the tree
4627  *         (ancestors first) and rank all non-directories after them.
4628  *         That works since everybody except rename does "lock parent, lookup,
4629  *         lock child" and rename is under ->s_vfs_rename_mutex.
4630  *         HOWEVER, it relies on the assumption that any object with ->lookup()
4631  *         has no more than 1 dentry.  If "hybrid" objects will ever appear,
4632  *         we'd better make sure that there's no link(2) for them.
4633  *      d) conversion from fhandle to dentry may come in the wrong moment - when
4634  *         we are removing the target. Solution: we will have to grab ->i_mutex
4635  *         in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on
4636  *         ->i_mutex on parents, which works but leads to some truly excessive
4637  *         locking].
4638  */
4639 int vfs_rename(struct renamedata *rd)
4640 {
4641         int error;
4642         struct inode *old_dir = rd->old_dir, *new_dir = rd->new_dir;
4643         struct dentry *old_dentry = rd->old_dentry;
4644         struct dentry *new_dentry = rd->new_dentry;
4645         struct inode **delegated_inode = rd->delegated_inode;
4646         unsigned int flags = rd->flags;
4647         bool is_dir = d_is_dir(old_dentry);
4648         struct inode *source = old_dentry->d_inode;
4649         struct inode *target = new_dentry->d_inode;
4650         bool new_is_dir = false;
4651         unsigned max_links = new_dir->i_sb->s_max_links;
4652         struct name_snapshot old_name;
4653
4654         if (source == target)
4655                 return 0;
4656
4657         error = may_delete(rd->old_mnt_userns, old_dir, old_dentry, is_dir);
4658         if (error)
4659                 return error;
4660
4661         if (!target) {
4662                 error = may_create(rd->new_mnt_userns, new_dir, new_dentry);
4663         } else {
4664                 new_is_dir = d_is_dir(new_dentry);
4665
4666                 if (!(flags & RENAME_EXCHANGE))
4667                         error = may_delete(rd->new_mnt_userns, new_dir,
4668                                            new_dentry, is_dir);
4669                 else
4670                         error = may_delete(rd->new_mnt_userns, new_dir,
4671                                            new_dentry, new_is_dir);
4672         }
4673         if (error)
4674                 return error;
4675
4676         if (!old_dir->i_op->rename)
4677                 return -EPERM;
4678
4679         /*
4680          * If we are going to change the parent - check write permissions,
4681          * we'll need to flip '..'.
4682          */
4683         if (new_dir != old_dir) {
4684                 if (is_dir) {
4685                         error = inode_permission(rd->old_mnt_userns, source,
4686                                                  MAY_WRITE);
4687                         if (error)
4688                                 return error;
4689                 }
4690                 if ((flags & RENAME_EXCHANGE) && new_is_dir) {
4691                         error = inode_permission(rd->new_mnt_userns, target,
4692                                                  MAY_WRITE);
4693                         if (error)
4694                                 return error;
4695                 }
4696         }
4697
4698         error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,
4699                                       flags);
4700         if (error)
4701                 return error;
4702
4703         take_dentry_name_snapshot(&old_name, old_dentry);
4704         dget(new_dentry);
4705         /*
4706          * Lock all moved children. Moved directories may need to change parent
4707          * pointer so they need the lock to prevent against concurrent
4708          * directory changes moving parent pointer. For regular files we've
4709          * historically always done this. The lockdep locking subclasses are
4710          * somewhat arbitrary but RENAME_EXCHANGE in particular can swap
4711          * regular files and directories so it's difficult to tell which
4712          * subclasses to use.
4713          */
4714         lock_two_inodes(source, target, I_MUTEX_NORMAL, I_MUTEX_NONDIR2);
4715
4716         error = -EPERM;
4717         if (IS_SWAPFILE(source) || (target && IS_SWAPFILE(target)))
4718                 goto out;
4719
4720         error = -EBUSY;
4721         if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
4722                 goto out;
4723
4724         if (max_links && new_dir != old_dir) {
4725                 error = -EMLINK;
4726                 if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)
4727                         goto out;
4728                 if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&
4729                     old_dir->i_nlink >= max_links)
4730                         goto out;
4731         }
4732         if (!is_dir) {
4733                 error = try_break_deleg(source, delegated_inode);
4734                 if (error)
4735                         goto out;
4736         }
4737         if (target && !new_is_dir) {
4738                 error = try_break_deleg(target, delegated_inode);
4739                 if (error)
4740                         goto out;
4741         }
4742         error = old_dir->i_op->rename(rd->new_mnt_userns, old_dir, old_dentry,
4743                                       new_dir, new_dentry, flags);
4744         if (error)
4745                 goto out;
4746
4747         if (!(flags & RENAME_EXCHANGE) && target) {
4748                 if (is_dir) {
4749                         shrink_dcache_parent(new_dentry);
4750                         target->i_flags |= S_DEAD;
4751                 }
4752                 dont_mount(new_dentry);
4753                 detach_mounts(new_dentry);
4754         }
4755         if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {
4756                 if (!(flags & RENAME_EXCHANGE))
4757                         d_move(old_dentry, new_dentry);
4758                 else
4759                         d_exchange(old_dentry, new_dentry);
4760         }
4761 out:
4762         inode_unlock(source);
4763         if (target)
4764                 inode_unlock(target);
4765         dput(new_dentry);
4766         if (!error) {
4767                 fsnotify_move(old_dir, new_dir, &old_name.name, is_dir,
4768                               !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);
4769                 if (flags & RENAME_EXCHANGE) {
4770                         fsnotify_move(new_dir, old_dir, &old_dentry->d_name,
4771                                       new_is_dir, NULL, new_dentry);
4772                 }
4773         }
4774         release_dentry_name_snapshot(&old_name);
4775
4776         return error;
4777 }
4778 EXPORT_SYMBOL(vfs_rename);
4779
4780 int do_renameat2(int olddfd, struct filename *from, int newdfd,
4781                  struct filename *to, unsigned int flags)
4782 {
4783         struct renamedata rd;
4784         struct dentry *old_dentry, *new_dentry;
4785         struct dentry *trap;
4786         struct path old_path, new_path;
4787         struct qstr old_last, new_last;
4788         int old_type, new_type;
4789         struct inode *delegated_inode = NULL;
4790         unsigned int lookup_flags = 0, target_flags = LOOKUP_RENAME_TARGET;
4791         bool should_retry = false;
4792         int error = -EINVAL;
4793
4794         if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
4795                 goto put_names;
4796
4797         if ((flags & (RENAME_NOREPLACE | RENAME_WHITEOUT)) &&
4798             (flags & RENAME_EXCHANGE))
4799                 goto put_names;
4800
4801         if (flags & RENAME_EXCHANGE)
4802                 target_flags = 0;
4803
4804 retry:
4805         error = filename_parentat(olddfd, from, lookup_flags, &old_path,
4806                                   &old_last, &old_type);
4807         if (error)
4808                 goto put_names;
4809
4810         error = filename_parentat(newdfd, to, lookup_flags, &new_path, &new_last,
4811                                   &new_type);
4812         if (error)
4813                 goto exit1;
4814
4815         error = -EXDEV;
4816         if (old_path.mnt != new_path.mnt)
4817                 goto exit2;
4818
4819         error = -EBUSY;
4820         if (old_type != LAST_NORM)
4821                 goto exit2;
4822
4823         if (flags & RENAME_NOREPLACE)
4824                 error = -EEXIST;
4825         if (new_type != LAST_NORM)
4826                 goto exit2;
4827
4828         error = mnt_want_write(old_path.mnt);
4829         if (error)
4830                 goto exit2;
4831
4832 retry_deleg:
4833         trap = lock_rename(new_path.dentry, old_path.dentry);
4834
4835         old_dentry = __lookup_hash(&old_last, old_path.dentry, lookup_flags);
4836         error = PTR_ERR(old_dentry);
4837         if (IS_ERR(old_dentry))
4838                 goto exit3;
4839         /* source must exist */
4840         error = -ENOENT;
4841         if (d_is_negative(old_dentry))
4842                 goto exit4;
4843         new_dentry = __lookup_hash(&new_last, new_path.dentry, lookup_flags | target_flags);
4844         error = PTR_ERR(new_dentry);
4845         if (IS_ERR(new_dentry))
4846                 goto exit4;
4847         error = -EEXIST;
4848         if ((flags & RENAME_NOREPLACE) && d_is_positive(new_dentry))
4849                 goto exit5;
4850         if (flags & RENAME_EXCHANGE) {
4851                 error = -ENOENT;
4852                 if (d_is_negative(new_dentry))
4853                         goto exit5;
4854
4855                 if (!d_is_dir(new_dentry)) {
4856                         error = -ENOTDIR;
4857                         if (new_last.name[new_last.len])
4858                                 goto exit5;
4859                 }
4860         }
4861         /* unless the source is a directory trailing slashes give -ENOTDIR */
4862         if (!d_is_dir(old_dentry)) {
4863                 error = -ENOTDIR;
4864                 if (old_last.name[old_last.len])
4865                         goto exit5;
4866                 if (!(flags & RENAME_EXCHANGE) && new_last.name[new_last.len])
4867                         goto exit5;
4868         }
4869         /* source should not be ancestor of target */
4870         error = -EINVAL;
4871         if (old_dentry == trap)
4872                 goto exit5;
4873         /* target should not be an ancestor of source */
4874         if (!(flags & RENAME_EXCHANGE))
4875                 error = -ENOTEMPTY;
4876         if (new_dentry == trap)
4877                 goto exit5;
4878
4879         error = security_path_rename(&old_path, old_dentry,
4880                                      &new_path, new_dentry, flags);
4881         if (error)
4882                 goto exit5;
4883
4884         rd.old_dir         = old_path.dentry->d_inode;
4885         rd.old_dentry      = old_dentry;
4886         rd.old_mnt_userns  = mnt_user_ns(old_path.mnt);
4887         rd.new_dir         = new_path.dentry->d_inode;
4888         rd.new_dentry      = new_dentry;
4889         rd.new_mnt_userns  = mnt_user_ns(new_path.mnt);
4890         rd.delegated_inode = &delegated_inode;
4891         rd.flags           = flags;
4892         error = vfs_rename(&rd);
4893 exit5:
4894         dput(new_dentry);
4895 exit4:
4896         dput(old_dentry);
4897 exit3:
4898         unlock_rename(new_path.dentry, old_path.dentry);
4899         if (delegated_inode) {
4900                 error = break_deleg_wait(&delegated_inode);
4901                 if (!error)
4902                         goto retry_deleg;
4903         }
4904         mnt_drop_write(old_path.mnt);
4905 exit2:
4906         if (retry_estale(error, lookup_flags))
4907                 should_retry = true;
4908         path_put(&new_path);
4909 exit1:
4910         path_put(&old_path);
4911         if (should_retry) {
4912                 should_retry = false;
4913                 lookup_flags |= LOOKUP_REVAL;
4914                 goto retry;
4915         }
4916 put_names:
4917         putname(from);
4918         putname(to);
4919         return error;
4920 }
4921
4922 SYSCALL_DEFINE5(renameat2, int, olddfd, const char __user *, oldname,
4923                 int, newdfd, const char __user *, newname, unsigned int, flags)
4924 {
4925         return do_renameat2(olddfd, getname(oldname), newdfd, getname(newname),
4926                                 flags);
4927 }
4928
4929 SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname,
4930                 int, newdfd, const char __user *, newname)
4931 {
4932         return do_renameat2(olddfd, getname(oldname), newdfd, getname(newname),
4933                                 0);
4934 }
4935
4936 SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname)
4937 {
4938         return do_renameat2(AT_FDCWD, getname(oldname), AT_FDCWD,
4939                                 getname(newname), 0);
4940 }
4941
4942 int readlink_copy(char __user *buffer, int buflen, const char *link)
4943 {
4944         int len = PTR_ERR(link);
4945         if (IS_ERR(link))
4946                 goto out;
4947
4948         len = strlen(link);
4949         if (len > (unsigned) buflen)
4950                 len = buflen;
4951         if (copy_to_user(buffer, link, len))
4952                 len = -EFAULT;
4953 out:
4954         return len;
4955 }
4956
4957 /**
4958  * vfs_readlink - copy symlink body into userspace buffer
4959  * @dentry: dentry on which to get symbolic link
4960  * @buffer: user memory pointer
4961  * @buflen: size of buffer
4962  *
4963  * Does not touch atime.  That's up to the caller if necessary
4964  *
4965  * Does not call security hook.
4966  */
4967 int vfs_readlink(struct dentry *dentry, char __user *buffer, int buflen)
4968 {
4969         struct inode *inode = d_inode(dentry);
4970         DEFINE_DELAYED_CALL(done);
4971         const char *link;
4972         int res;
4973
4974         if (unlikely(!(inode->i_opflags & IOP_DEFAULT_READLINK))) {
4975                 if (unlikely(inode->i_op->readlink))
4976                         return inode->i_op->readlink(dentry, buffer, buflen);
4977
4978                 if (!d_is_symlink(dentry))
4979                         return -EINVAL;
4980
4981                 spin_lock(&inode->i_lock);
4982                 inode->i_opflags |= IOP_DEFAULT_READLINK;
4983                 spin_unlock(&inode->i_lock);
4984         }
4985
4986         link = READ_ONCE(inode->i_link);
4987         if (!link) {
4988                 link = inode->i_op->get_link(dentry, inode, &done);
4989                 if (IS_ERR(link))
4990                         return PTR_ERR(link);
4991         }
4992         res = readlink_copy(buffer, buflen, link);
4993         do_delayed_call(&done);
4994         return res;
4995 }
4996 EXPORT_SYMBOL(vfs_readlink);
4997
4998 /**
4999  * vfs_get_link - get symlink body
5000  * @dentry: dentry on which to get symbolic link
5001  * @done: caller needs to free returned data with this
5002  *
5003  * Calls security hook and i_op->get_link() on the supplied inode.
5004  *
5005  * It does not touch atime.  That's up to the caller if necessary.
5006  *
5007  * Does not work on "special" symlinks like /proc/$$/fd/N
5008  */
5009 const char *vfs_get_link(struct dentry *dentry, struct delayed_call *done)
5010 {
5011         const char *res = ERR_PTR(-EINVAL);
5012         struct inode *inode = d_inode(dentry);
5013
5014         if (d_is_symlink(dentry)) {
5015                 res = ERR_PTR(security_inode_readlink(dentry));
5016                 if (!res)
5017                         res = inode->i_op->get_link(dentry, inode, done);
5018         }
5019         return res;
5020 }
5021 EXPORT_SYMBOL(vfs_get_link);
5022
5023 /* get the link contents into pagecache */
5024 const char *page_get_link(struct dentry *dentry, struct inode *inode,
5025                           struct delayed_call *callback)
5026 {
5027         char *kaddr;
5028         struct page *page;
5029         struct address_space *mapping = inode->i_mapping;
5030
5031         if (!dentry) {
5032                 page = find_get_page(mapping, 0);
5033                 if (!page)
5034                         return ERR_PTR(-ECHILD);
5035                 if (!PageUptodate(page)) {
5036                         put_page(page);
5037                         return ERR_PTR(-ECHILD);
5038                 }
5039         } else {
5040                 page = read_mapping_page(mapping, 0, NULL);
5041                 if (IS_ERR(page))
5042                         return (char*)page;
5043         }
5044         set_delayed_call(callback, page_put_link, page);
5045         BUG_ON(mapping_gfp_mask(mapping) & __GFP_HIGHMEM);
5046         kaddr = page_address(page);
5047         nd_terminate_link(kaddr, inode->i_size, PAGE_SIZE - 1);
5048         return kaddr;
5049 }
5050
5051 EXPORT_SYMBOL(page_get_link);
5052
5053 void page_put_link(void *arg)
5054 {
5055         put_page(arg);
5056 }
5057 EXPORT_SYMBOL(page_put_link);
5058
5059 int page_readlink(struct dentry *dentry, char __user *buffer, int buflen)
5060 {
5061         DEFINE_DELAYED_CALL(done);
5062         int res = readlink_copy(buffer, buflen,
5063                                 page_get_link(dentry, d_inode(dentry),
5064                                               &done));
5065         do_delayed_call(&done);
5066         return res;
5067 }
5068 EXPORT_SYMBOL(page_readlink);
5069
5070 /*
5071  * The nofs argument instructs pagecache_write_begin to pass AOP_FLAG_NOFS
5072  */
5073 int __page_symlink(struct inode *inode, const char *symname, int len, int nofs)
5074 {
5075         struct address_space *mapping = inode->i_mapping;
5076         struct page *page;
5077         void *fsdata = NULL;
5078         int err;
5079         unsigned int flags = 0;
5080         if (nofs)
5081                 flags |= AOP_FLAG_NOFS;
5082
5083 retry:
5084         err = pagecache_write_begin(NULL, mapping, 0, len-1,
5085                                 flags, &page, &fsdata);
5086         if (err)
5087                 goto fail;
5088
5089         memcpy(page_address(page), symname, len-1);
5090
5091         err = pagecache_write_end(NULL, mapping, 0, len-1, len-1,
5092                                                         page, fsdata);
5093         if (err < 0)
5094                 goto fail;
5095         if (err < len-1)
5096                 goto retry;
5097
5098         mark_inode_dirty(inode);
5099         return 0;
5100 fail:
5101         return err;
5102 }
5103 EXPORT_SYMBOL(__page_symlink);
5104
5105 int page_symlink(struct inode *inode, const char *symname, int len)
5106 {
5107         return __page_symlink(inode, symname, len,
5108                         !mapping_gfp_constraint(inode->i_mapping, __GFP_FS));
5109 }
5110 EXPORT_SYMBOL(page_symlink);
5111
5112 const struct inode_operations page_symlink_inode_operations = {
5113         .get_link       = page_get_link,
5114 };
5115 EXPORT_SYMBOL(page_symlink_inode_operations);