1 // SPDX-License-Identifier: GPL-2.0
5 * Copyright (C) 1991, 1992 Linus Torvalds
9 * Some corrections by tytso.
12 /* [Feb 1997 T. Schoebel-Theuer] Complete rewrite of the pathname
15 /* [Feb-Apr 2000, AV] Rewrite to the new namespace architecture.
18 #include <linux/init.h>
19 #include <linux/export.h>
20 #include <linux/kernel.h>
21 #include <linux/slab.h>
23 #include <linux/namei.h>
24 #include <linux/pagemap.h>
25 #include <linux/fsnotify.h>
26 #include <linux/personality.h>
27 #include <linux/security.h>
28 #include <linux/ima.h>
29 #include <linux/syscalls.h>
30 #include <linux/mount.h>
31 #include <linux/audit.h>
32 #include <linux/capability.h>
33 #include <linux/file.h>
34 #include <linux/fcntl.h>
35 #include <linux/device_cgroup.h>
36 #include <linux/fs_struct.h>
37 #include <linux/posix_acl.h>
38 #include <linux/hash.h>
39 #include <linux/bitops.h>
40 #include <linux/init_task.h>
41 #include <linux/uaccess.h>
46 /* [Feb-1997 T. Schoebel-Theuer]
47 * Fundamental changes in the pathname lookup mechanisms (namei)
48 * were necessary because of omirr. The reason is that omirr needs
49 * to know the _real_ pathname, not the user-supplied one, in case
50 * of symlinks (and also when transname replacements occur).
52 * The new code replaces the old recursive symlink resolution with
53 * an iterative one (in case of non-nested symlink chains). It does
54 * this with calls to <fs>_follow_link().
55 * As a side effect, dir_namei(), _namei() and follow_link() are now
56 * replaced with a single function lookup_dentry() that can handle all
57 * the special cases of the former code.
59 * With the new dcache, the pathname is stored at each inode, at least as
60 * long as the refcount of the inode is positive. As a side effect, the
61 * size of the dcache depends on the inode cache and thus is dynamic.
63 * [29-Apr-1998 C. Scott Ananian] Updated above description of symlink
64 * resolution to correspond with current state of the code.
66 * Note that the symlink resolution is not *completely* iterative.
67 * There is still a significant amount of tail- and mid- recursion in
68 * the algorithm. Also, note that <fs>_readlink() is not used in
69 * lookup_dentry(): lookup_dentry() on the result of <fs>_readlink()
70 * may return different results than <fs>_follow_link(). Many virtual
71 * filesystems (including /proc) exhibit this behavior.
74 /* [24-Feb-97 T. Schoebel-Theuer] Side effects caused by new implementation:
75 * New symlink semantics: when open() is called with flags O_CREAT | O_EXCL
76 * and the name already exists in form of a symlink, try to create the new
77 * name indicated by the symlink. The old code always complained that the
78 * name already exists, due to not following the symlink even if its target
79 * is nonexistent. The new semantics affects also mknod() and link() when
80 * the name is a symlink pointing to a non-existent name.
82 * I don't know which semantics is the right one, since I have no access
83 * to standards. But I found by trial that HP-UX 9.0 has the full "new"
84 * semantics implemented, while SunOS 4.1.1 and Solaris (SunOS 5.4) have the
85 * "old" one. Personally, I think the new semantics is much more logical.
86 * Note that "ln old new" where "new" is a symlink pointing to a non-existing
87 * file does succeed in both HP-UX and SunOs, but not in Solaris
88 * and in the old Linux semantics.
91 /* [16-Dec-97 Kevin Buhr] For security reasons, we change some symlink
92 * semantics. See the comments in "open_namei" and "do_link" below.
94 * [10-Sep-98 Alan Modra] Another symlink change.
97 /* [Feb-Apr 2000 AV] Complete rewrite. Rules for symlinks:
98 * inside the path - always follow.
99 * in the last component in creation/removal/renaming - never follow.
100 * if LOOKUP_FOLLOW passed - follow.
101 * if the pathname has trailing slashes - follow.
102 * otherwise - don't follow.
103 * (applied in that order).
105 * [Jun 2000 AV] Inconsistent behaviour of open() in case if flags==O_CREAT
106 * restored for 2.4. This is the last surviving part of old 4.2BSD bug.
107 * During the 2.4 we need to fix the userland stuff depending on it -
108 * hopefully we will be able to get rid of that wart in 2.5. So far only
109 * XEmacs seems to be relying on it...
112 * [Sep 2001 AV] Single-semaphore locking scheme (kudos to David Holland)
113 * implemented. Let's see if raised priority of ->s_vfs_rename_mutex gives
114 * any extra contention...
117 /* In order to reduce some races, while at the same time doing additional
118 * checking and hopefully speeding things up, we copy filenames to the
119 * kernel data space before using them..
121 * POSIX.1 2.4: an empty pathname is invalid (ENOENT).
122 * PATH_MAX includes the nul terminator --RR.
125 #define EMBEDDED_NAME_MAX (PATH_MAX - offsetof(struct filename, iname))
128 getname_flags(const char __user *filename, int flags, int *empty)
130 struct filename *result;
134 result = audit_reusename(filename);
138 result = __getname();
139 if (unlikely(!result))
140 return ERR_PTR(-ENOMEM);
143 * First, try to embed the struct filename inside the names_cache
146 kname = (char *)result->iname;
147 result->name = kname;
149 len = strncpy_from_user(kname, filename, EMBEDDED_NAME_MAX);
150 if (unlikely(len < 0)) {
156 * Uh-oh. We have a name that's approaching PATH_MAX. Allocate a
157 * separate struct filename so we can dedicate the entire
158 * names_cache allocation for the pathname, and re-do the copy from
161 if (unlikely(len == EMBEDDED_NAME_MAX)) {
162 const size_t size = offsetof(struct filename, iname[1]);
163 kname = (char *)result;
166 * size is chosen that way we to guarantee that
167 * result->iname[0] is within the same object and that
168 * kname can't be equal to result->iname, no matter what.
170 result = kzalloc(size, GFP_KERNEL);
171 if (unlikely(!result)) {
173 return ERR_PTR(-ENOMEM);
175 result->name = kname;
176 len = strncpy_from_user(kname, filename, PATH_MAX);
177 if (unlikely(len < 0)) {
182 if (unlikely(len == PATH_MAX)) {
185 return ERR_PTR(-ENAMETOOLONG);
190 /* The empty path is special. */
191 if (unlikely(!len)) {
194 if (!(flags & LOOKUP_EMPTY)) {
196 return ERR_PTR(-ENOENT);
200 result->uptr = filename;
201 result->aname = NULL;
202 audit_getname(result);
207 getname_uflags(const char __user *filename, int uflags)
209 int flags = (uflags & AT_EMPTY_PATH) ? LOOKUP_EMPTY : 0;
211 return getname_flags(filename, flags, NULL);
215 getname(const char __user * filename)
217 return getname_flags(filename, 0, NULL);
221 getname_kernel(const char * filename)
223 struct filename *result;
224 int len = strlen(filename) + 1;
226 result = __getname();
227 if (unlikely(!result))
228 return ERR_PTR(-ENOMEM);
230 if (len <= EMBEDDED_NAME_MAX) {
231 result->name = (char *)result->iname;
232 } else if (len <= PATH_MAX) {
233 const size_t size = offsetof(struct filename, iname[1]);
234 struct filename *tmp;
236 tmp = kmalloc(size, GFP_KERNEL);
237 if (unlikely(!tmp)) {
239 return ERR_PTR(-ENOMEM);
241 tmp->name = (char *)result;
245 return ERR_PTR(-ENAMETOOLONG);
247 memcpy((char *)result->name, filename, len);
249 result->aname = NULL;
251 audit_getname(result);
256 void putname(struct filename *name)
261 BUG_ON(name->refcnt <= 0);
263 if (--name->refcnt > 0)
266 if (name->name != name->iname) {
267 __putname(name->name);
274 * check_acl - perform ACL permission checking
275 * @mnt_userns: user namespace of the mount the inode was found from
276 * @inode: inode to check permissions on
277 * @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
279 * This function performs the ACL permission checking. Since this function
280 * retrieve POSIX acls it needs to know whether it is called from a blocking or
281 * non-blocking context and thus cares about the MAY_NOT_BLOCK bit.
283 * If the inode has been found through an idmapped mount the user namespace of
284 * the vfsmount must be passed through @mnt_userns. This function will then take
285 * care to map the inode according to @mnt_userns before checking permissions.
286 * On non-idmapped mounts or if permission checking is to be performed on the
287 * raw inode simply passs init_user_ns.
289 static int check_acl(struct user_namespace *mnt_userns,
290 struct inode *inode, int mask)
292 #ifdef CONFIG_FS_POSIX_ACL
293 struct posix_acl *acl;
295 if (mask & MAY_NOT_BLOCK) {
296 acl = get_cached_acl_rcu(inode, ACL_TYPE_ACCESS);
299 /* no ->get_acl() calls in RCU mode... */
300 if (is_uncached_acl(acl))
302 return posix_acl_permission(mnt_userns, inode, acl, mask);
305 acl = get_acl(inode, ACL_TYPE_ACCESS);
309 int error = posix_acl_permission(mnt_userns, inode, acl, mask);
310 posix_acl_release(acl);
319 * acl_permission_check - perform basic UNIX permission checking
320 * @mnt_userns: user namespace of the mount the inode was found from
321 * @inode: inode to check permissions on
322 * @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
324 * This function performs the basic UNIX permission checking. Since this
325 * function may retrieve POSIX acls it needs to know whether it is called from a
326 * blocking or non-blocking context and thus cares about the MAY_NOT_BLOCK bit.
328 * If the inode has been found through an idmapped mount the user namespace of
329 * the vfsmount must be passed through @mnt_userns. This function will then take
330 * care to map the inode according to @mnt_userns before checking permissions.
331 * On non-idmapped mounts or if permission checking is to be performed on the
332 * raw inode simply passs init_user_ns.
334 static int acl_permission_check(struct user_namespace *mnt_userns,
335 struct inode *inode, int mask)
337 unsigned int mode = inode->i_mode;
340 /* Are we the owner? If so, ACL's don't matter */
341 i_uid = i_uid_into_mnt(mnt_userns, inode);
342 if (likely(uid_eq(current_fsuid(), i_uid))) {
345 return (mask & ~mode) ? -EACCES : 0;
348 /* Do we have ACL's? */
349 if (IS_POSIXACL(inode) && (mode & S_IRWXG)) {
350 int error = check_acl(mnt_userns, inode, mask);
351 if (error != -EAGAIN)
355 /* Only RWX matters for group/other mode bits */
359 * Are the group permissions different from
360 * the other permissions in the bits we care
361 * about? Need to check group ownership if so.
363 if (mask & (mode ^ (mode >> 3))) {
364 kgid_t kgid = i_gid_into_mnt(mnt_userns, inode);
365 if (in_group_p(kgid))
369 /* Bits in 'mode' clear that we require? */
370 return (mask & ~mode) ? -EACCES : 0;
374 * generic_permission - check for access rights on a Posix-like filesystem
375 * @mnt_userns: user namespace of the mount the inode was found from
376 * @inode: inode to check access rights for
377 * @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC,
378 * %MAY_NOT_BLOCK ...)
380 * Used to check for read/write/execute permissions on a file.
381 * We use "fsuid" for this, letting us set arbitrary permissions
382 * for filesystem access without changing the "normal" uids which
383 * are used for other things.
385 * generic_permission is rcu-walk aware. It returns -ECHILD in case an rcu-walk
386 * request cannot be satisfied (eg. requires blocking or too much complexity).
387 * It would then be called again in ref-walk mode.
389 * If the inode has been found through an idmapped mount the user namespace of
390 * the vfsmount must be passed through @mnt_userns. This function will then take
391 * care to map the inode according to @mnt_userns before checking permissions.
392 * On non-idmapped mounts or if permission checking is to be performed on the
393 * raw inode simply passs init_user_ns.
395 int generic_permission(struct user_namespace *mnt_userns, struct inode *inode,
401 * Do the basic permission checks.
403 ret = acl_permission_check(mnt_userns, inode, mask);
407 if (S_ISDIR(inode->i_mode)) {
408 /* DACs are overridable for directories */
409 if (!(mask & MAY_WRITE))
410 if (capable_wrt_inode_uidgid(mnt_userns, inode,
411 CAP_DAC_READ_SEARCH))
413 if (capable_wrt_inode_uidgid(mnt_userns, inode,
420 * Searching includes executable on directories, else just read.
422 mask &= MAY_READ | MAY_WRITE | MAY_EXEC;
423 if (mask == MAY_READ)
424 if (capable_wrt_inode_uidgid(mnt_userns, inode,
425 CAP_DAC_READ_SEARCH))
428 * Read/write DACs are always overridable.
429 * Executable DACs are overridable when there is
430 * at least one exec bit set.
432 if (!(mask & MAY_EXEC) || (inode->i_mode & S_IXUGO))
433 if (capable_wrt_inode_uidgid(mnt_userns, inode,
439 EXPORT_SYMBOL(generic_permission);
442 * do_inode_permission - UNIX permission checking
443 * @mnt_userns: user namespace of the mount the inode was found from
444 * @inode: inode to check permissions on
445 * @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
447 * We _really_ want to just do "generic_permission()" without
448 * even looking at the inode->i_op values. So we keep a cache
449 * flag in inode->i_opflags, that says "this has not special
450 * permission function, use the fast case".
452 static inline int do_inode_permission(struct user_namespace *mnt_userns,
453 struct inode *inode, int mask)
455 if (unlikely(!(inode->i_opflags & IOP_FASTPERM))) {
456 if (likely(inode->i_op->permission))
457 return inode->i_op->permission(mnt_userns, inode, mask);
459 /* This gets set once for the inode lifetime */
460 spin_lock(&inode->i_lock);
461 inode->i_opflags |= IOP_FASTPERM;
462 spin_unlock(&inode->i_lock);
464 return generic_permission(mnt_userns, inode, mask);
468 * sb_permission - Check superblock-level permissions
469 * @sb: Superblock of inode to check permission on
470 * @inode: Inode to check permission on
471 * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
473 * Separate out file-system wide checks from inode-specific permission checks.
475 static int sb_permission(struct super_block *sb, struct inode *inode, int mask)
477 if (unlikely(mask & MAY_WRITE)) {
478 umode_t mode = inode->i_mode;
480 /* Nobody gets write access to a read-only fs. */
481 if (sb_rdonly(sb) && (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode)))
488 * inode_permission - Check for access rights to a given inode
489 * @mnt_userns: User namespace of the mount the inode was found from
490 * @inode: Inode to check permission on
491 * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
493 * Check for read/write/execute permissions on an inode. We use fs[ug]id for
494 * this, letting us set arbitrary permissions for filesystem access without
495 * changing the "normal" UIDs which are used for other things.
497 * When checking for MAY_APPEND, MAY_WRITE must also be set in @mask.
499 int inode_permission(struct user_namespace *mnt_userns,
500 struct inode *inode, int mask)
504 retval = sb_permission(inode->i_sb, inode, mask);
508 if (unlikely(mask & MAY_WRITE)) {
510 * Nobody gets write access to an immutable file.
512 if (IS_IMMUTABLE(inode))
516 * Updating mtime will likely cause i_uid and i_gid to be
517 * written back improperly if their true value is unknown
520 if (HAS_UNMAPPED_ID(mnt_userns, inode))
524 retval = do_inode_permission(mnt_userns, inode, mask);
528 retval = devcgroup_inode_permission(inode, mask);
532 return security_inode_permission(inode, mask);
534 EXPORT_SYMBOL(inode_permission);
537 * path_get - get a reference to a path
538 * @path: path to get the reference to
540 * Given a path increment the reference count to the dentry and the vfsmount.
542 void path_get(const struct path *path)
547 EXPORT_SYMBOL(path_get);
550 * path_put - put a reference to a path
551 * @path: path to put the reference to
553 * Given a path decrement the reference count to the dentry and the vfsmount.
555 void path_put(const struct path *path)
560 EXPORT_SYMBOL(path_put);
562 #define EMBEDDED_LEVELS 2
567 struct inode *inode; /* path.dentry.d_inode */
568 unsigned int flags, state;
569 unsigned seq, m_seq, r_seq;
572 int total_link_count;
575 struct delayed_call done;
578 } *stack, internal[EMBEDDED_LEVELS];
579 struct filename *name;
580 struct nameidata *saved;
585 } __randomize_layout;
587 #define ND_ROOT_PRESET 1
588 #define ND_ROOT_GRABBED 2
591 static void __set_nameidata(struct nameidata *p, int dfd, struct filename *name)
593 struct nameidata *old = current->nameidata;
594 p->stack = p->internal;
599 p->path.dentry = NULL;
600 p->total_link_count = old ? old->total_link_count : 0;
602 current->nameidata = p;
605 static inline void set_nameidata(struct nameidata *p, int dfd, struct filename *name,
606 const struct path *root)
608 __set_nameidata(p, dfd, name);
610 if (unlikely(root)) {
611 p->state = ND_ROOT_PRESET;
616 static void restore_nameidata(void)
618 struct nameidata *now = current->nameidata, *old = now->saved;
620 current->nameidata = old;
622 old->total_link_count = now->total_link_count;
623 if (now->stack != now->internal)
627 static bool nd_alloc_stack(struct nameidata *nd)
631 p= kmalloc_array(MAXSYMLINKS, sizeof(struct saved),
632 nd->flags & LOOKUP_RCU ? GFP_ATOMIC : GFP_KERNEL);
635 memcpy(p, nd->internal, sizeof(nd->internal));
641 * path_connected - Verify that a dentry is below mnt.mnt_root
643 * Rename can sometimes move a file or directory outside of a bind
644 * mount, path_connected allows those cases to be detected.
646 static bool path_connected(struct vfsmount *mnt, struct dentry *dentry)
648 struct super_block *sb = mnt->mnt_sb;
650 /* Bind mounts can have disconnected paths */
651 if (mnt->mnt_root == sb->s_root)
654 return is_subdir(dentry, mnt->mnt_root);
657 static void drop_links(struct nameidata *nd)
661 struct saved *last = nd->stack + i;
662 do_delayed_call(&last->done);
663 clear_delayed_call(&last->done);
667 static void terminate_walk(struct nameidata *nd)
670 if (!(nd->flags & LOOKUP_RCU)) {
673 for (i = 0; i < nd->depth; i++)
674 path_put(&nd->stack[i].link);
675 if (nd->state & ND_ROOT_GRABBED) {
677 nd->state &= ~ND_ROOT_GRABBED;
680 nd->flags &= ~LOOKUP_RCU;
685 nd->path.dentry = NULL;
688 /* path_put is needed afterwards regardless of success or failure */
689 static bool __legitimize_path(struct path *path, unsigned seq, unsigned mseq)
691 int res = __legitimize_mnt(path->mnt, mseq);
698 if (unlikely(!lockref_get_not_dead(&path->dentry->d_lockref))) {
702 return !read_seqcount_retry(&path->dentry->d_seq, seq);
705 static inline bool legitimize_path(struct nameidata *nd,
706 struct path *path, unsigned seq)
708 return __legitimize_path(path, seq, nd->m_seq);
711 static bool legitimize_links(struct nameidata *nd)
714 if (unlikely(nd->flags & LOOKUP_CACHED)) {
719 for (i = 0; i < nd->depth; i++) {
720 struct saved *last = nd->stack + i;
721 if (unlikely(!legitimize_path(nd, &last->link, last->seq))) {
730 static bool legitimize_root(struct nameidata *nd)
733 * For scoped-lookups (where nd->root has been zeroed), we need to
734 * restart the whole lookup from scratch -- because set_root() is wrong
735 * for these lookups (nd->dfd is the root, not the filesystem root).
737 if (!nd->root.mnt && (nd->flags & LOOKUP_IS_SCOPED))
739 /* Nothing to do if nd->root is zero or is managed by the VFS user. */
740 if (!nd->root.mnt || (nd->state & ND_ROOT_PRESET))
742 nd->state |= ND_ROOT_GRABBED;
743 return legitimize_path(nd, &nd->root, nd->root_seq);
747 * Path walking has 2 modes, rcu-walk and ref-walk (see
748 * Documentation/filesystems/path-lookup.txt). In situations when we can't
749 * continue in RCU mode, we attempt to drop out of rcu-walk mode and grab
750 * normal reference counts on dentries and vfsmounts to transition to ref-walk
751 * mode. Refcounts are grabbed at the last known good point before rcu-walk
752 * got stuck, so ref-walk may continue from there. If this is not successful
753 * (eg. a seqcount has changed), then failure is returned and it's up to caller
754 * to restart the path walk from the beginning in ref-walk mode.
758 * try_to_unlazy - try to switch to ref-walk mode.
759 * @nd: nameidata pathwalk data
760 * Returns: true on success, false on failure
762 * try_to_unlazy attempts to legitimize the current nd->path and nd->root
764 * Must be called from rcu-walk context.
765 * Nothing should touch nameidata between try_to_unlazy() failure and
768 static bool try_to_unlazy(struct nameidata *nd)
770 struct dentry *parent = nd->path.dentry;
772 BUG_ON(!(nd->flags & LOOKUP_RCU));
774 nd->flags &= ~LOOKUP_RCU;
775 if (unlikely(!legitimize_links(nd)))
777 if (unlikely(!legitimize_path(nd, &nd->path, nd->seq)))
779 if (unlikely(!legitimize_root(nd)))
782 BUG_ON(nd->inode != parent->d_inode);
787 nd->path.dentry = NULL;
794 * try_to_unlazy_next - try to switch to ref-walk mode.
795 * @nd: nameidata pathwalk data
796 * @dentry: next dentry to step into
797 * @seq: seq number to check @dentry against
798 * Returns: true on success, false on failure
800 * Similar to to try_to_unlazy(), but here we have the next dentry already
801 * picked by rcu-walk and want to legitimize that in addition to the current
802 * nd->path and nd->root for ref-walk mode. Must be called from rcu-walk context.
803 * Nothing should touch nameidata between try_to_unlazy_next() failure and
806 static bool try_to_unlazy_next(struct nameidata *nd, struct dentry *dentry, unsigned seq)
808 BUG_ON(!(nd->flags & LOOKUP_RCU));
810 nd->flags &= ~LOOKUP_RCU;
811 if (unlikely(!legitimize_links(nd)))
813 if (unlikely(!legitimize_mnt(nd->path.mnt, nd->m_seq)))
815 if (unlikely(!lockref_get_not_dead(&nd->path.dentry->d_lockref)))
819 * We need to move both the parent and the dentry from the RCU domain
820 * to be properly refcounted. And the sequence number in the dentry
821 * validates *both* dentry counters, since we checked the sequence
822 * number of the parent after we got the child sequence number. So we
823 * know the parent must still be valid if the child sequence number is
825 if (unlikely(!lockref_get_not_dead(&dentry->d_lockref)))
827 if (unlikely(read_seqcount_retry(&dentry->d_seq, seq)))
830 * Sequence counts matched. Now make sure that the root is
831 * still valid and get it if required.
833 if (unlikely(!legitimize_root(nd)))
841 nd->path.dentry = NULL;
851 static inline int d_revalidate(struct dentry *dentry, unsigned int flags)
853 if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE))
854 return dentry->d_op->d_revalidate(dentry, flags);
860 * complete_walk - successful completion of path walk
861 * @nd: pointer nameidata
863 * If we had been in RCU mode, drop out of it and legitimize nd->path.
864 * Revalidate the final result, unless we'd already done that during
865 * the path walk or the filesystem doesn't ask for it. Return 0 on
866 * success, -error on failure. In case of failure caller does not
867 * need to drop nd->path.
869 static int complete_walk(struct nameidata *nd)
871 struct dentry *dentry = nd->path.dentry;
874 if (nd->flags & LOOKUP_RCU) {
876 * We don't want to zero nd->root for scoped-lookups or
877 * externally-managed nd->root.
879 if (!(nd->state & ND_ROOT_PRESET))
880 if (!(nd->flags & LOOKUP_IS_SCOPED))
882 nd->flags &= ~LOOKUP_CACHED;
883 if (!try_to_unlazy(nd))
887 if (unlikely(nd->flags & LOOKUP_IS_SCOPED)) {
889 * While the guarantee of LOOKUP_IS_SCOPED is (roughly) "don't
890 * ever step outside the root during lookup" and should already
891 * be guaranteed by the rest of namei, we want to avoid a namei
892 * BUG resulting in userspace being given a path that was not
893 * scoped within the root at some point during the lookup.
895 * So, do a final sanity-check to make sure that in the
896 * worst-case scenario (a complete bypass of LOOKUP_IS_SCOPED)
897 * we won't silently return an fd completely outside of the
898 * requested root to userspace.
900 * Userspace could move the path outside the root after this
901 * check, but as discussed elsewhere this is not a concern (the
902 * resolved file was inside the root at some point).
904 if (!path_is_under(&nd->path, &nd->root))
908 if (likely(!(nd->state & ND_JUMPED)))
911 if (likely(!(dentry->d_flags & DCACHE_OP_WEAK_REVALIDATE)))
914 status = dentry->d_op->d_weak_revalidate(dentry, nd->flags);
924 static int set_root(struct nameidata *nd)
926 struct fs_struct *fs = current->fs;
929 * Jumping to the real root in a scoped-lookup is a BUG in namei, but we
930 * still have to ensure it doesn't happen because it will cause a breakout
933 if (WARN_ON(nd->flags & LOOKUP_IS_SCOPED))
934 return -ENOTRECOVERABLE;
936 if (nd->flags & LOOKUP_RCU) {
940 seq = read_seqcount_begin(&fs->seq);
942 nd->root_seq = __read_seqcount_begin(&nd->root.dentry->d_seq);
943 } while (read_seqcount_retry(&fs->seq, seq));
945 get_fs_root(fs, &nd->root);
946 nd->state |= ND_ROOT_GRABBED;
951 static int nd_jump_root(struct nameidata *nd)
953 if (unlikely(nd->flags & LOOKUP_BENEATH))
955 if (unlikely(nd->flags & LOOKUP_NO_XDEV)) {
956 /* Absolute path arguments to path_init() are allowed. */
957 if (nd->path.mnt != NULL && nd->path.mnt != nd->root.mnt)
961 int error = set_root(nd);
965 if (nd->flags & LOOKUP_RCU) {
969 nd->inode = d->d_inode;
970 nd->seq = nd->root_seq;
971 if (unlikely(read_seqcount_retry(&d->d_seq, nd->seq)))
977 nd->inode = nd->path.dentry->d_inode;
979 nd->state |= ND_JUMPED;
984 * Helper to directly jump to a known parsed path from ->get_link,
985 * caller must have taken a reference to path beforehand.
987 int nd_jump_link(struct path *path)
990 struct nameidata *nd = current->nameidata;
992 if (unlikely(nd->flags & LOOKUP_NO_MAGICLINKS))
996 if (unlikely(nd->flags & LOOKUP_NO_XDEV)) {
997 if (nd->path.mnt != path->mnt)
1000 /* Not currently safe for scoped-lookups. */
1001 if (unlikely(nd->flags & LOOKUP_IS_SCOPED))
1004 path_put(&nd->path);
1006 nd->inode = nd->path.dentry->d_inode;
1007 nd->state |= ND_JUMPED;
1015 static inline void put_link(struct nameidata *nd)
1017 struct saved *last = nd->stack + --nd->depth;
1018 do_delayed_call(&last->done);
1019 if (!(nd->flags & LOOKUP_RCU))
1020 path_put(&last->link);
1023 static int sysctl_protected_symlinks __read_mostly;
1024 static int sysctl_protected_hardlinks __read_mostly;
1025 static int sysctl_protected_fifos __read_mostly;
1026 static int sysctl_protected_regular __read_mostly;
1028 #ifdef CONFIG_SYSCTL
1029 static struct ctl_table namei_sysctls[] = {
1031 .procname = "protected_symlinks",
1032 .data = &sysctl_protected_symlinks,
1033 .maxlen = sizeof(int),
1035 .proc_handler = proc_dointvec_minmax,
1036 .extra1 = SYSCTL_ZERO,
1037 .extra2 = SYSCTL_ONE,
1040 .procname = "protected_hardlinks",
1041 .data = &sysctl_protected_hardlinks,
1042 .maxlen = sizeof(int),
1044 .proc_handler = proc_dointvec_minmax,
1045 .extra1 = SYSCTL_ZERO,
1046 .extra2 = SYSCTL_ONE,
1049 .procname = "protected_fifos",
1050 .data = &sysctl_protected_fifos,
1051 .maxlen = sizeof(int),
1053 .proc_handler = proc_dointvec_minmax,
1054 .extra1 = SYSCTL_ZERO,
1055 .extra2 = SYSCTL_TWO,
1058 .procname = "protected_regular",
1059 .data = &sysctl_protected_regular,
1060 .maxlen = sizeof(int),
1062 .proc_handler = proc_dointvec_minmax,
1063 .extra1 = SYSCTL_ZERO,
1064 .extra2 = SYSCTL_TWO,
1069 static int __init init_fs_namei_sysctls(void)
1071 register_sysctl_init("fs", namei_sysctls);
1074 fs_initcall(init_fs_namei_sysctls);
1076 #endif /* CONFIG_SYSCTL */
1079 * may_follow_link - Check symlink following for unsafe situations
1080 * @nd: nameidata pathwalk data
1082 * In the case of the sysctl_protected_symlinks sysctl being enabled,
1083 * CAP_DAC_OVERRIDE needs to be specifically ignored if the symlink is
1084 * in a sticky world-writable directory. This is to protect privileged
1085 * processes from failing races against path names that may change out
1086 * from under them by way of other users creating malicious symlinks.
1087 * It will permit symlinks to be followed only when outside a sticky
1088 * world-writable directory, or when the uid of the symlink and follower
1089 * match, or when the directory owner matches the symlink's owner.
1091 * Returns 0 if following the symlink is allowed, -ve on error.
1093 static inline int may_follow_link(struct nameidata *nd, const struct inode *inode)
1095 struct user_namespace *mnt_userns;
1098 if (!sysctl_protected_symlinks)
1101 mnt_userns = mnt_user_ns(nd->path.mnt);
1102 i_uid = i_uid_into_mnt(mnt_userns, inode);
1103 /* Allowed if owner and follower match. */
1104 if (uid_eq(current_cred()->fsuid, i_uid))
1107 /* Allowed if parent directory not sticky and world-writable. */
1108 if ((nd->dir_mode & (S_ISVTX|S_IWOTH)) != (S_ISVTX|S_IWOTH))
1111 /* Allowed if parent directory and link owner match. */
1112 if (uid_valid(nd->dir_uid) && uid_eq(nd->dir_uid, i_uid))
1115 if (nd->flags & LOOKUP_RCU)
1118 audit_inode(nd->name, nd->stack[0].link.dentry, 0);
1119 audit_log_path_denied(AUDIT_ANOM_LINK, "follow_link");
1124 * safe_hardlink_source - Check for safe hardlink conditions
1125 * @mnt_userns: user namespace of the mount the inode was found from
1126 * @inode: the source inode to hardlink from
1128 * Return false if at least one of the following conditions:
1129 * - inode is not a regular file
1131 * - inode is setgid and group-exec
1132 * - access failure for read and write
1134 * Otherwise returns true.
1136 static bool safe_hardlink_source(struct user_namespace *mnt_userns,
1137 struct inode *inode)
1139 umode_t mode = inode->i_mode;
1141 /* Special files should not get pinned to the filesystem. */
1145 /* Setuid files should not get pinned to the filesystem. */
1149 /* Executable setgid files should not get pinned to the filesystem. */
1150 if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP))
1153 /* Hardlinking to unreadable or unwritable sources is dangerous. */
1154 if (inode_permission(mnt_userns, inode, MAY_READ | MAY_WRITE))
1161 * may_linkat - Check permissions for creating a hardlink
1162 * @mnt_userns: user namespace of the mount the inode was found from
1163 * @link: the source to hardlink from
1165 * Block hardlink when all of:
1166 * - sysctl_protected_hardlinks enabled
1167 * - fsuid does not match inode
1168 * - hardlink source is unsafe (see safe_hardlink_source() above)
1169 * - not CAP_FOWNER in a namespace with the inode owner uid mapped
1171 * If the inode has been found through an idmapped mount the user namespace of
1172 * the vfsmount must be passed through @mnt_userns. This function will then take
1173 * care to map the inode according to @mnt_userns before checking permissions.
1174 * On non-idmapped mounts or if permission checking is to be performed on the
1175 * raw inode simply passs init_user_ns.
1177 * Returns 0 if successful, -ve on error.
1179 int may_linkat(struct user_namespace *mnt_userns, struct path *link)
1181 struct inode *inode = link->dentry->d_inode;
1183 /* Inode writeback is not safe when the uid or gid are invalid. */
1184 if (!uid_valid(i_uid_into_mnt(mnt_userns, inode)) ||
1185 !gid_valid(i_gid_into_mnt(mnt_userns, inode)))
1188 if (!sysctl_protected_hardlinks)
1191 /* Source inode owner (or CAP_FOWNER) can hardlink all they like,
1192 * otherwise, it must be a safe source.
1194 if (safe_hardlink_source(mnt_userns, inode) ||
1195 inode_owner_or_capable(mnt_userns, inode))
1198 audit_log_path_denied(AUDIT_ANOM_LINK, "linkat");
1203 * may_create_in_sticky - Check whether an O_CREAT open in a sticky directory
1204 * should be allowed, or not, on files that already
1206 * @mnt_userns: user namespace of the mount the inode was found from
1207 * @nd: nameidata pathwalk data
1208 * @inode: the inode of the file to open
1210 * Block an O_CREAT open of a FIFO (or a regular file) when:
1211 * - sysctl_protected_fifos (or sysctl_protected_regular) is enabled
1212 * - the file already exists
1213 * - we are in a sticky directory
1214 * - we don't own the file
1215 * - the owner of the directory doesn't own the file
1216 * - the directory is world writable
1217 * If the sysctl_protected_fifos (or sysctl_protected_regular) is set to 2
1218 * the directory doesn't have to be world writable: being group writable will
1221 * If the inode has been found through an idmapped mount the user namespace of
1222 * the vfsmount must be passed through @mnt_userns. This function will then take
1223 * care to map the inode according to @mnt_userns before checking permissions.
1224 * On non-idmapped mounts or if permission checking is to be performed on the
1225 * raw inode simply passs init_user_ns.
1227 * Returns 0 if the open is allowed, -ve on error.
1229 static int may_create_in_sticky(struct user_namespace *mnt_userns,
1230 struct nameidata *nd, struct inode *const inode)
1232 umode_t dir_mode = nd->dir_mode;
1233 kuid_t dir_uid = nd->dir_uid;
1235 if ((!sysctl_protected_fifos && S_ISFIFO(inode->i_mode)) ||
1236 (!sysctl_protected_regular && S_ISREG(inode->i_mode)) ||
1237 likely(!(dir_mode & S_ISVTX)) ||
1238 uid_eq(i_uid_into_mnt(mnt_userns, inode), dir_uid) ||
1239 uid_eq(current_fsuid(), i_uid_into_mnt(mnt_userns, inode)))
1242 if (likely(dir_mode & 0002) ||
1244 ((sysctl_protected_fifos >= 2 && S_ISFIFO(inode->i_mode)) ||
1245 (sysctl_protected_regular >= 2 && S_ISREG(inode->i_mode))))) {
1246 const char *operation = S_ISFIFO(inode->i_mode) ?
1247 "sticky_create_fifo" :
1248 "sticky_create_regular";
1249 audit_log_path_denied(AUDIT_ANOM_CREAT, operation);
1256 * follow_up - Find the mountpoint of path's vfsmount
1258 * Given a path, find the mountpoint of its source file system.
1259 * Replace @path with the path of the mountpoint in the parent mount.
1262 * Return 1 if we went up a level and 0 if we were already at the
1265 int follow_up(struct path *path)
1267 struct mount *mnt = real_mount(path->mnt);
1268 struct mount *parent;
1269 struct dentry *mountpoint;
1271 read_seqlock_excl(&mount_lock);
1272 parent = mnt->mnt_parent;
1273 if (parent == mnt) {
1274 read_sequnlock_excl(&mount_lock);
1277 mntget(&parent->mnt);
1278 mountpoint = dget(mnt->mnt_mountpoint);
1279 read_sequnlock_excl(&mount_lock);
1281 path->dentry = mountpoint;
1283 path->mnt = &parent->mnt;
1286 EXPORT_SYMBOL(follow_up);
1288 static bool choose_mountpoint_rcu(struct mount *m, const struct path *root,
1289 struct path *path, unsigned *seqp)
1291 while (mnt_has_parent(m)) {
1292 struct dentry *mountpoint = m->mnt_mountpoint;
1295 if (unlikely(root->dentry == mountpoint &&
1296 root->mnt == &m->mnt))
1298 if (mountpoint != m->mnt.mnt_root) {
1299 path->mnt = &m->mnt;
1300 path->dentry = mountpoint;
1301 *seqp = read_seqcount_begin(&mountpoint->d_seq);
1308 static bool choose_mountpoint(struct mount *m, const struct path *root,
1315 unsigned seq, mseq = read_seqbegin(&mount_lock);
1317 found = choose_mountpoint_rcu(m, root, path, &seq);
1318 if (unlikely(!found)) {
1319 if (!read_seqretry(&mount_lock, mseq))
1322 if (likely(__legitimize_path(path, seq, mseq)))
1334 * Perform an automount
1335 * - return -EISDIR to tell follow_managed() to stop and return the path we
1338 static int follow_automount(struct path *path, int *count, unsigned lookup_flags)
1340 struct dentry *dentry = path->dentry;
1342 /* We don't want to mount if someone's just doing a stat -
1343 * unless they're stat'ing a directory and appended a '/' to
1346 * We do, however, want to mount if someone wants to open or
1347 * create a file of any type under the mountpoint, wants to
1348 * traverse through the mountpoint or wants to open the
1349 * mounted directory. Also, autofs may mark negative dentries
1350 * as being automount points. These will need the attentions
1351 * of the daemon to instantiate them before they can be used.
1353 if (!(lookup_flags & (LOOKUP_PARENT | LOOKUP_DIRECTORY |
1354 LOOKUP_OPEN | LOOKUP_CREATE | LOOKUP_AUTOMOUNT)) &&
1358 if (count && (*count)++ >= MAXSYMLINKS)
1361 return finish_automount(dentry->d_op->d_automount(path), path);
1365 * mount traversal - out-of-line part. One note on ->d_flags accesses -
1366 * dentries are pinned but not locked here, so negative dentry can go
1367 * positive right under us. Use of smp_load_acquire() provides a barrier
1368 * sufficient for ->d_inode and ->d_flags consistency.
1370 static int __traverse_mounts(struct path *path, unsigned flags, bool *jumped,
1371 int *count, unsigned lookup_flags)
1373 struct vfsmount *mnt = path->mnt;
1374 bool need_mntput = false;
1377 while (flags & DCACHE_MANAGED_DENTRY) {
1378 /* Allow the filesystem to manage the transit without i_mutex
1380 if (flags & DCACHE_MANAGE_TRANSIT) {
1381 ret = path->dentry->d_op->d_manage(path, false);
1382 flags = smp_load_acquire(&path->dentry->d_flags);
1387 if (flags & DCACHE_MOUNTED) { // something's mounted on it..
1388 struct vfsmount *mounted = lookup_mnt(path);
1389 if (mounted) { // ... in our namespace
1393 path->mnt = mounted;
1394 path->dentry = dget(mounted->mnt_root);
1395 // here we know it's positive
1396 flags = path->dentry->d_flags;
1402 if (!(flags & DCACHE_NEED_AUTOMOUNT))
1405 // uncovered automount point
1406 ret = follow_automount(path, count, lookup_flags);
1407 flags = smp_load_acquire(&path->dentry->d_flags);
1414 // possible if you race with several mount --move
1415 if (need_mntput && path->mnt == mnt)
1417 if (!ret && unlikely(d_flags_negative(flags)))
1419 *jumped = need_mntput;
1423 static inline int traverse_mounts(struct path *path, bool *jumped,
1424 int *count, unsigned lookup_flags)
1426 unsigned flags = smp_load_acquire(&path->dentry->d_flags);
1429 if (likely(!(flags & DCACHE_MANAGED_DENTRY))) {
1431 if (unlikely(d_flags_negative(flags)))
1435 return __traverse_mounts(path, flags, jumped, count, lookup_flags);
1438 int follow_down_one(struct path *path)
1440 struct vfsmount *mounted;
1442 mounted = lookup_mnt(path);
1446 path->mnt = mounted;
1447 path->dentry = dget(mounted->mnt_root);
1452 EXPORT_SYMBOL(follow_down_one);
1455 * Follow down to the covering mount currently visible to userspace. At each
1456 * point, the filesystem owning that dentry may be queried as to whether the
1457 * caller is permitted to proceed or not.
1459 int follow_down(struct path *path)
1461 struct vfsmount *mnt = path->mnt;
1463 int ret = traverse_mounts(path, &jumped, NULL, 0);
1465 if (path->mnt != mnt)
1469 EXPORT_SYMBOL(follow_down);
1472 * Try to skip to top of mountpoint pile in rcuwalk mode. Fail if
1473 * we meet a managed dentry that would need blocking.
1475 static bool __follow_mount_rcu(struct nameidata *nd, struct path *path,
1476 struct inode **inode, unsigned *seqp)
1478 struct dentry *dentry = path->dentry;
1479 unsigned int flags = dentry->d_flags;
1481 if (likely(!(flags & DCACHE_MANAGED_DENTRY)))
1484 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1489 * Don't forget we might have a non-mountpoint managed dentry
1490 * that wants to block transit.
1492 if (unlikely(flags & DCACHE_MANAGE_TRANSIT)) {
1493 int res = dentry->d_op->d_manage(path, true);
1495 return res == -EISDIR;
1496 flags = dentry->d_flags;
1499 if (flags & DCACHE_MOUNTED) {
1500 struct mount *mounted = __lookup_mnt(path->mnt, dentry);
1502 path->mnt = &mounted->mnt;
1503 dentry = path->dentry = mounted->mnt.mnt_root;
1504 nd->state |= ND_JUMPED;
1505 *seqp = read_seqcount_begin(&dentry->d_seq);
1506 *inode = dentry->d_inode;
1508 * We don't need to re-check ->d_seq after this
1509 * ->d_inode read - there will be an RCU delay
1510 * between mount hash removal and ->mnt_root
1511 * becoming unpinned.
1513 flags = dentry->d_flags;
1516 if (read_seqretry(&mount_lock, nd->m_seq))
1519 return !(flags & DCACHE_NEED_AUTOMOUNT);
1523 static inline int handle_mounts(struct nameidata *nd, struct dentry *dentry,
1524 struct path *path, struct inode **inode,
1530 path->mnt = nd->path.mnt;
1531 path->dentry = dentry;
1532 if (nd->flags & LOOKUP_RCU) {
1533 unsigned int seq = *seqp;
1534 if (unlikely(!*inode))
1536 if (likely(__follow_mount_rcu(nd, path, inode, seqp)))
1538 if (!try_to_unlazy_next(nd, dentry, seq))
1540 // *path might've been clobbered by __follow_mount_rcu()
1541 path->mnt = nd->path.mnt;
1542 path->dentry = dentry;
1544 ret = traverse_mounts(path, &jumped, &nd->total_link_count, nd->flags);
1546 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1549 nd->state |= ND_JUMPED;
1551 if (unlikely(ret)) {
1553 if (path->mnt != nd->path.mnt)
1556 *inode = d_backing_inode(path->dentry);
1557 *seqp = 0; /* out of RCU mode, so the value doesn't matter */
1563 * This looks up the name in dcache and possibly revalidates the found dentry.
1564 * NULL is returned if the dentry does not exist in the cache.
1566 static struct dentry *lookup_dcache(const struct qstr *name,
1570 struct dentry *dentry = d_lookup(dir, name);
1572 int error = d_revalidate(dentry, flags);
1573 if (unlikely(error <= 0)) {
1575 d_invalidate(dentry);
1577 return ERR_PTR(error);
1584 * Parent directory has inode locked exclusive. This is one
1585 * and only case when ->lookup() gets called on non in-lookup
1586 * dentries - as the matter of fact, this only gets called
1587 * when directory is guaranteed to have no in-lookup children
1590 static struct dentry *__lookup_hash(const struct qstr *name,
1591 struct dentry *base, unsigned int flags)
1593 struct dentry *dentry = lookup_dcache(name, base, flags);
1595 struct inode *dir = base->d_inode;
1600 /* Don't create child dentry for a dead directory. */
1601 if (unlikely(IS_DEADDIR(dir)))
1602 return ERR_PTR(-ENOENT);
1604 dentry = d_alloc(base, name);
1605 if (unlikely(!dentry))
1606 return ERR_PTR(-ENOMEM);
1608 old = dir->i_op->lookup(dir, dentry, flags);
1609 if (unlikely(old)) {
1616 static struct dentry *lookup_fast(struct nameidata *nd,
1617 struct inode **inode,
1620 struct dentry *dentry, *parent = nd->path.dentry;
1624 * Rename seqlock is not required here because in the off chance
1625 * of a false negative due to a concurrent rename, the caller is
1626 * going to fall back to non-racy lookup.
1628 if (nd->flags & LOOKUP_RCU) {
1630 dentry = __d_lookup_rcu(parent, &nd->last, &seq);
1631 if (unlikely(!dentry)) {
1632 if (!try_to_unlazy(nd))
1633 return ERR_PTR(-ECHILD);
1638 * This sequence count validates that the inode matches
1639 * the dentry name information from lookup.
1641 *inode = d_backing_inode(dentry);
1642 if (unlikely(read_seqcount_retry(&dentry->d_seq, seq)))
1643 return ERR_PTR(-ECHILD);
1646 * This sequence count validates that the parent had no
1647 * changes while we did the lookup of the dentry above.
1649 * The memory barrier in read_seqcount_begin of child is
1650 * enough, we can use __read_seqcount_retry here.
1652 if (unlikely(__read_seqcount_retry(&parent->d_seq, nd->seq)))
1653 return ERR_PTR(-ECHILD);
1656 status = d_revalidate(dentry, nd->flags);
1657 if (likely(status > 0))
1659 if (!try_to_unlazy_next(nd, dentry, seq))
1660 return ERR_PTR(-ECHILD);
1661 if (status == -ECHILD)
1662 /* we'd been told to redo it in non-rcu mode */
1663 status = d_revalidate(dentry, nd->flags);
1665 dentry = __d_lookup(parent, &nd->last);
1666 if (unlikely(!dentry))
1668 status = d_revalidate(dentry, nd->flags);
1670 if (unlikely(status <= 0)) {
1672 d_invalidate(dentry);
1674 return ERR_PTR(status);
1679 /* Fast lookup failed, do it the slow way */
1680 static struct dentry *__lookup_slow(const struct qstr *name,
1684 struct dentry *dentry, *old;
1685 struct inode *inode = dir->d_inode;
1686 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
1688 /* Don't go there if it's already dead */
1689 if (unlikely(IS_DEADDIR(inode)))
1690 return ERR_PTR(-ENOENT);
1692 dentry = d_alloc_parallel(dir, name, &wq);
1695 if (unlikely(!d_in_lookup(dentry))) {
1696 int error = d_revalidate(dentry, flags);
1697 if (unlikely(error <= 0)) {
1699 d_invalidate(dentry);
1704 dentry = ERR_PTR(error);
1707 old = inode->i_op->lookup(inode, dentry, flags);
1708 d_lookup_done(dentry);
1709 if (unlikely(old)) {
1717 static struct dentry *lookup_slow(const struct qstr *name,
1721 struct inode *inode = dir->d_inode;
1723 inode_lock_shared(inode);
1724 res = __lookup_slow(name, dir, flags);
1725 inode_unlock_shared(inode);
1729 static inline int may_lookup(struct user_namespace *mnt_userns,
1730 struct nameidata *nd)
1732 if (nd->flags & LOOKUP_RCU) {
1733 int err = inode_permission(mnt_userns, nd->inode, MAY_EXEC|MAY_NOT_BLOCK);
1734 if (err != -ECHILD || !try_to_unlazy(nd))
1737 return inode_permission(mnt_userns, nd->inode, MAY_EXEC);
1740 static int reserve_stack(struct nameidata *nd, struct path *link, unsigned seq)
1742 if (unlikely(nd->total_link_count++ >= MAXSYMLINKS))
1745 if (likely(nd->depth != EMBEDDED_LEVELS))
1747 if (likely(nd->stack != nd->internal))
1749 if (likely(nd_alloc_stack(nd)))
1752 if (nd->flags & LOOKUP_RCU) {
1753 // we need to grab link before we do unlazy. And we can't skip
1754 // unlazy even if we fail to grab the link - cleanup needs it
1755 bool grabbed_link = legitimize_path(nd, link, seq);
1757 if (!try_to_unlazy(nd) != 0 || !grabbed_link)
1760 if (nd_alloc_stack(nd))
1766 enum {WALK_TRAILING = 1, WALK_MORE = 2, WALK_NOFOLLOW = 4};
1768 static const char *pick_link(struct nameidata *nd, struct path *link,
1769 struct inode *inode, unsigned seq, int flags)
1773 int error = reserve_stack(nd, link, seq);
1775 if (unlikely(error)) {
1776 if (!(nd->flags & LOOKUP_RCU))
1778 return ERR_PTR(error);
1780 last = nd->stack + nd->depth++;
1782 clear_delayed_call(&last->done);
1785 if (flags & WALK_TRAILING) {
1786 error = may_follow_link(nd, inode);
1787 if (unlikely(error))
1788 return ERR_PTR(error);
1791 if (unlikely(nd->flags & LOOKUP_NO_SYMLINKS) ||
1792 unlikely(link->mnt->mnt_flags & MNT_NOSYMFOLLOW))
1793 return ERR_PTR(-ELOOP);
1795 if (!(nd->flags & LOOKUP_RCU)) {
1796 touch_atime(&last->link);
1798 } else if (atime_needs_update(&last->link, inode)) {
1799 if (!try_to_unlazy(nd))
1800 return ERR_PTR(-ECHILD);
1801 touch_atime(&last->link);
1804 error = security_inode_follow_link(link->dentry, inode,
1805 nd->flags & LOOKUP_RCU);
1806 if (unlikely(error))
1807 return ERR_PTR(error);
1809 res = READ_ONCE(inode->i_link);
1811 const char * (*get)(struct dentry *, struct inode *,
1812 struct delayed_call *);
1813 get = inode->i_op->get_link;
1814 if (nd->flags & LOOKUP_RCU) {
1815 res = get(NULL, inode, &last->done);
1816 if (res == ERR_PTR(-ECHILD) && try_to_unlazy(nd))
1817 res = get(link->dentry, inode, &last->done);
1819 res = get(link->dentry, inode, &last->done);
1827 error = nd_jump_root(nd);
1828 if (unlikely(error))
1829 return ERR_PTR(error);
1830 while (unlikely(*++res == '/'))
1835 all_done: // pure jump
1841 * Do we need to follow links? We _really_ want to be able
1842 * to do this check without having to look at inode->i_op,
1843 * so we keep a cache of "no, this doesn't need follow_link"
1844 * for the common case.
1846 static const char *step_into(struct nameidata *nd, int flags,
1847 struct dentry *dentry, struct inode *inode, unsigned seq)
1850 int err = handle_mounts(nd, dentry, &path, &inode, &seq);
1853 return ERR_PTR(err);
1854 if (likely(!d_is_symlink(path.dentry)) ||
1855 ((flags & WALK_TRAILING) && !(nd->flags & LOOKUP_FOLLOW)) ||
1856 (flags & WALK_NOFOLLOW)) {
1857 /* not a symlink or should not follow */
1858 if (!(nd->flags & LOOKUP_RCU)) {
1859 dput(nd->path.dentry);
1860 if (nd->path.mnt != path.mnt)
1861 mntput(nd->path.mnt);
1868 if (nd->flags & LOOKUP_RCU) {
1869 /* make sure that d_is_symlink above matches inode */
1870 if (read_seqcount_retry(&path.dentry->d_seq, seq))
1871 return ERR_PTR(-ECHILD);
1873 if (path.mnt == nd->path.mnt)
1876 return pick_link(nd, &path, inode, seq, flags);
1879 static struct dentry *follow_dotdot_rcu(struct nameidata *nd,
1880 struct inode **inodep,
1883 struct dentry *parent, *old;
1885 if (path_equal(&nd->path, &nd->root))
1887 if (unlikely(nd->path.dentry == nd->path.mnt->mnt_root)) {
1890 if (!choose_mountpoint_rcu(real_mount(nd->path.mnt),
1891 &nd->root, &path, &seq))
1893 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1894 return ERR_PTR(-ECHILD);
1896 nd->inode = path.dentry->d_inode;
1898 if (unlikely(read_seqretry(&mount_lock, nd->m_seq)))
1899 return ERR_PTR(-ECHILD);
1900 /* we know that mountpoint was pinned */
1902 old = nd->path.dentry;
1903 parent = old->d_parent;
1904 *inodep = parent->d_inode;
1905 *seqp = read_seqcount_begin(&parent->d_seq);
1906 if (unlikely(read_seqcount_retry(&old->d_seq, nd->seq)))
1907 return ERR_PTR(-ECHILD);
1908 if (unlikely(!path_connected(nd->path.mnt, parent)))
1909 return ERR_PTR(-ECHILD);
1912 if (unlikely(read_seqretry(&mount_lock, nd->m_seq)))
1913 return ERR_PTR(-ECHILD);
1914 if (unlikely(nd->flags & LOOKUP_BENEATH))
1915 return ERR_PTR(-ECHILD);
1919 static struct dentry *follow_dotdot(struct nameidata *nd,
1920 struct inode **inodep,
1923 struct dentry *parent;
1925 if (path_equal(&nd->path, &nd->root))
1927 if (unlikely(nd->path.dentry == nd->path.mnt->mnt_root)) {
1930 if (!choose_mountpoint(real_mount(nd->path.mnt),
1933 path_put(&nd->path);
1935 nd->inode = path.dentry->d_inode;
1936 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1937 return ERR_PTR(-EXDEV);
1939 /* rare case of legitimate dget_parent()... */
1940 parent = dget_parent(nd->path.dentry);
1941 if (unlikely(!path_connected(nd->path.mnt, parent))) {
1943 return ERR_PTR(-ENOENT);
1946 *inodep = parent->d_inode;
1950 if (unlikely(nd->flags & LOOKUP_BENEATH))
1951 return ERR_PTR(-EXDEV);
1952 dget(nd->path.dentry);
1956 static const char *handle_dots(struct nameidata *nd, int type)
1958 if (type == LAST_DOTDOT) {
1959 const char *error = NULL;
1960 struct dentry *parent;
1961 struct inode *inode;
1964 if (!nd->root.mnt) {
1965 error = ERR_PTR(set_root(nd));
1969 if (nd->flags & LOOKUP_RCU)
1970 parent = follow_dotdot_rcu(nd, &inode, &seq);
1972 parent = follow_dotdot(nd, &inode, &seq);
1974 return ERR_CAST(parent);
1975 if (unlikely(!parent))
1976 error = step_into(nd, WALK_NOFOLLOW,
1977 nd->path.dentry, nd->inode, nd->seq);
1979 error = step_into(nd, WALK_NOFOLLOW,
1980 parent, inode, seq);
1981 if (unlikely(error))
1984 if (unlikely(nd->flags & LOOKUP_IS_SCOPED)) {
1986 * If there was a racing rename or mount along our
1987 * path, then we can't be sure that ".." hasn't jumped
1988 * above nd->root (and so userspace should retry or use
1992 if (unlikely(__read_seqcount_retry(&mount_lock.seqcount, nd->m_seq)))
1993 return ERR_PTR(-EAGAIN);
1994 if (unlikely(__read_seqcount_retry(&rename_lock.seqcount, nd->r_seq)))
1995 return ERR_PTR(-EAGAIN);
2001 static const char *walk_component(struct nameidata *nd, int flags)
2003 struct dentry *dentry;
2004 struct inode *inode;
2007 * "." and ".." are special - ".." especially so because it has
2008 * to be able to know about the current root directory and
2009 * parent relationships.
2011 if (unlikely(nd->last_type != LAST_NORM)) {
2012 if (!(flags & WALK_MORE) && nd->depth)
2014 return handle_dots(nd, nd->last_type);
2016 dentry = lookup_fast(nd, &inode, &seq);
2018 return ERR_CAST(dentry);
2019 if (unlikely(!dentry)) {
2020 dentry = lookup_slow(&nd->last, nd->path.dentry, nd->flags);
2022 return ERR_CAST(dentry);
2024 if (!(flags & WALK_MORE) && nd->depth)
2026 return step_into(nd, flags, dentry, inode, seq);
2030 * We can do the critical dentry name comparison and hashing
2031 * operations one word at a time, but we are limited to:
2033 * - Architectures with fast unaligned word accesses. We could
2034 * do a "get_unaligned()" if this helps and is sufficiently
2037 * - non-CONFIG_DEBUG_PAGEALLOC configurations (so that we
2038 * do not trap on the (extremely unlikely) case of a page
2039 * crossing operation.
2041 * - Furthermore, we need an efficient 64-bit compile for the
2042 * 64-bit case in order to generate the "number of bytes in
2043 * the final mask". Again, that could be replaced with a
2044 * efficient population count instruction or similar.
2046 #ifdef CONFIG_DCACHE_WORD_ACCESS
2048 #include <asm/word-at-a-time.h>
2052 /* Architecture provides HASH_MIX and fold_hash() in <asm/hash.h> */
2054 #elif defined(CONFIG_64BIT)
2056 * Register pressure in the mixing function is an issue, particularly
2057 * on 32-bit x86, but almost any function requires one state value and
2058 * one temporary. Instead, use a function designed for two state values
2059 * and no temporaries.
2061 * This function cannot create a collision in only two iterations, so
2062 * we have two iterations to achieve avalanche. In those two iterations,
2063 * we have six layers of mixing, which is enough to spread one bit's
2064 * influence out to 2^6 = 64 state bits.
2066 * Rotate constants are scored by considering either 64 one-bit input
2067 * deltas or 64*63/2 = 2016 two-bit input deltas, and finding the
2068 * probability of that delta causing a change to each of the 128 output
2069 * bits, using a sample of random initial states.
2071 * The Shannon entropy of the computed probabilities is then summed
2072 * to produce a score. Ideally, any input change has a 50% chance of
2073 * toggling any given output bit.
2075 * Mixing scores (in bits) for (12,45):
2076 * Input delta: 1-bit 2-bit
2077 * 1 round: 713.3 42542.6
2078 * 2 rounds: 2753.7 140389.8
2079 * 3 rounds: 5954.1 233458.2
2080 * 4 rounds: 7862.6 256672.2
2081 * Perfect: 8192 258048
2082 * (64*128) (64*63/2 * 128)
2084 #define HASH_MIX(x, y, a) \
2086 y ^= x, x = rol64(x,12),\
2087 x += y, y = rol64(y,45),\
2091 * Fold two longs into one 32-bit hash value. This must be fast, but
2092 * latency isn't quite as critical, as there is a fair bit of additional
2093 * work done before the hash value is used.
2095 static inline unsigned int fold_hash(unsigned long x, unsigned long y)
2097 y ^= x * GOLDEN_RATIO_64;
2098 y *= GOLDEN_RATIO_64;
2102 #else /* 32-bit case */
2105 * Mixing scores (in bits) for (7,20):
2106 * Input delta: 1-bit 2-bit
2107 * 1 round: 330.3 9201.6
2108 * 2 rounds: 1246.4 25475.4
2109 * 3 rounds: 1907.1 31295.1
2110 * 4 rounds: 2042.3 31718.6
2111 * Perfect: 2048 31744
2112 * (32*64) (32*31/2 * 64)
2114 #define HASH_MIX(x, y, a) \
2116 y ^= x, x = rol32(x, 7),\
2117 x += y, y = rol32(y,20),\
2120 static inline unsigned int fold_hash(unsigned long x, unsigned long y)
2122 /* Use arch-optimized multiply if one exists */
2123 return __hash_32(y ^ __hash_32(x));
2129 * Return the hash of a string of known length. This is carfully
2130 * designed to match hash_name(), which is the more critical function.
2131 * In particular, we must end by hashing a final word containing 0..7
2132 * payload bytes, to match the way that hash_name() iterates until it
2133 * finds the delimiter after the name.
2135 unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
2137 unsigned long a, x = 0, y = (unsigned long)salt;
2142 a = load_unaligned_zeropad(name);
2143 if (len < sizeof(unsigned long))
2146 name += sizeof(unsigned long);
2147 len -= sizeof(unsigned long);
2149 x ^= a & bytemask_from_count(len);
2151 return fold_hash(x, y);
2153 EXPORT_SYMBOL(full_name_hash);
2155 /* Return the "hash_len" (hash and length) of a null-terminated string */
2156 u64 hashlen_string(const void *salt, const char *name)
2158 unsigned long a = 0, x = 0, y = (unsigned long)salt;
2159 unsigned long adata, mask, len;
2160 const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2167 len += sizeof(unsigned long);
2169 a = load_unaligned_zeropad(name+len);
2170 } while (!has_zero(a, &adata, &constants));
2172 adata = prep_zero_mask(a, adata, &constants);
2173 mask = create_zero_mask(adata);
2174 x ^= a & zero_bytemask(mask);
2176 return hashlen_create(fold_hash(x, y), len + find_zero(mask));
2178 EXPORT_SYMBOL(hashlen_string);
2181 * Calculate the length and hash of the path component, and
2182 * return the "hash_len" as the result.
2184 static inline u64 hash_name(const void *salt, const char *name)
2186 unsigned long a = 0, b, x = 0, y = (unsigned long)salt;
2187 unsigned long adata, bdata, mask, len;
2188 const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2195 len += sizeof(unsigned long);
2197 a = load_unaligned_zeropad(name+len);
2198 b = a ^ REPEAT_BYTE('/');
2199 } while (!(has_zero(a, &adata, &constants) | has_zero(b, &bdata, &constants)));
2201 adata = prep_zero_mask(a, adata, &constants);
2202 bdata = prep_zero_mask(b, bdata, &constants);
2203 mask = create_zero_mask(adata | bdata);
2204 x ^= a & zero_bytemask(mask);
2206 return hashlen_create(fold_hash(x, y), len + find_zero(mask));
2209 #else /* !CONFIG_DCACHE_WORD_ACCESS: Slow, byte-at-a-time version */
2211 /* Return the hash of a string of known length */
2212 unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
2214 unsigned long hash = init_name_hash(salt);
2216 hash = partial_name_hash((unsigned char)*name++, hash);
2217 return end_name_hash(hash);
2219 EXPORT_SYMBOL(full_name_hash);
2221 /* Return the "hash_len" (hash and length) of a null-terminated string */
2222 u64 hashlen_string(const void *salt, const char *name)
2224 unsigned long hash = init_name_hash(salt);
2225 unsigned long len = 0, c;
2227 c = (unsigned char)*name;
2230 hash = partial_name_hash(c, hash);
2231 c = (unsigned char)name[len];
2233 return hashlen_create(end_name_hash(hash), len);
2235 EXPORT_SYMBOL(hashlen_string);
2238 * We know there's a real path component here of at least
2241 static inline u64 hash_name(const void *salt, const char *name)
2243 unsigned long hash = init_name_hash(salt);
2244 unsigned long len = 0, c;
2246 c = (unsigned char)*name;
2249 hash = partial_name_hash(c, hash);
2250 c = (unsigned char)name[len];
2251 } while (c && c != '/');
2252 return hashlen_create(end_name_hash(hash), len);
2259 * This is the basic name resolution function, turning a pathname into
2260 * the final dentry. We expect 'base' to be positive and a directory.
2262 * Returns 0 and nd will have valid dentry and mnt on success.
2263 * Returns error and drops reference to input namei data on failure.
2265 static int link_path_walk(const char *name, struct nameidata *nd)
2267 int depth = 0; // depth <= nd->depth
2270 nd->last_type = LAST_ROOT;
2271 nd->flags |= LOOKUP_PARENT;
2273 return PTR_ERR(name);
2277 nd->dir_mode = 0; // short-circuit the 'hardening' idiocy
2281 /* At this point we know we have a real path component. */
2283 struct user_namespace *mnt_userns;
2288 mnt_userns = mnt_user_ns(nd->path.mnt);
2289 err = may_lookup(mnt_userns, nd);
2293 hash_len = hash_name(nd->path.dentry, name);
2296 if (name[0] == '.') switch (hashlen_len(hash_len)) {
2298 if (name[1] == '.') {
2300 nd->state |= ND_JUMPED;
2306 if (likely(type == LAST_NORM)) {
2307 struct dentry *parent = nd->path.dentry;
2308 nd->state &= ~ND_JUMPED;
2309 if (unlikely(parent->d_flags & DCACHE_OP_HASH)) {
2310 struct qstr this = { { .hash_len = hash_len }, .name = name };
2311 err = parent->d_op->d_hash(parent, &this);
2314 hash_len = this.hash_len;
2319 nd->last.hash_len = hash_len;
2320 nd->last.name = name;
2321 nd->last_type = type;
2323 name += hashlen_len(hash_len);
2327 * If it wasn't NUL, we know it was '/'. Skip that
2328 * slash, and continue until no more slashes.
2332 } while (unlikely(*name == '/'));
2333 if (unlikely(!*name)) {
2335 /* pathname or trailing symlink, done */
2337 nd->dir_uid = i_uid_into_mnt(mnt_userns, nd->inode);
2338 nd->dir_mode = nd->inode->i_mode;
2339 nd->flags &= ~LOOKUP_PARENT;
2342 /* last component of nested symlink */
2343 name = nd->stack[--depth].name;
2344 link = walk_component(nd, 0);
2346 /* not the last component */
2347 link = walk_component(nd, WALK_MORE);
2349 if (unlikely(link)) {
2351 return PTR_ERR(link);
2352 /* a symlink to follow */
2353 nd->stack[depth++].name = name;
2357 if (unlikely(!d_can_lookup(nd->path.dentry))) {
2358 if (nd->flags & LOOKUP_RCU) {
2359 if (!try_to_unlazy(nd))
2367 /* must be paired with terminate_walk() */
2368 static const char *path_init(struct nameidata *nd, unsigned flags)
2371 const char *s = nd->name->name;
2373 /* LOOKUP_CACHED requires RCU, ask caller to retry */
2374 if ((flags & (LOOKUP_RCU | LOOKUP_CACHED)) == LOOKUP_CACHED)
2375 return ERR_PTR(-EAGAIN);
2378 flags &= ~LOOKUP_RCU;
2379 if (flags & LOOKUP_RCU)
2383 nd->state |= ND_JUMPED;
2385 nd->m_seq = __read_seqcount_begin(&mount_lock.seqcount);
2386 nd->r_seq = __read_seqcount_begin(&rename_lock.seqcount);
2389 if (nd->state & ND_ROOT_PRESET) {
2390 struct dentry *root = nd->root.dentry;
2391 struct inode *inode = root->d_inode;
2392 if (*s && unlikely(!d_can_lookup(root)))
2393 return ERR_PTR(-ENOTDIR);
2394 nd->path = nd->root;
2396 if (flags & LOOKUP_RCU) {
2397 nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
2398 nd->root_seq = nd->seq;
2400 path_get(&nd->path);
2405 nd->root.mnt = NULL;
2407 /* Absolute pathname -- fetch the root (LOOKUP_IN_ROOT uses nd->dfd). */
2408 if (*s == '/' && !(flags & LOOKUP_IN_ROOT)) {
2409 error = nd_jump_root(nd);
2410 if (unlikely(error))
2411 return ERR_PTR(error);
2415 /* Relative pathname -- get the starting-point it is relative to. */
2416 if (nd->dfd == AT_FDCWD) {
2417 if (flags & LOOKUP_RCU) {
2418 struct fs_struct *fs = current->fs;
2422 seq = read_seqcount_begin(&fs->seq);
2424 nd->inode = nd->path.dentry->d_inode;
2425 nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
2426 } while (read_seqcount_retry(&fs->seq, seq));
2428 get_fs_pwd(current->fs, &nd->path);
2429 nd->inode = nd->path.dentry->d_inode;
2432 /* Caller must check execute permissions on the starting path component */
2433 struct fd f = fdget_raw(nd->dfd);
2434 struct dentry *dentry;
2437 return ERR_PTR(-EBADF);
2439 dentry = f.file->f_path.dentry;
2441 if (*s && unlikely(!d_can_lookup(dentry))) {
2443 return ERR_PTR(-ENOTDIR);
2446 nd->path = f.file->f_path;
2447 if (flags & LOOKUP_RCU) {
2448 nd->inode = nd->path.dentry->d_inode;
2449 nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
2451 path_get(&nd->path);
2452 nd->inode = nd->path.dentry->d_inode;
2457 /* For scoped-lookups we need to set the root to the dirfd as well. */
2458 if (flags & LOOKUP_IS_SCOPED) {
2459 nd->root = nd->path;
2460 if (flags & LOOKUP_RCU) {
2461 nd->root_seq = nd->seq;
2463 path_get(&nd->root);
2464 nd->state |= ND_ROOT_GRABBED;
2470 static inline const char *lookup_last(struct nameidata *nd)
2472 if (nd->last_type == LAST_NORM && nd->last.name[nd->last.len])
2473 nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
2475 return walk_component(nd, WALK_TRAILING);
2478 static int handle_lookup_down(struct nameidata *nd)
2480 if (!(nd->flags & LOOKUP_RCU))
2481 dget(nd->path.dentry);
2482 return PTR_ERR(step_into(nd, WALK_NOFOLLOW,
2483 nd->path.dentry, nd->inode, nd->seq));
2486 /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
2487 static int path_lookupat(struct nameidata *nd, unsigned flags, struct path *path)
2489 const char *s = path_init(nd, flags);
2492 if (unlikely(flags & LOOKUP_DOWN) && !IS_ERR(s)) {
2493 err = handle_lookup_down(nd);
2494 if (unlikely(err < 0))
2498 while (!(err = link_path_walk(s, nd)) &&
2499 (s = lookup_last(nd)) != NULL)
2501 if (!err && unlikely(nd->flags & LOOKUP_MOUNTPOINT)) {
2502 err = handle_lookup_down(nd);
2503 nd->state &= ~ND_JUMPED; // no d_weak_revalidate(), please...
2506 err = complete_walk(nd);
2508 if (!err && nd->flags & LOOKUP_DIRECTORY)
2509 if (!d_can_lookup(nd->path.dentry))
2513 nd->path.mnt = NULL;
2514 nd->path.dentry = NULL;
2520 int filename_lookup(int dfd, struct filename *name, unsigned flags,
2521 struct path *path, struct path *root)
2524 struct nameidata nd;
2526 return PTR_ERR(name);
2527 set_nameidata(&nd, dfd, name, root);
2528 retval = path_lookupat(&nd, flags | LOOKUP_RCU, path);
2529 if (unlikely(retval == -ECHILD))
2530 retval = path_lookupat(&nd, flags, path);
2531 if (unlikely(retval == -ESTALE))
2532 retval = path_lookupat(&nd, flags | LOOKUP_REVAL, path);
2534 if (likely(!retval))
2535 audit_inode(name, path->dentry,
2536 flags & LOOKUP_MOUNTPOINT ? AUDIT_INODE_NOEVAL : 0);
2537 restore_nameidata();
2541 /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
2542 static int path_parentat(struct nameidata *nd, unsigned flags,
2543 struct path *parent)
2545 const char *s = path_init(nd, flags);
2546 int err = link_path_walk(s, nd);
2548 err = complete_walk(nd);
2551 nd->path.mnt = NULL;
2552 nd->path.dentry = NULL;
2558 /* Note: this does not consume "name" */
2559 static int filename_parentat(int dfd, struct filename *name,
2560 unsigned int flags, struct path *parent,
2561 struct qstr *last, int *type)
2564 struct nameidata nd;
2567 return PTR_ERR(name);
2568 set_nameidata(&nd, dfd, name, NULL);
2569 retval = path_parentat(&nd, flags | LOOKUP_RCU, parent);
2570 if (unlikely(retval == -ECHILD))
2571 retval = path_parentat(&nd, flags, parent);
2572 if (unlikely(retval == -ESTALE))
2573 retval = path_parentat(&nd, flags | LOOKUP_REVAL, parent);
2574 if (likely(!retval)) {
2576 *type = nd.last_type;
2577 audit_inode(name, parent->dentry, AUDIT_INODE_PARENT);
2579 restore_nameidata();
2583 /* does lookup, returns the object with parent locked */
2584 static struct dentry *__kern_path_locked(struct filename *name, struct path *path)
2590 error = filename_parentat(AT_FDCWD, name, 0, path, &last, &type);
2592 return ERR_PTR(error);
2593 if (unlikely(type != LAST_NORM)) {
2595 return ERR_PTR(-EINVAL);
2597 inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
2598 d = __lookup_hash(&last, path->dentry, 0);
2600 inode_unlock(path->dentry->d_inode);
2606 struct dentry *kern_path_locked(const char *name, struct path *path)
2608 struct filename *filename = getname_kernel(name);
2609 struct dentry *res = __kern_path_locked(filename, path);
2615 int kern_path(const char *name, unsigned int flags, struct path *path)
2617 struct filename *filename = getname_kernel(name);
2618 int ret = filename_lookup(AT_FDCWD, filename, flags, path, NULL);
2624 EXPORT_SYMBOL(kern_path);
2627 * vfs_path_lookup - lookup a file path relative to a dentry-vfsmount pair
2628 * @dentry: pointer to dentry of the base directory
2629 * @mnt: pointer to vfs mount of the base directory
2630 * @name: pointer to file name
2631 * @flags: lookup flags
2632 * @path: pointer to struct path to fill
2634 int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt,
2635 const char *name, unsigned int flags,
2638 struct filename *filename;
2639 struct path root = {.mnt = mnt, .dentry = dentry};
2642 filename = getname_kernel(name);
2643 /* the first argument of filename_lookup() is ignored with root */
2644 ret = filename_lookup(AT_FDCWD, filename, flags, path, &root);
2648 EXPORT_SYMBOL(vfs_path_lookup);
2650 static int lookup_one_common(struct user_namespace *mnt_userns,
2651 const char *name, struct dentry *base, int len,
2656 this->hash = full_name_hash(base, name, len);
2660 if (unlikely(name[0] == '.')) {
2661 if (len < 2 || (len == 2 && name[1] == '.'))
2666 unsigned int c = *(const unsigned char *)name++;
2667 if (c == '/' || c == '\0')
2671 * See if the low-level filesystem might want
2672 * to use its own hash..
2674 if (base->d_flags & DCACHE_OP_HASH) {
2675 int err = base->d_op->d_hash(base, this);
2680 return inode_permission(mnt_userns, base->d_inode, MAY_EXEC);
2684 * try_lookup_one_len - filesystem helper to lookup single pathname component
2685 * @name: pathname component to lookup
2686 * @base: base directory to lookup from
2687 * @len: maximum length @len should be interpreted to
2689 * Look up a dentry by name in the dcache, returning NULL if it does not
2690 * currently exist. The function does not try to create a dentry.
2692 * Note that this routine is purely a helper for filesystem usage and should
2693 * not be called by generic code.
2695 * The caller must hold base->i_mutex.
2697 struct dentry *try_lookup_one_len(const char *name, struct dentry *base, int len)
2702 WARN_ON_ONCE(!inode_is_locked(base->d_inode));
2704 err = lookup_one_common(&init_user_ns, name, base, len, &this);
2706 return ERR_PTR(err);
2708 return lookup_dcache(&this, base, 0);
2710 EXPORT_SYMBOL(try_lookup_one_len);
2713 * lookup_one_len - filesystem helper to lookup single pathname component
2714 * @name: pathname component to lookup
2715 * @base: base directory to lookup from
2716 * @len: maximum length @len should be interpreted to
2718 * Note that this routine is purely a helper for filesystem usage and should
2719 * not be called by generic code.
2721 * The caller must hold base->i_mutex.
2723 struct dentry *lookup_one_len(const char *name, struct dentry *base, int len)
2725 struct dentry *dentry;
2729 WARN_ON_ONCE(!inode_is_locked(base->d_inode));
2731 err = lookup_one_common(&init_user_ns, name, base, len, &this);
2733 return ERR_PTR(err);
2735 dentry = lookup_dcache(&this, base, 0);
2736 return dentry ? dentry : __lookup_slow(&this, base, 0);
2738 EXPORT_SYMBOL(lookup_one_len);
2741 * lookup_one - filesystem helper to lookup single pathname component
2742 * @mnt_userns: user namespace of the mount the lookup is performed from
2743 * @name: pathname component to lookup
2744 * @base: base directory to lookup from
2745 * @len: maximum length @len should be interpreted to
2747 * Note that this routine is purely a helper for filesystem usage and should
2748 * not be called by generic code.
2750 * The caller must hold base->i_mutex.
2752 struct dentry *lookup_one(struct user_namespace *mnt_userns, const char *name,
2753 struct dentry *base, int len)
2755 struct dentry *dentry;
2759 WARN_ON_ONCE(!inode_is_locked(base->d_inode));
2761 err = lookup_one_common(mnt_userns, name, base, len, &this);
2763 return ERR_PTR(err);
2765 dentry = lookup_dcache(&this, base, 0);
2766 return dentry ? dentry : __lookup_slow(&this, base, 0);
2768 EXPORT_SYMBOL(lookup_one);
2771 * lookup_one_len_unlocked - filesystem helper to lookup single pathname component
2772 * @name: pathname component to lookup
2773 * @base: base directory to lookup from
2774 * @len: maximum length @len should be interpreted to
2776 * Note that this routine is purely a helper for filesystem usage and should
2777 * not be called by generic code.
2779 * Unlike lookup_one_len, it should be called without the parent
2780 * i_mutex held, and will take the i_mutex itself if necessary.
2782 struct dentry *lookup_one_len_unlocked(const char *name,
2783 struct dentry *base, int len)
2789 err = lookup_one_common(&init_user_ns, name, base, len, &this);
2791 return ERR_PTR(err);
2793 ret = lookup_dcache(&this, base, 0);
2795 ret = lookup_slow(&this, base, 0);
2798 EXPORT_SYMBOL(lookup_one_len_unlocked);
2801 * Like lookup_one_len_unlocked(), except that it yields ERR_PTR(-ENOENT)
2802 * on negatives. Returns known positive or ERR_PTR(); that's what
2803 * most of the users want. Note that pinned negative with unlocked parent
2804 * _can_ become positive at any time, so callers of lookup_one_len_unlocked()
2805 * need to be very careful; pinned positives have ->d_inode stable, so
2806 * this one avoids such problems.
2808 struct dentry *lookup_positive_unlocked(const char *name,
2809 struct dentry *base, int len)
2811 struct dentry *ret = lookup_one_len_unlocked(name, base, len);
2812 if (!IS_ERR(ret) && d_flags_negative(smp_load_acquire(&ret->d_flags))) {
2814 ret = ERR_PTR(-ENOENT);
2818 EXPORT_SYMBOL(lookup_positive_unlocked);
2820 #ifdef CONFIG_UNIX98_PTYS
2821 int path_pts(struct path *path)
2823 /* Find something mounted on "pts" in the same directory as
2826 struct dentry *parent = dget_parent(path->dentry);
2827 struct dentry *child;
2828 struct qstr this = QSTR_INIT("pts", 3);
2830 if (unlikely(!path_connected(path->mnt, parent))) {
2835 path->dentry = parent;
2836 child = d_hash_and_lookup(parent, &this);
2840 path->dentry = child;
2847 int user_path_at_empty(int dfd, const char __user *name, unsigned flags,
2848 struct path *path, int *empty)
2850 struct filename *filename = getname_flags(name, flags, empty);
2851 int ret = filename_lookup(dfd, filename, flags, path, NULL);
2856 EXPORT_SYMBOL(user_path_at_empty);
2858 int __check_sticky(struct user_namespace *mnt_userns, struct inode *dir,
2859 struct inode *inode)
2861 kuid_t fsuid = current_fsuid();
2863 if (uid_eq(i_uid_into_mnt(mnt_userns, inode), fsuid))
2865 if (uid_eq(i_uid_into_mnt(mnt_userns, dir), fsuid))
2867 return !capable_wrt_inode_uidgid(mnt_userns, inode, CAP_FOWNER);
2869 EXPORT_SYMBOL(__check_sticky);
2872 * Check whether we can remove a link victim from directory dir, check
2873 * whether the type of victim is right.
2874 * 1. We can't do it if dir is read-only (done in permission())
2875 * 2. We should have write and exec permissions on dir
2876 * 3. We can't remove anything from append-only dir
2877 * 4. We can't do anything with immutable dir (done in permission())
2878 * 5. If the sticky bit on dir is set we should either
2879 * a. be owner of dir, or
2880 * b. be owner of victim, or
2881 * c. have CAP_FOWNER capability
2882 * 6. If the victim is append-only or immutable we can't do antyhing with
2883 * links pointing to it.
2884 * 7. If the victim has an unknown uid or gid we can't change the inode.
2885 * 8. If we were asked to remove a directory and victim isn't one - ENOTDIR.
2886 * 9. If we were asked to remove a non-directory and victim isn't one - EISDIR.
2887 * 10. We can't remove a root or mountpoint.
2888 * 11. We don't allow removal of NFS sillyrenamed files; it's handled by
2889 * nfs_async_unlink().
2891 static int may_delete(struct user_namespace *mnt_userns, struct inode *dir,
2892 struct dentry *victim, bool isdir)
2894 struct inode *inode = d_backing_inode(victim);
2897 if (d_is_negative(victim))
2901 BUG_ON(victim->d_parent->d_inode != dir);
2903 /* Inode writeback is not safe when the uid or gid are invalid. */
2904 if (!uid_valid(i_uid_into_mnt(mnt_userns, inode)) ||
2905 !gid_valid(i_gid_into_mnt(mnt_userns, inode)))
2908 audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
2910 error = inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
2916 if (check_sticky(mnt_userns, dir, inode) || IS_APPEND(inode) ||
2917 IS_IMMUTABLE(inode) || IS_SWAPFILE(inode) ||
2918 HAS_UNMAPPED_ID(mnt_userns, inode))
2921 if (!d_is_dir(victim))
2923 if (IS_ROOT(victim))
2925 } else if (d_is_dir(victim))
2927 if (IS_DEADDIR(dir))
2929 if (victim->d_flags & DCACHE_NFSFS_RENAMED)
2934 /* Check whether we can create an object with dentry child in directory
2936 * 1. We can't do it if child already exists (open has special treatment for
2937 * this case, but since we are inlined it's OK)
2938 * 2. We can't do it if dir is read-only (done in permission())
2939 * 3. We can't do it if the fs can't represent the fsuid or fsgid.
2940 * 4. We should have write and exec permissions on dir
2941 * 5. We can't do it if dir is immutable (done in permission())
2943 static inline int may_create(struct user_namespace *mnt_userns,
2944 struct inode *dir, struct dentry *child)
2946 audit_inode_child(dir, child, AUDIT_TYPE_CHILD_CREATE);
2949 if (IS_DEADDIR(dir))
2951 if (!fsuidgid_has_mapping(dir->i_sb, mnt_userns))
2954 return inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
2958 * p1 and p2 should be directories on the same fs.
2960 struct dentry *lock_rename(struct dentry *p1, struct dentry *p2)
2965 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
2969 mutex_lock(&p1->d_sb->s_vfs_rename_mutex);
2971 p = d_ancestor(p2, p1);
2973 inode_lock_nested(p2->d_inode, I_MUTEX_PARENT);
2974 inode_lock_nested(p1->d_inode, I_MUTEX_CHILD);
2978 p = d_ancestor(p1, p2);
2980 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
2981 inode_lock_nested(p2->d_inode, I_MUTEX_CHILD);
2985 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
2986 inode_lock_nested(p2->d_inode, I_MUTEX_PARENT2);
2989 EXPORT_SYMBOL(lock_rename);
2991 void unlock_rename(struct dentry *p1, struct dentry *p2)
2993 inode_unlock(p1->d_inode);
2995 inode_unlock(p2->d_inode);
2996 mutex_unlock(&p1->d_sb->s_vfs_rename_mutex);
2999 EXPORT_SYMBOL(unlock_rename);
3002 * vfs_create - create new file
3003 * @mnt_userns: user namespace of the mount the inode was found from
3004 * @dir: inode of @dentry
3005 * @dentry: pointer to dentry of the base directory
3006 * @mode: mode of the new file
3007 * @want_excl: whether the file must not yet exist
3009 * Create a new file.
3011 * If the inode has been found through an idmapped mount the user namespace of
3012 * the vfsmount must be passed through @mnt_userns. This function will then take
3013 * care to map the inode according to @mnt_userns before checking permissions.
3014 * On non-idmapped mounts or if permission checking is to be performed on the
3015 * raw inode simply passs init_user_ns.
3017 int vfs_create(struct user_namespace *mnt_userns, struct inode *dir,
3018 struct dentry *dentry, umode_t mode, bool want_excl)
3020 int error = may_create(mnt_userns, dir, dentry);
3024 if (!dir->i_op->create)
3025 return -EACCES; /* shouldn't it be ENOSYS? */
3028 error = security_inode_create(dir, dentry, mode);
3031 error = dir->i_op->create(mnt_userns, dir, dentry, mode, want_excl);
3033 fsnotify_create(dir, dentry);
3036 EXPORT_SYMBOL(vfs_create);
3038 int vfs_mkobj(struct dentry *dentry, umode_t mode,
3039 int (*f)(struct dentry *, umode_t, void *),
3042 struct inode *dir = dentry->d_parent->d_inode;
3043 int error = may_create(&init_user_ns, dir, dentry);
3049 error = security_inode_create(dir, dentry, mode);
3052 error = f(dentry, mode, arg);
3054 fsnotify_create(dir, dentry);
3057 EXPORT_SYMBOL(vfs_mkobj);
3059 bool may_open_dev(const struct path *path)
3061 return !(path->mnt->mnt_flags & MNT_NODEV) &&
3062 !(path->mnt->mnt_sb->s_iflags & SB_I_NODEV);
3065 static int may_open(struct user_namespace *mnt_userns, const struct path *path,
3066 int acc_mode, int flag)
3068 struct dentry *dentry = path->dentry;
3069 struct inode *inode = dentry->d_inode;
3075 switch (inode->i_mode & S_IFMT) {
3079 if (acc_mode & MAY_WRITE)
3081 if (acc_mode & MAY_EXEC)
3086 if (!may_open_dev(path))
3091 if (acc_mode & MAY_EXEC)
3096 if ((acc_mode & MAY_EXEC) && path_noexec(path))
3101 error = inode_permission(mnt_userns, inode, MAY_OPEN | acc_mode);
3106 * An append-only file must be opened in append mode for writing.
3108 if (IS_APPEND(inode)) {
3109 if ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND))
3115 /* O_NOATIME can only be set by the owner or superuser */
3116 if (flag & O_NOATIME && !inode_owner_or_capable(mnt_userns, inode))
3122 static int handle_truncate(struct user_namespace *mnt_userns, struct file *filp)
3124 const struct path *path = &filp->f_path;
3125 struct inode *inode = path->dentry->d_inode;
3126 int error = get_write_access(inode);
3130 error = security_path_truncate(path);
3132 error = do_truncate(mnt_userns, path->dentry, 0,
3133 ATTR_MTIME|ATTR_CTIME|ATTR_OPEN,
3136 put_write_access(inode);
3140 static inline int open_to_namei_flags(int flag)
3142 if ((flag & O_ACCMODE) == 3)
3147 static int may_o_create(struct user_namespace *mnt_userns,
3148 const struct path *dir, struct dentry *dentry,
3151 int error = security_path_mknod(dir, dentry, mode, 0);
3155 if (!fsuidgid_has_mapping(dir->dentry->d_sb, mnt_userns))
3158 error = inode_permission(mnt_userns, dir->dentry->d_inode,
3159 MAY_WRITE | MAY_EXEC);
3163 return security_inode_create(dir->dentry->d_inode, dentry, mode);
3167 * Attempt to atomically look up, create and open a file from a negative
3170 * Returns 0 if successful. The file will have been created and attached to
3171 * @file by the filesystem calling finish_open().
3173 * If the file was looked up only or didn't need creating, FMODE_OPENED won't
3174 * be set. The caller will need to perform the open themselves. @path will
3175 * have been updated to point to the new dentry. This may be negative.
3177 * Returns an error code otherwise.
3179 static struct dentry *atomic_open(struct nameidata *nd, struct dentry *dentry,
3181 int open_flag, umode_t mode)
3183 struct dentry *const DENTRY_NOT_SET = (void *) -1UL;
3184 struct inode *dir = nd->path.dentry->d_inode;
3187 if (nd->flags & LOOKUP_DIRECTORY)
3188 open_flag |= O_DIRECTORY;
3190 file->f_path.dentry = DENTRY_NOT_SET;
3191 file->f_path.mnt = nd->path.mnt;
3192 error = dir->i_op->atomic_open(dir, dentry, file,
3193 open_to_namei_flags(open_flag), mode);
3194 d_lookup_done(dentry);
3196 if (file->f_mode & FMODE_OPENED) {
3197 if (unlikely(dentry != file->f_path.dentry)) {
3199 dentry = dget(file->f_path.dentry);
3201 } else if (WARN_ON(file->f_path.dentry == DENTRY_NOT_SET)) {
3204 if (file->f_path.dentry) {
3206 dentry = file->f_path.dentry;
3208 if (unlikely(d_is_negative(dentry)))
3214 dentry = ERR_PTR(error);
3220 * Look up and maybe create and open the last component.
3222 * Must be called with parent locked (exclusive in O_CREAT case).
3224 * Returns 0 on success, that is, if
3225 * the file was successfully atomically created (if necessary) and opened, or
3226 * the file was not completely opened at this time, though lookups and
3227 * creations were performed.
3228 * These case are distinguished by presence of FMODE_OPENED on file->f_mode.
3229 * In the latter case dentry returned in @path might be negative if O_CREAT
3230 * hadn't been specified.
3232 * An error code is returned on failure.
3234 static struct dentry *lookup_open(struct nameidata *nd, struct file *file,
3235 const struct open_flags *op,
3238 struct user_namespace *mnt_userns;
3239 struct dentry *dir = nd->path.dentry;
3240 struct inode *dir_inode = dir->d_inode;
3241 int open_flag = op->open_flag;
3242 struct dentry *dentry;
3243 int error, create_error = 0;
3244 umode_t mode = op->mode;
3245 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
3247 if (unlikely(IS_DEADDIR(dir_inode)))
3248 return ERR_PTR(-ENOENT);
3250 file->f_mode &= ~FMODE_CREATED;
3251 dentry = d_lookup(dir, &nd->last);
3254 dentry = d_alloc_parallel(dir, &nd->last, &wq);
3258 if (d_in_lookup(dentry))
3261 error = d_revalidate(dentry, nd->flags);
3262 if (likely(error > 0))
3266 d_invalidate(dentry);
3270 if (dentry->d_inode) {
3271 /* Cached positive dentry: will open in f_op->open */
3276 * Checking write permission is tricky, bacuse we don't know if we are
3277 * going to actually need it: O_CREAT opens should work as long as the
3278 * file exists. But checking existence breaks atomicity. The trick is
3279 * to check access and if not granted clear O_CREAT from the flags.
3281 * Another problem is returing the "right" error value (e.g. for an
3282 * O_EXCL open we want to return EEXIST not EROFS).
3284 if (unlikely(!got_write))
3285 open_flag &= ~O_TRUNC;
3286 mnt_userns = mnt_user_ns(nd->path.mnt);
3287 if (open_flag & O_CREAT) {
3288 if (open_flag & O_EXCL)
3289 open_flag &= ~O_TRUNC;
3290 if (!IS_POSIXACL(dir->d_inode))
3291 mode &= ~current_umask();
3292 if (likely(got_write))
3293 create_error = may_o_create(mnt_userns, &nd->path,
3296 create_error = -EROFS;
3299 open_flag &= ~O_CREAT;
3300 if (dir_inode->i_op->atomic_open) {
3301 dentry = atomic_open(nd, dentry, file, open_flag, mode);
3302 if (unlikely(create_error) && dentry == ERR_PTR(-ENOENT))
3303 dentry = ERR_PTR(create_error);
3307 if (d_in_lookup(dentry)) {
3308 struct dentry *res = dir_inode->i_op->lookup(dir_inode, dentry,
3310 d_lookup_done(dentry);
3311 if (unlikely(res)) {
3313 error = PTR_ERR(res);
3321 /* Negative dentry, just create the file */
3322 if (!dentry->d_inode && (open_flag & O_CREAT)) {
3323 file->f_mode |= FMODE_CREATED;
3324 audit_inode_child(dir_inode, dentry, AUDIT_TYPE_CHILD_CREATE);
3325 if (!dir_inode->i_op->create) {
3330 error = dir_inode->i_op->create(mnt_userns, dir_inode, dentry,
3331 mode, open_flag & O_EXCL);
3335 if (unlikely(create_error) && !dentry->d_inode) {
3336 error = create_error;
3343 return ERR_PTR(error);
3346 static const char *open_last_lookups(struct nameidata *nd,
3347 struct file *file, const struct open_flags *op)
3349 struct dentry *dir = nd->path.dentry;
3350 int open_flag = op->open_flag;
3351 bool got_write = false;
3353 struct inode *inode;
3354 struct dentry *dentry;
3357 nd->flags |= op->intent;
3359 if (nd->last_type != LAST_NORM) {
3362 return handle_dots(nd, nd->last_type);
3365 if (!(open_flag & O_CREAT)) {
3366 if (nd->last.name[nd->last.len])
3367 nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
3368 /* we _can_ be in RCU mode here */
3369 dentry = lookup_fast(nd, &inode, &seq);
3371 return ERR_CAST(dentry);
3375 BUG_ON(nd->flags & LOOKUP_RCU);
3377 /* create side of things */
3378 if (nd->flags & LOOKUP_RCU) {
3379 if (!try_to_unlazy(nd))
3380 return ERR_PTR(-ECHILD);
3382 audit_inode(nd->name, dir, AUDIT_INODE_PARENT);
3383 /* trailing slashes? */
3384 if (unlikely(nd->last.name[nd->last.len]))
3385 return ERR_PTR(-EISDIR);
3388 if (open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) {
3389 got_write = !mnt_want_write(nd->path.mnt);
3391 * do _not_ fail yet - we might not need that or fail with
3392 * a different error; let lookup_open() decide; we'll be
3393 * dropping this one anyway.
3396 if (open_flag & O_CREAT)
3397 inode_lock(dir->d_inode);
3399 inode_lock_shared(dir->d_inode);
3400 dentry = lookup_open(nd, file, op, got_write);
3401 if (!IS_ERR(dentry) && (file->f_mode & FMODE_CREATED))
3402 fsnotify_create(dir->d_inode, dentry);
3403 if (open_flag & O_CREAT)
3404 inode_unlock(dir->d_inode);
3406 inode_unlock_shared(dir->d_inode);
3409 mnt_drop_write(nd->path.mnt);
3412 return ERR_CAST(dentry);
3414 if (file->f_mode & (FMODE_OPENED | FMODE_CREATED)) {
3415 dput(nd->path.dentry);
3416 nd->path.dentry = dentry;
3423 res = step_into(nd, WALK_TRAILING, dentry, inode, seq);
3425 nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL);
3430 * Handle the last step of open()
3432 static int do_open(struct nameidata *nd,
3433 struct file *file, const struct open_flags *op)
3435 struct user_namespace *mnt_userns;
3436 int open_flag = op->open_flag;
3441 if (!(file->f_mode & (FMODE_OPENED | FMODE_CREATED))) {
3442 error = complete_walk(nd);
3446 if (!(file->f_mode & FMODE_CREATED))
3447 audit_inode(nd->name, nd->path.dentry, 0);
3448 mnt_userns = mnt_user_ns(nd->path.mnt);
3449 if (open_flag & O_CREAT) {
3450 if ((open_flag & O_EXCL) && !(file->f_mode & FMODE_CREATED))
3452 if (d_is_dir(nd->path.dentry))
3454 error = may_create_in_sticky(mnt_userns, nd,
3455 d_backing_inode(nd->path.dentry));
3456 if (unlikely(error))
3459 if ((nd->flags & LOOKUP_DIRECTORY) && !d_can_lookup(nd->path.dentry))
3462 do_truncate = false;
3463 acc_mode = op->acc_mode;
3464 if (file->f_mode & FMODE_CREATED) {
3465 /* Don't check for write permission, don't truncate */
3466 open_flag &= ~O_TRUNC;
3468 } else if (d_is_reg(nd->path.dentry) && open_flag & O_TRUNC) {
3469 error = mnt_want_write(nd->path.mnt);
3474 error = may_open(mnt_userns, &nd->path, acc_mode, open_flag);
3475 if (!error && !(file->f_mode & FMODE_OPENED))
3476 error = vfs_open(&nd->path, file);
3478 error = ima_file_check(file, op->acc_mode);
3479 if (!error && do_truncate)
3480 error = handle_truncate(mnt_userns, file);
3481 if (unlikely(error > 0)) {
3486 mnt_drop_write(nd->path.mnt);
3491 * vfs_tmpfile - create tmpfile
3492 * @mnt_userns: user namespace of the mount the inode was found from
3493 * @dentry: pointer to dentry of the base directory
3494 * @mode: mode of the new tmpfile
3497 * Create a temporary file.
3499 * If the inode has been found through an idmapped mount the user namespace of
3500 * the vfsmount must be passed through @mnt_userns. This function will then take
3501 * care to map the inode according to @mnt_userns before checking permissions.
3502 * On non-idmapped mounts or if permission checking is to be performed on the
3503 * raw inode simply passs init_user_ns.
3505 struct dentry *vfs_tmpfile(struct user_namespace *mnt_userns,
3506 struct dentry *dentry, umode_t mode, int open_flag)
3508 struct dentry *child = NULL;
3509 struct inode *dir = dentry->d_inode;
3510 struct inode *inode;
3513 /* we want directory to be writable */
3514 error = inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
3517 error = -EOPNOTSUPP;
3518 if (!dir->i_op->tmpfile)
3521 child = d_alloc(dentry, &slash_name);
3522 if (unlikely(!child))
3524 error = dir->i_op->tmpfile(mnt_userns, dir, child, mode);
3528 inode = child->d_inode;
3529 if (unlikely(!inode))
3531 if (!(open_flag & O_EXCL)) {
3532 spin_lock(&inode->i_lock);
3533 inode->i_state |= I_LINKABLE;
3534 spin_unlock(&inode->i_lock);
3536 ima_post_create_tmpfile(mnt_userns, inode);
3541 return ERR_PTR(error);
3543 EXPORT_SYMBOL(vfs_tmpfile);
3545 static int do_tmpfile(struct nameidata *nd, unsigned flags,
3546 const struct open_flags *op,
3549 struct user_namespace *mnt_userns;
3550 struct dentry *child;
3552 int error = path_lookupat(nd, flags | LOOKUP_DIRECTORY, &path);
3553 if (unlikely(error))
3555 error = mnt_want_write(path.mnt);
3556 if (unlikely(error))
3558 mnt_userns = mnt_user_ns(path.mnt);
3559 child = vfs_tmpfile(mnt_userns, path.dentry, op->mode, op->open_flag);
3560 error = PTR_ERR(child);
3564 path.dentry = child;
3565 audit_inode(nd->name, child, 0);
3566 /* Don't check for other permissions, the inode was just created */
3567 error = may_open(mnt_userns, &path, 0, op->open_flag);
3569 error = vfs_open(&path, file);
3571 mnt_drop_write(path.mnt);
3577 static int do_o_path(struct nameidata *nd, unsigned flags, struct file *file)
3580 int error = path_lookupat(nd, flags, &path);
3582 audit_inode(nd->name, path.dentry, 0);
3583 error = vfs_open(&path, file);
3589 static struct file *path_openat(struct nameidata *nd,
3590 const struct open_flags *op, unsigned flags)
3595 file = alloc_empty_file(op->open_flag, current_cred());
3599 if (unlikely(file->f_flags & __O_TMPFILE)) {
3600 error = do_tmpfile(nd, flags, op, file);
3601 } else if (unlikely(file->f_flags & O_PATH)) {
3602 error = do_o_path(nd, flags, file);
3604 const char *s = path_init(nd, flags);
3605 while (!(error = link_path_walk(s, nd)) &&
3606 (s = open_last_lookups(nd, file, op)) != NULL)
3609 error = do_open(nd, file, op);
3612 if (likely(!error)) {
3613 if (likely(file->f_mode & FMODE_OPENED))
3619 if (error == -EOPENSTALE) {
3620 if (flags & LOOKUP_RCU)
3625 return ERR_PTR(error);
3628 struct file *do_filp_open(int dfd, struct filename *pathname,
3629 const struct open_flags *op)
3631 struct nameidata nd;
3632 int flags = op->lookup_flags;
3635 set_nameidata(&nd, dfd, pathname, NULL);
3636 filp = path_openat(&nd, op, flags | LOOKUP_RCU);
3637 if (unlikely(filp == ERR_PTR(-ECHILD)))
3638 filp = path_openat(&nd, op, flags);
3639 if (unlikely(filp == ERR_PTR(-ESTALE)))
3640 filp = path_openat(&nd, op, flags | LOOKUP_REVAL);
3641 restore_nameidata();
3645 struct file *do_file_open_root(const struct path *root,
3646 const char *name, const struct open_flags *op)
3648 struct nameidata nd;
3650 struct filename *filename;
3651 int flags = op->lookup_flags;
3653 if (d_is_symlink(root->dentry) && op->intent & LOOKUP_OPEN)
3654 return ERR_PTR(-ELOOP);
3656 filename = getname_kernel(name);
3657 if (IS_ERR(filename))
3658 return ERR_CAST(filename);
3660 set_nameidata(&nd, -1, filename, root);
3661 file = path_openat(&nd, op, flags | LOOKUP_RCU);
3662 if (unlikely(file == ERR_PTR(-ECHILD)))
3663 file = path_openat(&nd, op, flags);
3664 if (unlikely(file == ERR_PTR(-ESTALE)))
3665 file = path_openat(&nd, op, flags | LOOKUP_REVAL);
3666 restore_nameidata();
3671 static struct dentry *filename_create(int dfd, struct filename *name,
3672 struct path *path, unsigned int lookup_flags)
3674 struct dentry *dentry = ERR_PTR(-EEXIST);
3679 bool is_dir = (lookup_flags & LOOKUP_DIRECTORY);
3682 * Note that only LOOKUP_REVAL and LOOKUP_DIRECTORY matter here. Any
3683 * other flags passed in are ignored!
3685 lookup_flags &= LOOKUP_REVAL;
3687 error = filename_parentat(dfd, name, lookup_flags, path, &last, &type);
3689 return ERR_PTR(error);
3692 * Yucky last component or no last component at all?
3693 * (foo/., foo/.., /////)
3695 if (unlikely(type != LAST_NORM))
3698 /* don't fail immediately if it's r/o, at least try to report other errors */
3699 err2 = mnt_want_write(path->mnt);
3701 * Do the final lookup.
3703 lookup_flags |= LOOKUP_CREATE | LOOKUP_EXCL;
3704 inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
3705 dentry = __lookup_hash(&last, path->dentry, lookup_flags);
3710 if (d_is_positive(dentry))
3714 * Special case - lookup gave negative, but... we had foo/bar/
3715 * From the vfs_mknod() POV we just have a negative dentry -
3716 * all is fine. Let's be bastards - you had / on the end, you've
3717 * been asking for (non-existent) directory. -ENOENT for you.
3719 if (unlikely(!is_dir && last.name[last.len])) {
3723 if (unlikely(err2)) {
3730 dentry = ERR_PTR(error);
3732 inode_unlock(path->dentry->d_inode);
3734 mnt_drop_write(path->mnt);
3740 struct dentry *kern_path_create(int dfd, const char *pathname,
3741 struct path *path, unsigned int lookup_flags)
3743 struct filename *filename = getname_kernel(pathname);
3744 struct dentry *res = filename_create(dfd, filename, path, lookup_flags);
3749 EXPORT_SYMBOL(kern_path_create);
3751 void done_path_create(struct path *path, struct dentry *dentry)
3754 inode_unlock(path->dentry->d_inode);
3755 mnt_drop_write(path->mnt);
3758 EXPORT_SYMBOL(done_path_create);
3760 inline struct dentry *user_path_create(int dfd, const char __user *pathname,
3761 struct path *path, unsigned int lookup_flags)
3763 struct filename *filename = getname(pathname);
3764 struct dentry *res = filename_create(dfd, filename, path, lookup_flags);
3769 EXPORT_SYMBOL(user_path_create);
3772 * vfs_mknod - create device node or file
3773 * @mnt_userns: user namespace of the mount the inode was found from
3774 * @dir: inode of @dentry
3775 * @dentry: pointer to dentry of the base directory
3776 * @mode: mode of the new device node or file
3777 * @dev: device number of device to create
3779 * Create a device node or file.
3781 * If the inode has been found through an idmapped mount the user namespace of
3782 * the vfsmount must be passed through @mnt_userns. This function will then take
3783 * care to map the inode according to @mnt_userns before checking permissions.
3784 * On non-idmapped mounts or if permission checking is to be performed on the
3785 * raw inode simply passs init_user_ns.
3787 int vfs_mknod(struct user_namespace *mnt_userns, struct inode *dir,
3788 struct dentry *dentry, umode_t mode, dev_t dev)
3790 bool is_whiteout = S_ISCHR(mode) && dev == WHITEOUT_DEV;
3791 int error = may_create(mnt_userns, dir, dentry);
3796 if ((S_ISCHR(mode) || S_ISBLK(mode)) && !is_whiteout &&
3797 !capable(CAP_MKNOD))
3800 if (!dir->i_op->mknod)
3803 error = devcgroup_inode_mknod(mode, dev);
3807 error = security_inode_mknod(dir, dentry, mode, dev);
3811 error = dir->i_op->mknod(mnt_userns, dir, dentry, mode, dev);
3813 fsnotify_create(dir, dentry);
3816 EXPORT_SYMBOL(vfs_mknod);
3818 static int may_mknod(umode_t mode)
3820 switch (mode & S_IFMT) {
3826 case 0: /* zero mode translates to S_IFREG */
3835 static int do_mknodat(int dfd, struct filename *name, umode_t mode,
3838 struct user_namespace *mnt_userns;
3839 struct dentry *dentry;
3842 unsigned int lookup_flags = 0;
3844 error = may_mknod(mode);
3848 dentry = filename_create(dfd, name, &path, lookup_flags);
3849 error = PTR_ERR(dentry);
3853 if (!IS_POSIXACL(path.dentry->d_inode))
3854 mode &= ~current_umask();
3855 error = security_path_mknod(&path, dentry, mode, dev);
3859 mnt_userns = mnt_user_ns(path.mnt);
3860 switch (mode & S_IFMT) {
3861 case 0: case S_IFREG:
3862 error = vfs_create(mnt_userns, path.dentry->d_inode,
3863 dentry, mode, true);
3865 ima_post_path_mknod(mnt_userns, dentry);
3867 case S_IFCHR: case S_IFBLK:
3868 error = vfs_mknod(mnt_userns, path.dentry->d_inode,
3869 dentry, mode, new_decode_dev(dev));
3871 case S_IFIFO: case S_IFSOCK:
3872 error = vfs_mknod(mnt_userns, path.dentry->d_inode,
3877 done_path_create(&path, dentry);
3878 if (retry_estale(error, lookup_flags)) {
3879 lookup_flags |= LOOKUP_REVAL;
3887 SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, umode_t, mode,
3890 return do_mknodat(dfd, getname(filename), mode, dev);
3893 SYSCALL_DEFINE3(mknod, const char __user *, filename, umode_t, mode, unsigned, dev)
3895 return do_mknodat(AT_FDCWD, getname(filename), mode, dev);
3899 * vfs_mkdir - create directory
3900 * @mnt_userns: user namespace of the mount the inode was found from
3901 * @dir: inode of @dentry
3902 * @dentry: pointer to dentry of the base directory
3903 * @mode: mode of the new directory
3905 * Create a directory.
3907 * If the inode has been found through an idmapped mount the user namespace of
3908 * the vfsmount must be passed through @mnt_userns. This function will then take
3909 * care to map the inode according to @mnt_userns before checking permissions.
3910 * On non-idmapped mounts or if permission checking is to be performed on the
3911 * raw inode simply passs init_user_ns.
3913 int vfs_mkdir(struct user_namespace *mnt_userns, struct inode *dir,
3914 struct dentry *dentry, umode_t mode)
3916 int error = may_create(mnt_userns, dir, dentry);
3917 unsigned max_links = dir->i_sb->s_max_links;
3922 if (!dir->i_op->mkdir)
3925 mode &= (S_IRWXUGO|S_ISVTX);
3926 error = security_inode_mkdir(dir, dentry, mode);
3930 if (max_links && dir->i_nlink >= max_links)
3933 error = dir->i_op->mkdir(mnt_userns, dir, dentry, mode);
3935 fsnotify_mkdir(dir, dentry);
3938 EXPORT_SYMBOL(vfs_mkdir);
3940 int do_mkdirat(int dfd, struct filename *name, umode_t mode)
3942 struct dentry *dentry;
3945 unsigned int lookup_flags = LOOKUP_DIRECTORY;
3948 dentry = filename_create(dfd, name, &path, lookup_flags);
3949 error = PTR_ERR(dentry);
3953 if (!IS_POSIXACL(path.dentry->d_inode))
3954 mode &= ~current_umask();
3955 error = security_path_mkdir(&path, dentry, mode);
3957 struct user_namespace *mnt_userns;
3958 mnt_userns = mnt_user_ns(path.mnt);
3959 error = vfs_mkdir(mnt_userns, path.dentry->d_inode, dentry,
3962 done_path_create(&path, dentry);
3963 if (retry_estale(error, lookup_flags)) {
3964 lookup_flags |= LOOKUP_REVAL;
3972 SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, umode_t, mode)
3974 return do_mkdirat(dfd, getname(pathname), mode);
3977 SYSCALL_DEFINE2(mkdir, const char __user *, pathname, umode_t, mode)
3979 return do_mkdirat(AT_FDCWD, getname(pathname), mode);
3983 * vfs_rmdir - remove directory
3984 * @mnt_userns: user namespace of the mount the inode was found from
3985 * @dir: inode of @dentry
3986 * @dentry: pointer to dentry of the base directory
3988 * Remove a directory.
3990 * If the inode has been found through an idmapped mount the user namespace of
3991 * the vfsmount must be passed through @mnt_userns. This function will then take
3992 * care to map the inode according to @mnt_userns before checking permissions.
3993 * On non-idmapped mounts or if permission checking is to be performed on the
3994 * raw inode simply passs init_user_ns.
3996 int vfs_rmdir(struct user_namespace *mnt_userns, struct inode *dir,
3997 struct dentry *dentry)
3999 int error = may_delete(mnt_userns, dir, dentry, 1);
4004 if (!dir->i_op->rmdir)
4008 inode_lock(dentry->d_inode);
4011 if (is_local_mountpoint(dentry) ||
4012 (dentry->d_inode->i_flags & S_KERNEL_FILE))
4015 error = security_inode_rmdir(dir, dentry);
4019 error = dir->i_op->rmdir(dir, dentry);
4023 shrink_dcache_parent(dentry);
4024 dentry->d_inode->i_flags |= S_DEAD;
4026 detach_mounts(dentry);
4029 inode_unlock(dentry->d_inode);
4032 d_delete_notify(dir, dentry);
4035 EXPORT_SYMBOL(vfs_rmdir);
4037 int do_rmdir(int dfd, struct filename *name)
4039 struct user_namespace *mnt_userns;
4041 struct dentry *dentry;
4045 unsigned int lookup_flags = 0;
4047 error = filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
4063 error = mnt_want_write(path.mnt);
4067 inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
4068 dentry = __lookup_hash(&last, path.dentry, lookup_flags);
4069 error = PTR_ERR(dentry);
4072 if (!dentry->d_inode) {
4076 error = security_path_rmdir(&path, dentry);
4079 mnt_userns = mnt_user_ns(path.mnt);
4080 error = vfs_rmdir(mnt_userns, path.dentry->d_inode, dentry);
4084 inode_unlock(path.dentry->d_inode);
4085 mnt_drop_write(path.mnt);
4088 if (retry_estale(error, lookup_flags)) {
4089 lookup_flags |= LOOKUP_REVAL;
4097 SYSCALL_DEFINE1(rmdir, const char __user *, pathname)
4099 return do_rmdir(AT_FDCWD, getname(pathname));
4103 * vfs_unlink - unlink a filesystem object
4104 * @mnt_userns: user namespace of the mount the inode was found from
4105 * @dir: parent directory
4107 * @delegated_inode: returns victim inode, if the inode is delegated.
4109 * The caller must hold dir->i_mutex.
4111 * If vfs_unlink discovers a delegation, it will return -EWOULDBLOCK and
4112 * return a reference to the inode in delegated_inode. The caller
4113 * should then break the delegation on that inode and retry. Because
4114 * breaking a delegation may take a long time, the caller should drop
4115 * dir->i_mutex before doing so.
4117 * Alternatively, a caller may pass NULL for delegated_inode. This may
4118 * be appropriate for callers that expect the underlying filesystem not
4119 * to be NFS exported.
4121 * If the inode has been found through an idmapped mount the user namespace of
4122 * the vfsmount must be passed through @mnt_userns. This function will then take
4123 * care to map the inode according to @mnt_userns before checking permissions.
4124 * On non-idmapped mounts or if permission checking is to be performed on the
4125 * raw inode simply passs init_user_ns.
4127 int vfs_unlink(struct user_namespace *mnt_userns, struct inode *dir,
4128 struct dentry *dentry, struct inode **delegated_inode)
4130 struct inode *target = dentry->d_inode;
4131 int error = may_delete(mnt_userns, dir, dentry, 0);
4136 if (!dir->i_op->unlink)
4140 if (IS_SWAPFILE(target))
4142 else if (is_local_mountpoint(dentry))
4145 error = security_inode_unlink(dir, dentry);
4147 error = try_break_deleg(target, delegated_inode);
4150 error = dir->i_op->unlink(dir, dentry);
4153 detach_mounts(dentry);
4158 inode_unlock(target);
4160 /* We don't d_delete() NFS sillyrenamed files--they still exist. */
4161 if (!error && dentry->d_flags & DCACHE_NFSFS_RENAMED) {
4162 fsnotify_unlink(dir, dentry);
4163 } else if (!error) {
4164 fsnotify_link_count(target);
4165 d_delete_notify(dir, dentry);
4170 EXPORT_SYMBOL(vfs_unlink);
4173 * Make sure that the actual truncation of the file will occur outside its
4174 * directory's i_mutex. Truncate can take a long time if there is a lot of
4175 * writeout happening, and we don't want to prevent access to the directory
4176 * while waiting on the I/O.
4178 int do_unlinkat(int dfd, struct filename *name)
4181 struct dentry *dentry;
4185 struct inode *inode = NULL;
4186 struct inode *delegated_inode = NULL;
4187 unsigned int lookup_flags = 0;
4189 error = filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
4194 if (type != LAST_NORM)
4197 error = mnt_want_write(path.mnt);
4201 inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
4202 dentry = __lookup_hash(&last, path.dentry, lookup_flags);
4203 error = PTR_ERR(dentry);
4204 if (!IS_ERR(dentry)) {
4205 struct user_namespace *mnt_userns;
4207 /* Why not before? Because we want correct error value */
4208 if (last.name[last.len])
4210 inode = dentry->d_inode;
4211 if (d_is_negative(dentry))
4214 error = security_path_unlink(&path, dentry);
4217 mnt_userns = mnt_user_ns(path.mnt);
4218 error = vfs_unlink(mnt_userns, path.dentry->d_inode, dentry,
4223 inode_unlock(path.dentry->d_inode);
4225 iput(inode); /* truncate the inode here */
4227 if (delegated_inode) {
4228 error = break_deleg_wait(&delegated_inode);
4232 mnt_drop_write(path.mnt);
4235 if (retry_estale(error, lookup_flags)) {
4236 lookup_flags |= LOOKUP_REVAL;
4245 if (d_is_negative(dentry))
4247 else if (d_is_dir(dentry))
4254 SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag)
4256 if ((flag & ~AT_REMOVEDIR) != 0)
4259 if (flag & AT_REMOVEDIR)
4260 return do_rmdir(dfd, getname(pathname));
4261 return do_unlinkat(dfd, getname(pathname));
4264 SYSCALL_DEFINE1(unlink, const char __user *, pathname)
4266 return do_unlinkat(AT_FDCWD, getname(pathname));
4270 * vfs_symlink - create symlink
4271 * @mnt_userns: user namespace of the mount the inode was found from
4272 * @dir: inode of @dentry
4273 * @dentry: pointer to dentry of the base directory
4274 * @oldname: name of the file to link to
4278 * If the inode has been found through an idmapped mount the user namespace of
4279 * the vfsmount must be passed through @mnt_userns. This function will then take
4280 * care to map the inode according to @mnt_userns before checking permissions.
4281 * On non-idmapped mounts or if permission checking is to be performed on the
4282 * raw inode simply passs init_user_ns.
4284 int vfs_symlink(struct user_namespace *mnt_userns, struct inode *dir,
4285 struct dentry *dentry, const char *oldname)
4287 int error = may_create(mnt_userns, dir, dentry);
4292 if (!dir->i_op->symlink)
4295 error = security_inode_symlink(dir, dentry, oldname);
4299 error = dir->i_op->symlink(mnt_userns, dir, dentry, oldname);
4301 fsnotify_create(dir, dentry);
4304 EXPORT_SYMBOL(vfs_symlink);
4306 int do_symlinkat(struct filename *from, int newdfd, struct filename *to)
4309 struct dentry *dentry;
4311 unsigned int lookup_flags = 0;
4314 error = PTR_ERR(from);
4318 dentry = filename_create(newdfd, to, &path, lookup_flags);
4319 error = PTR_ERR(dentry);
4323 error = security_path_symlink(&path, dentry, from->name);
4325 struct user_namespace *mnt_userns;
4327 mnt_userns = mnt_user_ns(path.mnt);
4328 error = vfs_symlink(mnt_userns, path.dentry->d_inode, dentry,
4331 done_path_create(&path, dentry);
4332 if (retry_estale(error, lookup_flags)) {
4333 lookup_flags |= LOOKUP_REVAL;
4342 SYSCALL_DEFINE3(symlinkat, const char __user *, oldname,
4343 int, newdfd, const char __user *, newname)
4345 return do_symlinkat(getname(oldname), newdfd, getname(newname));
4348 SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname)
4350 return do_symlinkat(getname(oldname), AT_FDCWD, getname(newname));
4354 * vfs_link - create a new link
4355 * @old_dentry: object to be linked
4356 * @mnt_userns: the user namespace of the mount
4358 * @new_dentry: where to create the new link
4359 * @delegated_inode: returns inode needing a delegation break
4361 * The caller must hold dir->i_mutex
4363 * If vfs_link discovers a delegation on the to-be-linked file in need
4364 * of breaking, it will return -EWOULDBLOCK and return a reference to the
4365 * inode in delegated_inode. The caller should then break the delegation
4366 * and retry. Because breaking a delegation may take a long time, the
4367 * caller should drop the i_mutex before doing so.
4369 * Alternatively, a caller may pass NULL for delegated_inode. This may
4370 * be appropriate for callers that expect the underlying filesystem not
4371 * to be NFS exported.
4373 * If the inode has been found through an idmapped mount the user namespace of
4374 * the vfsmount must be passed through @mnt_userns. This function will then take
4375 * care to map the inode according to @mnt_userns before checking permissions.
4376 * On non-idmapped mounts or if permission checking is to be performed on the
4377 * raw inode simply passs init_user_ns.
4379 int vfs_link(struct dentry *old_dentry, struct user_namespace *mnt_userns,
4380 struct inode *dir, struct dentry *new_dentry,
4381 struct inode **delegated_inode)
4383 struct inode *inode = old_dentry->d_inode;
4384 unsigned max_links = dir->i_sb->s_max_links;
4390 error = may_create(mnt_userns, dir, new_dentry);
4394 if (dir->i_sb != inode->i_sb)
4398 * A link to an append-only or immutable file cannot be created.
4400 if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
4403 * Updating the link count will likely cause i_uid and i_gid to
4404 * be writen back improperly if their true value is unknown to
4407 if (HAS_UNMAPPED_ID(mnt_userns, inode))
4409 if (!dir->i_op->link)
4411 if (S_ISDIR(inode->i_mode))
4414 error = security_inode_link(old_dentry, dir, new_dentry);
4419 /* Make sure we don't allow creating hardlink to an unlinked file */
4420 if (inode->i_nlink == 0 && !(inode->i_state & I_LINKABLE))
4422 else if (max_links && inode->i_nlink >= max_links)
4425 error = try_break_deleg(inode, delegated_inode);
4427 error = dir->i_op->link(old_dentry, dir, new_dentry);
4430 if (!error && (inode->i_state & I_LINKABLE)) {
4431 spin_lock(&inode->i_lock);
4432 inode->i_state &= ~I_LINKABLE;
4433 spin_unlock(&inode->i_lock);
4435 inode_unlock(inode);
4437 fsnotify_link(dir, inode, new_dentry);
4440 EXPORT_SYMBOL(vfs_link);
4443 * Hardlinks are often used in delicate situations. We avoid
4444 * security-related surprises by not following symlinks on the
4447 * We don't follow them on the oldname either to be compatible
4448 * with linux 2.0, and to avoid hard-linking to directories
4449 * and other special files. --ADM
4451 int do_linkat(int olddfd, struct filename *old, int newdfd,
4452 struct filename *new, int flags)
4454 struct user_namespace *mnt_userns;
4455 struct dentry *new_dentry;
4456 struct path old_path, new_path;
4457 struct inode *delegated_inode = NULL;
4461 if ((flags & ~(AT_SYMLINK_FOLLOW | AT_EMPTY_PATH)) != 0) {
4466 * To use null names we require CAP_DAC_READ_SEARCH
4467 * This ensures that not everyone will be able to create
4468 * handlink using the passed filedescriptor.
4470 if (flags & AT_EMPTY_PATH && !capable(CAP_DAC_READ_SEARCH)) {
4475 if (flags & AT_SYMLINK_FOLLOW)
4476 how |= LOOKUP_FOLLOW;
4478 error = filename_lookup(olddfd, old, how, &old_path, NULL);
4482 new_dentry = filename_create(newdfd, new, &new_path,
4483 (how & LOOKUP_REVAL));
4484 error = PTR_ERR(new_dentry);
4485 if (IS_ERR(new_dentry))
4489 if (old_path.mnt != new_path.mnt)
4491 mnt_userns = mnt_user_ns(new_path.mnt);
4492 error = may_linkat(mnt_userns, &old_path);
4493 if (unlikely(error))
4495 error = security_path_link(old_path.dentry, &new_path, new_dentry);
4498 error = vfs_link(old_path.dentry, mnt_userns, new_path.dentry->d_inode,
4499 new_dentry, &delegated_inode);
4501 done_path_create(&new_path, new_dentry);
4502 if (delegated_inode) {
4503 error = break_deleg_wait(&delegated_inode);
4505 path_put(&old_path);
4509 if (retry_estale(error, how)) {
4510 path_put(&old_path);
4511 how |= LOOKUP_REVAL;
4515 path_put(&old_path);
4523 SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname,
4524 int, newdfd, const char __user *, newname, int, flags)
4526 return do_linkat(olddfd, getname_uflags(oldname, flags),
4527 newdfd, getname(newname), flags);
4530 SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname)
4532 return do_linkat(AT_FDCWD, getname(oldname), AT_FDCWD, getname(newname), 0);
4536 * vfs_rename - rename a filesystem object
4537 * @rd: pointer to &struct renamedata info
4539 * The caller must hold multiple mutexes--see lock_rename()).
4541 * If vfs_rename discovers a delegation in need of breaking at either
4542 * the source or destination, it will return -EWOULDBLOCK and return a
4543 * reference to the inode in delegated_inode. The caller should then
4544 * break the delegation and retry. Because breaking a delegation may
4545 * take a long time, the caller should drop all locks before doing
4548 * Alternatively, a caller may pass NULL for delegated_inode. This may
4549 * be appropriate for callers that expect the underlying filesystem not
4550 * to be NFS exported.
4552 * The worst of all namespace operations - renaming directory. "Perverted"
4553 * doesn't even start to describe it. Somebody in UCB had a heck of a trip...
4556 * a) we can get into loop creation.
4557 * b) race potential - two innocent renames can create a loop together.
4558 * That's where 4.4 screws up. Current fix: serialization on
4559 * sb->s_vfs_rename_mutex. We might be more accurate, but that's another
4561 * c) we have to lock _four_ objects - parents and victim (if it exists),
4562 * and source (if it is not a directory).
4563 * And that - after we got ->i_mutex on parents (until then we don't know
4564 * whether the target exists). Solution: try to be smart with locking
4565 * order for inodes. We rely on the fact that tree topology may change
4566 * only under ->s_vfs_rename_mutex _and_ that parent of the object we
4567 * move will be locked. Thus we can rank directories by the tree
4568 * (ancestors first) and rank all non-directories after them.
4569 * That works since everybody except rename does "lock parent, lookup,
4570 * lock child" and rename is under ->s_vfs_rename_mutex.
4571 * HOWEVER, it relies on the assumption that any object with ->lookup()
4572 * has no more than 1 dentry. If "hybrid" objects will ever appear,
4573 * we'd better make sure that there's no link(2) for them.
4574 * d) conversion from fhandle to dentry may come in the wrong moment - when
4575 * we are removing the target. Solution: we will have to grab ->i_mutex
4576 * in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on
4577 * ->i_mutex on parents, which works but leads to some truly excessive
4580 int vfs_rename(struct renamedata *rd)
4583 struct inode *old_dir = rd->old_dir, *new_dir = rd->new_dir;
4584 struct dentry *old_dentry = rd->old_dentry;
4585 struct dentry *new_dentry = rd->new_dentry;
4586 struct inode **delegated_inode = rd->delegated_inode;
4587 unsigned int flags = rd->flags;
4588 bool is_dir = d_is_dir(old_dentry);
4589 struct inode *source = old_dentry->d_inode;
4590 struct inode *target = new_dentry->d_inode;
4591 bool new_is_dir = false;
4592 unsigned max_links = new_dir->i_sb->s_max_links;
4593 struct name_snapshot old_name;
4595 if (source == target)
4598 error = may_delete(rd->old_mnt_userns, old_dir, old_dentry, is_dir);
4603 error = may_create(rd->new_mnt_userns, new_dir, new_dentry);
4605 new_is_dir = d_is_dir(new_dentry);
4607 if (!(flags & RENAME_EXCHANGE))
4608 error = may_delete(rd->new_mnt_userns, new_dir,
4609 new_dentry, is_dir);
4611 error = may_delete(rd->new_mnt_userns, new_dir,
4612 new_dentry, new_is_dir);
4617 if (!old_dir->i_op->rename)
4621 * If we are going to change the parent - check write permissions,
4622 * we'll need to flip '..'.
4624 if (new_dir != old_dir) {
4626 error = inode_permission(rd->old_mnt_userns, source,
4631 if ((flags & RENAME_EXCHANGE) && new_is_dir) {
4632 error = inode_permission(rd->new_mnt_userns, target,
4639 error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,
4644 take_dentry_name_snapshot(&old_name, old_dentry);
4646 if (!is_dir || (flags & RENAME_EXCHANGE))
4647 lock_two_nondirectories(source, target);
4652 if (IS_SWAPFILE(source) || (target && IS_SWAPFILE(target)))
4656 if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
4659 if (max_links && new_dir != old_dir) {
4661 if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)
4663 if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&
4664 old_dir->i_nlink >= max_links)
4668 error = try_break_deleg(source, delegated_inode);
4672 if (target && !new_is_dir) {
4673 error = try_break_deleg(target, delegated_inode);
4677 error = old_dir->i_op->rename(rd->new_mnt_userns, old_dir, old_dentry,
4678 new_dir, new_dentry, flags);
4682 if (!(flags & RENAME_EXCHANGE) && target) {
4684 shrink_dcache_parent(new_dentry);
4685 target->i_flags |= S_DEAD;
4687 dont_mount(new_dentry);
4688 detach_mounts(new_dentry);
4690 if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {
4691 if (!(flags & RENAME_EXCHANGE))
4692 d_move(old_dentry, new_dentry);
4694 d_exchange(old_dentry, new_dentry);
4697 if (!is_dir || (flags & RENAME_EXCHANGE))
4698 unlock_two_nondirectories(source, target);
4700 inode_unlock(target);
4703 fsnotify_move(old_dir, new_dir, &old_name.name, is_dir,
4704 !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);
4705 if (flags & RENAME_EXCHANGE) {
4706 fsnotify_move(new_dir, old_dir, &old_dentry->d_name,
4707 new_is_dir, NULL, new_dentry);
4710 release_dentry_name_snapshot(&old_name);
4714 EXPORT_SYMBOL(vfs_rename);
4716 int do_renameat2(int olddfd, struct filename *from, int newdfd,
4717 struct filename *to, unsigned int flags)
4719 struct renamedata rd;
4720 struct dentry *old_dentry, *new_dentry;
4721 struct dentry *trap;
4722 struct path old_path, new_path;
4723 struct qstr old_last, new_last;
4724 int old_type, new_type;
4725 struct inode *delegated_inode = NULL;
4726 unsigned int lookup_flags = 0, target_flags = LOOKUP_RENAME_TARGET;
4727 bool should_retry = false;
4728 int error = -EINVAL;
4730 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
4733 if ((flags & (RENAME_NOREPLACE | RENAME_WHITEOUT)) &&
4734 (flags & RENAME_EXCHANGE))
4737 if (flags & RENAME_EXCHANGE)
4741 error = filename_parentat(olddfd, from, lookup_flags, &old_path,
4742 &old_last, &old_type);
4746 error = filename_parentat(newdfd, to, lookup_flags, &new_path, &new_last,
4752 if (old_path.mnt != new_path.mnt)
4756 if (old_type != LAST_NORM)
4759 if (flags & RENAME_NOREPLACE)
4761 if (new_type != LAST_NORM)
4764 error = mnt_want_write(old_path.mnt);
4769 trap = lock_rename(new_path.dentry, old_path.dentry);
4771 old_dentry = __lookup_hash(&old_last, old_path.dentry, lookup_flags);
4772 error = PTR_ERR(old_dentry);
4773 if (IS_ERR(old_dentry))
4775 /* source must exist */
4777 if (d_is_negative(old_dentry))
4779 new_dentry = __lookup_hash(&new_last, new_path.dentry, lookup_flags | target_flags);
4780 error = PTR_ERR(new_dentry);
4781 if (IS_ERR(new_dentry))
4784 if ((flags & RENAME_NOREPLACE) && d_is_positive(new_dentry))
4786 if (flags & RENAME_EXCHANGE) {
4788 if (d_is_negative(new_dentry))
4791 if (!d_is_dir(new_dentry)) {
4793 if (new_last.name[new_last.len])
4797 /* unless the source is a directory trailing slashes give -ENOTDIR */
4798 if (!d_is_dir(old_dentry)) {
4800 if (old_last.name[old_last.len])
4802 if (!(flags & RENAME_EXCHANGE) && new_last.name[new_last.len])
4805 /* source should not be ancestor of target */
4807 if (old_dentry == trap)
4809 /* target should not be an ancestor of source */
4810 if (!(flags & RENAME_EXCHANGE))
4812 if (new_dentry == trap)
4815 error = security_path_rename(&old_path, old_dentry,
4816 &new_path, new_dentry, flags);
4820 rd.old_dir = old_path.dentry->d_inode;
4821 rd.old_dentry = old_dentry;
4822 rd.old_mnt_userns = mnt_user_ns(old_path.mnt);
4823 rd.new_dir = new_path.dentry->d_inode;
4824 rd.new_dentry = new_dentry;
4825 rd.new_mnt_userns = mnt_user_ns(new_path.mnt);
4826 rd.delegated_inode = &delegated_inode;
4828 error = vfs_rename(&rd);
4834 unlock_rename(new_path.dentry, old_path.dentry);
4835 if (delegated_inode) {
4836 error = break_deleg_wait(&delegated_inode);
4840 mnt_drop_write(old_path.mnt);
4842 if (retry_estale(error, lookup_flags))
4843 should_retry = true;
4844 path_put(&new_path);
4846 path_put(&old_path);
4848 should_retry = false;
4849 lookup_flags |= LOOKUP_REVAL;
4858 SYSCALL_DEFINE5(renameat2, int, olddfd, const char __user *, oldname,
4859 int, newdfd, const char __user *, newname, unsigned int, flags)
4861 return do_renameat2(olddfd, getname(oldname), newdfd, getname(newname),
4865 SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname,
4866 int, newdfd, const char __user *, newname)
4868 return do_renameat2(olddfd, getname(oldname), newdfd, getname(newname),
4872 SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname)
4874 return do_renameat2(AT_FDCWD, getname(oldname), AT_FDCWD,
4875 getname(newname), 0);
4878 int readlink_copy(char __user *buffer, int buflen, const char *link)
4880 int len = PTR_ERR(link);
4885 if (len > (unsigned) buflen)
4887 if (copy_to_user(buffer, link, len))
4894 * vfs_readlink - copy symlink body into userspace buffer
4895 * @dentry: dentry on which to get symbolic link
4896 * @buffer: user memory pointer
4897 * @buflen: size of buffer
4899 * Does not touch atime. That's up to the caller if necessary
4901 * Does not call security hook.
4903 int vfs_readlink(struct dentry *dentry, char __user *buffer, int buflen)
4905 struct inode *inode = d_inode(dentry);
4906 DEFINE_DELAYED_CALL(done);
4910 if (unlikely(!(inode->i_opflags & IOP_DEFAULT_READLINK))) {
4911 if (unlikely(inode->i_op->readlink))
4912 return inode->i_op->readlink(dentry, buffer, buflen);
4914 if (!d_is_symlink(dentry))
4917 spin_lock(&inode->i_lock);
4918 inode->i_opflags |= IOP_DEFAULT_READLINK;
4919 spin_unlock(&inode->i_lock);
4922 link = READ_ONCE(inode->i_link);
4924 link = inode->i_op->get_link(dentry, inode, &done);
4926 return PTR_ERR(link);
4928 res = readlink_copy(buffer, buflen, link);
4929 do_delayed_call(&done);
4932 EXPORT_SYMBOL(vfs_readlink);
4935 * vfs_get_link - get symlink body
4936 * @dentry: dentry on which to get symbolic link
4937 * @done: caller needs to free returned data with this
4939 * Calls security hook and i_op->get_link() on the supplied inode.
4941 * It does not touch atime. That's up to the caller if necessary.
4943 * Does not work on "special" symlinks like /proc/$$/fd/N
4945 const char *vfs_get_link(struct dentry *dentry, struct delayed_call *done)
4947 const char *res = ERR_PTR(-EINVAL);
4948 struct inode *inode = d_inode(dentry);
4950 if (d_is_symlink(dentry)) {
4951 res = ERR_PTR(security_inode_readlink(dentry));
4953 res = inode->i_op->get_link(dentry, inode, done);
4957 EXPORT_SYMBOL(vfs_get_link);
4959 /* get the link contents into pagecache */
4960 const char *page_get_link(struct dentry *dentry, struct inode *inode,
4961 struct delayed_call *callback)
4965 struct address_space *mapping = inode->i_mapping;
4968 page = find_get_page(mapping, 0);
4970 return ERR_PTR(-ECHILD);
4971 if (!PageUptodate(page)) {
4973 return ERR_PTR(-ECHILD);
4976 page = read_mapping_page(mapping, 0, NULL);
4980 set_delayed_call(callback, page_put_link, page);
4981 BUG_ON(mapping_gfp_mask(mapping) & __GFP_HIGHMEM);
4982 kaddr = page_address(page);
4983 nd_terminate_link(kaddr, inode->i_size, PAGE_SIZE - 1);
4987 EXPORT_SYMBOL(page_get_link);
4989 void page_put_link(void *arg)
4993 EXPORT_SYMBOL(page_put_link);
4995 int page_readlink(struct dentry *dentry, char __user *buffer, int buflen)
4997 DEFINE_DELAYED_CALL(done);
4998 int res = readlink_copy(buffer, buflen,
4999 page_get_link(dentry, d_inode(dentry),
5001 do_delayed_call(&done);
5004 EXPORT_SYMBOL(page_readlink);
5007 * The nofs argument instructs pagecache_write_begin to pass AOP_FLAG_NOFS
5009 int __page_symlink(struct inode *inode, const char *symname, int len, int nofs)
5011 struct address_space *mapping = inode->i_mapping;
5015 unsigned int flags = 0;
5017 flags |= AOP_FLAG_NOFS;
5020 err = pagecache_write_begin(NULL, mapping, 0, len-1,
5021 flags, &page, &fsdata);
5025 memcpy(page_address(page), symname, len-1);
5027 err = pagecache_write_end(NULL, mapping, 0, len-1, len-1,
5034 mark_inode_dirty(inode);
5039 EXPORT_SYMBOL(__page_symlink);
5041 int page_symlink(struct inode *inode, const char *symname, int len)
5043 return __page_symlink(inode, symname, len,
5044 !mapping_gfp_constraint(inode->i_mapping, __GFP_FS));
5046 EXPORT_SYMBOL(page_symlink);
5048 const struct inode_operations page_symlink_inode_operations = {
5049 .get_link = page_get_link,
5051 EXPORT_SYMBOL(page_symlink_inode_operations);