Merge tag 'for-5.15/io_uring-vfs-2021-08-30' of git://git.kernel.dk/linux-block
[linux-2.6-microblaze.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_OR_NULL(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                                 continue;
1465                         }
1466                         if (read_seqretry(&mount_lock, nd->m_seq))
1467                                 return false;
1468                 }
1469                 return !(flags & DCACHE_NEED_AUTOMOUNT);
1470         }
1471 }
1472
1473 static inline int handle_mounts(struct nameidata *nd, struct dentry *dentry,
1474                           struct path *path, struct inode **inode,
1475                           unsigned int *seqp)
1476 {
1477         bool jumped;
1478         int ret;
1479
1480         path->mnt = nd->path.mnt;
1481         path->dentry = dentry;
1482         if (nd->flags & LOOKUP_RCU) {
1483                 unsigned int seq = *seqp;
1484                 if (unlikely(!*inode))
1485                         return -ENOENT;
1486                 if (likely(__follow_mount_rcu(nd, path, inode, seqp)))
1487                         return 0;
1488                 if (!try_to_unlazy_next(nd, dentry, seq))
1489                         return -ECHILD;
1490                 // *path might've been clobbered by __follow_mount_rcu()
1491                 path->mnt = nd->path.mnt;
1492                 path->dentry = dentry;
1493         }
1494         ret = traverse_mounts(path, &jumped, &nd->total_link_count, nd->flags);
1495         if (jumped) {
1496                 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1497                         ret = -EXDEV;
1498                 else
1499                         nd->state |= ND_JUMPED;
1500         }
1501         if (unlikely(ret)) {
1502                 dput(path->dentry);
1503                 if (path->mnt != nd->path.mnt)
1504                         mntput(path->mnt);
1505         } else {
1506                 *inode = d_backing_inode(path->dentry);
1507                 *seqp = 0; /* out of RCU mode, so the value doesn't matter */
1508         }
1509         return ret;
1510 }
1511
1512 /*
1513  * This looks up the name in dcache and possibly revalidates the found dentry.
1514  * NULL is returned if the dentry does not exist in the cache.
1515  */
1516 static struct dentry *lookup_dcache(const struct qstr *name,
1517                                     struct dentry *dir,
1518                                     unsigned int flags)
1519 {
1520         struct dentry *dentry = d_lookup(dir, name);
1521         if (dentry) {
1522                 int error = d_revalidate(dentry, flags);
1523                 if (unlikely(error <= 0)) {
1524                         if (!error)
1525                                 d_invalidate(dentry);
1526                         dput(dentry);
1527                         return ERR_PTR(error);
1528                 }
1529         }
1530         return dentry;
1531 }
1532
1533 /*
1534  * Parent directory has inode locked exclusive.  This is one
1535  * and only case when ->lookup() gets called on non in-lookup
1536  * dentries - as the matter of fact, this only gets called
1537  * when directory is guaranteed to have no in-lookup children
1538  * at all.
1539  */
1540 static struct dentry *__lookup_hash(const struct qstr *name,
1541                 struct dentry *base, unsigned int flags)
1542 {
1543         struct dentry *dentry = lookup_dcache(name, base, flags);
1544         struct dentry *old;
1545         struct inode *dir = base->d_inode;
1546
1547         if (dentry)
1548                 return dentry;
1549
1550         /* Don't create child dentry for a dead directory. */
1551         if (unlikely(IS_DEADDIR(dir)))
1552                 return ERR_PTR(-ENOENT);
1553
1554         dentry = d_alloc(base, name);
1555         if (unlikely(!dentry))
1556                 return ERR_PTR(-ENOMEM);
1557
1558         old = dir->i_op->lookup(dir, dentry, flags);
1559         if (unlikely(old)) {
1560                 dput(dentry);
1561                 dentry = old;
1562         }
1563         return dentry;
1564 }
1565
1566 static struct dentry *lookup_fast(struct nameidata *nd,
1567                                   struct inode **inode,
1568                                   unsigned *seqp)
1569 {
1570         struct dentry *dentry, *parent = nd->path.dentry;
1571         int status = 1;
1572
1573         /*
1574          * Rename seqlock is not required here because in the off chance
1575          * of a false negative due to a concurrent rename, the caller is
1576          * going to fall back to non-racy lookup.
1577          */
1578         if (nd->flags & LOOKUP_RCU) {
1579                 unsigned seq;
1580                 dentry = __d_lookup_rcu(parent, &nd->last, &seq);
1581                 if (unlikely(!dentry)) {
1582                         if (!try_to_unlazy(nd))
1583                                 return ERR_PTR(-ECHILD);
1584                         return NULL;
1585                 }
1586
1587                 /*
1588                  * This sequence count validates that the inode matches
1589                  * the dentry name information from lookup.
1590                  */
1591                 *inode = d_backing_inode(dentry);
1592                 if (unlikely(read_seqcount_retry(&dentry->d_seq, seq)))
1593                         return ERR_PTR(-ECHILD);
1594
1595                 /*
1596                  * This sequence count validates that the parent had no
1597                  * changes while we did the lookup of the dentry above.
1598                  *
1599                  * The memory barrier in read_seqcount_begin of child is
1600                  *  enough, we can use __read_seqcount_retry here.
1601                  */
1602                 if (unlikely(__read_seqcount_retry(&parent->d_seq, nd->seq)))
1603                         return ERR_PTR(-ECHILD);
1604
1605                 *seqp = seq;
1606                 status = d_revalidate(dentry, nd->flags);
1607                 if (likely(status > 0))
1608                         return dentry;
1609                 if (!try_to_unlazy_next(nd, dentry, seq))
1610                         return ERR_PTR(-ECHILD);
1611                 if (status == -ECHILD)
1612                         /* we'd been told to redo it in non-rcu mode */
1613                         status = d_revalidate(dentry, nd->flags);
1614         } else {
1615                 dentry = __d_lookup(parent, &nd->last);
1616                 if (unlikely(!dentry))
1617                         return NULL;
1618                 status = d_revalidate(dentry, nd->flags);
1619         }
1620         if (unlikely(status <= 0)) {
1621                 if (!status)
1622                         d_invalidate(dentry);
1623                 dput(dentry);
1624                 return ERR_PTR(status);
1625         }
1626         return dentry;
1627 }
1628
1629 /* Fast lookup failed, do it the slow way */
1630 static struct dentry *__lookup_slow(const struct qstr *name,
1631                                     struct dentry *dir,
1632                                     unsigned int flags)
1633 {
1634         struct dentry *dentry, *old;
1635         struct inode *inode = dir->d_inode;
1636         DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
1637
1638         /* Don't go there if it's already dead */
1639         if (unlikely(IS_DEADDIR(inode)))
1640                 return ERR_PTR(-ENOENT);
1641 again:
1642         dentry = d_alloc_parallel(dir, name, &wq);
1643         if (IS_ERR(dentry))
1644                 return dentry;
1645         if (unlikely(!d_in_lookup(dentry))) {
1646                 int error = d_revalidate(dentry, flags);
1647                 if (unlikely(error <= 0)) {
1648                         if (!error) {
1649                                 d_invalidate(dentry);
1650                                 dput(dentry);
1651                                 goto again;
1652                         }
1653                         dput(dentry);
1654                         dentry = ERR_PTR(error);
1655                 }
1656         } else {
1657                 old = inode->i_op->lookup(inode, dentry, flags);
1658                 d_lookup_done(dentry);
1659                 if (unlikely(old)) {
1660                         dput(dentry);
1661                         dentry = old;
1662                 }
1663         }
1664         return dentry;
1665 }
1666
1667 static struct dentry *lookup_slow(const struct qstr *name,
1668                                   struct dentry *dir,
1669                                   unsigned int flags)
1670 {
1671         struct inode *inode = dir->d_inode;
1672         struct dentry *res;
1673         inode_lock_shared(inode);
1674         res = __lookup_slow(name, dir, flags);
1675         inode_unlock_shared(inode);
1676         return res;
1677 }
1678
1679 static inline int may_lookup(struct user_namespace *mnt_userns,
1680                              struct nameidata *nd)
1681 {
1682         if (nd->flags & LOOKUP_RCU) {
1683                 int err = inode_permission(mnt_userns, nd->inode, MAY_EXEC|MAY_NOT_BLOCK);
1684                 if (err != -ECHILD || !try_to_unlazy(nd))
1685                         return err;
1686         }
1687         return inode_permission(mnt_userns, nd->inode, MAY_EXEC);
1688 }
1689
1690 static int reserve_stack(struct nameidata *nd, struct path *link, unsigned seq)
1691 {
1692         if (unlikely(nd->total_link_count++ >= MAXSYMLINKS))
1693                 return -ELOOP;
1694
1695         if (likely(nd->depth != EMBEDDED_LEVELS))
1696                 return 0;
1697         if (likely(nd->stack != nd->internal))
1698                 return 0;
1699         if (likely(nd_alloc_stack(nd)))
1700                 return 0;
1701
1702         if (nd->flags & LOOKUP_RCU) {
1703                 // we need to grab link before we do unlazy.  And we can't skip
1704                 // unlazy even if we fail to grab the link - cleanup needs it
1705                 bool grabbed_link = legitimize_path(nd, link, seq);
1706
1707                 if (!try_to_unlazy(nd) != 0 || !grabbed_link)
1708                         return -ECHILD;
1709
1710                 if (nd_alloc_stack(nd))
1711                         return 0;
1712         }
1713         return -ENOMEM;
1714 }
1715
1716 enum {WALK_TRAILING = 1, WALK_MORE = 2, WALK_NOFOLLOW = 4};
1717
1718 static const char *pick_link(struct nameidata *nd, struct path *link,
1719                      struct inode *inode, unsigned seq, int flags)
1720 {
1721         struct saved *last;
1722         const char *res;
1723         int error = reserve_stack(nd, link, seq);
1724
1725         if (unlikely(error)) {
1726                 if (!(nd->flags & LOOKUP_RCU))
1727                         path_put(link);
1728                 return ERR_PTR(error);
1729         }
1730         last = nd->stack + nd->depth++;
1731         last->link = *link;
1732         clear_delayed_call(&last->done);
1733         last->seq = seq;
1734
1735         if (flags & WALK_TRAILING) {
1736                 error = may_follow_link(nd, inode);
1737                 if (unlikely(error))
1738                         return ERR_PTR(error);
1739         }
1740
1741         if (unlikely(nd->flags & LOOKUP_NO_SYMLINKS) ||
1742                         unlikely(link->mnt->mnt_flags & MNT_NOSYMFOLLOW))
1743                 return ERR_PTR(-ELOOP);
1744
1745         if (!(nd->flags & LOOKUP_RCU)) {
1746                 touch_atime(&last->link);
1747                 cond_resched();
1748         } else if (atime_needs_update(&last->link, inode)) {
1749                 if (!try_to_unlazy(nd))
1750                         return ERR_PTR(-ECHILD);
1751                 touch_atime(&last->link);
1752         }
1753
1754         error = security_inode_follow_link(link->dentry, inode,
1755                                            nd->flags & LOOKUP_RCU);
1756         if (unlikely(error))
1757                 return ERR_PTR(error);
1758
1759         res = READ_ONCE(inode->i_link);
1760         if (!res) {
1761                 const char * (*get)(struct dentry *, struct inode *,
1762                                 struct delayed_call *);
1763                 get = inode->i_op->get_link;
1764                 if (nd->flags & LOOKUP_RCU) {
1765                         res = get(NULL, inode, &last->done);
1766                         if (res == ERR_PTR(-ECHILD) && try_to_unlazy(nd))
1767                                 res = get(link->dentry, inode, &last->done);
1768                 } else {
1769                         res = get(link->dentry, inode, &last->done);
1770                 }
1771                 if (!res)
1772                         goto all_done;
1773                 if (IS_ERR(res))
1774                         return res;
1775         }
1776         if (*res == '/') {
1777                 error = nd_jump_root(nd);
1778                 if (unlikely(error))
1779                         return ERR_PTR(error);
1780                 while (unlikely(*++res == '/'))
1781                         ;
1782         }
1783         if (*res)
1784                 return res;
1785 all_done: // pure jump
1786         put_link(nd);
1787         return NULL;
1788 }
1789
1790 /*
1791  * Do we need to follow links? We _really_ want to be able
1792  * to do this check without having to look at inode->i_op,
1793  * so we keep a cache of "no, this doesn't need follow_link"
1794  * for the common case.
1795  */
1796 static const char *step_into(struct nameidata *nd, int flags,
1797                      struct dentry *dentry, struct inode *inode, unsigned seq)
1798 {
1799         struct path path;
1800         int err = handle_mounts(nd, dentry, &path, &inode, &seq);
1801
1802         if (err < 0)
1803                 return ERR_PTR(err);
1804         if (likely(!d_is_symlink(path.dentry)) ||
1805            ((flags & WALK_TRAILING) && !(nd->flags & LOOKUP_FOLLOW)) ||
1806            (flags & WALK_NOFOLLOW)) {
1807                 /* not a symlink or should not follow */
1808                 if (!(nd->flags & LOOKUP_RCU)) {
1809                         dput(nd->path.dentry);
1810                         if (nd->path.mnt != path.mnt)
1811                                 mntput(nd->path.mnt);
1812                 }
1813                 nd->path = path;
1814                 nd->inode = inode;
1815                 nd->seq = seq;
1816                 return NULL;
1817         }
1818         if (nd->flags & LOOKUP_RCU) {
1819                 /* make sure that d_is_symlink above matches inode */
1820                 if (read_seqcount_retry(&path.dentry->d_seq, seq))
1821                         return ERR_PTR(-ECHILD);
1822         } else {
1823                 if (path.mnt == nd->path.mnt)
1824                         mntget(path.mnt);
1825         }
1826         return pick_link(nd, &path, inode, seq, flags);
1827 }
1828
1829 static struct dentry *follow_dotdot_rcu(struct nameidata *nd,
1830                                         struct inode **inodep,
1831                                         unsigned *seqp)
1832 {
1833         struct dentry *parent, *old;
1834
1835         if (path_equal(&nd->path, &nd->root))
1836                 goto in_root;
1837         if (unlikely(nd->path.dentry == nd->path.mnt->mnt_root)) {
1838                 struct path path;
1839                 unsigned seq;
1840                 if (!choose_mountpoint_rcu(real_mount(nd->path.mnt),
1841                                            &nd->root, &path, &seq))
1842                         goto in_root;
1843                 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1844                         return ERR_PTR(-ECHILD);
1845                 nd->path = path;
1846                 nd->inode = path.dentry->d_inode;
1847                 nd->seq = seq;
1848                 if (unlikely(read_seqretry(&mount_lock, nd->m_seq)))
1849                         return ERR_PTR(-ECHILD);
1850                 /* we know that mountpoint was pinned */
1851         }
1852         old = nd->path.dentry;
1853         parent = old->d_parent;
1854         *inodep = parent->d_inode;
1855         *seqp = read_seqcount_begin(&parent->d_seq);
1856         if (unlikely(read_seqcount_retry(&old->d_seq, nd->seq)))
1857                 return ERR_PTR(-ECHILD);
1858         if (unlikely(!path_connected(nd->path.mnt, parent)))
1859                 return ERR_PTR(-ECHILD);
1860         return parent;
1861 in_root:
1862         if (unlikely(read_seqretry(&mount_lock, nd->m_seq)))
1863                 return ERR_PTR(-ECHILD);
1864         if (unlikely(nd->flags & LOOKUP_BENEATH))
1865                 return ERR_PTR(-ECHILD);
1866         return NULL;
1867 }
1868
1869 static struct dentry *follow_dotdot(struct nameidata *nd,
1870                                  struct inode **inodep,
1871                                  unsigned *seqp)
1872 {
1873         struct dentry *parent;
1874
1875         if (path_equal(&nd->path, &nd->root))
1876                 goto in_root;
1877         if (unlikely(nd->path.dentry == nd->path.mnt->mnt_root)) {
1878                 struct path path;
1879
1880                 if (!choose_mountpoint(real_mount(nd->path.mnt),
1881                                        &nd->root, &path))
1882                         goto in_root;
1883                 path_put(&nd->path);
1884                 nd->path = path;
1885                 nd->inode = path.dentry->d_inode;
1886                 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1887                         return ERR_PTR(-EXDEV);
1888         }
1889         /* rare case of legitimate dget_parent()... */
1890         parent = dget_parent(nd->path.dentry);
1891         if (unlikely(!path_connected(nd->path.mnt, parent))) {
1892                 dput(parent);
1893                 return ERR_PTR(-ENOENT);
1894         }
1895         *seqp = 0;
1896         *inodep = parent->d_inode;
1897         return parent;
1898
1899 in_root:
1900         if (unlikely(nd->flags & LOOKUP_BENEATH))
1901                 return ERR_PTR(-EXDEV);
1902         dget(nd->path.dentry);
1903         return NULL;
1904 }
1905
1906 static const char *handle_dots(struct nameidata *nd, int type)
1907 {
1908         if (type == LAST_DOTDOT) {
1909                 const char *error = NULL;
1910                 struct dentry *parent;
1911                 struct inode *inode;
1912                 unsigned seq;
1913
1914                 if (!nd->root.mnt) {
1915                         error = ERR_PTR(set_root(nd));
1916                         if (error)
1917                                 return error;
1918                 }
1919                 if (nd->flags & LOOKUP_RCU)
1920                         parent = follow_dotdot_rcu(nd, &inode, &seq);
1921                 else
1922                         parent = follow_dotdot(nd, &inode, &seq);
1923                 if (IS_ERR(parent))
1924                         return ERR_CAST(parent);
1925                 if (unlikely(!parent))
1926                         error = step_into(nd, WALK_NOFOLLOW,
1927                                          nd->path.dentry, nd->inode, nd->seq);
1928                 else
1929                         error = step_into(nd, WALK_NOFOLLOW,
1930                                          parent, inode, seq);
1931                 if (unlikely(error))
1932                         return error;
1933
1934                 if (unlikely(nd->flags & LOOKUP_IS_SCOPED)) {
1935                         /*
1936                          * If there was a racing rename or mount along our
1937                          * path, then we can't be sure that ".." hasn't jumped
1938                          * above nd->root (and so userspace should retry or use
1939                          * some fallback).
1940                          */
1941                         smp_rmb();
1942                         if (unlikely(__read_seqcount_retry(&mount_lock.seqcount, nd->m_seq)))
1943                                 return ERR_PTR(-EAGAIN);
1944                         if (unlikely(__read_seqcount_retry(&rename_lock.seqcount, nd->r_seq)))
1945                                 return ERR_PTR(-EAGAIN);
1946                 }
1947         }
1948         return NULL;
1949 }
1950
1951 static const char *walk_component(struct nameidata *nd, int flags)
1952 {
1953         struct dentry *dentry;
1954         struct inode *inode;
1955         unsigned seq;
1956         /*
1957          * "." and ".." are special - ".." especially so because it has
1958          * to be able to know about the current root directory and
1959          * parent relationships.
1960          */
1961         if (unlikely(nd->last_type != LAST_NORM)) {
1962                 if (!(flags & WALK_MORE) && nd->depth)
1963                         put_link(nd);
1964                 return handle_dots(nd, nd->last_type);
1965         }
1966         dentry = lookup_fast(nd, &inode, &seq);
1967         if (IS_ERR(dentry))
1968                 return ERR_CAST(dentry);
1969         if (unlikely(!dentry)) {
1970                 dentry = lookup_slow(&nd->last, nd->path.dentry, nd->flags);
1971                 if (IS_ERR(dentry))
1972                         return ERR_CAST(dentry);
1973         }
1974         if (!(flags & WALK_MORE) && nd->depth)
1975                 put_link(nd);
1976         return step_into(nd, flags, dentry, inode, seq);
1977 }
1978
1979 /*
1980  * We can do the critical dentry name comparison and hashing
1981  * operations one word at a time, but we are limited to:
1982  *
1983  * - Architectures with fast unaligned word accesses. We could
1984  *   do a "get_unaligned()" if this helps and is sufficiently
1985  *   fast.
1986  *
1987  * - non-CONFIG_DEBUG_PAGEALLOC configurations (so that we
1988  *   do not trap on the (extremely unlikely) case of a page
1989  *   crossing operation.
1990  *
1991  * - Furthermore, we need an efficient 64-bit compile for the
1992  *   64-bit case in order to generate the "number of bytes in
1993  *   the final mask". Again, that could be replaced with a
1994  *   efficient population count instruction or similar.
1995  */
1996 #ifdef CONFIG_DCACHE_WORD_ACCESS
1997
1998 #include <asm/word-at-a-time.h>
1999
2000 #ifdef HASH_MIX
2001
2002 /* Architecture provides HASH_MIX and fold_hash() in <asm/hash.h> */
2003
2004 #elif defined(CONFIG_64BIT)
2005 /*
2006  * Register pressure in the mixing function is an issue, particularly
2007  * on 32-bit x86, but almost any function requires one state value and
2008  * one temporary.  Instead, use a function designed for two state values
2009  * and no temporaries.
2010  *
2011  * This function cannot create a collision in only two iterations, so
2012  * we have two iterations to achieve avalanche.  In those two iterations,
2013  * we have six layers of mixing, which is enough to spread one bit's
2014  * influence out to 2^6 = 64 state bits.
2015  *
2016  * Rotate constants are scored by considering either 64 one-bit input
2017  * deltas or 64*63/2 = 2016 two-bit input deltas, and finding the
2018  * probability of that delta causing a change to each of the 128 output
2019  * bits, using a sample of random initial states.
2020  *
2021  * The Shannon entropy of the computed probabilities is then summed
2022  * to produce a score.  Ideally, any input change has a 50% chance of
2023  * toggling any given output bit.
2024  *
2025  * Mixing scores (in bits) for (12,45):
2026  * Input delta: 1-bit      2-bit
2027  * 1 round:     713.3    42542.6
2028  * 2 rounds:   2753.7   140389.8
2029  * 3 rounds:   5954.1   233458.2
2030  * 4 rounds:   7862.6   256672.2
2031  * Perfect:    8192     258048
2032  *            (64*128) (64*63/2 * 128)
2033  */
2034 #define HASH_MIX(x, y, a)       \
2035         (       x ^= (a),       \
2036         y ^= x, x = rol64(x,12),\
2037         x += y, y = rol64(y,45),\
2038         y *= 9                  )
2039
2040 /*
2041  * Fold two longs into one 32-bit hash value.  This must be fast, but
2042  * latency isn't quite as critical, as there is a fair bit of additional
2043  * work done before the hash value is used.
2044  */
2045 static inline unsigned int fold_hash(unsigned long x, unsigned long y)
2046 {
2047         y ^= x * GOLDEN_RATIO_64;
2048         y *= GOLDEN_RATIO_64;
2049         return y >> 32;
2050 }
2051
2052 #else   /* 32-bit case */
2053
2054 /*
2055  * Mixing scores (in bits) for (7,20):
2056  * Input delta: 1-bit      2-bit
2057  * 1 round:     330.3     9201.6
2058  * 2 rounds:   1246.4    25475.4
2059  * 3 rounds:   1907.1    31295.1
2060  * 4 rounds:   2042.3    31718.6
2061  * Perfect:    2048      31744
2062  *            (32*64)   (32*31/2 * 64)
2063  */
2064 #define HASH_MIX(x, y, a)       \
2065         (       x ^= (a),       \
2066         y ^= x, x = rol32(x, 7),\
2067         x += y, y = rol32(y,20),\
2068         y *= 9                  )
2069
2070 static inline unsigned int fold_hash(unsigned long x, unsigned long y)
2071 {
2072         /* Use arch-optimized multiply if one exists */
2073         return __hash_32(y ^ __hash_32(x));
2074 }
2075
2076 #endif
2077
2078 /*
2079  * Return the hash of a string of known length.  This is carfully
2080  * designed to match hash_name(), which is the more critical function.
2081  * In particular, we must end by hashing a final word containing 0..7
2082  * payload bytes, to match the way that hash_name() iterates until it
2083  * finds the delimiter after the name.
2084  */
2085 unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
2086 {
2087         unsigned long a, x = 0, y = (unsigned long)salt;
2088
2089         for (;;) {
2090                 if (!len)
2091                         goto done;
2092                 a = load_unaligned_zeropad(name);
2093                 if (len < sizeof(unsigned long))
2094                         break;
2095                 HASH_MIX(x, y, a);
2096                 name += sizeof(unsigned long);
2097                 len -= sizeof(unsigned long);
2098         }
2099         x ^= a & bytemask_from_count(len);
2100 done:
2101         return fold_hash(x, y);
2102 }
2103 EXPORT_SYMBOL(full_name_hash);
2104
2105 /* Return the "hash_len" (hash and length) of a null-terminated string */
2106 u64 hashlen_string(const void *salt, const char *name)
2107 {
2108         unsigned long a = 0, x = 0, y = (unsigned long)salt;
2109         unsigned long adata, mask, len;
2110         const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2111
2112         len = 0;
2113         goto inside;
2114
2115         do {
2116                 HASH_MIX(x, y, a);
2117                 len += sizeof(unsigned long);
2118 inside:
2119                 a = load_unaligned_zeropad(name+len);
2120         } while (!has_zero(a, &adata, &constants));
2121
2122         adata = prep_zero_mask(a, adata, &constants);
2123         mask = create_zero_mask(adata);
2124         x ^= a & zero_bytemask(mask);
2125
2126         return hashlen_create(fold_hash(x, y), len + find_zero(mask));
2127 }
2128 EXPORT_SYMBOL(hashlen_string);
2129
2130 /*
2131  * Calculate the length and hash of the path component, and
2132  * return the "hash_len" as the result.
2133  */
2134 static inline u64 hash_name(const void *salt, const char *name)
2135 {
2136         unsigned long a = 0, b, x = 0, y = (unsigned long)salt;
2137         unsigned long adata, bdata, mask, len;
2138         const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2139
2140         len = 0;
2141         goto inside;
2142
2143         do {
2144                 HASH_MIX(x, y, a);
2145                 len += sizeof(unsigned long);
2146 inside:
2147                 a = load_unaligned_zeropad(name+len);
2148                 b = a ^ REPEAT_BYTE('/');
2149         } while (!(has_zero(a, &adata, &constants) | has_zero(b, &bdata, &constants)));
2150
2151         adata = prep_zero_mask(a, adata, &constants);
2152         bdata = prep_zero_mask(b, bdata, &constants);
2153         mask = create_zero_mask(adata | bdata);
2154         x ^= a & zero_bytemask(mask);
2155
2156         return hashlen_create(fold_hash(x, y), len + find_zero(mask));
2157 }
2158
2159 #else   /* !CONFIG_DCACHE_WORD_ACCESS: Slow, byte-at-a-time version */
2160
2161 /* Return the hash of a string of known length */
2162 unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
2163 {
2164         unsigned long hash = init_name_hash(salt);
2165         while (len--)
2166                 hash = partial_name_hash((unsigned char)*name++, hash);
2167         return end_name_hash(hash);
2168 }
2169 EXPORT_SYMBOL(full_name_hash);
2170
2171 /* Return the "hash_len" (hash and length) of a null-terminated string */
2172 u64 hashlen_string(const void *salt, const char *name)
2173 {
2174         unsigned long hash = init_name_hash(salt);
2175         unsigned long len = 0, c;
2176
2177         c = (unsigned char)*name;
2178         while (c) {
2179                 len++;
2180                 hash = partial_name_hash(c, hash);
2181                 c = (unsigned char)name[len];
2182         }
2183         return hashlen_create(end_name_hash(hash), len);
2184 }
2185 EXPORT_SYMBOL(hashlen_string);
2186
2187 /*
2188  * We know there's a real path component here of at least
2189  * one character.
2190  */
2191 static inline u64 hash_name(const void *salt, const char *name)
2192 {
2193         unsigned long hash = init_name_hash(salt);
2194         unsigned long len = 0, c;
2195
2196         c = (unsigned char)*name;
2197         do {
2198                 len++;
2199                 hash = partial_name_hash(c, hash);
2200                 c = (unsigned char)name[len];
2201         } while (c && c != '/');
2202         return hashlen_create(end_name_hash(hash), len);
2203 }
2204
2205 #endif
2206
2207 /*
2208  * Name resolution.
2209  * This is the basic name resolution function, turning a pathname into
2210  * the final dentry. We expect 'base' to be positive and a directory.
2211  *
2212  * Returns 0 and nd will have valid dentry and mnt on success.
2213  * Returns error and drops reference to input namei data on failure.
2214  */
2215 static int link_path_walk(const char *name, struct nameidata *nd)
2216 {
2217         int depth = 0; // depth <= nd->depth
2218         int err;
2219
2220         nd->last_type = LAST_ROOT;
2221         nd->flags |= LOOKUP_PARENT;
2222         if (IS_ERR(name))
2223                 return PTR_ERR(name);
2224         while (*name=='/')
2225                 name++;
2226         if (!*name) {
2227                 nd->dir_mode = 0; // short-circuit the 'hardening' idiocy
2228                 return 0;
2229         }
2230
2231         /* At this point we know we have a real path component. */
2232         for(;;) {
2233                 struct user_namespace *mnt_userns;
2234                 const char *link;
2235                 u64 hash_len;
2236                 int type;
2237
2238                 mnt_userns = mnt_user_ns(nd->path.mnt);
2239                 err = may_lookup(mnt_userns, nd);
2240                 if (err)
2241                         return err;
2242
2243                 hash_len = hash_name(nd->path.dentry, name);
2244
2245                 type = LAST_NORM;
2246                 if (name[0] == '.') switch (hashlen_len(hash_len)) {
2247                         case 2:
2248                                 if (name[1] == '.') {
2249                                         type = LAST_DOTDOT;
2250                                         nd->state |= ND_JUMPED;
2251                                 }
2252                                 break;
2253                         case 1:
2254                                 type = LAST_DOT;
2255                 }
2256                 if (likely(type == LAST_NORM)) {
2257                         struct dentry *parent = nd->path.dentry;
2258                         nd->state &= ~ND_JUMPED;
2259                         if (unlikely(parent->d_flags & DCACHE_OP_HASH)) {
2260                                 struct qstr this = { { .hash_len = hash_len }, .name = name };
2261                                 err = parent->d_op->d_hash(parent, &this);
2262                                 if (err < 0)
2263                                         return err;
2264                                 hash_len = this.hash_len;
2265                                 name = this.name;
2266                         }
2267                 }
2268
2269                 nd->last.hash_len = hash_len;
2270                 nd->last.name = name;
2271                 nd->last_type = type;
2272
2273                 name += hashlen_len(hash_len);
2274                 if (!*name)
2275                         goto OK;
2276                 /*
2277                  * If it wasn't NUL, we know it was '/'. Skip that
2278                  * slash, and continue until no more slashes.
2279                  */
2280                 do {
2281                         name++;
2282                 } while (unlikely(*name == '/'));
2283                 if (unlikely(!*name)) {
2284 OK:
2285                         /* pathname or trailing symlink, done */
2286                         if (!depth) {
2287                                 nd->dir_uid = i_uid_into_mnt(mnt_userns, nd->inode);
2288                                 nd->dir_mode = nd->inode->i_mode;
2289                                 nd->flags &= ~LOOKUP_PARENT;
2290                                 return 0;
2291                         }
2292                         /* last component of nested symlink */
2293                         name = nd->stack[--depth].name;
2294                         link = walk_component(nd, 0);
2295                 } else {
2296                         /* not the last component */
2297                         link = walk_component(nd, WALK_MORE);
2298                 }
2299                 if (unlikely(link)) {
2300                         if (IS_ERR(link))
2301                                 return PTR_ERR(link);
2302                         /* a symlink to follow */
2303                         nd->stack[depth++].name = name;
2304                         name = link;
2305                         continue;
2306                 }
2307                 if (unlikely(!d_can_lookup(nd->path.dentry))) {
2308                         if (nd->flags & LOOKUP_RCU) {
2309                                 if (!try_to_unlazy(nd))
2310                                         return -ECHILD;
2311                         }
2312                         return -ENOTDIR;
2313                 }
2314         }
2315 }
2316
2317 /* must be paired with terminate_walk() */
2318 static const char *path_init(struct nameidata *nd, unsigned flags)
2319 {
2320         int error;
2321         const char *s = nd->name->name;
2322
2323         /* LOOKUP_CACHED requires RCU, ask caller to retry */
2324         if ((flags & (LOOKUP_RCU | LOOKUP_CACHED)) == LOOKUP_CACHED)
2325                 return ERR_PTR(-EAGAIN);
2326
2327         if (!*s)
2328                 flags &= ~LOOKUP_RCU;
2329         if (flags & LOOKUP_RCU)
2330                 rcu_read_lock();
2331
2332         nd->flags = flags;
2333         nd->state |= ND_JUMPED;
2334
2335         nd->m_seq = __read_seqcount_begin(&mount_lock.seqcount);
2336         nd->r_seq = __read_seqcount_begin(&rename_lock.seqcount);
2337         smp_rmb();
2338
2339         if (nd->state & ND_ROOT_PRESET) {
2340                 struct dentry *root = nd->root.dentry;
2341                 struct inode *inode = root->d_inode;
2342                 if (*s && unlikely(!d_can_lookup(root)))
2343                         return ERR_PTR(-ENOTDIR);
2344                 nd->path = nd->root;
2345                 nd->inode = inode;
2346                 if (flags & LOOKUP_RCU) {
2347                         nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
2348                         nd->root_seq = nd->seq;
2349                 } else {
2350                         path_get(&nd->path);
2351                 }
2352                 return s;
2353         }
2354
2355         nd->root.mnt = NULL;
2356
2357         /* Absolute pathname -- fetch the root (LOOKUP_IN_ROOT uses nd->dfd). */
2358         if (*s == '/' && !(flags & LOOKUP_IN_ROOT)) {
2359                 error = nd_jump_root(nd);
2360                 if (unlikely(error))
2361                         return ERR_PTR(error);
2362                 return s;
2363         }
2364
2365         /* Relative pathname -- get the starting-point it is relative to. */
2366         if (nd->dfd == AT_FDCWD) {
2367                 if (flags & LOOKUP_RCU) {
2368                         struct fs_struct *fs = current->fs;
2369                         unsigned seq;
2370
2371                         do {
2372                                 seq = read_seqcount_begin(&fs->seq);
2373                                 nd->path = fs->pwd;
2374                                 nd->inode = nd->path.dentry->d_inode;
2375                                 nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
2376                         } while (read_seqcount_retry(&fs->seq, seq));
2377                 } else {
2378                         get_fs_pwd(current->fs, &nd->path);
2379                         nd->inode = nd->path.dentry->d_inode;
2380                 }
2381         } else {
2382                 /* Caller must check execute permissions on the starting path component */
2383                 struct fd f = fdget_raw(nd->dfd);
2384                 struct dentry *dentry;
2385
2386                 if (!f.file)
2387                         return ERR_PTR(-EBADF);
2388
2389                 dentry = f.file->f_path.dentry;
2390
2391                 if (*s && unlikely(!d_can_lookup(dentry))) {
2392                         fdput(f);
2393                         return ERR_PTR(-ENOTDIR);
2394                 }
2395
2396                 nd->path = f.file->f_path;
2397                 if (flags & LOOKUP_RCU) {
2398                         nd->inode = nd->path.dentry->d_inode;
2399                         nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
2400                 } else {
2401                         path_get(&nd->path);
2402                         nd->inode = nd->path.dentry->d_inode;
2403                 }
2404                 fdput(f);
2405         }
2406
2407         /* For scoped-lookups we need to set the root to the dirfd as well. */
2408         if (flags & LOOKUP_IS_SCOPED) {
2409                 nd->root = nd->path;
2410                 if (flags & LOOKUP_RCU) {
2411                         nd->root_seq = nd->seq;
2412                 } else {
2413                         path_get(&nd->root);
2414                         nd->state |= ND_ROOT_GRABBED;
2415                 }
2416         }
2417         return s;
2418 }
2419
2420 static inline const char *lookup_last(struct nameidata *nd)
2421 {
2422         if (nd->last_type == LAST_NORM && nd->last.name[nd->last.len])
2423                 nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
2424
2425         return walk_component(nd, WALK_TRAILING);
2426 }
2427
2428 static int handle_lookup_down(struct nameidata *nd)
2429 {
2430         if (!(nd->flags & LOOKUP_RCU))
2431                 dget(nd->path.dentry);
2432         return PTR_ERR(step_into(nd, WALK_NOFOLLOW,
2433                         nd->path.dentry, nd->inode, nd->seq));
2434 }
2435
2436 /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
2437 static int path_lookupat(struct nameidata *nd, unsigned flags, struct path *path)
2438 {
2439         const char *s = path_init(nd, flags);
2440         int err;
2441
2442         if (unlikely(flags & LOOKUP_DOWN) && !IS_ERR(s)) {
2443                 err = handle_lookup_down(nd);
2444                 if (unlikely(err < 0))
2445                         s = ERR_PTR(err);
2446         }
2447
2448         while (!(err = link_path_walk(s, nd)) &&
2449                (s = lookup_last(nd)) != NULL)
2450                 ;
2451         if (!err && unlikely(nd->flags & LOOKUP_MOUNTPOINT)) {
2452                 err = handle_lookup_down(nd);
2453                 nd->state &= ~ND_JUMPED; // no d_weak_revalidate(), please...
2454         }
2455         if (!err)
2456                 err = complete_walk(nd);
2457
2458         if (!err && nd->flags & LOOKUP_DIRECTORY)
2459                 if (!d_can_lookup(nd->path.dentry))
2460                         err = -ENOTDIR;
2461         if (!err) {
2462                 *path = nd->path;
2463                 nd->path.mnt = NULL;
2464                 nd->path.dentry = NULL;
2465         }
2466         terminate_walk(nd);
2467         return err;
2468 }
2469
2470 static int __filename_lookup(int dfd, struct filename *name, unsigned flags,
2471                     struct path *path, struct path *root)
2472 {
2473         int retval;
2474         struct nameidata nd;
2475         if (IS_ERR(name))
2476                 return PTR_ERR(name);
2477         set_nameidata(&nd, dfd, name, root);
2478         retval = path_lookupat(&nd, flags | LOOKUP_RCU, path);
2479         if (unlikely(retval == -ECHILD))
2480                 retval = path_lookupat(&nd, flags, path);
2481         if (unlikely(retval == -ESTALE))
2482                 retval = path_lookupat(&nd, flags | LOOKUP_REVAL, path);
2483
2484         if (likely(!retval))
2485                 audit_inode(name, path->dentry,
2486                             flags & LOOKUP_MOUNTPOINT ? AUDIT_INODE_NOEVAL : 0);
2487         restore_nameidata();
2488         return retval;
2489 }
2490
2491 int filename_lookup(int dfd, struct filename *name, unsigned flags,
2492                     struct path *path, struct path *root)
2493 {
2494         int retval = __filename_lookup(dfd, name, flags, path, root);
2495
2496         putname(name);
2497         return retval;
2498 }
2499
2500 /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
2501 static int path_parentat(struct nameidata *nd, unsigned flags,
2502                                 struct path *parent)
2503 {
2504         const char *s = path_init(nd, flags);
2505         int err = link_path_walk(s, nd);
2506         if (!err)
2507                 err = complete_walk(nd);
2508         if (!err) {
2509                 *parent = nd->path;
2510                 nd->path.mnt = NULL;
2511                 nd->path.dentry = NULL;
2512         }
2513         terminate_walk(nd);
2514         return err;
2515 }
2516
2517 static int __filename_parentat(int dfd, struct filename *name,
2518                                 unsigned int flags, struct path *parent,
2519                                 struct qstr *last, int *type)
2520 {
2521         int retval;
2522         struct nameidata nd;
2523
2524         if (IS_ERR(name))
2525                 return PTR_ERR(name);
2526         set_nameidata(&nd, dfd, name, NULL);
2527         retval = path_parentat(&nd, flags | LOOKUP_RCU, parent);
2528         if (unlikely(retval == -ECHILD))
2529                 retval = path_parentat(&nd, flags, parent);
2530         if (unlikely(retval == -ESTALE))
2531                 retval = path_parentat(&nd, flags | LOOKUP_REVAL, parent);
2532         if (likely(!retval)) {
2533                 *last = nd.last;
2534                 *type = nd.last_type;
2535                 audit_inode(name, parent->dentry, AUDIT_INODE_PARENT);
2536         }
2537         restore_nameidata();
2538         return retval;
2539 }
2540
2541 static int filename_parentat(int dfd, struct filename *name,
2542                                 unsigned int flags, struct path *parent,
2543                                 struct qstr *last, int *type)
2544 {
2545         int retval = __filename_parentat(dfd, name, flags, parent, last, type);
2546
2547         putname(name);
2548         return retval;
2549 }
2550
2551 /* does lookup, returns the object with parent locked */
2552 struct dentry *kern_path_locked(const char *name, struct path *path)
2553 {
2554         struct dentry *d;
2555         struct qstr last;
2556         int type, error;
2557
2558         error = filename_parentat(AT_FDCWD, getname_kernel(name), 0, path,
2559                                     &last, &type);
2560         if (error)
2561                 return ERR_PTR(error);
2562         if (unlikely(type != LAST_NORM)) {
2563                 path_put(path);
2564                 return ERR_PTR(-EINVAL);
2565         }
2566         inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
2567         d = __lookup_hash(&last, path->dentry, 0);
2568         if (IS_ERR(d)) {
2569                 inode_unlock(path->dentry->d_inode);
2570                 path_put(path);
2571         }
2572         return d;
2573 }
2574
2575 int kern_path(const char *name, unsigned int flags, struct path *path)
2576 {
2577         return filename_lookup(AT_FDCWD, getname_kernel(name),
2578                                flags, path, NULL);
2579 }
2580 EXPORT_SYMBOL(kern_path);
2581
2582 /**
2583  * vfs_path_lookup - lookup a file path relative to a dentry-vfsmount pair
2584  * @dentry:  pointer to dentry of the base directory
2585  * @mnt: pointer to vfs mount of the base directory
2586  * @name: pointer to file name
2587  * @flags: lookup flags
2588  * @path: pointer to struct path to fill
2589  */
2590 int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt,
2591                     const char *name, unsigned int flags,
2592                     struct path *path)
2593 {
2594         struct path root = {.mnt = mnt, .dentry = dentry};
2595         /* the first argument of filename_lookup() is ignored with root */
2596         return filename_lookup(AT_FDCWD, getname_kernel(name),
2597                                flags , path, &root);
2598 }
2599 EXPORT_SYMBOL(vfs_path_lookup);
2600
2601 static int lookup_one_len_common(const char *name, struct dentry *base,
2602                                  int len, struct qstr *this)
2603 {
2604         this->name = name;
2605         this->len = len;
2606         this->hash = full_name_hash(base, name, len);
2607         if (!len)
2608                 return -EACCES;
2609
2610         if (unlikely(name[0] == '.')) {
2611                 if (len < 2 || (len == 2 && name[1] == '.'))
2612                         return -EACCES;
2613         }
2614
2615         while (len--) {
2616                 unsigned int c = *(const unsigned char *)name++;
2617                 if (c == '/' || c == '\0')
2618                         return -EACCES;
2619         }
2620         /*
2621          * See if the low-level filesystem might want
2622          * to use its own hash..
2623          */
2624         if (base->d_flags & DCACHE_OP_HASH) {
2625                 int err = base->d_op->d_hash(base, this);
2626                 if (err < 0)
2627                         return err;
2628         }
2629
2630         return inode_permission(&init_user_ns, base->d_inode, MAY_EXEC);
2631 }
2632
2633 /**
2634  * try_lookup_one_len - filesystem helper to lookup single pathname component
2635  * @name:       pathname component to lookup
2636  * @base:       base directory to lookup from
2637  * @len:        maximum length @len should be interpreted to
2638  *
2639  * Look up a dentry by name in the dcache, returning NULL if it does not
2640  * currently exist.  The function does not try to create a dentry.
2641  *
2642  * Note that this routine is purely a helper for filesystem usage and should
2643  * not be called by generic code.
2644  *
2645  * The caller must hold base->i_mutex.
2646  */
2647 struct dentry *try_lookup_one_len(const char *name, struct dentry *base, int len)
2648 {
2649         struct qstr this;
2650         int err;
2651
2652         WARN_ON_ONCE(!inode_is_locked(base->d_inode));
2653
2654         err = lookup_one_len_common(name, base, len, &this);
2655         if (err)
2656                 return ERR_PTR(err);
2657
2658         return lookup_dcache(&this, base, 0);
2659 }
2660 EXPORT_SYMBOL(try_lookup_one_len);
2661
2662 /**
2663  * lookup_one_len - filesystem helper to lookup single pathname component
2664  * @name:       pathname component to lookup
2665  * @base:       base directory to lookup from
2666  * @len:        maximum length @len should be interpreted to
2667  *
2668  * Note that this routine is purely a helper for filesystem usage and should
2669  * not be called by generic code.
2670  *
2671  * The caller must hold base->i_mutex.
2672  */
2673 struct dentry *lookup_one_len(const char *name, struct dentry *base, int len)
2674 {
2675         struct dentry *dentry;
2676         struct qstr this;
2677         int err;
2678
2679         WARN_ON_ONCE(!inode_is_locked(base->d_inode));
2680
2681         err = lookup_one_len_common(name, base, len, &this);
2682         if (err)
2683                 return ERR_PTR(err);
2684
2685         dentry = lookup_dcache(&this, base, 0);
2686         return dentry ? dentry : __lookup_slow(&this, base, 0);
2687 }
2688 EXPORT_SYMBOL(lookup_one_len);
2689
2690 /**
2691  * lookup_one_len_unlocked - filesystem helper to lookup single pathname component
2692  * @name:       pathname component to lookup
2693  * @base:       base directory to lookup from
2694  * @len:        maximum length @len should be interpreted to
2695  *
2696  * Note that this routine is purely a helper for filesystem usage and should
2697  * not be called by generic code.
2698  *
2699  * Unlike lookup_one_len, it should be called without the parent
2700  * i_mutex held, and will take the i_mutex itself if necessary.
2701  */
2702 struct dentry *lookup_one_len_unlocked(const char *name,
2703                                        struct dentry *base, int len)
2704 {
2705         struct qstr this;
2706         int err;
2707         struct dentry *ret;
2708
2709         err = lookup_one_len_common(name, base, len, &this);
2710         if (err)
2711                 return ERR_PTR(err);
2712
2713         ret = lookup_dcache(&this, base, 0);
2714         if (!ret)
2715                 ret = lookup_slow(&this, base, 0);
2716         return ret;
2717 }
2718 EXPORT_SYMBOL(lookup_one_len_unlocked);
2719
2720 /*
2721  * Like lookup_one_len_unlocked(), except that it yields ERR_PTR(-ENOENT)
2722  * on negatives.  Returns known positive or ERR_PTR(); that's what
2723  * most of the users want.  Note that pinned negative with unlocked parent
2724  * _can_ become positive at any time, so callers of lookup_one_len_unlocked()
2725  * need to be very careful; pinned positives have ->d_inode stable, so
2726  * this one avoids such problems.
2727  */
2728 struct dentry *lookup_positive_unlocked(const char *name,
2729                                        struct dentry *base, int len)
2730 {
2731         struct dentry *ret = lookup_one_len_unlocked(name, base, len);
2732         if (!IS_ERR(ret) && d_flags_negative(smp_load_acquire(&ret->d_flags))) {
2733                 dput(ret);
2734                 ret = ERR_PTR(-ENOENT);
2735         }
2736         return ret;
2737 }
2738 EXPORT_SYMBOL(lookup_positive_unlocked);
2739
2740 #ifdef CONFIG_UNIX98_PTYS
2741 int path_pts(struct path *path)
2742 {
2743         /* Find something mounted on "pts" in the same directory as
2744          * the input path.
2745          */
2746         struct dentry *parent = dget_parent(path->dentry);
2747         struct dentry *child;
2748         struct qstr this = QSTR_INIT("pts", 3);
2749
2750         if (unlikely(!path_connected(path->mnt, parent))) {
2751                 dput(parent);
2752                 return -ENOENT;
2753         }
2754         dput(path->dentry);
2755         path->dentry = parent;
2756         child = d_hash_and_lookup(parent, &this);
2757         if (!child)
2758                 return -ENOENT;
2759
2760         path->dentry = child;
2761         dput(parent);
2762         follow_down(path);
2763         return 0;
2764 }
2765 #endif
2766
2767 int user_path_at_empty(int dfd, const char __user *name, unsigned flags,
2768                  struct path *path, int *empty)
2769 {
2770         return filename_lookup(dfd, getname_flags(name, flags, empty),
2771                                flags, path, NULL);
2772 }
2773 EXPORT_SYMBOL(user_path_at_empty);
2774
2775 int __check_sticky(struct user_namespace *mnt_userns, struct inode *dir,
2776                    struct inode *inode)
2777 {
2778         kuid_t fsuid = current_fsuid();
2779
2780         if (uid_eq(i_uid_into_mnt(mnt_userns, inode), fsuid))
2781                 return 0;
2782         if (uid_eq(i_uid_into_mnt(mnt_userns, dir), fsuid))
2783                 return 0;
2784         return !capable_wrt_inode_uidgid(mnt_userns, inode, CAP_FOWNER);
2785 }
2786 EXPORT_SYMBOL(__check_sticky);
2787
2788 /*
2789  *      Check whether we can remove a link victim from directory dir, check
2790  *  whether the type of victim is right.
2791  *  1. We can't do it if dir is read-only (done in permission())
2792  *  2. We should have write and exec permissions on dir
2793  *  3. We can't remove anything from append-only dir
2794  *  4. We can't do anything with immutable dir (done in permission())
2795  *  5. If the sticky bit on dir is set we should either
2796  *      a. be owner of dir, or
2797  *      b. be owner of victim, or
2798  *      c. have CAP_FOWNER capability
2799  *  6. If the victim is append-only or immutable we can't do antyhing with
2800  *     links pointing to it.
2801  *  7. If the victim has an unknown uid or gid we can't change the inode.
2802  *  8. If we were asked to remove a directory and victim isn't one - ENOTDIR.
2803  *  9. If we were asked to remove a non-directory and victim isn't one - EISDIR.
2804  * 10. We can't remove a root or mountpoint.
2805  * 11. We don't allow removal of NFS sillyrenamed files; it's handled by
2806  *     nfs_async_unlink().
2807  */
2808 static int may_delete(struct user_namespace *mnt_userns, struct inode *dir,
2809                       struct dentry *victim, bool isdir)
2810 {
2811         struct inode *inode = d_backing_inode(victim);
2812         int error;
2813
2814         if (d_is_negative(victim))
2815                 return -ENOENT;
2816         BUG_ON(!inode);
2817
2818         BUG_ON(victim->d_parent->d_inode != dir);
2819
2820         /* Inode writeback is not safe when the uid or gid are invalid. */
2821         if (!uid_valid(i_uid_into_mnt(mnt_userns, inode)) ||
2822             !gid_valid(i_gid_into_mnt(mnt_userns, inode)))
2823                 return -EOVERFLOW;
2824
2825         audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
2826
2827         error = inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
2828         if (error)
2829                 return error;
2830         if (IS_APPEND(dir))
2831                 return -EPERM;
2832
2833         if (check_sticky(mnt_userns, dir, inode) || IS_APPEND(inode) ||
2834             IS_IMMUTABLE(inode) || IS_SWAPFILE(inode) ||
2835             HAS_UNMAPPED_ID(mnt_userns, inode))
2836                 return -EPERM;
2837         if (isdir) {
2838                 if (!d_is_dir(victim))
2839                         return -ENOTDIR;
2840                 if (IS_ROOT(victim))
2841                         return -EBUSY;
2842         } else if (d_is_dir(victim))
2843                 return -EISDIR;
2844         if (IS_DEADDIR(dir))
2845                 return -ENOENT;
2846         if (victim->d_flags & DCACHE_NFSFS_RENAMED)
2847                 return -EBUSY;
2848         return 0;
2849 }
2850
2851 /*      Check whether we can create an object with dentry child in directory
2852  *  dir.
2853  *  1. We can't do it if child already exists (open has special treatment for
2854  *     this case, but since we are inlined it's OK)
2855  *  2. We can't do it if dir is read-only (done in permission())
2856  *  3. We can't do it if the fs can't represent the fsuid or fsgid.
2857  *  4. We should have write and exec permissions on dir
2858  *  5. We can't do it if dir is immutable (done in permission())
2859  */
2860 static inline int may_create(struct user_namespace *mnt_userns,
2861                              struct inode *dir, struct dentry *child)
2862 {
2863         audit_inode_child(dir, child, AUDIT_TYPE_CHILD_CREATE);
2864         if (child->d_inode)
2865                 return -EEXIST;
2866         if (IS_DEADDIR(dir))
2867                 return -ENOENT;
2868         if (!fsuidgid_has_mapping(dir->i_sb, mnt_userns))
2869                 return -EOVERFLOW;
2870
2871         return inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
2872 }
2873
2874 /*
2875  * p1 and p2 should be directories on the same fs.
2876  */
2877 struct dentry *lock_rename(struct dentry *p1, struct dentry *p2)
2878 {
2879         struct dentry *p;
2880
2881         if (p1 == p2) {
2882                 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
2883                 return NULL;
2884         }
2885
2886         mutex_lock(&p1->d_sb->s_vfs_rename_mutex);
2887
2888         p = d_ancestor(p2, p1);
2889         if (p) {
2890                 inode_lock_nested(p2->d_inode, I_MUTEX_PARENT);
2891                 inode_lock_nested(p1->d_inode, I_MUTEX_CHILD);
2892                 return p;
2893         }
2894
2895         p = d_ancestor(p1, p2);
2896         if (p) {
2897                 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
2898                 inode_lock_nested(p2->d_inode, I_MUTEX_CHILD);
2899                 return p;
2900         }
2901
2902         inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
2903         inode_lock_nested(p2->d_inode, I_MUTEX_PARENT2);
2904         return NULL;
2905 }
2906 EXPORT_SYMBOL(lock_rename);
2907
2908 void unlock_rename(struct dentry *p1, struct dentry *p2)
2909 {
2910         inode_unlock(p1->d_inode);
2911         if (p1 != p2) {
2912                 inode_unlock(p2->d_inode);
2913                 mutex_unlock(&p1->d_sb->s_vfs_rename_mutex);
2914         }
2915 }
2916 EXPORT_SYMBOL(unlock_rename);
2917
2918 /**
2919  * vfs_create - create new file
2920  * @mnt_userns: user namespace of the mount the inode was found from
2921  * @dir:        inode of @dentry
2922  * @dentry:     pointer to dentry of the base directory
2923  * @mode:       mode of the new file
2924  * @want_excl:  whether the file must not yet exist
2925  *
2926  * Create a new file.
2927  *
2928  * If the inode has been found through an idmapped mount the user namespace of
2929  * the vfsmount must be passed through @mnt_userns. This function will then take
2930  * care to map the inode according to @mnt_userns before checking permissions.
2931  * On non-idmapped mounts or if permission checking is to be performed on the
2932  * raw inode simply passs init_user_ns.
2933  */
2934 int vfs_create(struct user_namespace *mnt_userns, struct inode *dir,
2935                struct dentry *dentry, umode_t mode, bool want_excl)
2936 {
2937         int error = may_create(mnt_userns, dir, dentry);
2938         if (error)
2939                 return error;
2940
2941         if (!dir->i_op->create)
2942                 return -EACCES; /* shouldn't it be ENOSYS? */
2943         mode &= S_IALLUGO;
2944         mode |= S_IFREG;
2945         error = security_inode_create(dir, dentry, mode);
2946         if (error)
2947                 return error;
2948         error = dir->i_op->create(mnt_userns, dir, dentry, mode, want_excl);
2949         if (!error)
2950                 fsnotify_create(dir, dentry);
2951         return error;
2952 }
2953 EXPORT_SYMBOL(vfs_create);
2954
2955 int vfs_mkobj(struct dentry *dentry, umode_t mode,
2956                 int (*f)(struct dentry *, umode_t, void *),
2957                 void *arg)
2958 {
2959         struct inode *dir = dentry->d_parent->d_inode;
2960         int error = may_create(&init_user_ns, dir, dentry);
2961         if (error)
2962                 return error;
2963
2964         mode &= S_IALLUGO;
2965         mode |= S_IFREG;
2966         error = security_inode_create(dir, dentry, mode);
2967         if (error)
2968                 return error;
2969         error = f(dentry, mode, arg);
2970         if (!error)
2971                 fsnotify_create(dir, dentry);
2972         return error;
2973 }
2974 EXPORT_SYMBOL(vfs_mkobj);
2975
2976 bool may_open_dev(const struct path *path)
2977 {
2978         return !(path->mnt->mnt_flags & MNT_NODEV) &&
2979                 !(path->mnt->mnt_sb->s_iflags & SB_I_NODEV);
2980 }
2981
2982 static int may_open(struct user_namespace *mnt_userns, const struct path *path,
2983                     int acc_mode, int flag)
2984 {
2985         struct dentry *dentry = path->dentry;
2986         struct inode *inode = dentry->d_inode;
2987         int error;
2988
2989         if (!inode)
2990                 return -ENOENT;
2991
2992         switch (inode->i_mode & S_IFMT) {
2993         case S_IFLNK:
2994                 return -ELOOP;
2995         case S_IFDIR:
2996                 if (acc_mode & MAY_WRITE)
2997                         return -EISDIR;
2998                 if (acc_mode & MAY_EXEC)
2999                         return -EACCES;
3000                 break;
3001         case S_IFBLK:
3002         case S_IFCHR:
3003                 if (!may_open_dev(path))
3004                         return -EACCES;
3005                 fallthrough;
3006         case S_IFIFO:
3007         case S_IFSOCK:
3008                 if (acc_mode & MAY_EXEC)
3009                         return -EACCES;
3010                 flag &= ~O_TRUNC;
3011                 break;
3012         case S_IFREG:
3013                 if ((acc_mode & MAY_EXEC) && path_noexec(path))
3014                         return -EACCES;
3015                 break;
3016         }
3017
3018         error = inode_permission(mnt_userns, inode, MAY_OPEN | acc_mode);
3019         if (error)
3020                 return error;
3021
3022         /*
3023          * An append-only file must be opened in append mode for writing.
3024          */
3025         if (IS_APPEND(inode)) {
3026                 if  ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND))
3027                         return -EPERM;
3028                 if (flag & O_TRUNC)
3029                         return -EPERM;
3030         }
3031
3032         /* O_NOATIME can only be set by the owner or superuser */
3033         if (flag & O_NOATIME && !inode_owner_or_capable(mnt_userns, inode))
3034                 return -EPERM;
3035
3036         return 0;
3037 }
3038
3039 static int handle_truncate(struct user_namespace *mnt_userns, struct file *filp)
3040 {
3041         const struct path *path = &filp->f_path;
3042         struct inode *inode = path->dentry->d_inode;
3043         int error = get_write_access(inode);
3044         if (error)
3045                 return error;
3046         /*
3047          * Refuse to truncate files with mandatory locks held on them.
3048          */
3049         error = security_path_truncate(path);
3050         if (!error) {
3051                 error = do_truncate(mnt_userns, path->dentry, 0,
3052                                     ATTR_MTIME|ATTR_CTIME|ATTR_OPEN,
3053                                     filp);
3054         }
3055         put_write_access(inode);
3056         return error;
3057 }
3058
3059 static inline int open_to_namei_flags(int flag)
3060 {
3061         if ((flag & O_ACCMODE) == 3)
3062                 flag--;
3063         return flag;
3064 }
3065
3066 static int may_o_create(struct user_namespace *mnt_userns,
3067                         const struct path *dir, struct dentry *dentry,
3068                         umode_t mode)
3069 {
3070         int error = security_path_mknod(dir, dentry, mode, 0);
3071         if (error)
3072                 return error;
3073
3074         if (!fsuidgid_has_mapping(dir->dentry->d_sb, mnt_userns))
3075                 return -EOVERFLOW;
3076
3077         error = inode_permission(mnt_userns, dir->dentry->d_inode,
3078                                  MAY_WRITE | MAY_EXEC);
3079         if (error)
3080                 return error;
3081
3082         return security_inode_create(dir->dentry->d_inode, dentry, mode);
3083 }
3084
3085 /*
3086  * Attempt to atomically look up, create and open a file from a negative
3087  * dentry.
3088  *
3089  * Returns 0 if successful.  The file will have been created and attached to
3090  * @file by the filesystem calling finish_open().
3091  *
3092  * If the file was looked up only or didn't need creating, FMODE_OPENED won't
3093  * be set.  The caller will need to perform the open themselves.  @path will
3094  * have been updated to point to the new dentry.  This may be negative.
3095  *
3096  * Returns an error code otherwise.
3097  */
3098 static struct dentry *atomic_open(struct nameidata *nd, struct dentry *dentry,
3099                                   struct file *file,
3100                                   int open_flag, umode_t mode)
3101 {
3102         struct dentry *const DENTRY_NOT_SET = (void *) -1UL;
3103         struct inode *dir =  nd->path.dentry->d_inode;
3104         int error;
3105
3106         if (nd->flags & LOOKUP_DIRECTORY)
3107                 open_flag |= O_DIRECTORY;
3108
3109         file->f_path.dentry = DENTRY_NOT_SET;
3110         file->f_path.mnt = nd->path.mnt;
3111         error = dir->i_op->atomic_open(dir, dentry, file,
3112                                        open_to_namei_flags(open_flag), mode);
3113         d_lookup_done(dentry);
3114         if (!error) {
3115                 if (file->f_mode & FMODE_OPENED) {
3116                         if (unlikely(dentry != file->f_path.dentry)) {
3117                                 dput(dentry);
3118                                 dentry = dget(file->f_path.dentry);
3119                         }
3120                 } else if (WARN_ON(file->f_path.dentry == DENTRY_NOT_SET)) {
3121                         error = -EIO;
3122                 } else {
3123                         if (file->f_path.dentry) {
3124                                 dput(dentry);
3125                                 dentry = file->f_path.dentry;
3126                         }
3127                         if (unlikely(d_is_negative(dentry)))
3128                                 error = -ENOENT;
3129                 }
3130         }
3131         if (error) {
3132                 dput(dentry);
3133                 dentry = ERR_PTR(error);
3134         }
3135         return dentry;
3136 }
3137
3138 /*
3139  * Look up and maybe create and open the last component.
3140  *
3141  * Must be called with parent locked (exclusive in O_CREAT case).
3142  *
3143  * Returns 0 on success, that is, if
3144  *  the file was successfully atomically created (if necessary) and opened, or
3145  *  the file was not completely opened at this time, though lookups and
3146  *  creations were performed.
3147  * These case are distinguished by presence of FMODE_OPENED on file->f_mode.
3148  * In the latter case dentry returned in @path might be negative if O_CREAT
3149  * hadn't been specified.
3150  *
3151  * An error code is returned on failure.
3152  */
3153 static struct dentry *lookup_open(struct nameidata *nd, struct file *file,
3154                                   const struct open_flags *op,
3155                                   bool got_write)
3156 {
3157         struct user_namespace *mnt_userns;
3158         struct dentry *dir = nd->path.dentry;
3159         struct inode *dir_inode = dir->d_inode;
3160         int open_flag = op->open_flag;
3161         struct dentry *dentry;
3162         int error, create_error = 0;
3163         umode_t mode = op->mode;
3164         DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
3165
3166         if (unlikely(IS_DEADDIR(dir_inode)))
3167                 return ERR_PTR(-ENOENT);
3168
3169         file->f_mode &= ~FMODE_CREATED;
3170         dentry = d_lookup(dir, &nd->last);
3171         for (;;) {
3172                 if (!dentry) {
3173                         dentry = d_alloc_parallel(dir, &nd->last, &wq);
3174                         if (IS_ERR(dentry))
3175                                 return dentry;
3176                 }
3177                 if (d_in_lookup(dentry))
3178                         break;
3179
3180                 error = d_revalidate(dentry, nd->flags);
3181                 if (likely(error > 0))
3182                         break;
3183                 if (error)
3184                         goto out_dput;
3185                 d_invalidate(dentry);
3186                 dput(dentry);
3187                 dentry = NULL;
3188         }
3189         if (dentry->d_inode) {
3190                 /* Cached positive dentry: will open in f_op->open */
3191                 return dentry;
3192         }
3193
3194         /*
3195          * Checking write permission is tricky, bacuse we don't know if we are
3196          * going to actually need it: O_CREAT opens should work as long as the
3197          * file exists.  But checking existence breaks atomicity.  The trick is
3198          * to check access and if not granted clear O_CREAT from the flags.
3199          *
3200          * Another problem is returing the "right" error value (e.g. for an
3201          * O_EXCL open we want to return EEXIST not EROFS).
3202          */
3203         if (unlikely(!got_write))
3204                 open_flag &= ~O_TRUNC;
3205         mnt_userns = mnt_user_ns(nd->path.mnt);
3206         if (open_flag & O_CREAT) {
3207                 if (open_flag & O_EXCL)
3208                         open_flag &= ~O_TRUNC;
3209                 if (!IS_POSIXACL(dir->d_inode))
3210                         mode &= ~current_umask();
3211                 if (likely(got_write))
3212                         create_error = may_o_create(mnt_userns, &nd->path,
3213                                                     dentry, mode);
3214                 else
3215                         create_error = -EROFS;
3216         }
3217         if (create_error)
3218                 open_flag &= ~O_CREAT;
3219         if (dir_inode->i_op->atomic_open) {
3220                 dentry = atomic_open(nd, dentry, file, open_flag, mode);
3221                 if (unlikely(create_error) && dentry == ERR_PTR(-ENOENT))
3222                         dentry = ERR_PTR(create_error);
3223                 return dentry;
3224         }
3225
3226         if (d_in_lookup(dentry)) {
3227                 struct dentry *res = dir_inode->i_op->lookup(dir_inode, dentry,
3228                                                              nd->flags);
3229                 d_lookup_done(dentry);
3230                 if (unlikely(res)) {
3231                         if (IS_ERR(res)) {
3232                                 error = PTR_ERR(res);
3233                                 goto out_dput;
3234                         }
3235                         dput(dentry);
3236                         dentry = res;
3237                 }
3238         }
3239
3240         /* Negative dentry, just create the file */
3241         if (!dentry->d_inode && (open_flag & O_CREAT)) {
3242                 file->f_mode |= FMODE_CREATED;
3243                 audit_inode_child(dir_inode, dentry, AUDIT_TYPE_CHILD_CREATE);
3244                 if (!dir_inode->i_op->create) {
3245                         error = -EACCES;
3246                         goto out_dput;
3247                 }
3248
3249                 error = dir_inode->i_op->create(mnt_userns, dir_inode, dentry,
3250                                                 mode, open_flag & O_EXCL);
3251                 if (error)
3252                         goto out_dput;
3253         }
3254         if (unlikely(create_error) && !dentry->d_inode) {
3255                 error = create_error;
3256                 goto out_dput;
3257         }
3258         return dentry;
3259
3260 out_dput:
3261         dput(dentry);
3262         return ERR_PTR(error);
3263 }
3264
3265 static const char *open_last_lookups(struct nameidata *nd,
3266                    struct file *file, const struct open_flags *op)
3267 {
3268         struct dentry *dir = nd->path.dentry;
3269         int open_flag = op->open_flag;
3270         bool got_write = false;
3271         unsigned seq;
3272         struct inode *inode;
3273         struct dentry *dentry;
3274         const char *res;
3275
3276         nd->flags |= op->intent;
3277
3278         if (nd->last_type != LAST_NORM) {
3279                 if (nd->depth)
3280                         put_link(nd);
3281                 return handle_dots(nd, nd->last_type);
3282         }
3283
3284         if (!(open_flag & O_CREAT)) {
3285                 if (nd->last.name[nd->last.len])
3286                         nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
3287                 /* we _can_ be in RCU mode here */
3288                 dentry = lookup_fast(nd, &inode, &seq);
3289                 if (IS_ERR(dentry))
3290                         return ERR_CAST(dentry);
3291                 if (likely(dentry))
3292                         goto finish_lookup;
3293
3294                 BUG_ON(nd->flags & LOOKUP_RCU);
3295         } else {
3296                 /* create side of things */
3297                 if (nd->flags & LOOKUP_RCU) {
3298                         if (!try_to_unlazy(nd))
3299                                 return ERR_PTR(-ECHILD);
3300                 }
3301                 audit_inode(nd->name, dir, AUDIT_INODE_PARENT);
3302                 /* trailing slashes? */
3303                 if (unlikely(nd->last.name[nd->last.len]))
3304                         return ERR_PTR(-EISDIR);
3305         }
3306
3307         if (open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) {
3308                 got_write = !mnt_want_write(nd->path.mnt);
3309                 /*
3310                  * do _not_ fail yet - we might not need that or fail with
3311                  * a different error; let lookup_open() decide; we'll be
3312                  * dropping this one anyway.
3313                  */
3314         }
3315         if (open_flag & O_CREAT)
3316                 inode_lock(dir->d_inode);
3317         else
3318                 inode_lock_shared(dir->d_inode);
3319         dentry = lookup_open(nd, file, op, got_write);
3320         if (!IS_ERR(dentry) && (file->f_mode & FMODE_CREATED))
3321                 fsnotify_create(dir->d_inode, dentry);
3322         if (open_flag & O_CREAT)
3323                 inode_unlock(dir->d_inode);
3324         else
3325                 inode_unlock_shared(dir->d_inode);
3326
3327         if (got_write)
3328                 mnt_drop_write(nd->path.mnt);
3329
3330         if (IS_ERR(dentry))
3331                 return ERR_CAST(dentry);
3332
3333         if (file->f_mode & (FMODE_OPENED | FMODE_CREATED)) {
3334                 dput(nd->path.dentry);
3335                 nd->path.dentry = dentry;
3336                 return NULL;
3337         }
3338
3339 finish_lookup:
3340         if (nd->depth)
3341                 put_link(nd);
3342         res = step_into(nd, WALK_TRAILING, dentry, inode, seq);
3343         if (unlikely(res))
3344                 nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL);
3345         return res;
3346 }
3347
3348 /*
3349  * Handle the last step of open()
3350  */
3351 static int do_open(struct nameidata *nd,
3352                    struct file *file, const struct open_flags *op)
3353 {
3354         struct user_namespace *mnt_userns;
3355         int open_flag = op->open_flag;
3356         bool do_truncate;
3357         int acc_mode;
3358         int error;
3359
3360         if (!(file->f_mode & (FMODE_OPENED | FMODE_CREATED))) {
3361                 error = complete_walk(nd);
3362                 if (error)
3363                         return error;
3364         }
3365         if (!(file->f_mode & FMODE_CREATED))
3366                 audit_inode(nd->name, nd->path.dentry, 0);
3367         mnt_userns = mnt_user_ns(nd->path.mnt);
3368         if (open_flag & O_CREAT) {
3369                 if ((open_flag & O_EXCL) && !(file->f_mode & FMODE_CREATED))
3370                         return -EEXIST;
3371                 if (d_is_dir(nd->path.dentry))
3372                         return -EISDIR;
3373                 error = may_create_in_sticky(mnt_userns, nd,
3374                                              d_backing_inode(nd->path.dentry));
3375                 if (unlikely(error))
3376                         return error;
3377         }
3378         if ((nd->flags & LOOKUP_DIRECTORY) && !d_can_lookup(nd->path.dentry))
3379                 return -ENOTDIR;
3380
3381         do_truncate = false;
3382         acc_mode = op->acc_mode;
3383         if (file->f_mode & FMODE_CREATED) {
3384                 /* Don't check for write permission, don't truncate */
3385                 open_flag &= ~O_TRUNC;
3386                 acc_mode = 0;
3387         } else if (d_is_reg(nd->path.dentry) && open_flag & O_TRUNC) {
3388                 error = mnt_want_write(nd->path.mnt);
3389                 if (error)
3390                         return error;
3391                 do_truncate = true;
3392         }
3393         error = may_open(mnt_userns, &nd->path, acc_mode, open_flag);
3394         if (!error && !(file->f_mode & FMODE_OPENED))
3395                 error = vfs_open(&nd->path, file);
3396         if (!error)
3397                 error = ima_file_check(file, op->acc_mode);
3398         if (!error && do_truncate)
3399                 error = handle_truncate(mnt_userns, file);
3400         if (unlikely(error > 0)) {
3401                 WARN_ON(1);
3402                 error = -EINVAL;
3403         }
3404         if (do_truncate)
3405                 mnt_drop_write(nd->path.mnt);
3406         return error;
3407 }
3408
3409 /**
3410  * vfs_tmpfile - create tmpfile
3411  * @mnt_userns: user namespace of the mount the inode was found from
3412  * @dentry:     pointer to dentry of the base directory
3413  * @mode:       mode of the new tmpfile
3414  * @open_flag:  flags
3415  *
3416  * Create a temporary file.
3417  *
3418  * If the inode has been found through an idmapped mount the user namespace of
3419  * the vfsmount must be passed through @mnt_userns. This function will then take
3420  * care to map the inode according to @mnt_userns before checking permissions.
3421  * On non-idmapped mounts or if permission checking is to be performed on the
3422  * raw inode simply passs init_user_ns.
3423  */
3424 struct dentry *vfs_tmpfile(struct user_namespace *mnt_userns,
3425                            struct dentry *dentry, umode_t mode, int open_flag)
3426 {
3427         struct dentry *child = NULL;
3428         struct inode *dir = dentry->d_inode;
3429         struct inode *inode;
3430         int error;
3431
3432         /* we want directory to be writable */
3433         error = inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
3434         if (error)
3435                 goto out_err;
3436         error = -EOPNOTSUPP;
3437         if (!dir->i_op->tmpfile)
3438                 goto out_err;
3439         error = -ENOMEM;
3440         child = d_alloc(dentry, &slash_name);
3441         if (unlikely(!child))
3442                 goto out_err;
3443         error = dir->i_op->tmpfile(mnt_userns, dir, child, mode);
3444         if (error)
3445                 goto out_err;
3446         error = -ENOENT;
3447         inode = child->d_inode;
3448         if (unlikely(!inode))
3449                 goto out_err;
3450         if (!(open_flag & O_EXCL)) {
3451                 spin_lock(&inode->i_lock);
3452                 inode->i_state |= I_LINKABLE;
3453                 spin_unlock(&inode->i_lock);
3454         }
3455         ima_post_create_tmpfile(mnt_userns, inode);
3456         return child;
3457
3458 out_err:
3459         dput(child);
3460         return ERR_PTR(error);
3461 }
3462 EXPORT_SYMBOL(vfs_tmpfile);
3463
3464 static int do_tmpfile(struct nameidata *nd, unsigned flags,
3465                 const struct open_flags *op,
3466                 struct file *file)
3467 {
3468         struct user_namespace *mnt_userns;
3469         struct dentry *child;
3470         struct path path;
3471         int error = path_lookupat(nd, flags | LOOKUP_DIRECTORY, &path);
3472         if (unlikely(error))
3473                 return error;
3474         error = mnt_want_write(path.mnt);
3475         if (unlikely(error))
3476                 goto out;
3477         mnt_userns = mnt_user_ns(path.mnt);
3478         child = vfs_tmpfile(mnt_userns, path.dentry, op->mode, op->open_flag);
3479         error = PTR_ERR(child);
3480         if (IS_ERR(child))
3481                 goto out2;
3482         dput(path.dentry);
3483         path.dentry = child;
3484         audit_inode(nd->name, child, 0);
3485         /* Don't check for other permissions, the inode was just created */
3486         error = may_open(mnt_userns, &path, 0, op->open_flag);
3487         if (!error)
3488                 error = vfs_open(&path, file);
3489 out2:
3490         mnt_drop_write(path.mnt);
3491 out:
3492         path_put(&path);
3493         return error;
3494 }
3495
3496 static int do_o_path(struct nameidata *nd, unsigned flags, struct file *file)
3497 {
3498         struct path path;
3499         int error = path_lookupat(nd, flags, &path);
3500         if (!error) {
3501                 audit_inode(nd->name, path.dentry, 0);
3502                 error = vfs_open(&path, file);
3503                 path_put(&path);
3504         }
3505         return error;
3506 }
3507
3508 static struct file *path_openat(struct nameidata *nd,
3509                         const struct open_flags *op, unsigned flags)
3510 {
3511         struct file *file;
3512         int error;
3513
3514         file = alloc_empty_file(op->open_flag, current_cred());
3515         if (IS_ERR(file))
3516                 return file;
3517
3518         if (unlikely(file->f_flags & __O_TMPFILE)) {
3519                 error = do_tmpfile(nd, flags, op, file);
3520         } else if (unlikely(file->f_flags & O_PATH)) {
3521                 error = do_o_path(nd, flags, file);
3522         } else {
3523                 const char *s = path_init(nd, flags);
3524                 while (!(error = link_path_walk(s, nd)) &&
3525                        (s = open_last_lookups(nd, file, op)) != NULL)
3526                         ;
3527                 if (!error)
3528                         error = do_open(nd, file, op);
3529                 terminate_walk(nd);
3530         }
3531         if (likely(!error)) {
3532                 if (likely(file->f_mode & FMODE_OPENED))
3533                         return file;
3534                 WARN_ON(1);
3535                 error = -EINVAL;
3536         }
3537         fput(file);
3538         if (error == -EOPENSTALE) {
3539                 if (flags & LOOKUP_RCU)
3540                         error = -ECHILD;
3541                 else
3542                         error = -ESTALE;
3543         }
3544         return ERR_PTR(error);
3545 }
3546
3547 struct file *do_filp_open(int dfd, struct filename *pathname,
3548                 const struct open_flags *op)
3549 {
3550         struct nameidata nd;
3551         int flags = op->lookup_flags;
3552         struct file *filp;
3553
3554         set_nameidata(&nd, dfd, pathname, NULL);
3555         filp = path_openat(&nd, op, flags | LOOKUP_RCU);
3556         if (unlikely(filp == ERR_PTR(-ECHILD)))
3557                 filp = path_openat(&nd, op, flags);
3558         if (unlikely(filp == ERR_PTR(-ESTALE)))
3559                 filp = path_openat(&nd, op, flags | LOOKUP_REVAL);
3560         restore_nameidata();
3561         return filp;
3562 }
3563
3564 struct file *do_file_open_root(const struct path *root,
3565                 const char *name, const struct open_flags *op)
3566 {
3567         struct nameidata nd;
3568         struct file *file;
3569         struct filename *filename;
3570         int flags = op->lookup_flags;
3571
3572         if (d_is_symlink(root->dentry) && op->intent & LOOKUP_OPEN)
3573                 return ERR_PTR(-ELOOP);
3574
3575         filename = getname_kernel(name);
3576         if (IS_ERR(filename))
3577                 return ERR_CAST(filename);
3578
3579         set_nameidata(&nd, -1, filename, root);
3580         file = path_openat(&nd, op, flags | LOOKUP_RCU);
3581         if (unlikely(file == ERR_PTR(-ECHILD)))
3582                 file = path_openat(&nd, op, flags);
3583         if (unlikely(file == ERR_PTR(-ESTALE)))
3584                 file = path_openat(&nd, op, flags | LOOKUP_REVAL);
3585         restore_nameidata();
3586         putname(filename);
3587         return file;
3588 }
3589
3590 static struct dentry *__filename_create(int dfd, struct filename *name,
3591                                 struct path *path, unsigned int lookup_flags)
3592 {
3593         struct dentry *dentry = ERR_PTR(-EEXIST);
3594         struct qstr last;
3595         int type;
3596         int err2;
3597         int error;
3598         bool is_dir = (lookup_flags & LOOKUP_DIRECTORY);
3599
3600         /*
3601          * Note that only LOOKUP_REVAL and LOOKUP_DIRECTORY matter here. Any
3602          * other flags passed in are ignored!
3603          */
3604         lookup_flags &= LOOKUP_REVAL;
3605
3606         error = __filename_parentat(dfd, name, lookup_flags, path, &last, &type);
3607         if (error)
3608                 return ERR_PTR(error);
3609
3610         /*
3611          * Yucky last component or no last component at all?
3612          * (foo/., foo/.., /////)
3613          */
3614         if (unlikely(type != LAST_NORM))
3615                 goto out;
3616
3617         /* don't fail immediately if it's r/o, at least try to report other errors */
3618         err2 = mnt_want_write(path->mnt);
3619         /*
3620          * Do the final lookup.
3621          */
3622         lookup_flags |= LOOKUP_CREATE | LOOKUP_EXCL;
3623         inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
3624         dentry = __lookup_hash(&last, path->dentry, lookup_flags);
3625         if (IS_ERR(dentry))
3626                 goto unlock;
3627
3628         error = -EEXIST;
3629         if (d_is_positive(dentry))
3630                 goto fail;
3631
3632         /*
3633          * Special case - lookup gave negative, but... we had foo/bar/
3634          * From the vfs_mknod() POV we just have a negative dentry -
3635          * all is fine. Let's be bastards - you had / on the end, you've
3636          * been asking for (non-existent) directory. -ENOENT for you.
3637          */
3638         if (unlikely(!is_dir && last.name[last.len])) {
3639                 error = -ENOENT;
3640                 goto fail;
3641         }
3642         if (unlikely(err2)) {
3643                 error = err2;
3644                 goto fail;
3645         }
3646         return dentry;
3647 fail:
3648         dput(dentry);
3649         dentry = ERR_PTR(error);
3650 unlock:
3651         inode_unlock(path->dentry->d_inode);
3652         if (!err2)
3653                 mnt_drop_write(path->mnt);
3654 out:
3655         path_put(path);
3656         return dentry;
3657 }
3658
3659 static inline struct dentry *filename_create(int dfd, struct filename *name,
3660                                 struct path *path, unsigned int lookup_flags)
3661 {
3662         struct dentry *res = __filename_create(dfd, name, path, lookup_flags);
3663
3664         putname(name);
3665         return res;
3666 }
3667
3668 struct dentry *kern_path_create(int dfd, const char *pathname,
3669                                 struct path *path, unsigned int lookup_flags)
3670 {
3671         return filename_create(dfd, getname_kernel(pathname),
3672                                 path, lookup_flags);
3673 }
3674 EXPORT_SYMBOL(kern_path_create);
3675
3676 void done_path_create(struct path *path, struct dentry *dentry)
3677 {
3678         dput(dentry);
3679         inode_unlock(path->dentry->d_inode);
3680         mnt_drop_write(path->mnt);
3681         path_put(path);
3682 }
3683 EXPORT_SYMBOL(done_path_create);
3684
3685 inline struct dentry *user_path_create(int dfd, const char __user *pathname,
3686                                 struct path *path, unsigned int lookup_flags)
3687 {
3688         return filename_create(dfd, getname(pathname), path, lookup_flags);
3689 }
3690 EXPORT_SYMBOL(user_path_create);
3691
3692 /**
3693  * vfs_mknod - create device node or file
3694  * @mnt_userns: user namespace of the mount the inode was found from
3695  * @dir:        inode of @dentry
3696  * @dentry:     pointer to dentry of the base directory
3697  * @mode:       mode of the new device node or file
3698  * @dev:        device number of device to create
3699  *
3700  * Create a device node or file.
3701  *
3702  * If the inode has been found through an idmapped mount the user namespace of
3703  * the vfsmount must be passed through @mnt_userns. This function will then take
3704  * care to map the inode according to @mnt_userns before checking permissions.
3705  * On non-idmapped mounts or if permission checking is to be performed on the
3706  * raw inode simply passs init_user_ns.
3707  */
3708 int vfs_mknod(struct user_namespace *mnt_userns, struct inode *dir,
3709               struct dentry *dentry, umode_t mode, dev_t dev)
3710 {
3711         bool is_whiteout = S_ISCHR(mode) && dev == WHITEOUT_DEV;
3712         int error = may_create(mnt_userns, dir, dentry);
3713
3714         if (error)
3715                 return error;
3716
3717         if ((S_ISCHR(mode) || S_ISBLK(mode)) && !is_whiteout &&
3718             !capable(CAP_MKNOD))
3719                 return -EPERM;
3720
3721         if (!dir->i_op->mknod)
3722                 return -EPERM;
3723
3724         error = devcgroup_inode_mknod(mode, dev);
3725         if (error)
3726                 return error;
3727
3728         error = security_inode_mknod(dir, dentry, mode, dev);
3729         if (error)
3730                 return error;
3731
3732         error = dir->i_op->mknod(mnt_userns, dir, dentry, mode, dev);
3733         if (!error)
3734                 fsnotify_create(dir, dentry);
3735         return error;
3736 }
3737 EXPORT_SYMBOL(vfs_mknod);
3738
3739 static int may_mknod(umode_t mode)
3740 {
3741         switch (mode & S_IFMT) {
3742         case S_IFREG:
3743         case S_IFCHR:
3744         case S_IFBLK:
3745         case S_IFIFO:
3746         case S_IFSOCK:
3747         case 0: /* zero mode translates to S_IFREG */
3748                 return 0;
3749         case S_IFDIR:
3750                 return -EPERM;
3751         default:
3752                 return -EINVAL;
3753         }
3754 }
3755
3756 static int do_mknodat(int dfd, struct filename *name, umode_t mode,
3757                 unsigned int dev)
3758 {
3759         struct user_namespace *mnt_userns;
3760         struct dentry *dentry;
3761         struct path path;
3762         int error;
3763         unsigned int lookup_flags = 0;
3764
3765         error = may_mknod(mode);
3766         if (error)
3767                 goto out1;
3768 retry:
3769         dentry = __filename_create(dfd, name, &path, lookup_flags);
3770         error = PTR_ERR(dentry);
3771         if (IS_ERR(dentry))
3772                 goto out1;
3773
3774         if (!IS_POSIXACL(path.dentry->d_inode))
3775                 mode &= ~current_umask();
3776         error = security_path_mknod(&path, dentry, mode, dev);
3777         if (error)
3778                 goto out2;
3779
3780         mnt_userns = mnt_user_ns(path.mnt);
3781         switch (mode & S_IFMT) {
3782                 case 0: case S_IFREG:
3783                         error = vfs_create(mnt_userns, path.dentry->d_inode,
3784                                            dentry, mode, true);
3785                         if (!error)
3786                                 ima_post_path_mknod(mnt_userns, dentry);
3787                         break;
3788                 case S_IFCHR: case S_IFBLK:
3789                         error = vfs_mknod(mnt_userns, path.dentry->d_inode,
3790                                           dentry, mode, new_decode_dev(dev));
3791                         break;
3792                 case S_IFIFO: case S_IFSOCK:
3793                         error = vfs_mknod(mnt_userns, path.dentry->d_inode,
3794                                           dentry, mode, 0);
3795                         break;
3796         }
3797 out2:
3798         done_path_create(&path, dentry);
3799         if (retry_estale(error, lookup_flags)) {
3800                 lookup_flags |= LOOKUP_REVAL;
3801                 goto retry;
3802         }
3803 out1:
3804         putname(name);
3805         return error;
3806 }
3807
3808 SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, umode_t, mode,
3809                 unsigned int, dev)
3810 {
3811         return do_mknodat(dfd, getname(filename), mode, dev);
3812 }
3813
3814 SYSCALL_DEFINE3(mknod, const char __user *, filename, umode_t, mode, unsigned, dev)
3815 {
3816         return do_mknodat(AT_FDCWD, getname(filename), mode, dev);
3817 }
3818
3819 /**
3820  * vfs_mkdir - create directory
3821  * @mnt_userns: user namespace of the mount the inode was found from
3822  * @dir:        inode of @dentry
3823  * @dentry:     pointer to dentry of the base directory
3824  * @mode:       mode of the new directory
3825  *
3826  * Create a directory.
3827  *
3828  * If the inode has been found through an idmapped mount the user namespace of
3829  * the vfsmount must be passed through @mnt_userns. This function will then take
3830  * care to map the inode according to @mnt_userns before checking permissions.
3831  * On non-idmapped mounts or if permission checking is to be performed on the
3832  * raw inode simply passs init_user_ns.
3833  */
3834 int vfs_mkdir(struct user_namespace *mnt_userns, struct inode *dir,
3835               struct dentry *dentry, umode_t mode)
3836 {
3837         int error = may_create(mnt_userns, dir, dentry);
3838         unsigned max_links = dir->i_sb->s_max_links;
3839
3840         if (error)
3841                 return error;
3842
3843         if (!dir->i_op->mkdir)
3844                 return -EPERM;
3845
3846         mode &= (S_IRWXUGO|S_ISVTX);
3847         error = security_inode_mkdir(dir, dentry, mode);
3848         if (error)
3849                 return error;
3850
3851         if (max_links && dir->i_nlink >= max_links)
3852                 return -EMLINK;
3853
3854         error = dir->i_op->mkdir(mnt_userns, dir, dentry, mode);
3855         if (!error)
3856                 fsnotify_mkdir(dir, dentry);
3857         return error;
3858 }
3859 EXPORT_SYMBOL(vfs_mkdir);
3860
3861 int do_mkdirat(int dfd, struct filename *name, umode_t mode)
3862 {
3863         struct dentry *dentry;
3864         struct path path;
3865         int error;
3866         unsigned int lookup_flags = LOOKUP_DIRECTORY;
3867
3868 retry:
3869         dentry = __filename_create(dfd, name, &path, lookup_flags);
3870         error = PTR_ERR(dentry);
3871         if (IS_ERR(dentry))
3872                 goto out_putname;
3873
3874         if (!IS_POSIXACL(path.dentry->d_inode))
3875                 mode &= ~current_umask();
3876         error = security_path_mkdir(&path, dentry, mode);
3877         if (!error) {
3878                 struct user_namespace *mnt_userns;
3879                 mnt_userns = mnt_user_ns(path.mnt);
3880                 error = vfs_mkdir(mnt_userns, path.dentry->d_inode, dentry,
3881                                   mode);
3882         }
3883         done_path_create(&path, dentry);
3884         if (retry_estale(error, lookup_flags)) {
3885                 lookup_flags |= LOOKUP_REVAL;
3886                 goto retry;
3887         }
3888 out_putname:
3889         putname(name);
3890         return error;
3891 }
3892
3893 SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, umode_t, mode)
3894 {
3895         return do_mkdirat(dfd, getname(pathname), mode);
3896 }
3897
3898 SYSCALL_DEFINE2(mkdir, const char __user *, pathname, umode_t, mode)
3899 {
3900         return do_mkdirat(AT_FDCWD, getname(pathname), mode);
3901 }
3902
3903 /**
3904  * vfs_rmdir - remove directory
3905  * @mnt_userns: user namespace of the mount the inode was found from
3906  * @dir:        inode of @dentry
3907  * @dentry:     pointer to dentry of the base directory
3908  *
3909  * Remove a directory.
3910  *
3911  * If the inode has been found through an idmapped mount the user namespace of
3912  * the vfsmount must be passed through @mnt_userns. This function will then take
3913  * care to map the inode according to @mnt_userns before checking permissions.
3914  * On non-idmapped mounts or if permission checking is to be performed on the
3915  * raw inode simply passs init_user_ns.
3916  */
3917 int vfs_rmdir(struct user_namespace *mnt_userns, struct inode *dir,
3918                      struct dentry *dentry)
3919 {
3920         int error = may_delete(mnt_userns, dir, dentry, 1);
3921
3922         if (error)
3923                 return error;
3924
3925         if (!dir->i_op->rmdir)
3926                 return -EPERM;
3927
3928         dget(dentry);
3929         inode_lock(dentry->d_inode);
3930
3931         error = -EBUSY;
3932         if (is_local_mountpoint(dentry))
3933                 goto out;
3934
3935         error = security_inode_rmdir(dir, dentry);
3936         if (error)
3937                 goto out;
3938
3939         error = dir->i_op->rmdir(dir, dentry);
3940         if (error)
3941                 goto out;
3942
3943         shrink_dcache_parent(dentry);
3944         dentry->d_inode->i_flags |= S_DEAD;
3945         dont_mount(dentry);
3946         detach_mounts(dentry);
3947         fsnotify_rmdir(dir, dentry);
3948
3949 out:
3950         inode_unlock(dentry->d_inode);
3951         dput(dentry);
3952         if (!error)
3953                 d_delete(dentry);
3954         return error;
3955 }
3956 EXPORT_SYMBOL(vfs_rmdir);
3957
3958 int do_rmdir(int dfd, struct filename *name)
3959 {
3960         struct user_namespace *mnt_userns;
3961         int error;
3962         struct dentry *dentry;
3963         struct path path;
3964         struct qstr last;
3965         int type;
3966         unsigned int lookup_flags = 0;
3967 retry:
3968         error = __filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
3969         if (error)
3970                 goto exit1;
3971
3972         switch (type) {
3973         case LAST_DOTDOT:
3974                 error = -ENOTEMPTY;
3975                 goto exit2;
3976         case LAST_DOT:
3977                 error = -EINVAL;
3978                 goto exit2;
3979         case LAST_ROOT:
3980                 error = -EBUSY;
3981                 goto exit2;
3982         }
3983
3984         error = mnt_want_write(path.mnt);
3985         if (error)
3986                 goto exit2;
3987
3988         inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
3989         dentry = __lookup_hash(&last, path.dentry, lookup_flags);
3990         error = PTR_ERR(dentry);
3991         if (IS_ERR(dentry))
3992                 goto exit3;
3993         if (!dentry->d_inode) {
3994                 error = -ENOENT;
3995                 goto exit4;
3996         }
3997         error = security_path_rmdir(&path, dentry);
3998         if (error)
3999                 goto exit4;
4000         mnt_userns = mnt_user_ns(path.mnt);
4001         error = vfs_rmdir(mnt_userns, path.dentry->d_inode, dentry);
4002 exit4:
4003         dput(dentry);
4004 exit3:
4005         inode_unlock(path.dentry->d_inode);
4006         mnt_drop_write(path.mnt);
4007 exit2:
4008         path_put(&path);
4009         if (retry_estale(error, lookup_flags)) {
4010                 lookup_flags |= LOOKUP_REVAL;
4011                 goto retry;
4012         }
4013 exit1:
4014         putname(name);
4015         return error;
4016 }
4017
4018 SYSCALL_DEFINE1(rmdir, const char __user *, pathname)
4019 {
4020         return do_rmdir(AT_FDCWD, getname(pathname));
4021 }
4022
4023 /**
4024  * vfs_unlink - unlink a filesystem object
4025  * @mnt_userns: user namespace of the mount the inode was found from
4026  * @dir:        parent directory
4027  * @dentry:     victim
4028  * @delegated_inode: returns victim inode, if the inode is delegated.
4029  *
4030  * The caller must hold dir->i_mutex.
4031  *
4032  * If vfs_unlink discovers a delegation, it will return -EWOULDBLOCK and
4033  * return a reference to the inode in delegated_inode.  The caller
4034  * should then break the delegation on that inode and retry.  Because
4035  * breaking a delegation may take a long time, the caller should drop
4036  * dir->i_mutex before doing so.
4037  *
4038  * Alternatively, a caller may pass NULL for delegated_inode.  This may
4039  * be appropriate for callers that expect the underlying filesystem not
4040  * to be NFS exported.
4041  *
4042  * If the inode has been found through an idmapped mount the user namespace of
4043  * the vfsmount must be passed through @mnt_userns. This function will then take
4044  * care to map the inode according to @mnt_userns before checking permissions.
4045  * On non-idmapped mounts or if permission checking is to be performed on the
4046  * raw inode simply passs init_user_ns.
4047  */
4048 int vfs_unlink(struct user_namespace *mnt_userns, struct inode *dir,
4049                struct dentry *dentry, struct inode **delegated_inode)
4050 {
4051         struct inode *target = dentry->d_inode;
4052         int error = may_delete(mnt_userns, dir, dentry, 0);
4053
4054         if (error)
4055                 return error;
4056
4057         if (!dir->i_op->unlink)
4058                 return -EPERM;
4059
4060         inode_lock(target);
4061         if (is_local_mountpoint(dentry))
4062                 error = -EBUSY;
4063         else {
4064                 error = security_inode_unlink(dir, dentry);
4065                 if (!error) {
4066                         error = try_break_deleg(target, delegated_inode);
4067                         if (error)
4068                                 goto out;
4069                         error = dir->i_op->unlink(dir, dentry);
4070                         if (!error) {
4071                                 dont_mount(dentry);
4072                                 detach_mounts(dentry);
4073                                 fsnotify_unlink(dir, dentry);
4074                         }
4075                 }
4076         }
4077 out:
4078         inode_unlock(target);
4079
4080         /* We don't d_delete() NFS sillyrenamed files--they still exist. */
4081         if (!error && !(dentry->d_flags & DCACHE_NFSFS_RENAMED)) {
4082                 fsnotify_link_count(target);
4083                 d_delete(dentry);
4084         }
4085
4086         return error;
4087 }
4088 EXPORT_SYMBOL(vfs_unlink);
4089
4090 /*
4091  * Make sure that the actual truncation of the file will occur outside its
4092  * directory's i_mutex.  Truncate can take a long time if there is a lot of
4093  * writeout happening, and we don't want to prevent access to the directory
4094  * while waiting on the I/O.
4095  */
4096 int do_unlinkat(int dfd, struct filename *name)
4097 {
4098         int error;
4099         struct dentry *dentry;
4100         struct path path;
4101         struct qstr last;
4102         int type;
4103         struct inode *inode = NULL;
4104         struct inode *delegated_inode = NULL;
4105         unsigned int lookup_flags = 0;
4106 retry:
4107         error = __filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
4108         if (error)
4109                 goto exit1;
4110
4111         error = -EISDIR;
4112         if (type != LAST_NORM)
4113                 goto exit2;
4114
4115         error = mnt_want_write(path.mnt);
4116         if (error)
4117                 goto exit2;
4118 retry_deleg:
4119         inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
4120         dentry = __lookup_hash(&last, path.dentry, lookup_flags);
4121         error = PTR_ERR(dentry);
4122         if (!IS_ERR(dentry)) {
4123                 struct user_namespace *mnt_userns;
4124
4125                 /* Why not before? Because we want correct error value */
4126                 if (last.name[last.len])
4127                         goto slashes;
4128                 inode = dentry->d_inode;
4129                 if (d_is_negative(dentry))
4130                         goto slashes;
4131                 ihold(inode);
4132                 error = security_path_unlink(&path, dentry);
4133                 if (error)
4134                         goto exit3;
4135                 mnt_userns = mnt_user_ns(path.mnt);
4136                 error = vfs_unlink(mnt_userns, path.dentry->d_inode, dentry,
4137                                    &delegated_inode);
4138 exit3:
4139                 dput(dentry);
4140         }
4141         inode_unlock(path.dentry->d_inode);
4142         if (inode)
4143                 iput(inode);    /* truncate the inode here */
4144         inode = NULL;
4145         if (delegated_inode) {
4146                 error = break_deleg_wait(&delegated_inode);
4147                 if (!error)
4148                         goto retry_deleg;
4149         }
4150         mnt_drop_write(path.mnt);
4151 exit2:
4152         path_put(&path);
4153         if (retry_estale(error, lookup_flags)) {
4154                 lookup_flags |= LOOKUP_REVAL;
4155                 inode = NULL;
4156                 goto retry;
4157         }
4158 exit1:
4159         putname(name);
4160         return error;
4161
4162 slashes:
4163         if (d_is_negative(dentry))
4164                 error = -ENOENT;
4165         else if (d_is_dir(dentry))
4166                 error = -EISDIR;
4167         else
4168                 error = -ENOTDIR;
4169         goto exit3;
4170 }
4171
4172 SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag)
4173 {
4174         if ((flag & ~AT_REMOVEDIR) != 0)
4175                 return -EINVAL;
4176
4177         if (flag & AT_REMOVEDIR)
4178                 return do_rmdir(dfd, getname(pathname));
4179         return do_unlinkat(dfd, getname(pathname));
4180 }
4181
4182 SYSCALL_DEFINE1(unlink, const char __user *, pathname)
4183 {
4184         return do_unlinkat(AT_FDCWD, getname(pathname));
4185 }
4186
4187 /**
4188  * vfs_symlink - create symlink
4189  * @mnt_userns: user namespace of the mount the inode was found from
4190  * @dir:        inode of @dentry
4191  * @dentry:     pointer to dentry of the base directory
4192  * @oldname:    name of the file to link to
4193  *
4194  * Create a symlink.
4195  *
4196  * If the inode has been found through an idmapped mount the user namespace of
4197  * the vfsmount must be passed through @mnt_userns. This function will then take
4198  * care to map the inode according to @mnt_userns before checking permissions.
4199  * On non-idmapped mounts or if permission checking is to be performed on the
4200  * raw inode simply passs init_user_ns.
4201  */
4202 int vfs_symlink(struct user_namespace *mnt_userns, struct inode *dir,
4203                 struct dentry *dentry, const char *oldname)
4204 {
4205         int error = may_create(mnt_userns, dir, dentry);
4206
4207         if (error)
4208                 return error;
4209
4210         if (!dir->i_op->symlink)
4211                 return -EPERM;
4212
4213         error = security_inode_symlink(dir, dentry, oldname);
4214         if (error)
4215                 return error;
4216
4217         error = dir->i_op->symlink(mnt_userns, dir, dentry, oldname);
4218         if (!error)
4219                 fsnotify_create(dir, dentry);
4220         return error;
4221 }
4222 EXPORT_SYMBOL(vfs_symlink);
4223
4224 int do_symlinkat(struct filename *from, int newdfd, struct filename *to)
4225 {
4226         int error;
4227         struct dentry *dentry;
4228         struct path path;
4229         unsigned int lookup_flags = 0;
4230
4231         if (IS_ERR(from)) {
4232                 error = PTR_ERR(from);
4233                 goto out_putnames;
4234         }
4235 retry:
4236         dentry = __filename_create(newdfd, to, &path, lookup_flags);
4237         error = PTR_ERR(dentry);
4238         if (IS_ERR(dentry))
4239                 goto out_putnames;
4240
4241         error = security_path_symlink(&path, dentry, from->name);
4242         if (!error) {
4243                 struct user_namespace *mnt_userns;
4244
4245                 mnt_userns = mnt_user_ns(path.mnt);
4246                 error = vfs_symlink(mnt_userns, path.dentry->d_inode, dentry,
4247                                     from->name);
4248         }
4249         done_path_create(&path, dentry);
4250         if (retry_estale(error, lookup_flags)) {
4251                 lookup_flags |= LOOKUP_REVAL;
4252                 goto retry;
4253         }
4254 out_putnames:
4255         putname(to);
4256         putname(from);
4257         return error;
4258 }
4259
4260 SYSCALL_DEFINE3(symlinkat, const char __user *, oldname,
4261                 int, newdfd, const char __user *, newname)
4262 {
4263         return do_symlinkat(getname(oldname), newdfd, getname(newname));
4264 }
4265
4266 SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname)
4267 {
4268         return do_symlinkat(getname(oldname), AT_FDCWD, getname(newname));
4269 }
4270
4271 /**
4272  * vfs_link - create a new link
4273  * @old_dentry: object to be linked
4274  * @mnt_userns: the user namespace of the mount
4275  * @dir:        new parent
4276  * @new_dentry: where to create the new link
4277  * @delegated_inode: returns inode needing a delegation break
4278  *
4279  * The caller must hold dir->i_mutex
4280  *
4281  * If vfs_link discovers a delegation on the to-be-linked file in need
4282  * of breaking, it will return -EWOULDBLOCK and return a reference to the
4283  * inode in delegated_inode.  The caller should then break the delegation
4284  * and retry.  Because breaking a delegation may take a long time, the
4285  * caller should drop the i_mutex before doing so.
4286  *
4287  * Alternatively, a caller may pass NULL for delegated_inode.  This may
4288  * be appropriate for callers that expect the underlying filesystem not
4289  * to be NFS exported.
4290  *
4291  * If the inode has been found through an idmapped mount the user namespace of
4292  * the vfsmount must be passed through @mnt_userns. This function will then take
4293  * care to map the inode according to @mnt_userns before checking permissions.
4294  * On non-idmapped mounts or if permission checking is to be performed on the
4295  * raw inode simply passs init_user_ns.
4296  */
4297 int vfs_link(struct dentry *old_dentry, struct user_namespace *mnt_userns,
4298              struct inode *dir, struct dentry *new_dentry,
4299              struct inode **delegated_inode)
4300 {
4301         struct inode *inode = old_dentry->d_inode;
4302         unsigned max_links = dir->i_sb->s_max_links;
4303         int error;
4304
4305         if (!inode)
4306                 return -ENOENT;
4307
4308         error = may_create(mnt_userns, dir, new_dentry);
4309         if (error)
4310                 return error;
4311
4312         if (dir->i_sb != inode->i_sb)
4313                 return -EXDEV;
4314
4315         /*
4316          * A link to an append-only or immutable file cannot be created.
4317          */
4318         if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
4319                 return -EPERM;
4320         /*
4321          * Updating the link count will likely cause i_uid and i_gid to
4322          * be writen back improperly if their true value is unknown to
4323          * the vfs.
4324          */
4325         if (HAS_UNMAPPED_ID(mnt_userns, inode))
4326                 return -EPERM;
4327         if (!dir->i_op->link)
4328                 return -EPERM;
4329         if (S_ISDIR(inode->i_mode))
4330                 return -EPERM;
4331
4332         error = security_inode_link(old_dentry, dir, new_dentry);
4333         if (error)
4334                 return error;
4335
4336         inode_lock(inode);
4337         /* Make sure we don't allow creating hardlink to an unlinked file */
4338         if (inode->i_nlink == 0 && !(inode->i_state & I_LINKABLE))
4339                 error =  -ENOENT;
4340         else if (max_links && inode->i_nlink >= max_links)
4341                 error = -EMLINK;
4342         else {
4343                 error = try_break_deleg(inode, delegated_inode);
4344                 if (!error)
4345                         error = dir->i_op->link(old_dentry, dir, new_dentry);
4346         }
4347
4348         if (!error && (inode->i_state & I_LINKABLE)) {
4349                 spin_lock(&inode->i_lock);
4350                 inode->i_state &= ~I_LINKABLE;
4351                 spin_unlock(&inode->i_lock);
4352         }
4353         inode_unlock(inode);
4354         if (!error)
4355                 fsnotify_link(dir, inode, new_dentry);
4356         return error;
4357 }
4358 EXPORT_SYMBOL(vfs_link);
4359
4360 /*
4361  * Hardlinks are often used in delicate situations.  We avoid
4362  * security-related surprises by not following symlinks on the
4363  * newname.  --KAB
4364  *
4365  * We don't follow them on the oldname either to be compatible
4366  * with linux 2.0, and to avoid hard-linking to directories
4367  * and other special files.  --ADM
4368  */
4369 int do_linkat(int olddfd, struct filename *old, int newdfd,
4370               struct filename *new, int flags)
4371 {
4372         struct user_namespace *mnt_userns;
4373         struct dentry *new_dentry;
4374         struct path old_path, new_path;
4375         struct inode *delegated_inode = NULL;
4376         int how = 0;
4377         int error;
4378
4379         if ((flags & ~(AT_SYMLINK_FOLLOW | AT_EMPTY_PATH)) != 0) {
4380                 error = -EINVAL;
4381                 goto out_putnames;
4382         }
4383         /*
4384          * To use null names we require CAP_DAC_READ_SEARCH
4385          * This ensures that not everyone will be able to create
4386          * handlink using the passed filedescriptor.
4387          */
4388         if (flags & AT_EMPTY_PATH && !capable(CAP_DAC_READ_SEARCH)) {
4389                 error = -ENOENT;
4390                 goto out_putnames;
4391         }
4392
4393         if (flags & AT_SYMLINK_FOLLOW)
4394                 how |= LOOKUP_FOLLOW;
4395 retry:
4396         error = __filename_lookup(olddfd, old, how, &old_path, NULL);
4397         if (error)
4398                 goto out_putnames;
4399
4400         new_dentry = __filename_create(newdfd, new, &new_path,
4401                                         (how & LOOKUP_REVAL));
4402         error = PTR_ERR(new_dentry);
4403         if (IS_ERR(new_dentry))
4404                 goto out_putpath;
4405
4406         error = -EXDEV;
4407         if (old_path.mnt != new_path.mnt)
4408                 goto out_dput;
4409         mnt_userns = mnt_user_ns(new_path.mnt);
4410         error = may_linkat(mnt_userns, &old_path);
4411         if (unlikely(error))
4412                 goto out_dput;
4413         error = security_path_link(old_path.dentry, &new_path, new_dentry);
4414         if (error)
4415                 goto out_dput;
4416         error = vfs_link(old_path.dentry, mnt_userns, new_path.dentry->d_inode,
4417                          new_dentry, &delegated_inode);
4418 out_dput:
4419         done_path_create(&new_path, new_dentry);
4420         if (delegated_inode) {
4421                 error = break_deleg_wait(&delegated_inode);
4422                 if (!error) {
4423                         path_put(&old_path);
4424                         goto retry;
4425                 }
4426         }
4427         if (retry_estale(error, how)) {
4428                 path_put(&old_path);
4429                 how |= LOOKUP_REVAL;
4430                 goto retry;
4431         }
4432 out_putpath:
4433         path_put(&old_path);
4434 out_putnames:
4435         putname(old);
4436         putname(new);
4437
4438         return error;
4439 }
4440
4441 SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname,
4442                 int, newdfd, const char __user *, newname, int, flags)
4443 {
4444         return do_linkat(olddfd, getname_uflags(oldname, flags),
4445                 newdfd, getname(newname), flags);
4446 }
4447
4448 SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname)
4449 {
4450         return do_linkat(AT_FDCWD, getname(oldname), AT_FDCWD, getname(newname), 0);
4451 }
4452
4453 /**
4454  * vfs_rename - rename a filesystem object
4455  * @rd:         pointer to &struct renamedata info
4456  *
4457  * The caller must hold multiple mutexes--see lock_rename()).
4458  *
4459  * If vfs_rename discovers a delegation in need of breaking at either
4460  * the source or destination, it will return -EWOULDBLOCK and return a
4461  * reference to the inode in delegated_inode.  The caller should then
4462  * break the delegation and retry.  Because breaking a delegation may
4463  * take a long time, the caller should drop all locks before doing
4464  * so.
4465  *
4466  * Alternatively, a caller may pass NULL for delegated_inode.  This may
4467  * be appropriate for callers that expect the underlying filesystem not
4468  * to be NFS exported.
4469  *
4470  * The worst of all namespace operations - renaming directory. "Perverted"
4471  * doesn't even start to describe it. Somebody in UCB had a heck of a trip...
4472  * Problems:
4473  *
4474  *      a) we can get into loop creation.
4475  *      b) race potential - two innocent renames can create a loop together.
4476  *         That's where 4.4 screws up. Current fix: serialization on
4477  *         sb->s_vfs_rename_mutex. We might be more accurate, but that's another
4478  *         story.
4479  *      c) we have to lock _four_ objects - parents and victim (if it exists),
4480  *         and source (if it is not a directory).
4481  *         And that - after we got ->i_mutex on parents (until then we don't know
4482  *         whether the target exists).  Solution: try to be smart with locking
4483  *         order for inodes.  We rely on the fact that tree topology may change
4484  *         only under ->s_vfs_rename_mutex _and_ that parent of the object we
4485  *         move will be locked.  Thus we can rank directories by the tree
4486  *         (ancestors first) and rank all non-directories after them.
4487  *         That works since everybody except rename does "lock parent, lookup,
4488  *         lock child" and rename is under ->s_vfs_rename_mutex.
4489  *         HOWEVER, it relies on the assumption that any object with ->lookup()
4490  *         has no more than 1 dentry.  If "hybrid" objects will ever appear,
4491  *         we'd better make sure that there's no link(2) for them.
4492  *      d) conversion from fhandle to dentry may come in the wrong moment - when
4493  *         we are removing the target. Solution: we will have to grab ->i_mutex
4494  *         in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on
4495  *         ->i_mutex on parents, which works but leads to some truly excessive
4496  *         locking].
4497  */
4498 int vfs_rename(struct renamedata *rd)
4499 {
4500         int error;
4501         struct inode *old_dir = rd->old_dir, *new_dir = rd->new_dir;
4502         struct dentry *old_dentry = rd->old_dentry;
4503         struct dentry *new_dentry = rd->new_dentry;
4504         struct inode **delegated_inode = rd->delegated_inode;
4505         unsigned int flags = rd->flags;
4506         bool is_dir = d_is_dir(old_dentry);
4507         struct inode *source = old_dentry->d_inode;
4508         struct inode *target = new_dentry->d_inode;
4509         bool new_is_dir = false;
4510         unsigned max_links = new_dir->i_sb->s_max_links;
4511         struct name_snapshot old_name;
4512
4513         if (source == target)
4514                 return 0;
4515
4516         error = may_delete(rd->old_mnt_userns, old_dir, old_dentry, is_dir);
4517         if (error)
4518                 return error;
4519
4520         if (!target) {
4521                 error = may_create(rd->new_mnt_userns, new_dir, new_dentry);
4522         } else {
4523                 new_is_dir = d_is_dir(new_dentry);
4524
4525                 if (!(flags & RENAME_EXCHANGE))
4526                         error = may_delete(rd->new_mnt_userns, new_dir,
4527                                            new_dentry, is_dir);
4528                 else
4529                         error = may_delete(rd->new_mnt_userns, new_dir,
4530                                            new_dentry, new_is_dir);
4531         }
4532         if (error)
4533                 return error;
4534
4535         if (!old_dir->i_op->rename)
4536                 return -EPERM;
4537
4538         /*
4539          * If we are going to change the parent - check write permissions,
4540          * we'll need to flip '..'.
4541          */
4542         if (new_dir != old_dir) {
4543                 if (is_dir) {
4544                         error = inode_permission(rd->old_mnt_userns, source,
4545                                                  MAY_WRITE);
4546                         if (error)
4547                                 return error;
4548                 }
4549                 if ((flags & RENAME_EXCHANGE) && new_is_dir) {
4550                         error = inode_permission(rd->new_mnt_userns, target,
4551                                                  MAY_WRITE);
4552                         if (error)
4553                                 return error;
4554                 }
4555         }
4556
4557         error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,
4558                                       flags);
4559         if (error)
4560                 return error;
4561
4562         take_dentry_name_snapshot(&old_name, old_dentry);
4563         dget(new_dentry);
4564         if (!is_dir || (flags & RENAME_EXCHANGE))
4565                 lock_two_nondirectories(source, target);
4566         else if (target)
4567                 inode_lock(target);
4568
4569         error = -EBUSY;
4570         if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
4571                 goto out;
4572
4573         if (max_links && new_dir != old_dir) {
4574                 error = -EMLINK;
4575                 if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)
4576                         goto out;
4577                 if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&
4578                     old_dir->i_nlink >= max_links)
4579                         goto out;
4580         }
4581         if (!is_dir) {
4582                 error = try_break_deleg(source, delegated_inode);
4583                 if (error)
4584                         goto out;
4585         }
4586         if (target && !new_is_dir) {
4587                 error = try_break_deleg(target, delegated_inode);
4588                 if (error)
4589                         goto out;
4590         }
4591         error = old_dir->i_op->rename(rd->new_mnt_userns, old_dir, old_dentry,
4592                                       new_dir, new_dentry, flags);
4593         if (error)
4594                 goto out;
4595
4596         if (!(flags & RENAME_EXCHANGE) && target) {
4597                 if (is_dir) {
4598                         shrink_dcache_parent(new_dentry);
4599                         target->i_flags |= S_DEAD;
4600                 }
4601                 dont_mount(new_dentry);
4602                 detach_mounts(new_dentry);
4603         }
4604         if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {
4605                 if (!(flags & RENAME_EXCHANGE))
4606                         d_move(old_dentry, new_dentry);
4607                 else
4608                         d_exchange(old_dentry, new_dentry);
4609         }
4610 out:
4611         if (!is_dir || (flags & RENAME_EXCHANGE))
4612                 unlock_two_nondirectories(source, target);
4613         else if (target)
4614                 inode_unlock(target);
4615         dput(new_dentry);
4616         if (!error) {
4617                 fsnotify_move(old_dir, new_dir, &old_name.name, is_dir,
4618                               !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);
4619                 if (flags & RENAME_EXCHANGE) {
4620                         fsnotify_move(new_dir, old_dir, &old_dentry->d_name,
4621                                       new_is_dir, NULL, new_dentry);
4622                 }
4623         }
4624         release_dentry_name_snapshot(&old_name);
4625
4626         return error;
4627 }
4628 EXPORT_SYMBOL(vfs_rename);
4629
4630 int do_renameat2(int olddfd, struct filename *from, int newdfd,
4631                  struct filename *to, unsigned int flags)
4632 {
4633         struct renamedata rd;
4634         struct dentry *old_dentry, *new_dentry;
4635         struct dentry *trap;
4636         struct path old_path, new_path;
4637         struct qstr old_last, new_last;
4638         int old_type, new_type;
4639         struct inode *delegated_inode = NULL;
4640         unsigned int lookup_flags = 0, target_flags = LOOKUP_RENAME_TARGET;
4641         bool should_retry = false;
4642         int error = -EINVAL;
4643
4644         if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
4645                 goto put_names;
4646
4647         if ((flags & (RENAME_NOREPLACE | RENAME_WHITEOUT)) &&
4648             (flags & RENAME_EXCHANGE))
4649                 goto put_names;
4650
4651         if (flags & RENAME_EXCHANGE)
4652                 target_flags = 0;
4653
4654 retry:
4655         error = __filename_parentat(olddfd, from, lookup_flags, &old_path,
4656                                         &old_last, &old_type);
4657         if (error)
4658                 goto put_names;
4659
4660         error = __filename_parentat(newdfd, to, lookup_flags, &new_path, &new_last,
4661                                 &new_type);
4662         if (error)
4663                 goto exit1;
4664
4665         error = -EXDEV;
4666         if (old_path.mnt != new_path.mnt)
4667                 goto exit2;
4668
4669         error = -EBUSY;
4670         if (old_type != LAST_NORM)
4671                 goto exit2;
4672
4673         if (flags & RENAME_NOREPLACE)
4674                 error = -EEXIST;
4675         if (new_type != LAST_NORM)
4676                 goto exit2;
4677
4678         error = mnt_want_write(old_path.mnt);
4679         if (error)
4680                 goto exit2;
4681
4682 retry_deleg:
4683         trap = lock_rename(new_path.dentry, old_path.dentry);
4684
4685         old_dentry = __lookup_hash(&old_last, old_path.dentry, lookup_flags);
4686         error = PTR_ERR(old_dentry);
4687         if (IS_ERR(old_dentry))
4688                 goto exit3;
4689         /* source must exist */
4690         error = -ENOENT;
4691         if (d_is_negative(old_dentry))
4692                 goto exit4;
4693         new_dentry = __lookup_hash(&new_last, new_path.dentry, lookup_flags | target_flags);
4694         error = PTR_ERR(new_dentry);
4695         if (IS_ERR(new_dentry))
4696                 goto exit4;
4697         error = -EEXIST;
4698         if ((flags & RENAME_NOREPLACE) && d_is_positive(new_dentry))
4699                 goto exit5;
4700         if (flags & RENAME_EXCHANGE) {
4701                 error = -ENOENT;
4702                 if (d_is_negative(new_dentry))
4703                         goto exit5;
4704
4705                 if (!d_is_dir(new_dentry)) {
4706                         error = -ENOTDIR;
4707                         if (new_last.name[new_last.len])
4708                                 goto exit5;
4709                 }
4710         }
4711         /* unless the source is a directory trailing slashes give -ENOTDIR */
4712         if (!d_is_dir(old_dentry)) {
4713                 error = -ENOTDIR;
4714                 if (old_last.name[old_last.len])
4715                         goto exit5;
4716                 if (!(flags & RENAME_EXCHANGE) && new_last.name[new_last.len])
4717                         goto exit5;
4718         }
4719         /* source should not be ancestor of target */
4720         error = -EINVAL;
4721         if (old_dentry == trap)
4722                 goto exit5;
4723         /* target should not be an ancestor of source */
4724         if (!(flags & RENAME_EXCHANGE))
4725                 error = -ENOTEMPTY;
4726         if (new_dentry == trap)
4727                 goto exit5;
4728
4729         error = security_path_rename(&old_path, old_dentry,
4730                                      &new_path, new_dentry, flags);
4731         if (error)
4732                 goto exit5;
4733
4734         rd.old_dir         = old_path.dentry->d_inode;
4735         rd.old_dentry      = old_dentry;
4736         rd.old_mnt_userns  = mnt_user_ns(old_path.mnt);
4737         rd.new_dir         = new_path.dentry->d_inode;
4738         rd.new_dentry      = new_dentry;
4739         rd.new_mnt_userns  = mnt_user_ns(new_path.mnt);
4740         rd.delegated_inode = &delegated_inode;
4741         rd.flags           = flags;
4742         error = vfs_rename(&rd);
4743 exit5:
4744         dput(new_dentry);
4745 exit4:
4746         dput(old_dentry);
4747 exit3:
4748         unlock_rename(new_path.dentry, old_path.dentry);
4749         if (delegated_inode) {
4750                 error = break_deleg_wait(&delegated_inode);
4751                 if (!error)
4752                         goto retry_deleg;
4753         }
4754         mnt_drop_write(old_path.mnt);
4755 exit2:
4756         if (retry_estale(error, lookup_flags))
4757                 should_retry = true;
4758         path_put(&new_path);
4759 exit1:
4760         path_put(&old_path);
4761         if (should_retry) {
4762                 should_retry = false;
4763                 lookup_flags |= LOOKUP_REVAL;
4764                 goto retry;
4765         }
4766 put_names:
4767         putname(from);
4768         putname(to);
4769         return error;
4770 }
4771
4772 SYSCALL_DEFINE5(renameat2, int, olddfd, const char __user *, oldname,
4773                 int, newdfd, const char __user *, newname, unsigned int, flags)
4774 {
4775         return do_renameat2(olddfd, getname(oldname), newdfd, getname(newname),
4776                                 flags);
4777 }
4778
4779 SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname,
4780                 int, newdfd, const char __user *, newname)
4781 {
4782         return do_renameat2(olddfd, getname(oldname), newdfd, getname(newname),
4783                                 0);
4784 }
4785
4786 SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname)
4787 {
4788         return do_renameat2(AT_FDCWD, getname(oldname), AT_FDCWD,
4789                                 getname(newname), 0);
4790 }
4791
4792 int readlink_copy(char __user *buffer, int buflen, const char *link)
4793 {
4794         int len = PTR_ERR(link);
4795         if (IS_ERR(link))
4796                 goto out;
4797
4798         len = strlen(link);
4799         if (len > (unsigned) buflen)
4800                 len = buflen;
4801         if (copy_to_user(buffer, link, len))
4802                 len = -EFAULT;
4803 out:
4804         return len;
4805 }
4806
4807 /**
4808  * vfs_readlink - copy symlink body into userspace buffer
4809  * @dentry: dentry on which to get symbolic link
4810  * @buffer: user memory pointer
4811  * @buflen: size of buffer
4812  *
4813  * Does not touch atime.  That's up to the caller if necessary
4814  *
4815  * Does not call security hook.
4816  */
4817 int vfs_readlink(struct dentry *dentry, char __user *buffer, int buflen)
4818 {
4819         struct inode *inode = d_inode(dentry);
4820         DEFINE_DELAYED_CALL(done);
4821         const char *link;
4822         int res;
4823
4824         if (unlikely(!(inode->i_opflags & IOP_DEFAULT_READLINK))) {
4825                 if (unlikely(inode->i_op->readlink))
4826                         return inode->i_op->readlink(dentry, buffer, buflen);
4827
4828                 if (!d_is_symlink(dentry))
4829                         return -EINVAL;
4830
4831                 spin_lock(&inode->i_lock);
4832                 inode->i_opflags |= IOP_DEFAULT_READLINK;
4833                 spin_unlock(&inode->i_lock);
4834         }
4835
4836         link = READ_ONCE(inode->i_link);
4837         if (!link) {
4838                 link = inode->i_op->get_link(dentry, inode, &done);
4839                 if (IS_ERR(link))
4840                         return PTR_ERR(link);
4841         }
4842         res = readlink_copy(buffer, buflen, link);
4843         do_delayed_call(&done);
4844         return res;
4845 }
4846 EXPORT_SYMBOL(vfs_readlink);
4847
4848 /**
4849  * vfs_get_link - get symlink body
4850  * @dentry: dentry on which to get symbolic link
4851  * @done: caller needs to free returned data with this
4852  *
4853  * Calls security hook and i_op->get_link() on the supplied inode.
4854  *
4855  * It does not touch atime.  That's up to the caller if necessary.
4856  *
4857  * Does not work on "special" symlinks like /proc/$$/fd/N
4858  */
4859 const char *vfs_get_link(struct dentry *dentry, struct delayed_call *done)
4860 {
4861         const char *res = ERR_PTR(-EINVAL);
4862         struct inode *inode = d_inode(dentry);
4863
4864         if (d_is_symlink(dentry)) {
4865                 res = ERR_PTR(security_inode_readlink(dentry));
4866                 if (!res)
4867                         res = inode->i_op->get_link(dentry, inode, done);
4868         }
4869         return res;
4870 }
4871 EXPORT_SYMBOL(vfs_get_link);
4872
4873 /* get the link contents into pagecache */
4874 const char *page_get_link(struct dentry *dentry, struct inode *inode,
4875                           struct delayed_call *callback)
4876 {
4877         char *kaddr;
4878         struct page *page;
4879         struct address_space *mapping = inode->i_mapping;
4880
4881         if (!dentry) {
4882                 page = find_get_page(mapping, 0);
4883                 if (!page)
4884                         return ERR_PTR(-ECHILD);
4885                 if (!PageUptodate(page)) {
4886                         put_page(page);
4887                         return ERR_PTR(-ECHILD);
4888                 }
4889         } else {
4890                 page = read_mapping_page(mapping, 0, NULL);
4891                 if (IS_ERR(page))
4892                         return (char*)page;
4893         }
4894         set_delayed_call(callback, page_put_link, page);
4895         BUG_ON(mapping_gfp_mask(mapping) & __GFP_HIGHMEM);
4896         kaddr = page_address(page);
4897         nd_terminate_link(kaddr, inode->i_size, PAGE_SIZE - 1);
4898         return kaddr;
4899 }
4900
4901 EXPORT_SYMBOL(page_get_link);
4902
4903 void page_put_link(void *arg)
4904 {
4905         put_page(arg);
4906 }
4907 EXPORT_SYMBOL(page_put_link);
4908
4909 int page_readlink(struct dentry *dentry, char __user *buffer, int buflen)
4910 {
4911         DEFINE_DELAYED_CALL(done);
4912         int res = readlink_copy(buffer, buflen,
4913                                 page_get_link(dentry, d_inode(dentry),
4914                                               &done));
4915         do_delayed_call(&done);
4916         return res;
4917 }
4918 EXPORT_SYMBOL(page_readlink);
4919
4920 /*
4921  * The nofs argument instructs pagecache_write_begin to pass AOP_FLAG_NOFS
4922  */
4923 int __page_symlink(struct inode *inode, const char *symname, int len, int nofs)
4924 {
4925         struct address_space *mapping = inode->i_mapping;
4926         struct page *page;
4927         void *fsdata;
4928         int err;
4929         unsigned int flags = 0;
4930         if (nofs)
4931                 flags |= AOP_FLAG_NOFS;
4932
4933 retry:
4934         err = pagecache_write_begin(NULL, mapping, 0, len-1,
4935                                 flags, &page, &fsdata);
4936         if (err)
4937                 goto fail;
4938
4939         memcpy(page_address(page), symname, len-1);
4940
4941         err = pagecache_write_end(NULL, mapping, 0, len-1, len-1,
4942                                                         page, fsdata);
4943         if (err < 0)
4944                 goto fail;
4945         if (err < len-1)
4946                 goto retry;
4947
4948         mark_inode_dirty(inode);
4949         return 0;
4950 fail:
4951         return err;
4952 }
4953 EXPORT_SYMBOL(__page_symlink);
4954
4955 int page_symlink(struct inode *inode, const char *symname, int len)
4956 {
4957         return __page_symlink(inode, symname, len,
4958                         !mapping_gfp_constraint(inode->i_mapping, __GFP_FS));
4959 }
4960 EXPORT_SYMBOL(page_symlink);
4961
4962 const struct inode_operations page_symlink_inode_operations = {
4963         .get_link       = page_get_link,
4964 };
4965 EXPORT_SYMBOL(page_symlink_inode_operations);