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