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))
129 getname_flags(const char __user *filename, int flags)
131 struct filename *result;
135 result = audit_reusename(filename);
139 result = __getname();
140 if (unlikely(!result))
141 return ERR_PTR(-ENOMEM);
144 * First, try to embed the struct filename inside the names_cache
147 kname = (char *)result->iname;
148 result->name = kname;
150 len = strncpy_from_user(kname, filename, EMBEDDED_NAME_MAX);
152 * Handle both empty path and copy failure in one go.
154 if (unlikely(len <= 0)) {
155 if (unlikely(len < 0)) {
160 /* The empty path is special. */
161 if (!(flags & LOOKUP_EMPTY)) {
163 return ERR_PTR(-ENOENT);
168 * Uh-oh. We have a name that's approaching PATH_MAX. Allocate a
169 * separate struct filename so we can dedicate the entire
170 * names_cache allocation for the pathname, and re-do the copy from
173 if (unlikely(len == EMBEDDED_NAME_MAX)) {
174 const size_t size = offsetof(struct filename, iname[1]);
175 kname = (char *)result;
178 * size is chosen that way we to guarantee that
179 * result->iname[0] is within the same object and that
180 * kname can't be equal to result->iname, no matter what.
182 result = kzalloc(size, GFP_KERNEL);
183 if (unlikely(!result)) {
185 return ERR_PTR(-ENOMEM);
187 result->name = kname;
188 len = strncpy_from_user(kname, filename, PATH_MAX);
189 if (unlikely(len < 0)) {
194 /* The empty path is special. */
195 if (unlikely(!len) && !(flags & LOOKUP_EMPTY)) {
198 return ERR_PTR(-ENOENT);
200 if (unlikely(len == PATH_MAX)) {
203 return ERR_PTR(-ENAMETOOLONG);
207 atomic_set(&result->refcnt, 1);
208 result->uptr = filename;
209 result->aname = NULL;
210 audit_getname(result);
215 getname_uflags(const char __user *filename, int uflags)
217 int flags = (uflags & AT_EMPTY_PATH) ? LOOKUP_EMPTY : 0;
219 return getname_flags(filename, flags);
223 getname(const char __user * filename)
225 return getname_flags(filename, 0);
229 getname_kernel(const char * filename)
231 struct filename *result;
232 int len = strlen(filename) + 1;
234 result = __getname();
235 if (unlikely(!result))
236 return ERR_PTR(-ENOMEM);
238 if (len <= EMBEDDED_NAME_MAX) {
239 result->name = (char *)result->iname;
240 } else if (len <= PATH_MAX) {
241 const size_t size = offsetof(struct filename, iname[1]);
242 struct filename *tmp;
244 tmp = kmalloc(size, GFP_KERNEL);
245 if (unlikely(!tmp)) {
247 return ERR_PTR(-ENOMEM);
249 tmp->name = (char *)result;
253 return ERR_PTR(-ENAMETOOLONG);
255 memcpy((char *)result->name, filename, len);
257 result->aname = NULL;
258 atomic_set(&result->refcnt, 1);
259 audit_getname(result);
263 EXPORT_SYMBOL(getname_kernel);
265 void putname(struct filename *name)
270 if (WARN_ON_ONCE(!atomic_read(&name->refcnt)))
273 if (!atomic_dec_and_test(&name->refcnt))
276 if (name->name != name->iname) {
277 __putname(name->name);
282 EXPORT_SYMBOL(putname);
285 * check_acl - perform ACL permission checking
286 * @idmap: idmap of the mount the inode was found from
287 * @inode: inode to check permissions on
288 * @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
290 * This function performs the ACL permission checking. Since this function
291 * retrieve POSIX acls it needs to know whether it is called from a blocking or
292 * non-blocking context and thus cares about the MAY_NOT_BLOCK bit.
294 * If the inode has been found through an idmapped mount the idmap of
295 * the vfsmount must be passed through @idmap. This function will then take
296 * care to map the inode according to @idmap before checking permissions.
297 * On non-idmapped mounts or if permission checking is to be performed on the
298 * raw inode simply pass @nop_mnt_idmap.
300 static int check_acl(struct mnt_idmap *idmap,
301 struct inode *inode, int mask)
303 #ifdef CONFIG_FS_POSIX_ACL
304 struct posix_acl *acl;
306 if (mask & MAY_NOT_BLOCK) {
307 acl = get_cached_acl_rcu(inode, ACL_TYPE_ACCESS);
310 /* no ->get_inode_acl() calls in RCU mode... */
311 if (is_uncached_acl(acl))
313 return posix_acl_permission(idmap, inode, acl, mask);
316 acl = get_inode_acl(inode, ACL_TYPE_ACCESS);
320 int error = posix_acl_permission(idmap, inode, acl, mask);
321 posix_acl_release(acl);
330 * acl_permission_check - perform basic UNIX permission checking
331 * @idmap: idmap of the mount the inode was found from
332 * @inode: inode to check permissions on
333 * @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
335 * This function performs the basic UNIX permission checking. Since this
336 * function may retrieve POSIX acls it needs to know whether it is called from a
337 * blocking or non-blocking context and thus cares about the MAY_NOT_BLOCK bit.
339 * If the inode has been found through an idmapped mount the idmap of
340 * the vfsmount must be passed through @idmap. This function will then take
341 * care to map the inode according to @idmap before checking permissions.
342 * On non-idmapped mounts or if permission checking is to be performed on the
343 * raw inode simply pass @nop_mnt_idmap.
345 static int acl_permission_check(struct mnt_idmap *idmap,
346 struct inode *inode, int mask)
348 unsigned int mode = inode->i_mode;
351 /* Are we the owner? If so, ACL's don't matter */
352 vfsuid = i_uid_into_vfsuid(idmap, inode);
353 if (likely(vfsuid_eq_kuid(vfsuid, current_fsuid()))) {
356 return (mask & ~mode) ? -EACCES : 0;
359 /* Do we have ACL's? */
360 if (IS_POSIXACL(inode) && (mode & S_IRWXG)) {
361 int error = check_acl(idmap, inode, mask);
362 if (error != -EAGAIN)
366 /* Only RWX matters for group/other mode bits */
370 * Are the group permissions different from
371 * the other permissions in the bits we care
372 * about? Need to check group ownership if so.
374 if (mask & (mode ^ (mode >> 3))) {
375 vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
376 if (vfsgid_in_group_p(vfsgid))
380 /* Bits in 'mode' clear that we require? */
381 return (mask & ~mode) ? -EACCES : 0;
385 * generic_permission - check for access rights on a Posix-like filesystem
386 * @idmap: idmap of the mount the inode was found from
387 * @inode: inode to check access rights for
388 * @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC,
389 * %MAY_NOT_BLOCK ...)
391 * Used to check for read/write/execute permissions on a file.
392 * We use "fsuid" for this, letting us set arbitrary permissions
393 * for filesystem access without changing the "normal" uids which
394 * are used for other things.
396 * generic_permission is rcu-walk aware. It returns -ECHILD in case an rcu-walk
397 * request cannot be satisfied (eg. requires blocking or too much complexity).
398 * It would then be called again in ref-walk mode.
400 * If the inode has been found through an idmapped mount the idmap of
401 * the vfsmount must be passed through @idmap. This function will then take
402 * care to map the inode according to @idmap before checking permissions.
403 * On non-idmapped mounts or if permission checking is to be performed on the
404 * raw inode simply pass @nop_mnt_idmap.
406 int generic_permission(struct mnt_idmap *idmap, struct inode *inode,
412 * Do the basic permission checks.
414 ret = acl_permission_check(idmap, inode, mask);
418 if (S_ISDIR(inode->i_mode)) {
419 /* DACs are overridable for directories */
420 if (!(mask & MAY_WRITE))
421 if (capable_wrt_inode_uidgid(idmap, inode,
422 CAP_DAC_READ_SEARCH))
424 if (capable_wrt_inode_uidgid(idmap, inode,
431 * Searching includes executable on directories, else just read.
433 mask &= MAY_READ | MAY_WRITE | MAY_EXEC;
434 if (mask == MAY_READ)
435 if (capable_wrt_inode_uidgid(idmap, inode,
436 CAP_DAC_READ_SEARCH))
439 * Read/write DACs are always overridable.
440 * Executable DACs are overridable when there is
441 * at least one exec bit set.
443 if (!(mask & MAY_EXEC) || (inode->i_mode & S_IXUGO))
444 if (capable_wrt_inode_uidgid(idmap, inode,
450 EXPORT_SYMBOL(generic_permission);
453 * do_inode_permission - UNIX permission checking
454 * @idmap: idmap of the mount the inode was found from
455 * @inode: inode to check permissions on
456 * @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
458 * We _really_ want to just do "generic_permission()" without
459 * even looking at the inode->i_op values. So we keep a cache
460 * flag in inode->i_opflags, that says "this has not special
461 * permission function, use the fast case".
463 static inline int do_inode_permission(struct mnt_idmap *idmap,
464 struct inode *inode, int mask)
466 if (unlikely(!(inode->i_opflags & IOP_FASTPERM))) {
467 if (likely(inode->i_op->permission))
468 return inode->i_op->permission(idmap, inode, mask);
470 /* This gets set once for the inode lifetime */
471 spin_lock(&inode->i_lock);
472 inode->i_opflags |= IOP_FASTPERM;
473 spin_unlock(&inode->i_lock);
475 return generic_permission(idmap, inode, mask);
479 * sb_permission - Check superblock-level permissions
480 * @sb: Superblock of inode to check permission on
481 * @inode: Inode to check permission on
482 * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
484 * Separate out file-system wide checks from inode-specific permission checks.
486 static int sb_permission(struct super_block *sb, struct inode *inode, int mask)
488 if (unlikely(mask & MAY_WRITE)) {
489 umode_t mode = inode->i_mode;
491 /* Nobody gets write access to a read-only fs. */
492 if (sb_rdonly(sb) && (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode)))
499 * inode_permission - Check for access rights to a given inode
500 * @idmap: idmap of the mount the inode was found from
501 * @inode: Inode to check permission on
502 * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
504 * Check for read/write/execute permissions on an inode. We use fs[ug]id for
505 * this, letting us set arbitrary permissions for filesystem access without
506 * changing the "normal" UIDs which are used for other things.
508 * When checking for MAY_APPEND, MAY_WRITE must also be set in @mask.
510 int inode_permission(struct mnt_idmap *idmap,
511 struct inode *inode, int mask)
515 retval = sb_permission(inode->i_sb, inode, mask);
519 if (unlikely(mask & MAY_WRITE)) {
521 * Nobody gets write access to an immutable file.
523 if (IS_IMMUTABLE(inode))
527 * Updating mtime will likely cause i_uid and i_gid to be
528 * written back improperly if their true value is unknown
531 if (HAS_UNMAPPED_ID(idmap, inode))
535 retval = do_inode_permission(idmap, inode, mask);
539 retval = devcgroup_inode_permission(inode, mask);
543 return security_inode_permission(inode, mask);
545 EXPORT_SYMBOL(inode_permission);
548 * path_get - get a reference to a path
549 * @path: path to get the reference to
551 * Given a path increment the reference count to the dentry and the vfsmount.
553 void path_get(const struct path *path)
558 EXPORT_SYMBOL(path_get);
561 * path_put - put a reference to a path
562 * @path: path to put the reference to
564 * Given a path decrement the reference count to the dentry and the vfsmount.
566 void path_put(const struct path *path)
571 EXPORT_SYMBOL(path_put);
573 #define EMBEDDED_LEVELS 2
578 struct inode *inode; /* path.dentry.d_inode */
579 unsigned int flags, state;
580 unsigned seq, next_seq, m_seq, r_seq;
583 int total_link_count;
586 struct delayed_call done;
589 } *stack, internal[EMBEDDED_LEVELS];
590 struct filename *name;
591 struct nameidata *saved;
596 } __randomize_layout;
598 #define ND_ROOT_PRESET 1
599 #define ND_ROOT_GRABBED 2
602 static void __set_nameidata(struct nameidata *p, int dfd, struct filename *name)
604 struct nameidata *old = current->nameidata;
605 p->stack = p->internal;
610 p->path.dentry = NULL;
611 p->total_link_count = old ? old->total_link_count : 0;
613 current->nameidata = p;
616 static inline void set_nameidata(struct nameidata *p, int dfd, struct filename *name,
617 const struct path *root)
619 __set_nameidata(p, dfd, name);
621 if (unlikely(root)) {
622 p->state = ND_ROOT_PRESET;
627 static void restore_nameidata(void)
629 struct nameidata *now = current->nameidata, *old = now->saved;
631 current->nameidata = old;
633 old->total_link_count = now->total_link_count;
634 if (now->stack != now->internal)
638 static bool nd_alloc_stack(struct nameidata *nd)
642 p= kmalloc_array(MAXSYMLINKS, sizeof(struct saved),
643 nd->flags & LOOKUP_RCU ? GFP_ATOMIC : GFP_KERNEL);
646 memcpy(p, nd->internal, sizeof(nd->internal));
652 * path_connected - Verify that a dentry is below mnt.mnt_root
653 * @mnt: The mountpoint to check.
654 * @dentry: The dentry to check.
656 * Rename can sometimes move a file or directory outside of a bind
657 * mount, path_connected allows those cases to be detected.
659 static bool path_connected(struct vfsmount *mnt, struct dentry *dentry)
661 struct super_block *sb = mnt->mnt_sb;
663 /* Bind mounts can have disconnected paths */
664 if (mnt->mnt_root == sb->s_root)
667 return is_subdir(dentry, mnt->mnt_root);
670 static void drop_links(struct nameidata *nd)
674 struct saved *last = nd->stack + i;
675 do_delayed_call(&last->done);
676 clear_delayed_call(&last->done);
680 static void leave_rcu(struct nameidata *nd)
682 nd->flags &= ~LOOKUP_RCU;
683 nd->seq = nd->next_seq = 0;
687 static void terminate_walk(struct nameidata *nd)
690 if (!(nd->flags & LOOKUP_RCU)) {
693 for (i = 0; i < nd->depth; i++)
694 path_put(&nd->stack[i].link);
695 if (nd->state & ND_ROOT_GRABBED) {
697 nd->state &= ~ND_ROOT_GRABBED;
704 nd->path.dentry = NULL;
707 /* path_put is needed afterwards regardless of success or failure */
708 static bool __legitimize_path(struct path *path, unsigned seq, unsigned mseq)
710 int res = __legitimize_mnt(path->mnt, mseq);
717 if (unlikely(!lockref_get_not_dead(&path->dentry->d_lockref))) {
721 return !read_seqcount_retry(&path->dentry->d_seq, seq);
724 static inline bool legitimize_path(struct nameidata *nd,
725 struct path *path, unsigned seq)
727 return __legitimize_path(path, seq, nd->m_seq);
730 static bool legitimize_links(struct nameidata *nd)
733 if (unlikely(nd->flags & LOOKUP_CACHED)) {
738 for (i = 0; i < nd->depth; i++) {
739 struct saved *last = nd->stack + i;
740 if (unlikely(!legitimize_path(nd, &last->link, last->seq))) {
749 static bool legitimize_root(struct nameidata *nd)
751 /* Nothing to do if nd->root is zero or is managed by the VFS user. */
752 if (!nd->root.mnt || (nd->state & ND_ROOT_PRESET))
754 nd->state |= ND_ROOT_GRABBED;
755 return legitimize_path(nd, &nd->root, nd->root_seq);
759 * Path walking has 2 modes, rcu-walk and ref-walk (see
760 * Documentation/filesystems/path-lookup.txt). In situations when we can't
761 * continue in RCU mode, we attempt to drop out of rcu-walk mode and grab
762 * normal reference counts on dentries and vfsmounts to transition to ref-walk
763 * mode. Refcounts are grabbed at the last known good point before rcu-walk
764 * got stuck, so ref-walk may continue from there. If this is not successful
765 * (eg. a seqcount has changed), then failure is returned and it's up to caller
766 * to restart the path walk from the beginning in ref-walk mode.
770 * try_to_unlazy - try to switch to ref-walk mode.
771 * @nd: nameidata pathwalk data
772 * Returns: true on success, false on failure
774 * try_to_unlazy attempts to legitimize the current nd->path and nd->root
776 * Must be called from rcu-walk context.
777 * Nothing should touch nameidata between try_to_unlazy() failure and
780 static bool try_to_unlazy(struct nameidata *nd)
782 struct dentry *parent = nd->path.dentry;
784 BUG_ON(!(nd->flags & LOOKUP_RCU));
786 if (unlikely(!legitimize_links(nd)))
788 if (unlikely(!legitimize_path(nd, &nd->path, nd->seq)))
790 if (unlikely(!legitimize_root(nd)))
793 BUG_ON(nd->inode != parent->d_inode);
798 nd->path.dentry = NULL;
805 * try_to_unlazy_next - try to switch to ref-walk mode.
806 * @nd: nameidata pathwalk data
807 * @dentry: next dentry to step into
808 * Returns: true on success, false on failure
810 * Similar to try_to_unlazy(), but here we have the next dentry already
811 * picked by rcu-walk and want to legitimize that in addition to the current
812 * nd->path and nd->root for ref-walk mode. Must be called from rcu-walk context.
813 * Nothing should touch nameidata between try_to_unlazy_next() failure and
816 static bool try_to_unlazy_next(struct nameidata *nd, struct dentry *dentry)
819 BUG_ON(!(nd->flags & LOOKUP_RCU));
821 if (unlikely(!legitimize_links(nd)))
823 res = __legitimize_mnt(nd->path.mnt, nd->m_seq);
829 if (unlikely(!lockref_get_not_dead(&nd->path.dentry->d_lockref)))
833 * We need to move both the parent and the dentry from the RCU domain
834 * to be properly refcounted. And the sequence number in the dentry
835 * validates *both* dentry counters, since we checked the sequence
836 * number of the parent after we got the child sequence number. So we
837 * know the parent must still be valid if the child sequence number is
839 if (unlikely(!lockref_get_not_dead(&dentry->d_lockref)))
841 if (read_seqcount_retry(&dentry->d_seq, nd->next_seq))
844 * Sequence counts matched. Now make sure that the root is
845 * still valid and get it if required.
847 if (unlikely(!legitimize_root(nd)))
855 nd->path.dentry = NULL;
865 static inline int d_revalidate(struct dentry *dentry, unsigned int flags)
867 if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE))
868 return dentry->d_op->d_revalidate(dentry, flags);
874 * complete_walk - successful completion of path walk
875 * @nd: pointer nameidata
877 * If we had been in RCU mode, drop out of it and legitimize nd->path.
878 * Revalidate the final result, unless we'd already done that during
879 * the path walk or the filesystem doesn't ask for it. Return 0 on
880 * success, -error on failure. In case of failure caller does not
881 * need to drop nd->path.
883 static int complete_walk(struct nameidata *nd)
885 struct dentry *dentry = nd->path.dentry;
888 if (nd->flags & LOOKUP_RCU) {
890 * We don't want to zero nd->root for scoped-lookups or
891 * externally-managed nd->root.
893 if (!(nd->state & ND_ROOT_PRESET))
894 if (!(nd->flags & LOOKUP_IS_SCOPED))
896 nd->flags &= ~LOOKUP_CACHED;
897 if (!try_to_unlazy(nd))
901 if (unlikely(nd->flags & LOOKUP_IS_SCOPED)) {
903 * While the guarantee of LOOKUP_IS_SCOPED is (roughly) "don't
904 * ever step outside the root during lookup" and should already
905 * be guaranteed by the rest of namei, we want to avoid a namei
906 * BUG resulting in userspace being given a path that was not
907 * scoped within the root at some point during the lookup.
909 * So, do a final sanity-check to make sure that in the
910 * worst-case scenario (a complete bypass of LOOKUP_IS_SCOPED)
911 * we won't silently return an fd completely outside of the
912 * requested root to userspace.
914 * Userspace could move the path outside the root after this
915 * check, but as discussed elsewhere this is not a concern (the
916 * resolved file was inside the root at some point).
918 if (!path_is_under(&nd->path, &nd->root))
922 if (likely(!(nd->state & ND_JUMPED)))
925 if (likely(!(dentry->d_flags & DCACHE_OP_WEAK_REVALIDATE)))
928 status = dentry->d_op->d_weak_revalidate(dentry, nd->flags);
938 static int set_root(struct nameidata *nd)
940 struct fs_struct *fs = current->fs;
943 * Jumping to the real root in a scoped-lookup is a BUG in namei, but we
944 * still have to ensure it doesn't happen because it will cause a breakout
947 if (WARN_ON(nd->flags & LOOKUP_IS_SCOPED))
948 return -ENOTRECOVERABLE;
950 if (nd->flags & LOOKUP_RCU) {
954 seq = read_seqcount_begin(&fs->seq);
956 nd->root_seq = __read_seqcount_begin(&nd->root.dentry->d_seq);
957 } while (read_seqcount_retry(&fs->seq, seq));
959 get_fs_root(fs, &nd->root);
960 nd->state |= ND_ROOT_GRABBED;
965 static int nd_jump_root(struct nameidata *nd)
967 if (unlikely(nd->flags & LOOKUP_BENEATH))
969 if (unlikely(nd->flags & LOOKUP_NO_XDEV)) {
970 /* Absolute path arguments to path_init() are allowed. */
971 if (nd->path.mnt != NULL && nd->path.mnt != nd->root.mnt)
975 int error = set_root(nd);
979 if (nd->flags & LOOKUP_RCU) {
983 nd->inode = d->d_inode;
984 nd->seq = nd->root_seq;
985 if (read_seqcount_retry(&d->d_seq, nd->seq))
991 nd->inode = nd->path.dentry->d_inode;
993 nd->state |= ND_JUMPED;
998 * Helper to directly jump to a known parsed path from ->get_link,
999 * caller must have taken a reference to path beforehand.
1001 int nd_jump_link(const struct path *path)
1004 struct nameidata *nd = current->nameidata;
1006 if (unlikely(nd->flags & LOOKUP_NO_MAGICLINKS))
1010 if (unlikely(nd->flags & LOOKUP_NO_XDEV)) {
1011 if (nd->path.mnt != path->mnt)
1014 /* Not currently safe for scoped-lookups. */
1015 if (unlikely(nd->flags & LOOKUP_IS_SCOPED))
1018 path_put(&nd->path);
1020 nd->inode = nd->path.dentry->d_inode;
1021 nd->state |= ND_JUMPED;
1029 static inline void put_link(struct nameidata *nd)
1031 struct saved *last = nd->stack + --nd->depth;
1032 do_delayed_call(&last->done);
1033 if (!(nd->flags & LOOKUP_RCU))
1034 path_put(&last->link);
1037 static int sysctl_protected_symlinks __read_mostly;
1038 static int sysctl_protected_hardlinks __read_mostly;
1039 static int sysctl_protected_fifos __read_mostly;
1040 static int sysctl_protected_regular __read_mostly;
1042 #ifdef CONFIG_SYSCTL
1043 static struct ctl_table namei_sysctls[] = {
1045 .procname = "protected_symlinks",
1046 .data = &sysctl_protected_symlinks,
1047 .maxlen = sizeof(int),
1049 .proc_handler = proc_dointvec_minmax,
1050 .extra1 = SYSCTL_ZERO,
1051 .extra2 = SYSCTL_ONE,
1054 .procname = "protected_hardlinks",
1055 .data = &sysctl_protected_hardlinks,
1056 .maxlen = sizeof(int),
1058 .proc_handler = proc_dointvec_minmax,
1059 .extra1 = SYSCTL_ZERO,
1060 .extra2 = SYSCTL_ONE,
1063 .procname = "protected_fifos",
1064 .data = &sysctl_protected_fifos,
1065 .maxlen = sizeof(int),
1067 .proc_handler = proc_dointvec_minmax,
1068 .extra1 = SYSCTL_ZERO,
1069 .extra2 = SYSCTL_TWO,
1072 .procname = "protected_regular",
1073 .data = &sysctl_protected_regular,
1074 .maxlen = sizeof(int),
1076 .proc_handler = proc_dointvec_minmax,
1077 .extra1 = SYSCTL_ZERO,
1078 .extra2 = SYSCTL_TWO,
1082 static int __init init_fs_namei_sysctls(void)
1084 register_sysctl_init("fs", namei_sysctls);
1087 fs_initcall(init_fs_namei_sysctls);
1089 #endif /* CONFIG_SYSCTL */
1092 * may_follow_link - Check symlink following for unsafe situations
1093 * @nd: nameidata pathwalk data
1094 * @inode: Used for idmapping.
1096 * In the case of the sysctl_protected_symlinks sysctl being enabled,
1097 * CAP_DAC_OVERRIDE needs to be specifically ignored if the symlink is
1098 * in a sticky world-writable directory. This is to protect privileged
1099 * processes from failing races against path names that may change out
1100 * from under them by way of other users creating malicious symlinks.
1101 * It will permit symlinks to be followed only when outside a sticky
1102 * world-writable directory, or when the uid of the symlink and follower
1103 * match, or when the directory owner matches the symlink's owner.
1105 * Returns 0 if following the symlink is allowed, -ve on error.
1107 static inline int may_follow_link(struct nameidata *nd, const struct inode *inode)
1109 struct mnt_idmap *idmap;
1112 if (!sysctl_protected_symlinks)
1115 idmap = mnt_idmap(nd->path.mnt);
1116 vfsuid = i_uid_into_vfsuid(idmap, inode);
1117 /* Allowed if owner and follower match. */
1118 if (vfsuid_eq_kuid(vfsuid, current_fsuid()))
1121 /* Allowed if parent directory not sticky and world-writable. */
1122 if ((nd->dir_mode & (S_ISVTX|S_IWOTH)) != (S_ISVTX|S_IWOTH))
1125 /* Allowed if parent directory and link owner match. */
1126 if (vfsuid_valid(nd->dir_vfsuid) && vfsuid_eq(nd->dir_vfsuid, vfsuid))
1129 if (nd->flags & LOOKUP_RCU)
1132 audit_inode(nd->name, nd->stack[0].link.dentry, 0);
1133 audit_log_path_denied(AUDIT_ANOM_LINK, "follow_link");
1138 * safe_hardlink_source - Check for safe hardlink conditions
1139 * @idmap: idmap of the mount the inode was found from
1140 * @inode: the source inode to hardlink from
1142 * Return false if at least one of the following conditions:
1143 * - inode is not a regular file
1145 * - inode is setgid and group-exec
1146 * - access failure for read and write
1148 * Otherwise returns true.
1150 static bool safe_hardlink_source(struct mnt_idmap *idmap,
1151 struct inode *inode)
1153 umode_t mode = inode->i_mode;
1155 /* Special files should not get pinned to the filesystem. */
1159 /* Setuid files should not get pinned to the filesystem. */
1163 /* Executable setgid files should not get pinned to the filesystem. */
1164 if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP))
1167 /* Hardlinking to unreadable or unwritable sources is dangerous. */
1168 if (inode_permission(idmap, inode, MAY_READ | MAY_WRITE))
1175 * may_linkat - Check permissions for creating a hardlink
1176 * @idmap: idmap of the mount the inode was found from
1177 * @link: the source to hardlink from
1179 * Block hardlink when all of:
1180 * - sysctl_protected_hardlinks enabled
1181 * - fsuid does not match inode
1182 * - hardlink source is unsafe (see safe_hardlink_source() above)
1183 * - not CAP_FOWNER in a namespace with the inode owner uid mapped
1185 * If the inode has been found through an idmapped mount the idmap of
1186 * the vfsmount must be passed through @idmap. This function will then take
1187 * care to map the inode according to @idmap before checking permissions.
1188 * On non-idmapped mounts or if permission checking is to be performed on the
1189 * raw inode simply pass @nop_mnt_idmap.
1191 * Returns 0 if successful, -ve on error.
1193 int may_linkat(struct mnt_idmap *idmap, const struct path *link)
1195 struct inode *inode = link->dentry->d_inode;
1197 /* Inode writeback is not safe when the uid or gid are invalid. */
1198 if (!vfsuid_valid(i_uid_into_vfsuid(idmap, inode)) ||
1199 !vfsgid_valid(i_gid_into_vfsgid(idmap, inode)))
1202 if (!sysctl_protected_hardlinks)
1205 /* Source inode owner (or CAP_FOWNER) can hardlink all they like,
1206 * otherwise, it must be a safe source.
1208 if (safe_hardlink_source(idmap, inode) ||
1209 inode_owner_or_capable(idmap, inode))
1212 audit_log_path_denied(AUDIT_ANOM_LINK, "linkat");
1217 * may_create_in_sticky - Check whether an O_CREAT open in a sticky directory
1218 * should be allowed, or not, on files that already
1220 * @idmap: idmap of the mount the inode was found from
1221 * @nd: nameidata pathwalk data
1222 * @inode: the inode of the file to open
1224 * Block an O_CREAT open of a FIFO (or a regular file) when:
1225 * - sysctl_protected_fifos (or sysctl_protected_regular) is enabled
1226 * - the file already exists
1227 * - we are in a sticky directory
1228 * - we don't own the file
1229 * - the owner of the directory doesn't own the file
1230 * - the directory is world writable
1231 * If the sysctl_protected_fifos (or sysctl_protected_regular) is set to 2
1232 * the directory doesn't have to be world writable: being group writable will
1235 * If the inode has been found through an idmapped mount the idmap of
1236 * the vfsmount must be passed through @idmap. This function will then take
1237 * care to map the inode according to @idmap before checking permissions.
1238 * On non-idmapped mounts or if permission checking is to be performed on the
1239 * raw inode simply pass @nop_mnt_idmap.
1241 * Returns 0 if the open is allowed, -ve on error.
1243 static int may_create_in_sticky(struct mnt_idmap *idmap, struct nameidata *nd,
1244 struct inode *const inode)
1246 umode_t dir_mode = nd->dir_mode;
1247 vfsuid_t dir_vfsuid = nd->dir_vfsuid, i_vfsuid;
1249 if (likely(!(dir_mode & S_ISVTX)))
1252 if (S_ISREG(inode->i_mode) && !sysctl_protected_regular)
1255 if (S_ISFIFO(inode->i_mode) && !sysctl_protected_fifos)
1258 i_vfsuid = i_uid_into_vfsuid(idmap, inode);
1260 if (vfsuid_eq(i_vfsuid, dir_vfsuid))
1263 if (vfsuid_eq_kuid(i_vfsuid, current_fsuid()))
1266 if (likely(dir_mode & 0002)) {
1267 audit_log_path_denied(AUDIT_ANOM_CREAT, "sticky_create");
1271 if (dir_mode & 0020) {
1272 if (sysctl_protected_fifos >= 2 && S_ISFIFO(inode->i_mode)) {
1273 audit_log_path_denied(AUDIT_ANOM_CREAT,
1274 "sticky_create_fifo");
1278 if (sysctl_protected_regular >= 2 && S_ISREG(inode->i_mode)) {
1279 audit_log_path_denied(AUDIT_ANOM_CREAT,
1280 "sticky_create_regular");
1289 * follow_up - Find the mountpoint of path's vfsmount
1291 * Given a path, find the mountpoint of its source file system.
1292 * Replace @path with the path of the mountpoint in the parent mount.
1295 * Return 1 if we went up a level and 0 if we were already at the
1298 int follow_up(struct path *path)
1300 struct mount *mnt = real_mount(path->mnt);
1301 struct mount *parent;
1302 struct dentry *mountpoint;
1304 read_seqlock_excl(&mount_lock);
1305 parent = mnt->mnt_parent;
1306 if (parent == mnt) {
1307 read_sequnlock_excl(&mount_lock);
1310 mntget(&parent->mnt);
1311 mountpoint = dget(mnt->mnt_mountpoint);
1312 read_sequnlock_excl(&mount_lock);
1314 path->dentry = mountpoint;
1316 path->mnt = &parent->mnt;
1319 EXPORT_SYMBOL(follow_up);
1321 static bool choose_mountpoint_rcu(struct mount *m, const struct path *root,
1322 struct path *path, unsigned *seqp)
1324 while (mnt_has_parent(m)) {
1325 struct dentry *mountpoint = m->mnt_mountpoint;
1328 if (unlikely(root->dentry == mountpoint &&
1329 root->mnt == &m->mnt))
1331 if (mountpoint != m->mnt.mnt_root) {
1332 path->mnt = &m->mnt;
1333 path->dentry = mountpoint;
1334 *seqp = read_seqcount_begin(&mountpoint->d_seq);
1341 static bool choose_mountpoint(struct mount *m, const struct path *root,
1348 unsigned seq, mseq = read_seqbegin(&mount_lock);
1350 found = choose_mountpoint_rcu(m, root, path, &seq);
1351 if (unlikely(!found)) {
1352 if (!read_seqretry(&mount_lock, mseq))
1355 if (likely(__legitimize_path(path, seq, mseq)))
1367 * Perform an automount
1368 * - return -EISDIR to tell follow_managed() to stop and return the path we
1371 static int follow_automount(struct path *path, int *count, unsigned lookup_flags)
1373 struct dentry *dentry = path->dentry;
1375 /* We don't want to mount if someone's just doing a stat -
1376 * unless they're stat'ing a directory and appended a '/' to
1379 * We do, however, want to mount if someone wants to open or
1380 * create a file of any type under the mountpoint, wants to
1381 * traverse through the mountpoint or wants to open the
1382 * mounted directory. Also, autofs may mark negative dentries
1383 * as being automount points. These will need the attentions
1384 * of the daemon to instantiate them before they can be used.
1386 if (!(lookup_flags & (LOOKUP_PARENT | LOOKUP_DIRECTORY |
1387 LOOKUP_OPEN | LOOKUP_CREATE | LOOKUP_AUTOMOUNT)) &&
1391 if (count && (*count)++ >= MAXSYMLINKS)
1394 return finish_automount(dentry->d_op->d_automount(path), path);
1398 * mount traversal - out-of-line part. One note on ->d_flags accesses -
1399 * dentries are pinned but not locked here, so negative dentry can go
1400 * positive right under us. Use of smp_load_acquire() provides a barrier
1401 * sufficient for ->d_inode and ->d_flags consistency.
1403 static int __traverse_mounts(struct path *path, unsigned flags, bool *jumped,
1404 int *count, unsigned lookup_flags)
1406 struct vfsmount *mnt = path->mnt;
1407 bool need_mntput = false;
1410 while (flags & DCACHE_MANAGED_DENTRY) {
1411 /* Allow the filesystem to manage the transit without i_mutex
1413 if (flags & DCACHE_MANAGE_TRANSIT) {
1414 ret = path->dentry->d_op->d_manage(path, false);
1415 flags = smp_load_acquire(&path->dentry->d_flags);
1420 if (flags & DCACHE_MOUNTED) { // something's mounted on it..
1421 struct vfsmount *mounted = lookup_mnt(path);
1422 if (mounted) { // ... in our namespace
1426 path->mnt = mounted;
1427 path->dentry = dget(mounted->mnt_root);
1428 // here we know it's positive
1429 flags = path->dentry->d_flags;
1435 if (!(flags & DCACHE_NEED_AUTOMOUNT))
1438 // uncovered automount point
1439 ret = follow_automount(path, count, lookup_flags);
1440 flags = smp_load_acquire(&path->dentry->d_flags);
1447 // possible if you race with several mount --move
1448 if (need_mntput && path->mnt == mnt)
1450 if (!ret && unlikely(d_flags_negative(flags)))
1452 *jumped = need_mntput;
1456 static inline int traverse_mounts(struct path *path, bool *jumped,
1457 int *count, unsigned lookup_flags)
1459 unsigned flags = smp_load_acquire(&path->dentry->d_flags);
1462 if (likely(!(flags & DCACHE_MANAGED_DENTRY))) {
1464 if (unlikely(d_flags_negative(flags)))
1468 return __traverse_mounts(path, flags, jumped, count, lookup_flags);
1471 int follow_down_one(struct path *path)
1473 struct vfsmount *mounted;
1475 mounted = lookup_mnt(path);
1479 path->mnt = mounted;
1480 path->dentry = dget(mounted->mnt_root);
1485 EXPORT_SYMBOL(follow_down_one);
1488 * Follow down to the covering mount currently visible to userspace. At each
1489 * point, the filesystem owning that dentry may be queried as to whether the
1490 * caller is permitted to proceed or not.
1492 int follow_down(struct path *path, unsigned int flags)
1494 struct vfsmount *mnt = path->mnt;
1496 int ret = traverse_mounts(path, &jumped, NULL, flags);
1498 if (path->mnt != mnt)
1502 EXPORT_SYMBOL(follow_down);
1505 * Try to skip to top of mountpoint pile in rcuwalk mode. Fail if
1506 * we meet a managed dentry that would need blocking.
1508 static bool __follow_mount_rcu(struct nameidata *nd, struct path *path)
1510 struct dentry *dentry = path->dentry;
1511 unsigned int flags = dentry->d_flags;
1513 if (likely(!(flags & DCACHE_MANAGED_DENTRY)))
1516 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1521 * Don't forget we might have a non-mountpoint managed dentry
1522 * that wants to block transit.
1524 if (unlikely(flags & DCACHE_MANAGE_TRANSIT)) {
1525 int res = dentry->d_op->d_manage(path, true);
1527 return res == -EISDIR;
1528 flags = dentry->d_flags;
1531 if (flags & DCACHE_MOUNTED) {
1532 struct mount *mounted = __lookup_mnt(path->mnt, dentry);
1534 path->mnt = &mounted->mnt;
1535 dentry = path->dentry = mounted->mnt.mnt_root;
1536 nd->state |= ND_JUMPED;
1537 nd->next_seq = read_seqcount_begin(&dentry->d_seq);
1538 flags = dentry->d_flags;
1539 // makes sure that non-RCU pathwalk could reach
1541 if (read_seqretry(&mount_lock, nd->m_seq))
1545 if (read_seqretry(&mount_lock, nd->m_seq))
1548 return !(flags & DCACHE_NEED_AUTOMOUNT);
1552 static inline int handle_mounts(struct nameidata *nd, struct dentry *dentry,
1558 path->mnt = nd->path.mnt;
1559 path->dentry = dentry;
1560 if (nd->flags & LOOKUP_RCU) {
1561 unsigned int seq = nd->next_seq;
1562 if (likely(__follow_mount_rcu(nd, path)))
1564 // *path and nd->next_seq might've been clobbered
1565 path->mnt = nd->path.mnt;
1566 path->dentry = dentry;
1568 if (!try_to_unlazy_next(nd, dentry))
1571 ret = traverse_mounts(path, &jumped, &nd->total_link_count, nd->flags);
1573 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1576 nd->state |= ND_JUMPED;
1578 if (unlikely(ret)) {
1580 if (path->mnt != nd->path.mnt)
1587 * This looks up the name in dcache and possibly revalidates the found dentry.
1588 * NULL is returned if the dentry does not exist in the cache.
1590 static struct dentry *lookup_dcache(const struct qstr *name,
1594 struct dentry *dentry = d_lookup(dir, name);
1596 int error = d_revalidate(dentry, flags);
1597 if (unlikely(error <= 0)) {
1599 d_invalidate(dentry);
1601 return ERR_PTR(error);
1608 * Parent directory has inode locked exclusive. This is one
1609 * and only case when ->lookup() gets called on non in-lookup
1610 * dentries - as the matter of fact, this only gets called
1611 * when directory is guaranteed to have no in-lookup children
1614 struct dentry *lookup_one_qstr_excl(const struct qstr *name,
1615 struct dentry *base,
1618 struct dentry *dentry = lookup_dcache(name, base, flags);
1620 struct inode *dir = base->d_inode;
1625 /* Don't create child dentry for a dead directory. */
1626 if (unlikely(IS_DEADDIR(dir)))
1627 return ERR_PTR(-ENOENT);
1629 dentry = d_alloc(base, name);
1630 if (unlikely(!dentry))
1631 return ERR_PTR(-ENOMEM);
1633 old = dir->i_op->lookup(dir, dentry, flags);
1634 if (unlikely(old)) {
1640 EXPORT_SYMBOL(lookup_one_qstr_excl);
1642 static struct dentry *lookup_fast(struct nameidata *nd)
1644 struct dentry *dentry, *parent = nd->path.dentry;
1648 * Rename seqlock is not required here because in the off chance
1649 * of a false negative due to a concurrent rename, the caller is
1650 * going to fall back to non-racy lookup.
1652 if (nd->flags & LOOKUP_RCU) {
1653 dentry = __d_lookup_rcu(parent, &nd->last, &nd->next_seq);
1654 if (unlikely(!dentry)) {
1655 if (!try_to_unlazy(nd))
1656 return ERR_PTR(-ECHILD);
1661 * This sequence count validates that the parent had no
1662 * changes while we did the lookup of the dentry above.
1664 if (read_seqcount_retry(&parent->d_seq, nd->seq))
1665 return ERR_PTR(-ECHILD);
1667 status = d_revalidate(dentry, nd->flags);
1668 if (likely(status > 0))
1670 if (!try_to_unlazy_next(nd, dentry))
1671 return ERR_PTR(-ECHILD);
1672 if (status == -ECHILD)
1673 /* we'd been told to redo it in non-rcu mode */
1674 status = d_revalidate(dentry, nd->flags);
1676 dentry = __d_lookup(parent, &nd->last);
1677 if (unlikely(!dentry))
1679 status = d_revalidate(dentry, nd->flags);
1681 if (unlikely(status <= 0)) {
1683 d_invalidate(dentry);
1685 return ERR_PTR(status);
1690 /* Fast lookup failed, do it the slow way */
1691 static struct dentry *__lookup_slow(const struct qstr *name,
1695 struct dentry *dentry, *old;
1696 struct inode *inode = dir->d_inode;
1697 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
1699 /* Don't go there if it's already dead */
1700 if (unlikely(IS_DEADDIR(inode)))
1701 return ERR_PTR(-ENOENT);
1703 dentry = d_alloc_parallel(dir, name, &wq);
1706 if (unlikely(!d_in_lookup(dentry))) {
1707 int error = d_revalidate(dentry, flags);
1708 if (unlikely(error <= 0)) {
1710 d_invalidate(dentry);
1715 dentry = ERR_PTR(error);
1718 old = inode->i_op->lookup(inode, dentry, flags);
1719 d_lookup_done(dentry);
1720 if (unlikely(old)) {
1728 static struct dentry *lookup_slow(const struct qstr *name,
1732 struct inode *inode = dir->d_inode;
1734 inode_lock_shared(inode);
1735 res = __lookup_slow(name, dir, flags);
1736 inode_unlock_shared(inode);
1740 static inline int may_lookup(struct mnt_idmap *idmap,
1741 struct nameidata *restrict nd)
1745 mask = nd->flags & LOOKUP_RCU ? MAY_NOT_BLOCK : 0;
1746 err = inode_permission(idmap, nd->inode, mask | MAY_EXEC);
1750 // If we failed, and we weren't in LOOKUP_RCU, it's final
1751 if (!(nd->flags & LOOKUP_RCU))
1754 // Drop out of RCU mode to make sure it wasn't transient
1755 if (!try_to_unlazy(nd))
1756 return -ECHILD; // redo it all non-lazy
1758 if (err != -ECHILD) // hard error
1761 return inode_permission(idmap, nd->inode, MAY_EXEC);
1764 static int reserve_stack(struct nameidata *nd, struct path *link)
1766 if (unlikely(nd->total_link_count++ >= MAXSYMLINKS))
1769 if (likely(nd->depth != EMBEDDED_LEVELS))
1771 if (likely(nd->stack != nd->internal))
1773 if (likely(nd_alloc_stack(nd)))
1776 if (nd->flags & LOOKUP_RCU) {
1777 // we need to grab link before we do unlazy. And we can't skip
1778 // unlazy even if we fail to grab the link - cleanup needs it
1779 bool grabbed_link = legitimize_path(nd, link, nd->next_seq);
1781 if (!try_to_unlazy(nd) || !grabbed_link)
1784 if (nd_alloc_stack(nd))
1790 enum {WALK_TRAILING = 1, WALK_MORE = 2, WALK_NOFOLLOW = 4};
1792 static const char *pick_link(struct nameidata *nd, struct path *link,
1793 struct inode *inode, int flags)
1797 int error = reserve_stack(nd, link);
1799 if (unlikely(error)) {
1800 if (!(nd->flags & LOOKUP_RCU))
1802 return ERR_PTR(error);
1804 last = nd->stack + nd->depth++;
1806 clear_delayed_call(&last->done);
1807 last->seq = nd->next_seq;
1809 if (flags & WALK_TRAILING) {
1810 error = may_follow_link(nd, inode);
1811 if (unlikely(error))
1812 return ERR_PTR(error);
1815 if (unlikely(nd->flags & LOOKUP_NO_SYMLINKS) ||
1816 unlikely(link->mnt->mnt_flags & MNT_NOSYMFOLLOW))
1817 return ERR_PTR(-ELOOP);
1819 if (!(nd->flags & LOOKUP_RCU)) {
1820 touch_atime(&last->link);
1822 } else if (atime_needs_update(&last->link, inode)) {
1823 if (!try_to_unlazy(nd))
1824 return ERR_PTR(-ECHILD);
1825 touch_atime(&last->link);
1828 error = security_inode_follow_link(link->dentry, inode,
1829 nd->flags & LOOKUP_RCU);
1830 if (unlikely(error))
1831 return ERR_PTR(error);
1833 res = READ_ONCE(inode->i_link);
1835 const char * (*get)(struct dentry *, struct inode *,
1836 struct delayed_call *);
1837 get = inode->i_op->get_link;
1838 if (nd->flags & LOOKUP_RCU) {
1839 res = get(NULL, inode, &last->done);
1840 if (res == ERR_PTR(-ECHILD) && try_to_unlazy(nd))
1841 res = get(link->dentry, inode, &last->done);
1843 res = get(link->dentry, inode, &last->done);
1851 error = nd_jump_root(nd);
1852 if (unlikely(error))
1853 return ERR_PTR(error);
1854 while (unlikely(*++res == '/'))
1859 all_done: // pure jump
1865 * Do we need to follow links? We _really_ want to be able
1866 * to do this check without having to look at inode->i_op,
1867 * so we keep a cache of "no, this doesn't need follow_link"
1868 * for the common case.
1870 * NOTE: dentry must be what nd->next_seq had been sampled from.
1872 static const char *step_into(struct nameidata *nd, int flags,
1873 struct dentry *dentry)
1876 struct inode *inode;
1877 int err = handle_mounts(nd, dentry, &path);
1880 return ERR_PTR(err);
1881 inode = path.dentry->d_inode;
1882 if (likely(!d_is_symlink(path.dentry)) ||
1883 ((flags & WALK_TRAILING) && !(nd->flags & LOOKUP_FOLLOW)) ||
1884 (flags & WALK_NOFOLLOW)) {
1885 /* not a symlink or should not follow */
1886 if (nd->flags & LOOKUP_RCU) {
1887 if (read_seqcount_retry(&path.dentry->d_seq, nd->next_seq))
1888 return ERR_PTR(-ECHILD);
1889 if (unlikely(!inode))
1890 return ERR_PTR(-ENOENT);
1892 dput(nd->path.dentry);
1893 if (nd->path.mnt != path.mnt)
1894 mntput(nd->path.mnt);
1898 nd->seq = nd->next_seq;
1901 if (nd->flags & LOOKUP_RCU) {
1902 /* make sure that d_is_symlink above matches inode */
1903 if (read_seqcount_retry(&path.dentry->d_seq, nd->next_seq))
1904 return ERR_PTR(-ECHILD);
1906 if (path.mnt == nd->path.mnt)
1909 return pick_link(nd, &path, inode, flags);
1912 static struct dentry *follow_dotdot_rcu(struct nameidata *nd)
1914 struct dentry *parent, *old;
1916 if (path_equal(&nd->path, &nd->root))
1918 if (unlikely(nd->path.dentry == nd->path.mnt->mnt_root)) {
1921 if (!choose_mountpoint_rcu(real_mount(nd->path.mnt),
1922 &nd->root, &path, &seq))
1924 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1925 return ERR_PTR(-ECHILD);
1927 nd->inode = path.dentry->d_inode;
1929 // makes sure that non-RCU pathwalk could reach this state
1930 if (read_seqretry(&mount_lock, nd->m_seq))
1931 return ERR_PTR(-ECHILD);
1932 /* we know that mountpoint was pinned */
1934 old = nd->path.dentry;
1935 parent = old->d_parent;
1936 nd->next_seq = read_seqcount_begin(&parent->d_seq);
1937 // makes sure that non-RCU pathwalk could reach this state
1938 if (read_seqcount_retry(&old->d_seq, nd->seq))
1939 return ERR_PTR(-ECHILD);
1940 if (unlikely(!path_connected(nd->path.mnt, parent)))
1941 return ERR_PTR(-ECHILD);
1944 if (read_seqretry(&mount_lock, nd->m_seq))
1945 return ERR_PTR(-ECHILD);
1946 if (unlikely(nd->flags & LOOKUP_BENEATH))
1947 return ERR_PTR(-ECHILD);
1948 nd->next_seq = nd->seq;
1949 return nd->path.dentry;
1952 static struct dentry *follow_dotdot(struct nameidata *nd)
1954 struct dentry *parent;
1956 if (path_equal(&nd->path, &nd->root))
1958 if (unlikely(nd->path.dentry == nd->path.mnt->mnt_root)) {
1961 if (!choose_mountpoint(real_mount(nd->path.mnt),
1964 path_put(&nd->path);
1966 nd->inode = path.dentry->d_inode;
1967 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1968 return ERR_PTR(-EXDEV);
1970 /* rare case of legitimate dget_parent()... */
1971 parent = dget_parent(nd->path.dentry);
1972 if (unlikely(!path_connected(nd->path.mnt, parent))) {
1974 return ERR_PTR(-ENOENT);
1979 if (unlikely(nd->flags & LOOKUP_BENEATH))
1980 return ERR_PTR(-EXDEV);
1981 return dget(nd->path.dentry);
1984 static const char *handle_dots(struct nameidata *nd, int type)
1986 if (type == LAST_DOTDOT) {
1987 const char *error = NULL;
1988 struct dentry *parent;
1990 if (!nd->root.mnt) {
1991 error = ERR_PTR(set_root(nd));
1995 if (nd->flags & LOOKUP_RCU)
1996 parent = follow_dotdot_rcu(nd);
1998 parent = follow_dotdot(nd);
2000 return ERR_CAST(parent);
2001 error = step_into(nd, WALK_NOFOLLOW, parent);
2002 if (unlikely(error))
2005 if (unlikely(nd->flags & LOOKUP_IS_SCOPED)) {
2007 * If there was a racing rename or mount along our
2008 * path, then we can't be sure that ".." hasn't jumped
2009 * above nd->root (and so userspace should retry or use
2013 if (__read_seqcount_retry(&mount_lock.seqcount, nd->m_seq))
2014 return ERR_PTR(-EAGAIN);
2015 if (__read_seqcount_retry(&rename_lock.seqcount, nd->r_seq))
2016 return ERR_PTR(-EAGAIN);
2022 static const char *walk_component(struct nameidata *nd, int flags)
2024 struct dentry *dentry;
2026 * "." and ".." are special - ".." especially so because it has
2027 * to be able to know about the current root directory and
2028 * parent relationships.
2030 if (unlikely(nd->last_type != LAST_NORM)) {
2031 if (!(flags & WALK_MORE) && nd->depth)
2033 return handle_dots(nd, nd->last_type);
2035 dentry = lookup_fast(nd);
2037 return ERR_CAST(dentry);
2038 if (unlikely(!dentry)) {
2039 dentry = lookup_slow(&nd->last, nd->path.dentry, nd->flags);
2041 return ERR_CAST(dentry);
2043 if (!(flags & WALK_MORE) && nd->depth)
2045 return step_into(nd, flags, dentry);
2049 * We can do the critical dentry name comparison and hashing
2050 * operations one word at a time, but we are limited to:
2052 * - Architectures with fast unaligned word accesses. We could
2053 * do a "get_unaligned()" if this helps and is sufficiently
2056 * - non-CONFIG_DEBUG_PAGEALLOC configurations (so that we
2057 * do not trap on the (extremely unlikely) case of a page
2058 * crossing operation.
2060 * - Furthermore, we need an efficient 64-bit compile for the
2061 * 64-bit case in order to generate the "number of bytes in
2062 * the final mask". Again, that could be replaced with a
2063 * efficient population count instruction or similar.
2065 #ifdef CONFIG_DCACHE_WORD_ACCESS
2067 #include <asm/word-at-a-time.h>
2071 /* Architecture provides HASH_MIX and fold_hash() in <asm/hash.h> */
2073 #elif defined(CONFIG_64BIT)
2075 * Register pressure in the mixing function is an issue, particularly
2076 * on 32-bit x86, but almost any function requires one state value and
2077 * one temporary. Instead, use a function designed for two state values
2078 * and no temporaries.
2080 * This function cannot create a collision in only two iterations, so
2081 * we have two iterations to achieve avalanche. In those two iterations,
2082 * we have six layers of mixing, which is enough to spread one bit's
2083 * influence out to 2^6 = 64 state bits.
2085 * Rotate constants are scored by considering either 64 one-bit input
2086 * deltas or 64*63/2 = 2016 two-bit input deltas, and finding the
2087 * probability of that delta causing a change to each of the 128 output
2088 * bits, using a sample of random initial states.
2090 * The Shannon entropy of the computed probabilities is then summed
2091 * to produce a score. Ideally, any input change has a 50% chance of
2092 * toggling any given output bit.
2094 * Mixing scores (in bits) for (12,45):
2095 * Input delta: 1-bit 2-bit
2096 * 1 round: 713.3 42542.6
2097 * 2 rounds: 2753.7 140389.8
2098 * 3 rounds: 5954.1 233458.2
2099 * 4 rounds: 7862.6 256672.2
2100 * Perfect: 8192 258048
2101 * (64*128) (64*63/2 * 128)
2103 #define HASH_MIX(x, y, a) \
2105 y ^= x, x = rol64(x,12),\
2106 x += y, y = rol64(y,45),\
2110 * Fold two longs into one 32-bit hash value. This must be fast, but
2111 * latency isn't quite as critical, as there is a fair bit of additional
2112 * work done before the hash value is used.
2114 static inline unsigned int fold_hash(unsigned long x, unsigned long y)
2116 y ^= x * GOLDEN_RATIO_64;
2117 y *= GOLDEN_RATIO_64;
2121 #else /* 32-bit case */
2124 * Mixing scores (in bits) for (7,20):
2125 * Input delta: 1-bit 2-bit
2126 * 1 round: 330.3 9201.6
2127 * 2 rounds: 1246.4 25475.4
2128 * 3 rounds: 1907.1 31295.1
2129 * 4 rounds: 2042.3 31718.6
2130 * Perfect: 2048 31744
2131 * (32*64) (32*31/2 * 64)
2133 #define HASH_MIX(x, y, a) \
2135 y ^= x, x = rol32(x, 7),\
2136 x += y, y = rol32(y,20),\
2139 static inline unsigned int fold_hash(unsigned long x, unsigned long y)
2141 /* Use arch-optimized multiply if one exists */
2142 return __hash_32(y ^ __hash_32(x));
2148 * Return the hash of a string of known length. This is carfully
2149 * designed to match hash_name(), which is the more critical function.
2150 * In particular, we must end by hashing a final word containing 0..7
2151 * payload bytes, to match the way that hash_name() iterates until it
2152 * finds the delimiter after the name.
2154 unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
2156 unsigned long a, x = 0, y = (unsigned long)salt;
2161 a = load_unaligned_zeropad(name);
2162 if (len < sizeof(unsigned long))
2165 name += sizeof(unsigned long);
2166 len -= sizeof(unsigned long);
2168 x ^= a & bytemask_from_count(len);
2170 return fold_hash(x, y);
2172 EXPORT_SYMBOL(full_name_hash);
2174 /* Return the "hash_len" (hash and length) of a null-terminated string */
2175 u64 hashlen_string(const void *salt, const char *name)
2177 unsigned long a = 0, x = 0, y = (unsigned long)salt;
2178 unsigned long adata, mask, len;
2179 const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2186 len += sizeof(unsigned long);
2188 a = load_unaligned_zeropad(name+len);
2189 } while (!has_zero(a, &adata, &constants));
2191 adata = prep_zero_mask(a, adata, &constants);
2192 mask = create_zero_mask(adata);
2193 x ^= a & zero_bytemask(mask);
2195 return hashlen_create(fold_hash(x, y), len + find_zero(mask));
2197 EXPORT_SYMBOL(hashlen_string);
2200 * Calculate the length and hash of the path component, and
2201 * return the length as the result.
2203 static inline const char *hash_name(struct nameidata *nd,
2205 unsigned long *lastword)
2207 unsigned long a, b, x, y = (unsigned long)nd->path.dentry;
2208 unsigned long adata, bdata, mask, len;
2209 const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2212 * The first iteration is special, because it can result in
2213 * '.' and '..' and has no mixing other than the final fold.
2215 a = load_unaligned_zeropad(name);
2216 b = a ^ REPEAT_BYTE('/');
2217 if (has_zero(a, &adata, &constants) | has_zero(b, &bdata, &constants)) {
2218 adata = prep_zero_mask(a, adata, &constants);
2219 bdata = prep_zero_mask(b, bdata, &constants);
2220 mask = create_zero_mask(adata | bdata);
2221 a &= zero_bytemask(mask);
2223 len = find_zero(mask);
2224 nd->last.hash = fold_hash(a, y);
2233 len += sizeof(unsigned long);
2234 a = load_unaligned_zeropad(name+len);
2235 b = a ^ REPEAT_BYTE('/');
2236 } while (!(has_zero(a, &adata, &constants) | has_zero(b, &bdata, &constants)));
2238 adata = prep_zero_mask(a, adata, &constants);
2239 bdata = prep_zero_mask(b, bdata, &constants);
2240 mask = create_zero_mask(adata | bdata);
2241 a &= zero_bytemask(mask);
2243 len += find_zero(mask);
2244 *lastword = 0; // Multi-word components cannot be DOT or DOTDOT
2246 nd->last.hash = fold_hash(x, y);
2252 * Note that the 'last' word is always zero-masked, but
2253 * was loaded as a possibly big-endian word.
2256 #define LAST_WORD_IS_DOT (0x2eul << (BITS_PER_LONG-8))
2257 #define LAST_WORD_IS_DOTDOT (0x2e2eul << (BITS_PER_LONG-16))
2260 #else /* !CONFIG_DCACHE_WORD_ACCESS: Slow, byte-at-a-time version */
2262 /* Return the hash of a string of known length */
2263 unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
2265 unsigned long hash = init_name_hash(salt);
2267 hash = partial_name_hash((unsigned char)*name++, hash);
2268 return end_name_hash(hash);
2270 EXPORT_SYMBOL(full_name_hash);
2272 /* Return the "hash_len" (hash and length) of a null-terminated string */
2273 u64 hashlen_string(const void *salt, const char *name)
2275 unsigned long hash = init_name_hash(salt);
2276 unsigned long len = 0, c;
2278 c = (unsigned char)*name;
2281 hash = partial_name_hash(c, hash);
2282 c = (unsigned char)name[len];
2284 return hashlen_create(end_name_hash(hash), len);
2286 EXPORT_SYMBOL(hashlen_string);
2289 * We know there's a real path component here of at least
2292 static inline const char *hash_name(struct nameidata *nd, const char *name, unsigned long *lastword)
2294 unsigned long hash = init_name_hash(nd->path.dentry);
2295 unsigned long len = 0, c, last = 0;
2297 c = (unsigned char)*name;
2299 last = (last << 8) + c;
2301 hash = partial_name_hash(c, hash);
2302 c = (unsigned char)name[len];
2303 } while (c && c != '/');
2305 // This is reliable for DOT or DOTDOT, since the component
2306 // cannot contain NUL characters - top bits being zero means
2307 // we cannot have had any other pathnames.
2309 nd->last.hash = end_name_hash(hash);
2316 #ifndef LAST_WORD_IS_DOT
2317 #define LAST_WORD_IS_DOT 0x2e
2318 #define LAST_WORD_IS_DOTDOT 0x2e2e
2323 * This is the basic name resolution function, turning a pathname into
2324 * the final dentry. We expect 'base' to be positive and a directory.
2326 * Returns 0 and nd will have valid dentry and mnt on success.
2327 * Returns error and drops reference to input namei data on failure.
2329 static int link_path_walk(const char *name, struct nameidata *nd)
2331 int depth = 0; // depth <= nd->depth
2334 nd->last_type = LAST_ROOT;
2335 nd->flags |= LOOKUP_PARENT;
2337 return PTR_ERR(name);
2341 nd->dir_mode = 0; // short-circuit the 'hardening' idiocy
2345 /* At this point we know we have a real path component. */
2347 struct mnt_idmap *idmap;
2349 unsigned long lastword;
2351 idmap = mnt_idmap(nd->path.mnt);
2352 err = may_lookup(idmap, nd);
2356 nd->last.name = name;
2357 name = hash_name(nd, name, &lastword);
2360 case LAST_WORD_IS_DOTDOT:
2361 nd->last_type = LAST_DOTDOT;
2362 nd->state |= ND_JUMPED;
2365 case LAST_WORD_IS_DOT:
2366 nd->last_type = LAST_DOT;
2370 nd->last_type = LAST_NORM;
2371 nd->state &= ~ND_JUMPED;
2373 struct dentry *parent = nd->path.dentry;
2374 if (unlikely(parent->d_flags & DCACHE_OP_HASH)) {
2375 err = parent->d_op->d_hash(parent, &nd->last);
2384 * If it wasn't NUL, we know it was '/'. Skip that
2385 * slash, and continue until no more slashes.
2389 } while (unlikely(*name == '/'));
2390 if (unlikely(!*name)) {
2392 /* pathname or trailing symlink, done */
2394 nd->dir_vfsuid = i_uid_into_vfsuid(idmap, nd->inode);
2395 nd->dir_mode = nd->inode->i_mode;
2396 nd->flags &= ~LOOKUP_PARENT;
2399 /* last component of nested symlink */
2400 name = nd->stack[--depth].name;
2401 link = walk_component(nd, 0);
2403 /* not the last component */
2404 link = walk_component(nd, WALK_MORE);
2406 if (unlikely(link)) {
2408 return PTR_ERR(link);
2409 /* a symlink to follow */
2410 nd->stack[depth++].name = name;
2414 if (unlikely(!d_can_lookup(nd->path.dentry))) {
2415 if (nd->flags & LOOKUP_RCU) {
2416 if (!try_to_unlazy(nd))
2424 /* must be paired with terminate_walk() */
2425 static const char *path_init(struct nameidata *nd, unsigned flags)
2428 const char *s = nd->name->name;
2430 /* LOOKUP_CACHED requires RCU, ask caller to retry */
2431 if ((flags & (LOOKUP_RCU | LOOKUP_CACHED)) == LOOKUP_CACHED)
2432 return ERR_PTR(-EAGAIN);
2435 flags &= ~LOOKUP_RCU;
2436 if (flags & LOOKUP_RCU)
2439 nd->seq = nd->next_seq = 0;
2442 nd->state |= ND_JUMPED;
2444 nd->m_seq = __read_seqcount_begin(&mount_lock.seqcount);
2445 nd->r_seq = __read_seqcount_begin(&rename_lock.seqcount);
2448 if (nd->state & ND_ROOT_PRESET) {
2449 struct dentry *root = nd->root.dentry;
2450 struct inode *inode = root->d_inode;
2451 if (*s && unlikely(!d_can_lookup(root)))
2452 return ERR_PTR(-ENOTDIR);
2453 nd->path = nd->root;
2455 if (flags & LOOKUP_RCU) {
2456 nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
2457 nd->root_seq = nd->seq;
2459 path_get(&nd->path);
2464 nd->root.mnt = NULL;
2466 /* Absolute pathname -- fetch the root (LOOKUP_IN_ROOT uses nd->dfd). */
2467 if (*s == '/' && !(flags & LOOKUP_IN_ROOT)) {
2468 error = nd_jump_root(nd);
2469 if (unlikely(error))
2470 return ERR_PTR(error);
2474 /* Relative pathname -- get the starting-point it is relative to. */
2475 if (nd->dfd == AT_FDCWD) {
2476 if (flags & LOOKUP_RCU) {
2477 struct fs_struct *fs = current->fs;
2481 seq = read_seqcount_begin(&fs->seq);
2483 nd->inode = nd->path.dentry->d_inode;
2484 nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
2485 } while (read_seqcount_retry(&fs->seq, seq));
2487 get_fs_pwd(current->fs, &nd->path);
2488 nd->inode = nd->path.dentry->d_inode;
2491 /* Caller must check execute permissions on the starting path component */
2492 struct fd f = fdget_raw(nd->dfd);
2493 struct dentry *dentry;
2496 return ERR_PTR(-EBADF);
2498 if (flags & LOOKUP_LINKAT_EMPTY) {
2499 if (f.file->f_cred != current_cred() &&
2500 !ns_capable(f.file->f_cred->user_ns, CAP_DAC_READ_SEARCH)) {
2502 return ERR_PTR(-ENOENT);
2506 dentry = f.file->f_path.dentry;
2508 if (*s && unlikely(!d_can_lookup(dentry))) {
2510 return ERR_PTR(-ENOTDIR);
2513 nd->path = f.file->f_path;
2514 if (flags & LOOKUP_RCU) {
2515 nd->inode = nd->path.dentry->d_inode;
2516 nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
2518 path_get(&nd->path);
2519 nd->inode = nd->path.dentry->d_inode;
2524 /* For scoped-lookups we need to set the root to the dirfd as well. */
2525 if (flags & LOOKUP_IS_SCOPED) {
2526 nd->root = nd->path;
2527 if (flags & LOOKUP_RCU) {
2528 nd->root_seq = nd->seq;
2530 path_get(&nd->root);
2531 nd->state |= ND_ROOT_GRABBED;
2537 static inline const char *lookup_last(struct nameidata *nd)
2539 if (nd->last_type == LAST_NORM && nd->last.name[nd->last.len])
2540 nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
2542 return walk_component(nd, WALK_TRAILING);
2545 static int handle_lookup_down(struct nameidata *nd)
2547 if (!(nd->flags & LOOKUP_RCU))
2548 dget(nd->path.dentry);
2549 nd->next_seq = nd->seq;
2550 return PTR_ERR(step_into(nd, WALK_NOFOLLOW, nd->path.dentry));
2553 /* Returns 0 and nd will be valid on success; Returns error, otherwise. */
2554 static int path_lookupat(struct nameidata *nd, unsigned flags, struct path *path)
2556 const char *s = path_init(nd, flags);
2559 if (unlikely(flags & LOOKUP_DOWN) && !IS_ERR(s)) {
2560 err = handle_lookup_down(nd);
2561 if (unlikely(err < 0))
2565 while (!(err = link_path_walk(s, nd)) &&
2566 (s = lookup_last(nd)) != NULL)
2568 if (!err && unlikely(nd->flags & LOOKUP_MOUNTPOINT)) {
2569 err = handle_lookup_down(nd);
2570 nd->state &= ~ND_JUMPED; // no d_weak_revalidate(), please...
2573 err = complete_walk(nd);
2575 if (!err && nd->flags & LOOKUP_DIRECTORY)
2576 if (!d_can_lookup(nd->path.dentry))
2580 nd->path.mnt = NULL;
2581 nd->path.dentry = NULL;
2587 int filename_lookup(int dfd, struct filename *name, unsigned flags,
2588 struct path *path, struct path *root)
2591 struct nameidata nd;
2593 return PTR_ERR(name);
2594 set_nameidata(&nd, dfd, name, root);
2595 retval = path_lookupat(&nd, flags | LOOKUP_RCU, path);
2596 if (unlikely(retval == -ECHILD))
2597 retval = path_lookupat(&nd, flags, path);
2598 if (unlikely(retval == -ESTALE))
2599 retval = path_lookupat(&nd, flags | LOOKUP_REVAL, path);
2601 if (likely(!retval))
2602 audit_inode(name, path->dentry,
2603 flags & LOOKUP_MOUNTPOINT ? AUDIT_INODE_NOEVAL : 0);
2604 restore_nameidata();
2608 /* Returns 0 and nd will be valid on success; Returns error, otherwise. */
2609 static int path_parentat(struct nameidata *nd, unsigned flags,
2610 struct path *parent)
2612 const char *s = path_init(nd, flags);
2613 int err = link_path_walk(s, nd);
2615 err = complete_walk(nd);
2618 nd->path.mnt = NULL;
2619 nd->path.dentry = NULL;
2625 /* Note: this does not consume "name" */
2626 static int __filename_parentat(int dfd, struct filename *name,
2627 unsigned int flags, struct path *parent,
2628 struct qstr *last, int *type,
2629 const struct path *root)
2632 struct nameidata nd;
2635 return PTR_ERR(name);
2636 set_nameidata(&nd, dfd, name, root);
2637 retval = path_parentat(&nd, flags | LOOKUP_RCU, parent);
2638 if (unlikely(retval == -ECHILD))
2639 retval = path_parentat(&nd, flags, parent);
2640 if (unlikely(retval == -ESTALE))
2641 retval = path_parentat(&nd, flags | LOOKUP_REVAL, parent);
2642 if (likely(!retval)) {
2644 *type = nd.last_type;
2645 audit_inode(name, parent->dentry, AUDIT_INODE_PARENT);
2647 restore_nameidata();
2651 static int filename_parentat(int dfd, struct filename *name,
2652 unsigned int flags, struct path *parent,
2653 struct qstr *last, int *type)
2655 return __filename_parentat(dfd, name, flags, parent, last, type, NULL);
2658 /* does lookup, returns the object with parent locked */
2659 static struct dentry *__kern_path_locked(int dfd, struct filename *name, struct path *path)
2665 error = filename_parentat(dfd, name, 0, path, &last, &type);
2667 return ERR_PTR(error);
2668 if (unlikely(type != LAST_NORM)) {
2670 return ERR_PTR(-EINVAL);
2672 inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
2673 d = lookup_one_qstr_excl(&last, path->dentry, 0);
2675 inode_unlock(path->dentry->d_inode);
2681 struct dentry *kern_path_locked(const char *name, struct path *path)
2683 struct filename *filename = getname_kernel(name);
2684 struct dentry *res = __kern_path_locked(AT_FDCWD, filename, path);
2690 struct dentry *user_path_locked_at(int dfd, const char __user *name, struct path *path)
2692 struct filename *filename = getname(name);
2693 struct dentry *res = __kern_path_locked(dfd, filename, path);
2698 EXPORT_SYMBOL(user_path_locked_at);
2700 int kern_path(const char *name, unsigned int flags, struct path *path)
2702 struct filename *filename = getname_kernel(name);
2703 int ret = filename_lookup(AT_FDCWD, filename, flags, path, NULL);
2709 EXPORT_SYMBOL(kern_path);
2712 * vfs_path_parent_lookup - lookup a parent path relative to a dentry-vfsmount pair
2713 * @filename: filename structure
2714 * @flags: lookup flags
2715 * @parent: pointer to struct path to fill
2716 * @last: last component
2717 * @type: type of the last component
2718 * @root: pointer to struct path of the base directory
2720 int vfs_path_parent_lookup(struct filename *filename, unsigned int flags,
2721 struct path *parent, struct qstr *last, int *type,
2722 const struct path *root)
2724 return __filename_parentat(AT_FDCWD, filename, flags, parent, last,
2727 EXPORT_SYMBOL(vfs_path_parent_lookup);
2730 * vfs_path_lookup - lookup a file path relative to a dentry-vfsmount pair
2731 * @dentry: pointer to dentry of the base directory
2732 * @mnt: pointer to vfs mount of the base directory
2733 * @name: pointer to file name
2734 * @flags: lookup flags
2735 * @path: pointer to struct path to fill
2737 int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt,
2738 const char *name, unsigned int flags,
2741 struct filename *filename;
2742 struct path root = {.mnt = mnt, .dentry = dentry};
2745 filename = getname_kernel(name);
2746 /* the first argument of filename_lookup() is ignored with root */
2747 ret = filename_lookup(AT_FDCWD, filename, flags, path, &root);
2751 EXPORT_SYMBOL(vfs_path_lookup);
2753 static int lookup_one_common(struct mnt_idmap *idmap,
2754 const char *name, struct dentry *base, int len,
2759 this->hash = full_name_hash(base, name, len);
2763 if (is_dot_dotdot(name, len))
2767 unsigned int c = *(const unsigned char *)name++;
2768 if (c == '/' || c == '\0')
2772 * See if the low-level filesystem might want
2773 * to use its own hash..
2775 if (base->d_flags & DCACHE_OP_HASH) {
2776 int err = base->d_op->d_hash(base, this);
2781 return inode_permission(idmap, base->d_inode, MAY_EXEC);
2785 * try_lookup_one_len - filesystem helper to lookup single pathname component
2786 * @name: pathname component to lookup
2787 * @base: base directory to lookup from
2788 * @len: maximum length @len should be interpreted to
2790 * Look up a dentry by name in the dcache, returning NULL if it does not
2791 * currently exist. The function does not try to create a dentry.
2793 * Note that this routine is purely a helper for filesystem usage and should
2794 * not be called by generic code.
2796 * The caller must hold base->i_mutex.
2798 struct dentry *try_lookup_one_len(const char *name, struct dentry *base, int len)
2803 WARN_ON_ONCE(!inode_is_locked(base->d_inode));
2805 err = lookup_one_common(&nop_mnt_idmap, name, base, len, &this);
2807 return ERR_PTR(err);
2809 return lookup_dcache(&this, base, 0);
2811 EXPORT_SYMBOL(try_lookup_one_len);
2814 * lookup_one_len - filesystem helper to lookup single pathname component
2815 * @name: pathname component to lookup
2816 * @base: base directory to lookup from
2817 * @len: maximum length @len should be interpreted to
2819 * Note that this routine is purely a helper for filesystem usage and should
2820 * not be called by generic code.
2822 * The caller must hold base->i_mutex.
2824 struct dentry *lookup_one_len(const char *name, struct dentry *base, int len)
2826 struct dentry *dentry;
2830 WARN_ON_ONCE(!inode_is_locked(base->d_inode));
2832 err = lookup_one_common(&nop_mnt_idmap, name, base, len, &this);
2834 return ERR_PTR(err);
2836 dentry = lookup_dcache(&this, base, 0);
2837 return dentry ? dentry : __lookup_slow(&this, base, 0);
2839 EXPORT_SYMBOL(lookup_one_len);
2842 * lookup_one - filesystem helper to lookup single pathname component
2843 * @idmap: idmap of the mount the lookup is performed from
2844 * @name: pathname component to lookup
2845 * @base: base directory to lookup from
2846 * @len: maximum length @len should be interpreted to
2848 * Note that this routine is purely a helper for filesystem usage and should
2849 * not be called by generic code.
2851 * The caller must hold base->i_mutex.
2853 struct dentry *lookup_one(struct mnt_idmap *idmap, const char *name,
2854 struct dentry *base, int len)
2856 struct dentry *dentry;
2860 WARN_ON_ONCE(!inode_is_locked(base->d_inode));
2862 err = lookup_one_common(idmap, name, base, len, &this);
2864 return ERR_PTR(err);
2866 dentry = lookup_dcache(&this, base, 0);
2867 return dentry ? dentry : __lookup_slow(&this, base, 0);
2869 EXPORT_SYMBOL(lookup_one);
2872 * lookup_one_unlocked - filesystem helper to lookup single pathname component
2873 * @idmap: idmap of the mount the lookup is performed from
2874 * @name: pathname component to lookup
2875 * @base: base directory to lookup from
2876 * @len: maximum length @len should be interpreted to
2878 * Note that this routine is purely a helper for filesystem usage and should
2879 * not be called by generic code.
2881 * Unlike lookup_one_len, it should be called without the parent
2882 * i_mutex held, and will take the i_mutex itself if necessary.
2884 struct dentry *lookup_one_unlocked(struct mnt_idmap *idmap,
2885 const char *name, struct dentry *base,
2892 err = lookup_one_common(idmap, name, base, len, &this);
2894 return ERR_PTR(err);
2896 ret = lookup_dcache(&this, base, 0);
2898 ret = lookup_slow(&this, base, 0);
2901 EXPORT_SYMBOL(lookup_one_unlocked);
2904 * lookup_one_positive_unlocked - filesystem helper to lookup single
2905 * pathname component
2906 * @idmap: idmap of the mount the lookup is performed from
2907 * @name: pathname component to lookup
2908 * @base: base directory to lookup from
2909 * @len: maximum length @len should be interpreted to
2911 * This helper will yield ERR_PTR(-ENOENT) on negatives. The helper returns
2912 * known positive or ERR_PTR(). This is what most of the users want.
2914 * Note that pinned negative with unlocked parent _can_ become positive at any
2915 * time, so callers of lookup_one_unlocked() need to be very careful; pinned
2916 * positives have >d_inode stable, so this one avoids such problems.
2918 * Note that this routine is purely a helper for filesystem usage and should
2919 * not be called by generic code.
2921 * The helper should be called without i_mutex held.
2923 struct dentry *lookup_one_positive_unlocked(struct mnt_idmap *idmap,
2925 struct dentry *base, int len)
2927 struct dentry *ret = lookup_one_unlocked(idmap, name, base, len);
2929 if (!IS_ERR(ret) && d_flags_negative(smp_load_acquire(&ret->d_flags))) {
2931 ret = ERR_PTR(-ENOENT);
2935 EXPORT_SYMBOL(lookup_one_positive_unlocked);
2938 * lookup_one_len_unlocked - filesystem helper to lookup single pathname component
2939 * @name: pathname component to lookup
2940 * @base: base directory to lookup from
2941 * @len: maximum length @len should be interpreted to
2943 * Note that this routine is purely a helper for filesystem usage and should
2944 * not be called by generic code.
2946 * Unlike lookup_one_len, it should be called without the parent
2947 * i_mutex held, and will take the i_mutex itself if necessary.
2949 struct dentry *lookup_one_len_unlocked(const char *name,
2950 struct dentry *base, int len)
2952 return lookup_one_unlocked(&nop_mnt_idmap, name, base, len);
2954 EXPORT_SYMBOL(lookup_one_len_unlocked);
2957 * Like lookup_one_len_unlocked(), except that it yields ERR_PTR(-ENOENT)
2958 * on negatives. Returns known positive or ERR_PTR(); that's what
2959 * most of the users want. Note that pinned negative with unlocked parent
2960 * _can_ become positive at any time, so callers of lookup_one_len_unlocked()
2961 * need to be very careful; pinned positives have ->d_inode stable, so
2962 * this one avoids such problems.
2964 struct dentry *lookup_positive_unlocked(const char *name,
2965 struct dentry *base, int len)
2967 return lookup_one_positive_unlocked(&nop_mnt_idmap, name, base, len);
2969 EXPORT_SYMBOL(lookup_positive_unlocked);
2971 #ifdef CONFIG_UNIX98_PTYS
2972 int path_pts(struct path *path)
2974 /* Find something mounted on "pts" in the same directory as
2977 struct dentry *parent = dget_parent(path->dentry);
2978 struct dentry *child;
2979 struct qstr this = QSTR_INIT("pts", 3);
2981 if (unlikely(!path_connected(path->mnt, parent))) {
2986 path->dentry = parent;
2987 child = d_hash_and_lookup(parent, &this);
2988 if (IS_ERR_OR_NULL(child))
2991 path->dentry = child;
2993 follow_down(path, 0);
2998 int user_path_at(int dfd, const char __user *name, unsigned flags,
3001 struct filename *filename = getname_flags(name, flags);
3002 int ret = filename_lookup(dfd, filename, flags, path, NULL);
3007 EXPORT_SYMBOL(user_path_at);
3009 int __check_sticky(struct mnt_idmap *idmap, struct inode *dir,
3010 struct inode *inode)
3012 kuid_t fsuid = current_fsuid();
3014 if (vfsuid_eq_kuid(i_uid_into_vfsuid(idmap, inode), fsuid))
3016 if (vfsuid_eq_kuid(i_uid_into_vfsuid(idmap, dir), fsuid))
3018 return !capable_wrt_inode_uidgid(idmap, inode, CAP_FOWNER);
3020 EXPORT_SYMBOL(__check_sticky);
3023 * Check whether we can remove a link victim from directory dir, check
3024 * whether the type of victim is right.
3025 * 1. We can't do it if dir is read-only (done in permission())
3026 * 2. We should have write and exec permissions on dir
3027 * 3. We can't remove anything from append-only dir
3028 * 4. We can't do anything with immutable dir (done in permission())
3029 * 5. If the sticky bit on dir is set we should either
3030 * a. be owner of dir, or
3031 * b. be owner of victim, or
3032 * c. have CAP_FOWNER capability
3033 * 6. If the victim is append-only or immutable we can't do antyhing with
3034 * links pointing to it.
3035 * 7. If the victim has an unknown uid or gid we can't change the inode.
3036 * 8. If we were asked to remove a directory and victim isn't one - ENOTDIR.
3037 * 9. If we were asked to remove a non-directory and victim isn't one - EISDIR.
3038 * 10. We can't remove a root or mountpoint.
3039 * 11. We don't allow removal of NFS sillyrenamed files; it's handled by
3040 * nfs_async_unlink().
3042 static int may_delete(struct mnt_idmap *idmap, struct inode *dir,
3043 struct dentry *victim, bool isdir)
3045 struct inode *inode = d_backing_inode(victim);
3048 if (d_is_negative(victim))
3052 BUG_ON(victim->d_parent->d_inode != dir);
3054 /* Inode writeback is not safe when the uid or gid are invalid. */
3055 if (!vfsuid_valid(i_uid_into_vfsuid(idmap, inode)) ||
3056 !vfsgid_valid(i_gid_into_vfsgid(idmap, inode)))
3059 audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
3061 error = inode_permission(idmap, dir, MAY_WRITE | MAY_EXEC);
3067 if (check_sticky(idmap, dir, inode) || IS_APPEND(inode) ||
3068 IS_IMMUTABLE(inode) || IS_SWAPFILE(inode) ||
3069 HAS_UNMAPPED_ID(idmap, inode))
3072 if (!d_is_dir(victim))
3074 if (IS_ROOT(victim))
3076 } else if (d_is_dir(victim))
3078 if (IS_DEADDIR(dir))
3080 if (victim->d_flags & DCACHE_NFSFS_RENAMED)
3085 /* Check whether we can create an object with dentry child in directory
3087 * 1. We can't do it if child already exists (open has special treatment for
3088 * this case, but since we are inlined it's OK)
3089 * 2. We can't do it if dir is read-only (done in permission())
3090 * 3. We can't do it if the fs can't represent the fsuid or fsgid.
3091 * 4. We should have write and exec permissions on dir
3092 * 5. We can't do it if dir is immutable (done in permission())
3094 static inline int may_create(struct mnt_idmap *idmap,
3095 struct inode *dir, struct dentry *child)
3097 audit_inode_child(dir, child, AUDIT_TYPE_CHILD_CREATE);
3100 if (IS_DEADDIR(dir))
3102 if (!fsuidgid_has_mapping(dir->i_sb, idmap))
3105 return inode_permission(idmap, dir, MAY_WRITE | MAY_EXEC);
3108 // p1 != p2, both are on the same filesystem, ->s_vfs_rename_mutex is held
3109 static struct dentry *lock_two_directories(struct dentry *p1, struct dentry *p2)
3111 struct dentry *p = p1, *q = p2, *r;
3113 while ((r = p->d_parent) != p2 && r != p)
3116 // p is a child of p2 and an ancestor of p1 or p1 itself
3117 inode_lock_nested(p2->d_inode, I_MUTEX_PARENT);
3118 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT2);
3121 // p is the root of connected component that contains p1
3122 // p2 does not occur on the path from p to p1
3123 while ((r = q->d_parent) != p1 && r != p && r != q)
3126 // q is a child of p1 and an ancestor of p2 or p2 itself
3127 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
3128 inode_lock_nested(p2->d_inode, I_MUTEX_PARENT2);
3130 } else if (likely(r == p)) {
3131 // both p2 and p1 are descendents of p
3132 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
3133 inode_lock_nested(p2->d_inode, I_MUTEX_PARENT2);
3135 } else { // no common ancestor at the time we'd been called
3136 mutex_unlock(&p1->d_sb->s_vfs_rename_mutex);
3137 return ERR_PTR(-EXDEV);
3142 * p1 and p2 should be directories on the same fs.
3144 struct dentry *lock_rename(struct dentry *p1, struct dentry *p2)
3147 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
3151 mutex_lock(&p1->d_sb->s_vfs_rename_mutex);
3152 return lock_two_directories(p1, p2);
3154 EXPORT_SYMBOL(lock_rename);
3157 * c1 and p2 should be on the same fs.
3159 struct dentry *lock_rename_child(struct dentry *c1, struct dentry *p2)
3161 if (READ_ONCE(c1->d_parent) == p2) {
3163 * hopefully won't need to touch ->s_vfs_rename_mutex at all.
3165 inode_lock_nested(p2->d_inode, I_MUTEX_PARENT);
3167 * now that p2 is locked, nobody can move in or out of it,
3168 * so the test below is safe.
3170 if (likely(c1->d_parent == p2))
3174 * c1 got moved out of p2 while we'd been taking locks;
3175 * unlock and fall back to slow case.
3177 inode_unlock(p2->d_inode);
3180 mutex_lock(&c1->d_sb->s_vfs_rename_mutex);
3182 * nobody can move out of any directories on this fs.
3184 if (likely(c1->d_parent != p2))
3185 return lock_two_directories(c1->d_parent, p2);
3188 * c1 got moved into p2 while we were taking locks;
3189 * we need p2 locked and ->s_vfs_rename_mutex unlocked,
3190 * for consistency with lock_rename().
3192 inode_lock_nested(p2->d_inode, I_MUTEX_PARENT);
3193 mutex_unlock(&c1->d_sb->s_vfs_rename_mutex);
3196 EXPORT_SYMBOL(lock_rename_child);
3198 void unlock_rename(struct dentry *p1, struct dentry *p2)
3200 inode_unlock(p1->d_inode);
3202 inode_unlock(p2->d_inode);
3203 mutex_unlock(&p1->d_sb->s_vfs_rename_mutex);
3206 EXPORT_SYMBOL(unlock_rename);
3209 * vfs_prepare_mode - prepare the mode to be used for a new inode
3210 * @idmap: idmap of the mount the inode was found from
3211 * @dir: parent directory of the new inode
3212 * @mode: mode of the new inode
3213 * @mask_perms: allowed permission by the vfs
3214 * @type: type of file to be created
3216 * This helper consolidates and enforces vfs restrictions on the @mode of a new
3217 * object to be created.
3219 * Umask stripping depends on whether the filesystem supports POSIX ACLs (see
3220 * the kernel documentation for mode_strip_umask()). Moving umask stripping
3221 * after setgid stripping allows the same ordering for both non-POSIX ACL and
3222 * POSIX ACL supporting filesystems.
3224 * Note that it's currently valid for @type to be 0 if a directory is created.
3225 * Filesystems raise that flag individually and we need to check whether each
3226 * filesystem can deal with receiving S_IFDIR from the vfs before we enforce a
3229 * Returns: mode to be passed to the filesystem
3231 static inline umode_t vfs_prepare_mode(struct mnt_idmap *idmap,
3232 const struct inode *dir, umode_t mode,
3233 umode_t mask_perms, umode_t type)
3235 mode = mode_strip_sgid(idmap, dir, mode);
3236 mode = mode_strip_umask(dir, mode);
3239 * Apply the vfs mandated allowed permission mask and set the type of
3240 * file to be created before we call into the filesystem.
3242 mode &= (mask_perms & ~S_IFMT);
3243 mode |= (type & S_IFMT);
3249 * vfs_create - create new file
3250 * @idmap: idmap of the mount the inode was found from
3251 * @dir: inode of the parent directory
3252 * @dentry: dentry of the child file
3253 * @mode: mode of the child file
3254 * @want_excl: whether the file must not yet exist
3256 * Create a new file.
3258 * If the inode has been found through an idmapped mount the idmap of
3259 * the vfsmount must be passed through @idmap. This function will then take
3260 * care to map the inode according to @idmap before checking permissions.
3261 * On non-idmapped mounts or if permission checking is to be performed on the
3262 * raw inode simply pass @nop_mnt_idmap.
3264 int vfs_create(struct mnt_idmap *idmap, struct inode *dir,
3265 struct dentry *dentry, umode_t mode, bool want_excl)
3269 error = may_create(idmap, dir, dentry);
3273 if (!dir->i_op->create)
3274 return -EACCES; /* shouldn't it be ENOSYS? */
3276 mode = vfs_prepare_mode(idmap, dir, mode, S_IALLUGO, S_IFREG);
3277 error = security_inode_create(dir, dentry, mode);
3280 error = dir->i_op->create(idmap, dir, dentry, mode, want_excl);
3282 fsnotify_create(dir, dentry);
3285 EXPORT_SYMBOL(vfs_create);
3287 int vfs_mkobj(struct dentry *dentry, umode_t mode,
3288 int (*f)(struct dentry *, umode_t, void *),
3291 struct inode *dir = dentry->d_parent->d_inode;
3292 int error = may_create(&nop_mnt_idmap, dir, dentry);
3298 error = security_inode_create(dir, dentry, mode);
3301 error = f(dentry, mode, arg);
3303 fsnotify_create(dir, dentry);
3306 EXPORT_SYMBOL(vfs_mkobj);
3308 bool may_open_dev(const struct path *path)
3310 return !(path->mnt->mnt_flags & MNT_NODEV) &&
3311 !(path->mnt->mnt_sb->s_iflags & SB_I_NODEV);
3314 static int may_open(struct mnt_idmap *idmap, const struct path *path,
3315 int acc_mode, int flag)
3317 struct dentry *dentry = path->dentry;
3318 struct inode *inode = dentry->d_inode;
3324 switch (inode->i_mode & S_IFMT) {
3328 if (acc_mode & MAY_WRITE)
3330 if (acc_mode & MAY_EXEC)
3335 if (!may_open_dev(path))
3340 if (acc_mode & MAY_EXEC)
3345 if ((acc_mode & MAY_EXEC) && path_noexec(path))
3350 error = inode_permission(idmap, inode, MAY_OPEN | acc_mode);
3355 * An append-only file must be opened in append mode for writing.
3357 if (IS_APPEND(inode)) {
3358 if ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND))
3364 /* O_NOATIME can only be set by the owner or superuser */
3365 if (flag & O_NOATIME && !inode_owner_or_capable(idmap, inode))
3371 static int handle_truncate(struct mnt_idmap *idmap, struct file *filp)
3373 const struct path *path = &filp->f_path;
3374 struct inode *inode = path->dentry->d_inode;
3375 int error = get_write_access(inode);
3379 error = security_file_truncate(filp);
3381 error = do_truncate(idmap, path->dentry, 0,
3382 ATTR_MTIME|ATTR_CTIME|ATTR_OPEN,
3385 put_write_access(inode);
3389 static inline int open_to_namei_flags(int flag)
3391 if ((flag & O_ACCMODE) == 3)
3396 static int may_o_create(struct mnt_idmap *idmap,
3397 const struct path *dir, struct dentry *dentry,
3400 int error = security_path_mknod(dir, dentry, mode, 0);
3404 if (!fsuidgid_has_mapping(dir->dentry->d_sb, idmap))
3407 error = inode_permission(idmap, dir->dentry->d_inode,
3408 MAY_WRITE | MAY_EXEC);
3412 return security_inode_create(dir->dentry->d_inode, dentry, mode);
3416 * Attempt to atomically look up, create and open a file from a negative
3419 * Returns 0 if successful. The file will have been created and attached to
3420 * @file by the filesystem calling finish_open().
3422 * If the file was looked up only or didn't need creating, FMODE_OPENED won't
3423 * be set. The caller will need to perform the open themselves. @path will
3424 * have been updated to point to the new dentry. This may be negative.
3426 * Returns an error code otherwise.
3428 static struct dentry *atomic_open(struct nameidata *nd, struct dentry *dentry,
3430 int open_flag, umode_t mode)
3432 struct dentry *const DENTRY_NOT_SET = (void *) -1UL;
3433 struct inode *dir = nd->path.dentry->d_inode;
3436 if (nd->flags & LOOKUP_DIRECTORY)
3437 open_flag |= O_DIRECTORY;
3439 file->f_path.dentry = DENTRY_NOT_SET;
3440 file->f_path.mnt = nd->path.mnt;
3441 error = dir->i_op->atomic_open(dir, dentry, file,
3442 open_to_namei_flags(open_flag), mode);
3443 d_lookup_done(dentry);
3445 if (file->f_mode & FMODE_OPENED) {
3446 if (unlikely(dentry != file->f_path.dentry)) {
3448 dentry = dget(file->f_path.dentry);
3450 } else if (WARN_ON(file->f_path.dentry == DENTRY_NOT_SET)) {
3453 if (file->f_path.dentry) {
3455 dentry = file->f_path.dentry;
3457 if (unlikely(d_is_negative(dentry)))
3463 dentry = ERR_PTR(error);
3469 * Look up and maybe create and open the last component.
3471 * Must be called with parent locked (exclusive in O_CREAT case).
3473 * Returns 0 on success, that is, if
3474 * the file was successfully atomically created (if necessary) and opened, or
3475 * the file was not completely opened at this time, though lookups and
3476 * creations were performed.
3477 * These case are distinguished by presence of FMODE_OPENED on file->f_mode.
3478 * In the latter case dentry returned in @path might be negative if O_CREAT
3479 * hadn't been specified.
3481 * An error code is returned on failure.
3483 static struct dentry *lookup_open(struct nameidata *nd, struct file *file,
3484 const struct open_flags *op,
3487 struct mnt_idmap *idmap;
3488 struct dentry *dir = nd->path.dentry;
3489 struct inode *dir_inode = dir->d_inode;
3490 int open_flag = op->open_flag;
3491 struct dentry *dentry;
3492 int error, create_error = 0;
3493 umode_t mode = op->mode;
3494 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
3496 if (unlikely(IS_DEADDIR(dir_inode)))
3497 return ERR_PTR(-ENOENT);
3499 file->f_mode &= ~FMODE_CREATED;
3500 dentry = d_lookup(dir, &nd->last);
3503 dentry = d_alloc_parallel(dir, &nd->last, &wq);
3507 if (d_in_lookup(dentry))
3510 error = d_revalidate(dentry, nd->flags);
3511 if (likely(error > 0))
3515 d_invalidate(dentry);
3519 if (dentry->d_inode) {
3520 /* Cached positive dentry: will open in f_op->open */
3525 * Checking write permission is tricky, bacuse we don't know if we are
3526 * going to actually need it: O_CREAT opens should work as long as the
3527 * file exists. But checking existence breaks atomicity. The trick is
3528 * to check access and if not granted clear O_CREAT from the flags.
3530 * Another problem is returing the "right" error value (e.g. for an
3531 * O_EXCL open we want to return EEXIST not EROFS).
3533 if (unlikely(!got_write))
3534 open_flag &= ~O_TRUNC;
3535 idmap = mnt_idmap(nd->path.mnt);
3536 if (open_flag & O_CREAT) {
3537 if (open_flag & O_EXCL)
3538 open_flag &= ~O_TRUNC;
3539 mode = vfs_prepare_mode(idmap, dir->d_inode, mode, mode, mode);
3540 if (likely(got_write))
3541 create_error = may_o_create(idmap, &nd->path,
3544 create_error = -EROFS;
3547 open_flag &= ~O_CREAT;
3548 if (dir_inode->i_op->atomic_open) {
3549 dentry = atomic_open(nd, dentry, file, open_flag, mode);
3550 if (unlikely(create_error) && dentry == ERR_PTR(-ENOENT))
3551 dentry = ERR_PTR(create_error);
3555 if (d_in_lookup(dentry)) {
3556 struct dentry *res = dir_inode->i_op->lookup(dir_inode, dentry,
3558 d_lookup_done(dentry);
3559 if (unlikely(res)) {
3561 error = PTR_ERR(res);
3569 /* Negative dentry, just create the file */
3570 if (!dentry->d_inode && (open_flag & O_CREAT)) {
3571 file->f_mode |= FMODE_CREATED;
3572 audit_inode_child(dir_inode, dentry, AUDIT_TYPE_CHILD_CREATE);
3573 if (!dir_inode->i_op->create) {
3578 error = dir_inode->i_op->create(idmap, dir_inode, dentry,
3579 mode, open_flag & O_EXCL);
3583 if (unlikely(create_error) && !dentry->d_inode) {
3584 error = create_error;
3591 return ERR_PTR(error);
3594 static const char *open_last_lookups(struct nameidata *nd,
3595 struct file *file, const struct open_flags *op)
3597 struct dentry *dir = nd->path.dentry;
3598 int open_flag = op->open_flag;
3599 bool got_write = false;
3600 struct dentry *dentry;
3603 nd->flags |= op->intent;
3605 if (nd->last_type != LAST_NORM) {
3608 return handle_dots(nd, nd->last_type);
3611 if (!(open_flag & O_CREAT)) {
3612 if (nd->last.name[nd->last.len])
3613 nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
3614 /* we _can_ be in RCU mode here */
3615 dentry = lookup_fast(nd);
3617 return ERR_CAST(dentry);
3621 if (WARN_ON_ONCE(nd->flags & LOOKUP_RCU))
3622 return ERR_PTR(-ECHILD);
3624 /* create side of things */
3625 if (nd->flags & LOOKUP_RCU) {
3626 if (!try_to_unlazy(nd))
3627 return ERR_PTR(-ECHILD);
3629 audit_inode(nd->name, dir, AUDIT_INODE_PARENT);
3630 /* trailing slashes? */
3631 if (unlikely(nd->last.name[nd->last.len]))
3632 return ERR_PTR(-EISDIR);
3635 if (open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) {
3636 got_write = !mnt_want_write(nd->path.mnt);
3638 * do _not_ fail yet - we might not need that or fail with
3639 * a different error; let lookup_open() decide; we'll be
3640 * dropping this one anyway.
3643 if (open_flag & O_CREAT)
3644 inode_lock(dir->d_inode);
3646 inode_lock_shared(dir->d_inode);
3647 dentry = lookup_open(nd, file, op, got_write);
3648 if (!IS_ERR(dentry)) {
3649 if (file->f_mode & FMODE_CREATED)
3650 fsnotify_create(dir->d_inode, dentry);
3651 if (file->f_mode & FMODE_OPENED)
3652 fsnotify_open(file);
3654 if (open_flag & O_CREAT)
3655 inode_unlock(dir->d_inode);
3657 inode_unlock_shared(dir->d_inode);
3660 mnt_drop_write(nd->path.mnt);
3663 return ERR_CAST(dentry);
3665 if (file->f_mode & (FMODE_OPENED | FMODE_CREATED)) {
3666 dput(nd->path.dentry);
3667 nd->path.dentry = dentry;
3674 res = step_into(nd, WALK_TRAILING, dentry);
3676 nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL);
3681 * Handle the last step of open()
3683 static int do_open(struct nameidata *nd,
3684 struct file *file, const struct open_flags *op)
3686 struct mnt_idmap *idmap;
3687 int open_flag = op->open_flag;
3692 if (!(file->f_mode & (FMODE_OPENED | FMODE_CREATED))) {
3693 error = complete_walk(nd);
3697 if (!(file->f_mode & FMODE_CREATED))
3698 audit_inode(nd->name, nd->path.dentry, 0);
3699 idmap = mnt_idmap(nd->path.mnt);
3700 if (open_flag & O_CREAT) {
3701 if ((open_flag & O_EXCL) && !(file->f_mode & FMODE_CREATED))
3703 if (d_is_dir(nd->path.dentry))
3705 error = may_create_in_sticky(idmap, nd,
3706 d_backing_inode(nd->path.dentry));
3707 if (unlikely(error))
3710 if ((nd->flags & LOOKUP_DIRECTORY) && !d_can_lookup(nd->path.dentry))
3713 do_truncate = false;
3714 acc_mode = op->acc_mode;
3715 if (file->f_mode & FMODE_CREATED) {
3716 /* Don't check for write permission, don't truncate */
3717 open_flag &= ~O_TRUNC;
3719 } else if (d_is_reg(nd->path.dentry) && open_flag & O_TRUNC) {
3720 error = mnt_want_write(nd->path.mnt);
3725 error = may_open(idmap, &nd->path, acc_mode, open_flag);
3726 if (!error && !(file->f_mode & FMODE_OPENED))
3727 error = vfs_open(&nd->path, file);
3729 error = security_file_post_open(file, op->acc_mode);
3730 if (!error && do_truncate)
3731 error = handle_truncate(idmap, file);
3732 if (unlikely(error > 0)) {
3737 mnt_drop_write(nd->path.mnt);
3742 * vfs_tmpfile - create tmpfile
3743 * @idmap: idmap of the mount the inode was found from
3744 * @parentpath: pointer to the path of the base directory
3745 * @file: file descriptor of the new tmpfile
3746 * @mode: mode of the new tmpfile
3748 * Create a temporary file.
3750 * If the inode has been found through an idmapped mount the idmap of
3751 * the vfsmount must be passed through @idmap. This function will then take
3752 * care to map the inode according to @idmap before checking permissions.
3753 * On non-idmapped mounts or if permission checking is to be performed on the
3754 * raw inode simply pass @nop_mnt_idmap.
3756 int vfs_tmpfile(struct mnt_idmap *idmap,
3757 const struct path *parentpath,
3758 struct file *file, umode_t mode)
3760 struct dentry *child;
3761 struct inode *dir = d_inode(parentpath->dentry);
3762 struct inode *inode;
3764 int open_flag = file->f_flags;
3766 /* we want directory to be writable */
3767 error = inode_permission(idmap, dir, MAY_WRITE | MAY_EXEC);
3770 if (!dir->i_op->tmpfile)
3772 child = d_alloc(parentpath->dentry, &slash_name);
3773 if (unlikely(!child))
3775 file->f_path.mnt = parentpath->mnt;
3776 file->f_path.dentry = child;
3777 mode = vfs_prepare_mode(idmap, dir, mode, mode, mode);
3778 error = dir->i_op->tmpfile(idmap, dir, file, mode);
3780 if (file->f_mode & FMODE_OPENED)
3781 fsnotify_open(file);
3784 /* Don't check for other permissions, the inode was just created */
3785 error = may_open(idmap, &file->f_path, 0, file->f_flags);
3788 inode = file_inode(file);
3789 if (!(open_flag & O_EXCL)) {
3790 spin_lock(&inode->i_lock);
3791 inode->i_state |= I_LINKABLE;
3792 spin_unlock(&inode->i_lock);
3794 security_inode_post_create_tmpfile(idmap, inode);
3799 * kernel_tmpfile_open - open a tmpfile for kernel internal use
3800 * @idmap: idmap of the mount the inode was found from
3801 * @parentpath: path of the base directory
3802 * @mode: mode of the new tmpfile
3804 * @cred: credentials for open
3806 * Create and open a temporary file. The file is not accounted in nr_files,
3807 * hence this is only for kernel internal use, and must not be installed into
3808 * file tables or such.
3810 struct file *kernel_tmpfile_open(struct mnt_idmap *idmap,
3811 const struct path *parentpath,
3812 umode_t mode, int open_flag,
3813 const struct cred *cred)
3818 file = alloc_empty_file_noaccount(open_flag, cred);
3822 error = vfs_tmpfile(idmap, parentpath, file, mode);
3825 file = ERR_PTR(error);
3829 EXPORT_SYMBOL(kernel_tmpfile_open);
3831 static int do_tmpfile(struct nameidata *nd, unsigned flags,
3832 const struct open_flags *op,
3836 int error = path_lookupat(nd, flags | LOOKUP_DIRECTORY, &path);
3838 if (unlikely(error))
3840 error = mnt_want_write(path.mnt);
3841 if (unlikely(error))
3843 error = vfs_tmpfile(mnt_idmap(path.mnt), &path, file, op->mode);
3846 audit_inode(nd->name, file->f_path.dentry, 0);
3848 mnt_drop_write(path.mnt);
3854 static int do_o_path(struct nameidata *nd, unsigned flags, struct file *file)
3857 int error = path_lookupat(nd, flags, &path);
3859 audit_inode(nd->name, path.dentry, 0);
3860 error = vfs_open(&path, file);
3866 static struct file *path_openat(struct nameidata *nd,
3867 const struct open_flags *op, unsigned flags)
3872 file = alloc_empty_file(op->open_flag, current_cred());
3876 if (unlikely(file->f_flags & __O_TMPFILE)) {
3877 error = do_tmpfile(nd, flags, op, file);
3878 } else if (unlikely(file->f_flags & O_PATH)) {
3879 error = do_o_path(nd, flags, file);
3881 const char *s = path_init(nd, flags);
3882 while (!(error = link_path_walk(s, nd)) &&
3883 (s = open_last_lookups(nd, file, op)) != NULL)
3886 error = do_open(nd, file, op);
3889 if (likely(!error)) {
3890 if (likely(file->f_mode & FMODE_OPENED))
3896 if (error == -EOPENSTALE) {
3897 if (flags & LOOKUP_RCU)
3902 return ERR_PTR(error);
3905 struct file *do_filp_open(int dfd, struct filename *pathname,
3906 const struct open_flags *op)
3908 struct nameidata nd;
3909 int flags = op->lookup_flags;
3912 set_nameidata(&nd, dfd, pathname, NULL);
3913 filp = path_openat(&nd, op, flags | LOOKUP_RCU);
3914 if (unlikely(filp == ERR_PTR(-ECHILD)))
3915 filp = path_openat(&nd, op, flags);
3916 if (unlikely(filp == ERR_PTR(-ESTALE)))
3917 filp = path_openat(&nd, op, flags | LOOKUP_REVAL);
3918 restore_nameidata();
3922 struct file *do_file_open_root(const struct path *root,
3923 const char *name, const struct open_flags *op)
3925 struct nameidata nd;
3927 struct filename *filename;
3928 int flags = op->lookup_flags;
3930 if (d_is_symlink(root->dentry) && op->intent & LOOKUP_OPEN)
3931 return ERR_PTR(-ELOOP);
3933 filename = getname_kernel(name);
3934 if (IS_ERR(filename))
3935 return ERR_CAST(filename);
3937 set_nameidata(&nd, -1, filename, root);
3938 file = path_openat(&nd, op, flags | LOOKUP_RCU);
3939 if (unlikely(file == ERR_PTR(-ECHILD)))
3940 file = path_openat(&nd, op, flags);
3941 if (unlikely(file == ERR_PTR(-ESTALE)))
3942 file = path_openat(&nd, op, flags | LOOKUP_REVAL);
3943 restore_nameidata();
3948 static struct dentry *filename_create(int dfd, struct filename *name,
3949 struct path *path, unsigned int lookup_flags)
3951 struct dentry *dentry = ERR_PTR(-EEXIST);
3953 bool want_dir = lookup_flags & LOOKUP_DIRECTORY;
3954 unsigned int reval_flag = lookup_flags & LOOKUP_REVAL;
3955 unsigned int create_flags = LOOKUP_CREATE | LOOKUP_EXCL;
3960 error = filename_parentat(dfd, name, reval_flag, path, &last, &type);
3962 return ERR_PTR(error);
3965 * Yucky last component or no last component at all?
3966 * (foo/., foo/.., /////)
3968 if (unlikely(type != LAST_NORM))
3971 /* don't fail immediately if it's r/o, at least try to report other errors */
3972 err2 = mnt_want_write(path->mnt);
3974 * Do the final lookup. Suppress 'create' if there is a trailing
3975 * '/', and a directory wasn't requested.
3977 if (last.name[last.len] && !want_dir)
3979 inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
3980 dentry = lookup_one_qstr_excl(&last, path->dentry,
3981 reval_flag | create_flags);
3986 if (d_is_positive(dentry))
3990 * Special case - lookup gave negative, but... we had foo/bar/
3991 * From the vfs_mknod() POV we just have a negative dentry -
3992 * all is fine. Let's be bastards - you had / on the end, you've
3993 * been asking for (non-existent) directory. -ENOENT for you.
3995 if (unlikely(!create_flags)) {
3999 if (unlikely(err2)) {
4006 dentry = ERR_PTR(error);
4008 inode_unlock(path->dentry->d_inode);
4010 mnt_drop_write(path->mnt);
4016 struct dentry *kern_path_create(int dfd, const char *pathname,
4017 struct path *path, unsigned int lookup_flags)
4019 struct filename *filename = getname_kernel(pathname);
4020 struct dentry *res = filename_create(dfd, filename, path, lookup_flags);
4025 EXPORT_SYMBOL(kern_path_create);
4027 void done_path_create(struct path *path, struct dentry *dentry)
4030 inode_unlock(path->dentry->d_inode);
4031 mnt_drop_write(path->mnt);
4034 EXPORT_SYMBOL(done_path_create);
4036 inline struct dentry *user_path_create(int dfd, const char __user *pathname,
4037 struct path *path, unsigned int lookup_flags)
4039 struct filename *filename = getname(pathname);
4040 struct dentry *res = filename_create(dfd, filename, path, lookup_flags);
4045 EXPORT_SYMBOL(user_path_create);
4048 * vfs_mknod - create device node or file
4049 * @idmap: idmap of the mount the inode was found from
4050 * @dir: inode of the parent directory
4051 * @dentry: dentry of the child device node
4052 * @mode: mode of the child device node
4053 * @dev: device number of device to create
4055 * Create a device node or file.
4057 * If the inode has been found through an idmapped mount the idmap of
4058 * the vfsmount must be passed through @idmap. This function will then take
4059 * care to map the inode according to @idmap before checking permissions.
4060 * On non-idmapped mounts or if permission checking is to be performed on the
4061 * raw inode simply pass @nop_mnt_idmap.
4063 int vfs_mknod(struct mnt_idmap *idmap, struct inode *dir,
4064 struct dentry *dentry, umode_t mode, dev_t dev)
4066 bool is_whiteout = S_ISCHR(mode) && dev == WHITEOUT_DEV;
4067 int error = may_create(idmap, dir, dentry);
4072 if ((S_ISCHR(mode) || S_ISBLK(mode)) && !is_whiteout &&
4073 !capable(CAP_MKNOD))
4076 if (!dir->i_op->mknod)
4079 mode = vfs_prepare_mode(idmap, dir, mode, mode, mode);
4080 error = devcgroup_inode_mknod(mode, dev);
4084 error = security_inode_mknod(dir, dentry, mode, dev);
4088 error = dir->i_op->mknod(idmap, dir, dentry, mode, dev);
4090 fsnotify_create(dir, dentry);
4093 EXPORT_SYMBOL(vfs_mknod);
4095 static int may_mknod(umode_t mode)
4097 switch (mode & S_IFMT) {
4103 case 0: /* zero mode translates to S_IFREG */
4112 static int do_mknodat(int dfd, struct filename *name, umode_t mode,
4115 struct mnt_idmap *idmap;
4116 struct dentry *dentry;
4119 unsigned int lookup_flags = 0;
4121 error = may_mknod(mode);
4125 dentry = filename_create(dfd, name, &path, lookup_flags);
4126 error = PTR_ERR(dentry);
4130 error = security_path_mknod(&path, dentry,
4131 mode_strip_umask(path.dentry->d_inode, mode), dev);
4135 idmap = mnt_idmap(path.mnt);
4136 switch (mode & S_IFMT) {
4137 case 0: case S_IFREG:
4138 error = vfs_create(idmap, path.dentry->d_inode,
4139 dentry, mode, true);
4141 security_path_post_mknod(idmap, dentry);
4143 case S_IFCHR: case S_IFBLK:
4144 error = vfs_mknod(idmap, path.dentry->d_inode,
4145 dentry, mode, new_decode_dev(dev));
4147 case S_IFIFO: case S_IFSOCK:
4148 error = vfs_mknod(idmap, path.dentry->d_inode,
4153 done_path_create(&path, dentry);
4154 if (retry_estale(error, lookup_flags)) {
4155 lookup_flags |= LOOKUP_REVAL;
4163 SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, umode_t, mode,
4166 return do_mknodat(dfd, getname(filename), mode, dev);
4169 SYSCALL_DEFINE3(mknod, const char __user *, filename, umode_t, mode, unsigned, dev)
4171 return do_mknodat(AT_FDCWD, getname(filename), mode, dev);
4175 * vfs_mkdir - create directory
4176 * @idmap: idmap of the mount the inode was found from
4177 * @dir: inode of the parent directory
4178 * @dentry: dentry of the child directory
4179 * @mode: mode of the child directory
4181 * Create a directory.
4183 * If the inode has been found through an idmapped mount the idmap of
4184 * the vfsmount must be passed through @idmap. This function will then take
4185 * care to map the inode according to @idmap before checking permissions.
4186 * On non-idmapped mounts or if permission checking is to be performed on the
4187 * raw inode simply pass @nop_mnt_idmap.
4189 int vfs_mkdir(struct mnt_idmap *idmap, struct inode *dir,
4190 struct dentry *dentry, umode_t mode)
4193 unsigned max_links = dir->i_sb->s_max_links;
4195 error = may_create(idmap, dir, dentry);
4199 if (!dir->i_op->mkdir)
4202 mode = vfs_prepare_mode(idmap, dir, mode, S_IRWXUGO | S_ISVTX, 0);
4203 error = security_inode_mkdir(dir, dentry, mode);
4207 if (max_links && dir->i_nlink >= max_links)
4210 error = dir->i_op->mkdir(idmap, dir, dentry, mode);
4212 fsnotify_mkdir(dir, dentry);
4215 EXPORT_SYMBOL(vfs_mkdir);
4217 int do_mkdirat(int dfd, struct filename *name, umode_t mode)
4219 struct dentry *dentry;
4222 unsigned int lookup_flags = LOOKUP_DIRECTORY;
4225 dentry = filename_create(dfd, name, &path, lookup_flags);
4226 error = PTR_ERR(dentry);
4230 error = security_path_mkdir(&path, dentry,
4231 mode_strip_umask(path.dentry->d_inode, mode));
4233 error = vfs_mkdir(mnt_idmap(path.mnt), path.dentry->d_inode,
4236 done_path_create(&path, dentry);
4237 if (retry_estale(error, lookup_flags)) {
4238 lookup_flags |= LOOKUP_REVAL;
4246 SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, umode_t, mode)
4248 return do_mkdirat(dfd, getname(pathname), mode);
4251 SYSCALL_DEFINE2(mkdir, const char __user *, pathname, umode_t, mode)
4253 return do_mkdirat(AT_FDCWD, getname(pathname), mode);
4257 * vfs_rmdir - remove directory
4258 * @idmap: idmap of the mount the inode was found from
4259 * @dir: inode of the parent directory
4260 * @dentry: dentry of the child directory
4262 * Remove a directory.
4264 * If the inode has been found through an idmapped mount the idmap of
4265 * the vfsmount must be passed through @idmap. This function will then take
4266 * care to map the inode according to @idmap before checking permissions.
4267 * On non-idmapped mounts or if permission checking is to be performed on the
4268 * raw inode simply pass @nop_mnt_idmap.
4270 int vfs_rmdir(struct mnt_idmap *idmap, struct inode *dir,
4271 struct dentry *dentry)
4273 int error = may_delete(idmap, dir, dentry, 1);
4278 if (!dir->i_op->rmdir)
4282 inode_lock(dentry->d_inode);
4285 if (is_local_mountpoint(dentry) ||
4286 (dentry->d_inode->i_flags & S_KERNEL_FILE))
4289 error = security_inode_rmdir(dir, dentry);
4293 error = dir->i_op->rmdir(dir, dentry);
4297 shrink_dcache_parent(dentry);
4298 dentry->d_inode->i_flags |= S_DEAD;
4300 detach_mounts(dentry);
4303 inode_unlock(dentry->d_inode);
4306 d_delete_notify(dir, dentry);
4309 EXPORT_SYMBOL(vfs_rmdir);
4311 int do_rmdir(int dfd, struct filename *name)
4314 struct dentry *dentry;
4318 unsigned int lookup_flags = 0;
4320 error = filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
4336 error = mnt_want_write(path.mnt);
4340 inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
4341 dentry = lookup_one_qstr_excl(&last, path.dentry, lookup_flags);
4342 error = PTR_ERR(dentry);
4345 if (!dentry->d_inode) {
4349 error = security_path_rmdir(&path, dentry);
4352 error = vfs_rmdir(mnt_idmap(path.mnt), path.dentry->d_inode, dentry);
4356 inode_unlock(path.dentry->d_inode);
4357 mnt_drop_write(path.mnt);
4360 if (retry_estale(error, lookup_flags)) {
4361 lookup_flags |= LOOKUP_REVAL;
4369 SYSCALL_DEFINE1(rmdir, const char __user *, pathname)
4371 return do_rmdir(AT_FDCWD, getname(pathname));
4375 * vfs_unlink - unlink a filesystem object
4376 * @idmap: idmap of the mount the inode was found from
4377 * @dir: parent directory
4379 * @delegated_inode: returns victim inode, if the inode is delegated.
4381 * The caller must hold dir->i_mutex.
4383 * If vfs_unlink discovers a delegation, it will return -EWOULDBLOCK and
4384 * return a reference to the inode in delegated_inode. The caller
4385 * should then break the delegation on that inode and retry. Because
4386 * breaking a delegation may take a long time, the caller should drop
4387 * dir->i_mutex before doing so.
4389 * Alternatively, a caller may pass NULL for delegated_inode. This may
4390 * be appropriate for callers that expect the underlying filesystem not
4391 * to be NFS exported.
4393 * If the inode has been found through an idmapped mount the idmap of
4394 * the vfsmount must be passed through @idmap. This function will then take
4395 * care to map the inode according to @idmap before checking permissions.
4396 * On non-idmapped mounts or if permission checking is to be performed on the
4397 * raw inode simply pass @nop_mnt_idmap.
4399 int vfs_unlink(struct mnt_idmap *idmap, struct inode *dir,
4400 struct dentry *dentry, struct inode **delegated_inode)
4402 struct inode *target = dentry->d_inode;
4403 int error = may_delete(idmap, dir, dentry, 0);
4408 if (!dir->i_op->unlink)
4412 if (IS_SWAPFILE(target))
4414 else if (is_local_mountpoint(dentry))
4417 error = security_inode_unlink(dir, dentry);
4419 error = try_break_deleg(target, delegated_inode);
4422 error = dir->i_op->unlink(dir, dentry);
4425 detach_mounts(dentry);
4430 inode_unlock(target);
4432 /* We don't d_delete() NFS sillyrenamed files--they still exist. */
4433 if (!error && dentry->d_flags & DCACHE_NFSFS_RENAMED) {
4434 fsnotify_unlink(dir, dentry);
4435 } else if (!error) {
4436 fsnotify_link_count(target);
4437 d_delete_notify(dir, dentry);
4442 EXPORT_SYMBOL(vfs_unlink);
4445 * Make sure that the actual truncation of the file will occur outside its
4446 * directory's i_mutex. Truncate can take a long time if there is a lot of
4447 * writeout happening, and we don't want to prevent access to the directory
4448 * while waiting on the I/O.
4450 int do_unlinkat(int dfd, struct filename *name)
4453 struct dentry *dentry;
4457 struct inode *inode = NULL;
4458 struct inode *delegated_inode = NULL;
4459 unsigned int lookup_flags = 0;
4461 error = filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
4466 if (type != LAST_NORM)
4469 error = mnt_want_write(path.mnt);
4473 inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
4474 dentry = lookup_one_qstr_excl(&last, path.dentry, lookup_flags);
4475 error = PTR_ERR(dentry);
4476 if (!IS_ERR(dentry)) {
4478 /* Why not before? Because we want correct error value */
4479 if (last.name[last.len] || d_is_negative(dentry))
4481 inode = dentry->d_inode;
4483 error = security_path_unlink(&path, dentry);
4486 error = vfs_unlink(mnt_idmap(path.mnt), path.dentry->d_inode,
4487 dentry, &delegated_inode);
4491 inode_unlock(path.dentry->d_inode);
4493 iput(inode); /* truncate the inode here */
4495 if (delegated_inode) {
4496 error = break_deleg_wait(&delegated_inode);
4500 mnt_drop_write(path.mnt);
4503 if (retry_estale(error, lookup_flags)) {
4504 lookup_flags |= LOOKUP_REVAL;
4513 if (d_is_negative(dentry))
4515 else if (d_is_dir(dentry))
4522 SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag)
4524 if ((flag & ~AT_REMOVEDIR) != 0)
4527 if (flag & AT_REMOVEDIR)
4528 return do_rmdir(dfd, getname(pathname));
4529 return do_unlinkat(dfd, getname(pathname));
4532 SYSCALL_DEFINE1(unlink, const char __user *, pathname)
4534 return do_unlinkat(AT_FDCWD, getname(pathname));
4538 * vfs_symlink - create symlink
4539 * @idmap: idmap of the mount the inode was found from
4540 * @dir: inode of the parent directory
4541 * @dentry: dentry of the child symlink file
4542 * @oldname: name of the file to link to
4546 * If the inode has been found through an idmapped mount the idmap of
4547 * the vfsmount must be passed through @idmap. This function will then take
4548 * care to map the inode according to @idmap before checking permissions.
4549 * On non-idmapped mounts or if permission checking is to be performed on the
4550 * raw inode simply pass @nop_mnt_idmap.
4552 int vfs_symlink(struct mnt_idmap *idmap, struct inode *dir,
4553 struct dentry *dentry, const char *oldname)
4557 error = may_create(idmap, dir, dentry);
4561 if (!dir->i_op->symlink)
4564 error = security_inode_symlink(dir, dentry, oldname);
4568 error = dir->i_op->symlink(idmap, dir, dentry, oldname);
4570 fsnotify_create(dir, dentry);
4573 EXPORT_SYMBOL(vfs_symlink);
4575 int do_symlinkat(struct filename *from, int newdfd, struct filename *to)
4578 struct dentry *dentry;
4580 unsigned int lookup_flags = 0;
4583 error = PTR_ERR(from);
4587 dentry = filename_create(newdfd, to, &path, lookup_flags);
4588 error = PTR_ERR(dentry);
4592 error = security_path_symlink(&path, dentry, from->name);
4594 error = vfs_symlink(mnt_idmap(path.mnt), path.dentry->d_inode,
4595 dentry, from->name);
4596 done_path_create(&path, dentry);
4597 if (retry_estale(error, lookup_flags)) {
4598 lookup_flags |= LOOKUP_REVAL;
4607 SYSCALL_DEFINE3(symlinkat, const char __user *, oldname,
4608 int, newdfd, const char __user *, newname)
4610 return do_symlinkat(getname(oldname), newdfd, getname(newname));
4613 SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname)
4615 return do_symlinkat(getname(oldname), AT_FDCWD, getname(newname));
4619 * vfs_link - create a new link
4620 * @old_dentry: object to be linked
4621 * @idmap: idmap of the mount
4623 * @new_dentry: where to create the new link
4624 * @delegated_inode: returns inode needing a delegation break
4626 * The caller must hold dir->i_mutex
4628 * If vfs_link discovers a delegation on the to-be-linked file in need
4629 * of breaking, it will return -EWOULDBLOCK and return a reference to the
4630 * inode in delegated_inode. The caller should then break the delegation
4631 * and retry. Because breaking a delegation may take a long time, the
4632 * caller should drop the i_mutex before doing so.
4634 * Alternatively, a caller may pass NULL for delegated_inode. This may
4635 * be appropriate for callers that expect the underlying filesystem not
4636 * to be NFS exported.
4638 * If the inode has been found through an idmapped mount the idmap of
4639 * the vfsmount must be passed through @idmap. This function will then take
4640 * care to map the inode according to @idmap before checking permissions.
4641 * On non-idmapped mounts or if permission checking is to be performed on the
4642 * raw inode simply pass @nop_mnt_idmap.
4644 int vfs_link(struct dentry *old_dentry, struct mnt_idmap *idmap,
4645 struct inode *dir, struct dentry *new_dentry,
4646 struct inode **delegated_inode)
4648 struct inode *inode = old_dentry->d_inode;
4649 unsigned max_links = dir->i_sb->s_max_links;
4655 error = may_create(idmap, dir, new_dentry);
4659 if (dir->i_sb != inode->i_sb)
4663 * A link to an append-only or immutable file cannot be created.
4665 if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
4668 * Updating the link count will likely cause i_uid and i_gid to
4669 * be writen back improperly if their true value is unknown to
4672 if (HAS_UNMAPPED_ID(idmap, inode))
4674 if (!dir->i_op->link)
4676 if (S_ISDIR(inode->i_mode))
4679 error = security_inode_link(old_dentry, dir, new_dentry);
4684 /* Make sure we don't allow creating hardlink to an unlinked file */
4685 if (inode->i_nlink == 0 && !(inode->i_state & I_LINKABLE))
4687 else if (max_links && inode->i_nlink >= max_links)
4690 error = try_break_deleg(inode, delegated_inode);
4692 error = dir->i_op->link(old_dentry, dir, new_dentry);
4695 if (!error && (inode->i_state & I_LINKABLE)) {
4696 spin_lock(&inode->i_lock);
4697 inode->i_state &= ~I_LINKABLE;
4698 spin_unlock(&inode->i_lock);
4700 inode_unlock(inode);
4702 fsnotify_link(dir, inode, new_dentry);
4705 EXPORT_SYMBOL(vfs_link);
4708 * Hardlinks are often used in delicate situations. We avoid
4709 * security-related surprises by not following symlinks on the
4712 * We don't follow them on the oldname either to be compatible
4713 * with linux 2.0, and to avoid hard-linking to directories
4714 * and other special files. --ADM
4716 int do_linkat(int olddfd, struct filename *old, int newdfd,
4717 struct filename *new, int flags)
4719 struct mnt_idmap *idmap;
4720 struct dentry *new_dentry;
4721 struct path old_path, new_path;
4722 struct inode *delegated_inode = NULL;
4726 if ((flags & ~(AT_SYMLINK_FOLLOW | AT_EMPTY_PATH)) != 0) {
4731 * To use null names we require CAP_DAC_READ_SEARCH or
4732 * that the open-time creds of the dfd matches current.
4733 * This ensures that not everyone will be able to create
4734 * a hardlink using the passed file descriptor.
4736 if (flags & AT_EMPTY_PATH)
4737 how |= LOOKUP_LINKAT_EMPTY;
4739 if (flags & AT_SYMLINK_FOLLOW)
4740 how |= LOOKUP_FOLLOW;
4742 error = filename_lookup(olddfd, old, how, &old_path, NULL);
4746 new_dentry = filename_create(newdfd, new, &new_path,
4747 (how & LOOKUP_REVAL));
4748 error = PTR_ERR(new_dentry);
4749 if (IS_ERR(new_dentry))
4753 if (old_path.mnt != new_path.mnt)
4755 idmap = mnt_idmap(new_path.mnt);
4756 error = may_linkat(idmap, &old_path);
4757 if (unlikely(error))
4759 error = security_path_link(old_path.dentry, &new_path, new_dentry);
4762 error = vfs_link(old_path.dentry, idmap, new_path.dentry->d_inode,
4763 new_dentry, &delegated_inode);
4765 done_path_create(&new_path, new_dentry);
4766 if (delegated_inode) {
4767 error = break_deleg_wait(&delegated_inode);
4769 path_put(&old_path);
4773 if (retry_estale(error, how)) {
4774 path_put(&old_path);
4775 how |= LOOKUP_REVAL;
4779 path_put(&old_path);
4787 SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname,
4788 int, newdfd, const char __user *, newname, int, flags)
4790 return do_linkat(olddfd, getname_uflags(oldname, flags),
4791 newdfd, getname(newname), flags);
4794 SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname)
4796 return do_linkat(AT_FDCWD, getname(oldname), AT_FDCWD, getname(newname), 0);
4800 * vfs_rename - rename a filesystem object
4801 * @rd: pointer to &struct renamedata info
4803 * The caller must hold multiple mutexes--see lock_rename()).
4805 * If vfs_rename discovers a delegation in need of breaking at either
4806 * the source or destination, it will return -EWOULDBLOCK and return a
4807 * reference to the inode in delegated_inode. The caller should then
4808 * break the delegation and retry. Because breaking a delegation may
4809 * take a long time, the caller should drop all locks before doing
4812 * Alternatively, a caller may pass NULL for delegated_inode. This may
4813 * be appropriate for callers that expect the underlying filesystem not
4814 * to be NFS exported.
4816 * The worst of all namespace operations - renaming directory. "Perverted"
4817 * doesn't even start to describe it. Somebody in UCB had a heck of a trip...
4820 * a) we can get into loop creation.
4821 * b) race potential - two innocent renames can create a loop together.
4822 * That's where 4.4BSD screws up. Current fix: serialization on
4823 * sb->s_vfs_rename_mutex. We might be more accurate, but that's another
4825 * c) we may have to lock up to _four_ objects - parents and victim (if it exists),
4826 * and source (if it's a non-directory or a subdirectory that moves to
4827 * different parent).
4828 * And that - after we got ->i_mutex on parents (until then we don't know
4829 * whether the target exists). Solution: try to be smart with locking
4830 * order for inodes. We rely on the fact that tree topology may change
4831 * only under ->s_vfs_rename_mutex _and_ that parent of the object we
4832 * move will be locked. Thus we can rank directories by the tree
4833 * (ancestors first) and rank all non-directories after them.
4834 * That works since everybody except rename does "lock parent, lookup,
4835 * lock child" and rename is under ->s_vfs_rename_mutex.
4836 * HOWEVER, it relies on the assumption that any object with ->lookup()
4837 * has no more than 1 dentry. If "hybrid" objects will ever appear,
4838 * we'd better make sure that there's no link(2) for them.
4839 * d) conversion from fhandle to dentry may come in the wrong moment - when
4840 * we are removing the target. Solution: we will have to grab ->i_mutex
4841 * in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on
4842 * ->i_mutex on parents, which works but leads to some truly excessive
4845 int vfs_rename(struct renamedata *rd)
4848 struct inode *old_dir = rd->old_dir, *new_dir = rd->new_dir;
4849 struct dentry *old_dentry = rd->old_dentry;
4850 struct dentry *new_dentry = rd->new_dentry;
4851 struct inode **delegated_inode = rd->delegated_inode;
4852 unsigned int flags = rd->flags;
4853 bool is_dir = d_is_dir(old_dentry);
4854 struct inode *source = old_dentry->d_inode;
4855 struct inode *target = new_dentry->d_inode;
4856 bool new_is_dir = false;
4857 unsigned max_links = new_dir->i_sb->s_max_links;
4858 struct name_snapshot old_name;
4859 bool lock_old_subdir, lock_new_subdir;
4861 if (source == target)
4864 error = may_delete(rd->old_mnt_idmap, old_dir, old_dentry, is_dir);
4869 error = may_create(rd->new_mnt_idmap, new_dir, new_dentry);
4871 new_is_dir = d_is_dir(new_dentry);
4873 if (!(flags & RENAME_EXCHANGE))
4874 error = may_delete(rd->new_mnt_idmap, new_dir,
4875 new_dentry, is_dir);
4877 error = may_delete(rd->new_mnt_idmap, new_dir,
4878 new_dentry, new_is_dir);
4883 if (!old_dir->i_op->rename)
4887 * If we are going to change the parent - check write permissions,
4888 * we'll need to flip '..'.
4890 if (new_dir != old_dir) {
4892 error = inode_permission(rd->old_mnt_idmap, source,
4897 if ((flags & RENAME_EXCHANGE) && new_is_dir) {
4898 error = inode_permission(rd->new_mnt_idmap, target,
4905 error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,
4910 take_dentry_name_snapshot(&old_name, old_dentry);
4914 * The source subdirectory needs to be locked on cross-directory
4915 * rename or cross-directory exchange since its parent changes.
4916 * The target subdirectory needs to be locked on cross-directory
4917 * exchange due to parent change and on any rename due to becoming
4919 * Non-directories need locking in all cases (for NFS reasons);
4920 * they get locked after any subdirectories (in inode address order).
4922 * NOTE: WE ONLY LOCK UNRELATED DIRECTORIES IN CROSS-DIRECTORY CASE.
4923 * NEVER, EVER DO THAT WITHOUT ->s_vfs_rename_mutex.
4925 lock_old_subdir = new_dir != old_dir;
4926 lock_new_subdir = new_dir != old_dir || !(flags & RENAME_EXCHANGE);
4928 if (lock_old_subdir)
4929 inode_lock_nested(source, I_MUTEX_CHILD);
4930 if (target && (!new_is_dir || lock_new_subdir))
4932 } else if (new_is_dir) {
4933 if (lock_new_subdir)
4934 inode_lock_nested(target, I_MUTEX_CHILD);
4937 lock_two_nondirectories(source, target);
4941 if (IS_SWAPFILE(source) || (target && IS_SWAPFILE(target)))
4945 if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
4948 if (max_links && new_dir != old_dir) {
4950 if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)
4952 if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&
4953 old_dir->i_nlink >= max_links)
4957 error = try_break_deleg(source, delegated_inode);
4961 if (target && !new_is_dir) {
4962 error = try_break_deleg(target, delegated_inode);
4966 error = old_dir->i_op->rename(rd->new_mnt_idmap, old_dir, old_dentry,
4967 new_dir, new_dentry, flags);
4971 if (!(flags & RENAME_EXCHANGE) && target) {
4973 shrink_dcache_parent(new_dentry);
4974 target->i_flags |= S_DEAD;
4976 dont_mount(new_dentry);
4977 detach_mounts(new_dentry);
4979 if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {
4980 if (!(flags & RENAME_EXCHANGE))
4981 d_move(old_dentry, new_dentry);
4983 d_exchange(old_dentry, new_dentry);
4986 if (!is_dir || lock_old_subdir)
4987 inode_unlock(source);
4988 if (target && (!new_is_dir || lock_new_subdir))
4989 inode_unlock(target);
4992 fsnotify_move(old_dir, new_dir, &old_name.name, is_dir,
4993 !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);
4994 if (flags & RENAME_EXCHANGE) {
4995 fsnotify_move(new_dir, old_dir, &old_dentry->d_name,
4996 new_is_dir, NULL, new_dentry);
4999 release_dentry_name_snapshot(&old_name);
5003 EXPORT_SYMBOL(vfs_rename);
5005 int do_renameat2(int olddfd, struct filename *from, int newdfd,
5006 struct filename *to, unsigned int flags)
5008 struct renamedata rd;
5009 struct dentry *old_dentry, *new_dentry;
5010 struct dentry *trap;
5011 struct path old_path, new_path;
5012 struct qstr old_last, new_last;
5013 int old_type, new_type;
5014 struct inode *delegated_inode = NULL;
5015 unsigned int lookup_flags = 0, target_flags = LOOKUP_RENAME_TARGET;
5016 bool should_retry = false;
5017 int error = -EINVAL;
5019 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
5022 if ((flags & (RENAME_NOREPLACE | RENAME_WHITEOUT)) &&
5023 (flags & RENAME_EXCHANGE))
5026 if (flags & RENAME_EXCHANGE)
5030 error = filename_parentat(olddfd, from, lookup_flags, &old_path,
5031 &old_last, &old_type);
5035 error = filename_parentat(newdfd, to, lookup_flags, &new_path, &new_last,
5041 if (old_path.mnt != new_path.mnt)
5045 if (old_type != LAST_NORM)
5048 if (flags & RENAME_NOREPLACE)
5050 if (new_type != LAST_NORM)
5053 error = mnt_want_write(old_path.mnt);
5058 trap = lock_rename(new_path.dentry, old_path.dentry);
5060 error = PTR_ERR(trap);
5061 goto exit_lock_rename;
5064 old_dentry = lookup_one_qstr_excl(&old_last, old_path.dentry,
5066 error = PTR_ERR(old_dentry);
5067 if (IS_ERR(old_dentry))
5069 /* source must exist */
5071 if (d_is_negative(old_dentry))
5073 new_dentry = lookup_one_qstr_excl(&new_last, new_path.dentry,
5074 lookup_flags | target_flags);
5075 error = PTR_ERR(new_dentry);
5076 if (IS_ERR(new_dentry))
5079 if ((flags & RENAME_NOREPLACE) && d_is_positive(new_dentry))
5081 if (flags & RENAME_EXCHANGE) {
5083 if (d_is_negative(new_dentry))
5086 if (!d_is_dir(new_dentry)) {
5088 if (new_last.name[new_last.len])
5092 /* unless the source is a directory trailing slashes give -ENOTDIR */
5093 if (!d_is_dir(old_dentry)) {
5095 if (old_last.name[old_last.len])
5097 if (!(flags & RENAME_EXCHANGE) && new_last.name[new_last.len])
5100 /* source should not be ancestor of target */
5102 if (old_dentry == trap)
5104 /* target should not be an ancestor of source */
5105 if (!(flags & RENAME_EXCHANGE))
5107 if (new_dentry == trap)
5110 error = security_path_rename(&old_path, old_dentry,
5111 &new_path, new_dentry, flags);
5115 rd.old_dir = old_path.dentry->d_inode;
5116 rd.old_dentry = old_dentry;
5117 rd.old_mnt_idmap = mnt_idmap(old_path.mnt);
5118 rd.new_dir = new_path.dentry->d_inode;
5119 rd.new_dentry = new_dentry;
5120 rd.new_mnt_idmap = mnt_idmap(new_path.mnt);
5121 rd.delegated_inode = &delegated_inode;
5123 error = vfs_rename(&rd);
5129 unlock_rename(new_path.dentry, old_path.dentry);
5131 if (delegated_inode) {
5132 error = break_deleg_wait(&delegated_inode);
5136 mnt_drop_write(old_path.mnt);
5138 if (retry_estale(error, lookup_flags))
5139 should_retry = true;
5140 path_put(&new_path);
5142 path_put(&old_path);
5144 should_retry = false;
5145 lookup_flags |= LOOKUP_REVAL;
5154 SYSCALL_DEFINE5(renameat2, int, olddfd, const char __user *, oldname,
5155 int, newdfd, const char __user *, newname, unsigned int, flags)
5157 return do_renameat2(olddfd, getname(oldname), newdfd, getname(newname),
5161 SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname,
5162 int, newdfd, const char __user *, newname)
5164 return do_renameat2(olddfd, getname(oldname), newdfd, getname(newname),
5168 SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname)
5170 return do_renameat2(AT_FDCWD, getname(oldname), AT_FDCWD,
5171 getname(newname), 0);
5174 int readlink_copy(char __user *buffer, int buflen, const char *link)
5176 int len = PTR_ERR(link);
5181 if (len > (unsigned) buflen)
5183 if (copy_to_user(buffer, link, len))
5190 * vfs_readlink - copy symlink body into userspace buffer
5191 * @dentry: dentry on which to get symbolic link
5192 * @buffer: user memory pointer
5193 * @buflen: size of buffer
5195 * Does not touch atime. That's up to the caller if necessary
5197 * Does not call security hook.
5199 int vfs_readlink(struct dentry *dentry, char __user *buffer, int buflen)
5201 struct inode *inode = d_inode(dentry);
5202 DEFINE_DELAYED_CALL(done);
5206 if (unlikely(!(inode->i_opflags & IOP_DEFAULT_READLINK))) {
5207 if (unlikely(inode->i_op->readlink))
5208 return inode->i_op->readlink(dentry, buffer, buflen);
5210 if (!d_is_symlink(dentry))
5213 spin_lock(&inode->i_lock);
5214 inode->i_opflags |= IOP_DEFAULT_READLINK;
5215 spin_unlock(&inode->i_lock);
5218 link = READ_ONCE(inode->i_link);
5220 link = inode->i_op->get_link(dentry, inode, &done);
5222 return PTR_ERR(link);
5224 res = readlink_copy(buffer, buflen, link);
5225 do_delayed_call(&done);
5228 EXPORT_SYMBOL(vfs_readlink);
5231 * vfs_get_link - get symlink body
5232 * @dentry: dentry on which to get symbolic link
5233 * @done: caller needs to free returned data with this
5235 * Calls security hook and i_op->get_link() on the supplied inode.
5237 * It does not touch atime. That's up to the caller if necessary.
5239 * Does not work on "special" symlinks like /proc/$$/fd/N
5241 const char *vfs_get_link(struct dentry *dentry, struct delayed_call *done)
5243 const char *res = ERR_PTR(-EINVAL);
5244 struct inode *inode = d_inode(dentry);
5246 if (d_is_symlink(dentry)) {
5247 res = ERR_PTR(security_inode_readlink(dentry));
5249 res = inode->i_op->get_link(dentry, inode, done);
5253 EXPORT_SYMBOL(vfs_get_link);
5255 /* get the link contents into pagecache */
5256 const char *page_get_link(struct dentry *dentry, struct inode *inode,
5257 struct delayed_call *callback)
5261 struct address_space *mapping = inode->i_mapping;
5264 page = find_get_page(mapping, 0);
5266 return ERR_PTR(-ECHILD);
5267 if (!PageUptodate(page)) {
5269 return ERR_PTR(-ECHILD);
5272 page = read_mapping_page(mapping, 0, NULL);
5276 set_delayed_call(callback, page_put_link, page);
5277 BUG_ON(mapping_gfp_mask(mapping) & __GFP_HIGHMEM);
5278 kaddr = page_address(page);
5279 nd_terminate_link(kaddr, inode->i_size, PAGE_SIZE - 1);
5283 EXPORT_SYMBOL(page_get_link);
5285 void page_put_link(void *arg)
5289 EXPORT_SYMBOL(page_put_link);
5291 int page_readlink(struct dentry *dentry, char __user *buffer, int buflen)
5293 DEFINE_DELAYED_CALL(done);
5294 int res = readlink_copy(buffer, buflen,
5295 page_get_link(dentry, d_inode(dentry),
5297 do_delayed_call(&done);
5300 EXPORT_SYMBOL(page_readlink);
5302 int page_symlink(struct inode *inode, const char *symname, int len)
5304 struct address_space *mapping = inode->i_mapping;
5305 const struct address_space_operations *aops = mapping->a_ops;
5306 bool nofs = !mapping_gfp_constraint(mapping, __GFP_FS);
5308 void *fsdata = NULL;
5314 flags = memalloc_nofs_save();
5315 err = aops->write_begin(NULL, mapping, 0, len-1, &page, &fsdata);
5317 memalloc_nofs_restore(flags);
5321 memcpy(page_address(page), symname, len-1);
5323 err = aops->write_end(NULL, mapping, 0, len-1, len-1,
5330 mark_inode_dirty(inode);
5335 EXPORT_SYMBOL(page_symlink);
5337 const struct inode_operations page_symlink_inode_operations = {
5338 .get_link = page_get_link,
5340 EXPORT_SYMBOL(page_symlink_inode_operations);