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/sched/mm.h>
26 #include <linux/fsnotify.h>
27 #include <linux/personality.h>
28 #include <linux/security.h>
29 #include <linux/ima.h>
30 #include <linux/syscalls.h>
31 #include <linux/mount.h>
32 #include <linux/audit.h>
33 #include <linux/capability.h>
34 #include <linux/file.h>
35 #include <linux/fcntl.h>
36 #include <linux/device_cgroup.h>
37 #include <linux/fs_struct.h>
38 #include <linux/posix_acl.h>
39 #include <linux/hash.h>
40 #include <linux/bitops.h>
41 #include <linux/init_task.h>
42 #include <linux/uaccess.h>
47 /* [Feb-1997 T. Schoebel-Theuer]
48 * Fundamental changes in the pathname lookup mechanisms (namei)
49 * were necessary because of omirr. The reason is that omirr needs
50 * to know the _real_ pathname, not the user-supplied one, in case
51 * of symlinks (and also when transname replacements occur).
53 * The new code replaces the old recursive symlink resolution with
54 * an iterative one (in case of non-nested symlink chains). It does
55 * this with calls to <fs>_follow_link().
56 * As a side effect, dir_namei(), _namei() and follow_link() are now
57 * replaced with a single function lookup_dentry() that can handle all
58 * the special cases of the former code.
60 * With the new dcache, the pathname is stored at each inode, at least as
61 * long as the refcount of the inode is positive. As a side effect, the
62 * size of the dcache depends on the inode cache and thus is dynamic.
64 * [29-Apr-1998 C. Scott Ananian] Updated above description of symlink
65 * resolution to correspond with current state of the code.
67 * Note that the symlink resolution is not *completely* iterative.
68 * There is still a significant amount of tail- and mid- recursion in
69 * the algorithm. Also, note that <fs>_readlink() is not used in
70 * lookup_dentry(): lookup_dentry() on the result of <fs>_readlink()
71 * may return different results than <fs>_follow_link(). Many virtual
72 * filesystems (including /proc) exhibit this behavior.
75 /* [24-Feb-97 T. Schoebel-Theuer] Side effects caused by new implementation:
76 * New symlink semantics: when open() is called with flags O_CREAT | O_EXCL
77 * and the name already exists in form of a symlink, try to create the new
78 * name indicated by the symlink. The old code always complained that the
79 * name already exists, due to not following the symlink even if its target
80 * is nonexistent. The new semantics affects also mknod() and link() when
81 * the name is a symlink pointing to a non-existent name.
83 * I don't know which semantics is the right one, since I have no access
84 * to standards. But I found by trial that HP-UX 9.0 has the full "new"
85 * semantics implemented, while SunOS 4.1.1 and Solaris (SunOS 5.4) have the
86 * "old" one. Personally, I think the new semantics is much more logical.
87 * Note that "ln old new" where "new" is a symlink pointing to a non-existing
88 * file does succeed in both HP-UX and SunOs, but not in Solaris
89 * and in the old Linux semantics.
92 /* [16-Dec-97 Kevin Buhr] For security reasons, we change some symlink
93 * semantics. See the comments in "open_namei" and "do_link" below.
95 * [10-Sep-98 Alan Modra] Another symlink change.
98 /* [Feb-Apr 2000 AV] Complete rewrite. Rules for symlinks:
99 * inside the path - always follow.
100 * in the last component in creation/removal/renaming - never follow.
101 * if LOOKUP_FOLLOW passed - follow.
102 * if the pathname has trailing slashes - follow.
103 * otherwise - don't follow.
104 * (applied in that order).
106 * [Jun 2000 AV] Inconsistent behaviour of open() in case if flags==O_CREAT
107 * restored for 2.4. This is the last surviving part of old 4.2BSD bug.
108 * During the 2.4 we need to fix the userland stuff depending on it -
109 * hopefully we will be able to get rid of that wart in 2.5. So far only
110 * XEmacs seems to be relying on it...
113 * [Sep 2001 AV] Single-semaphore locking scheme (kudos to David Holland)
114 * implemented. Let's see if raised priority of ->s_vfs_rename_mutex gives
115 * any extra contention...
118 /* In order to reduce some races, while at the same time doing additional
119 * checking and hopefully speeding things up, we copy filenames to the
120 * kernel data space before using them..
122 * POSIX.1 2.4: an empty pathname is invalid (ENOENT).
123 * PATH_MAX includes the nul terminator --RR.
126 #define EMBEDDED_NAME_MAX (PATH_MAX - offsetof(struct filename, iname))
129 getname_flags(const char __user *filename, int flags, int *empty)
131 struct filename *result;
135 result = audit_reusename(filename);
139 result = __getname();
140 if (unlikely(!result))
141 return ERR_PTR(-ENOMEM);
144 * First, try to embed the struct filename inside the names_cache
147 kname = (char *)result->iname;
148 result->name = kname;
150 len = strncpy_from_user(kname, filename, EMBEDDED_NAME_MAX);
151 if (unlikely(len < 0)) {
157 * Uh-oh. We have a name that's approaching PATH_MAX. Allocate a
158 * separate struct filename so we can dedicate the entire
159 * names_cache allocation for the pathname, and re-do the copy from
162 if (unlikely(len == EMBEDDED_NAME_MAX)) {
163 const size_t size = offsetof(struct filename, iname[1]);
164 kname = (char *)result;
167 * size is chosen that way we to guarantee that
168 * result->iname[0] is within the same object and that
169 * kname can't be equal to result->iname, no matter what.
171 result = kzalloc(size, GFP_KERNEL);
172 if (unlikely(!result)) {
174 return ERR_PTR(-ENOMEM);
176 result->name = kname;
177 len = strncpy_from_user(kname, filename, PATH_MAX);
178 if (unlikely(len < 0)) {
183 if (unlikely(len == PATH_MAX)) {
186 return ERR_PTR(-ENAMETOOLONG);
191 /* The empty path is special. */
192 if (unlikely(!len)) {
195 if (!(flags & LOOKUP_EMPTY)) {
197 return ERR_PTR(-ENOENT);
201 result->uptr = filename;
202 result->aname = NULL;
203 audit_getname(result);
208 getname_uflags(const char __user *filename, int uflags)
210 int flags = (uflags & AT_EMPTY_PATH) ? LOOKUP_EMPTY : 0;
212 return getname_flags(filename, flags, NULL);
216 getname(const char __user * filename)
218 return getname_flags(filename, 0, NULL);
222 getname_kernel(const char * filename)
224 struct filename *result;
225 int len = strlen(filename) + 1;
227 result = __getname();
228 if (unlikely(!result))
229 return ERR_PTR(-ENOMEM);
231 if (len <= EMBEDDED_NAME_MAX) {
232 result->name = (char *)result->iname;
233 } else if (len <= PATH_MAX) {
234 const size_t size = offsetof(struct filename, iname[1]);
235 struct filename *tmp;
237 tmp = kmalloc(size, GFP_KERNEL);
238 if (unlikely(!tmp)) {
240 return ERR_PTR(-ENOMEM);
242 tmp->name = (char *)result;
246 return ERR_PTR(-ENAMETOOLONG);
248 memcpy((char *)result->name, filename, len);
250 result->aname = NULL;
252 audit_getname(result);
257 void putname(struct filename *name)
262 BUG_ON(name->refcnt <= 0);
264 if (--name->refcnt > 0)
267 if (name->name != name->iname) {
268 __putname(name->name);
275 * check_acl - perform ACL permission checking
276 * @idmap: idmap of the mount the inode was found from
277 * @inode: inode to check permissions on
278 * @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
280 * This function performs the ACL permission checking. Since this function
281 * retrieve POSIX acls it needs to know whether it is called from a blocking or
282 * non-blocking context and thus cares about the MAY_NOT_BLOCK bit.
284 * If the inode has been found through an idmapped mount the idmap of
285 * the vfsmount must be passed through @idmap. This function will then take
286 * care to map the inode according to @idmap before checking permissions.
287 * On non-idmapped mounts or if permission checking is to be performed on the
288 * raw inode simply passs @nop_mnt_idmap.
290 static int check_acl(struct mnt_idmap *idmap,
291 struct inode *inode, int mask)
293 #ifdef CONFIG_FS_POSIX_ACL
294 struct posix_acl *acl;
296 if (mask & MAY_NOT_BLOCK) {
297 acl = get_cached_acl_rcu(inode, ACL_TYPE_ACCESS);
300 /* no ->get_inode_acl() calls in RCU mode... */
301 if (is_uncached_acl(acl))
303 return posix_acl_permission(idmap, inode, acl, mask);
306 acl = get_inode_acl(inode, ACL_TYPE_ACCESS);
310 int error = posix_acl_permission(idmap, inode, acl, mask);
311 posix_acl_release(acl);
320 * acl_permission_check - perform basic UNIX permission checking
321 * @idmap: idmap of the mount the inode was found from
322 * @inode: inode to check permissions on
323 * @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
325 * This function performs the basic UNIX permission checking. Since this
326 * function may retrieve POSIX acls it needs to know whether it is called from a
327 * blocking or non-blocking context and thus cares about the MAY_NOT_BLOCK bit.
329 * If the inode has been found through an idmapped mount the idmap of
330 * the vfsmount must be passed through @idmap. This function will then take
331 * care to map the inode according to @idmap before checking permissions.
332 * On non-idmapped mounts or if permission checking is to be performed on the
333 * raw inode simply passs @nop_mnt_idmap.
335 static int acl_permission_check(struct mnt_idmap *idmap,
336 struct inode *inode, int mask)
338 struct user_namespace *mnt_userns = mnt_idmap_owner(idmap);
339 unsigned int mode = inode->i_mode;
342 /* Are we the owner? If so, ACL's don't matter */
343 vfsuid = i_uid_into_vfsuid(mnt_userns, inode);
344 if (likely(vfsuid_eq_kuid(vfsuid, current_fsuid()))) {
347 return (mask & ~mode) ? -EACCES : 0;
350 /* Do we have ACL's? */
351 if (IS_POSIXACL(inode) && (mode & S_IRWXG)) {
352 int error = check_acl(idmap, inode, mask);
353 if (error != -EAGAIN)
357 /* Only RWX matters for group/other mode bits */
361 * Are the group permissions different from
362 * the other permissions in the bits we care
363 * about? Need to check group ownership if so.
365 if (mask & (mode ^ (mode >> 3))) {
366 vfsgid_t vfsgid = i_gid_into_vfsgid(mnt_userns, inode);
367 if (vfsgid_in_group_p(vfsgid))
371 /* Bits in 'mode' clear that we require? */
372 return (mask & ~mode) ? -EACCES : 0;
376 * generic_permission - check for access rights on a Posix-like filesystem
377 * @idmap: idmap of the mount the inode was found from
378 * @inode: inode to check access rights for
379 * @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC,
380 * %MAY_NOT_BLOCK ...)
382 * Used to check for read/write/execute permissions on a file.
383 * We use "fsuid" for this, letting us set arbitrary permissions
384 * for filesystem access without changing the "normal" uids which
385 * are used for other things.
387 * generic_permission is rcu-walk aware. It returns -ECHILD in case an rcu-walk
388 * request cannot be satisfied (eg. requires blocking or too much complexity).
389 * It would then be called again in ref-walk mode.
391 * If the inode has been found through an idmapped mount the idmap of
392 * the vfsmount must be passed through @idmap. This function will then take
393 * care to map the inode according to @idmap before checking permissions.
394 * On non-idmapped mounts or if permission checking is to be performed on the
395 * raw inode simply passs @nop_mnt_idmap.
397 int generic_permission(struct mnt_idmap *idmap, struct inode *inode,
401 struct user_namespace *mnt_userns = mnt_idmap_owner(idmap);
404 * Do the basic permission checks.
406 ret = acl_permission_check(idmap, inode, mask);
410 if (S_ISDIR(inode->i_mode)) {
411 /* DACs are overridable for directories */
412 if (!(mask & MAY_WRITE))
413 if (capable_wrt_inode_uidgid(mnt_userns, inode,
414 CAP_DAC_READ_SEARCH))
416 if (capable_wrt_inode_uidgid(mnt_userns, inode,
423 * Searching includes executable on directories, else just read.
425 mask &= MAY_READ | MAY_WRITE | MAY_EXEC;
426 if (mask == MAY_READ)
427 if (capable_wrt_inode_uidgid(mnt_userns, inode,
428 CAP_DAC_READ_SEARCH))
431 * Read/write DACs are always overridable.
432 * Executable DACs are overridable when there is
433 * at least one exec bit set.
435 if (!(mask & MAY_EXEC) || (inode->i_mode & S_IXUGO))
436 if (capable_wrt_inode_uidgid(mnt_userns, inode,
442 EXPORT_SYMBOL(generic_permission);
445 * do_inode_permission - UNIX permission checking
446 * @idmap: idmap of the mount the inode was found from
447 * @inode: inode to check permissions on
448 * @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
450 * We _really_ want to just do "generic_permission()" without
451 * even looking at the inode->i_op values. So we keep a cache
452 * flag in inode->i_opflags, that says "this has not special
453 * permission function, use the fast case".
455 static inline int do_inode_permission(struct mnt_idmap *idmap,
456 struct inode *inode, int mask)
458 if (unlikely(!(inode->i_opflags & IOP_FASTPERM))) {
459 if (likely(inode->i_op->permission))
460 return inode->i_op->permission(idmap, inode, mask);
462 /* This gets set once for the inode lifetime */
463 spin_lock(&inode->i_lock);
464 inode->i_opflags |= IOP_FASTPERM;
465 spin_unlock(&inode->i_lock);
467 return generic_permission(idmap, inode, mask);
471 * sb_permission - Check superblock-level permissions
472 * @sb: Superblock of inode to check permission on
473 * @inode: Inode to check permission on
474 * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
476 * Separate out file-system wide checks from inode-specific permission checks.
478 static int sb_permission(struct super_block *sb, struct inode *inode, int mask)
480 if (unlikely(mask & MAY_WRITE)) {
481 umode_t mode = inode->i_mode;
483 /* Nobody gets write access to a read-only fs. */
484 if (sb_rdonly(sb) && (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode)))
491 * inode_permission - Check for access rights to a given inode
492 * @idmap: idmap of the mount the inode was found from
493 * @inode: Inode to check permission on
494 * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
496 * Check for read/write/execute permissions on an inode. We use fs[ug]id for
497 * this, letting us set arbitrary permissions for filesystem access without
498 * changing the "normal" UIDs which are used for other things.
500 * When checking for MAY_APPEND, MAY_WRITE must also be set in @mask.
502 int inode_permission(struct mnt_idmap *idmap,
503 struct inode *inode, int mask)
507 retval = sb_permission(inode->i_sb, inode, mask);
511 if (unlikely(mask & MAY_WRITE)) {
513 * Nobody gets write access to an immutable file.
515 if (IS_IMMUTABLE(inode))
519 * Updating mtime will likely cause i_uid and i_gid to be
520 * written back improperly if their true value is unknown
523 if (HAS_UNMAPPED_ID(idmap, inode))
527 retval = do_inode_permission(idmap, inode, mask);
531 retval = devcgroup_inode_permission(inode, mask);
535 return security_inode_permission(inode, mask);
537 EXPORT_SYMBOL(inode_permission);
540 * path_get - get a reference to a path
541 * @path: path to get the reference to
543 * Given a path increment the reference count to the dentry and the vfsmount.
545 void path_get(const struct path *path)
550 EXPORT_SYMBOL(path_get);
553 * path_put - put a reference to a path
554 * @path: path to put the reference to
556 * Given a path decrement the reference count to the dentry and the vfsmount.
558 void path_put(const struct path *path)
563 EXPORT_SYMBOL(path_put);
565 #define EMBEDDED_LEVELS 2
570 struct inode *inode; /* path.dentry.d_inode */
571 unsigned int flags, state;
572 unsigned seq, next_seq, m_seq, r_seq;
575 int total_link_count;
578 struct delayed_call done;
581 } *stack, internal[EMBEDDED_LEVELS];
582 struct filename *name;
583 struct nameidata *saved;
588 } __randomize_layout;
590 #define ND_ROOT_PRESET 1
591 #define ND_ROOT_GRABBED 2
594 static void __set_nameidata(struct nameidata *p, int dfd, struct filename *name)
596 struct nameidata *old = current->nameidata;
597 p->stack = p->internal;
602 p->path.dentry = NULL;
603 p->total_link_count = old ? old->total_link_count : 0;
605 current->nameidata = p;
608 static inline void set_nameidata(struct nameidata *p, int dfd, struct filename *name,
609 const struct path *root)
611 __set_nameidata(p, dfd, name);
613 if (unlikely(root)) {
614 p->state = ND_ROOT_PRESET;
619 static void restore_nameidata(void)
621 struct nameidata *now = current->nameidata, *old = now->saved;
623 current->nameidata = old;
625 old->total_link_count = now->total_link_count;
626 if (now->stack != now->internal)
630 static bool nd_alloc_stack(struct nameidata *nd)
634 p= kmalloc_array(MAXSYMLINKS, sizeof(struct saved),
635 nd->flags & LOOKUP_RCU ? GFP_ATOMIC : GFP_KERNEL);
638 memcpy(p, nd->internal, sizeof(nd->internal));
644 * path_connected - Verify that a dentry is below mnt.mnt_root
646 * Rename can sometimes move a file or directory outside of a bind
647 * mount, path_connected allows those cases to be detected.
649 static bool path_connected(struct vfsmount *mnt, struct dentry *dentry)
651 struct super_block *sb = mnt->mnt_sb;
653 /* Bind mounts can have disconnected paths */
654 if (mnt->mnt_root == sb->s_root)
657 return is_subdir(dentry, mnt->mnt_root);
660 static void drop_links(struct nameidata *nd)
664 struct saved *last = nd->stack + i;
665 do_delayed_call(&last->done);
666 clear_delayed_call(&last->done);
670 static void leave_rcu(struct nameidata *nd)
672 nd->flags &= ~LOOKUP_RCU;
673 nd->seq = nd->next_seq = 0;
677 static void terminate_walk(struct nameidata *nd)
680 if (!(nd->flags & LOOKUP_RCU)) {
683 for (i = 0; i < nd->depth; i++)
684 path_put(&nd->stack[i].link);
685 if (nd->state & ND_ROOT_GRABBED) {
687 nd->state &= ~ND_ROOT_GRABBED;
694 nd->path.dentry = NULL;
697 /* path_put is needed afterwards regardless of success or failure */
698 static bool __legitimize_path(struct path *path, unsigned seq, unsigned mseq)
700 int res = __legitimize_mnt(path->mnt, mseq);
707 if (unlikely(!lockref_get_not_dead(&path->dentry->d_lockref))) {
711 return !read_seqcount_retry(&path->dentry->d_seq, seq);
714 static inline bool legitimize_path(struct nameidata *nd,
715 struct path *path, unsigned seq)
717 return __legitimize_path(path, seq, nd->m_seq);
720 static bool legitimize_links(struct nameidata *nd)
723 if (unlikely(nd->flags & LOOKUP_CACHED)) {
728 for (i = 0; i < nd->depth; i++) {
729 struct saved *last = nd->stack + i;
730 if (unlikely(!legitimize_path(nd, &last->link, last->seq))) {
739 static bool legitimize_root(struct nameidata *nd)
741 /* Nothing to do if nd->root is zero or is managed by the VFS user. */
742 if (!nd->root.mnt || (nd->state & ND_ROOT_PRESET))
744 nd->state |= ND_ROOT_GRABBED;
745 return legitimize_path(nd, &nd->root, nd->root_seq);
749 * Path walking has 2 modes, rcu-walk and ref-walk (see
750 * Documentation/filesystems/path-lookup.txt). In situations when we can't
751 * continue in RCU mode, we attempt to drop out of rcu-walk mode and grab
752 * normal reference counts on dentries and vfsmounts to transition to ref-walk
753 * mode. Refcounts are grabbed at the last known good point before rcu-walk
754 * got stuck, so ref-walk may continue from there. If this is not successful
755 * (eg. a seqcount has changed), then failure is returned and it's up to caller
756 * to restart the path walk from the beginning in ref-walk mode.
760 * try_to_unlazy - try to switch to ref-walk mode.
761 * @nd: nameidata pathwalk data
762 * Returns: true on success, false on failure
764 * try_to_unlazy attempts to legitimize the current nd->path and nd->root
766 * Must be called from rcu-walk context.
767 * Nothing should touch nameidata between try_to_unlazy() failure and
770 static bool try_to_unlazy(struct nameidata *nd)
772 struct dentry *parent = nd->path.dentry;
774 BUG_ON(!(nd->flags & LOOKUP_RCU));
776 if (unlikely(!legitimize_links(nd)))
778 if (unlikely(!legitimize_path(nd, &nd->path, nd->seq)))
780 if (unlikely(!legitimize_root(nd)))
783 BUG_ON(nd->inode != parent->d_inode);
788 nd->path.dentry = NULL;
795 * try_to_unlazy_next - try to switch to ref-walk mode.
796 * @nd: nameidata pathwalk data
797 * @dentry: next dentry to step into
798 * Returns: true on success, false on failure
800 * Similar to try_to_unlazy(), but here we have the next dentry already
801 * picked by rcu-walk and want to legitimize that in addition to the current
802 * nd->path and nd->root for ref-walk mode. Must be called from rcu-walk context.
803 * Nothing should touch nameidata between try_to_unlazy_next() failure and
806 static bool try_to_unlazy_next(struct nameidata *nd, struct dentry *dentry)
809 BUG_ON(!(nd->flags & LOOKUP_RCU));
811 if (unlikely(!legitimize_links(nd)))
813 res = __legitimize_mnt(nd->path.mnt, nd->m_seq);
819 if (unlikely(!lockref_get_not_dead(&nd->path.dentry->d_lockref)))
823 * We need to move both the parent and the dentry from the RCU domain
824 * to be properly refcounted. And the sequence number in the dentry
825 * validates *both* dentry counters, since we checked the sequence
826 * number of the parent after we got the child sequence number. So we
827 * know the parent must still be valid if the child sequence number is
829 if (unlikely(!lockref_get_not_dead(&dentry->d_lockref)))
831 if (read_seqcount_retry(&dentry->d_seq, nd->next_seq))
834 * Sequence counts matched. Now make sure that the root is
835 * still valid and get it if required.
837 if (unlikely(!legitimize_root(nd)))
845 nd->path.dentry = NULL;
855 static inline int d_revalidate(struct dentry *dentry, unsigned int flags)
857 if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE))
858 return dentry->d_op->d_revalidate(dentry, flags);
864 * complete_walk - successful completion of path walk
865 * @nd: pointer nameidata
867 * If we had been in RCU mode, drop out of it and legitimize nd->path.
868 * Revalidate the final result, unless we'd already done that during
869 * the path walk or the filesystem doesn't ask for it. Return 0 on
870 * success, -error on failure. In case of failure caller does not
871 * need to drop nd->path.
873 static int complete_walk(struct nameidata *nd)
875 struct dentry *dentry = nd->path.dentry;
878 if (nd->flags & LOOKUP_RCU) {
880 * We don't want to zero nd->root for scoped-lookups or
881 * externally-managed nd->root.
883 if (!(nd->state & ND_ROOT_PRESET))
884 if (!(nd->flags & LOOKUP_IS_SCOPED))
886 nd->flags &= ~LOOKUP_CACHED;
887 if (!try_to_unlazy(nd))
891 if (unlikely(nd->flags & LOOKUP_IS_SCOPED)) {
893 * While the guarantee of LOOKUP_IS_SCOPED is (roughly) "don't
894 * ever step outside the root during lookup" and should already
895 * be guaranteed by the rest of namei, we want to avoid a namei
896 * BUG resulting in userspace being given a path that was not
897 * scoped within the root at some point during the lookup.
899 * So, do a final sanity-check to make sure that in the
900 * worst-case scenario (a complete bypass of LOOKUP_IS_SCOPED)
901 * we won't silently return an fd completely outside of the
902 * requested root to userspace.
904 * Userspace could move the path outside the root after this
905 * check, but as discussed elsewhere this is not a concern (the
906 * resolved file was inside the root at some point).
908 if (!path_is_under(&nd->path, &nd->root))
912 if (likely(!(nd->state & ND_JUMPED)))
915 if (likely(!(dentry->d_flags & DCACHE_OP_WEAK_REVALIDATE)))
918 status = dentry->d_op->d_weak_revalidate(dentry, nd->flags);
928 static int set_root(struct nameidata *nd)
930 struct fs_struct *fs = current->fs;
933 * Jumping to the real root in a scoped-lookup is a BUG in namei, but we
934 * still have to ensure it doesn't happen because it will cause a breakout
937 if (WARN_ON(nd->flags & LOOKUP_IS_SCOPED))
938 return -ENOTRECOVERABLE;
940 if (nd->flags & LOOKUP_RCU) {
944 seq = read_seqcount_begin(&fs->seq);
946 nd->root_seq = __read_seqcount_begin(&nd->root.dentry->d_seq);
947 } while (read_seqcount_retry(&fs->seq, seq));
949 get_fs_root(fs, &nd->root);
950 nd->state |= ND_ROOT_GRABBED;
955 static int nd_jump_root(struct nameidata *nd)
957 if (unlikely(nd->flags & LOOKUP_BENEATH))
959 if (unlikely(nd->flags & LOOKUP_NO_XDEV)) {
960 /* Absolute path arguments to path_init() are allowed. */
961 if (nd->path.mnt != NULL && nd->path.mnt != nd->root.mnt)
965 int error = set_root(nd);
969 if (nd->flags & LOOKUP_RCU) {
973 nd->inode = d->d_inode;
974 nd->seq = nd->root_seq;
975 if (read_seqcount_retry(&d->d_seq, nd->seq))
981 nd->inode = nd->path.dentry->d_inode;
983 nd->state |= ND_JUMPED;
988 * Helper to directly jump to a known parsed path from ->get_link,
989 * caller must have taken a reference to path beforehand.
991 int nd_jump_link(const struct path *path)
994 struct nameidata *nd = current->nameidata;
996 if (unlikely(nd->flags & LOOKUP_NO_MAGICLINKS))
1000 if (unlikely(nd->flags & LOOKUP_NO_XDEV)) {
1001 if (nd->path.mnt != path->mnt)
1004 /* Not currently safe for scoped-lookups. */
1005 if (unlikely(nd->flags & LOOKUP_IS_SCOPED))
1008 path_put(&nd->path);
1010 nd->inode = nd->path.dentry->d_inode;
1011 nd->state |= ND_JUMPED;
1019 static inline void put_link(struct nameidata *nd)
1021 struct saved *last = nd->stack + --nd->depth;
1022 do_delayed_call(&last->done);
1023 if (!(nd->flags & LOOKUP_RCU))
1024 path_put(&last->link);
1027 static int sysctl_protected_symlinks __read_mostly;
1028 static int sysctl_protected_hardlinks __read_mostly;
1029 static int sysctl_protected_fifos __read_mostly;
1030 static int sysctl_protected_regular __read_mostly;
1032 #ifdef CONFIG_SYSCTL
1033 static struct ctl_table namei_sysctls[] = {
1035 .procname = "protected_symlinks",
1036 .data = &sysctl_protected_symlinks,
1037 .maxlen = sizeof(int),
1039 .proc_handler = proc_dointvec_minmax,
1040 .extra1 = SYSCTL_ZERO,
1041 .extra2 = SYSCTL_ONE,
1044 .procname = "protected_hardlinks",
1045 .data = &sysctl_protected_hardlinks,
1046 .maxlen = sizeof(int),
1048 .proc_handler = proc_dointvec_minmax,
1049 .extra1 = SYSCTL_ZERO,
1050 .extra2 = SYSCTL_ONE,
1053 .procname = "protected_fifos",
1054 .data = &sysctl_protected_fifos,
1055 .maxlen = sizeof(int),
1057 .proc_handler = proc_dointvec_minmax,
1058 .extra1 = SYSCTL_ZERO,
1059 .extra2 = SYSCTL_TWO,
1062 .procname = "protected_regular",
1063 .data = &sysctl_protected_regular,
1064 .maxlen = sizeof(int),
1066 .proc_handler = proc_dointvec_minmax,
1067 .extra1 = SYSCTL_ZERO,
1068 .extra2 = SYSCTL_TWO,
1073 static int __init init_fs_namei_sysctls(void)
1075 register_sysctl_init("fs", namei_sysctls);
1078 fs_initcall(init_fs_namei_sysctls);
1080 #endif /* CONFIG_SYSCTL */
1083 * may_follow_link - Check symlink following for unsafe situations
1084 * @nd: nameidata pathwalk data
1086 * In the case of the sysctl_protected_symlinks sysctl being enabled,
1087 * CAP_DAC_OVERRIDE needs to be specifically ignored if the symlink is
1088 * in a sticky world-writable directory. This is to protect privileged
1089 * processes from failing races against path names that may change out
1090 * from under them by way of other users creating malicious symlinks.
1091 * It will permit symlinks to be followed only when outside a sticky
1092 * world-writable directory, or when the uid of the symlink and follower
1093 * match, or when the directory owner matches the symlink's owner.
1095 * Returns 0 if following the symlink is allowed, -ve on error.
1097 static inline int may_follow_link(struct nameidata *nd, const struct inode *inode)
1099 struct user_namespace *mnt_userns;
1102 if (!sysctl_protected_symlinks)
1105 mnt_userns = mnt_user_ns(nd->path.mnt);
1106 vfsuid = i_uid_into_vfsuid(mnt_userns, inode);
1107 /* Allowed if owner and follower match. */
1108 if (vfsuid_eq_kuid(vfsuid, current_fsuid()))
1111 /* Allowed if parent directory not sticky and world-writable. */
1112 if ((nd->dir_mode & (S_ISVTX|S_IWOTH)) != (S_ISVTX|S_IWOTH))
1115 /* Allowed if parent directory and link owner match. */
1116 if (vfsuid_valid(nd->dir_vfsuid) && vfsuid_eq(nd->dir_vfsuid, vfsuid))
1119 if (nd->flags & LOOKUP_RCU)
1122 audit_inode(nd->name, nd->stack[0].link.dentry, 0);
1123 audit_log_path_denied(AUDIT_ANOM_LINK, "follow_link");
1128 * safe_hardlink_source - Check for safe hardlink conditions
1129 * @idmap: idmap of the mount the inode was found from
1130 * @inode: the source inode to hardlink from
1132 * Return false if at least one of the following conditions:
1133 * - inode is not a regular file
1135 * - inode is setgid and group-exec
1136 * - access failure for read and write
1138 * Otherwise returns true.
1140 static bool safe_hardlink_source(struct mnt_idmap *idmap,
1141 struct inode *inode)
1143 umode_t mode = inode->i_mode;
1145 /* Special files should not get pinned to the filesystem. */
1149 /* Setuid files should not get pinned to the filesystem. */
1153 /* Executable setgid files should not get pinned to the filesystem. */
1154 if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP))
1157 /* Hardlinking to unreadable or unwritable sources is dangerous. */
1158 if (inode_permission(idmap, inode, MAY_READ | MAY_WRITE))
1165 * may_linkat - Check permissions for creating a hardlink
1166 * @idmap: idmap of the mount the inode was found from
1167 * @link: the source to hardlink from
1169 * Block hardlink when all of:
1170 * - sysctl_protected_hardlinks enabled
1171 * - fsuid does not match inode
1172 * - hardlink source is unsafe (see safe_hardlink_source() above)
1173 * - not CAP_FOWNER in a namespace with the inode owner uid mapped
1175 * If the inode has been found through an idmapped mount the idmap of
1176 * the vfsmount must be passed through @idmap. This function will then take
1177 * care to map the inode according to @idmap before checking permissions.
1178 * On non-idmapped mounts or if permission checking is to be performed on the
1179 * raw inode simply pass @nop_mnt_idmap.
1181 * Returns 0 if successful, -ve on error.
1183 int may_linkat(struct mnt_idmap *idmap, const struct path *link)
1185 struct user_namespace *mnt_userns = mnt_idmap_owner(idmap);
1186 struct inode *inode = link->dentry->d_inode;
1188 /* Inode writeback is not safe when the uid or gid are invalid. */
1189 if (!vfsuid_valid(i_uid_into_vfsuid(mnt_userns, inode)) ||
1190 !vfsgid_valid(i_gid_into_vfsgid(mnt_userns, inode)))
1193 if (!sysctl_protected_hardlinks)
1196 /* Source inode owner (or CAP_FOWNER) can hardlink all they like,
1197 * otherwise, it must be a safe source.
1199 if (safe_hardlink_source(idmap, inode) ||
1200 inode_owner_or_capable(mnt_userns, inode))
1203 audit_log_path_denied(AUDIT_ANOM_LINK, "linkat");
1208 * may_create_in_sticky - Check whether an O_CREAT open in a sticky directory
1209 * should be allowed, or not, on files that already
1211 * @mnt_userns: user namespace of the mount the inode was found from
1212 * @nd: nameidata pathwalk data
1213 * @inode: the inode of the file to open
1215 * Block an O_CREAT open of a FIFO (or a regular file) when:
1216 * - sysctl_protected_fifos (or sysctl_protected_regular) is enabled
1217 * - the file already exists
1218 * - we are in a sticky directory
1219 * - we don't own the file
1220 * - the owner of the directory doesn't own the file
1221 * - the directory is world writable
1222 * If the sysctl_protected_fifos (or sysctl_protected_regular) is set to 2
1223 * the directory doesn't have to be world writable: being group writable will
1226 * If the inode has been found through an idmapped mount the user namespace of
1227 * the vfsmount must be passed through @mnt_userns. This function will then take
1228 * care to map the inode according to @mnt_userns before checking permissions.
1229 * On non-idmapped mounts or if permission checking is to be performed on the
1230 * raw inode simply passs init_user_ns.
1232 * Returns 0 if the open is allowed, -ve on error.
1234 static int may_create_in_sticky(struct user_namespace *mnt_userns,
1235 struct nameidata *nd, struct inode *const inode)
1237 umode_t dir_mode = nd->dir_mode;
1238 vfsuid_t dir_vfsuid = nd->dir_vfsuid;
1240 if ((!sysctl_protected_fifos && S_ISFIFO(inode->i_mode)) ||
1241 (!sysctl_protected_regular && S_ISREG(inode->i_mode)) ||
1242 likely(!(dir_mode & S_ISVTX)) ||
1243 vfsuid_eq(i_uid_into_vfsuid(mnt_userns, inode), dir_vfsuid) ||
1244 vfsuid_eq_kuid(i_uid_into_vfsuid(mnt_userns, inode), current_fsuid()))
1247 if (likely(dir_mode & 0002) ||
1249 ((sysctl_protected_fifos >= 2 && S_ISFIFO(inode->i_mode)) ||
1250 (sysctl_protected_regular >= 2 && S_ISREG(inode->i_mode))))) {
1251 const char *operation = S_ISFIFO(inode->i_mode) ?
1252 "sticky_create_fifo" :
1253 "sticky_create_regular";
1254 audit_log_path_denied(AUDIT_ANOM_CREAT, operation);
1261 * follow_up - Find the mountpoint of path's vfsmount
1263 * Given a path, find the mountpoint of its source file system.
1264 * Replace @path with the path of the mountpoint in the parent mount.
1267 * Return 1 if we went up a level and 0 if we were already at the
1270 int follow_up(struct path *path)
1272 struct mount *mnt = real_mount(path->mnt);
1273 struct mount *parent;
1274 struct dentry *mountpoint;
1276 read_seqlock_excl(&mount_lock);
1277 parent = mnt->mnt_parent;
1278 if (parent == mnt) {
1279 read_sequnlock_excl(&mount_lock);
1282 mntget(&parent->mnt);
1283 mountpoint = dget(mnt->mnt_mountpoint);
1284 read_sequnlock_excl(&mount_lock);
1286 path->dentry = mountpoint;
1288 path->mnt = &parent->mnt;
1291 EXPORT_SYMBOL(follow_up);
1293 static bool choose_mountpoint_rcu(struct mount *m, const struct path *root,
1294 struct path *path, unsigned *seqp)
1296 while (mnt_has_parent(m)) {
1297 struct dentry *mountpoint = m->mnt_mountpoint;
1300 if (unlikely(root->dentry == mountpoint &&
1301 root->mnt == &m->mnt))
1303 if (mountpoint != m->mnt.mnt_root) {
1304 path->mnt = &m->mnt;
1305 path->dentry = mountpoint;
1306 *seqp = read_seqcount_begin(&mountpoint->d_seq);
1313 static bool choose_mountpoint(struct mount *m, const struct path *root,
1320 unsigned seq, mseq = read_seqbegin(&mount_lock);
1322 found = choose_mountpoint_rcu(m, root, path, &seq);
1323 if (unlikely(!found)) {
1324 if (!read_seqretry(&mount_lock, mseq))
1327 if (likely(__legitimize_path(path, seq, mseq)))
1339 * Perform an automount
1340 * - return -EISDIR to tell follow_managed() to stop and return the path we
1343 static int follow_automount(struct path *path, int *count, unsigned lookup_flags)
1345 struct dentry *dentry = path->dentry;
1347 /* We don't want to mount if someone's just doing a stat -
1348 * unless they're stat'ing a directory and appended a '/' to
1351 * We do, however, want to mount if someone wants to open or
1352 * create a file of any type under the mountpoint, wants to
1353 * traverse through the mountpoint or wants to open the
1354 * mounted directory. Also, autofs may mark negative dentries
1355 * as being automount points. These will need the attentions
1356 * of the daemon to instantiate them before they can be used.
1358 if (!(lookup_flags & (LOOKUP_PARENT | LOOKUP_DIRECTORY |
1359 LOOKUP_OPEN | LOOKUP_CREATE | LOOKUP_AUTOMOUNT)) &&
1363 if (count && (*count)++ >= MAXSYMLINKS)
1366 return finish_automount(dentry->d_op->d_automount(path), path);
1370 * mount traversal - out-of-line part. One note on ->d_flags accesses -
1371 * dentries are pinned but not locked here, so negative dentry can go
1372 * positive right under us. Use of smp_load_acquire() provides a barrier
1373 * sufficient for ->d_inode and ->d_flags consistency.
1375 static int __traverse_mounts(struct path *path, unsigned flags, bool *jumped,
1376 int *count, unsigned lookup_flags)
1378 struct vfsmount *mnt = path->mnt;
1379 bool need_mntput = false;
1382 while (flags & DCACHE_MANAGED_DENTRY) {
1383 /* Allow the filesystem to manage the transit without i_mutex
1385 if (flags & DCACHE_MANAGE_TRANSIT) {
1386 ret = path->dentry->d_op->d_manage(path, false);
1387 flags = smp_load_acquire(&path->dentry->d_flags);
1392 if (flags & DCACHE_MOUNTED) { // something's mounted on it..
1393 struct vfsmount *mounted = lookup_mnt(path);
1394 if (mounted) { // ... in our namespace
1398 path->mnt = mounted;
1399 path->dentry = dget(mounted->mnt_root);
1400 // here we know it's positive
1401 flags = path->dentry->d_flags;
1407 if (!(flags & DCACHE_NEED_AUTOMOUNT))
1410 // uncovered automount point
1411 ret = follow_automount(path, count, lookup_flags);
1412 flags = smp_load_acquire(&path->dentry->d_flags);
1419 // possible if you race with several mount --move
1420 if (need_mntput && path->mnt == mnt)
1422 if (!ret && unlikely(d_flags_negative(flags)))
1424 *jumped = need_mntput;
1428 static inline int traverse_mounts(struct path *path, bool *jumped,
1429 int *count, unsigned lookup_flags)
1431 unsigned flags = smp_load_acquire(&path->dentry->d_flags);
1434 if (likely(!(flags & DCACHE_MANAGED_DENTRY))) {
1436 if (unlikely(d_flags_negative(flags)))
1440 return __traverse_mounts(path, flags, jumped, count, lookup_flags);
1443 int follow_down_one(struct path *path)
1445 struct vfsmount *mounted;
1447 mounted = lookup_mnt(path);
1451 path->mnt = mounted;
1452 path->dentry = dget(mounted->mnt_root);
1457 EXPORT_SYMBOL(follow_down_one);
1460 * Follow down to the covering mount currently visible to userspace. At each
1461 * point, the filesystem owning that dentry may be queried as to whether the
1462 * caller is permitted to proceed or not.
1464 int follow_down(struct path *path)
1466 struct vfsmount *mnt = path->mnt;
1468 int ret = traverse_mounts(path, &jumped, NULL, 0);
1470 if (path->mnt != mnt)
1474 EXPORT_SYMBOL(follow_down);
1477 * Try to skip to top of mountpoint pile in rcuwalk mode. Fail if
1478 * we meet a managed dentry that would need blocking.
1480 static bool __follow_mount_rcu(struct nameidata *nd, struct path *path)
1482 struct dentry *dentry = path->dentry;
1483 unsigned int flags = dentry->d_flags;
1485 if (likely(!(flags & DCACHE_MANAGED_DENTRY)))
1488 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1493 * Don't forget we might have a non-mountpoint managed dentry
1494 * that wants to block transit.
1496 if (unlikely(flags & DCACHE_MANAGE_TRANSIT)) {
1497 int res = dentry->d_op->d_manage(path, true);
1499 return res == -EISDIR;
1500 flags = dentry->d_flags;
1503 if (flags & DCACHE_MOUNTED) {
1504 struct mount *mounted = __lookup_mnt(path->mnt, dentry);
1506 path->mnt = &mounted->mnt;
1507 dentry = path->dentry = mounted->mnt.mnt_root;
1508 nd->state |= ND_JUMPED;
1509 nd->next_seq = read_seqcount_begin(&dentry->d_seq);
1510 flags = dentry->d_flags;
1511 // makes sure that non-RCU pathwalk could reach
1513 if (read_seqretry(&mount_lock, nd->m_seq))
1517 if (read_seqretry(&mount_lock, nd->m_seq))
1520 return !(flags & DCACHE_NEED_AUTOMOUNT);
1524 static inline int handle_mounts(struct nameidata *nd, struct dentry *dentry,
1530 path->mnt = nd->path.mnt;
1531 path->dentry = dentry;
1532 if (nd->flags & LOOKUP_RCU) {
1533 unsigned int seq = nd->next_seq;
1534 if (likely(__follow_mount_rcu(nd, path)))
1536 // *path and nd->next_seq might've been clobbered
1537 path->mnt = nd->path.mnt;
1538 path->dentry = dentry;
1540 if (!try_to_unlazy_next(nd, dentry))
1543 ret = traverse_mounts(path, &jumped, &nd->total_link_count, nd->flags);
1545 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1548 nd->state |= ND_JUMPED;
1550 if (unlikely(ret)) {
1552 if (path->mnt != nd->path.mnt)
1559 * This looks up the name in dcache and possibly revalidates the found dentry.
1560 * NULL is returned if the dentry does not exist in the cache.
1562 static struct dentry *lookup_dcache(const struct qstr *name,
1566 struct dentry *dentry = d_lookup(dir, name);
1568 int error = d_revalidate(dentry, flags);
1569 if (unlikely(error <= 0)) {
1571 d_invalidate(dentry);
1573 return ERR_PTR(error);
1580 * Parent directory has inode locked exclusive. This is one
1581 * and only case when ->lookup() gets called on non in-lookup
1582 * dentries - as the matter of fact, this only gets called
1583 * when directory is guaranteed to have no in-lookup children
1586 static struct dentry *__lookup_hash(const struct qstr *name,
1587 struct dentry *base, unsigned int flags)
1589 struct dentry *dentry = lookup_dcache(name, base, flags);
1591 struct inode *dir = base->d_inode;
1596 /* Don't create child dentry for a dead directory. */
1597 if (unlikely(IS_DEADDIR(dir)))
1598 return ERR_PTR(-ENOENT);
1600 dentry = d_alloc(base, name);
1601 if (unlikely(!dentry))
1602 return ERR_PTR(-ENOMEM);
1604 old = dir->i_op->lookup(dir, dentry, flags);
1605 if (unlikely(old)) {
1612 static struct dentry *lookup_fast(struct nameidata *nd)
1614 struct dentry *dentry, *parent = nd->path.dentry;
1618 * Rename seqlock is not required here because in the off chance
1619 * of a false negative due to a concurrent rename, the caller is
1620 * going to fall back to non-racy lookup.
1622 if (nd->flags & LOOKUP_RCU) {
1623 dentry = __d_lookup_rcu(parent, &nd->last, &nd->next_seq);
1624 if (unlikely(!dentry)) {
1625 if (!try_to_unlazy(nd))
1626 return ERR_PTR(-ECHILD);
1631 * This sequence count validates that the parent had no
1632 * changes while we did the lookup of the dentry above.
1634 if (read_seqcount_retry(&parent->d_seq, nd->seq))
1635 return ERR_PTR(-ECHILD);
1637 status = d_revalidate(dentry, nd->flags);
1638 if (likely(status > 0))
1640 if (!try_to_unlazy_next(nd, dentry))
1641 return ERR_PTR(-ECHILD);
1642 if (status == -ECHILD)
1643 /* we'd been told to redo it in non-rcu mode */
1644 status = d_revalidate(dentry, nd->flags);
1646 dentry = __d_lookup(parent, &nd->last);
1647 if (unlikely(!dentry))
1649 status = d_revalidate(dentry, nd->flags);
1651 if (unlikely(status <= 0)) {
1653 d_invalidate(dentry);
1655 return ERR_PTR(status);
1660 /* Fast lookup failed, do it the slow way */
1661 static struct dentry *__lookup_slow(const struct qstr *name,
1665 struct dentry *dentry, *old;
1666 struct inode *inode = dir->d_inode;
1667 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
1669 /* Don't go there if it's already dead */
1670 if (unlikely(IS_DEADDIR(inode)))
1671 return ERR_PTR(-ENOENT);
1673 dentry = d_alloc_parallel(dir, name, &wq);
1676 if (unlikely(!d_in_lookup(dentry))) {
1677 int error = d_revalidate(dentry, flags);
1678 if (unlikely(error <= 0)) {
1680 d_invalidate(dentry);
1685 dentry = ERR_PTR(error);
1688 old = inode->i_op->lookup(inode, dentry, flags);
1689 d_lookup_done(dentry);
1690 if (unlikely(old)) {
1698 static struct dentry *lookup_slow(const struct qstr *name,
1702 struct inode *inode = dir->d_inode;
1704 inode_lock_shared(inode);
1705 res = __lookup_slow(name, dir, flags);
1706 inode_unlock_shared(inode);
1710 static inline int may_lookup(struct mnt_idmap *idmap,
1711 struct nameidata *nd)
1713 if (nd->flags & LOOKUP_RCU) {
1714 int err = inode_permission(idmap, nd->inode, MAY_EXEC|MAY_NOT_BLOCK);
1715 if (err != -ECHILD || !try_to_unlazy(nd))
1718 return inode_permission(idmap, nd->inode, MAY_EXEC);
1721 static int reserve_stack(struct nameidata *nd, struct path *link)
1723 if (unlikely(nd->total_link_count++ >= MAXSYMLINKS))
1726 if (likely(nd->depth != EMBEDDED_LEVELS))
1728 if (likely(nd->stack != nd->internal))
1730 if (likely(nd_alloc_stack(nd)))
1733 if (nd->flags & LOOKUP_RCU) {
1734 // we need to grab link before we do unlazy. And we can't skip
1735 // unlazy even if we fail to grab the link - cleanup needs it
1736 bool grabbed_link = legitimize_path(nd, link, nd->next_seq);
1738 if (!try_to_unlazy(nd) || !grabbed_link)
1741 if (nd_alloc_stack(nd))
1747 enum {WALK_TRAILING = 1, WALK_MORE = 2, WALK_NOFOLLOW = 4};
1749 static const char *pick_link(struct nameidata *nd, struct path *link,
1750 struct inode *inode, int flags)
1754 int error = reserve_stack(nd, link);
1756 if (unlikely(error)) {
1757 if (!(nd->flags & LOOKUP_RCU))
1759 return ERR_PTR(error);
1761 last = nd->stack + nd->depth++;
1763 clear_delayed_call(&last->done);
1764 last->seq = nd->next_seq;
1766 if (flags & WALK_TRAILING) {
1767 error = may_follow_link(nd, inode);
1768 if (unlikely(error))
1769 return ERR_PTR(error);
1772 if (unlikely(nd->flags & LOOKUP_NO_SYMLINKS) ||
1773 unlikely(link->mnt->mnt_flags & MNT_NOSYMFOLLOW))
1774 return ERR_PTR(-ELOOP);
1776 if (!(nd->flags & LOOKUP_RCU)) {
1777 touch_atime(&last->link);
1779 } else if (atime_needs_update(&last->link, inode)) {
1780 if (!try_to_unlazy(nd))
1781 return ERR_PTR(-ECHILD);
1782 touch_atime(&last->link);
1785 error = security_inode_follow_link(link->dentry, inode,
1786 nd->flags & LOOKUP_RCU);
1787 if (unlikely(error))
1788 return ERR_PTR(error);
1790 res = READ_ONCE(inode->i_link);
1792 const char * (*get)(struct dentry *, struct inode *,
1793 struct delayed_call *);
1794 get = inode->i_op->get_link;
1795 if (nd->flags & LOOKUP_RCU) {
1796 res = get(NULL, inode, &last->done);
1797 if (res == ERR_PTR(-ECHILD) && try_to_unlazy(nd))
1798 res = get(link->dentry, inode, &last->done);
1800 res = get(link->dentry, inode, &last->done);
1808 error = nd_jump_root(nd);
1809 if (unlikely(error))
1810 return ERR_PTR(error);
1811 while (unlikely(*++res == '/'))
1816 all_done: // pure jump
1822 * Do we need to follow links? We _really_ want to be able
1823 * to do this check without having to look at inode->i_op,
1824 * so we keep a cache of "no, this doesn't need follow_link"
1825 * for the common case.
1827 * NOTE: dentry must be what nd->next_seq had been sampled from.
1829 static const char *step_into(struct nameidata *nd, int flags,
1830 struct dentry *dentry)
1833 struct inode *inode;
1834 int err = handle_mounts(nd, dentry, &path);
1837 return ERR_PTR(err);
1838 inode = path.dentry->d_inode;
1839 if (likely(!d_is_symlink(path.dentry)) ||
1840 ((flags & WALK_TRAILING) && !(nd->flags & LOOKUP_FOLLOW)) ||
1841 (flags & WALK_NOFOLLOW)) {
1842 /* not a symlink or should not follow */
1843 if (nd->flags & LOOKUP_RCU) {
1844 if (read_seqcount_retry(&path.dentry->d_seq, nd->next_seq))
1845 return ERR_PTR(-ECHILD);
1846 if (unlikely(!inode))
1847 return ERR_PTR(-ENOENT);
1849 dput(nd->path.dentry);
1850 if (nd->path.mnt != path.mnt)
1851 mntput(nd->path.mnt);
1855 nd->seq = nd->next_seq;
1858 if (nd->flags & LOOKUP_RCU) {
1859 /* make sure that d_is_symlink above matches inode */
1860 if (read_seqcount_retry(&path.dentry->d_seq, nd->next_seq))
1861 return ERR_PTR(-ECHILD);
1863 if (path.mnt == nd->path.mnt)
1866 return pick_link(nd, &path, inode, flags);
1869 static struct dentry *follow_dotdot_rcu(struct nameidata *nd)
1871 struct dentry *parent, *old;
1873 if (path_equal(&nd->path, &nd->root))
1875 if (unlikely(nd->path.dentry == nd->path.mnt->mnt_root)) {
1878 if (!choose_mountpoint_rcu(real_mount(nd->path.mnt),
1879 &nd->root, &path, &seq))
1881 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1882 return ERR_PTR(-ECHILD);
1884 nd->inode = path.dentry->d_inode;
1886 // makes sure that non-RCU pathwalk could reach this state
1887 if (read_seqretry(&mount_lock, nd->m_seq))
1888 return ERR_PTR(-ECHILD);
1889 /* we know that mountpoint was pinned */
1891 old = nd->path.dentry;
1892 parent = old->d_parent;
1893 nd->next_seq = read_seqcount_begin(&parent->d_seq);
1894 // makes sure that non-RCU pathwalk could reach this state
1895 if (read_seqcount_retry(&old->d_seq, nd->seq))
1896 return ERR_PTR(-ECHILD);
1897 if (unlikely(!path_connected(nd->path.mnt, parent)))
1898 return ERR_PTR(-ECHILD);
1901 if (read_seqretry(&mount_lock, nd->m_seq))
1902 return ERR_PTR(-ECHILD);
1903 if (unlikely(nd->flags & LOOKUP_BENEATH))
1904 return ERR_PTR(-ECHILD);
1905 nd->next_seq = nd->seq;
1906 return nd->path.dentry;
1909 static struct dentry *follow_dotdot(struct nameidata *nd)
1911 struct dentry *parent;
1913 if (path_equal(&nd->path, &nd->root))
1915 if (unlikely(nd->path.dentry == nd->path.mnt->mnt_root)) {
1918 if (!choose_mountpoint(real_mount(nd->path.mnt),
1921 path_put(&nd->path);
1923 nd->inode = path.dentry->d_inode;
1924 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1925 return ERR_PTR(-EXDEV);
1927 /* rare case of legitimate dget_parent()... */
1928 parent = dget_parent(nd->path.dentry);
1929 if (unlikely(!path_connected(nd->path.mnt, parent))) {
1931 return ERR_PTR(-ENOENT);
1936 if (unlikely(nd->flags & LOOKUP_BENEATH))
1937 return ERR_PTR(-EXDEV);
1938 return dget(nd->path.dentry);
1941 static const char *handle_dots(struct nameidata *nd, int type)
1943 if (type == LAST_DOTDOT) {
1944 const char *error = NULL;
1945 struct dentry *parent;
1947 if (!nd->root.mnt) {
1948 error = ERR_PTR(set_root(nd));
1952 if (nd->flags & LOOKUP_RCU)
1953 parent = follow_dotdot_rcu(nd);
1955 parent = follow_dotdot(nd);
1957 return ERR_CAST(parent);
1958 error = step_into(nd, WALK_NOFOLLOW, parent);
1959 if (unlikely(error))
1962 if (unlikely(nd->flags & LOOKUP_IS_SCOPED)) {
1964 * If there was a racing rename or mount along our
1965 * path, then we can't be sure that ".." hasn't jumped
1966 * above nd->root (and so userspace should retry or use
1970 if (__read_seqcount_retry(&mount_lock.seqcount, nd->m_seq))
1971 return ERR_PTR(-EAGAIN);
1972 if (__read_seqcount_retry(&rename_lock.seqcount, nd->r_seq))
1973 return ERR_PTR(-EAGAIN);
1979 static const char *walk_component(struct nameidata *nd, int flags)
1981 struct dentry *dentry;
1983 * "." and ".." are special - ".." especially so because it has
1984 * to be able to know about the current root directory and
1985 * parent relationships.
1987 if (unlikely(nd->last_type != LAST_NORM)) {
1988 if (!(flags & WALK_MORE) && nd->depth)
1990 return handle_dots(nd, nd->last_type);
1992 dentry = lookup_fast(nd);
1994 return ERR_CAST(dentry);
1995 if (unlikely(!dentry)) {
1996 dentry = lookup_slow(&nd->last, nd->path.dentry, nd->flags);
1998 return ERR_CAST(dentry);
2000 if (!(flags & WALK_MORE) && nd->depth)
2002 return step_into(nd, flags, dentry);
2006 * We can do the critical dentry name comparison and hashing
2007 * operations one word at a time, but we are limited to:
2009 * - Architectures with fast unaligned word accesses. We could
2010 * do a "get_unaligned()" if this helps and is sufficiently
2013 * - non-CONFIG_DEBUG_PAGEALLOC configurations (so that we
2014 * do not trap on the (extremely unlikely) case of a page
2015 * crossing operation.
2017 * - Furthermore, we need an efficient 64-bit compile for the
2018 * 64-bit case in order to generate the "number of bytes in
2019 * the final mask". Again, that could be replaced with a
2020 * efficient population count instruction or similar.
2022 #ifdef CONFIG_DCACHE_WORD_ACCESS
2024 #include <asm/word-at-a-time.h>
2028 /* Architecture provides HASH_MIX and fold_hash() in <asm/hash.h> */
2030 #elif defined(CONFIG_64BIT)
2032 * Register pressure in the mixing function is an issue, particularly
2033 * on 32-bit x86, but almost any function requires one state value and
2034 * one temporary. Instead, use a function designed for two state values
2035 * and no temporaries.
2037 * This function cannot create a collision in only two iterations, so
2038 * we have two iterations to achieve avalanche. In those two iterations,
2039 * we have six layers of mixing, which is enough to spread one bit's
2040 * influence out to 2^6 = 64 state bits.
2042 * Rotate constants are scored by considering either 64 one-bit input
2043 * deltas or 64*63/2 = 2016 two-bit input deltas, and finding the
2044 * probability of that delta causing a change to each of the 128 output
2045 * bits, using a sample of random initial states.
2047 * The Shannon entropy of the computed probabilities is then summed
2048 * to produce a score. Ideally, any input change has a 50% chance of
2049 * toggling any given output bit.
2051 * Mixing scores (in bits) for (12,45):
2052 * Input delta: 1-bit 2-bit
2053 * 1 round: 713.3 42542.6
2054 * 2 rounds: 2753.7 140389.8
2055 * 3 rounds: 5954.1 233458.2
2056 * 4 rounds: 7862.6 256672.2
2057 * Perfect: 8192 258048
2058 * (64*128) (64*63/2 * 128)
2060 #define HASH_MIX(x, y, a) \
2062 y ^= x, x = rol64(x,12),\
2063 x += y, y = rol64(y,45),\
2067 * Fold two longs into one 32-bit hash value. This must be fast, but
2068 * latency isn't quite as critical, as there is a fair bit of additional
2069 * work done before the hash value is used.
2071 static inline unsigned int fold_hash(unsigned long x, unsigned long y)
2073 y ^= x * GOLDEN_RATIO_64;
2074 y *= GOLDEN_RATIO_64;
2078 #else /* 32-bit case */
2081 * Mixing scores (in bits) for (7,20):
2082 * Input delta: 1-bit 2-bit
2083 * 1 round: 330.3 9201.6
2084 * 2 rounds: 1246.4 25475.4
2085 * 3 rounds: 1907.1 31295.1
2086 * 4 rounds: 2042.3 31718.6
2087 * Perfect: 2048 31744
2088 * (32*64) (32*31/2 * 64)
2090 #define HASH_MIX(x, y, a) \
2092 y ^= x, x = rol32(x, 7),\
2093 x += y, y = rol32(y,20),\
2096 static inline unsigned int fold_hash(unsigned long x, unsigned long y)
2098 /* Use arch-optimized multiply if one exists */
2099 return __hash_32(y ^ __hash_32(x));
2105 * Return the hash of a string of known length. This is carfully
2106 * designed to match hash_name(), which is the more critical function.
2107 * In particular, we must end by hashing a final word containing 0..7
2108 * payload bytes, to match the way that hash_name() iterates until it
2109 * finds the delimiter after the name.
2111 unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
2113 unsigned long a, x = 0, y = (unsigned long)salt;
2118 a = load_unaligned_zeropad(name);
2119 if (len < sizeof(unsigned long))
2122 name += sizeof(unsigned long);
2123 len -= sizeof(unsigned long);
2125 x ^= a & bytemask_from_count(len);
2127 return fold_hash(x, y);
2129 EXPORT_SYMBOL(full_name_hash);
2131 /* Return the "hash_len" (hash and length) of a null-terminated string */
2132 u64 hashlen_string(const void *salt, const char *name)
2134 unsigned long a = 0, x = 0, y = (unsigned long)salt;
2135 unsigned long adata, mask, len;
2136 const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2143 len += sizeof(unsigned long);
2145 a = load_unaligned_zeropad(name+len);
2146 } while (!has_zero(a, &adata, &constants));
2148 adata = prep_zero_mask(a, adata, &constants);
2149 mask = create_zero_mask(adata);
2150 x ^= a & zero_bytemask(mask);
2152 return hashlen_create(fold_hash(x, y), len + find_zero(mask));
2154 EXPORT_SYMBOL(hashlen_string);
2157 * Calculate the length and hash of the path component, and
2158 * return the "hash_len" as the result.
2160 static inline u64 hash_name(const void *salt, const char *name)
2162 unsigned long a = 0, b, x = 0, y = (unsigned long)salt;
2163 unsigned long adata, bdata, mask, len;
2164 const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2171 len += sizeof(unsigned long);
2173 a = load_unaligned_zeropad(name+len);
2174 b = a ^ REPEAT_BYTE('/');
2175 } while (!(has_zero(a, &adata, &constants) | has_zero(b, &bdata, &constants)));
2177 adata = prep_zero_mask(a, adata, &constants);
2178 bdata = prep_zero_mask(b, bdata, &constants);
2179 mask = create_zero_mask(adata | bdata);
2180 x ^= a & zero_bytemask(mask);
2182 return hashlen_create(fold_hash(x, y), len + find_zero(mask));
2185 #else /* !CONFIG_DCACHE_WORD_ACCESS: Slow, byte-at-a-time version */
2187 /* Return the hash of a string of known length */
2188 unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
2190 unsigned long hash = init_name_hash(salt);
2192 hash = partial_name_hash((unsigned char)*name++, hash);
2193 return end_name_hash(hash);
2195 EXPORT_SYMBOL(full_name_hash);
2197 /* Return the "hash_len" (hash and length) of a null-terminated string */
2198 u64 hashlen_string(const void *salt, const char *name)
2200 unsigned long hash = init_name_hash(salt);
2201 unsigned long len = 0, c;
2203 c = (unsigned char)*name;
2206 hash = partial_name_hash(c, hash);
2207 c = (unsigned char)name[len];
2209 return hashlen_create(end_name_hash(hash), len);
2211 EXPORT_SYMBOL(hashlen_string);
2214 * We know there's a real path component here of at least
2217 static inline u64 hash_name(const void *salt, const char *name)
2219 unsigned long hash = init_name_hash(salt);
2220 unsigned long len = 0, c;
2222 c = (unsigned char)*name;
2225 hash = partial_name_hash(c, hash);
2226 c = (unsigned char)name[len];
2227 } while (c && c != '/');
2228 return hashlen_create(end_name_hash(hash), len);
2235 * This is the basic name resolution function, turning a pathname into
2236 * the final dentry. We expect 'base' to be positive and a directory.
2238 * Returns 0 and nd will have valid dentry and mnt on success.
2239 * Returns error and drops reference to input namei data on failure.
2241 static int link_path_walk(const char *name, struct nameidata *nd)
2243 int depth = 0; // depth <= nd->depth
2246 nd->last_type = LAST_ROOT;
2247 nd->flags |= LOOKUP_PARENT;
2249 return PTR_ERR(name);
2253 nd->dir_mode = 0; // short-circuit the 'hardening' idiocy
2257 /* At this point we know we have a real path component. */
2259 struct mnt_idmap *idmap;
2260 struct user_namespace *mnt_userns;
2265 idmap = mnt_idmap(nd->path.mnt);
2266 mnt_userns = mnt_idmap_owner(idmap);
2267 err = may_lookup(idmap, nd);
2271 hash_len = hash_name(nd->path.dentry, name);
2274 if (name[0] == '.') switch (hashlen_len(hash_len)) {
2276 if (name[1] == '.') {
2278 nd->state |= ND_JUMPED;
2284 if (likely(type == LAST_NORM)) {
2285 struct dentry *parent = nd->path.dentry;
2286 nd->state &= ~ND_JUMPED;
2287 if (unlikely(parent->d_flags & DCACHE_OP_HASH)) {
2288 struct qstr this = { { .hash_len = hash_len }, .name = name };
2289 err = parent->d_op->d_hash(parent, &this);
2292 hash_len = this.hash_len;
2297 nd->last.hash_len = hash_len;
2298 nd->last.name = name;
2299 nd->last_type = type;
2301 name += hashlen_len(hash_len);
2305 * If it wasn't NUL, we know it was '/'. Skip that
2306 * slash, and continue until no more slashes.
2310 } while (unlikely(*name == '/'));
2311 if (unlikely(!*name)) {
2313 /* pathname or trailing symlink, done */
2315 nd->dir_vfsuid = i_uid_into_vfsuid(mnt_userns, nd->inode);
2316 nd->dir_mode = nd->inode->i_mode;
2317 nd->flags &= ~LOOKUP_PARENT;
2320 /* last component of nested symlink */
2321 name = nd->stack[--depth].name;
2322 link = walk_component(nd, 0);
2324 /* not the last component */
2325 link = walk_component(nd, WALK_MORE);
2327 if (unlikely(link)) {
2329 return PTR_ERR(link);
2330 /* a symlink to follow */
2331 nd->stack[depth++].name = name;
2335 if (unlikely(!d_can_lookup(nd->path.dentry))) {
2336 if (nd->flags & LOOKUP_RCU) {
2337 if (!try_to_unlazy(nd))
2345 /* must be paired with terminate_walk() */
2346 static const char *path_init(struct nameidata *nd, unsigned flags)
2349 const char *s = nd->name->name;
2351 /* LOOKUP_CACHED requires RCU, ask caller to retry */
2352 if ((flags & (LOOKUP_RCU | LOOKUP_CACHED)) == LOOKUP_CACHED)
2353 return ERR_PTR(-EAGAIN);
2356 flags &= ~LOOKUP_RCU;
2357 if (flags & LOOKUP_RCU)
2360 nd->seq = nd->next_seq = 0;
2363 nd->state |= ND_JUMPED;
2365 nd->m_seq = __read_seqcount_begin(&mount_lock.seqcount);
2366 nd->r_seq = __read_seqcount_begin(&rename_lock.seqcount);
2369 if (nd->state & ND_ROOT_PRESET) {
2370 struct dentry *root = nd->root.dentry;
2371 struct inode *inode = root->d_inode;
2372 if (*s && unlikely(!d_can_lookup(root)))
2373 return ERR_PTR(-ENOTDIR);
2374 nd->path = nd->root;
2376 if (flags & LOOKUP_RCU) {
2377 nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
2378 nd->root_seq = nd->seq;
2380 path_get(&nd->path);
2385 nd->root.mnt = NULL;
2387 /* Absolute pathname -- fetch the root (LOOKUP_IN_ROOT uses nd->dfd). */
2388 if (*s == '/' && !(flags & LOOKUP_IN_ROOT)) {
2389 error = nd_jump_root(nd);
2390 if (unlikely(error))
2391 return ERR_PTR(error);
2395 /* Relative pathname -- get the starting-point it is relative to. */
2396 if (nd->dfd == AT_FDCWD) {
2397 if (flags & LOOKUP_RCU) {
2398 struct fs_struct *fs = current->fs;
2402 seq = read_seqcount_begin(&fs->seq);
2404 nd->inode = nd->path.dentry->d_inode;
2405 nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
2406 } while (read_seqcount_retry(&fs->seq, seq));
2408 get_fs_pwd(current->fs, &nd->path);
2409 nd->inode = nd->path.dentry->d_inode;
2412 /* Caller must check execute permissions on the starting path component */
2413 struct fd f = fdget_raw(nd->dfd);
2414 struct dentry *dentry;
2417 return ERR_PTR(-EBADF);
2419 dentry = f.file->f_path.dentry;
2421 if (*s && unlikely(!d_can_lookup(dentry))) {
2423 return ERR_PTR(-ENOTDIR);
2426 nd->path = f.file->f_path;
2427 if (flags & LOOKUP_RCU) {
2428 nd->inode = nd->path.dentry->d_inode;
2429 nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
2431 path_get(&nd->path);
2432 nd->inode = nd->path.dentry->d_inode;
2437 /* For scoped-lookups we need to set the root to the dirfd as well. */
2438 if (flags & LOOKUP_IS_SCOPED) {
2439 nd->root = nd->path;
2440 if (flags & LOOKUP_RCU) {
2441 nd->root_seq = nd->seq;
2443 path_get(&nd->root);
2444 nd->state |= ND_ROOT_GRABBED;
2450 static inline const char *lookup_last(struct nameidata *nd)
2452 if (nd->last_type == LAST_NORM && nd->last.name[nd->last.len])
2453 nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
2455 return walk_component(nd, WALK_TRAILING);
2458 static int handle_lookup_down(struct nameidata *nd)
2460 if (!(nd->flags & LOOKUP_RCU))
2461 dget(nd->path.dentry);
2462 nd->next_seq = nd->seq;
2463 return PTR_ERR(step_into(nd, WALK_NOFOLLOW, nd->path.dentry));
2466 /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
2467 static int path_lookupat(struct nameidata *nd, unsigned flags, struct path *path)
2469 const char *s = path_init(nd, flags);
2472 if (unlikely(flags & LOOKUP_DOWN) && !IS_ERR(s)) {
2473 err = handle_lookup_down(nd);
2474 if (unlikely(err < 0))
2478 while (!(err = link_path_walk(s, nd)) &&
2479 (s = lookup_last(nd)) != NULL)
2481 if (!err && unlikely(nd->flags & LOOKUP_MOUNTPOINT)) {
2482 err = handle_lookup_down(nd);
2483 nd->state &= ~ND_JUMPED; // no d_weak_revalidate(), please...
2486 err = complete_walk(nd);
2488 if (!err && nd->flags & LOOKUP_DIRECTORY)
2489 if (!d_can_lookup(nd->path.dentry))
2493 nd->path.mnt = NULL;
2494 nd->path.dentry = NULL;
2500 int filename_lookup(int dfd, struct filename *name, unsigned flags,
2501 struct path *path, struct path *root)
2504 struct nameidata nd;
2506 return PTR_ERR(name);
2507 set_nameidata(&nd, dfd, name, root);
2508 retval = path_lookupat(&nd, flags | LOOKUP_RCU, path);
2509 if (unlikely(retval == -ECHILD))
2510 retval = path_lookupat(&nd, flags, path);
2511 if (unlikely(retval == -ESTALE))
2512 retval = path_lookupat(&nd, flags | LOOKUP_REVAL, path);
2514 if (likely(!retval))
2515 audit_inode(name, path->dentry,
2516 flags & LOOKUP_MOUNTPOINT ? AUDIT_INODE_NOEVAL : 0);
2517 restore_nameidata();
2521 /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
2522 static int path_parentat(struct nameidata *nd, unsigned flags,
2523 struct path *parent)
2525 const char *s = path_init(nd, flags);
2526 int err = link_path_walk(s, nd);
2528 err = complete_walk(nd);
2531 nd->path.mnt = NULL;
2532 nd->path.dentry = NULL;
2538 /* Note: this does not consume "name" */
2539 static int filename_parentat(int dfd, struct filename *name,
2540 unsigned int flags, struct path *parent,
2541 struct qstr *last, int *type)
2544 struct nameidata nd;
2547 return PTR_ERR(name);
2548 set_nameidata(&nd, dfd, name, NULL);
2549 retval = path_parentat(&nd, flags | LOOKUP_RCU, parent);
2550 if (unlikely(retval == -ECHILD))
2551 retval = path_parentat(&nd, flags, parent);
2552 if (unlikely(retval == -ESTALE))
2553 retval = path_parentat(&nd, flags | LOOKUP_REVAL, parent);
2554 if (likely(!retval)) {
2556 *type = nd.last_type;
2557 audit_inode(name, parent->dentry, AUDIT_INODE_PARENT);
2559 restore_nameidata();
2563 /* does lookup, returns the object with parent locked */
2564 static struct dentry *__kern_path_locked(struct filename *name, struct path *path)
2570 error = filename_parentat(AT_FDCWD, name, 0, path, &last, &type);
2572 return ERR_PTR(error);
2573 if (unlikely(type != LAST_NORM)) {
2575 return ERR_PTR(-EINVAL);
2577 inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
2578 d = __lookup_hash(&last, path->dentry, 0);
2580 inode_unlock(path->dentry->d_inode);
2586 struct dentry *kern_path_locked(const char *name, struct path *path)
2588 struct filename *filename = getname_kernel(name);
2589 struct dentry *res = __kern_path_locked(filename, path);
2595 int kern_path(const char *name, unsigned int flags, struct path *path)
2597 struct filename *filename = getname_kernel(name);
2598 int ret = filename_lookup(AT_FDCWD, filename, flags, path, NULL);
2604 EXPORT_SYMBOL(kern_path);
2607 * vfs_path_lookup - lookup a file path relative to a dentry-vfsmount pair
2608 * @dentry: pointer to dentry of the base directory
2609 * @mnt: pointer to vfs mount of the base directory
2610 * @name: pointer to file name
2611 * @flags: lookup flags
2612 * @path: pointer to struct path to fill
2614 int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt,
2615 const char *name, unsigned int flags,
2618 struct filename *filename;
2619 struct path root = {.mnt = mnt, .dentry = dentry};
2622 filename = getname_kernel(name);
2623 /* the first argument of filename_lookup() is ignored with root */
2624 ret = filename_lookup(AT_FDCWD, filename, flags, path, &root);
2628 EXPORT_SYMBOL(vfs_path_lookup);
2630 static int lookup_one_common(struct mnt_idmap *idmap,
2631 const char *name, struct dentry *base, int len,
2636 this->hash = full_name_hash(base, name, len);
2640 if (unlikely(name[0] == '.')) {
2641 if (len < 2 || (len == 2 && name[1] == '.'))
2646 unsigned int c = *(const unsigned char *)name++;
2647 if (c == '/' || c == '\0')
2651 * See if the low-level filesystem might want
2652 * to use its own hash..
2654 if (base->d_flags & DCACHE_OP_HASH) {
2655 int err = base->d_op->d_hash(base, this);
2660 return inode_permission(idmap, base->d_inode, MAY_EXEC);
2664 * try_lookup_one_len - filesystem helper to lookup single pathname component
2665 * @name: pathname component to lookup
2666 * @base: base directory to lookup from
2667 * @len: maximum length @len should be interpreted to
2669 * Look up a dentry by name in the dcache, returning NULL if it does not
2670 * currently exist. The function does not try to create a dentry.
2672 * Note that this routine is purely a helper for filesystem usage and should
2673 * not be called by generic code.
2675 * The caller must hold base->i_mutex.
2677 struct dentry *try_lookup_one_len(const char *name, struct dentry *base, int len)
2682 WARN_ON_ONCE(!inode_is_locked(base->d_inode));
2684 err = lookup_one_common(&nop_mnt_idmap, name, base, len, &this);
2686 return ERR_PTR(err);
2688 return lookup_dcache(&this, base, 0);
2690 EXPORT_SYMBOL(try_lookup_one_len);
2693 * lookup_one_len - filesystem helper to lookup single pathname component
2694 * @name: pathname component to lookup
2695 * @base: base directory to lookup from
2696 * @len: maximum length @len should be interpreted to
2698 * Note that this routine is purely a helper for filesystem usage and should
2699 * not be called by generic code.
2701 * The caller must hold base->i_mutex.
2703 struct dentry *lookup_one_len(const char *name, struct dentry *base, int len)
2705 struct dentry *dentry;
2709 WARN_ON_ONCE(!inode_is_locked(base->d_inode));
2711 err = lookup_one_common(&nop_mnt_idmap, name, base, len, &this);
2713 return ERR_PTR(err);
2715 dentry = lookup_dcache(&this, base, 0);
2716 return dentry ? dentry : __lookup_slow(&this, base, 0);
2718 EXPORT_SYMBOL(lookup_one_len);
2721 * lookup_one - filesystem helper to lookup single pathname component
2722 * @idmap: idmap of the mount the lookup is performed from
2723 * @name: pathname component to lookup
2724 * @base: base directory to lookup from
2725 * @len: maximum length @len should be interpreted to
2727 * Note that this routine is purely a helper for filesystem usage and should
2728 * not be called by generic code.
2730 * The caller must hold base->i_mutex.
2732 struct dentry *lookup_one(struct mnt_idmap *idmap, const char *name,
2733 struct dentry *base, int len)
2735 struct dentry *dentry;
2739 WARN_ON_ONCE(!inode_is_locked(base->d_inode));
2741 err = lookup_one_common(idmap, name, base, len, &this);
2743 return ERR_PTR(err);
2745 dentry = lookup_dcache(&this, base, 0);
2746 return dentry ? dentry : __lookup_slow(&this, base, 0);
2748 EXPORT_SYMBOL(lookup_one);
2751 * lookup_one_unlocked - filesystem helper to lookup single pathname component
2752 * @idmap: idmap of the mount the lookup is performed from
2753 * @name: pathname component to lookup
2754 * @base: base directory to lookup from
2755 * @len: maximum length @len should be interpreted to
2757 * Note that this routine is purely a helper for filesystem usage and should
2758 * not be called by generic code.
2760 * Unlike lookup_one_len, it should be called without the parent
2761 * i_mutex held, and will take the i_mutex itself if necessary.
2763 struct dentry *lookup_one_unlocked(struct mnt_idmap *idmap,
2764 const char *name, struct dentry *base,
2771 err = lookup_one_common(idmap, name, base, len, &this);
2773 return ERR_PTR(err);
2775 ret = lookup_dcache(&this, base, 0);
2777 ret = lookup_slow(&this, base, 0);
2780 EXPORT_SYMBOL(lookup_one_unlocked);
2783 * lookup_one_positive_unlocked - filesystem helper to lookup single
2784 * pathname component
2785 * @idmap: idmap of the mount the lookup is performed from
2786 * @name: pathname component to lookup
2787 * @base: base directory to lookup from
2788 * @len: maximum length @len should be interpreted to
2790 * This helper will yield ERR_PTR(-ENOENT) on negatives. The helper returns
2791 * known positive or ERR_PTR(). This is what most of the users want.
2793 * Note that pinned negative with unlocked parent _can_ become positive at any
2794 * time, so callers of lookup_one_unlocked() need to be very careful; pinned
2795 * positives have >d_inode stable, so this one avoids such problems.
2797 * Note that this routine is purely a helper for filesystem usage and should
2798 * not be called by generic code.
2800 * The helper should be called without i_mutex held.
2802 struct dentry *lookup_one_positive_unlocked(struct mnt_idmap *idmap,
2804 struct dentry *base, int len)
2806 struct dentry *ret = lookup_one_unlocked(idmap, name, base, len);
2808 if (!IS_ERR(ret) && d_flags_negative(smp_load_acquire(&ret->d_flags))) {
2810 ret = ERR_PTR(-ENOENT);
2814 EXPORT_SYMBOL(lookup_one_positive_unlocked);
2817 * lookup_one_len_unlocked - filesystem helper to lookup single pathname component
2818 * @name: pathname component to lookup
2819 * @base: base directory to lookup from
2820 * @len: maximum length @len should be interpreted to
2822 * Note that this routine is purely a helper for filesystem usage and should
2823 * not be called by generic code.
2825 * Unlike lookup_one_len, it should be called without the parent
2826 * i_mutex held, and will take the i_mutex itself if necessary.
2828 struct dentry *lookup_one_len_unlocked(const char *name,
2829 struct dentry *base, int len)
2831 return lookup_one_unlocked(&nop_mnt_idmap, name, base, len);
2833 EXPORT_SYMBOL(lookup_one_len_unlocked);
2836 * Like lookup_one_len_unlocked(), except that it yields ERR_PTR(-ENOENT)
2837 * on negatives. Returns known positive or ERR_PTR(); that's what
2838 * most of the users want. Note that pinned negative with unlocked parent
2839 * _can_ become positive at any time, so callers of lookup_one_len_unlocked()
2840 * need to be very careful; pinned positives have ->d_inode stable, so
2841 * this one avoids such problems.
2843 struct dentry *lookup_positive_unlocked(const char *name,
2844 struct dentry *base, int len)
2846 return lookup_one_positive_unlocked(&nop_mnt_idmap, name, base, len);
2848 EXPORT_SYMBOL(lookup_positive_unlocked);
2850 #ifdef CONFIG_UNIX98_PTYS
2851 int path_pts(struct path *path)
2853 /* Find something mounted on "pts" in the same directory as
2856 struct dentry *parent = dget_parent(path->dentry);
2857 struct dentry *child;
2858 struct qstr this = QSTR_INIT("pts", 3);
2860 if (unlikely(!path_connected(path->mnt, parent))) {
2865 path->dentry = parent;
2866 child = d_hash_and_lookup(parent, &this);
2870 path->dentry = child;
2877 int user_path_at_empty(int dfd, const char __user *name, unsigned flags,
2878 struct path *path, int *empty)
2880 struct filename *filename = getname_flags(name, flags, empty);
2881 int ret = filename_lookup(dfd, filename, flags, path, NULL);
2886 EXPORT_SYMBOL(user_path_at_empty);
2888 int __check_sticky(struct user_namespace *mnt_userns, struct inode *dir,
2889 struct inode *inode)
2891 kuid_t fsuid = current_fsuid();
2893 if (vfsuid_eq_kuid(i_uid_into_vfsuid(mnt_userns, inode), fsuid))
2895 if (vfsuid_eq_kuid(i_uid_into_vfsuid(mnt_userns, dir), fsuid))
2897 return !capable_wrt_inode_uidgid(mnt_userns, inode, CAP_FOWNER);
2899 EXPORT_SYMBOL(__check_sticky);
2902 * Check whether we can remove a link victim from directory dir, check
2903 * whether the type of victim is right.
2904 * 1. We can't do it if dir is read-only (done in permission())
2905 * 2. We should have write and exec permissions on dir
2906 * 3. We can't remove anything from append-only dir
2907 * 4. We can't do anything with immutable dir (done in permission())
2908 * 5. If the sticky bit on dir is set we should either
2909 * a. be owner of dir, or
2910 * b. be owner of victim, or
2911 * c. have CAP_FOWNER capability
2912 * 6. If the victim is append-only or immutable we can't do antyhing with
2913 * links pointing to it.
2914 * 7. If the victim has an unknown uid or gid we can't change the inode.
2915 * 8. If we were asked to remove a directory and victim isn't one - ENOTDIR.
2916 * 9. If we were asked to remove a non-directory and victim isn't one - EISDIR.
2917 * 10. We can't remove a root or mountpoint.
2918 * 11. We don't allow removal of NFS sillyrenamed files; it's handled by
2919 * nfs_async_unlink().
2921 static int may_delete(struct mnt_idmap *idmap, struct inode *dir,
2922 struct dentry *victim, bool isdir)
2924 struct user_namespace *mnt_userns = mnt_idmap_owner(idmap);
2925 struct inode *inode = d_backing_inode(victim);
2928 if (d_is_negative(victim))
2932 BUG_ON(victim->d_parent->d_inode != dir);
2934 /* Inode writeback is not safe when the uid or gid are invalid. */
2935 if (!vfsuid_valid(i_uid_into_vfsuid(mnt_userns, inode)) ||
2936 !vfsgid_valid(i_gid_into_vfsgid(mnt_userns, inode)))
2939 audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
2941 error = inode_permission(idmap, dir, MAY_WRITE | MAY_EXEC);
2947 if (check_sticky(mnt_userns, dir, inode) || IS_APPEND(inode) ||
2948 IS_IMMUTABLE(inode) || IS_SWAPFILE(inode) ||
2949 HAS_UNMAPPED_ID(idmap, inode))
2952 if (!d_is_dir(victim))
2954 if (IS_ROOT(victim))
2956 } else if (d_is_dir(victim))
2958 if (IS_DEADDIR(dir))
2960 if (victim->d_flags & DCACHE_NFSFS_RENAMED)
2965 /* Check whether we can create an object with dentry child in directory
2967 * 1. We can't do it if child already exists (open has special treatment for
2968 * this case, but since we are inlined it's OK)
2969 * 2. We can't do it if dir is read-only (done in permission())
2970 * 3. We can't do it if the fs can't represent the fsuid or fsgid.
2971 * 4. We should have write and exec permissions on dir
2972 * 5. We can't do it if dir is immutable (done in permission())
2974 static inline int may_create(struct mnt_idmap *idmap,
2975 struct inode *dir, struct dentry *child)
2977 audit_inode_child(dir, child, AUDIT_TYPE_CHILD_CREATE);
2980 if (IS_DEADDIR(dir))
2982 if (!fsuidgid_has_mapping(dir->i_sb, idmap))
2985 return inode_permission(idmap, dir, MAY_WRITE | MAY_EXEC);
2989 * p1 and p2 should be directories on the same fs.
2991 struct dentry *lock_rename(struct dentry *p1, struct dentry *p2)
2996 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
3000 mutex_lock(&p1->d_sb->s_vfs_rename_mutex);
3002 p = d_ancestor(p2, p1);
3004 inode_lock_nested(p2->d_inode, I_MUTEX_PARENT);
3005 inode_lock_nested(p1->d_inode, I_MUTEX_CHILD);
3009 p = d_ancestor(p1, p2);
3011 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
3012 inode_lock_nested(p2->d_inode, I_MUTEX_CHILD);
3016 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
3017 inode_lock_nested(p2->d_inode, I_MUTEX_PARENT2);
3020 EXPORT_SYMBOL(lock_rename);
3022 void unlock_rename(struct dentry *p1, struct dentry *p2)
3024 inode_unlock(p1->d_inode);
3026 inode_unlock(p2->d_inode);
3027 mutex_unlock(&p1->d_sb->s_vfs_rename_mutex);
3030 EXPORT_SYMBOL(unlock_rename);
3033 * mode_strip_umask - handle vfs umask stripping
3034 * @dir: parent directory of the new inode
3035 * @mode: mode of the new inode to be created in @dir
3037 * Umask stripping depends on whether or not the filesystem supports POSIX
3038 * ACLs. If the filesystem doesn't support it umask stripping is done directly
3039 * in here. If the filesystem does support POSIX ACLs umask stripping is
3040 * deferred until the filesystem calls posix_acl_create().
3044 static inline umode_t mode_strip_umask(const struct inode *dir, umode_t mode)
3046 if (!IS_POSIXACL(dir))
3047 mode &= ~current_umask();
3052 * vfs_prepare_mode - prepare the mode to be used for a new inode
3053 * @mnt_userns: user namespace of the mount the inode was found from
3054 * @dir: parent directory of the new inode
3055 * @mode: mode of the new inode
3056 * @mask_perms: allowed permission by the vfs
3057 * @type: type of file to be created
3059 * This helper consolidates and enforces vfs restrictions on the @mode of a new
3060 * object to be created.
3062 * Umask stripping depends on whether the filesystem supports POSIX ACLs (see
3063 * the kernel documentation for mode_strip_umask()). Moving umask stripping
3064 * after setgid stripping allows the same ordering for both non-POSIX ACL and
3065 * POSIX ACL supporting filesystems.
3067 * Note that it's currently valid for @type to be 0 if a directory is created.
3068 * Filesystems raise that flag individually and we need to check whether each
3069 * filesystem can deal with receiving S_IFDIR from the vfs before we enforce a
3072 * Returns: mode to be passed to the filesystem
3074 static inline umode_t vfs_prepare_mode(struct user_namespace *mnt_userns,
3075 const struct inode *dir, umode_t mode,
3076 umode_t mask_perms, umode_t type)
3078 mode = mode_strip_sgid(mnt_userns, dir, mode);
3079 mode = mode_strip_umask(dir, mode);
3082 * Apply the vfs mandated allowed permission mask and set the type of
3083 * file to be created before we call into the filesystem.
3085 mode &= (mask_perms & ~S_IFMT);
3086 mode |= (type & S_IFMT);
3092 * vfs_create - create new file
3093 * @idmap: idmap of the mount the inode was found from
3094 * @dir: inode of @dentry
3095 * @dentry: pointer to dentry of the base directory
3096 * @mode: mode of the new file
3097 * @want_excl: whether the file must not yet exist
3099 * Create a new file.
3101 * If the inode has been found through an idmapped mount the idmap of
3102 * the vfsmount must be passed through @idmap. This function will then take
3103 * care to map the inode according to @idmap before checking permissions.
3104 * On non-idmapped mounts or if permission checking is to be performed on the
3105 * raw inode simply passs @nop_mnt_idmap.
3107 int vfs_create(struct mnt_idmap *idmap, struct inode *dir,
3108 struct dentry *dentry, umode_t mode, bool want_excl)
3110 struct user_namespace *mnt_userns = mnt_idmap_owner(idmap);
3113 error = may_create(idmap, dir, dentry);
3117 if (!dir->i_op->create)
3118 return -EACCES; /* shouldn't it be ENOSYS? */
3120 mode = vfs_prepare_mode(mnt_userns, dir, mode, S_IALLUGO, S_IFREG);
3121 error = security_inode_create(dir, dentry, mode);
3124 error = dir->i_op->create(idmap, dir, dentry, mode, want_excl);
3126 fsnotify_create(dir, dentry);
3129 EXPORT_SYMBOL(vfs_create);
3131 int vfs_mkobj(struct dentry *dentry, umode_t mode,
3132 int (*f)(struct dentry *, umode_t, void *),
3135 struct inode *dir = dentry->d_parent->d_inode;
3136 int error = may_create(&nop_mnt_idmap, dir, dentry);
3142 error = security_inode_create(dir, dentry, mode);
3145 error = f(dentry, mode, arg);
3147 fsnotify_create(dir, dentry);
3150 EXPORT_SYMBOL(vfs_mkobj);
3152 bool may_open_dev(const struct path *path)
3154 return !(path->mnt->mnt_flags & MNT_NODEV) &&
3155 !(path->mnt->mnt_sb->s_iflags & SB_I_NODEV);
3158 static int may_open(struct mnt_idmap *idmap, const struct path *path,
3159 int acc_mode, int flag)
3161 struct user_namespace *mnt_userns = mnt_idmap_owner(idmap);
3162 struct dentry *dentry = path->dentry;
3163 struct inode *inode = dentry->d_inode;
3169 switch (inode->i_mode & S_IFMT) {
3173 if (acc_mode & MAY_WRITE)
3175 if (acc_mode & MAY_EXEC)
3180 if (!may_open_dev(path))
3185 if (acc_mode & MAY_EXEC)
3190 if ((acc_mode & MAY_EXEC) && path_noexec(path))
3195 error = inode_permission(idmap, inode, MAY_OPEN | acc_mode);
3200 * An append-only file must be opened in append mode for writing.
3202 if (IS_APPEND(inode)) {
3203 if ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND))
3209 /* O_NOATIME can only be set by the owner or superuser */
3210 if (flag & O_NOATIME && !inode_owner_or_capable(mnt_userns, inode))
3216 static int handle_truncate(struct mnt_idmap *idmap, struct file *filp)
3218 const struct path *path = &filp->f_path;
3219 struct inode *inode = path->dentry->d_inode;
3220 int error = get_write_access(inode);
3224 error = security_file_truncate(filp);
3226 error = do_truncate(idmap, path->dentry, 0,
3227 ATTR_MTIME|ATTR_CTIME|ATTR_OPEN,
3230 put_write_access(inode);
3234 static inline int open_to_namei_flags(int flag)
3236 if ((flag & O_ACCMODE) == 3)
3241 static int may_o_create(struct mnt_idmap *idmap,
3242 const struct path *dir, struct dentry *dentry,
3245 int error = security_path_mknod(dir, dentry, mode, 0);
3249 if (!fsuidgid_has_mapping(dir->dentry->d_sb, idmap))
3252 error = inode_permission(idmap, dir->dentry->d_inode,
3253 MAY_WRITE | MAY_EXEC);
3257 return security_inode_create(dir->dentry->d_inode, dentry, mode);
3261 * Attempt to atomically look up, create and open a file from a negative
3264 * Returns 0 if successful. The file will have been created and attached to
3265 * @file by the filesystem calling finish_open().
3267 * If the file was looked up only or didn't need creating, FMODE_OPENED won't
3268 * be set. The caller will need to perform the open themselves. @path will
3269 * have been updated to point to the new dentry. This may be negative.
3271 * Returns an error code otherwise.
3273 static struct dentry *atomic_open(struct nameidata *nd, struct dentry *dentry,
3275 int open_flag, umode_t mode)
3277 struct dentry *const DENTRY_NOT_SET = (void *) -1UL;
3278 struct inode *dir = nd->path.dentry->d_inode;
3281 if (nd->flags & LOOKUP_DIRECTORY)
3282 open_flag |= O_DIRECTORY;
3284 file->f_path.dentry = DENTRY_NOT_SET;
3285 file->f_path.mnt = nd->path.mnt;
3286 error = dir->i_op->atomic_open(dir, dentry, file,
3287 open_to_namei_flags(open_flag), mode);
3288 d_lookup_done(dentry);
3290 if (file->f_mode & FMODE_OPENED) {
3291 if (unlikely(dentry != file->f_path.dentry)) {
3293 dentry = dget(file->f_path.dentry);
3295 } else if (WARN_ON(file->f_path.dentry == DENTRY_NOT_SET)) {
3298 if (file->f_path.dentry) {
3300 dentry = file->f_path.dentry;
3302 if (unlikely(d_is_negative(dentry)))
3308 dentry = ERR_PTR(error);
3314 * Look up and maybe create and open the last component.
3316 * Must be called with parent locked (exclusive in O_CREAT case).
3318 * Returns 0 on success, that is, if
3319 * the file was successfully atomically created (if necessary) and opened, or
3320 * the file was not completely opened at this time, though lookups and
3321 * creations were performed.
3322 * These case are distinguished by presence of FMODE_OPENED on file->f_mode.
3323 * In the latter case dentry returned in @path might be negative if O_CREAT
3324 * hadn't been specified.
3326 * An error code is returned on failure.
3328 static struct dentry *lookup_open(struct nameidata *nd, struct file *file,
3329 const struct open_flags *op,
3332 struct mnt_idmap *idmap;
3333 struct user_namespace *mnt_userns;
3334 struct dentry *dir = nd->path.dentry;
3335 struct inode *dir_inode = dir->d_inode;
3336 int open_flag = op->open_flag;
3337 struct dentry *dentry;
3338 int error, create_error = 0;
3339 umode_t mode = op->mode;
3340 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
3342 if (unlikely(IS_DEADDIR(dir_inode)))
3343 return ERR_PTR(-ENOENT);
3345 file->f_mode &= ~FMODE_CREATED;
3346 dentry = d_lookup(dir, &nd->last);
3349 dentry = d_alloc_parallel(dir, &nd->last, &wq);
3353 if (d_in_lookup(dentry))
3356 error = d_revalidate(dentry, nd->flags);
3357 if (likely(error > 0))
3361 d_invalidate(dentry);
3365 if (dentry->d_inode) {
3366 /* Cached positive dentry: will open in f_op->open */
3371 * Checking write permission is tricky, bacuse we don't know if we are
3372 * going to actually need it: O_CREAT opens should work as long as the
3373 * file exists. But checking existence breaks atomicity. The trick is
3374 * to check access and if not granted clear O_CREAT from the flags.
3376 * Another problem is returing the "right" error value (e.g. for an
3377 * O_EXCL open we want to return EEXIST not EROFS).
3379 if (unlikely(!got_write))
3380 open_flag &= ~O_TRUNC;
3381 idmap = mnt_idmap(nd->path.mnt);
3382 mnt_userns = mnt_idmap_owner(idmap);
3383 if (open_flag & O_CREAT) {
3384 if (open_flag & O_EXCL)
3385 open_flag &= ~O_TRUNC;
3386 mode = vfs_prepare_mode(mnt_userns, dir->d_inode, mode, mode, mode);
3387 if (likely(got_write))
3388 create_error = may_o_create(idmap, &nd->path,
3391 create_error = -EROFS;
3394 open_flag &= ~O_CREAT;
3395 if (dir_inode->i_op->atomic_open) {
3396 dentry = atomic_open(nd, dentry, file, open_flag, mode);
3397 if (unlikely(create_error) && dentry == ERR_PTR(-ENOENT))
3398 dentry = ERR_PTR(create_error);
3402 if (d_in_lookup(dentry)) {
3403 struct dentry *res = dir_inode->i_op->lookup(dir_inode, dentry,
3405 d_lookup_done(dentry);
3406 if (unlikely(res)) {
3408 error = PTR_ERR(res);
3416 /* Negative dentry, just create the file */
3417 if (!dentry->d_inode && (open_flag & O_CREAT)) {
3418 file->f_mode |= FMODE_CREATED;
3419 audit_inode_child(dir_inode, dentry, AUDIT_TYPE_CHILD_CREATE);
3420 if (!dir_inode->i_op->create) {
3425 error = dir_inode->i_op->create(idmap, dir_inode, dentry,
3426 mode, open_flag & O_EXCL);
3430 if (unlikely(create_error) && !dentry->d_inode) {
3431 error = create_error;
3438 return ERR_PTR(error);
3441 static const char *open_last_lookups(struct nameidata *nd,
3442 struct file *file, const struct open_flags *op)
3444 struct dentry *dir = nd->path.dentry;
3445 int open_flag = op->open_flag;
3446 bool got_write = false;
3447 struct dentry *dentry;
3450 nd->flags |= op->intent;
3452 if (nd->last_type != LAST_NORM) {
3455 return handle_dots(nd, nd->last_type);
3458 if (!(open_flag & O_CREAT)) {
3459 if (nd->last.name[nd->last.len])
3460 nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
3461 /* we _can_ be in RCU mode here */
3462 dentry = lookup_fast(nd);
3464 return ERR_CAST(dentry);
3468 BUG_ON(nd->flags & LOOKUP_RCU);
3470 /* create side of things */
3471 if (nd->flags & LOOKUP_RCU) {
3472 if (!try_to_unlazy(nd))
3473 return ERR_PTR(-ECHILD);
3475 audit_inode(nd->name, dir, AUDIT_INODE_PARENT);
3476 /* trailing slashes? */
3477 if (unlikely(nd->last.name[nd->last.len]))
3478 return ERR_PTR(-EISDIR);
3481 if (open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) {
3482 got_write = !mnt_want_write(nd->path.mnt);
3484 * do _not_ fail yet - we might not need that or fail with
3485 * a different error; let lookup_open() decide; we'll be
3486 * dropping this one anyway.
3489 if (open_flag & O_CREAT)
3490 inode_lock(dir->d_inode);
3492 inode_lock_shared(dir->d_inode);
3493 dentry = lookup_open(nd, file, op, got_write);
3494 if (!IS_ERR(dentry) && (file->f_mode & FMODE_CREATED))
3495 fsnotify_create(dir->d_inode, dentry);
3496 if (open_flag & O_CREAT)
3497 inode_unlock(dir->d_inode);
3499 inode_unlock_shared(dir->d_inode);
3502 mnt_drop_write(nd->path.mnt);
3505 return ERR_CAST(dentry);
3507 if (file->f_mode & (FMODE_OPENED | FMODE_CREATED)) {
3508 dput(nd->path.dentry);
3509 nd->path.dentry = dentry;
3516 res = step_into(nd, WALK_TRAILING, dentry);
3518 nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL);
3523 * Handle the last step of open()
3525 static int do_open(struct nameidata *nd,
3526 struct file *file, const struct open_flags *op)
3528 struct mnt_idmap *idmap;
3529 struct user_namespace *mnt_userns;
3530 int open_flag = op->open_flag;
3535 if (!(file->f_mode & (FMODE_OPENED | FMODE_CREATED))) {
3536 error = complete_walk(nd);
3540 if (!(file->f_mode & FMODE_CREATED))
3541 audit_inode(nd->name, nd->path.dentry, 0);
3542 idmap = mnt_idmap(nd->path.mnt);
3543 mnt_userns = mnt_idmap_owner(idmap);
3544 if (open_flag & O_CREAT) {
3545 if ((open_flag & O_EXCL) && !(file->f_mode & FMODE_CREATED))
3547 if (d_is_dir(nd->path.dentry))
3549 error = may_create_in_sticky(mnt_userns, nd,
3550 d_backing_inode(nd->path.dentry));
3551 if (unlikely(error))
3554 if ((nd->flags & LOOKUP_DIRECTORY) && !d_can_lookup(nd->path.dentry))
3557 do_truncate = false;
3558 acc_mode = op->acc_mode;
3559 if (file->f_mode & FMODE_CREATED) {
3560 /* Don't check for write permission, don't truncate */
3561 open_flag &= ~O_TRUNC;
3563 } else if (d_is_reg(nd->path.dentry) && open_flag & O_TRUNC) {
3564 error = mnt_want_write(nd->path.mnt);
3569 error = may_open(idmap, &nd->path, acc_mode, open_flag);
3570 if (!error && !(file->f_mode & FMODE_OPENED))
3571 error = vfs_open(&nd->path, file);
3573 error = ima_file_check(file, op->acc_mode);
3574 if (!error && do_truncate)
3575 error = handle_truncate(idmap, file);
3576 if (unlikely(error > 0)) {
3581 mnt_drop_write(nd->path.mnt);
3586 * vfs_tmpfile - create tmpfile
3587 * @idmap: idmap of the mount the inode was found from
3588 * @dentry: pointer to dentry of the base directory
3589 * @mode: mode of the new tmpfile
3592 * Create a temporary file.
3594 * If the inode has been found through an idmapped mount the idmap of
3595 * the vfsmount must be passed through @idmap. This function will then take
3596 * care to map the inode according to @idmap before checking permissions.
3597 * On non-idmapped mounts or if permission checking is to be performed on the
3598 * raw inode simply passs @nop_mnt_idmap.
3600 static int vfs_tmpfile(struct mnt_idmap *idmap,
3601 const struct path *parentpath,
3602 struct file *file, umode_t mode)
3604 struct user_namespace *mnt_userns = mnt_idmap_owner(idmap);
3605 struct dentry *child;
3606 struct inode *dir = d_inode(parentpath->dentry);
3607 struct inode *inode;
3609 int open_flag = file->f_flags;
3611 /* we want directory to be writable */
3612 error = inode_permission(idmap, dir, MAY_WRITE | MAY_EXEC);
3615 if (!dir->i_op->tmpfile)
3617 child = d_alloc(parentpath->dentry, &slash_name);
3618 if (unlikely(!child))
3620 file->f_path.mnt = parentpath->mnt;
3621 file->f_path.dentry = child;
3622 mode = vfs_prepare_mode(mnt_userns, dir, mode, mode, mode);
3623 error = dir->i_op->tmpfile(idmap, dir, file, mode);
3627 /* Don't check for other permissions, the inode was just created */
3628 error = may_open(idmap, &file->f_path, 0, file->f_flags);
3631 inode = file_inode(file);
3632 if (!(open_flag & O_EXCL)) {
3633 spin_lock(&inode->i_lock);
3634 inode->i_state |= I_LINKABLE;
3635 spin_unlock(&inode->i_lock);
3637 ima_post_create_tmpfile(idmap, inode);
3642 * vfs_tmpfile_open - open a tmpfile for kernel internal use
3643 * @idmap: idmap of the mount the inode was found from
3644 * @parentpath: path of the base directory
3645 * @mode: mode of the new tmpfile
3647 * @cred: credentials for open
3649 * Create and open a temporary file. The file is not accounted in nr_files,
3650 * hence this is only for kernel internal use, and must not be installed into
3651 * file tables or such.
3653 struct file *vfs_tmpfile_open(struct mnt_idmap *idmap,
3654 const struct path *parentpath,
3655 umode_t mode, int open_flag, const struct cred *cred)
3660 file = alloc_empty_file_noaccount(open_flag, cred);
3661 if (!IS_ERR(file)) {
3662 error = vfs_tmpfile(idmap, parentpath, file, mode);
3665 file = ERR_PTR(error);
3670 EXPORT_SYMBOL(vfs_tmpfile_open);
3672 static int do_tmpfile(struct nameidata *nd, unsigned flags,
3673 const struct open_flags *op,
3677 int error = path_lookupat(nd, flags | LOOKUP_DIRECTORY, &path);
3679 if (unlikely(error))
3681 error = mnt_want_write(path.mnt);
3682 if (unlikely(error))
3684 error = vfs_tmpfile(mnt_idmap(path.mnt), &path, file, op->mode);
3687 audit_inode(nd->name, file->f_path.dentry, 0);
3689 mnt_drop_write(path.mnt);
3695 static int do_o_path(struct nameidata *nd, unsigned flags, struct file *file)
3698 int error = path_lookupat(nd, flags, &path);
3700 audit_inode(nd->name, path.dentry, 0);
3701 error = vfs_open(&path, file);
3707 static struct file *path_openat(struct nameidata *nd,
3708 const struct open_flags *op, unsigned flags)
3713 file = alloc_empty_file(op->open_flag, current_cred());
3717 if (unlikely(file->f_flags & __O_TMPFILE)) {
3718 error = do_tmpfile(nd, flags, op, file);
3719 } else if (unlikely(file->f_flags & O_PATH)) {
3720 error = do_o_path(nd, flags, file);
3722 const char *s = path_init(nd, flags);
3723 while (!(error = link_path_walk(s, nd)) &&
3724 (s = open_last_lookups(nd, file, op)) != NULL)
3727 error = do_open(nd, file, op);
3730 if (likely(!error)) {
3731 if (likely(file->f_mode & FMODE_OPENED))
3737 if (error == -EOPENSTALE) {
3738 if (flags & LOOKUP_RCU)
3743 return ERR_PTR(error);
3746 struct file *do_filp_open(int dfd, struct filename *pathname,
3747 const struct open_flags *op)
3749 struct nameidata nd;
3750 int flags = op->lookup_flags;
3753 set_nameidata(&nd, dfd, pathname, NULL);
3754 filp = path_openat(&nd, op, flags | LOOKUP_RCU);
3755 if (unlikely(filp == ERR_PTR(-ECHILD)))
3756 filp = path_openat(&nd, op, flags);
3757 if (unlikely(filp == ERR_PTR(-ESTALE)))
3758 filp = path_openat(&nd, op, flags | LOOKUP_REVAL);
3759 restore_nameidata();
3763 struct file *do_file_open_root(const struct path *root,
3764 const char *name, const struct open_flags *op)
3766 struct nameidata nd;
3768 struct filename *filename;
3769 int flags = op->lookup_flags;
3771 if (d_is_symlink(root->dentry) && op->intent & LOOKUP_OPEN)
3772 return ERR_PTR(-ELOOP);
3774 filename = getname_kernel(name);
3775 if (IS_ERR(filename))
3776 return ERR_CAST(filename);
3778 set_nameidata(&nd, -1, filename, root);
3779 file = path_openat(&nd, op, flags | LOOKUP_RCU);
3780 if (unlikely(file == ERR_PTR(-ECHILD)))
3781 file = path_openat(&nd, op, flags);
3782 if (unlikely(file == ERR_PTR(-ESTALE)))
3783 file = path_openat(&nd, op, flags | LOOKUP_REVAL);
3784 restore_nameidata();
3789 static struct dentry *filename_create(int dfd, struct filename *name,
3790 struct path *path, unsigned int lookup_flags)
3792 struct dentry *dentry = ERR_PTR(-EEXIST);
3794 bool want_dir = lookup_flags & LOOKUP_DIRECTORY;
3795 unsigned int reval_flag = lookup_flags & LOOKUP_REVAL;
3796 unsigned int create_flags = LOOKUP_CREATE | LOOKUP_EXCL;
3801 error = filename_parentat(dfd, name, reval_flag, path, &last, &type);
3803 return ERR_PTR(error);
3806 * Yucky last component or no last component at all?
3807 * (foo/., foo/.., /////)
3809 if (unlikely(type != LAST_NORM))
3812 /* don't fail immediately if it's r/o, at least try to report other errors */
3813 err2 = mnt_want_write(path->mnt);
3815 * Do the final lookup. Suppress 'create' if there is a trailing
3816 * '/', and a directory wasn't requested.
3818 if (last.name[last.len] && !want_dir)
3820 inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
3821 dentry = __lookup_hash(&last, path->dentry, reval_flag | create_flags);
3826 if (d_is_positive(dentry))
3830 * Special case - lookup gave negative, but... we had foo/bar/
3831 * From the vfs_mknod() POV we just have a negative dentry -
3832 * all is fine. Let's be bastards - you had / on the end, you've
3833 * been asking for (non-existent) directory. -ENOENT for you.
3835 if (unlikely(!create_flags)) {
3839 if (unlikely(err2)) {
3846 dentry = ERR_PTR(error);
3848 inode_unlock(path->dentry->d_inode);
3850 mnt_drop_write(path->mnt);
3856 struct dentry *kern_path_create(int dfd, const char *pathname,
3857 struct path *path, unsigned int lookup_flags)
3859 struct filename *filename = getname_kernel(pathname);
3860 struct dentry *res = filename_create(dfd, filename, path, lookup_flags);
3865 EXPORT_SYMBOL(kern_path_create);
3867 void done_path_create(struct path *path, struct dentry *dentry)
3870 inode_unlock(path->dentry->d_inode);
3871 mnt_drop_write(path->mnt);
3874 EXPORT_SYMBOL(done_path_create);
3876 inline struct dentry *user_path_create(int dfd, const char __user *pathname,
3877 struct path *path, unsigned int lookup_flags)
3879 struct filename *filename = getname(pathname);
3880 struct dentry *res = filename_create(dfd, filename, path, lookup_flags);
3885 EXPORT_SYMBOL(user_path_create);
3888 * vfs_mknod - create device node or file
3889 * @idmap: idmap of the mount the inode was found from
3890 * @dir: inode of @dentry
3891 * @dentry: pointer to dentry of the base directory
3892 * @mode: mode of the new device node or file
3893 * @dev: device number of device to create
3895 * Create a device node or file.
3897 * If the inode has been found through an idmapped mount the idmap of
3898 * the vfsmount must be passed through @idmap. This function will then take
3899 * care to map the inode according to @idmap before checking permissions.
3900 * On non-idmapped mounts or if permission checking is to be performed on the
3901 * raw inode simply passs @nop_mnt_idmap.
3903 int vfs_mknod(struct mnt_idmap *idmap, struct inode *dir,
3904 struct dentry *dentry, umode_t mode, dev_t dev)
3906 struct user_namespace *mnt_userns = mnt_idmap_owner(idmap);
3907 bool is_whiteout = S_ISCHR(mode) && dev == WHITEOUT_DEV;
3908 int error = may_create(idmap, dir, dentry);
3913 if ((S_ISCHR(mode) || S_ISBLK(mode)) && !is_whiteout &&
3914 !capable(CAP_MKNOD))
3917 if (!dir->i_op->mknod)
3920 mode = vfs_prepare_mode(mnt_userns, dir, mode, mode, mode);
3921 error = devcgroup_inode_mknod(mode, dev);
3925 error = security_inode_mknod(dir, dentry, mode, dev);
3929 error = dir->i_op->mknod(idmap, dir, dentry, mode, dev);
3931 fsnotify_create(dir, dentry);
3934 EXPORT_SYMBOL(vfs_mknod);
3936 static int may_mknod(umode_t mode)
3938 switch (mode & S_IFMT) {
3944 case 0: /* zero mode translates to S_IFREG */
3953 static int do_mknodat(int dfd, struct filename *name, umode_t mode,
3956 struct mnt_idmap *idmap;
3957 struct dentry *dentry;
3960 unsigned int lookup_flags = 0;
3962 error = may_mknod(mode);
3966 dentry = filename_create(dfd, name, &path, lookup_flags);
3967 error = PTR_ERR(dentry);
3971 error = security_path_mknod(&path, dentry,
3972 mode_strip_umask(path.dentry->d_inode, mode), dev);
3976 idmap = mnt_idmap(path.mnt);
3977 switch (mode & S_IFMT) {
3978 case 0: case S_IFREG:
3979 error = vfs_create(idmap, path.dentry->d_inode,
3980 dentry, mode, true);
3982 ima_post_path_mknod(idmap, dentry);
3984 case S_IFCHR: case S_IFBLK:
3985 error = vfs_mknod(idmap, path.dentry->d_inode,
3986 dentry, mode, new_decode_dev(dev));
3988 case S_IFIFO: case S_IFSOCK:
3989 error = vfs_mknod(idmap, path.dentry->d_inode,
3994 done_path_create(&path, dentry);
3995 if (retry_estale(error, lookup_flags)) {
3996 lookup_flags |= LOOKUP_REVAL;
4004 SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, umode_t, mode,
4007 return do_mknodat(dfd, getname(filename), mode, dev);
4010 SYSCALL_DEFINE3(mknod, const char __user *, filename, umode_t, mode, unsigned, dev)
4012 return do_mknodat(AT_FDCWD, getname(filename), mode, dev);
4016 * vfs_mkdir - create directory
4017 * @idmap: idmap of the mount the inode was found from
4018 * @dir: inode of @dentry
4019 * @dentry: pointer to dentry of the base directory
4020 * @mode: mode of the new directory
4022 * Create a directory.
4024 * If the inode has been found through an idmapped mount the idmap of
4025 * the vfsmount must be passed through @idmap. This function will then take
4026 * care to map the inode according to @idmap before checking permissions.
4027 * On non-idmapped mounts or if permission checking is to be performed on the
4028 * raw inode simply passs @nop_mnt_idmap.
4030 int vfs_mkdir(struct mnt_idmap *idmap, struct inode *dir,
4031 struct dentry *dentry, umode_t mode)
4033 struct user_namespace *mnt_userns = mnt_idmap_owner(idmap);
4035 unsigned max_links = dir->i_sb->s_max_links;
4037 error = may_create(idmap, dir, dentry);
4041 if (!dir->i_op->mkdir)
4044 mode = vfs_prepare_mode(mnt_userns, dir, mode, S_IRWXUGO | S_ISVTX, 0);
4045 error = security_inode_mkdir(dir, dentry, mode);
4049 if (max_links && dir->i_nlink >= max_links)
4052 error = dir->i_op->mkdir(idmap, dir, dentry, mode);
4054 fsnotify_mkdir(dir, dentry);
4057 EXPORT_SYMBOL(vfs_mkdir);
4059 int do_mkdirat(int dfd, struct filename *name, umode_t mode)
4061 struct dentry *dentry;
4064 unsigned int lookup_flags = LOOKUP_DIRECTORY;
4067 dentry = filename_create(dfd, name, &path, lookup_flags);
4068 error = PTR_ERR(dentry);
4072 error = security_path_mkdir(&path, dentry,
4073 mode_strip_umask(path.dentry->d_inode, mode));
4075 error = vfs_mkdir(mnt_idmap(path.mnt), path.dentry->d_inode,
4078 done_path_create(&path, dentry);
4079 if (retry_estale(error, lookup_flags)) {
4080 lookup_flags |= LOOKUP_REVAL;
4088 SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, umode_t, mode)
4090 return do_mkdirat(dfd, getname(pathname), mode);
4093 SYSCALL_DEFINE2(mkdir, const char __user *, pathname, umode_t, mode)
4095 return do_mkdirat(AT_FDCWD, getname(pathname), mode);
4099 * vfs_rmdir - remove directory
4100 * @idmap: idmap of the mount the inode was found from
4101 * @dir: inode of @dentry
4102 * @dentry: pointer to dentry of the base directory
4104 * Remove a directory.
4106 * If the inode has been found through an idmapped mount the idmap of
4107 * the vfsmount must be passed through @idmap. This function will then take
4108 * care to map the inode according to @idmap before checking permissions.
4109 * On non-idmapped mounts or if permission checking is to be performed on the
4110 * raw inode simply passs @nop_mnt_idmap.
4112 int vfs_rmdir(struct mnt_idmap *idmap, struct inode *dir,
4113 struct dentry *dentry)
4115 int error = may_delete(idmap, dir, dentry, 1);
4120 if (!dir->i_op->rmdir)
4124 inode_lock(dentry->d_inode);
4127 if (is_local_mountpoint(dentry) ||
4128 (dentry->d_inode->i_flags & S_KERNEL_FILE))
4131 error = security_inode_rmdir(dir, dentry);
4135 error = dir->i_op->rmdir(dir, dentry);
4139 shrink_dcache_parent(dentry);
4140 dentry->d_inode->i_flags |= S_DEAD;
4142 detach_mounts(dentry);
4145 inode_unlock(dentry->d_inode);
4148 d_delete_notify(dir, dentry);
4151 EXPORT_SYMBOL(vfs_rmdir);
4153 int do_rmdir(int dfd, struct filename *name)
4156 struct dentry *dentry;
4160 unsigned int lookup_flags = 0;
4162 error = filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
4178 error = mnt_want_write(path.mnt);
4182 inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
4183 dentry = __lookup_hash(&last, path.dentry, lookup_flags);
4184 error = PTR_ERR(dentry);
4187 if (!dentry->d_inode) {
4191 error = security_path_rmdir(&path, dentry);
4194 error = vfs_rmdir(mnt_idmap(path.mnt), path.dentry->d_inode, dentry);
4198 inode_unlock(path.dentry->d_inode);
4199 mnt_drop_write(path.mnt);
4202 if (retry_estale(error, lookup_flags)) {
4203 lookup_flags |= LOOKUP_REVAL;
4211 SYSCALL_DEFINE1(rmdir, const char __user *, pathname)
4213 return do_rmdir(AT_FDCWD, getname(pathname));
4217 * vfs_unlink - unlink a filesystem object
4218 * @idmap: idmap of the mount the inode was found from
4219 * @dir: parent directory
4221 * @delegated_inode: returns victim inode, if the inode is delegated.
4223 * The caller must hold dir->i_mutex.
4225 * If vfs_unlink discovers a delegation, it will return -EWOULDBLOCK and
4226 * return a reference to the inode in delegated_inode. The caller
4227 * should then break the delegation on that inode and retry. Because
4228 * breaking a delegation may take a long time, the caller should drop
4229 * dir->i_mutex before doing so.
4231 * Alternatively, a caller may pass NULL for delegated_inode. This may
4232 * be appropriate for callers that expect the underlying filesystem not
4233 * to be NFS exported.
4235 * If the inode has been found through an idmapped mount the idmap of
4236 * the vfsmount must be passed through @idmap. This function will then take
4237 * care to map the inode according to @idmap before checking permissions.
4238 * On non-idmapped mounts or if permission checking is to be performed on the
4239 * raw inode simply passs @nop_mnt_idmap.
4241 int vfs_unlink(struct mnt_idmap *idmap, struct inode *dir,
4242 struct dentry *dentry, struct inode **delegated_inode)
4244 struct inode *target = dentry->d_inode;
4245 int error = may_delete(idmap, dir, dentry, 0);
4250 if (!dir->i_op->unlink)
4254 if (IS_SWAPFILE(target))
4256 else if (is_local_mountpoint(dentry))
4259 error = security_inode_unlink(dir, dentry);
4261 error = try_break_deleg(target, delegated_inode);
4264 error = dir->i_op->unlink(dir, dentry);
4267 detach_mounts(dentry);
4272 inode_unlock(target);
4274 /* We don't d_delete() NFS sillyrenamed files--they still exist. */
4275 if (!error && dentry->d_flags & DCACHE_NFSFS_RENAMED) {
4276 fsnotify_unlink(dir, dentry);
4277 } else if (!error) {
4278 fsnotify_link_count(target);
4279 d_delete_notify(dir, dentry);
4284 EXPORT_SYMBOL(vfs_unlink);
4287 * Make sure that the actual truncation of the file will occur outside its
4288 * directory's i_mutex. Truncate can take a long time if there is a lot of
4289 * writeout happening, and we don't want to prevent access to the directory
4290 * while waiting on the I/O.
4292 int do_unlinkat(int dfd, struct filename *name)
4295 struct dentry *dentry;
4299 struct inode *inode = NULL;
4300 struct inode *delegated_inode = NULL;
4301 unsigned int lookup_flags = 0;
4303 error = filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
4308 if (type != LAST_NORM)
4311 error = mnt_want_write(path.mnt);
4315 inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
4316 dentry = __lookup_hash(&last, path.dentry, lookup_flags);
4317 error = PTR_ERR(dentry);
4318 if (!IS_ERR(dentry)) {
4320 /* Why not before? Because we want correct error value */
4321 if (last.name[last.len])
4323 inode = dentry->d_inode;
4324 if (d_is_negative(dentry))
4327 error = security_path_unlink(&path, dentry);
4330 error = vfs_unlink(mnt_idmap(path.mnt), path.dentry->d_inode,
4331 dentry, &delegated_inode);
4335 inode_unlock(path.dentry->d_inode);
4337 iput(inode); /* truncate the inode here */
4339 if (delegated_inode) {
4340 error = break_deleg_wait(&delegated_inode);
4344 mnt_drop_write(path.mnt);
4347 if (retry_estale(error, lookup_flags)) {
4348 lookup_flags |= LOOKUP_REVAL;
4357 if (d_is_negative(dentry))
4359 else if (d_is_dir(dentry))
4366 SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag)
4368 if ((flag & ~AT_REMOVEDIR) != 0)
4371 if (flag & AT_REMOVEDIR)
4372 return do_rmdir(dfd, getname(pathname));
4373 return do_unlinkat(dfd, getname(pathname));
4376 SYSCALL_DEFINE1(unlink, const char __user *, pathname)
4378 return do_unlinkat(AT_FDCWD, getname(pathname));
4382 * vfs_symlink - create symlink
4383 * @idmap: idmap of the mount the inode was found from
4384 * @dir: inode of @dentry
4385 * @dentry: pointer to dentry of the base directory
4386 * @oldname: name of the file to link to
4390 * If the inode has been found through an idmapped mount the idmap of
4391 * the vfsmount must be passed through @idmap. This function will then take
4392 * care to map the inode according to @idmap before checking permissions.
4393 * On non-idmapped mounts or if permission checking is to be performed on the
4394 * raw inode simply passs @nop_mnt_idmap.
4396 int vfs_symlink(struct mnt_idmap *idmap, struct inode *dir,
4397 struct dentry *dentry, const char *oldname)
4401 error = may_create(idmap, dir, dentry);
4405 if (!dir->i_op->symlink)
4408 error = security_inode_symlink(dir, dentry, oldname);
4412 error = dir->i_op->symlink(idmap, dir, dentry, oldname);
4414 fsnotify_create(dir, dentry);
4417 EXPORT_SYMBOL(vfs_symlink);
4419 int do_symlinkat(struct filename *from, int newdfd, struct filename *to)
4422 struct dentry *dentry;
4424 unsigned int lookup_flags = 0;
4427 error = PTR_ERR(from);
4431 dentry = filename_create(newdfd, to, &path, lookup_flags);
4432 error = PTR_ERR(dentry);
4436 error = security_path_symlink(&path, dentry, from->name);
4438 error = vfs_symlink(mnt_idmap(path.mnt), path.dentry->d_inode,
4439 dentry, from->name);
4440 done_path_create(&path, dentry);
4441 if (retry_estale(error, lookup_flags)) {
4442 lookup_flags |= LOOKUP_REVAL;
4451 SYSCALL_DEFINE3(symlinkat, const char __user *, oldname,
4452 int, newdfd, const char __user *, newname)
4454 return do_symlinkat(getname(oldname), newdfd, getname(newname));
4457 SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname)
4459 return do_symlinkat(getname(oldname), AT_FDCWD, getname(newname));
4463 * vfs_link - create a new link
4464 * @old_dentry: object to be linked
4465 * @idmap: idmap of the mount
4467 * @new_dentry: where to create the new link
4468 * @delegated_inode: returns inode needing a delegation break
4470 * The caller must hold dir->i_mutex
4472 * If vfs_link discovers a delegation on the to-be-linked file in need
4473 * of breaking, it will return -EWOULDBLOCK and return a reference to the
4474 * inode in delegated_inode. The caller should then break the delegation
4475 * and retry. Because breaking a delegation may take a long time, the
4476 * caller should drop the i_mutex before doing so.
4478 * Alternatively, a caller may pass NULL for delegated_inode. This may
4479 * be appropriate for callers that expect the underlying filesystem not
4480 * to be NFS exported.
4482 * If the inode has been found through an idmapped mount the idmap of
4483 * the vfsmount must be passed through @idmap. This function will then take
4484 * care to map the inode according to @idmap before checking permissions.
4485 * On non-idmapped mounts or if permission checking is to be performed on the
4486 * raw inode simply passs @nop_mnt_idmap.
4488 int vfs_link(struct dentry *old_dentry, struct mnt_idmap *idmap,
4489 struct inode *dir, struct dentry *new_dentry,
4490 struct inode **delegated_inode)
4492 struct inode *inode = old_dentry->d_inode;
4493 unsigned max_links = dir->i_sb->s_max_links;
4499 error = may_create(idmap, dir, new_dentry);
4503 if (dir->i_sb != inode->i_sb)
4507 * A link to an append-only or immutable file cannot be created.
4509 if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
4512 * Updating the link count will likely cause i_uid and i_gid to
4513 * be writen back improperly if their true value is unknown to
4516 if (HAS_UNMAPPED_ID(idmap, inode))
4518 if (!dir->i_op->link)
4520 if (S_ISDIR(inode->i_mode))
4523 error = security_inode_link(old_dentry, dir, new_dentry);
4528 /* Make sure we don't allow creating hardlink to an unlinked file */
4529 if (inode->i_nlink == 0 && !(inode->i_state & I_LINKABLE))
4531 else if (max_links && inode->i_nlink >= max_links)
4534 error = try_break_deleg(inode, delegated_inode);
4536 error = dir->i_op->link(old_dentry, dir, new_dentry);
4539 if (!error && (inode->i_state & I_LINKABLE)) {
4540 spin_lock(&inode->i_lock);
4541 inode->i_state &= ~I_LINKABLE;
4542 spin_unlock(&inode->i_lock);
4544 inode_unlock(inode);
4546 fsnotify_link(dir, inode, new_dentry);
4549 EXPORT_SYMBOL(vfs_link);
4552 * Hardlinks are often used in delicate situations. We avoid
4553 * security-related surprises by not following symlinks on the
4556 * We don't follow them on the oldname either to be compatible
4557 * with linux 2.0, and to avoid hard-linking to directories
4558 * and other special files. --ADM
4560 int do_linkat(int olddfd, struct filename *old, int newdfd,
4561 struct filename *new, int flags)
4563 struct mnt_idmap *idmap;
4564 struct dentry *new_dentry;
4565 struct path old_path, new_path;
4566 struct inode *delegated_inode = NULL;
4570 if ((flags & ~(AT_SYMLINK_FOLLOW | AT_EMPTY_PATH)) != 0) {
4575 * To use null names we require CAP_DAC_READ_SEARCH
4576 * This ensures that not everyone will be able to create
4577 * handlink using the passed filedescriptor.
4579 if (flags & AT_EMPTY_PATH && !capable(CAP_DAC_READ_SEARCH)) {
4584 if (flags & AT_SYMLINK_FOLLOW)
4585 how |= LOOKUP_FOLLOW;
4587 error = filename_lookup(olddfd, old, how, &old_path, NULL);
4591 new_dentry = filename_create(newdfd, new, &new_path,
4592 (how & LOOKUP_REVAL));
4593 error = PTR_ERR(new_dentry);
4594 if (IS_ERR(new_dentry))
4598 if (old_path.mnt != new_path.mnt)
4600 idmap = mnt_idmap(new_path.mnt);
4601 error = may_linkat(idmap, &old_path);
4602 if (unlikely(error))
4604 error = security_path_link(old_path.dentry, &new_path, new_dentry);
4607 error = vfs_link(old_path.dentry, idmap, new_path.dentry->d_inode,
4608 new_dentry, &delegated_inode);
4610 done_path_create(&new_path, new_dentry);
4611 if (delegated_inode) {
4612 error = break_deleg_wait(&delegated_inode);
4614 path_put(&old_path);
4618 if (retry_estale(error, how)) {
4619 path_put(&old_path);
4620 how |= LOOKUP_REVAL;
4624 path_put(&old_path);
4632 SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname,
4633 int, newdfd, const char __user *, newname, int, flags)
4635 return do_linkat(olddfd, getname_uflags(oldname, flags),
4636 newdfd, getname(newname), flags);
4639 SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname)
4641 return do_linkat(AT_FDCWD, getname(oldname), AT_FDCWD, getname(newname), 0);
4645 * vfs_rename - rename a filesystem object
4646 * @rd: pointer to &struct renamedata info
4648 * The caller must hold multiple mutexes--see lock_rename()).
4650 * If vfs_rename discovers a delegation in need of breaking at either
4651 * the source or destination, it will return -EWOULDBLOCK and return a
4652 * reference to the inode in delegated_inode. The caller should then
4653 * break the delegation and retry. Because breaking a delegation may
4654 * take a long time, the caller should drop all locks before doing
4657 * Alternatively, a caller may pass NULL for delegated_inode. This may
4658 * be appropriate for callers that expect the underlying filesystem not
4659 * to be NFS exported.
4661 * The worst of all namespace operations - renaming directory. "Perverted"
4662 * doesn't even start to describe it. Somebody in UCB had a heck of a trip...
4665 * a) we can get into loop creation.
4666 * b) race potential - two innocent renames can create a loop together.
4667 * That's where 4.4 screws up. Current fix: serialization on
4668 * sb->s_vfs_rename_mutex. We might be more accurate, but that's another
4670 * c) we have to lock _four_ objects - parents and victim (if it exists),
4671 * and source (if it is not a directory).
4672 * And that - after we got ->i_mutex on parents (until then we don't know
4673 * whether the target exists). Solution: try to be smart with locking
4674 * order for inodes. We rely on the fact that tree topology may change
4675 * only under ->s_vfs_rename_mutex _and_ that parent of the object we
4676 * move will be locked. Thus we can rank directories by the tree
4677 * (ancestors first) and rank all non-directories after them.
4678 * That works since everybody except rename does "lock parent, lookup,
4679 * lock child" and rename is under ->s_vfs_rename_mutex.
4680 * HOWEVER, it relies on the assumption that any object with ->lookup()
4681 * has no more than 1 dentry. If "hybrid" objects will ever appear,
4682 * we'd better make sure that there's no link(2) for them.
4683 * d) conversion from fhandle to dentry may come in the wrong moment - when
4684 * we are removing the target. Solution: we will have to grab ->i_mutex
4685 * in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on
4686 * ->i_mutex on parents, which works but leads to some truly excessive
4689 int vfs_rename(struct renamedata *rd)
4692 struct inode *old_dir = rd->old_dir, *new_dir = rd->new_dir;
4693 struct dentry *old_dentry = rd->old_dentry;
4694 struct dentry *new_dentry = rd->new_dentry;
4695 struct inode **delegated_inode = rd->delegated_inode;
4696 unsigned int flags = rd->flags;
4697 bool is_dir = d_is_dir(old_dentry);
4698 struct inode *source = old_dentry->d_inode;
4699 struct inode *target = new_dentry->d_inode;
4700 bool new_is_dir = false;
4701 unsigned max_links = new_dir->i_sb->s_max_links;
4702 struct name_snapshot old_name;
4704 if (source == target)
4707 error = may_delete(rd->old_mnt_idmap, old_dir, old_dentry, is_dir);
4712 error = may_create(rd->new_mnt_idmap, new_dir, new_dentry);
4714 new_is_dir = d_is_dir(new_dentry);
4716 if (!(flags & RENAME_EXCHANGE))
4717 error = may_delete(rd->new_mnt_idmap, new_dir,
4718 new_dentry, is_dir);
4720 error = may_delete(rd->new_mnt_idmap, new_dir,
4721 new_dentry, new_is_dir);
4726 if (!old_dir->i_op->rename)
4730 * If we are going to change the parent - check write permissions,
4731 * we'll need to flip '..'.
4733 if (new_dir != old_dir) {
4735 error = inode_permission(rd->old_mnt_idmap, source,
4740 if ((flags & RENAME_EXCHANGE) && new_is_dir) {
4741 error = inode_permission(rd->new_mnt_idmap, target,
4748 error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,
4753 take_dentry_name_snapshot(&old_name, old_dentry);
4755 if (!is_dir || (flags & RENAME_EXCHANGE))
4756 lock_two_nondirectories(source, target);
4761 if (IS_SWAPFILE(source) || (target && IS_SWAPFILE(target)))
4765 if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
4768 if (max_links && new_dir != old_dir) {
4770 if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)
4772 if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&
4773 old_dir->i_nlink >= max_links)
4777 error = try_break_deleg(source, delegated_inode);
4781 if (target && !new_is_dir) {
4782 error = try_break_deleg(target, delegated_inode);
4786 error = old_dir->i_op->rename(rd->new_mnt_idmap, old_dir, old_dentry,
4787 new_dir, new_dentry, flags);
4791 if (!(flags & RENAME_EXCHANGE) && target) {
4793 shrink_dcache_parent(new_dentry);
4794 target->i_flags |= S_DEAD;
4796 dont_mount(new_dentry);
4797 detach_mounts(new_dentry);
4799 if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {
4800 if (!(flags & RENAME_EXCHANGE))
4801 d_move(old_dentry, new_dentry);
4803 d_exchange(old_dentry, new_dentry);
4806 if (!is_dir || (flags & RENAME_EXCHANGE))
4807 unlock_two_nondirectories(source, target);
4809 inode_unlock(target);
4812 fsnotify_move(old_dir, new_dir, &old_name.name, is_dir,
4813 !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);
4814 if (flags & RENAME_EXCHANGE) {
4815 fsnotify_move(new_dir, old_dir, &old_dentry->d_name,
4816 new_is_dir, NULL, new_dentry);
4819 release_dentry_name_snapshot(&old_name);
4823 EXPORT_SYMBOL(vfs_rename);
4825 int do_renameat2(int olddfd, struct filename *from, int newdfd,
4826 struct filename *to, unsigned int flags)
4828 struct renamedata rd;
4829 struct dentry *old_dentry, *new_dentry;
4830 struct dentry *trap;
4831 struct path old_path, new_path;
4832 struct qstr old_last, new_last;
4833 int old_type, new_type;
4834 struct inode *delegated_inode = NULL;
4835 unsigned int lookup_flags = 0, target_flags = LOOKUP_RENAME_TARGET;
4836 bool should_retry = false;
4837 int error = -EINVAL;
4839 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
4842 if ((flags & (RENAME_NOREPLACE | RENAME_WHITEOUT)) &&
4843 (flags & RENAME_EXCHANGE))
4846 if (flags & RENAME_EXCHANGE)
4850 error = filename_parentat(olddfd, from, lookup_flags, &old_path,
4851 &old_last, &old_type);
4855 error = filename_parentat(newdfd, to, lookup_flags, &new_path, &new_last,
4861 if (old_path.mnt != new_path.mnt)
4865 if (old_type != LAST_NORM)
4868 if (flags & RENAME_NOREPLACE)
4870 if (new_type != LAST_NORM)
4873 error = mnt_want_write(old_path.mnt);
4878 trap = lock_rename(new_path.dentry, old_path.dentry);
4880 old_dentry = __lookup_hash(&old_last, old_path.dentry, lookup_flags);
4881 error = PTR_ERR(old_dentry);
4882 if (IS_ERR(old_dentry))
4884 /* source must exist */
4886 if (d_is_negative(old_dentry))
4888 new_dentry = __lookup_hash(&new_last, new_path.dentry, lookup_flags | target_flags);
4889 error = PTR_ERR(new_dentry);
4890 if (IS_ERR(new_dentry))
4893 if ((flags & RENAME_NOREPLACE) && d_is_positive(new_dentry))
4895 if (flags & RENAME_EXCHANGE) {
4897 if (d_is_negative(new_dentry))
4900 if (!d_is_dir(new_dentry)) {
4902 if (new_last.name[new_last.len])
4906 /* unless the source is a directory trailing slashes give -ENOTDIR */
4907 if (!d_is_dir(old_dentry)) {
4909 if (old_last.name[old_last.len])
4911 if (!(flags & RENAME_EXCHANGE) && new_last.name[new_last.len])
4914 /* source should not be ancestor of target */
4916 if (old_dentry == trap)
4918 /* target should not be an ancestor of source */
4919 if (!(flags & RENAME_EXCHANGE))
4921 if (new_dentry == trap)
4924 error = security_path_rename(&old_path, old_dentry,
4925 &new_path, new_dentry, flags);
4929 rd.old_dir = old_path.dentry->d_inode;
4930 rd.old_dentry = old_dentry;
4931 rd.old_mnt_idmap = mnt_idmap(old_path.mnt);
4932 rd.new_dir = new_path.dentry->d_inode;
4933 rd.new_dentry = new_dentry;
4934 rd.new_mnt_idmap = mnt_idmap(new_path.mnt);
4935 rd.delegated_inode = &delegated_inode;
4937 error = vfs_rename(&rd);
4943 unlock_rename(new_path.dentry, old_path.dentry);
4944 if (delegated_inode) {
4945 error = break_deleg_wait(&delegated_inode);
4949 mnt_drop_write(old_path.mnt);
4951 if (retry_estale(error, lookup_flags))
4952 should_retry = true;
4953 path_put(&new_path);
4955 path_put(&old_path);
4957 should_retry = false;
4958 lookup_flags |= LOOKUP_REVAL;
4967 SYSCALL_DEFINE5(renameat2, int, olddfd, const char __user *, oldname,
4968 int, newdfd, const char __user *, newname, unsigned int, flags)
4970 return do_renameat2(olddfd, getname(oldname), newdfd, getname(newname),
4974 SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname,
4975 int, newdfd, const char __user *, newname)
4977 return do_renameat2(olddfd, getname(oldname), newdfd, getname(newname),
4981 SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname)
4983 return do_renameat2(AT_FDCWD, getname(oldname), AT_FDCWD,
4984 getname(newname), 0);
4987 int readlink_copy(char __user *buffer, int buflen, const char *link)
4989 int len = PTR_ERR(link);
4994 if (len > (unsigned) buflen)
4996 if (copy_to_user(buffer, link, len))
5003 * vfs_readlink - copy symlink body into userspace buffer
5004 * @dentry: dentry on which to get symbolic link
5005 * @buffer: user memory pointer
5006 * @buflen: size of buffer
5008 * Does not touch atime. That's up to the caller if necessary
5010 * Does not call security hook.
5012 int vfs_readlink(struct dentry *dentry, char __user *buffer, int buflen)
5014 struct inode *inode = d_inode(dentry);
5015 DEFINE_DELAYED_CALL(done);
5019 if (unlikely(!(inode->i_opflags & IOP_DEFAULT_READLINK))) {
5020 if (unlikely(inode->i_op->readlink))
5021 return inode->i_op->readlink(dentry, buffer, buflen);
5023 if (!d_is_symlink(dentry))
5026 spin_lock(&inode->i_lock);
5027 inode->i_opflags |= IOP_DEFAULT_READLINK;
5028 spin_unlock(&inode->i_lock);
5031 link = READ_ONCE(inode->i_link);
5033 link = inode->i_op->get_link(dentry, inode, &done);
5035 return PTR_ERR(link);
5037 res = readlink_copy(buffer, buflen, link);
5038 do_delayed_call(&done);
5041 EXPORT_SYMBOL(vfs_readlink);
5044 * vfs_get_link - get symlink body
5045 * @dentry: dentry on which to get symbolic link
5046 * @done: caller needs to free returned data with this
5048 * Calls security hook and i_op->get_link() on the supplied inode.
5050 * It does not touch atime. That's up to the caller if necessary.
5052 * Does not work on "special" symlinks like /proc/$$/fd/N
5054 const char *vfs_get_link(struct dentry *dentry, struct delayed_call *done)
5056 const char *res = ERR_PTR(-EINVAL);
5057 struct inode *inode = d_inode(dentry);
5059 if (d_is_symlink(dentry)) {
5060 res = ERR_PTR(security_inode_readlink(dentry));
5062 res = inode->i_op->get_link(dentry, inode, done);
5066 EXPORT_SYMBOL(vfs_get_link);
5068 /* get the link contents into pagecache */
5069 const char *page_get_link(struct dentry *dentry, struct inode *inode,
5070 struct delayed_call *callback)
5074 struct address_space *mapping = inode->i_mapping;
5077 page = find_get_page(mapping, 0);
5079 return ERR_PTR(-ECHILD);
5080 if (!PageUptodate(page)) {
5082 return ERR_PTR(-ECHILD);
5085 page = read_mapping_page(mapping, 0, NULL);
5089 set_delayed_call(callback, page_put_link, page);
5090 BUG_ON(mapping_gfp_mask(mapping) & __GFP_HIGHMEM);
5091 kaddr = page_address(page);
5092 nd_terminate_link(kaddr, inode->i_size, PAGE_SIZE - 1);
5096 EXPORT_SYMBOL(page_get_link);
5098 void page_put_link(void *arg)
5102 EXPORT_SYMBOL(page_put_link);
5104 int page_readlink(struct dentry *dentry, char __user *buffer, int buflen)
5106 DEFINE_DELAYED_CALL(done);
5107 int res = readlink_copy(buffer, buflen,
5108 page_get_link(dentry, d_inode(dentry),
5110 do_delayed_call(&done);
5113 EXPORT_SYMBOL(page_readlink);
5115 int page_symlink(struct inode *inode, const char *symname, int len)
5117 struct address_space *mapping = inode->i_mapping;
5118 const struct address_space_operations *aops = mapping->a_ops;
5119 bool nofs = !mapping_gfp_constraint(mapping, __GFP_FS);
5121 void *fsdata = NULL;
5127 flags = memalloc_nofs_save();
5128 err = aops->write_begin(NULL, mapping, 0, len-1, &page, &fsdata);
5130 memalloc_nofs_restore(flags);
5134 memcpy(page_address(page), symname, len-1);
5136 err = aops->write_end(NULL, mapping, 0, len-1, len-1,
5143 mark_inode_dirty(inode);
5148 EXPORT_SYMBOL(page_symlink);
5150 const struct inode_operations page_symlink_inode_operations = {
5151 .get_link = page_get_link,
5153 EXPORT_SYMBOL(page_symlink_inode_operations);