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/slab.h>
21 #include <linux/wordpart.h>
23 #include <linux/filelock.h>
24 #include <linux/namei.h>
25 #include <linux/pagemap.h>
26 #include <linux/sched/mm.h>
27 #include <linux/fsnotify.h>
28 #include <linux/personality.h>
29 #include <linux/security.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))
128 static inline void initname(struct filename *name, const char __user *uptr)
132 atomic_set(&name->refcnt, 1);
136 getname_flags(const char __user *filename, int flags)
138 struct filename *result;
142 result = audit_reusename(filename);
146 result = __getname();
147 if (unlikely(!result))
148 return ERR_PTR(-ENOMEM);
151 * First, try to embed the struct filename inside the names_cache
154 kname = (char *)result->iname;
155 result->name = kname;
157 len = strncpy_from_user(kname, filename, EMBEDDED_NAME_MAX);
159 * Handle both empty path and copy failure in one go.
161 if (unlikely(len <= 0)) {
162 if (unlikely(len < 0)) {
167 /* The empty path is special. */
168 if (!(flags & LOOKUP_EMPTY)) {
170 return ERR_PTR(-ENOENT);
175 * Uh-oh. We have a name that's approaching PATH_MAX. Allocate a
176 * separate struct filename so we can dedicate the entire
177 * names_cache allocation for the pathname, and re-do the copy from
180 if (unlikely(len == EMBEDDED_NAME_MAX)) {
181 const size_t size = offsetof(struct filename, iname[1]);
182 kname = (char *)result;
185 * size is chosen that way we to guarantee that
186 * result->iname[0] is within the same object and that
187 * kname can't be equal to result->iname, no matter what.
189 result = kzalloc(size, GFP_KERNEL);
190 if (unlikely(!result)) {
192 return ERR_PTR(-ENOMEM);
194 result->name = kname;
195 len = strncpy_from_user(kname, filename, PATH_MAX);
196 if (unlikely(len < 0)) {
201 /* The empty path is special. */
202 if (unlikely(!len) && !(flags & LOOKUP_EMPTY)) {
205 return ERR_PTR(-ENOENT);
207 if (unlikely(len == PATH_MAX)) {
210 return ERR_PTR(-ENAMETOOLONG);
213 initname(result, filename);
214 audit_getname(result);
218 struct filename *getname_uflags(const char __user *filename, int uflags)
220 int flags = (uflags & AT_EMPTY_PATH) ? LOOKUP_EMPTY : 0;
222 return getname_flags(filename, flags);
225 struct filename *__getname_maybe_null(const char __user *pathname)
227 struct filename *name;
230 /* try to save on allocations; loss on um, though */
231 if (get_user(c, pathname))
232 return ERR_PTR(-EFAULT);
236 name = getname_flags(pathname, LOOKUP_EMPTY);
237 if (!IS_ERR(name) && !(name->name[0])) {
244 struct filename *getname_kernel(const char * filename)
246 struct filename *result;
247 int len = strlen(filename) + 1;
249 result = __getname();
250 if (unlikely(!result))
251 return ERR_PTR(-ENOMEM);
253 if (len <= EMBEDDED_NAME_MAX) {
254 result->name = (char *)result->iname;
255 } else if (len <= PATH_MAX) {
256 const size_t size = offsetof(struct filename, iname[1]);
257 struct filename *tmp;
259 tmp = kmalloc(size, GFP_KERNEL);
260 if (unlikely(!tmp)) {
262 return ERR_PTR(-ENOMEM);
264 tmp->name = (char *)result;
268 return ERR_PTR(-ENAMETOOLONG);
270 memcpy((char *)result->name, filename, len);
271 initname(result, NULL);
272 audit_getname(result);
275 EXPORT_SYMBOL(getname_kernel);
277 void putname(struct filename *name)
281 if (IS_ERR_OR_NULL(name))
284 refcnt = atomic_read(&name->refcnt);
286 if (WARN_ON_ONCE(!refcnt))
289 if (!atomic_dec_and_test(&name->refcnt))
293 if (name->name != name->iname) {
294 __putname(name->name);
299 EXPORT_SYMBOL(putname);
302 * check_acl - perform ACL permission checking
303 * @idmap: idmap of the mount the inode was found from
304 * @inode: inode to check permissions on
305 * @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
307 * This function performs the ACL permission checking. Since this function
308 * retrieve POSIX acls it needs to know whether it is called from a blocking or
309 * non-blocking context and thus cares about the MAY_NOT_BLOCK bit.
311 * If the inode has been found through an idmapped mount the idmap of
312 * the vfsmount must be passed through @idmap. This function will then take
313 * care to map the inode according to @idmap before checking permissions.
314 * On non-idmapped mounts or if permission checking is to be performed on the
315 * raw inode simply pass @nop_mnt_idmap.
317 static int check_acl(struct mnt_idmap *idmap,
318 struct inode *inode, int mask)
320 #ifdef CONFIG_FS_POSIX_ACL
321 struct posix_acl *acl;
323 if (mask & MAY_NOT_BLOCK) {
324 acl = get_cached_acl_rcu(inode, ACL_TYPE_ACCESS);
327 /* no ->get_inode_acl() calls in RCU mode... */
328 if (is_uncached_acl(acl))
330 return posix_acl_permission(idmap, inode, acl, mask);
333 acl = get_inode_acl(inode, ACL_TYPE_ACCESS);
337 int error = posix_acl_permission(idmap, inode, acl, mask);
338 posix_acl_release(acl);
347 * Very quick optimistic "we know we have no ACL's" check.
349 * Note that this is purely for ACL_TYPE_ACCESS, and purely
350 * for the "we have cached that there are no ACLs" case.
352 * If this returns true, we know there are no ACLs. But if
353 * it returns false, we might still not have ACLs (it could
354 * be the is_uncached_acl() case).
356 static inline bool no_acl_inode(struct inode *inode)
358 #ifdef CONFIG_FS_POSIX_ACL
359 return likely(!READ_ONCE(inode->i_acl));
366 * acl_permission_check - perform basic UNIX permission checking
367 * @idmap: idmap of the mount the inode was found from
368 * @inode: inode to check permissions on
369 * @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
371 * This function performs the basic UNIX permission checking. Since this
372 * function may retrieve POSIX acls it needs to know whether it is called from a
373 * blocking or non-blocking context and thus cares about the MAY_NOT_BLOCK bit.
375 * If the inode has been found through an idmapped mount the idmap of
376 * the vfsmount must be passed through @idmap. This function will then take
377 * care to map the inode according to @idmap before checking permissions.
378 * On non-idmapped mounts or if permission checking is to be performed on the
379 * raw inode simply pass @nop_mnt_idmap.
381 static int acl_permission_check(struct mnt_idmap *idmap,
382 struct inode *inode, int mask)
384 unsigned int mode = inode->i_mode;
388 * Common cheap case: everybody has the requested
389 * rights, and there are no ACLs to check. No need
390 * to do any owner/group checks in that case.
392 * - 'mask&7' is the requested permission bit set
393 * - multiplying by 0111 spreads them out to all of ugo
394 * - '& ~mode' looks for missing inode permission bits
395 * - the '!' is for "no missing permissions"
397 * After that, we just need to check that there are no
398 * ACL's on the inode - do the 'IS_POSIXACL()' check last
399 * because it will dereference the ->i_sb pointer and we
400 * want to avoid that if at all possible.
402 if (!((mask & 7) * 0111 & ~mode)) {
403 if (no_acl_inode(inode))
405 if (!IS_POSIXACL(inode))
409 /* Are we the owner? If so, ACL's don't matter */
410 vfsuid = i_uid_into_vfsuid(idmap, inode);
411 if (likely(vfsuid_eq_kuid(vfsuid, current_fsuid()))) {
414 return (mask & ~mode) ? -EACCES : 0;
417 /* Do we have ACL's? */
418 if (IS_POSIXACL(inode) && (mode & S_IRWXG)) {
419 int error = check_acl(idmap, inode, mask);
420 if (error != -EAGAIN)
424 /* Only RWX matters for group/other mode bits */
428 * Are the group permissions different from
429 * the other permissions in the bits we care
430 * about? Need to check group ownership if so.
432 if (mask & (mode ^ (mode >> 3))) {
433 vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
434 if (vfsgid_in_group_p(vfsgid))
438 /* Bits in 'mode' clear that we require? */
439 return (mask & ~mode) ? -EACCES : 0;
443 * generic_permission - check for access rights on a Posix-like filesystem
444 * @idmap: idmap of the mount the inode was found from
445 * @inode: inode to check access rights for
446 * @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC,
447 * %MAY_NOT_BLOCK ...)
449 * Used to check for read/write/execute permissions on a file.
450 * We use "fsuid" for this, letting us set arbitrary permissions
451 * for filesystem access without changing the "normal" uids which
452 * are used for other things.
454 * generic_permission is rcu-walk aware. It returns -ECHILD in case an rcu-walk
455 * request cannot be satisfied (eg. requires blocking or too much complexity).
456 * It would then be called again in ref-walk mode.
458 * If the inode has been found through an idmapped mount the idmap of
459 * the vfsmount must be passed through @idmap. This function will then take
460 * care to map the inode according to @idmap before checking permissions.
461 * On non-idmapped mounts or if permission checking is to be performed on the
462 * raw inode simply pass @nop_mnt_idmap.
464 int generic_permission(struct mnt_idmap *idmap, struct inode *inode,
470 * Do the basic permission checks.
472 ret = acl_permission_check(idmap, inode, mask);
476 if (S_ISDIR(inode->i_mode)) {
477 /* DACs are overridable for directories */
478 if (!(mask & MAY_WRITE))
479 if (capable_wrt_inode_uidgid(idmap, inode,
480 CAP_DAC_READ_SEARCH))
482 if (capable_wrt_inode_uidgid(idmap, inode,
489 * Searching includes executable on directories, else just read.
491 mask &= MAY_READ | MAY_WRITE | MAY_EXEC;
492 if (mask == MAY_READ)
493 if (capable_wrt_inode_uidgid(idmap, inode,
494 CAP_DAC_READ_SEARCH))
497 * Read/write DACs are always overridable.
498 * Executable DACs are overridable when there is
499 * at least one exec bit set.
501 if (!(mask & MAY_EXEC) || (inode->i_mode & S_IXUGO))
502 if (capable_wrt_inode_uidgid(idmap, inode,
508 EXPORT_SYMBOL(generic_permission);
511 * do_inode_permission - UNIX permission checking
512 * @idmap: idmap of the mount the inode was found from
513 * @inode: inode to check permissions on
514 * @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
516 * We _really_ want to just do "generic_permission()" without
517 * even looking at the inode->i_op values. So we keep a cache
518 * flag in inode->i_opflags, that says "this has not special
519 * permission function, use the fast case".
521 static inline int do_inode_permission(struct mnt_idmap *idmap,
522 struct inode *inode, int mask)
524 if (unlikely(!(inode->i_opflags & IOP_FASTPERM))) {
525 if (likely(inode->i_op->permission))
526 return inode->i_op->permission(idmap, inode, mask);
528 /* This gets set once for the inode lifetime */
529 spin_lock(&inode->i_lock);
530 inode->i_opflags |= IOP_FASTPERM;
531 spin_unlock(&inode->i_lock);
533 return generic_permission(idmap, inode, mask);
537 * sb_permission - Check superblock-level permissions
538 * @sb: Superblock of inode to check permission on
539 * @inode: Inode to check permission on
540 * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
542 * Separate out file-system wide checks from inode-specific permission checks.
544 static int sb_permission(struct super_block *sb, struct inode *inode, int mask)
546 if (unlikely(mask & MAY_WRITE)) {
547 umode_t mode = inode->i_mode;
549 /* Nobody gets write access to a read-only fs. */
550 if (sb_rdonly(sb) && (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode)))
557 * inode_permission - Check for access rights to a given inode
558 * @idmap: idmap of the mount the inode was found from
559 * @inode: Inode to check permission on
560 * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
562 * Check for read/write/execute permissions on an inode. We use fs[ug]id for
563 * this, letting us set arbitrary permissions for filesystem access without
564 * changing the "normal" UIDs which are used for other things.
566 * When checking for MAY_APPEND, MAY_WRITE must also be set in @mask.
568 int inode_permission(struct mnt_idmap *idmap,
569 struct inode *inode, int mask)
573 retval = sb_permission(inode->i_sb, inode, mask);
574 if (unlikely(retval))
577 if (unlikely(mask & MAY_WRITE)) {
579 * Nobody gets write access to an immutable file.
581 if (unlikely(IS_IMMUTABLE(inode)))
585 * Updating mtime will likely cause i_uid and i_gid to be
586 * written back improperly if their true value is unknown
589 if (unlikely(HAS_UNMAPPED_ID(idmap, inode)))
593 retval = do_inode_permission(idmap, inode, mask);
594 if (unlikely(retval))
597 retval = devcgroup_inode_permission(inode, mask);
598 if (unlikely(retval))
601 return security_inode_permission(inode, mask);
603 EXPORT_SYMBOL(inode_permission);
606 * path_get - get a reference to a path
607 * @path: path to get the reference to
609 * Given a path increment the reference count to the dentry and the vfsmount.
611 void path_get(const struct path *path)
616 EXPORT_SYMBOL(path_get);
619 * path_put - put a reference to a path
620 * @path: path to put the reference to
622 * Given a path decrement the reference count to the dentry and the vfsmount.
624 void path_put(const struct path *path)
629 EXPORT_SYMBOL(path_put);
631 #define EMBEDDED_LEVELS 2
636 struct inode *inode; /* path.dentry.d_inode */
637 unsigned int flags, state;
638 unsigned seq, next_seq, m_seq, r_seq;
641 int total_link_count;
644 struct delayed_call done;
647 } *stack, internal[EMBEDDED_LEVELS];
648 struct filename *name;
649 const char *pathname;
650 struct nameidata *saved;
655 } __randomize_layout;
657 #define ND_ROOT_PRESET 1
658 #define ND_ROOT_GRABBED 2
661 static void __set_nameidata(struct nameidata *p, int dfd, struct filename *name)
663 struct nameidata *old = current->nameidata;
664 p->stack = p->internal;
668 p->pathname = likely(name) ? name->name : "";
670 p->path.dentry = NULL;
671 p->total_link_count = old ? old->total_link_count : 0;
673 current->nameidata = p;
676 static inline void set_nameidata(struct nameidata *p, int dfd, struct filename *name,
677 const struct path *root)
679 __set_nameidata(p, dfd, name);
681 if (unlikely(root)) {
682 p->state = ND_ROOT_PRESET;
687 static void restore_nameidata(void)
689 struct nameidata *now = current->nameidata, *old = now->saved;
691 current->nameidata = old;
693 old->total_link_count = now->total_link_count;
694 if (now->stack != now->internal)
698 static bool nd_alloc_stack(struct nameidata *nd)
702 p= kmalloc_array(MAXSYMLINKS, sizeof(struct saved),
703 nd->flags & LOOKUP_RCU ? GFP_ATOMIC : GFP_KERNEL);
706 memcpy(p, nd->internal, sizeof(nd->internal));
712 * path_connected - Verify that a dentry is below mnt.mnt_root
713 * @mnt: The mountpoint to check.
714 * @dentry: The dentry to check.
716 * Rename can sometimes move a file or directory outside of a bind
717 * mount, path_connected allows those cases to be detected.
719 static bool path_connected(struct vfsmount *mnt, struct dentry *dentry)
721 struct super_block *sb = mnt->mnt_sb;
723 /* Bind mounts can have disconnected paths */
724 if (mnt->mnt_root == sb->s_root)
727 return is_subdir(dentry, mnt->mnt_root);
730 static void drop_links(struct nameidata *nd)
734 struct saved *last = nd->stack + i;
735 do_delayed_call(&last->done);
736 clear_delayed_call(&last->done);
740 static void leave_rcu(struct nameidata *nd)
742 nd->flags &= ~LOOKUP_RCU;
743 nd->seq = nd->next_seq = 0;
747 static void terminate_walk(struct nameidata *nd)
750 if (!(nd->flags & LOOKUP_RCU)) {
753 for (i = 0; i < nd->depth; i++)
754 path_put(&nd->stack[i].link);
755 if (nd->state & ND_ROOT_GRABBED) {
757 nd->state &= ~ND_ROOT_GRABBED;
764 nd->path.dentry = NULL;
767 /* path_put is needed afterwards regardless of success or failure */
768 static bool __legitimize_path(struct path *path, unsigned seq, unsigned mseq)
770 int res = __legitimize_mnt(path->mnt, mseq);
777 if (unlikely(!lockref_get_not_dead(&path->dentry->d_lockref))) {
781 return !read_seqcount_retry(&path->dentry->d_seq, seq);
784 static inline bool legitimize_path(struct nameidata *nd,
785 struct path *path, unsigned seq)
787 return __legitimize_path(path, seq, nd->m_seq);
790 static bool legitimize_links(struct nameidata *nd)
793 if (unlikely(nd->flags & LOOKUP_CACHED)) {
798 for (i = 0; i < nd->depth; i++) {
799 struct saved *last = nd->stack + i;
800 if (unlikely(!legitimize_path(nd, &last->link, last->seq))) {
809 static bool legitimize_root(struct nameidata *nd)
811 /* Nothing to do if nd->root is zero or is managed by the VFS user. */
812 if (!nd->root.mnt || (nd->state & ND_ROOT_PRESET))
814 nd->state |= ND_ROOT_GRABBED;
815 return legitimize_path(nd, &nd->root, nd->root_seq);
819 * Path walking has 2 modes, rcu-walk and ref-walk (see
820 * Documentation/filesystems/path-lookup.txt). In situations when we can't
821 * continue in RCU mode, we attempt to drop out of rcu-walk mode and grab
822 * normal reference counts on dentries and vfsmounts to transition to ref-walk
823 * mode. Refcounts are grabbed at the last known good point before rcu-walk
824 * got stuck, so ref-walk may continue from there. If this is not successful
825 * (eg. a seqcount has changed), then failure is returned and it's up to caller
826 * to restart the path walk from the beginning in ref-walk mode.
830 * try_to_unlazy - try to switch to ref-walk mode.
831 * @nd: nameidata pathwalk data
832 * Returns: true on success, false on failure
834 * try_to_unlazy attempts to legitimize the current nd->path and nd->root
836 * Must be called from rcu-walk context.
837 * Nothing should touch nameidata between try_to_unlazy() failure and
840 static bool try_to_unlazy(struct nameidata *nd)
842 struct dentry *parent = nd->path.dentry;
844 BUG_ON(!(nd->flags & LOOKUP_RCU));
846 if (unlikely(!legitimize_links(nd)))
848 if (unlikely(!legitimize_path(nd, &nd->path, nd->seq)))
850 if (unlikely(!legitimize_root(nd)))
853 BUG_ON(nd->inode != parent->d_inode);
858 nd->path.dentry = NULL;
865 * try_to_unlazy_next - try to switch to ref-walk mode.
866 * @nd: nameidata pathwalk data
867 * @dentry: next dentry to step into
868 * Returns: true on success, false on failure
870 * Similar to try_to_unlazy(), but here we have the next dentry already
871 * picked by rcu-walk and want to legitimize that in addition to the current
872 * nd->path and nd->root for ref-walk mode. Must be called from rcu-walk context.
873 * Nothing should touch nameidata between try_to_unlazy_next() failure and
876 static bool try_to_unlazy_next(struct nameidata *nd, struct dentry *dentry)
879 BUG_ON(!(nd->flags & LOOKUP_RCU));
881 if (unlikely(!legitimize_links(nd)))
883 res = __legitimize_mnt(nd->path.mnt, nd->m_seq);
889 if (unlikely(!lockref_get_not_dead(&nd->path.dentry->d_lockref)))
893 * We need to move both the parent and the dentry from the RCU domain
894 * to be properly refcounted. And the sequence number in the dentry
895 * validates *both* dentry counters, since we checked the sequence
896 * number of the parent after we got the child sequence number. So we
897 * know the parent must still be valid if the child sequence number is
899 if (unlikely(!lockref_get_not_dead(&dentry->d_lockref)))
901 if (read_seqcount_retry(&dentry->d_seq, nd->next_seq))
904 * Sequence counts matched. Now make sure that the root is
905 * still valid and get it if required.
907 if (unlikely(!legitimize_root(nd)))
915 nd->path.dentry = NULL;
925 static inline int d_revalidate(struct inode *dir, const struct qstr *name,
926 struct dentry *dentry, unsigned int flags)
928 if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE))
929 return dentry->d_op->d_revalidate(dir, name, dentry, flags);
935 * complete_walk - successful completion of path walk
936 * @nd: pointer nameidata
938 * If we had been in RCU mode, drop out of it and legitimize nd->path.
939 * Revalidate the final result, unless we'd already done that during
940 * the path walk or the filesystem doesn't ask for it. Return 0 on
941 * success, -error on failure. In case of failure caller does not
942 * need to drop nd->path.
944 static int complete_walk(struct nameidata *nd)
946 struct dentry *dentry = nd->path.dentry;
949 if (nd->flags & LOOKUP_RCU) {
951 * We don't want to zero nd->root for scoped-lookups or
952 * externally-managed nd->root.
954 if (!(nd->state & ND_ROOT_PRESET))
955 if (!(nd->flags & LOOKUP_IS_SCOPED))
957 nd->flags &= ~LOOKUP_CACHED;
958 if (!try_to_unlazy(nd))
962 if (unlikely(nd->flags & LOOKUP_IS_SCOPED)) {
964 * While the guarantee of LOOKUP_IS_SCOPED is (roughly) "don't
965 * ever step outside the root during lookup" and should already
966 * be guaranteed by the rest of namei, we want to avoid a namei
967 * BUG resulting in userspace being given a path that was not
968 * scoped within the root at some point during the lookup.
970 * So, do a final sanity-check to make sure that in the
971 * worst-case scenario (a complete bypass of LOOKUP_IS_SCOPED)
972 * we won't silently return an fd completely outside of the
973 * requested root to userspace.
975 * Userspace could move the path outside the root after this
976 * check, but as discussed elsewhere this is not a concern (the
977 * resolved file was inside the root at some point).
979 if (!path_is_under(&nd->path, &nd->root))
983 if (likely(!(nd->state & ND_JUMPED)))
986 if (likely(!(dentry->d_flags & DCACHE_OP_WEAK_REVALIDATE)))
989 status = dentry->d_op->d_weak_revalidate(dentry, nd->flags);
999 static int set_root(struct nameidata *nd)
1001 struct fs_struct *fs = current->fs;
1004 * Jumping to the real root in a scoped-lookup is a BUG in namei, but we
1005 * still have to ensure it doesn't happen because it will cause a breakout
1008 if (WARN_ON(nd->flags & LOOKUP_IS_SCOPED))
1009 return -ENOTRECOVERABLE;
1011 if (nd->flags & LOOKUP_RCU) {
1015 seq = read_seqcount_begin(&fs->seq);
1016 nd->root = fs->root;
1017 nd->root_seq = __read_seqcount_begin(&nd->root.dentry->d_seq);
1018 } while (read_seqcount_retry(&fs->seq, seq));
1020 get_fs_root(fs, &nd->root);
1021 nd->state |= ND_ROOT_GRABBED;
1026 static int nd_jump_root(struct nameidata *nd)
1028 if (unlikely(nd->flags & LOOKUP_BENEATH))
1030 if (unlikely(nd->flags & LOOKUP_NO_XDEV)) {
1031 /* Absolute path arguments to path_init() are allowed. */
1032 if (nd->path.mnt != NULL && nd->path.mnt != nd->root.mnt)
1035 if (!nd->root.mnt) {
1036 int error = set_root(nd);
1040 if (nd->flags & LOOKUP_RCU) {
1042 nd->path = nd->root;
1043 d = nd->path.dentry;
1044 nd->inode = d->d_inode;
1045 nd->seq = nd->root_seq;
1046 if (read_seqcount_retry(&d->d_seq, nd->seq))
1049 path_put(&nd->path);
1050 nd->path = nd->root;
1051 path_get(&nd->path);
1052 nd->inode = nd->path.dentry->d_inode;
1054 nd->state |= ND_JUMPED;
1059 * Helper to directly jump to a known parsed path from ->get_link,
1060 * caller must have taken a reference to path beforehand.
1062 int nd_jump_link(const struct path *path)
1065 struct nameidata *nd = current->nameidata;
1067 if (unlikely(nd->flags & LOOKUP_NO_MAGICLINKS))
1071 if (unlikely(nd->flags & LOOKUP_NO_XDEV)) {
1072 if (nd->path.mnt != path->mnt)
1075 /* Not currently safe for scoped-lookups. */
1076 if (unlikely(nd->flags & LOOKUP_IS_SCOPED))
1079 path_put(&nd->path);
1081 nd->inode = nd->path.dentry->d_inode;
1082 nd->state |= ND_JUMPED;
1090 static inline void put_link(struct nameidata *nd)
1092 struct saved *last = nd->stack + --nd->depth;
1093 do_delayed_call(&last->done);
1094 if (!(nd->flags & LOOKUP_RCU))
1095 path_put(&last->link);
1098 static int sysctl_protected_symlinks __read_mostly;
1099 static int sysctl_protected_hardlinks __read_mostly;
1100 static int sysctl_protected_fifos __read_mostly;
1101 static int sysctl_protected_regular __read_mostly;
1103 #ifdef CONFIG_SYSCTL
1104 static const struct ctl_table namei_sysctls[] = {
1106 .procname = "protected_symlinks",
1107 .data = &sysctl_protected_symlinks,
1108 .maxlen = sizeof(int),
1110 .proc_handler = proc_dointvec_minmax,
1111 .extra1 = SYSCTL_ZERO,
1112 .extra2 = SYSCTL_ONE,
1115 .procname = "protected_hardlinks",
1116 .data = &sysctl_protected_hardlinks,
1117 .maxlen = sizeof(int),
1119 .proc_handler = proc_dointvec_minmax,
1120 .extra1 = SYSCTL_ZERO,
1121 .extra2 = SYSCTL_ONE,
1124 .procname = "protected_fifos",
1125 .data = &sysctl_protected_fifos,
1126 .maxlen = sizeof(int),
1128 .proc_handler = proc_dointvec_minmax,
1129 .extra1 = SYSCTL_ZERO,
1130 .extra2 = SYSCTL_TWO,
1133 .procname = "protected_regular",
1134 .data = &sysctl_protected_regular,
1135 .maxlen = sizeof(int),
1137 .proc_handler = proc_dointvec_minmax,
1138 .extra1 = SYSCTL_ZERO,
1139 .extra2 = SYSCTL_TWO,
1143 static int __init init_fs_namei_sysctls(void)
1145 register_sysctl_init("fs", namei_sysctls);
1148 fs_initcall(init_fs_namei_sysctls);
1150 #endif /* CONFIG_SYSCTL */
1153 * may_follow_link - Check symlink following for unsafe situations
1154 * @nd: nameidata pathwalk data
1155 * @inode: Used for idmapping.
1157 * In the case of the sysctl_protected_symlinks sysctl being enabled,
1158 * CAP_DAC_OVERRIDE needs to be specifically ignored if the symlink is
1159 * in a sticky world-writable directory. This is to protect privileged
1160 * processes from failing races against path names that may change out
1161 * from under them by way of other users creating malicious symlinks.
1162 * It will permit symlinks to be followed only when outside a sticky
1163 * world-writable directory, or when the uid of the symlink and follower
1164 * match, or when the directory owner matches the symlink's owner.
1166 * Returns 0 if following the symlink is allowed, -ve on error.
1168 static inline int may_follow_link(struct nameidata *nd, const struct inode *inode)
1170 struct mnt_idmap *idmap;
1173 if (!sysctl_protected_symlinks)
1176 idmap = mnt_idmap(nd->path.mnt);
1177 vfsuid = i_uid_into_vfsuid(idmap, inode);
1178 /* Allowed if owner and follower match. */
1179 if (vfsuid_eq_kuid(vfsuid, current_fsuid()))
1182 /* Allowed if parent directory not sticky and world-writable. */
1183 if ((nd->dir_mode & (S_ISVTX|S_IWOTH)) != (S_ISVTX|S_IWOTH))
1186 /* Allowed if parent directory and link owner match. */
1187 if (vfsuid_valid(nd->dir_vfsuid) && vfsuid_eq(nd->dir_vfsuid, vfsuid))
1190 if (nd->flags & LOOKUP_RCU)
1193 audit_inode(nd->name, nd->stack[0].link.dentry, 0);
1194 audit_log_path_denied(AUDIT_ANOM_LINK, "follow_link");
1199 * safe_hardlink_source - Check for safe hardlink conditions
1200 * @idmap: idmap of the mount the inode was found from
1201 * @inode: the source inode to hardlink from
1203 * Return false if at least one of the following conditions:
1204 * - inode is not a regular file
1206 * - inode is setgid and group-exec
1207 * - access failure for read and write
1209 * Otherwise returns true.
1211 static bool safe_hardlink_source(struct mnt_idmap *idmap,
1212 struct inode *inode)
1214 umode_t mode = inode->i_mode;
1216 /* Special files should not get pinned to the filesystem. */
1220 /* Setuid files should not get pinned to the filesystem. */
1224 /* Executable setgid files should not get pinned to the filesystem. */
1225 if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP))
1228 /* Hardlinking to unreadable or unwritable sources is dangerous. */
1229 if (inode_permission(idmap, inode, MAY_READ | MAY_WRITE))
1236 * may_linkat - Check permissions for creating a hardlink
1237 * @idmap: idmap of the mount the inode was found from
1238 * @link: the source to hardlink from
1240 * Block hardlink when all of:
1241 * - sysctl_protected_hardlinks enabled
1242 * - fsuid does not match inode
1243 * - hardlink source is unsafe (see safe_hardlink_source() above)
1244 * - not CAP_FOWNER in a namespace with the inode owner uid mapped
1246 * If the inode has been found through an idmapped mount the idmap of
1247 * the vfsmount must be passed through @idmap. This function will then take
1248 * care to map the inode according to @idmap before checking permissions.
1249 * On non-idmapped mounts or if permission checking is to be performed on the
1250 * raw inode simply pass @nop_mnt_idmap.
1252 * Returns 0 if successful, -ve on error.
1254 int may_linkat(struct mnt_idmap *idmap, const struct path *link)
1256 struct inode *inode = link->dentry->d_inode;
1258 /* Inode writeback is not safe when the uid or gid are invalid. */
1259 if (!vfsuid_valid(i_uid_into_vfsuid(idmap, inode)) ||
1260 !vfsgid_valid(i_gid_into_vfsgid(idmap, inode)))
1263 if (!sysctl_protected_hardlinks)
1266 /* Source inode owner (or CAP_FOWNER) can hardlink all they like,
1267 * otherwise, it must be a safe source.
1269 if (safe_hardlink_source(idmap, inode) ||
1270 inode_owner_or_capable(idmap, inode))
1273 audit_log_path_denied(AUDIT_ANOM_LINK, "linkat");
1278 * may_create_in_sticky - Check whether an O_CREAT open in a sticky directory
1279 * should be allowed, or not, on files that already
1281 * @idmap: idmap of the mount the inode was found from
1282 * @nd: nameidata pathwalk data
1283 * @inode: the inode of the file to open
1285 * Block an O_CREAT open of a FIFO (or a regular file) when:
1286 * - sysctl_protected_fifos (or sysctl_protected_regular) is enabled
1287 * - the file already exists
1288 * - we are in a sticky directory
1289 * - we don't own the file
1290 * - the owner of the directory doesn't own the file
1291 * - the directory is world writable
1292 * If the sysctl_protected_fifos (or sysctl_protected_regular) is set to 2
1293 * the directory doesn't have to be world writable: being group writable will
1296 * If the inode has been found through an idmapped mount the idmap of
1297 * the vfsmount must be passed through @idmap. This function will then take
1298 * care to map the inode according to @idmap before checking permissions.
1299 * On non-idmapped mounts or if permission checking is to be performed on the
1300 * raw inode simply pass @nop_mnt_idmap.
1302 * Returns 0 if the open is allowed, -ve on error.
1304 static int may_create_in_sticky(struct mnt_idmap *idmap, struct nameidata *nd,
1305 struct inode *const inode)
1307 umode_t dir_mode = nd->dir_mode;
1308 vfsuid_t dir_vfsuid = nd->dir_vfsuid, i_vfsuid;
1310 if (likely(!(dir_mode & S_ISVTX)))
1313 if (S_ISREG(inode->i_mode) && !sysctl_protected_regular)
1316 if (S_ISFIFO(inode->i_mode) && !sysctl_protected_fifos)
1319 i_vfsuid = i_uid_into_vfsuid(idmap, inode);
1321 if (vfsuid_eq(i_vfsuid, dir_vfsuid))
1324 if (vfsuid_eq_kuid(i_vfsuid, current_fsuid()))
1327 if (likely(dir_mode & 0002)) {
1328 audit_log_path_denied(AUDIT_ANOM_CREAT, "sticky_create");
1332 if (dir_mode & 0020) {
1333 if (sysctl_protected_fifos >= 2 && S_ISFIFO(inode->i_mode)) {
1334 audit_log_path_denied(AUDIT_ANOM_CREAT,
1335 "sticky_create_fifo");
1339 if (sysctl_protected_regular >= 2 && S_ISREG(inode->i_mode)) {
1340 audit_log_path_denied(AUDIT_ANOM_CREAT,
1341 "sticky_create_regular");
1350 * follow_up - Find the mountpoint of path's vfsmount
1352 * Given a path, find the mountpoint of its source file system.
1353 * Replace @path with the path of the mountpoint in the parent mount.
1356 * Return 1 if we went up a level and 0 if we were already at the
1359 int follow_up(struct path *path)
1361 struct mount *mnt = real_mount(path->mnt);
1362 struct mount *parent;
1363 struct dentry *mountpoint;
1365 read_seqlock_excl(&mount_lock);
1366 parent = mnt->mnt_parent;
1367 if (parent == mnt) {
1368 read_sequnlock_excl(&mount_lock);
1371 mntget(&parent->mnt);
1372 mountpoint = dget(mnt->mnt_mountpoint);
1373 read_sequnlock_excl(&mount_lock);
1375 path->dentry = mountpoint;
1377 path->mnt = &parent->mnt;
1380 EXPORT_SYMBOL(follow_up);
1382 static bool choose_mountpoint_rcu(struct mount *m, const struct path *root,
1383 struct path *path, unsigned *seqp)
1385 while (mnt_has_parent(m)) {
1386 struct dentry *mountpoint = m->mnt_mountpoint;
1389 if (unlikely(root->dentry == mountpoint &&
1390 root->mnt == &m->mnt))
1392 if (mountpoint != m->mnt.mnt_root) {
1393 path->mnt = &m->mnt;
1394 path->dentry = mountpoint;
1395 *seqp = read_seqcount_begin(&mountpoint->d_seq);
1402 static bool choose_mountpoint(struct mount *m, const struct path *root,
1409 unsigned seq, mseq = read_seqbegin(&mount_lock);
1411 found = choose_mountpoint_rcu(m, root, path, &seq);
1412 if (unlikely(!found)) {
1413 if (!read_seqretry(&mount_lock, mseq))
1416 if (likely(__legitimize_path(path, seq, mseq)))
1428 * Perform an automount
1429 * - return -EISDIR to tell follow_managed() to stop and return the path we
1432 static int follow_automount(struct path *path, int *count, unsigned lookup_flags)
1434 struct dentry *dentry = path->dentry;
1436 /* We don't want to mount if someone's just doing a stat -
1437 * unless they're stat'ing a directory and appended a '/' to
1440 * We do, however, want to mount if someone wants to open or
1441 * create a file of any type under the mountpoint, wants to
1442 * traverse through the mountpoint or wants to open the
1443 * mounted directory. Also, autofs may mark negative dentries
1444 * as being automount points. These will need the attentions
1445 * of the daemon to instantiate them before they can be used.
1447 if (!(lookup_flags & (LOOKUP_PARENT | LOOKUP_DIRECTORY |
1448 LOOKUP_OPEN | LOOKUP_CREATE | LOOKUP_AUTOMOUNT)) &&
1452 if (count && (*count)++ >= MAXSYMLINKS)
1455 return finish_automount(dentry->d_op->d_automount(path), path);
1459 * mount traversal - out-of-line part. One note on ->d_flags accesses -
1460 * dentries are pinned but not locked here, so negative dentry can go
1461 * positive right under us. Use of smp_load_acquire() provides a barrier
1462 * sufficient for ->d_inode and ->d_flags consistency.
1464 static int __traverse_mounts(struct path *path, unsigned flags, bool *jumped,
1465 int *count, unsigned lookup_flags)
1467 struct vfsmount *mnt = path->mnt;
1468 bool need_mntput = false;
1471 while (flags & DCACHE_MANAGED_DENTRY) {
1472 /* Allow the filesystem to manage the transit without i_mutex
1474 if (flags & DCACHE_MANAGE_TRANSIT) {
1475 ret = path->dentry->d_op->d_manage(path, false);
1476 flags = smp_load_acquire(&path->dentry->d_flags);
1481 if (flags & DCACHE_MOUNTED) { // something's mounted on it..
1482 struct vfsmount *mounted = lookup_mnt(path);
1483 if (mounted) { // ... in our namespace
1487 path->mnt = mounted;
1488 path->dentry = dget(mounted->mnt_root);
1489 // here we know it's positive
1490 flags = path->dentry->d_flags;
1496 if (!(flags & DCACHE_NEED_AUTOMOUNT))
1499 // uncovered automount point
1500 ret = follow_automount(path, count, lookup_flags);
1501 flags = smp_load_acquire(&path->dentry->d_flags);
1508 // possible if you race with several mount --move
1509 if (need_mntput && path->mnt == mnt)
1511 if (!ret && unlikely(d_flags_negative(flags)))
1513 *jumped = need_mntput;
1517 static inline int traverse_mounts(struct path *path, bool *jumped,
1518 int *count, unsigned lookup_flags)
1520 unsigned flags = smp_load_acquire(&path->dentry->d_flags);
1523 if (likely(!(flags & DCACHE_MANAGED_DENTRY))) {
1525 if (unlikely(d_flags_negative(flags)))
1529 return __traverse_mounts(path, flags, jumped, count, lookup_flags);
1532 int follow_down_one(struct path *path)
1534 struct vfsmount *mounted;
1536 mounted = lookup_mnt(path);
1540 path->mnt = mounted;
1541 path->dentry = dget(mounted->mnt_root);
1546 EXPORT_SYMBOL(follow_down_one);
1549 * Follow down to the covering mount currently visible to userspace. At each
1550 * point, the filesystem owning that dentry may be queried as to whether the
1551 * caller is permitted to proceed or not.
1553 int follow_down(struct path *path, unsigned int flags)
1555 struct vfsmount *mnt = path->mnt;
1557 int ret = traverse_mounts(path, &jumped, NULL, flags);
1559 if (path->mnt != mnt)
1563 EXPORT_SYMBOL(follow_down);
1566 * Try to skip to top of mountpoint pile in rcuwalk mode. Fail if
1567 * we meet a managed dentry that would need blocking.
1569 static bool __follow_mount_rcu(struct nameidata *nd, struct path *path)
1571 struct dentry *dentry = path->dentry;
1572 unsigned int flags = dentry->d_flags;
1574 if (likely(!(flags & DCACHE_MANAGED_DENTRY)))
1577 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1582 * Don't forget we might have a non-mountpoint managed dentry
1583 * that wants to block transit.
1585 if (unlikely(flags & DCACHE_MANAGE_TRANSIT)) {
1586 int res = dentry->d_op->d_manage(path, true);
1588 return res == -EISDIR;
1589 flags = dentry->d_flags;
1592 if (flags & DCACHE_MOUNTED) {
1593 struct mount *mounted = __lookup_mnt(path->mnt, dentry);
1595 path->mnt = &mounted->mnt;
1596 dentry = path->dentry = mounted->mnt.mnt_root;
1597 nd->state |= ND_JUMPED;
1598 nd->next_seq = read_seqcount_begin(&dentry->d_seq);
1599 flags = dentry->d_flags;
1600 // makes sure that non-RCU pathwalk could reach
1602 if (read_seqretry(&mount_lock, nd->m_seq))
1606 if (read_seqretry(&mount_lock, nd->m_seq))
1609 return !(flags & DCACHE_NEED_AUTOMOUNT);
1613 static inline int handle_mounts(struct nameidata *nd, struct dentry *dentry,
1619 path->mnt = nd->path.mnt;
1620 path->dentry = dentry;
1621 if (nd->flags & LOOKUP_RCU) {
1622 unsigned int seq = nd->next_seq;
1623 if (likely(__follow_mount_rcu(nd, path)))
1625 // *path and nd->next_seq might've been clobbered
1626 path->mnt = nd->path.mnt;
1627 path->dentry = dentry;
1629 if (!try_to_unlazy_next(nd, dentry))
1632 ret = traverse_mounts(path, &jumped, &nd->total_link_count, nd->flags);
1634 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1637 nd->state |= ND_JUMPED;
1639 if (unlikely(ret)) {
1641 if (path->mnt != nd->path.mnt)
1648 * This looks up the name in dcache and possibly revalidates the found dentry.
1649 * NULL is returned if the dentry does not exist in the cache.
1651 static struct dentry *lookup_dcache(const struct qstr *name,
1655 struct dentry *dentry = d_lookup(dir, name);
1657 int error = d_revalidate(dir->d_inode, name, dentry, flags);
1658 if (unlikely(error <= 0)) {
1660 d_invalidate(dentry);
1662 return ERR_PTR(error);
1668 static struct dentry *lookup_one_qstr_excl_raw(const struct qstr *name,
1669 struct dentry *base,
1672 struct dentry *dentry;
1676 dentry = lookup_dcache(name, base, flags);
1680 /* Don't create child dentry for a dead directory. */
1681 dir = base->d_inode;
1682 if (unlikely(IS_DEADDIR(dir)))
1683 return ERR_PTR(-ENOENT);
1685 dentry = d_alloc(base, name);
1686 if (unlikely(!dentry))
1687 return ERR_PTR(-ENOMEM);
1689 old = dir->i_op->lookup(dir, dentry, flags);
1690 if (unlikely(old)) {
1698 * Parent directory has inode locked exclusive. This is one
1699 * and only case when ->lookup() gets called on non in-lookup
1700 * dentries - as the matter of fact, this only gets called
1701 * when directory is guaranteed to have no in-lookup children
1703 * Will return -ENOENT if name isn't found and LOOKUP_CREATE wasn't passed.
1704 * Will return -EEXIST if name is found and LOOKUP_EXCL was passed.
1706 struct dentry *lookup_one_qstr_excl(const struct qstr *name,
1707 struct dentry *base, unsigned int flags)
1709 struct dentry *dentry;
1711 dentry = lookup_one_qstr_excl_raw(name, base, flags);
1714 if (d_is_negative(dentry) && !(flags & LOOKUP_CREATE)) {
1716 return ERR_PTR(-ENOENT);
1718 if (d_is_positive(dentry) && (flags & LOOKUP_EXCL)) {
1720 return ERR_PTR(-EEXIST);
1724 EXPORT_SYMBOL(lookup_one_qstr_excl);
1727 * lookup_fast - do fast lockless (but racy) lookup of a dentry
1728 * @nd: current nameidata
1730 * Do a fast, but racy lookup in the dcache for the given dentry, and
1731 * revalidate it. Returns a valid dentry pointer or NULL if one wasn't
1732 * found. On error, an ERR_PTR will be returned.
1734 * If this function returns a valid dentry and the walk is no longer
1735 * lazy, the dentry will carry a reference that must later be put. If
1736 * RCU mode is still in force, then this is not the case and the dentry
1737 * must be legitimized before use. If this returns NULL, then the walk
1738 * will no longer be in RCU mode.
1740 static struct dentry *lookup_fast(struct nameidata *nd)
1742 struct dentry *dentry, *parent = nd->path.dentry;
1746 * Rename seqlock is not required here because in the off chance
1747 * of a false negative due to a concurrent rename, the caller is
1748 * going to fall back to non-racy lookup.
1750 if (nd->flags & LOOKUP_RCU) {
1751 dentry = __d_lookup_rcu(parent, &nd->last, &nd->next_seq);
1752 if (unlikely(!dentry)) {
1753 if (!try_to_unlazy(nd))
1754 return ERR_PTR(-ECHILD);
1759 * This sequence count validates that the parent had no
1760 * changes while we did the lookup of the dentry above.
1762 if (read_seqcount_retry(&parent->d_seq, nd->seq))
1763 return ERR_PTR(-ECHILD);
1765 status = d_revalidate(nd->inode, &nd->last, dentry, nd->flags);
1766 if (likely(status > 0))
1768 if (!try_to_unlazy_next(nd, dentry))
1769 return ERR_PTR(-ECHILD);
1770 if (status == -ECHILD)
1771 /* we'd been told to redo it in non-rcu mode */
1772 status = d_revalidate(nd->inode, &nd->last,
1775 dentry = __d_lookup(parent, &nd->last);
1776 if (unlikely(!dentry))
1778 status = d_revalidate(nd->inode, &nd->last, dentry, nd->flags);
1780 if (unlikely(status <= 0)) {
1782 d_invalidate(dentry);
1784 return ERR_PTR(status);
1789 /* Fast lookup failed, do it the slow way */
1790 static struct dentry *__lookup_slow(const struct qstr *name,
1794 struct dentry *dentry, *old;
1795 struct inode *inode = dir->d_inode;
1796 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
1798 /* Don't go there if it's already dead */
1799 if (unlikely(IS_DEADDIR(inode)))
1800 return ERR_PTR(-ENOENT);
1802 dentry = d_alloc_parallel(dir, name, &wq);
1805 if (unlikely(!d_in_lookup(dentry))) {
1806 int error = d_revalidate(inode, name, dentry, flags);
1807 if (unlikely(error <= 0)) {
1809 d_invalidate(dentry);
1814 dentry = ERR_PTR(error);
1817 old = inode->i_op->lookup(inode, dentry, flags);
1818 d_lookup_done(dentry);
1819 if (unlikely(old)) {
1827 static struct dentry *lookup_slow(const struct qstr *name,
1831 struct inode *inode = dir->d_inode;
1833 inode_lock_shared(inode);
1834 res = __lookup_slow(name, dir, flags);
1835 inode_unlock_shared(inode);
1839 static inline int may_lookup(struct mnt_idmap *idmap,
1840 struct nameidata *restrict nd)
1844 mask = nd->flags & LOOKUP_RCU ? MAY_NOT_BLOCK : 0;
1845 err = inode_permission(idmap, nd->inode, mask | MAY_EXEC);
1849 // If we failed, and we weren't in LOOKUP_RCU, it's final
1850 if (!(nd->flags & LOOKUP_RCU))
1853 // Drop out of RCU mode to make sure it wasn't transient
1854 if (!try_to_unlazy(nd))
1855 return -ECHILD; // redo it all non-lazy
1857 if (err != -ECHILD) // hard error
1860 return inode_permission(idmap, nd->inode, MAY_EXEC);
1863 static int reserve_stack(struct nameidata *nd, struct path *link)
1865 if (unlikely(nd->total_link_count++ >= MAXSYMLINKS))
1868 if (likely(nd->depth != EMBEDDED_LEVELS))
1870 if (likely(nd->stack != nd->internal))
1872 if (likely(nd_alloc_stack(nd)))
1875 if (nd->flags & LOOKUP_RCU) {
1876 // we need to grab link before we do unlazy. And we can't skip
1877 // unlazy even if we fail to grab the link - cleanup needs it
1878 bool grabbed_link = legitimize_path(nd, link, nd->next_seq);
1880 if (!try_to_unlazy(nd) || !grabbed_link)
1883 if (nd_alloc_stack(nd))
1889 enum {WALK_TRAILING = 1, WALK_MORE = 2, WALK_NOFOLLOW = 4};
1891 static const char *pick_link(struct nameidata *nd, struct path *link,
1892 struct inode *inode, int flags)
1896 int error = reserve_stack(nd, link);
1898 if (unlikely(error)) {
1899 if (!(nd->flags & LOOKUP_RCU))
1901 return ERR_PTR(error);
1903 last = nd->stack + nd->depth++;
1905 clear_delayed_call(&last->done);
1906 last->seq = nd->next_seq;
1908 if (flags & WALK_TRAILING) {
1909 error = may_follow_link(nd, inode);
1910 if (unlikely(error))
1911 return ERR_PTR(error);
1914 if (unlikely(nd->flags & LOOKUP_NO_SYMLINKS) ||
1915 unlikely(link->mnt->mnt_flags & MNT_NOSYMFOLLOW))
1916 return ERR_PTR(-ELOOP);
1918 if (unlikely(atime_needs_update(&last->link, inode))) {
1919 if (nd->flags & LOOKUP_RCU) {
1920 if (!try_to_unlazy(nd))
1921 return ERR_PTR(-ECHILD);
1923 touch_atime(&last->link);
1927 error = security_inode_follow_link(link->dentry, inode,
1928 nd->flags & LOOKUP_RCU);
1929 if (unlikely(error))
1930 return ERR_PTR(error);
1932 res = READ_ONCE(inode->i_link);
1934 const char * (*get)(struct dentry *, struct inode *,
1935 struct delayed_call *);
1936 get = inode->i_op->get_link;
1937 if (nd->flags & LOOKUP_RCU) {
1938 res = get(NULL, inode, &last->done);
1939 if (res == ERR_PTR(-ECHILD) && try_to_unlazy(nd))
1940 res = get(link->dentry, inode, &last->done);
1942 res = get(link->dentry, inode, &last->done);
1950 error = nd_jump_root(nd);
1951 if (unlikely(error))
1952 return ERR_PTR(error);
1953 while (unlikely(*++res == '/'))
1958 all_done: // pure jump
1964 * Do we need to follow links? We _really_ want to be able
1965 * to do this check without having to look at inode->i_op,
1966 * so we keep a cache of "no, this doesn't need follow_link"
1967 * for the common case.
1969 * NOTE: dentry must be what nd->next_seq had been sampled from.
1971 static const char *step_into(struct nameidata *nd, int flags,
1972 struct dentry *dentry)
1975 struct inode *inode;
1976 int err = handle_mounts(nd, dentry, &path);
1979 return ERR_PTR(err);
1980 inode = path.dentry->d_inode;
1981 if (likely(!d_is_symlink(path.dentry)) ||
1982 ((flags & WALK_TRAILING) && !(nd->flags & LOOKUP_FOLLOW)) ||
1983 (flags & WALK_NOFOLLOW)) {
1984 /* not a symlink or should not follow */
1985 if (nd->flags & LOOKUP_RCU) {
1986 if (read_seqcount_retry(&path.dentry->d_seq, nd->next_seq))
1987 return ERR_PTR(-ECHILD);
1988 if (unlikely(!inode))
1989 return ERR_PTR(-ENOENT);
1991 dput(nd->path.dentry);
1992 if (nd->path.mnt != path.mnt)
1993 mntput(nd->path.mnt);
1997 nd->seq = nd->next_seq;
2000 if (nd->flags & LOOKUP_RCU) {
2001 /* make sure that d_is_symlink above matches inode */
2002 if (read_seqcount_retry(&path.dentry->d_seq, nd->next_seq))
2003 return ERR_PTR(-ECHILD);
2005 if (path.mnt == nd->path.mnt)
2008 return pick_link(nd, &path, inode, flags);
2011 static struct dentry *follow_dotdot_rcu(struct nameidata *nd)
2013 struct dentry *parent, *old;
2015 if (path_equal(&nd->path, &nd->root))
2017 if (unlikely(nd->path.dentry == nd->path.mnt->mnt_root)) {
2020 if (!choose_mountpoint_rcu(real_mount(nd->path.mnt),
2021 &nd->root, &path, &seq))
2023 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
2024 return ERR_PTR(-ECHILD);
2026 nd->inode = path.dentry->d_inode;
2028 // makes sure that non-RCU pathwalk could reach this state
2029 if (read_seqretry(&mount_lock, nd->m_seq))
2030 return ERR_PTR(-ECHILD);
2031 /* we know that mountpoint was pinned */
2033 old = nd->path.dentry;
2034 parent = old->d_parent;
2035 nd->next_seq = read_seqcount_begin(&parent->d_seq);
2036 // makes sure that non-RCU pathwalk could reach this state
2037 if (read_seqcount_retry(&old->d_seq, nd->seq))
2038 return ERR_PTR(-ECHILD);
2039 if (unlikely(!path_connected(nd->path.mnt, parent)))
2040 return ERR_PTR(-ECHILD);
2043 if (read_seqretry(&mount_lock, nd->m_seq))
2044 return ERR_PTR(-ECHILD);
2045 if (unlikely(nd->flags & LOOKUP_BENEATH))
2046 return ERR_PTR(-ECHILD);
2047 nd->next_seq = nd->seq;
2048 return nd->path.dentry;
2051 static struct dentry *follow_dotdot(struct nameidata *nd)
2053 struct dentry *parent;
2055 if (path_equal(&nd->path, &nd->root))
2057 if (unlikely(nd->path.dentry == nd->path.mnt->mnt_root)) {
2060 if (!choose_mountpoint(real_mount(nd->path.mnt),
2063 path_put(&nd->path);
2065 nd->inode = path.dentry->d_inode;
2066 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
2067 return ERR_PTR(-EXDEV);
2069 /* rare case of legitimate dget_parent()... */
2070 parent = dget_parent(nd->path.dentry);
2071 if (unlikely(!path_connected(nd->path.mnt, parent))) {
2073 return ERR_PTR(-ENOENT);
2078 if (unlikely(nd->flags & LOOKUP_BENEATH))
2079 return ERR_PTR(-EXDEV);
2080 return dget(nd->path.dentry);
2083 static const char *handle_dots(struct nameidata *nd, int type)
2085 if (type == LAST_DOTDOT) {
2086 const char *error = NULL;
2087 struct dentry *parent;
2089 if (!nd->root.mnt) {
2090 error = ERR_PTR(set_root(nd));
2094 if (nd->flags & LOOKUP_RCU)
2095 parent = follow_dotdot_rcu(nd);
2097 parent = follow_dotdot(nd);
2099 return ERR_CAST(parent);
2100 error = step_into(nd, WALK_NOFOLLOW, parent);
2101 if (unlikely(error))
2104 if (unlikely(nd->flags & LOOKUP_IS_SCOPED)) {
2106 * If there was a racing rename or mount along our
2107 * path, then we can't be sure that ".." hasn't jumped
2108 * above nd->root (and so userspace should retry or use
2112 if (__read_seqcount_retry(&mount_lock.seqcount, nd->m_seq))
2113 return ERR_PTR(-EAGAIN);
2114 if (__read_seqcount_retry(&rename_lock.seqcount, nd->r_seq))
2115 return ERR_PTR(-EAGAIN);
2121 static const char *walk_component(struct nameidata *nd, int flags)
2123 struct dentry *dentry;
2125 * "." and ".." are special - ".." especially so because it has
2126 * to be able to know about the current root directory and
2127 * parent relationships.
2129 if (unlikely(nd->last_type != LAST_NORM)) {
2130 if (!(flags & WALK_MORE) && nd->depth)
2132 return handle_dots(nd, nd->last_type);
2134 dentry = lookup_fast(nd);
2136 return ERR_CAST(dentry);
2137 if (unlikely(!dentry)) {
2138 dentry = lookup_slow(&nd->last, nd->path.dentry, nd->flags);
2140 return ERR_CAST(dentry);
2142 if (!(flags & WALK_MORE) && nd->depth)
2144 return step_into(nd, flags, dentry);
2148 * We can do the critical dentry name comparison and hashing
2149 * operations one word at a time, but we are limited to:
2151 * - Architectures with fast unaligned word accesses. We could
2152 * do a "get_unaligned()" if this helps and is sufficiently
2155 * - non-CONFIG_DEBUG_PAGEALLOC configurations (so that we
2156 * do not trap on the (extremely unlikely) case of a page
2157 * crossing operation.
2159 * - Furthermore, we need an efficient 64-bit compile for the
2160 * 64-bit case in order to generate the "number of bytes in
2161 * the final mask". Again, that could be replaced with a
2162 * efficient population count instruction or similar.
2164 #ifdef CONFIG_DCACHE_WORD_ACCESS
2166 #include <asm/word-at-a-time.h>
2170 /* Architecture provides HASH_MIX and fold_hash() in <asm/hash.h> */
2172 #elif defined(CONFIG_64BIT)
2174 * Register pressure in the mixing function is an issue, particularly
2175 * on 32-bit x86, but almost any function requires one state value and
2176 * one temporary. Instead, use a function designed for two state values
2177 * and no temporaries.
2179 * This function cannot create a collision in only two iterations, so
2180 * we have two iterations to achieve avalanche. In those two iterations,
2181 * we have six layers of mixing, which is enough to spread one bit's
2182 * influence out to 2^6 = 64 state bits.
2184 * Rotate constants are scored by considering either 64 one-bit input
2185 * deltas or 64*63/2 = 2016 two-bit input deltas, and finding the
2186 * probability of that delta causing a change to each of the 128 output
2187 * bits, using a sample of random initial states.
2189 * The Shannon entropy of the computed probabilities is then summed
2190 * to produce a score. Ideally, any input change has a 50% chance of
2191 * toggling any given output bit.
2193 * Mixing scores (in bits) for (12,45):
2194 * Input delta: 1-bit 2-bit
2195 * 1 round: 713.3 42542.6
2196 * 2 rounds: 2753.7 140389.8
2197 * 3 rounds: 5954.1 233458.2
2198 * 4 rounds: 7862.6 256672.2
2199 * Perfect: 8192 258048
2200 * (64*128) (64*63/2 * 128)
2202 #define HASH_MIX(x, y, a) \
2204 y ^= x, x = rol64(x,12),\
2205 x += y, y = rol64(y,45),\
2209 * Fold two longs into one 32-bit hash value. This must be fast, but
2210 * latency isn't quite as critical, as there is a fair bit of additional
2211 * work done before the hash value is used.
2213 static inline unsigned int fold_hash(unsigned long x, unsigned long y)
2215 y ^= x * GOLDEN_RATIO_64;
2216 y *= GOLDEN_RATIO_64;
2220 #else /* 32-bit case */
2223 * Mixing scores (in bits) for (7,20):
2224 * Input delta: 1-bit 2-bit
2225 * 1 round: 330.3 9201.6
2226 * 2 rounds: 1246.4 25475.4
2227 * 3 rounds: 1907.1 31295.1
2228 * 4 rounds: 2042.3 31718.6
2229 * Perfect: 2048 31744
2230 * (32*64) (32*31/2 * 64)
2232 #define HASH_MIX(x, y, a) \
2234 y ^= x, x = rol32(x, 7),\
2235 x += y, y = rol32(y,20),\
2238 static inline unsigned int fold_hash(unsigned long x, unsigned long y)
2240 /* Use arch-optimized multiply if one exists */
2241 return __hash_32(y ^ __hash_32(x));
2247 * Return the hash of a string of known length. This is carfully
2248 * designed to match hash_name(), which is the more critical function.
2249 * In particular, we must end by hashing a final word containing 0..7
2250 * payload bytes, to match the way that hash_name() iterates until it
2251 * finds the delimiter after the name.
2253 unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
2255 unsigned long a, x = 0, y = (unsigned long)salt;
2260 a = load_unaligned_zeropad(name);
2261 if (len < sizeof(unsigned long))
2264 name += sizeof(unsigned long);
2265 len -= sizeof(unsigned long);
2267 x ^= a & bytemask_from_count(len);
2269 return fold_hash(x, y);
2271 EXPORT_SYMBOL(full_name_hash);
2273 /* Return the "hash_len" (hash and length) of a null-terminated string */
2274 u64 hashlen_string(const void *salt, const char *name)
2276 unsigned long a = 0, x = 0, y = (unsigned long)salt;
2277 unsigned long adata, mask, len;
2278 const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2285 len += sizeof(unsigned long);
2287 a = load_unaligned_zeropad(name+len);
2288 } while (!has_zero(a, &adata, &constants));
2290 adata = prep_zero_mask(a, adata, &constants);
2291 mask = create_zero_mask(adata);
2292 x ^= a & zero_bytemask(mask);
2294 return hashlen_create(fold_hash(x, y), len + find_zero(mask));
2296 EXPORT_SYMBOL(hashlen_string);
2299 * Calculate the length and hash of the path component, and
2300 * return the length as the result.
2302 static inline const char *hash_name(struct nameidata *nd,
2304 unsigned long *lastword)
2306 unsigned long a, b, x, y = (unsigned long)nd->path.dentry;
2307 unsigned long adata, bdata, mask, len;
2308 const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2311 * The first iteration is special, because it can result in
2312 * '.' and '..' and has no mixing other than the final fold.
2314 a = load_unaligned_zeropad(name);
2315 b = a ^ REPEAT_BYTE('/');
2316 if (has_zero(a, &adata, &constants) | has_zero(b, &bdata, &constants)) {
2317 adata = prep_zero_mask(a, adata, &constants);
2318 bdata = prep_zero_mask(b, bdata, &constants);
2319 mask = create_zero_mask(adata | bdata);
2320 a &= zero_bytemask(mask);
2322 len = find_zero(mask);
2323 nd->last.hash = fold_hash(a, y);
2332 len += sizeof(unsigned long);
2333 a = load_unaligned_zeropad(name+len);
2334 b = a ^ REPEAT_BYTE('/');
2335 } while (!(has_zero(a, &adata, &constants) | has_zero(b, &bdata, &constants)));
2337 adata = prep_zero_mask(a, adata, &constants);
2338 bdata = prep_zero_mask(b, bdata, &constants);
2339 mask = create_zero_mask(adata | bdata);
2340 a &= zero_bytemask(mask);
2342 len += find_zero(mask);
2343 *lastword = 0; // Multi-word components cannot be DOT or DOTDOT
2345 nd->last.hash = fold_hash(x, y);
2351 * Note that the 'last' word is always zero-masked, but
2352 * was loaded as a possibly big-endian word.
2355 #define LAST_WORD_IS_DOT (0x2eul << (BITS_PER_LONG-8))
2356 #define LAST_WORD_IS_DOTDOT (0x2e2eul << (BITS_PER_LONG-16))
2359 #else /* !CONFIG_DCACHE_WORD_ACCESS: Slow, byte-at-a-time version */
2361 /* Return the hash of a string of known length */
2362 unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
2364 unsigned long hash = init_name_hash(salt);
2366 hash = partial_name_hash((unsigned char)*name++, hash);
2367 return end_name_hash(hash);
2369 EXPORT_SYMBOL(full_name_hash);
2371 /* Return the "hash_len" (hash and length) of a null-terminated string */
2372 u64 hashlen_string(const void *salt, const char *name)
2374 unsigned long hash = init_name_hash(salt);
2375 unsigned long len = 0, c;
2377 c = (unsigned char)*name;
2380 hash = partial_name_hash(c, hash);
2381 c = (unsigned char)name[len];
2383 return hashlen_create(end_name_hash(hash), len);
2385 EXPORT_SYMBOL(hashlen_string);
2388 * We know there's a real path component here of at least
2391 static inline const char *hash_name(struct nameidata *nd, const char *name, unsigned long *lastword)
2393 unsigned long hash = init_name_hash(nd->path.dentry);
2394 unsigned long len = 0, c, last = 0;
2396 c = (unsigned char)*name;
2398 last = (last << 8) + c;
2400 hash = partial_name_hash(c, hash);
2401 c = (unsigned char)name[len];
2402 } while (c && c != '/');
2404 // This is reliable for DOT or DOTDOT, since the component
2405 // cannot contain NUL characters - top bits being zero means
2406 // we cannot have had any other pathnames.
2408 nd->last.hash = end_name_hash(hash);
2415 #ifndef LAST_WORD_IS_DOT
2416 #define LAST_WORD_IS_DOT 0x2e
2417 #define LAST_WORD_IS_DOTDOT 0x2e2e
2422 * This is the basic name resolution function, turning a pathname into
2423 * the final dentry. We expect 'base' to be positive and a directory.
2425 * Returns 0 and nd will have valid dentry and mnt on success.
2426 * Returns error and drops reference to input namei data on failure.
2428 static int link_path_walk(const char *name, struct nameidata *nd)
2430 int depth = 0; // depth <= nd->depth
2433 nd->last_type = LAST_ROOT;
2434 nd->flags |= LOOKUP_PARENT;
2436 return PTR_ERR(name);
2440 } while (unlikely(*name == '/'));
2442 if (unlikely(!*name)) {
2443 nd->dir_mode = 0; // short-circuit the 'hardening' idiocy
2447 /* At this point we know we have a real path component. */
2449 struct mnt_idmap *idmap;
2451 unsigned long lastword;
2453 idmap = mnt_idmap(nd->path.mnt);
2454 err = may_lookup(idmap, nd);
2458 nd->last.name = name;
2459 name = hash_name(nd, name, &lastword);
2462 case LAST_WORD_IS_DOTDOT:
2463 nd->last_type = LAST_DOTDOT;
2464 nd->state |= ND_JUMPED;
2467 case LAST_WORD_IS_DOT:
2468 nd->last_type = LAST_DOT;
2472 nd->last_type = LAST_NORM;
2473 nd->state &= ~ND_JUMPED;
2475 struct dentry *parent = nd->path.dentry;
2476 if (unlikely(parent->d_flags & DCACHE_OP_HASH)) {
2477 err = parent->d_op->d_hash(parent, &nd->last);
2486 * If it wasn't NUL, we know it was '/'. Skip that
2487 * slash, and continue until no more slashes.
2491 } while (unlikely(*name == '/'));
2492 if (unlikely(!*name)) {
2494 /* pathname or trailing symlink, done */
2496 nd->dir_vfsuid = i_uid_into_vfsuid(idmap, nd->inode);
2497 nd->dir_mode = nd->inode->i_mode;
2498 nd->flags &= ~LOOKUP_PARENT;
2501 /* last component of nested symlink */
2502 name = nd->stack[--depth].name;
2503 link = walk_component(nd, 0);
2505 /* not the last component */
2506 link = walk_component(nd, WALK_MORE);
2508 if (unlikely(link)) {
2510 return PTR_ERR(link);
2511 /* a symlink to follow */
2512 nd->stack[depth++].name = name;
2516 if (unlikely(!d_can_lookup(nd->path.dentry))) {
2517 if (nd->flags & LOOKUP_RCU) {
2518 if (!try_to_unlazy(nd))
2526 /* must be paired with terminate_walk() */
2527 static const char *path_init(struct nameidata *nd, unsigned flags)
2530 const char *s = nd->pathname;
2532 /* LOOKUP_CACHED requires RCU, ask caller to retry */
2533 if ((flags & (LOOKUP_RCU | LOOKUP_CACHED)) == LOOKUP_CACHED)
2534 return ERR_PTR(-EAGAIN);
2537 flags &= ~LOOKUP_RCU;
2538 if (flags & LOOKUP_RCU)
2541 nd->seq = nd->next_seq = 0;
2544 nd->state |= ND_JUMPED;
2546 nd->m_seq = __read_seqcount_begin(&mount_lock.seqcount);
2547 nd->r_seq = __read_seqcount_begin(&rename_lock.seqcount);
2550 if (nd->state & ND_ROOT_PRESET) {
2551 struct dentry *root = nd->root.dentry;
2552 struct inode *inode = root->d_inode;
2553 if (*s && unlikely(!d_can_lookup(root)))
2554 return ERR_PTR(-ENOTDIR);
2555 nd->path = nd->root;
2557 if (flags & LOOKUP_RCU) {
2558 nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
2559 nd->root_seq = nd->seq;
2561 path_get(&nd->path);
2566 nd->root.mnt = NULL;
2568 /* Absolute pathname -- fetch the root (LOOKUP_IN_ROOT uses nd->dfd). */
2569 if (*s == '/' && !(flags & LOOKUP_IN_ROOT)) {
2570 error = nd_jump_root(nd);
2571 if (unlikely(error))
2572 return ERR_PTR(error);
2576 /* Relative pathname -- get the starting-point it is relative to. */
2577 if (nd->dfd == AT_FDCWD) {
2578 if (flags & LOOKUP_RCU) {
2579 struct fs_struct *fs = current->fs;
2583 seq = read_seqcount_begin(&fs->seq);
2585 nd->inode = nd->path.dentry->d_inode;
2586 nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
2587 } while (read_seqcount_retry(&fs->seq, seq));
2589 get_fs_pwd(current->fs, &nd->path);
2590 nd->inode = nd->path.dentry->d_inode;
2593 /* Caller must check execute permissions on the starting path component */
2594 CLASS(fd_raw, f)(nd->dfd);
2595 struct dentry *dentry;
2598 return ERR_PTR(-EBADF);
2600 if (flags & LOOKUP_LINKAT_EMPTY) {
2601 if (fd_file(f)->f_cred != current_cred() &&
2602 !ns_capable(fd_file(f)->f_cred->user_ns, CAP_DAC_READ_SEARCH))
2603 return ERR_PTR(-ENOENT);
2606 dentry = fd_file(f)->f_path.dentry;
2608 if (*s && unlikely(!d_can_lookup(dentry)))
2609 return ERR_PTR(-ENOTDIR);
2611 nd->path = fd_file(f)->f_path;
2612 if (flags & LOOKUP_RCU) {
2613 nd->inode = nd->path.dentry->d_inode;
2614 nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
2616 path_get(&nd->path);
2617 nd->inode = nd->path.dentry->d_inode;
2621 /* For scoped-lookups we need to set the root to the dirfd as well. */
2622 if (flags & LOOKUP_IS_SCOPED) {
2623 nd->root = nd->path;
2624 if (flags & LOOKUP_RCU) {
2625 nd->root_seq = nd->seq;
2627 path_get(&nd->root);
2628 nd->state |= ND_ROOT_GRABBED;
2634 static inline const char *lookup_last(struct nameidata *nd)
2636 if (nd->last_type == LAST_NORM && nd->last.name[nd->last.len])
2637 nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
2639 return walk_component(nd, WALK_TRAILING);
2642 static int handle_lookup_down(struct nameidata *nd)
2644 if (!(nd->flags & LOOKUP_RCU))
2645 dget(nd->path.dentry);
2646 nd->next_seq = nd->seq;
2647 return PTR_ERR(step_into(nd, WALK_NOFOLLOW, nd->path.dentry));
2650 /* Returns 0 and nd will be valid on success; Returns error, otherwise. */
2651 static int path_lookupat(struct nameidata *nd, unsigned flags, struct path *path)
2653 const char *s = path_init(nd, flags);
2656 if (unlikely(flags & LOOKUP_DOWN) && !IS_ERR(s)) {
2657 err = handle_lookup_down(nd);
2658 if (unlikely(err < 0))
2662 while (!(err = link_path_walk(s, nd)) &&
2663 (s = lookup_last(nd)) != NULL)
2665 if (!err && unlikely(nd->flags & LOOKUP_MOUNTPOINT)) {
2666 err = handle_lookup_down(nd);
2667 nd->state &= ~ND_JUMPED; // no d_weak_revalidate(), please...
2670 err = complete_walk(nd);
2672 if (!err && nd->flags & LOOKUP_DIRECTORY)
2673 if (!d_can_lookup(nd->path.dentry))
2677 nd->path.mnt = NULL;
2678 nd->path.dentry = NULL;
2684 int filename_lookup(int dfd, struct filename *name, unsigned flags,
2685 struct path *path, struct path *root)
2688 struct nameidata nd;
2690 return PTR_ERR(name);
2691 set_nameidata(&nd, dfd, name, root);
2692 retval = path_lookupat(&nd, flags | LOOKUP_RCU, path);
2693 if (unlikely(retval == -ECHILD))
2694 retval = path_lookupat(&nd, flags, path);
2695 if (unlikely(retval == -ESTALE))
2696 retval = path_lookupat(&nd, flags | LOOKUP_REVAL, path);
2698 if (likely(!retval))
2699 audit_inode(name, path->dentry,
2700 flags & LOOKUP_MOUNTPOINT ? AUDIT_INODE_NOEVAL : 0);
2701 restore_nameidata();
2705 /* Returns 0 and nd will be valid on success; Returns error, otherwise. */
2706 static int path_parentat(struct nameidata *nd, unsigned flags,
2707 struct path *parent)
2709 const char *s = path_init(nd, flags);
2710 int err = link_path_walk(s, nd);
2712 err = complete_walk(nd);
2715 nd->path.mnt = NULL;
2716 nd->path.dentry = NULL;
2722 /* Note: this does not consume "name" */
2723 static int __filename_parentat(int dfd, struct filename *name,
2724 unsigned int flags, struct path *parent,
2725 struct qstr *last, int *type,
2726 const struct path *root)
2729 struct nameidata nd;
2732 return PTR_ERR(name);
2733 set_nameidata(&nd, dfd, name, root);
2734 retval = path_parentat(&nd, flags | LOOKUP_RCU, parent);
2735 if (unlikely(retval == -ECHILD))
2736 retval = path_parentat(&nd, flags, parent);
2737 if (unlikely(retval == -ESTALE))
2738 retval = path_parentat(&nd, flags | LOOKUP_REVAL, parent);
2739 if (likely(!retval)) {
2741 *type = nd.last_type;
2742 audit_inode(name, parent->dentry, AUDIT_INODE_PARENT);
2744 restore_nameidata();
2748 static int filename_parentat(int dfd, struct filename *name,
2749 unsigned int flags, struct path *parent,
2750 struct qstr *last, int *type)
2752 return __filename_parentat(dfd, name, flags, parent, last, type, NULL);
2755 /* does lookup, returns the object with parent locked */
2756 static struct dentry *__kern_path_locked(int dfd, struct filename *name, struct path *path)
2758 struct path parent_path __free(path_put) = {};
2763 error = filename_parentat(dfd, name, 0, &parent_path, &last, &type);
2765 return ERR_PTR(error);
2766 if (unlikely(type != LAST_NORM))
2767 return ERR_PTR(-EINVAL);
2768 inode_lock_nested(parent_path.dentry->d_inode, I_MUTEX_PARENT);
2769 d = lookup_one_qstr_excl(&last, parent_path.dentry, 0);
2771 inode_unlock(parent_path.dentry->d_inode);
2774 path->dentry = no_free_ptr(parent_path.dentry);
2775 path->mnt = no_free_ptr(parent_path.mnt);
2779 struct dentry *kern_path_locked_negative(const char *name, struct path *path)
2781 struct path parent_path __free(path_put) = {};
2782 struct filename *filename __free(putname) = getname_kernel(name);
2787 error = filename_parentat(AT_FDCWD, filename, 0, &parent_path, &last, &type);
2789 return ERR_PTR(error);
2790 if (unlikely(type != LAST_NORM))
2791 return ERR_PTR(-EINVAL);
2792 inode_lock_nested(parent_path.dentry->d_inode, I_MUTEX_PARENT);
2793 d = lookup_one_qstr_excl_raw(&last, parent_path.dentry, 0);
2795 inode_unlock(parent_path.dentry->d_inode);
2798 path->dentry = no_free_ptr(parent_path.dentry);
2799 path->mnt = no_free_ptr(parent_path.mnt);
2803 struct dentry *kern_path_locked(const char *name, struct path *path)
2805 struct filename *filename = getname_kernel(name);
2806 struct dentry *res = __kern_path_locked(AT_FDCWD, filename, path);
2812 struct dentry *user_path_locked_at(int dfd, const char __user *name, struct path *path)
2814 struct filename *filename = getname(name);
2815 struct dentry *res = __kern_path_locked(dfd, filename, path);
2820 EXPORT_SYMBOL(user_path_locked_at);
2822 int kern_path(const char *name, unsigned int flags, struct path *path)
2824 struct filename *filename = getname_kernel(name);
2825 int ret = filename_lookup(AT_FDCWD, filename, flags, path, NULL);
2831 EXPORT_SYMBOL(kern_path);
2834 * vfs_path_parent_lookup - lookup a parent path relative to a dentry-vfsmount pair
2835 * @filename: filename structure
2836 * @flags: lookup flags
2837 * @parent: pointer to struct path to fill
2838 * @last: last component
2839 * @type: type of the last component
2840 * @root: pointer to struct path of the base directory
2842 int vfs_path_parent_lookup(struct filename *filename, unsigned int flags,
2843 struct path *parent, struct qstr *last, int *type,
2844 const struct path *root)
2846 return __filename_parentat(AT_FDCWD, filename, flags, parent, last,
2849 EXPORT_SYMBOL(vfs_path_parent_lookup);
2852 * vfs_path_lookup - lookup a file path relative to a dentry-vfsmount pair
2853 * @dentry: pointer to dentry of the base directory
2854 * @mnt: pointer to vfs mount of the base directory
2855 * @name: pointer to file name
2856 * @flags: lookup flags
2857 * @path: pointer to struct path to fill
2859 int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt,
2860 const char *name, unsigned int flags,
2863 struct filename *filename;
2864 struct path root = {.mnt = mnt, .dentry = dentry};
2867 filename = getname_kernel(name);
2868 /* the first argument of filename_lookup() is ignored with root */
2869 ret = filename_lookup(AT_FDCWD, filename, flags, path, &root);
2873 EXPORT_SYMBOL(vfs_path_lookup);
2875 static int lookup_noperm_common(struct qstr *qname, struct dentry *base)
2877 const char *name = qname->name;
2878 u32 len = qname->len;
2880 qname->hash = full_name_hash(base, name, len);
2884 if (is_dot_dotdot(name, len))
2888 unsigned int c = *(const unsigned char *)name++;
2889 if (c == '/' || c == '\0')
2893 * See if the low-level filesystem might want
2894 * to use its own hash..
2896 if (base->d_flags & DCACHE_OP_HASH) {
2897 int err = base->d_op->d_hash(base, qname);
2904 static int lookup_one_common(struct mnt_idmap *idmap,
2905 struct qstr *qname, struct dentry *base)
2908 err = lookup_noperm_common(qname, base);
2911 return inode_permission(idmap, base->d_inode, MAY_EXEC);
2915 * try_lookup_noperm - filesystem helper to lookup single pathname component
2916 * @name: qstr storing pathname component to lookup
2917 * @base: base directory to lookup from
2919 * Look up a dentry by name in the dcache, returning NULL if it does not
2920 * currently exist. The function does not try to create a dentry and if one
2921 * is found it doesn't try to revalidate it.
2923 * Note that this routine is purely a helper for filesystem usage and should
2924 * not be called by generic code. It does no permission checking.
2926 * No locks need be held - only a counted reference to @base is needed.
2929 struct dentry *try_lookup_noperm(struct qstr *name, struct dentry *base)
2933 err = lookup_noperm_common(name, base);
2935 return ERR_PTR(err);
2937 return d_lookup(base, name);
2939 EXPORT_SYMBOL(try_lookup_noperm);
2942 * lookup_noperm - filesystem helper to lookup single pathname component
2943 * @name: qstr storing pathname component to lookup
2944 * @base: base directory to lookup from
2946 * Note that this routine is purely a helper for filesystem usage and should
2947 * not be called by generic code. It does no permission checking.
2949 * The caller must hold base->i_mutex.
2951 struct dentry *lookup_noperm(struct qstr *name, struct dentry *base)
2953 struct dentry *dentry;
2956 WARN_ON_ONCE(!inode_is_locked(base->d_inode));
2958 err = lookup_noperm_common(name, base);
2960 return ERR_PTR(err);
2962 dentry = lookup_dcache(name, base, 0);
2963 return dentry ? dentry : __lookup_slow(name, base, 0);
2965 EXPORT_SYMBOL(lookup_noperm);
2968 * lookup_one - lookup single pathname component
2969 * @idmap: idmap of the mount the lookup is performed from
2970 * @name: qstr holding pathname component to lookup
2971 * @base: base directory to lookup from
2973 * This can be used for in-kernel filesystem clients such as file servers.
2975 * The caller must hold base->i_mutex.
2977 struct dentry *lookup_one(struct mnt_idmap *idmap, struct qstr *name,
2978 struct dentry *base)
2980 struct dentry *dentry;
2983 WARN_ON_ONCE(!inode_is_locked(base->d_inode));
2985 err = lookup_one_common(idmap, name, base);
2987 return ERR_PTR(err);
2989 dentry = lookup_dcache(name, base, 0);
2990 return dentry ? dentry : __lookup_slow(name, base, 0);
2992 EXPORT_SYMBOL(lookup_one);
2995 * lookup_one_unlocked - lookup single pathname component
2996 * @idmap: idmap of the mount the lookup is performed from
2997 * @name: qstr olding pathname component to lookup
2998 * @base: base directory to lookup from
3000 * This can be used for in-kernel filesystem clients such as file servers.
3002 * Unlike lookup_one, it should be called without the parent
3003 * i_rwsem held, and will take the i_rwsem itself if necessary.
3005 struct dentry *lookup_one_unlocked(struct mnt_idmap *idmap, struct qstr *name,
3006 struct dentry *base)
3011 err = lookup_one_common(idmap, name, base);
3013 return ERR_PTR(err);
3015 ret = lookup_dcache(name, base, 0);
3017 ret = lookup_slow(name, base, 0);
3020 EXPORT_SYMBOL(lookup_one_unlocked);
3023 * lookup_one_positive_unlocked - lookup single pathname component
3024 * @idmap: idmap of the mount the lookup is performed from
3025 * @name: qstr holding pathname component to lookup
3026 * @base: base directory to lookup from
3028 * This helper will yield ERR_PTR(-ENOENT) on negatives. The helper returns
3029 * known positive or ERR_PTR(). This is what most of the users want.
3031 * Note that pinned negative with unlocked parent _can_ become positive at any
3032 * time, so callers of lookup_one_unlocked() need to be very careful; pinned
3033 * positives have >d_inode stable, so this one avoids such problems.
3035 * This can be used for in-kernel filesystem clients such as file servers.
3037 * The helper should be called without i_rwsem held.
3039 struct dentry *lookup_one_positive_unlocked(struct mnt_idmap *idmap,
3041 struct dentry *base)
3043 struct dentry *ret = lookup_one_unlocked(idmap, name, base);
3045 if (!IS_ERR(ret) && d_flags_negative(smp_load_acquire(&ret->d_flags))) {
3047 ret = ERR_PTR(-ENOENT);
3051 EXPORT_SYMBOL(lookup_one_positive_unlocked);
3054 * lookup_noperm_unlocked - filesystem helper to lookup single pathname component
3055 * @name: pathname component to lookup
3056 * @base: base directory to lookup from
3058 * Note that this routine is purely a helper for filesystem usage and should
3059 * not be called by generic code. It does no permission checking.
3061 * Unlike lookup_noperm(), it should be called without the parent
3062 * i_rwsem held, and will take the i_rwsem itself if necessary.
3064 * Unlike try_lookup_noperm() it *does* revalidate the dentry if it already
3067 struct dentry *lookup_noperm_unlocked(struct qstr *name, struct dentry *base)
3072 err = lookup_noperm_common(name, base);
3074 return ERR_PTR(err);
3076 ret = lookup_dcache(name, base, 0);
3078 ret = lookup_slow(name, base, 0);
3081 EXPORT_SYMBOL(lookup_noperm_unlocked);
3084 * Like lookup_noperm_unlocked(), except that it yields ERR_PTR(-ENOENT)
3085 * on negatives. Returns known positive or ERR_PTR(); that's what
3086 * most of the users want. Note that pinned negative with unlocked parent
3087 * _can_ become positive at any time, so callers of lookup_noperm_unlocked()
3088 * need to be very careful; pinned positives have ->d_inode stable, so
3089 * this one avoids such problems.
3091 struct dentry *lookup_noperm_positive_unlocked(struct qstr *name,
3092 struct dentry *base)
3096 ret = lookup_noperm_unlocked(name, base);
3097 if (!IS_ERR(ret) && d_flags_negative(smp_load_acquire(&ret->d_flags))) {
3099 ret = ERR_PTR(-ENOENT);
3103 EXPORT_SYMBOL(lookup_noperm_positive_unlocked);
3105 #ifdef CONFIG_UNIX98_PTYS
3106 int path_pts(struct path *path)
3108 /* Find something mounted on "pts" in the same directory as
3111 struct dentry *parent = dget_parent(path->dentry);
3112 struct dentry *child;
3113 struct qstr this = QSTR_INIT("pts", 3);
3115 if (unlikely(!path_connected(path->mnt, parent))) {
3120 path->dentry = parent;
3121 child = d_hash_and_lookup(parent, &this);
3122 if (IS_ERR_OR_NULL(child))
3125 path->dentry = child;
3127 follow_down(path, 0);
3132 int user_path_at(int dfd, const char __user *name, unsigned flags,
3135 struct filename *filename = getname_flags(name, flags);
3136 int ret = filename_lookup(dfd, filename, flags, path, NULL);
3141 EXPORT_SYMBOL(user_path_at);
3143 int __check_sticky(struct mnt_idmap *idmap, struct inode *dir,
3144 struct inode *inode)
3146 kuid_t fsuid = current_fsuid();
3148 if (vfsuid_eq_kuid(i_uid_into_vfsuid(idmap, inode), fsuid))
3150 if (vfsuid_eq_kuid(i_uid_into_vfsuid(idmap, dir), fsuid))
3152 return !capable_wrt_inode_uidgid(idmap, inode, CAP_FOWNER);
3154 EXPORT_SYMBOL(__check_sticky);
3157 * Check whether we can remove a link victim from directory dir, check
3158 * whether the type of victim is right.
3159 * 1. We can't do it if dir is read-only (done in permission())
3160 * 2. We should have write and exec permissions on dir
3161 * 3. We can't remove anything from append-only dir
3162 * 4. We can't do anything with immutable dir (done in permission())
3163 * 5. If the sticky bit on dir is set we should either
3164 * a. be owner of dir, or
3165 * b. be owner of victim, or
3166 * c. have CAP_FOWNER capability
3167 * 6. If the victim is append-only or immutable we can't do antyhing with
3168 * links pointing to it.
3169 * 7. If the victim has an unknown uid or gid we can't change the inode.
3170 * 8. If we were asked to remove a directory and victim isn't one - ENOTDIR.
3171 * 9. If we were asked to remove a non-directory and victim isn't one - EISDIR.
3172 * 10. We can't remove a root or mountpoint.
3173 * 11. We don't allow removal of NFS sillyrenamed files; it's handled by
3174 * nfs_async_unlink().
3176 static int may_delete(struct mnt_idmap *idmap, struct inode *dir,
3177 struct dentry *victim, bool isdir)
3179 struct inode *inode = d_backing_inode(victim);
3182 if (d_is_negative(victim))
3186 BUG_ON(victim->d_parent->d_inode != dir);
3188 /* Inode writeback is not safe when the uid or gid are invalid. */
3189 if (!vfsuid_valid(i_uid_into_vfsuid(idmap, inode)) ||
3190 !vfsgid_valid(i_gid_into_vfsgid(idmap, inode)))
3193 audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
3195 error = inode_permission(idmap, dir, MAY_WRITE | MAY_EXEC);
3201 if (check_sticky(idmap, dir, inode) || IS_APPEND(inode) ||
3202 IS_IMMUTABLE(inode) || IS_SWAPFILE(inode) ||
3203 HAS_UNMAPPED_ID(idmap, inode))
3206 if (!d_is_dir(victim))
3208 if (IS_ROOT(victim))
3210 } else if (d_is_dir(victim))
3212 if (IS_DEADDIR(dir))
3214 if (victim->d_flags & DCACHE_NFSFS_RENAMED)
3219 /* Check whether we can create an object with dentry child in directory
3221 * 1. We can't do it if child already exists (open has special treatment for
3222 * this case, but since we are inlined it's OK)
3223 * 2. We can't do it if dir is read-only (done in permission())
3224 * 3. We can't do it if the fs can't represent the fsuid or fsgid.
3225 * 4. We should have write and exec permissions on dir
3226 * 5. We can't do it if dir is immutable (done in permission())
3228 static inline int may_create(struct mnt_idmap *idmap,
3229 struct inode *dir, struct dentry *child)
3231 audit_inode_child(dir, child, AUDIT_TYPE_CHILD_CREATE);
3234 if (IS_DEADDIR(dir))
3236 if (!fsuidgid_has_mapping(dir->i_sb, idmap))
3239 return inode_permission(idmap, dir, MAY_WRITE | MAY_EXEC);
3242 // p1 != p2, both are on the same filesystem, ->s_vfs_rename_mutex is held
3243 static struct dentry *lock_two_directories(struct dentry *p1, struct dentry *p2)
3245 struct dentry *p = p1, *q = p2, *r;
3247 while ((r = p->d_parent) != p2 && r != p)
3250 // p is a child of p2 and an ancestor of p1 or p1 itself
3251 inode_lock_nested(p2->d_inode, I_MUTEX_PARENT);
3252 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT2);
3255 // p is the root of connected component that contains p1
3256 // p2 does not occur on the path from p to p1
3257 while ((r = q->d_parent) != p1 && r != p && r != q)
3260 // q is a child of p1 and an ancestor of p2 or p2 itself
3261 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
3262 inode_lock_nested(p2->d_inode, I_MUTEX_PARENT2);
3264 } else if (likely(r == p)) {
3265 // both p2 and p1 are descendents of p
3266 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
3267 inode_lock_nested(p2->d_inode, I_MUTEX_PARENT2);
3269 } else { // no common ancestor at the time we'd been called
3270 mutex_unlock(&p1->d_sb->s_vfs_rename_mutex);
3271 return ERR_PTR(-EXDEV);
3276 * p1 and p2 should be directories on the same fs.
3278 struct dentry *lock_rename(struct dentry *p1, struct dentry *p2)
3281 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
3285 mutex_lock(&p1->d_sb->s_vfs_rename_mutex);
3286 return lock_two_directories(p1, p2);
3288 EXPORT_SYMBOL(lock_rename);
3291 * c1 and p2 should be on the same fs.
3293 struct dentry *lock_rename_child(struct dentry *c1, struct dentry *p2)
3295 if (READ_ONCE(c1->d_parent) == p2) {
3297 * hopefully won't need to touch ->s_vfs_rename_mutex at all.
3299 inode_lock_nested(p2->d_inode, I_MUTEX_PARENT);
3301 * now that p2 is locked, nobody can move in or out of it,
3302 * so the test below is safe.
3304 if (likely(c1->d_parent == p2))
3308 * c1 got moved out of p2 while we'd been taking locks;
3309 * unlock and fall back to slow case.
3311 inode_unlock(p2->d_inode);
3314 mutex_lock(&c1->d_sb->s_vfs_rename_mutex);
3316 * nobody can move out of any directories on this fs.
3318 if (likely(c1->d_parent != p2))
3319 return lock_two_directories(c1->d_parent, p2);
3322 * c1 got moved into p2 while we were taking locks;
3323 * we need p2 locked and ->s_vfs_rename_mutex unlocked,
3324 * for consistency with lock_rename().
3326 inode_lock_nested(p2->d_inode, I_MUTEX_PARENT);
3327 mutex_unlock(&c1->d_sb->s_vfs_rename_mutex);
3330 EXPORT_SYMBOL(lock_rename_child);
3332 void unlock_rename(struct dentry *p1, struct dentry *p2)
3334 inode_unlock(p1->d_inode);
3336 inode_unlock(p2->d_inode);
3337 mutex_unlock(&p1->d_sb->s_vfs_rename_mutex);
3340 EXPORT_SYMBOL(unlock_rename);
3343 * vfs_prepare_mode - prepare the mode to be used for a new inode
3344 * @idmap: idmap of the mount the inode was found from
3345 * @dir: parent directory of the new inode
3346 * @mode: mode of the new inode
3347 * @mask_perms: allowed permission by the vfs
3348 * @type: type of file to be created
3350 * This helper consolidates and enforces vfs restrictions on the @mode of a new
3351 * object to be created.
3353 * Umask stripping depends on whether the filesystem supports POSIX ACLs (see
3354 * the kernel documentation for mode_strip_umask()). Moving umask stripping
3355 * after setgid stripping allows the same ordering for both non-POSIX ACL and
3356 * POSIX ACL supporting filesystems.
3358 * Note that it's currently valid for @type to be 0 if a directory is created.
3359 * Filesystems raise that flag individually and we need to check whether each
3360 * filesystem can deal with receiving S_IFDIR from the vfs before we enforce a
3363 * Returns: mode to be passed to the filesystem
3365 static inline umode_t vfs_prepare_mode(struct mnt_idmap *idmap,
3366 const struct inode *dir, umode_t mode,
3367 umode_t mask_perms, umode_t type)
3369 mode = mode_strip_sgid(idmap, dir, mode);
3370 mode = mode_strip_umask(dir, mode);
3373 * Apply the vfs mandated allowed permission mask and set the type of
3374 * file to be created before we call into the filesystem.
3376 mode &= (mask_perms & ~S_IFMT);
3377 mode |= (type & S_IFMT);
3383 * vfs_create - create new file
3384 * @idmap: idmap of the mount the inode was found from
3385 * @dir: inode of the parent directory
3386 * @dentry: dentry of the child file
3387 * @mode: mode of the child file
3388 * @want_excl: whether the file must not yet exist
3390 * Create a new file.
3392 * If the inode has been found through an idmapped mount the idmap of
3393 * the vfsmount must be passed through @idmap. This function will then take
3394 * care to map the inode according to @idmap before checking permissions.
3395 * On non-idmapped mounts or if permission checking is to be performed on the
3396 * raw inode simply pass @nop_mnt_idmap.
3398 int vfs_create(struct mnt_idmap *idmap, struct inode *dir,
3399 struct dentry *dentry, umode_t mode, bool want_excl)
3403 error = may_create(idmap, dir, dentry);
3407 if (!dir->i_op->create)
3408 return -EACCES; /* shouldn't it be ENOSYS? */
3410 mode = vfs_prepare_mode(idmap, dir, mode, S_IALLUGO, S_IFREG);
3411 error = security_inode_create(dir, dentry, mode);
3414 error = dir->i_op->create(idmap, dir, dentry, mode, want_excl);
3416 fsnotify_create(dir, dentry);
3419 EXPORT_SYMBOL(vfs_create);
3421 int vfs_mkobj(struct dentry *dentry, umode_t mode,
3422 int (*f)(struct dentry *, umode_t, void *),
3425 struct inode *dir = dentry->d_parent->d_inode;
3426 int error = may_create(&nop_mnt_idmap, dir, dentry);
3432 error = security_inode_create(dir, dentry, mode);
3435 error = f(dentry, mode, arg);
3437 fsnotify_create(dir, dentry);
3440 EXPORT_SYMBOL(vfs_mkobj);
3442 bool may_open_dev(const struct path *path)
3444 return !(path->mnt->mnt_flags & MNT_NODEV) &&
3445 !(path->mnt->mnt_sb->s_iflags & SB_I_NODEV);
3448 static int may_open(struct mnt_idmap *idmap, const struct path *path,
3449 int acc_mode, int flag)
3451 struct dentry *dentry = path->dentry;
3452 struct inode *inode = dentry->d_inode;
3458 switch (inode->i_mode & S_IFMT) {
3462 if (acc_mode & MAY_WRITE)
3464 if (acc_mode & MAY_EXEC)
3469 if (!may_open_dev(path))
3474 if (acc_mode & MAY_EXEC)
3479 if ((acc_mode & MAY_EXEC) && path_noexec(path))
3483 VFS_BUG_ON_INODE(!IS_ANON_FILE(inode), inode);
3486 error = inode_permission(idmap, inode, MAY_OPEN | acc_mode);
3491 * An append-only file must be opened in append mode for writing.
3493 if (IS_APPEND(inode)) {
3494 if ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND))
3500 /* O_NOATIME can only be set by the owner or superuser */
3501 if (flag & O_NOATIME && !inode_owner_or_capable(idmap, inode))
3507 static int handle_truncate(struct mnt_idmap *idmap, struct file *filp)
3509 const struct path *path = &filp->f_path;
3510 struct inode *inode = path->dentry->d_inode;
3511 int error = get_write_access(inode);
3515 error = security_file_truncate(filp);
3517 error = do_truncate(idmap, path->dentry, 0,
3518 ATTR_MTIME|ATTR_CTIME|ATTR_OPEN,
3521 put_write_access(inode);
3525 static inline int open_to_namei_flags(int flag)
3527 if ((flag & O_ACCMODE) == 3)
3532 static int may_o_create(struct mnt_idmap *idmap,
3533 const struct path *dir, struct dentry *dentry,
3536 int error = security_path_mknod(dir, dentry, mode, 0);
3540 if (!fsuidgid_has_mapping(dir->dentry->d_sb, idmap))
3543 error = inode_permission(idmap, dir->dentry->d_inode,
3544 MAY_WRITE | MAY_EXEC);
3548 return security_inode_create(dir->dentry->d_inode, dentry, mode);
3552 * Attempt to atomically look up, create and open a file from a negative
3555 * Returns 0 if successful. The file will have been created and attached to
3556 * @file by the filesystem calling finish_open().
3558 * If the file was looked up only or didn't need creating, FMODE_OPENED won't
3559 * be set. The caller will need to perform the open themselves. @path will
3560 * have been updated to point to the new dentry. This may be negative.
3562 * Returns an error code otherwise.
3564 static struct dentry *atomic_open(struct nameidata *nd, struct dentry *dentry,
3566 int open_flag, umode_t mode)
3568 struct dentry *const DENTRY_NOT_SET = (void *) -1UL;
3569 struct inode *dir = nd->path.dentry->d_inode;
3572 if (nd->flags & LOOKUP_DIRECTORY)
3573 open_flag |= O_DIRECTORY;
3575 file->f_path.dentry = DENTRY_NOT_SET;
3576 file->f_path.mnt = nd->path.mnt;
3577 error = dir->i_op->atomic_open(dir, dentry, file,
3578 open_to_namei_flags(open_flag), mode);
3579 d_lookup_done(dentry);
3581 if (file->f_mode & FMODE_OPENED) {
3582 if (unlikely(dentry != file->f_path.dentry)) {
3584 dentry = dget(file->f_path.dentry);
3586 } else if (WARN_ON(file->f_path.dentry == DENTRY_NOT_SET)) {
3589 if (file->f_path.dentry) {
3591 dentry = file->f_path.dentry;
3593 if (unlikely(d_is_negative(dentry)))
3599 dentry = ERR_PTR(error);
3605 * Look up and maybe create and open the last component.
3607 * Must be called with parent locked (exclusive in O_CREAT case).
3609 * Returns 0 on success, that is, if
3610 * the file was successfully atomically created (if necessary) and opened, or
3611 * the file was not completely opened at this time, though lookups and
3612 * creations were performed.
3613 * These case are distinguished by presence of FMODE_OPENED on file->f_mode.
3614 * In the latter case dentry returned in @path might be negative if O_CREAT
3615 * hadn't been specified.
3617 * An error code is returned on failure.
3619 static struct dentry *lookup_open(struct nameidata *nd, struct file *file,
3620 const struct open_flags *op,
3623 struct mnt_idmap *idmap;
3624 struct dentry *dir = nd->path.dentry;
3625 struct inode *dir_inode = dir->d_inode;
3626 int open_flag = op->open_flag;
3627 struct dentry *dentry;
3628 int error, create_error = 0;
3629 umode_t mode = op->mode;
3630 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
3632 if (unlikely(IS_DEADDIR(dir_inode)))
3633 return ERR_PTR(-ENOENT);
3635 file->f_mode &= ~FMODE_CREATED;
3636 dentry = d_lookup(dir, &nd->last);
3639 dentry = d_alloc_parallel(dir, &nd->last, &wq);
3643 if (d_in_lookup(dentry))
3646 error = d_revalidate(dir_inode, &nd->last, dentry, nd->flags);
3647 if (likely(error > 0))
3651 d_invalidate(dentry);
3655 if (dentry->d_inode) {
3656 /* Cached positive dentry: will open in f_op->open */
3660 if (open_flag & O_CREAT)
3661 audit_inode(nd->name, dir, AUDIT_INODE_PARENT);
3664 * Checking write permission is tricky, bacuse we don't know if we are
3665 * going to actually need it: O_CREAT opens should work as long as the
3666 * file exists. But checking existence breaks atomicity. The trick is
3667 * to check access and if not granted clear O_CREAT from the flags.
3669 * Another problem is returing the "right" error value (e.g. for an
3670 * O_EXCL open we want to return EEXIST not EROFS).
3672 if (unlikely(!got_write))
3673 open_flag &= ~O_TRUNC;
3674 idmap = mnt_idmap(nd->path.mnt);
3675 if (open_flag & O_CREAT) {
3676 if (open_flag & O_EXCL)
3677 open_flag &= ~O_TRUNC;
3678 mode = vfs_prepare_mode(idmap, dir->d_inode, mode, mode, mode);
3679 if (likely(got_write))
3680 create_error = may_o_create(idmap, &nd->path,
3683 create_error = -EROFS;
3686 open_flag &= ~O_CREAT;
3687 if (dir_inode->i_op->atomic_open) {
3688 dentry = atomic_open(nd, dentry, file, open_flag, mode);
3689 if (unlikely(create_error) && dentry == ERR_PTR(-ENOENT))
3690 dentry = ERR_PTR(create_error);
3694 if (d_in_lookup(dentry)) {
3695 struct dentry *res = dir_inode->i_op->lookup(dir_inode, dentry,
3697 d_lookup_done(dentry);
3698 if (unlikely(res)) {
3700 error = PTR_ERR(res);
3708 /* Negative dentry, just create the file */
3709 if (!dentry->d_inode && (open_flag & O_CREAT)) {
3710 file->f_mode |= FMODE_CREATED;
3711 audit_inode_child(dir_inode, dentry, AUDIT_TYPE_CHILD_CREATE);
3712 if (!dir_inode->i_op->create) {
3717 error = dir_inode->i_op->create(idmap, dir_inode, dentry,
3718 mode, open_flag & O_EXCL);
3722 if (unlikely(create_error) && !dentry->d_inode) {
3723 error = create_error;
3730 return ERR_PTR(error);
3733 static inline bool trailing_slashes(struct nameidata *nd)
3735 return (bool)nd->last.name[nd->last.len];
3738 static struct dentry *lookup_fast_for_open(struct nameidata *nd, int open_flag)
3740 struct dentry *dentry;
3742 if (open_flag & O_CREAT) {
3743 if (trailing_slashes(nd))
3744 return ERR_PTR(-EISDIR);
3746 /* Don't bother on an O_EXCL create */
3747 if (open_flag & O_EXCL)
3751 if (trailing_slashes(nd))
3752 nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
3754 dentry = lookup_fast(nd);
3755 if (IS_ERR_OR_NULL(dentry))
3758 if (open_flag & O_CREAT) {
3759 /* Discard negative dentries. Need inode_lock to do the create */
3760 if (!dentry->d_inode) {
3761 if (!(nd->flags & LOOKUP_RCU))
3769 static const char *open_last_lookups(struct nameidata *nd,
3770 struct file *file, const struct open_flags *op)
3772 struct dentry *dir = nd->path.dentry;
3773 int open_flag = op->open_flag;
3774 bool got_write = false;
3775 struct dentry *dentry;
3778 nd->flags |= op->intent;
3780 if (nd->last_type != LAST_NORM) {
3783 return handle_dots(nd, nd->last_type);
3786 /* We _can_ be in RCU mode here */
3787 dentry = lookup_fast_for_open(nd, open_flag);
3789 return ERR_CAST(dentry);
3794 if (!(open_flag & O_CREAT)) {
3795 if (WARN_ON_ONCE(nd->flags & LOOKUP_RCU))
3796 return ERR_PTR(-ECHILD);
3798 if (nd->flags & LOOKUP_RCU) {
3799 if (!try_to_unlazy(nd))
3800 return ERR_PTR(-ECHILD);
3804 if (open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) {
3805 got_write = !mnt_want_write(nd->path.mnt);
3807 * do _not_ fail yet - we might not need that or fail with
3808 * a different error; let lookup_open() decide; we'll be
3809 * dropping this one anyway.
3812 if (open_flag & O_CREAT)
3813 inode_lock(dir->d_inode);
3815 inode_lock_shared(dir->d_inode);
3816 dentry = lookup_open(nd, file, op, got_write);
3817 if (!IS_ERR(dentry)) {
3818 if (file->f_mode & FMODE_CREATED)
3819 fsnotify_create(dir->d_inode, dentry);
3820 if (file->f_mode & FMODE_OPENED)
3821 fsnotify_open(file);
3823 if (open_flag & O_CREAT)
3824 inode_unlock(dir->d_inode);
3826 inode_unlock_shared(dir->d_inode);
3829 mnt_drop_write(nd->path.mnt);
3832 return ERR_CAST(dentry);
3834 if (file->f_mode & (FMODE_OPENED | FMODE_CREATED)) {
3835 dput(nd->path.dentry);
3836 nd->path.dentry = dentry;
3843 res = step_into(nd, WALK_TRAILING, dentry);
3845 nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL);
3850 * Handle the last step of open()
3852 static int do_open(struct nameidata *nd,
3853 struct file *file, const struct open_flags *op)
3855 struct mnt_idmap *idmap;
3856 int open_flag = op->open_flag;
3861 if (!(file->f_mode & (FMODE_OPENED | FMODE_CREATED))) {
3862 error = complete_walk(nd);
3866 if (!(file->f_mode & FMODE_CREATED))
3867 audit_inode(nd->name, nd->path.dentry, 0);
3868 idmap = mnt_idmap(nd->path.mnt);
3869 if (open_flag & O_CREAT) {
3870 if ((open_flag & O_EXCL) && !(file->f_mode & FMODE_CREATED))
3872 if (d_is_dir(nd->path.dentry))
3874 error = may_create_in_sticky(idmap, nd,
3875 d_backing_inode(nd->path.dentry));
3876 if (unlikely(error))
3879 if ((nd->flags & LOOKUP_DIRECTORY) && !d_can_lookup(nd->path.dentry))
3882 do_truncate = false;
3883 acc_mode = op->acc_mode;
3884 if (file->f_mode & FMODE_CREATED) {
3885 /* Don't check for write permission, don't truncate */
3886 open_flag &= ~O_TRUNC;
3888 } else if (d_is_reg(nd->path.dentry) && open_flag & O_TRUNC) {
3889 error = mnt_want_write(nd->path.mnt);
3894 error = may_open(idmap, &nd->path, acc_mode, open_flag);
3895 if (!error && !(file->f_mode & FMODE_OPENED))
3896 error = vfs_open(&nd->path, file);
3898 error = security_file_post_open(file, op->acc_mode);
3899 if (!error && do_truncate)
3900 error = handle_truncate(idmap, file);
3901 if (unlikely(error > 0)) {
3906 mnt_drop_write(nd->path.mnt);
3911 * vfs_tmpfile - create tmpfile
3912 * @idmap: idmap of the mount the inode was found from
3913 * @parentpath: pointer to the path of the base directory
3914 * @file: file descriptor of the new tmpfile
3915 * @mode: mode of the new tmpfile
3917 * Create a temporary file.
3919 * If the inode has been found through an idmapped mount the idmap of
3920 * the vfsmount must be passed through @idmap. This function will then take
3921 * care to map the inode according to @idmap before checking permissions.
3922 * On non-idmapped mounts or if permission checking is to be performed on the
3923 * raw inode simply pass @nop_mnt_idmap.
3925 int vfs_tmpfile(struct mnt_idmap *idmap,
3926 const struct path *parentpath,
3927 struct file *file, umode_t mode)
3929 struct dentry *child;
3930 struct inode *dir = d_inode(parentpath->dentry);
3931 struct inode *inode;
3933 int open_flag = file->f_flags;
3935 /* we want directory to be writable */
3936 error = inode_permission(idmap, dir, MAY_WRITE | MAY_EXEC);
3939 if (!dir->i_op->tmpfile)
3941 child = d_alloc(parentpath->dentry, &slash_name);
3942 if (unlikely(!child))
3944 file->f_path.mnt = parentpath->mnt;
3945 file->f_path.dentry = child;
3946 mode = vfs_prepare_mode(idmap, dir, mode, mode, mode);
3947 error = dir->i_op->tmpfile(idmap, dir, file, mode);
3949 if (file->f_mode & FMODE_OPENED)
3950 fsnotify_open(file);
3953 /* Don't check for other permissions, the inode was just created */
3954 error = may_open(idmap, &file->f_path, 0, file->f_flags);
3957 inode = file_inode(file);
3958 if (!(open_flag & O_EXCL)) {
3959 spin_lock(&inode->i_lock);
3960 inode->i_state |= I_LINKABLE;
3961 spin_unlock(&inode->i_lock);
3963 security_inode_post_create_tmpfile(idmap, inode);
3968 * kernel_tmpfile_open - open a tmpfile for kernel internal use
3969 * @idmap: idmap of the mount the inode was found from
3970 * @parentpath: path of the base directory
3971 * @mode: mode of the new tmpfile
3973 * @cred: credentials for open
3975 * Create and open a temporary file. The file is not accounted in nr_files,
3976 * hence this is only for kernel internal use, and must not be installed into
3977 * file tables or such.
3979 struct file *kernel_tmpfile_open(struct mnt_idmap *idmap,
3980 const struct path *parentpath,
3981 umode_t mode, int open_flag,
3982 const struct cred *cred)
3987 file = alloc_empty_file_noaccount(open_flag, cred);
3991 error = vfs_tmpfile(idmap, parentpath, file, mode);
3994 file = ERR_PTR(error);
3998 EXPORT_SYMBOL(kernel_tmpfile_open);
4000 static int do_tmpfile(struct nameidata *nd, unsigned flags,
4001 const struct open_flags *op,
4005 int error = path_lookupat(nd, flags | LOOKUP_DIRECTORY, &path);
4007 if (unlikely(error))
4009 error = mnt_want_write(path.mnt);
4010 if (unlikely(error))
4012 error = vfs_tmpfile(mnt_idmap(path.mnt), &path, file, op->mode);
4015 audit_inode(nd->name, file->f_path.dentry, 0);
4017 mnt_drop_write(path.mnt);
4023 static int do_o_path(struct nameidata *nd, unsigned flags, struct file *file)
4026 int error = path_lookupat(nd, flags, &path);
4028 audit_inode(nd->name, path.dentry, 0);
4029 error = vfs_open(&path, file);
4035 static struct file *path_openat(struct nameidata *nd,
4036 const struct open_flags *op, unsigned flags)
4041 file = alloc_empty_file(op->open_flag, current_cred());
4045 if (unlikely(file->f_flags & __O_TMPFILE)) {
4046 error = do_tmpfile(nd, flags, op, file);
4047 } else if (unlikely(file->f_flags & O_PATH)) {
4048 error = do_o_path(nd, flags, file);
4050 const char *s = path_init(nd, flags);
4051 while (!(error = link_path_walk(s, nd)) &&
4052 (s = open_last_lookups(nd, file, op)) != NULL)
4055 error = do_open(nd, file, op);
4058 if (likely(!error)) {
4059 if (likely(file->f_mode & FMODE_OPENED))
4065 if (error == -EOPENSTALE) {
4066 if (flags & LOOKUP_RCU)
4071 return ERR_PTR(error);
4074 struct file *do_filp_open(int dfd, struct filename *pathname,
4075 const struct open_flags *op)
4077 struct nameidata nd;
4078 int flags = op->lookup_flags;
4081 set_nameidata(&nd, dfd, pathname, NULL);
4082 filp = path_openat(&nd, op, flags | LOOKUP_RCU);
4083 if (unlikely(filp == ERR_PTR(-ECHILD)))
4084 filp = path_openat(&nd, op, flags);
4085 if (unlikely(filp == ERR_PTR(-ESTALE)))
4086 filp = path_openat(&nd, op, flags | LOOKUP_REVAL);
4087 restore_nameidata();
4091 struct file *do_file_open_root(const struct path *root,
4092 const char *name, const struct open_flags *op)
4094 struct nameidata nd;
4096 struct filename *filename;
4097 int flags = op->lookup_flags;
4099 if (d_is_symlink(root->dentry) && op->intent & LOOKUP_OPEN)
4100 return ERR_PTR(-ELOOP);
4102 filename = getname_kernel(name);
4103 if (IS_ERR(filename))
4104 return ERR_CAST(filename);
4106 set_nameidata(&nd, -1, filename, root);
4107 file = path_openat(&nd, op, flags | LOOKUP_RCU);
4108 if (unlikely(file == ERR_PTR(-ECHILD)))
4109 file = path_openat(&nd, op, flags);
4110 if (unlikely(file == ERR_PTR(-ESTALE)))
4111 file = path_openat(&nd, op, flags | LOOKUP_REVAL);
4112 restore_nameidata();
4117 static struct dentry *filename_create(int dfd, struct filename *name,
4118 struct path *path, unsigned int lookup_flags)
4120 struct dentry *dentry = ERR_PTR(-EEXIST);
4122 bool want_dir = lookup_flags & LOOKUP_DIRECTORY;
4123 unsigned int reval_flag = lookup_flags & LOOKUP_REVAL;
4124 unsigned int create_flags = LOOKUP_CREATE | LOOKUP_EXCL;
4129 error = filename_parentat(dfd, name, reval_flag, path, &last, &type);
4131 return ERR_PTR(error);
4134 * Yucky last component or no last component at all?
4135 * (foo/., foo/.., /////)
4137 if (unlikely(type != LAST_NORM))
4140 /* don't fail immediately if it's r/o, at least try to report other errors */
4141 err2 = mnt_want_write(path->mnt);
4143 * Do the final lookup. Suppress 'create' if there is a trailing
4144 * '/', and a directory wasn't requested.
4146 if (last.name[last.len] && !want_dir)
4147 create_flags &= ~LOOKUP_CREATE;
4148 inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
4149 dentry = lookup_one_qstr_excl(&last, path->dentry,
4150 reval_flag | create_flags);
4154 if (unlikely(err2)) {
4161 dentry = ERR_PTR(error);
4163 inode_unlock(path->dentry->d_inode);
4165 mnt_drop_write(path->mnt);
4171 struct dentry *kern_path_create(int dfd, const char *pathname,
4172 struct path *path, unsigned int lookup_flags)
4174 struct filename *filename = getname_kernel(pathname);
4175 struct dentry *res = filename_create(dfd, filename, path, lookup_flags);
4180 EXPORT_SYMBOL(kern_path_create);
4182 void done_path_create(struct path *path, struct dentry *dentry)
4184 if (!IS_ERR(dentry))
4186 inode_unlock(path->dentry->d_inode);
4187 mnt_drop_write(path->mnt);
4190 EXPORT_SYMBOL(done_path_create);
4192 inline struct dentry *user_path_create(int dfd, const char __user *pathname,
4193 struct path *path, unsigned int lookup_flags)
4195 struct filename *filename = getname(pathname);
4196 struct dentry *res = filename_create(dfd, filename, path, lookup_flags);
4201 EXPORT_SYMBOL(user_path_create);
4204 * vfs_mknod - create device node or file
4205 * @idmap: idmap of the mount the inode was found from
4206 * @dir: inode of the parent directory
4207 * @dentry: dentry of the child device node
4208 * @mode: mode of the child device node
4209 * @dev: device number of device to create
4211 * Create a device node or file.
4213 * If the inode has been found through an idmapped mount the idmap of
4214 * the vfsmount must be passed through @idmap. This function will then take
4215 * care to map the inode according to @idmap before checking permissions.
4216 * On non-idmapped mounts or if permission checking is to be performed on the
4217 * raw inode simply pass @nop_mnt_idmap.
4219 int vfs_mknod(struct mnt_idmap *idmap, struct inode *dir,
4220 struct dentry *dentry, umode_t mode, dev_t dev)
4222 bool is_whiteout = S_ISCHR(mode) && dev == WHITEOUT_DEV;
4223 int error = may_create(idmap, dir, dentry);
4228 if ((S_ISCHR(mode) || S_ISBLK(mode)) && !is_whiteout &&
4229 !capable(CAP_MKNOD))
4232 if (!dir->i_op->mknod)
4235 mode = vfs_prepare_mode(idmap, dir, mode, mode, mode);
4236 error = devcgroup_inode_mknod(mode, dev);
4240 error = security_inode_mknod(dir, dentry, mode, dev);
4244 error = dir->i_op->mknod(idmap, dir, dentry, mode, dev);
4246 fsnotify_create(dir, dentry);
4249 EXPORT_SYMBOL(vfs_mknod);
4251 static int may_mknod(umode_t mode)
4253 switch (mode & S_IFMT) {
4259 case 0: /* zero mode translates to S_IFREG */
4268 static int do_mknodat(int dfd, struct filename *name, umode_t mode,
4271 struct mnt_idmap *idmap;
4272 struct dentry *dentry;
4275 unsigned int lookup_flags = 0;
4277 error = may_mknod(mode);
4281 dentry = filename_create(dfd, name, &path, lookup_flags);
4282 error = PTR_ERR(dentry);
4286 error = security_path_mknod(&path, dentry,
4287 mode_strip_umask(path.dentry->d_inode, mode), dev);
4291 idmap = mnt_idmap(path.mnt);
4292 switch (mode & S_IFMT) {
4293 case 0: case S_IFREG:
4294 error = vfs_create(idmap, path.dentry->d_inode,
4295 dentry, mode, true);
4297 security_path_post_mknod(idmap, dentry);
4299 case S_IFCHR: case S_IFBLK:
4300 error = vfs_mknod(idmap, path.dentry->d_inode,
4301 dentry, mode, new_decode_dev(dev));
4303 case S_IFIFO: case S_IFSOCK:
4304 error = vfs_mknod(idmap, path.dentry->d_inode,
4309 done_path_create(&path, dentry);
4310 if (retry_estale(error, lookup_flags)) {
4311 lookup_flags |= LOOKUP_REVAL;
4319 SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, umode_t, mode,
4322 return do_mknodat(dfd, getname(filename), mode, dev);
4325 SYSCALL_DEFINE3(mknod, const char __user *, filename, umode_t, mode, unsigned, dev)
4327 return do_mknodat(AT_FDCWD, getname(filename), mode, dev);
4331 * vfs_mkdir - create directory returning correct dentry if possible
4332 * @idmap: idmap of the mount the inode was found from
4333 * @dir: inode of the parent directory
4334 * @dentry: dentry of the child directory
4335 * @mode: mode of the child directory
4337 * Create a directory.
4339 * If the inode has been found through an idmapped mount the idmap of
4340 * the vfsmount must be passed through @idmap. This function will then take
4341 * care to map the inode according to @idmap before checking permissions.
4342 * On non-idmapped mounts or if permission checking is to be performed on the
4343 * raw inode simply pass @nop_mnt_idmap.
4345 * In the event that the filesystem does not use the *@dentry but leaves it
4346 * negative or unhashes it and possibly splices a different one returning it,
4347 * the original dentry is dput() and the alternate is returned.
4349 * In case of an error the dentry is dput() and an ERR_PTR() is returned.
4351 struct dentry *vfs_mkdir(struct mnt_idmap *idmap, struct inode *dir,
4352 struct dentry *dentry, umode_t mode)
4355 unsigned max_links = dir->i_sb->s_max_links;
4358 error = may_create(idmap, dir, dentry);
4363 if (!dir->i_op->mkdir)
4366 mode = vfs_prepare_mode(idmap, dir, mode, S_IRWXUGO | S_ISVTX, 0);
4367 error = security_inode_mkdir(dir, dentry, mode);
4372 if (max_links && dir->i_nlink >= max_links)
4375 de = dir->i_op->mkdir(idmap, dir, dentry, mode);
4376 error = PTR_ERR(de);
4383 fsnotify_mkdir(dir, dentry);
4388 return ERR_PTR(error);
4390 EXPORT_SYMBOL(vfs_mkdir);
4392 int do_mkdirat(int dfd, struct filename *name, umode_t mode)
4394 struct dentry *dentry;
4397 unsigned int lookup_flags = LOOKUP_DIRECTORY;
4400 dentry = filename_create(dfd, name, &path, lookup_flags);
4401 error = PTR_ERR(dentry);
4405 error = security_path_mkdir(&path, dentry,
4406 mode_strip_umask(path.dentry->d_inode, mode));
4408 dentry = vfs_mkdir(mnt_idmap(path.mnt), path.dentry->d_inode,
4411 error = PTR_ERR(dentry);
4413 done_path_create(&path, dentry);
4414 if (retry_estale(error, lookup_flags)) {
4415 lookup_flags |= LOOKUP_REVAL;
4423 SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, umode_t, mode)
4425 return do_mkdirat(dfd, getname(pathname), mode);
4428 SYSCALL_DEFINE2(mkdir, const char __user *, pathname, umode_t, mode)
4430 return do_mkdirat(AT_FDCWD, getname(pathname), mode);
4434 * vfs_rmdir - remove directory
4435 * @idmap: idmap of the mount the inode was found from
4436 * @dir: inode of the parent directory
4437 * @dentry: dentry of the child directory
4439 * Remove a directory.
4441 * If the inode has been found through an idmapped mount the idmap of
4442 * the vfsmount must be passed through @idmap. This function will then take
4443 * care to map the inode according to @idmap before checking permissions.
4444 * On non-idmapped mounts or if permission checking is to be performed on the
4445 * raw inode simply pass @nop_mnt_idmap.
4447 int vfs_rmdir(struct mnt_idmap *idmap, struct inode *dir,
4448 struct dentry *dentry)
4450 int error = may_delete(idmap, dir, dentry, 1);
4455 if (!dir->i_op->rmdir)
4459 inode_lock(dentry->d_inode);
4462 if (is_local_mountpoint(dentry) ||
4463 (dentry->d_inode->i_flags & S_KERNEL_FILE))
4466 error = security_inode_rmdir(dir, dentry);
4470 error = dir->i_op->rmdir(dir, dentry);
4474 shrink_dcache_parent(dentry);
4475 dentry->d_inode->i_flags |= S_DEAD;
4477 detach_mounts(dentry);
4480 inode_unlock(dentry->d_inode);
4483 d_delete_notify(dir, dentry);
4486 EXPORT_SYMBOL(vfs_rmdir);
4488 int do_rmdir(int dfd, struct filename *name)
4491 struct dentry *dentry;
4495 unsigned int lookup_flags = 0;
4497 error = filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
4513 error = mnt_want_write(path.mnt);
4517 inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
4518 dentry = lookup_one_qstr_excl(&last, path.dentry, lookup_flags);
4519 error = PTR_ERR(dentry);
4522 error = security_path_rmdir(&path, dentry);
4525 error = vfs_rmdir(mnt_idmap(path.mnt), path.dentry->d_inode, dentry);
4529 inode_unlock(path.dentry->d_inode);
4530 mnt_drop_write(path.mnt);
4533 if (retry_estale(error, lookup_flags)) {
4534 lookup_flags |= LOOKUP_REVAL;
4542 SYSCALL_DEFINE1(rmdir, const char __user *, pathname)
4544 return do_rmdir(AT_FDCWD, getname(pathname));
4548 * vfs_unlink - unlink a filesystem object
4549 * @idmap: idmap of the mount the inode was found from
4550 * @dir: parent directory
4552 * @delegated_inode: returns victim inode, if the inode is delegated.
4554 * The caller must hold dir->i_mutex.
4556 * If vfs_unlink discovers a delegation, it will return -EWOULDBLOCK and
4557 * return a reference to the inode in delegated_inode. The caller
4558 * should then break the delegation on that inode and retry. Because
4559 * breaking a delegation may take a long time, the caller should drop
4560 * dir->i_mutex before doing so.
4562 * Alternatively, a caller may pass NULL for delegated_inode. This may
4563 * be appropriate for callers that expect the underlying filesystem not
4564 * to be NFS exported.
4566 * If the inode has been found through an idmapped mount the idmap of
4567 * the vfsmount must be passed through @idmap. This function will then take
4568 * care to map the inode according to @idmap before checking permissions.
4569 * On non-idmapped mounts or if permission checking is to be performed on the
4570 * raw inode simply pass @nop_mnt_idmap.
4572 int vfs_unlink(struct mnt_idmap *idmap, struct inode *dir,
4573 struct dentry *dentry, struct inode **delegated_inode)
4575 struct inode *target = dentry->d_inode;
4576 int error = may_delete(idmap, dir, dentry, 0);
4581 if (!dir->i_op->unlink)
4585 if (IS_SWAPFILE(target))
4587 else if (is_local_mountpoint(dentry))
4590 error = security_inode_unlink(dir, dentry);
4592 error = try_break_deleg(target, delegated_inode);
4595 error = dir->i_op->unlink(dir, dentry);
4598 detach_mounts(dentry);
4603 inode_unlock(target);
4605 /* We don't d_delete() NFS sillyrenamed files--they still exist. */
4606 if (!error && dentry->d_flags & DCACHE_NFSFS_RENAMED) {
4607 fsnotify_unlink(dir, dentry);
4608 } else if (!error) {
4609 fsnotify_link_count(target);
4610 d_delete_notify(dir, dentry);
4615 EXPORT_SYMBOL(vfs_unlink);
4618 * Make sure that the actual truncation of the file will occur outside its
4619 * directory's i_mutex. Truncate can take a long time if there is a lot of
4620 * writeout happening, and we don't want to prevent access to the directory
4621 * while waiting on the I/O.
4623 int do_unlinkat(int dfd, struct filename *name)
4626 struct dentry *dentry;
4630 struct inode *inode = NULL;
4631 struct inode *delegated_inode = NULL;
4632 unsigned int lookup_flags = 0;
4634 error = filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
4639 if (type != LAST_NORM)
4642 error = mnt_want_write(path.mnt);
4646 inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
4647 dentry = lookup_one_qstr_excl(&last, path.dentry, lookup_flags);
4648 error = PTR_ERR(dentry);
4649 if (!IS_ERR(dentry)) {
4651 /* Why not before? Because we want correct error value */
4652 if (last.name[last.len])
4654 inode = dentry->d_inode;
4656 error = security_path_unlink(&path, dentry);
4659 error = vfs_unlink(mnt_idmap(path.mnt), path.dentry->d_inode,
4660 dentry, &delegated_inode);
4664 inode_unlock(path.dentry->d_inode);
4666 iput(inode); /* truncate the inode here */
4668 if (delegated_inode) {
4669 error = break_deleg_wait(&delegated_inode);
4673 mnt_drop_write(path.mnt);
4676 if (retry_estale(error, lookup_flags)) {
4677 lookup_flags |= LOOKUP_REVAL;
4686 if (d_is_dir(dentry))
4693 SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag)
4695 if ((flag & ~AT_REMOVEDIR) != 0)
4698 if (flag & AT_REMOVEDIR)
4699 return do_rmdir(dfd, getname(pathname));
4700 return do_unlinkat(dfd, getname(pathname));
4703 SYSCALL_DEFINE1(unlink, const char __user *, pathname)
4705 return do_unlinkat(AT_FDCWD, getname(pathname));
4709 * vfs_symlink - create symlink
4710 * @idmap: idmap of the mount the inode was found from
4711 * @dir: inode of the parent directory
4712 * @dentry: dentry of the child symlink file
4713 * @oldname: name of the file to link to
4717 * If the inode has been found through an idmapped mount the idmap of
4718 * the vfsmount must be passed through @idmap. This function will then take
4719 * care to map the inode according to @idmap before checking permissions.
4720 * On non-idmapped mounts or if permission checking is to be performed on the
4721 * raw inode simply pass @nop_mnt_idmap.
4723 int vfs_symlink(struct mnt_idmap *idmap, struct inode *dir,
4724 struct dentry *dentry, const char *oldname)
4728 error = may_create(idmap, dir, dentry);
4732 if (!dir->i_op->symlink)
4735 error = security_inode_symlink(dir, dentry, oldname);
4739 error = dir->i_op->symlink(idmap, dir, dentry, oldname);
4741 fsnotify_create(dir, dentry);
4744 EXPORT_SYMBOL(vfs_symlink);
4746 int do_symlinkat(struct filename *from, int newdfd, struct filename *to)
4749 struct dentry *dentry;
4751 unsigned int lookup_flags = 0;
4754 error = PTR_ERR(from);
4758 dentry = filename_create(newdfd, to, &path, lookup_flags);
4759 error = PTR_ERR(dentry);
4763 error = security_path_symlink(&path, dentry, from->name);
4765 error = vfs_symlink(mnt_idmap(path.mnt), path.dentry->d_inode,
4766 dentry, from->name);
4767 done_path_create(&path, dentry);
4768 if (retry_estale(error, lookup_flags)) {
4769 lookup_flags |= LOOKUP_REVAL;
4778 SYSCALL_DEFINE3(symlinkat, const char __user *, oldname,
4779 int, newdfd, const char __user *, newname)
4781 return do_symlinkat(getname(oldname), newdfd, getname(newname));
4784 SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname)
4786 return do_symlinkat(getname(oldname), AT_FDCWD, getname(newname));
4790 * vfs_link - create a new link
4791 * @old_dentry: object to be linked
4792 * @idmap: idmap of the mount
4794 * @new_dentry: where to create the new link
4795 * @delegated_inode: returns inode needing a delegation break
4797 * The caller must hold dir->i_mutex
4799 * If vfs_link discovers a delegation on the to-be-linked file in need
4800 * of breaking, it will return -EWOULDBLOCK and return a reference to the
4801 * inode in delegated_inode. The caller should then break the delegation
4802 * and retry. Because breaking a delegation may take a long time, the
4803 * caller should drop the i_mutex before doing so.
4805 * Alternatively, a caller may pass NULL for delegated_inode. This may
4806 * be appropriate for callers that expect the underlying filesystem not
4807 * to be NFS exported.
4809 * If the inode has been found through an idmapped mount the idmap of
4810 * the vfsmount must be passed through @idmap. This function will then take
4811 * care to map the inode according to @idmap before checking permissions.
4812 * On non-idmapped mounts or if permission checking is to be performed on the
4813 * raw inode simply pass @nop_mnt_idmap.
4815 int vfs_link(struct dentry *old_dentry, struct mnt_idmap *idmap,
4816 struct inode *dir, struct dentry *new_dentry,
4817 struct inode **delegated_inode)
4819 struct inode *inode = old_dentry->d_inode;
4820 unsigned max_links = dir->i_sb->s_max_links;
4826 error = may_create(idmap, dir, new_dentry);
4830 if (dir->i_sb != inode->i_sb)
4834 * A link to an append-only or immutable file cannot be created.
4836 if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
4839 * Updating the link count will likely cause i_uid and i_gid to
4840 * be writen back improperly if their true value is unknown to
4843 if (HAS_UNMAPPED_ID(idmap, inode))
4845 if (!dir->i_op->link)
4847 if (S_ISDIR(inode->i_mode))
4850 error = security_inode_link(old_dentry, dir, new_dentry);
4855 /* Make sure we don't allow creating hardlink to an unlinked file */
4856 if (inode->i_nlink == 0 && !(inode->i_state & I_LINKABLE))
4858 else if (max_links && inode->i_nlink >= max_links)
4861 error = try_break_deleg(inode, delegated_inode);
4863 error = dir->i_op->link(old_dentry, dir, new_dentry);
4866 if (!error && (inode->i_state & I_LINKABLE)) {
4867 spin_lock(&inode->i_lock);
4868 inode->i_state &= ~I_LINKABLE;
4869 spin_unlock(&inode->i_lock);
4871 inode_unlock(inode);
4873 fsnotify_link(dir, inode, new_dentry);
4876 EXPORT_SYMBOL(vfs_link);
4879 * Hardlinks are often used in delicate situations. We avoid
4880 * security-related surprises by not following symlinks on the
4883 * We don't follow them on the oldname either to be compatible
4884 * with linux 2.0, and to avoid hard-linking to directories
4885 * and other special files. --ADM
4887 int do_linkat(int olddfd, struct filename *old, int newdfd,
4888 struct filename *new, int flags)
4890 struct mnt_idmap *idmap;
4891 struct dentry *new_dentry;
4892 struct path old_path, new_path;
4893 struct inode *delegated_inode = NULL;
4897 if ((flags & ~(AT_SYMLINK_FOLLOW | AT_EMPTY_PATH)) != 0) {
4902 * To use null names we require CAP_DAC_READ_SEARCH or
4903 * that the open-time creds of the dfd matches current.
4904 * This ensures that not everyone will be able to create
4905 * a hardlink using the passed file descriptor.
4907 if (flags & AT_EMPTY_PATH)
4908 how |= LOOKUP_LINKAT_EMPTY;
4910 if (flags & AT_SYMLINK_FOLLOW)
4911 how |= LOOKUP_FOLLOW;
4913 error = filename_lookup(olddfd, old, how, &old_path, NULL);
4917 new_dentry = filename_create(newdfd, new, &new_path,
4918 (how & LOOKUP_REVAL));
4919 error = PTR_ERR(new_dentry);
4920 if (IS_ERR(new_dentry))
4924 if (old_path.mnt != new_path.mnt)
4926 idmap = mnt_idmap(new_path.mnt);
4927 error = may_linkat(idmap, &old_path);
4928 if (unlikely(error))
4930 error = security_path_link(old_path.dentry, &new_path, new_dentry);
4933 error = vfs_link(old_path.dentry, idmap, new_path.dentry->d_inode,
4934 new_dentry, &delegated_inode);
4936 done_path_create(&new_path, new_dentry);
4937 if (delegated_inode) {
4938 error = break_deleg_wait(&delegated_inode);
4940 path_put(&old_path);
4944 if (retry_estale(error, how)) {
4945 path_put(&old_path);
4946 how |= LOOKUP_REVAL;
4950 path_put(&old_path);
4958 SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname,
4959 int, newdfd, const char __user *, newname, int, flags)
4961 return do_linkat(olddfd, getname_uflags(oldname, flags),
4962 newdfd, getname(newname), flags);
4965 SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname)
4967 return do_linkat(AT_FDCWD, getname(oldname), AT_FDCWD, getname(newname), 0);
4971 * vfs_rename - rename a filesystem object
4972 * @rd: pointer to &struct renamedata info
4974 * The caller must hold multiple mutexes--see lock_rename()).
4976 * If vfs_rename discovers a delegation in need of breaking at either
4977 * the source or destination, it will return -EWOULDBLOCK and return a
4978 * reference to the inode in delegated_inode. The caller should then
4979 * break the delegation and retry. Because breaking a delegation may
4980 * take a long time, the caller should drop all locks before doing
4983 * Alternatively, a caller may pass NULL for delegated_inode. This may
4984 * be appropriate for callers that expect the underlying filesystem not
4985 * to be NFS exported.
4987 * The worst of all namespace operations - renaming directory. "Perverted"
4988 * doesn't even start to describe it. Somebody in UCB had a heck of a trip...
4991 * a) we can get into loop creation.
4992 * b) race potential - two innocent renames can create a loop together.
4993 * That's where 4.4BSD screws up. Current fix: serialization on
4994 * sb->s_vfs_rename_mutex. We might be more accurate, but that's another
4996 * c) we may have to lock up to _four_ objects - parents and victim (if it exists),
4997 * and source (if it's a non-directory or a subdirectory that moves to
4998 * different parent).
4999 * And that - after we got ->i_mutex on parents (until then we don't know
5000 * whether the target exists). Solution: try to be smart with locking
5001 * order for inodes. We rely on the fact that tree topology may change
5002 * only under ->s_vfs_rename_mutex _and_ that parent of the object we
5003 * move will be locked. Thus we can rank directories by the tree
5004 * (ancestors first) and rank all non-directories after them.
5005 * That works since everybody except rename does "lock parent, lookup,
5006 * lock child" and rename is under ->s_vfs_rename_mutex.
5007 * HOWEVER, it relies on the assumption that any object with ->lookup()
5008 * has no more than 1 dentry. If "hybrid" objects will ever appear,
5009 * we'd better make sure that there's no link(2) for them.
5010 * d) conversion from fhandle to dentry may come in the wrong moment - when
5011 * we are removing the target. Solution: we will have to grab ->i_mutex
5012 * in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on
5013 * ->i_mutex on parents, which works but leads to some truly excessive
5016 int vfs_rename(struct renamedata *rd)
5019 struct inode *old_dir = rd->old_dir, *new_dir = rd->new_dir;
5020 struct dentry *old_dentry = rd->old_dentry;
5021 struct dentry *new_dentry = rd->new_dentry;
5022 struct inode **delegated_inode = rd->delegated_inode;
5023 unsigned int flags = rd->flags;
5024 bool is_dir = d_is_dir(old_dentry);
5025 struct inode *source = old_dentry->d_inode;
5026 struct inode *target = new_dentry->d_inode;
5027 bool new_is_dir = false;
5028 unsigned max_links = new_dir->i_sb->s_max_links;
5029 struct name_snapshot old_name;
5030 bool lock_old_subdir, lock_new_subdir;
5032 if (source == target)
5035 error = may_delete(rd->old_mnt_idmap, old_dir, old_dentry, is_dir);
5040 error = may_create(rd->new_mnt_idmap, new_dir, new_dentry);
5042 new_is_dir = d_is_dir(new_dentry);
5044 if (!(flags & RENAME_EXCHANGE))
5045 error = may_delete(rd->new_mnt_idmap, new_dir,
5046 new_dentry, is_dir);
5048 error = may_delete(rd->new_mnt_idmap, new_dir,
5049 new_dentry, new_is_dir);
5054 if (!old_dir->i_op->rename)
5058 * If we are going to change the parent - check write permissions,
5059 * we'll need to flip '..'.
5061 if (new_dir != old_dir) {
5063 error = inode_permission(rd->old_mnt_idmap, source,
5068 if ((flags & RENAME_EXCHANGE) && new_is_dir) {
5069 error = inode_permission(rd->new_mnt_idmap, target,
5076 error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,
5081 take_dentry_name_snapshot(&old_name, old_dentry);
5085 * The source subdirectory needs to be locked on cross-directory
5086 * rename or cross-directory exchange since its parent changes.
5087 * The target subdirectory needs to be locked on cross-directory
5088 * exchange due to parent change and on any rename due to becoming
5090 * Non-directories need locking in all cases (for NFS reasons);
5091 * they get locked after any subdirectories (in inode address order).
5093 * NOTE: WE ONLY LOCK UNRELATED DIRECTORIES IN CROSS-DIRECTORY CASE.
5094 * NEVER, EVER DO THAT WITHOUT ->s_vfs_rename_mutex.
5096 lock_old_subdir = new_dir != old_dir;
5097 lock_new_subdir = new_dir != old_dir || !(flags & RENAME_EXCHANGE);
5099 if (lock_old_subdir)
5100 inode_lock_nested(source, I_MUTEX_CHILD);
5101 if (target && (!new_is_dir || lock_new_subdir))
5103 } else if (new_is_dir) {
5104 if (lock_new_subdir)
5105 inode_lock_nested(target, I_MUTEX_CHILD);
5108 lock_two_nondirectories(source, target);
5112 if (IS_SWAPFILE(source) || (target && IS_SWAPFILE(target)))
5116 if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
5119 if (max_links && new_dir != old_dir) {
5121 if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)
5123 if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&
5124 old_dir->i_nlink >= max_links)
5128 error = try_break_deleg(source, delegated_inode);
5132 if (target && !new_is_dir) {
5133 error = try_break_deleg(target, delegated_inode);
5137 error = old_dir->i_op->rename(rd->new_mnt_idmap, old_dir, old_dentry,
5138 new_dir, new_dentry, flags);
5142 if (!(flags & RENAME_EXCHANGE) && target) {
5144 shrink_dcache_parent(new_dentry);
5145 target->i_flags |= S_DEAD;
5147 dont_mount(new_dentry);
5148 detach_mounts(new_dentry);
5150 if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {
5151 if (!(flags & RENAME_EXCHANGE))
5152 d_move(old_dentry, new_dentry);
5154 d_exchange(old_dentry, new_dentry);
5157 if (!is_dir || lock_old_subdir)
5158 inode_unlock(source);
5159 if (target && (!new_is_dir || lock_new_subdir))
5160 inode_unlock(target);
5163 fsnotify_move(old_dir, new_dir, &old_name.name, is_dir,
5164 !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);
5165 if (flags & RENAME_EXCHANGE) {
5166 fsnotify_move(new_dir, old_dir, &old_dentry->d_name,
5167 new_is_dir, NULL, new_dentry);
5170 release_dentry_name_snapshot(&old_name);
5174 EXPORT_SYMBOL(vfs_rename);
5176 int do_renameat2(int olddfd, struct filename *from, int newdfd,
5177 struct filename *to, unsigned int flags)
5179 struct renamedata rd;
5180 struct dentry *old_dentry, *new_dentry;
5181 struct dentry *trap;
5182 struct path old_path, new_path;
5183 struct qstr old_last, new_last;
5184 int old_type, new_type;
5185 struct inode *delegated_inode = NULL;
5186 unsigned int lookup_flags = 0, target_flags =
5187 LOOKUP_RENAME_TARGET | LOOKUP_CREATE;
5188 bool should_retry = false;
5189 int error = -EINVAL;
5191 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
5194 if ((flags & (RENAME_NOREPLACE | RENAME_WHITEOUT)) &&
5195 (flags & RENAME_EXCHANGE))
5198 if (flags & RENAME_EXCHANGE)
5200 if (flags & RENAME_NOREPLACE)
5201 target_flags |= LOOKUP_EXCL;
5204 error = filename_parentat(olddfd, from, lookup_flags, &old_path,
5205 &old_last, &old_type);
5209 error = filename_parentat(newdfd, to, lookup_flags, &new_path, &new_last,
5215 if (old_path.mnt != new_path.mnt)
5219 if (old_type != LAST_NORM)
5222 if (flags & RENAME_NOREPLACE)
5224 if (new_type != LAST_NORM)
5227 error = mnt_want_write(old_path.mnt);
5232 trap = lock_rename(new_path.dentry, old_path.dentry);
5234 error = PTR_ERR(trap);
5235 goto exit_lock_rename;
5238 old_dentry = lookup_one_qstr_excl(&old_last, old_path.dentry,
5240 error = PTR_ERR(old_dentry);
5241 if (IS_ERR(old_dentry))
5243 new_dentry = lookup_one_qstr_excl(&new_last, new_path.dentry,
5244 lookup_flags | target_flags);
5245 error = PTR_ERR(new_dentry);
5246 if (IS_ERR(new_dentry))
5248 if (flags & RENAME_EXCHANGE) {
5249 if (!d_is_dir(new_dentry)) {
5251 if (new_last.name[new_last.len])
5255 /* unless the source is a directory trailing slashes give -ENOTDIR */
5256 if (!d_is_dir(old_dentry)) {
5258 if (old_last.name[old_last.len])
5260 if (!(flags & RENAME_EXCHANGE) && new_last.name[new_last.len])
5263 /* source should not be ancestor of target */
5265 if (old_dentry == trap)
5267 /* target should not be an ancestor of source */
5268 if (!(flags & RENAME_EXCHANGE))
5270 if (new_dentry == trap)
5273 error = security_path_rename(&old_path, old_dentry,
5274 &new_path, new_dentry, flags);
5278 rd.old_dir = old_path.dentry->d_inode;
5279 rd.old_dentry = old_dentry;
5280 rd.old_mnt_idmap = mnt_idmap(old_path.mnt);
5281 rd.new_dir = new_path.dentry->d_inode;
5282 rd.new_dentry = new_dentry;
5283 rd.new_mnt_idmap = mnt_idmap(new_path.mnt);
5284 rd.delegated_inode = &delegated_inode;
5286 error = vfs_rename(&rd);
5292 unlock_rename(new_path.dentry, old_path.dentry);
5294 if (delegated_inode) {
5295 error = break_deleg_wait(&delegated_inode);
5299 mnt_drop_write(old_path.mnt);
5301 if (retry_estale(error, lookup_flags))
5302 should_retry = true;
5303 path_put(&new_path);
5305 path_put(&old_path);
5307 should_retry = false;
5308 lookup_flags |= LOOKUP_REVAL;
5317 SYSCALL_DEFINE5(renameat2, int, olddfd, const char __user *, oldname,
5318 int, newdfd, const char __user *, newname, unsigned int, flags)
5320 return do_renameat2(olddfd, getname(oldname), newdfd, getname(newname),
5324 SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname,
5325 int, newdfd, const char __user *, newname)
5327 return do_renameat2(olddfd, getname(oldname), newdfd, getname(newname),
5331 SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname)
5333 return do_renameat2(AT_FDCWD, getname(oldname), AT_FDCWD,
5334 getname(newname), 0);
5337 int readlink_copy(char __user *buffer, int buflen, const char *link, int linklen)
5342 if (unlikely(copylen > (unsigned) buflen))
5344 if (copy_to_user(buffer, link, copylen))
5350 * vfs_readlink - copy symlink body into userspace buffer
5351 * @dentry: dentry on which to get symbolic link
5352 * @buffer: user memory pointer
5353 * @buflen: size of buffer
5355 * Does not touch atime. That's up to the caller if necessary
5357 * Does not call security hook.
5359 int vfs_readlink(struct dentry *dentry, char __user *buffer, int buflen)
5361 struct inode *inode = d_inode(dentry);
5362 DEFINE_DELAYED_CALL(done);
5366 if (inode->i_opflags & IOP_CACHED_LINK)
5367 return readlink_copy(buffer, buflen, inode->i_link, inode->i_linklen);
5369 if (unlikely(!(inode->i_opflags & IOP_DEFAULT_READLINK))) {
5370 if (unlikely(inode->i_op->readlink))
5371 return inode->i_op->readlink(dentry, buffer, buflen);
5373 if (!d_is_symlink(dentry))
5376 spin_lock(&inode->i_lock);
5377 inode->i_opflags |= IOP_DEFAULT_READLINK;
5378 spin_unlock(&inode->i_lock);
5381 link = READ_ONCE(inode->i_link);
5383 link = inode->i_op->get_link(dentry, inode, &done);
5385 return PTR_ERR(link);
5387 res = readlink_copy(buffer, buflen, link, strlen(link));
5388 do_delayed_call(&done);
5391 EXPORT_SYMBOL(vfs_readlink);
5394 * vfs_get_link - get symlink body
5395 * @dentry: dentry on which to get symbolic link
5396 * @done: caller needs to free returned data with this
5398 * Calls security hook and i_op->get_link() on the supplied inode.
5400 * It does not touch atime. That's up to the caller if necessary.
5402 * Does not work on "special" symlinks like /proc/$$/fd/N
5404 const char *vfs_get_link(struct dentry *dentry, struct delayed_call *done)
5406 const char *res = ERR_PTR(-EINVAL);
5407 struct inode *inode = d_inode(dentry);
5409 if (d_is_symlink(dentry)) {
5410 res = ERR_PTR(security_inode_readlink(dentry));
5412 res = inode->i_op->get_link(dentry, inode, done);
5416 EXPORT_SYMBOL(vfs_get_link);
5418 /* get the link contents into pagecache */
5419 static char *__page_get_link(struct dentry *dentry, struct inode *inode,
5420 struct delayed_call *callback)
5422 struct folio *folio;
5423 struct address_space *mapping = inode->i_mapping;
5426 folio = filemap_get_folio(mapping, 0);
5428 return ERR_PTR(-ECHILD);
5429 if (!folio_test_uptodate(folio)) {
5431 return ERR_PTR(-ECHILD);
5434 folio = read_mapping_folio(mapping, 0, NULL);
5436 return ERR_CAST(folio);
5438 set_delayed_call(callback, page_put_link, folio);
5439 BUG_ON(mapping_gfp_mask(mapping) & __GFP_HIGHMEM);
5440 return folio_address(folio);
5443 const char *page_get_link_raw(struct dentry *dentry, struct inode *inode,
5444 struct delayed_call *callback)
5446 return __page_get_link(dentry, inode, callback);
5448 EXPORT_SYMBOL_GPL(page_get_link_raw);
5451 * page_get_link() - An implementation of the get_link inode_operation.
5452 * @dentry: The directory entry which is the symlink.
5453 * @inode: The inode for the symlink.
5454 * @callback: Used to drop the reference to the symlink.
5456 * Filesystems which store their symlinks in the page cache should use
5457 * this to implement the get_link() member of their inode_operations.
5459 * Return: A pointer to the NUL-terminated symlink.
5461 const char *page_get_link(struct dentry *dentry, struct inode *inode,
5462 struct delayed_call *callback)
5464 char *kaddr = __page_get_link(dentry, inode, callback);
5467 nd_terminate_link(kaddr, inode->i_size, PAGE_SIZE - 1);
5470 EXPORT_SYMBOL(page_get_link);
5473 * page_put_link() - Drop the reference to the symlink.
5474 * @arg: The folio which contains the symlink.
5476 * This is used internally by page_get_link(). It is exported for use
5477 * by filesystems which need to implement a variant of page_get_link()
5478 * themselves. Despite the apparent symmetry, filesystems which use
5479 * page_get_link() do not need to call page_put_link().
5481 * The argument, while it has a void pointer type, must be a pointer to
5482 * the folio which was retrieved from the page cache. The delayed_call
5483 * infrastructure is used to drop the reference count once the caller
5484 * is done with the symlink.
5486 void page_put_link(void *arg)
5490 EXPORT_SYMBOL(page_put_link);
5492 int page_readlink(struct dentry *dentry, char __user *buffer, int buflen)
5497 DEFINE_DELAYED_CALL(done);
5498 link = page_get_link(dentry, d_inode(dentry), &done);
5499 res = PTR_ERR(link);
5501 res = readlink_copy(buffer, buflen, link, strlen(link));
5502 do_delayed_call(&done);
5505 EXPORT_SYMBOL(page_readlink);
5507 int page_symlink(struct inode *inode, const char *symname, int len)
5509 struct address_space *mapping = inode->i_mapping;
5510 const struct address_space_operations *aops = mapping->a_ops;
5511 bool nofs = !mapping_gfp_constraint(mapping, __GFP_FS);
5512 struct folio *folio;
5513 void *fsdata = NULL;
5519 flags = memalloc_nofs_save();
5520 err = aops->write_begin(NULL, mapping, 0, len-1, &folio, &fsdata);
5522 memalloc_nofs_restore(flags);
5526 memcpy(folio_address(folio), symname, len - 1);
5528 err = aops->write_end(NULL, mapping, 0, len - 1, len - 1,
5535 mark_inode_dirty(inode);
5540 EXPORT_SYMBOL(page_symlink);
5542 const struct inode_operations page_symlink_inode_operations = {
5543 .get_link = page_get_link,
5545 EXPORT_SYMBOL(page_symlink_inode_operations);