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