xref: /openbmc/linux/fs/namei.c (revision c2fd68b6)
1b2441318SGreg Kroah-Hartman // SPDX-License-Identifier: GPL-2.0
21da177e4SLinus Torvalds /*
31da177e4SLinus Torvalds  *  linux/fs/namei.c
41da177e4SLinus Torvalds  *
51da177e4SLinus Torvalds  *  Copyright (C) 1991, 1992  Linus Torvalds
61da177e4SLinus Torvalds  */
71da177e4SLinus Torvalds 
81da177e4SLinus Torvalds /*
91da177e4SLinus Torvalds  * Some corrections by tytso.
101da177e4SLinus Torvalds  */
111da177e4SLinus Torvalds 
121da177e4SLinus Torvalds /* [Feb 1997 T. Schoebel-Theuer] Complete rewrite of the pathname
131da177e4SLinus Torvalds  * lookup logic.
141da177e4SLinus Torvalds  */
151da177e4SLinus Torvalds /* [Feb-Apr 2000, AV] Rewrite to the new namespace architecture.
161da177e4SLinus Torvalds  */
171da177e4SLinus Torvalds 
181da177e4SLinus Torvalds #include <linux/init.h>
19630d9c47SPaul Gortmaker #include <linux/export.h>
2044696908SDavid S. Miller #include <linux/kernel.h>
211da177e4SLinus Torvalds #include <linux/slab.h>
221da177e4SLinus Torvalds #include <linux/fs.h>
231da177e4SLinus Torvalds #include <linux/namei.h>
241da177e4SLinus Torvalds #include <linux/pagemap.h>
250eeca283SRobert Love #include <linux/fsnotify.h>
261da177e4SLinus Torvalds #include <linux/personality.h>
271da177e4SLinus Torvalds #include <linux/security.h>
286146f0d5SMimi Zohar #include <linux/ima.h>
291da177e4SLinus Torvalds #include <linux/syscalls.h>
301da177e4SLinus Torvalds #include <linux/mount.h>
311da177e4SLinus Torvalds #include <linux/audit.h>
3216f7e0feSRandy Dunlap #include <linux/capability.h>
33834f2a4aSTrond Myklebust #include <linux/file.h>
345590ff0dSUlrich Drepper #include <linux/fcntl.h>
3508ce5f16SSerge E. Hallyn #include <linux/device_cgroup.h>
365ad4e53bSAl Viro #include <linux/fs_struct.h>
37e77819e5SLinus Torvalds #include <linux/posix_acl.h>
3899d263d4SLinus Torvalds #include <linux/hash.h>
392a18da7aSGeorge Spelvin #include <linux/bitops.h>
40aeaa4a79SEric W. Biederman #include <linux/init_task.h>
417c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
421da177e4SLinus Torvalds 
43e81e3f4dSEric Paris #include "internal.h"
44c7105365SAl Viro #include "mount.h"
45e81e3f4dSEric Paris 
461da177e4SLinus Torvalds /* [Feb-1997 T. Schoebel-Theuer]
471da177e4SLinus Torvalds  * Fundamental changes in the pathname lookup mechanisms (namei)
481da177e4SLinus Torvalds  * were necessary because of omirr.  The reason is that omirr needs
491da177e4SLinus Torvalds  * to know the _real_ pathname, not the user-supplied one, in case
501da177e4SLinus Torvalds  * of symlinks (and also when transname replacements occur).
511da177e4SLinus Torvalds  *
521da177e4SLinus Torvalds  * The new code replaces the old recursive symlink resolution with
531da177e4SLinus Torvalds  * an iterative one (in case of non-nested symlink chains).  It does
541da177e4SLinus Torvalds  * this with calls to <fs>_follow_link().
551da177e4SLinus Torvalds  * As a side effect, dir_namei(), _namei() and follow_link() are now
561da177e4SLinus Torvalds  * replaced with a single function lookup_dentry() that can handle all
571da177e4SLinus Torvalds  * the special cases of the former code.
581da177e4SLinus Torvalds  *
591da177e4SLinus Torvalds  * With the new dcache, the pathname is stored at each inode, at least as
601da177e4SLinus Torvalds  * long as the refcount of the inode is positive.  As a side effect, the
611da177e4SLinus Torvalds  * size of the dcache depends on the inode cache and thus is dynamic.
621da177e4SLinus Torvalds  *
631da177e4SLinus Torvalds  * [29-Apr-1998 C. Scott Ananian] Updated above description of symlink
641da177e4SLinus Torvalds  * resolution to correspond with current state of the code.
651da177e4SLinus Torvalds  *
661da177e4SLinus Torvalds  * Note that the symlink resolution is not *completely* iterative.
671da177e4SLinus Torvalds  * There is still a significant amount of tail- and mid- recursion in
681da177e4SLinus Torvalds  * the algorithm.  Also, note that <fs>_readlink() is not used in
691da177e4SLinus Torvalds  * lookup_dentry(): lookup_dentry() on the result of <fs>_readlink()
701da177e4SLinus Torvalds  * may return different results than <fs>_follow_link().  Many virtual
711da177e4SLinus Torvalds  * filesystems (including /proc) exhibit this behavior.
721da177e4SLinus Torvalds  */
731da177e4SLinus Torvalds 
741da177e4SLinus Torvalds /* [24-Feb-97 T. Schoebel-Theuer] Side effects caused by new implementation:
751da177e4SLinus Torvalds  * New symlink semantics: when open() is called with flags O_CREAT | O_EXCL
761da177e4SLinus Torvalds  * and the name already exists in form of a symlink, try to create the new
771da177e4SLinus Torvalds  * name indicated by the symlink. The old code always complained that the
781da177e4SLinus Torvalds  * name already exists, due to not following the symlink even if its target
791da177e4SLinus Torvalds  * is nonexistent.  The new semantics affects also mknod() and link() when
8025985edcSLucas De Marchi  * the name is a symlink pointing to a non-existent name.
811da177e4SLinus Torvalds  *
821da177e4SLinus Torvalds  * I don't know which semantics is the right one, since I have no access
831da177e4SLinus Torvalds  * to standards. But I found by trial that HP-UX 9.0 has the full "new"
841da177e4SLinus Torvalds  * semantics implemented, while SunOS 4.1.1 and Solaris (SunOS 5.4) have the
851da177e4SLinus Torvalds  * "old" one. Personally, I think the new semantics is much more logical.
861da177e4SLinus Torvalds  * Note that "ln old new" where "new" is a symlink pointing to a non-existing
871da177e4SLinus Torvalds  * file does succeed in both HP-UX and SunOs, but not in Solaris
881da177e4SLinus Torvalds  * and in the old Linux semantics.
891da177e4SLinus Torvalds  */
901da177e4SLinus Torvalds 
911da177e4SLinus Torvalds /* [16-Dec-97 Kevin Buhr] For security reasons, we change some symlink
921da177e4SLinus Torvalds  * semantics.  See the comments in "open_namei" and "do_link" below.
931da177e4SLinus Torvalds  *
941da177e4SLinus Torvalds  * [10-Sep-98 Alan Modra] Another symlink change.
951da177e4SLinus Torvalds  */
961da177e4SLinus Torvalds 
971da177e4SLinus Torvalds /* [Feb-Apr 2000 AV] Complete rewrite. Rules for symlinks:
981da177e4SLinus Torvalds  *	inside the path - always follow.
991da177e4SLinus Torvalds  *	in the last component in creation/removal/renaming - never follow.
1001da177e4SLinus Torvalds  *	if LOOKUP_FOLLOW passed - follow.
1011da177e4SLinus Torvalds  *	if the pathname has trailing slashes - follow.
1021da177e4SLinus Torvalds  *	otherwise - don't follow.
1031da177e4SLinus Torvalds  * (applied in that order).
1041da177e4SLinus Torvalds  *
1051da177e4SLinus Torvalds  * [Jun 2000 AV] Inconsistent behaviour of open() in case if flags==O_CREAT
1061da177e4SLinus Torvalds  * restored for 2.4. This is the last surviving part of old 4.2BSD bug.
1071da177e4SLinus Torvalds  * During the 2.4 we need to fix the userland stuff depending on it -
1081da177e4SLinus Torvalds  * hopefully we will be able to get rid of that wart in 2.5. So far only
1091da177e4SLinus Torvalds  * XEmacs seems to be relying on it...
1101da177e4SLinus Torvalds  */
1111da177e4SLinus Torvalds /*
1121da177e4SLinus Torvalds  * [Sep 2001 AV] Single-semaphore locking scheme (kudos to David Holland)
113a11f3a05SArjan van de Ven  * implemented.  Let's see if raised priority of ->s_vfs_rename_mutex gives
1141da177e4SLinus Torvalds  * any extra contention...
1151da177e4SLinus Torvalds  */
1161da177e4SLinus Torvalds 
1171da177e4SLinus Torvalds /* In order to reduce some races, while at the same time doing additional
1181da177e4SLinus Torvalds  * checking and hopefully speeding things up, we copy filenames to the
1191da177e4SLinus Torvalds  * kernel data space before using them..
1201da177e4SLinus Torvalds  *
1211da177e4SLinus Torvalds  * POSIX.1 2.4: an empty pathname is invalid (ENOENT).
1221da177e4SLinus Torvalds  * PATH_MAX includes the nul terminator --RR.
1231da177e4SLinus Torvalds  */
1247950e385SJeff Layton 
125fd2f7cb5SAl Viro #define EMBEDDED_NAME_MAX	(PATH_MAX - offsetof(struct filename, iname))
12691a27b2aSJeff Layton 
12751f39a1fSDavid Drysdale struct filename *
12891a27b2aSJeff Layton getname_flags(const char __user *filename, int flags, int *empty)
12991a27b2aSJeff Layton {
13094b5d262SAl Viro 	struct filename *result;
1317950e385SJeff Layton 	char *kname;
13294b5d262SAl Viro 	int len;
1331da177e4SLinus Torvalds 
1347ac86265SJeff Layton 	result = audit_reusename(filename);
1357ac86265SJeff Layton 	if (result)
1367ac86265SJeff Layton 		return result;
1377ac86265SJeff Layton 
1387950e385SJeff Layton 	result = __getname();
1393f9f0aa6SLinus Torvalds 	if (unlikely(!result))
1404043cde8SEric Paris 		return ERR_PTR(-ENOMEM);
1411da177e4SLinus Torvalds 
1427950e385SJeff Layton 	/*
1437950e385SJeff Layton 	 * First, try to embed the struct filename inside the names_cache
1447950e385SJeff Layton 	 * allocation
1457950e385SJeff Layton 	 */
146fd2f7cb5SAl Viro 	kname = (char *)result->iname;
14791a27b2aSJeff Layton 	result->name = kname;
1487950e385SJeff Layton 
14994b5d262SAl Viro 	len = strncpy_from_user(kname, filename, EMBEDDED_NAME_MAX);
15091a27b2aSJeff Layton 	if (unlikely(len < 0)) {
15194b5d262SAl Viro 		__putname(result);
15294b5d262SAl Viro 		return ERR_PTR(len);
15391a27b2aSJeff Layton 	}
1543f9f0aa6SLinus Torvalds 
1557950e385SJeff Layton 	/*
1567950e385SJeff Layton 	 * Uh-oh. We have a name that's approaching PATH_MAX. Allocate a
1577950e385SJeff Layton 	 * separate struct filename so we can dedicate the entire
1587950e385SJeff Layton 	 * names_cache allocation for the pathname, and re-do the copy from
1597950e385SJeff Layton 	 * userland.
1607950e385SJeff Layton 	 */
16194b5d262SAl Viro 	if (unlikely(len == EMBEDDED_NAME_MAX)) {
162fd2f7cb5SAl Viro 		const size_t size = offsetof(struct filename, iname[1]);
1637950e385SJeff Layton 		kname = (char *)result;
1647950e385SJeff Layton 
165fd2f7cb5SAl Viro 		/*
166fd2f7cb5SAl Viro 		 * size is chosen that way we to guarantee that
167fd2f7cb5SAl Viro 		 * result->iname[0] is within the same object and that
168fd2f7cb5SAl Viro 		 * kname can't be equal to result->iname, no matter what.
169fd2f7cb5SAl Viro 		 */
170fd2f7cb5SAl Viro 		result = kzalloc(size, GFP_KERNEL);
17194b5d262SAl Viro 		if (unlikely(!result)) {
17294b5d262SAl Viro 			__putname(kname);
17394b5d262SAl Viro 			return ERR_PTR(-ENOMEM);
1747950e385SJeff Layton 		}
1757950e385SJeff Layton 		result->name = kname;
17694b5d262SAl Viro 		len = strncpy_from_user(kname, filename, PATH_MAX);
17794b5d262SAl Viro 		if (unlikely(len < 0)) {
17894b5d262SAl Viro 			__putname(kname);
17994b5d262SAl Viro 			kfree(result);
18094b5d262SAl Viro 			return ERR_PTR(len);
18194b5d262SAl Viro 		}
18294b5d262SAl Viro 		if (unlikely(len == PATH_MAX)) {
18394b5d262SAl Viro 			__putname(kname);
18494b5d262SAl Viro 			kfree(result);
18594b5d262SAl Viro 			return ERR_PTR(-ENAMETOOLONG);
18694b5d262SAl Viro 		}
1877950e385SJeff Layton 	}
1887950e385SJeff Layton 
18994b5d262SAl Viro 	result->refcnt = 1;
1903f9f0aa6SLinus Torvalds 	/* The empty path is special. */
1913f9f0aa6SLinus Torvalds 	if (unlikely(!len)) {
1923f9f0aa6SLinus Torvalds 		if (empty)
1931fa1e7f6SAndy Whitcroft 			*empty = 1;
19494b5d262SAl Viro 		if (!(flags & LOOKUP_EMPTY)) {
19594b5d262SAl Viro 			putname(result);
19694b5d262SAl Viro 			return ERR_PTR(-ENOENT);
1971da177e4SLinus Torvalds 		}
19894b5d262SAl Viro 	}
1997950e385SJeff Layton 
2007950e385SJeff Layton 	result->uptr = filename;
201c4ad8f98SLinus Torvalds 	result->aname = NULL;
2021da177e4SLinus Torvalds 	audit_getname(result);
2031da177e4SLinus Torvalds 	return result;
2043f9f0aa6SLinus Torvalds }
2053f9f0aa6SLinus Torvalds 
20691a27b2aSJeff Layton struct filename *
20791a27b2aSJeff Layton getname(const char __user * filename)
208f52e0c11SAl Viro {
209f7493e5dSLinus Torvalds 	return getname_flags(filename, 0, NULL);
210f52e0c11SAl Viro }
211f52e0c11SAl Viro 
212c4ad8f98SLinus Torvalds struct filename *
213c4ad8f98SLinus Torvalds getname_kernel(const char * filename)
214c4ad8f98SLinus Torvalds {
215c4ad8f98SLinus Torvalds 	struct filename *result;
21608518549SPaul Moore 	int len = strlen(filename) + 1;
217c4ad8f98SLinus Torvalds 
218c4ad8f98SLinus Torvalds 	result = __getname();
219c4ad8f98SLinus Torvalds 	if (unlikely(!result))
220c4ad8f98SLinus Torvalds 		return ERR_PTR(-ENOMEM);
221c4ad8f98SLinus Torvalds 
22208518549SPaul Moore 	if (len <= EMBEDDED_NAME_MAX) {
223fd2f7cb5SAl Viro 		result->name = (char *)result->iname;
22408518549SPaul Moore 	} else if (len <= PATH_MAX) {
22530ce4d19SAl Viro 		const size_t size = offsetof(struct filename, iname[1]);
22608518549SPaul Moore 		struct filename *tmp;
22708518549SPaul Moore 
22830ce4d19SAl Viro 		tmp = kmalloc(size, GFP_KERNEL);
22908518549SPaul Moore 		if (unlikely(!tmp)) {
23008518549SPaul Moore 			__putname(result);
23108518549SPaul Moore 			return ERR_PTR(-ENOMEM);
23208518549SPaul Moore 		}
23308518549SPaul Moore 		tmp->name = (char *)result;
23408518549SPaul Moore 		result = tmp;
23508518549SPaul Moore 	} else {
23608518549SPaul Moore 		__putname(result);
23708518549SPaul Moore 		return ERR_PTR(-ENAMETOOLONG);
23808518549SPaul Moore 	}
23908518549SPaul Moore 	memcpy((char *)result->name, filename, len);
240c4ad8f98SLinus Torvalds 	result->uptr = NULL;
241c4ad8f98SLinus Torvalds 	result->aname = NULL;
24255422d0bSPaul Moore 	result->refcnt = 1;
243fd3522fdSPaul Moore 	audit_getname(result);
244c4ad8f98SLinus Torvalds 
245c4ad8f98SLinus Torvalds 	return result;
246c4ad8f98SLinus Torvalds }
247c4ad8f98SLinus Torvalds 
24891a27b2aSJeff Layton void putname(struct filename *name)
2491da177e4SLinus Torvalds {
25055422d0bSPaul Moore 	BUG_ON(name->refcnt <= 0);
25155422d0bSPaul Moore 
25255422d0bSPaul Moore 	if (--name->refcnt > 0)
25355422d0bSPaul Moore 		return;
25455422d0bSPaul Moore 
255fd2f7cb5SAl Viro 	if (name->name != name->iname) {
25655422d0bSPaul Moore 		__putname(name->name);
25755422d0bSPaul Moore 		kfree(name);
25855422d0bSPaul Moore 	} else
25955422d0bSPaul Moore 		__putname(name);
2601da177e4SLinus Torvalds }
2611da177e4SLinus Torvalds 
26247291baaSChristian Brauner /**
26347291baaSChristian Brauner  * check_acl - perform ACL permission checking
26447291baaSChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
26547291baaSChristian Brauner  * @inode:	inode to check permissions on
26647291baaSChristian Brauner  * @mask:	right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
26747291baaSChristian Brauner  *
26847291baaSChristian Brauner  * This function performs the ACL permission checking. Since this function
26947291baaSChristian Brauner  * retrieve POSIX acls it needs to know whether it is called from a blocking or
27047291baaSChristian Brauner  * non-blocking context and thus cares about the MAY_NOT_BLOCK bit.
27147291baaSChristian Brauner  *
27247291baaSChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
27347291baaSChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
27447291baaSChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
27547291baaSChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
27647291baaSChristian Brauner  * raw inode simply passs init_user_ns.
27747291baaSChristian Brauner  */
27847291baaSChristian Brauner static int check_acl(struct user_namespace *mnt_userns,
27947291baaSChristian Brauner 		     struct inode *inode, int mask)
280e77819e5SLinus Torvalds {
28184635d68SLinus Torvalds #ifdef CONFIG_FS_POSIX_ACL
282e77819e5SLinus Torvalds 	struct posix_acl *acl;
283e77819e5SLinus Torvalds 
284e77819e5SLinus Torvalds 	if (mask & MAY_NOT_BLOCK) {
2853567866bSAl Viro 		acl = get_cached_acl_rcu(inode, ACL_TYPE_ACCESS);
2863567866bSAl Viro 	        if (!acl)
287e77819e5SLinus Torvalds 	                return -EAGAIN;
2883567866bSAl Viro 		/* no ->get_acl() calls in RCU mode... */
289b8a7a3a6SAndreas Gruenbacher 		if (is_uncached_acl(acl))
290e77819e5SLinus Torvalds 			return -ECHILD;
29147291baaSChristian Brauner 	        return posix_acl_permission(mnt_userns, inode, acl, mask);
292e77819e5SLinus Torvalds 	}
293e77819e5SLinus Torvalds 
2942982baa2SChristoph Hellwig 	acl = get_acl(inode, ACL_TYPE_ACCESS);
2954e34e719SChristoph Hellwig 	if (IS_ERR(acl))
2964e34e719SChristoph Hellwig 		return PTR_ERR(acl);
297e77819e5SLinus Torvalds 	if (acl) {
29847291baaSChristian Brauner 	        int error = posix_acl_permission(mnt_userns, inode, acl, mask);
299e77819e5SLinus Torvalds 	        posix_acl_release(acl);
300e77819e5SLinus Torvalds 	        return error;
301e77819e5SLinus Torvalds 	}
30284635d68SLinus Torvalds #endif
303e77819e5SLinus Torvalds 
304e77819e5SLinus Torvalds 	return -EAGAIN;
305e77819e5SLinus Torvalds }
306e77819e5SLinus Torvalds 
30747291baaSChristian Brauner /**
30847291baaSChristian Brauner  * acl_permission_check - perform basic UNIX permission checking
30947291baaSChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
31047291baaSChristian Brauner  * @inode:	inode to check permissions on
31147291baaSChristian Brauner  * @mask:	right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
3125fc475b7SLinus Torvalds  *
31347291baaSChristian Brauner  * This function performs the basic UNIX permission checking. Since this
31447291baaSChristian Brauner  * function may retrieve POSIX acls it needs to know whether it is called from a
31547291baaSChristian Brauner  * blocking or non-blocking context and thus cares about the MAY_NOT_BLOCK bit.
31647291baaSChristian Brauner  *
31747291baaSChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
31847291baaSChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
31947291baaSChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
32047291baaSChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
32147291baaSChristian Brauner  * raw inode simply passs init_user_ns.
3225909ccaaSLinus Torvalds  */
32347291baaSChristian Brauner static int acl_permission_check(struct user_namespace *mnt_userns,
32447291baaSChristian Brauner 				struct inode *inode, int mask)
3255909ccaaSLinus Torvalds {
32626cf46beSLinus Torvalds 	unsigned int mode = inode->i_mode;
32747291baaSChristian Brauner 	kuid_t i_uid;
3285909ccaaSLinus Torvalds 
3295fc475b7SLinus Torvalds 	/* Are we the owner? If so, ACL's don't matter */
33047291baaSChristian Brauner 	i_uid = i_uid_into_mnt(mnt_userns, inode);
33147291baaSChristian Brauner 	if (likely(uid_eq(current_fsuid(), i_uid))) {
3325fc475b7SLinus Torvalds 		mask &= 7;
3335909ccaaSLinus Torvalds 		mode >>= 6;
3345fc475b7SLinus Torvalds 		return (mask & ~mode) ? -EACCES : 0;
3355fc475b7SLinus Torvalds 	}
3365fc475b7SLinus Torvalds 
3375fc475b7SLinus Torvalds 	/* Do we have ACL's? */
338e77819e5SLinus Torvalds 	if (IS_POSIXACL(inode) && (mode & S_IRWXG)) {
33947291baaSChristian Brauner 		int error = check_acl(mnt_userns, inode, mask);
3405909ccaaSLinus Torvalds 		if (error != -EAGAIN)
3415909ccaaSLinus Torvalds 			return error;
3425909ccaaSLinus Torvalds 	}
3435909ccaaSLinus Torvalds 
3445fc475b7SLinus Torvalds 	/* Only RWX matters for group/other mode bits */
3455fc475b7SLinus Torvalds 	mask &= 7;
3465fc475b7SLinus Torvalds 
3475fc475b7SLinus Torvalds 	/*
3485fc475b7SLinus Torvalds 	 * Are the group permissions different from
3495fc475b7SLinus Torvalds 	 * the other permissions in the bits we care
3505fc475b7SLinus Torvalds 	 * about? Need to check group ownership if so.
3515fc475b7SLinus Torvalds 	 */
3525fc475b7SLinus Torvalds 	if (mask & (mode ^ (mode >> 3))) {
35347291baaSChristian Brauner 		kgid_t kgid = i_gid_into_mnt(mnt_userns, inode);
35447291baaSChristian Brauner 		if (in_group_p(kgid))
3555909ccaaSLinus Torvalds 			mode >>= 3;
3565909ccaaSLinus Torvalds 	}
3575909ccaaSLinus Torvalds 
3585fc475b7SLinus Torvalds 	/* Bits in 'mode' clear that we require? */
3595fc475b7SLinus Torvalds 	return (mask & ~mode) ? -EACCES : 0;
3605909ccaaSLinus Torvalds }
3611da177e4SLinus Torvalds 
3621da177e4SLinus Torvalds /**
3631da177e4SLinus Torvalds  * generic_permission -  check for access rights on a Posix-like filesystem
36447291baaSChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
3651da177e4SLinus Torvalds  * @inode:	inode to check access rights for
3665fc475b7SLinus Torvalds  * @mask:	right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC,
3675fc475b7SLinus Torvalds  *		%MAY_NOT_BLOCK ...)
3681da177e4SLinus Torvalds  *
3691da177e4SLinus Torvalds  * Used to check for read/write/execute permissions on a file.
3701da177e4SLinus Torvalds  * We use "fsuid" for this, letting us set arbitrary permissions
3711da177e4SLinus Torvalds  * for filesystem access without changing the "normal" uids which
372b74c79e9SNick Piggin  * are used for other things.
373b74c79e9SNick Piggin  *
374b74c79e9SNick Piggin  * generic_permission is rcu-walk aware. It returns -ECHILD in case an rcu-walk
375b74c79e9SNick Piggin  * request cannot be satisfied (eg. requires blocking or too much complexity).
376b74c79e9SNick Piggin  * It would then be called again in ref-walk mode.
37747291baaSChristian Brauner  *
37847291baaSChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
37947291baaSChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
38047291baaSChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
38147291baaSChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
38247291baaSChristian Brauner  * raw inode simply passs init_user_ns.
3831da177e4SLinus Torvalds  */
38447291baaSChristian Brauner int generic_permission(struct user_namespace *mnt_userns, struct inode *inode,
38547291baaSChristian Brauner 		       int mask)
3861da177e4SLinus Torvalds {
3875909ccaaSLinus Torvalds 	int ret;
3881da177e4SLinus Torvalds 
3891da177e4SLinus Torvalds 	/*
390948409c7SAndreas Gruenbacher 	 * Do the basic permission checks.
3911da177e4SLinus Torvalds 	 */
39247291baaSChristian Brauner 	ret = acl_permission_check(mnt_userns, inode, mask);
3935909ccaaSLinus Torvalds 	if (ret != -EACCES)
3945909ccaaSLinus Torvalds 		return ret;
3951da177e4SLinus Torvalds 
396d594e7ecSAl Viro 	if (S_ISDIR(inode->i_mode)) {
397d594e7ecSAl Viro 		/* DACs are overridable for directories */
398d594e7ecSAl Viro 		if (!(mask & MAY_WRITE))
39947291baaSChristian Brauner 			if (capable_wrt_inode_uidgid(mnt_userns, inode,
40023adbe12SAndy Lutomirski 						     CAP_DAC_READ_SEARCH))
401d594e7ecSAl Viro 				return 0;
40247291baaSChristian Brauner 		if (capable_wrt_inode_uidgid(mnt_userns, inode,
4030558c1bfSChristian Brauner 					     CAP_DAC_OVERRIDE))
4041da177e4SLinus Torvalds 			return 0;
4052a4c2242SStephen Smalley 		return -EACCES;
4062a4c2242SStephen Smalley 	}
4071da177e4SLinus Torvalds 
4081da177e4SLinus Torvalds 	/*
4091da177e4SLinus Torvalds 	 * Searching includes executable on directories, else just read.
4101da177e4SLinus Torvalds 	 */
4117ea66001SSerge E. Hallyn 	mask &= MAY_READ | MAY_WRITE | MAY_EXEC;
412d594e7ecSAl Viro 	if (mask == MAY_READ)
41347291baaSChristian Brauner 		if (capable_wrt_inode_uidgid(mnt_userns, inode,
4140558c1bfSChristian Brauner 					     CAP_DAC_READ_SEARCH))
4151da177e4SLinus Torvalds 			return 0;
4162a4c2242SStephen Smalley 	/*
4172a4c2242SStephen Smalley 	 * Read/write DACs are always overridable.
4182a4c2242SStephen Smalley 	 * Executable DACs are overridable when there is
4192a4c2242SStephen Smalley 	 * at least one exec bit set.
4202a4c2242SStephen Smalley 	 */
4212a4c2242SStephen Smalley 	if (!(mask & MAY_EXEC) || (inode->i_mode & S_IXUGO))
42247291baaSChristian Brauner 		if (capable_wrt_inode_uidgid(mnt_userns, inode,
4230558c1bfSChristian Brauner 					     CAP_DAC_OVERRIDE))
4242a4c2242SStephen Smalley 			return 0;
4251da177e4SLinus Torvalds 
4261da177e4SLinus Torvalds 	return -EACCES;
4271da177e4SLinus Torvalds }
4284d359507SAl Viro EXPORT_SYMBOL(generic_permission);
4291da177e4SLinus Torvalds 
43047291baaSChristian Brauner /**
43147291baaSChristian Brauner  * do_inode_permission - UNIX permission checking
43247291baaSChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
43347291baaSChristian Brauner  * @inode:	inode to check permissions on
43447291baaSChristian Brauner  * @mask:	right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
43547291baaSChristian Brauner  *
4363ddcd056SLinus Torvalds  * We _really_ want to just do "generic_permission()" without
4373ddcd056SLinus Torvalds  * even looking at the inode->i_op values. So we keep a cache
4383ddcd056SLinus Torvalds  * flag in inode->i_opflags, that says "this has not special
4393ddcd056SLinus Torvalds  * permission function, use the fast case".
4403ddcd056SLinus Torvalds  */
44147291baaSChristian Brauner static inline int do_inode_permission(struct user_namespace *mnt_userns,
44247291baaSChristian Brauner 				      struct inode *inode, int mask)
4433ddcd056SLinus Torvalds {
4443ddcd056SLinus Torvalds 	if (unlikely(!(inode->i_opflags & IOP_FASTPERM))) {
4453ddcd056SLinus Torvalds 		if (likely(inode->i_op->permission))
446549c7297SChristian Brauner 			return inode->i_op->permission(mnt_userns, inode, mask);
4473ddcd056SLinus Torvalds 
4483ddcd056SLinus Torvalds 		/* This gets set once for the inode lifetime */
4493ddcd056SLinus Torvalds 		spin_lock(&inode->i_lock);
4503ddcd056SLinus Torvalds 		inode->i_opflags |= IOP_FASTPERM;
4513ddcd056SLinus Torvalds 		spin_unlock(&inode->i_lock);
4523ddcd056SLinus Torvalds 	}
45347291baaSChristian Brauner 	return generic_permission(mnt_userns, inode, mask);
4543ddcd056SLinus Torvalds }
4553ddcd056SLinus Torvalds 
456cb23beb5SChristoph Hellwig /**
4570bdaea90SDavid Howells  * sb_permission - Check superblock-level permissions
4580bdaea90SDavid Howells  * @sb: Superblock of inode to check permission on
45955852635SRandy Dunlap  * @inode: Inode to check permission on
4600bdaea90SDavid Howells  * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
4610bdaea90SDavid Howells  *
4620bdaea90SDavid Howells  * Separate out file-system wide checks from inode-specific permission checks.
4630bdaea90SDavid Howells  */
4640bdaea90SDavid Howells static int sb_permission(struct super_block *sb, struct inode *inode, int mask)
4650bdaea90SDavid Howells {
4660bdaea90SDavid Howells 	if (unlikely(mask & MAY_WRITE)) {
4670bdaea90SDavid Howells 		umode_t mode = inode->i_mode;
4680bdaea90SDavid Howells 
4690bdaea90SDavid Howells 		/* Nobody gets write access to a read-only fs. */
470bc98a42cSDavid Howells 		if (sb_rdonly(sb) && (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode)))
4710bdaea90SDavid Howells 			return -EROFS;
4720bdaea90SDavid Howells 	}
4730bdaea90SDavid Howells 	return 0;
4740bdaea90SDavid Howells }
4750bdaea90SDavid Howells 
4760bdaea90SDavid Howells /**
4770bdaea90SDavid Howells  * inode_permission - Check for access rights to a given inode
47847291baaSChristian Brauner  * @mnt_userns:	User namespace of the mount the inode was found from
4790bdaea90SDavid Howells  * @inode:	Inode to check permission on
4800bdaea90SDavid Howells  * @mask:	Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
4810bdaea90SDavid Howells  *
4820bdaea90SDavid Howells  * Check for read/write/execute permissions on an inode.  We use fs[ug]id for
4830bdaea90SDavid Howells  * this, letting us set arbitrary permissions for filesystem access without
4840bdaea90SDavid Howells  * changing the "normal" UIDs which are used for other things.
4850bdaea90SDavid Howells  *
4860bdaea90SDavid Howells  * When checking for MAY_APPEND, MAY_WRITE must also be set in @mask.
4870bdaea90SDavid Howells  */
48847291baaSChristian Brauner int inode_permission(struct user_namespace *mnt_userns,
48947291baaSChristian Brauner 		     struct inode *inode, int mask)
4900bdaea90SDavid Howells {
4910bdaea90SDavid Howells 	int retval;
4920bdaea90SDavid Howells 
4930bdaea90SDavid Howells 	retval = sb_permission(inode->i_sb, inode, mask);
4940bdaea90SDavid Howells 	if (retval)
4950bdaea90SDavid Howells 		return retval;
4964bfd054aSEric Biggers 
4974bfd054aSEric Biggers 	if (unlikely(mask & MAY_WRITE)) {
4984bfd054aSEric Biggers 		/*
4994bfd054aSEric Biggers 		 * Nobody gets write access to an immutable file.
5004bfd054aSEric Biggers 		 */
5014bfd054aSEric Biggers 		if (IS_IMMUTABLE(inode))
5024bfd054aSEric Biggers 			return -EPERM;
5034bfd054aSEric Biggers 
5044bfd054aSEric Biggers 		/*
5054bfd054aSEric Biggers 		 * Updating mtime will likely cause i_uid and i_gid to be
5064bfd054aSEric Biggers 		 * written back improperly if their true value is unknown
5074bfd054aSEric Biggers 		 * to the vfs.
5084bfd054aSEric Biggers 		 */
509ba73d987SChristian Brauner 		if (HAS_UNMAPPED_ID(mnt_userns, inode))
5104bfd054aSEric Biggers 			return -EACCES;
5114bfd054aSEric Biggers 	}
5124bfd054aSEric Biggers 
51347291baaSChristian Brauner 	retval = do_inode_permission(mnt_userns, inode, mask);
5144bfd054aSEric Biggers 	if (retval)
5154bfd054aSEric Biggers 		return retval;
5164bfd054aSEric Biggers 
5174bfd054aSEric Biggers 	retval = devcgroup_inode_permission(inode, mask);
5184bfd054aSEric Biggers 	if (retval)
5194bfd054aSEric Biggers 		return retval;
5204bfd054aSEric Biggers 
5214bfd054aSEric Biggers 	return security_inode_permission(inode, mask);
5220bdaea90SDavid Howells }
5234d359507SAl Viro EXPORT_SYMBOL(inode_permission);
5240bdaea90SDavid Howells 
5250bdaea90SDavid Howells /**
5265dd784d0SJan Blunck  * path_get - get a reference to a path
5275dd784d0SJan Blunck  * @path: path to get the reference to
5285dd784d0SJan Blunck  *
5295dd784d0SJan Blunck  * Given a path increment the reference count to the dentry and the vfsmount.
5305dd784d0SJan Blunck  */
531dcf787f3SAl Viro void path_get(const struct path *path)
5325dd784d0SJan Blunck {
5335dd784d0SJan Blunck 	mntget(path->mnt);
5345dd784d0SJan Blunck 	dget(path->dentry);
5355dd784d0SJan Blunck }
5365dd784d0SJan Blunck EXPORT_SYMBOL(path_get);
5375dd784d0SJan Blunck 
5385dd784d0SJan Blunck /**
5391d957f9bSJan Blunck  * path_put - put a reference to a path
5401d957f9bSJan Blunck  * @path: path to put the reference to
5411d957f9bSJan Blunck  *
5421d957f9bSJan Blunck  * Given a path decrement the reference count to the dentry and the vfsmount.
5431d957f9bSJan Blunck  */
544dcf787f3SAl Viro void path_put(const struct path *path)
5451da177e4SLinus Torvalds {
5461d957f9bSJan Blunck 	dput(path->dentry);
5471d957f9bSJan Blunck 	mntput(path->mnt);
5481da177e4SLinus Torvalds }
5491d957f9bSJan Blunck EXPORT_SYMBOL(path_put);
5501da177e4SLinus Torvalds 
551894bc8c4SAl Viro #define EMBEDDED_LEVELS 2
5521f55a6ecSAl Viro struct nameidata {
5531f55a6ecSAl Viro 	struct path	path;
5541f55a6ecSAl Viro 	struct qstr	last;
5551f55a6ecSAl Viro 	struct path	root;
5561f55a6ecSAl Viro 	struct inode	*inode; /* path.dentry.d_inode */
557bcba1e7dSAl Viro 	unsigned int	flags, state;
558ab87f9a5SAleksa Sarai 	unsigned	seq, m_seq, r_seq;
5591f55a6ecSAl Viro 	int		last_type;
5601f55a6ecSAl Viro 	unsigned	depth;
561756daf26SNeilBrown 	int		total_link_count;
562697fc6caSAl Viro 	struct saved {
563697fc6caSAl Viro 		struct path link;
564fceef393SAl Viro 		struct delayed_call done;
565697fc6caSAl Viro 		const char *name;
5660450b2d1SAl Viro 		unsigned seq;
567894bc8c4SAl Viro 	} *stack, internal[EMBEDDED_LEVELS];
5689883d185SAl Viro 	struct filename	*name;
5699883d185SAl Viro 	struct nameidata *saved;
5709883d185SAl Viro 	unsigned	root_seq;
5719883d185SAl Viro 	int		dfd;
5720f705953SAl Viro 	kuid_t		dir_uid;
5730f705953SAl Viro 	umode_t		dir_mode;
5743859a271SKees Cook } __randomize_layout;
5751f55a6ecSAl Viro 
576bcba1e7dSAl Viro #define ND_ROOT_PRESET 1
577bcba1e7dSAl Viro #define ND_ROOT_GRABBED 2
578bcba1e7dSAl Viro #define ND_JUMPED 4
579bcba1e7dSAl Viro 
58006422964SAl Viro static void __set_nameidata(struct nameidata *p, int dfd, struct filename *name)
581894bc8c4SAl Viro {
582756daf26SNeilBrown 	struct nameidata *old = current->nameidata;
583756daf26SNeilBrown 	p->stack = p->internal;
5847962c7d1SAl Viro 	p->depth = 0;
585c8a53ee5SAl Viro 	p->dfd = dfd;
586c8a53ee5SAl Viro 	p->name = name;
5877d01ef75SAl Viro 	p->path.mnt = NULL;
5887d01ef75SAl Viro 	p->path.dentry = NULL;
589756daf26SNeilBrown 	p->total_link_count = old ? old->total_link_count : 0;
5909883d185SAl Viro 	p->saved = old;
591756daf26SNeilBrown 	current->nameidata = p;
592894bc8c4SAl Viro }
593894bc8c4SAl Viro 
59406422964SAl Viro static inline void set_nameidata(struct nameidata *p, int dfd, struct filename *name,
59506422964SAl Viro 			  const struct path *root)
59606422964SAl Viro {
59706422964SAl Viro 	__set_nameidata(p, dfd, name);
59806422964SAl Viro 	p->state = 0;
59906422964SAl Viro 	if (unlikely(root)) {
60006422964SAl Viro 		p->state = ND_ROOT_PRESET;
60106422964SAl Viro 		p->root = *root;
60206422964SAl Viro 	}
60306422964SAl Viro }
60406422964SAl Viro 
6059883d185SAl Viro static void restore_nameidata(void)
606894bc8c4SAl Viro {
6079883d185SAl Viro 	struct nameidata *now = current->nameidata, *old = now->saved;
608756daf26SNeilBrown 
609756daf26SNeilBrown 	current->nameidata = old;
610756daf26SNeilBrown 	if (old)
611756daf26SNeilBrown 		old->total_link_count = now->total_link_count;
612e1a63bbcSAl Viro 	if (now->stack != now->internal)
613756daf26SNeilBrown 		kfree(now->stack);
614894bc8c4SAl Viro }
615894bc8c4SAl Viro 
61660ef60c7SAl Viro static bool nd_alloc_stack(struct nameidata *nd)
617894bc8c4SAl Viro {
618bc40aee0SAl Viro 	struct saved *p;
619bc40aee0SAl Viro 
6206da2ec56SKees Cook 	p= kmalloc_array(MAXSYMLINKS, sizeof(struct saved),
62160ef60c7SAl Viro 			 nd->flags & LOOKUP_RCU ? GFP_ATOMIC : GFP_KERNEL);
622bc40aee0SAl Viro 	if (unlikely(!p))
62360ef60c7SAl Viro 		return false;
624894bc8c4SAl Viro 	memcpy(p, nd->internal, sizeof(nd->internal));
625894bc8c4SAl Viro 	nd->stack = p;
62660ef60c7SAl Viro 	return true;
627894bc8c4SAl Viro }
628894bc8c4SAl Viro 
629397d425dSEric W. Biederman /**
6306b03f7edSAl Viro  * path_connected - Verify that a dentry is below mnt.mnt_root
631397d425dSEric W. Biederman  *
632397d425dSEric W. Biederman  * Rename can sometimes move a file or directory outside of a bind
633397d425dSEric W. Biederman  * mount, path_connected allows those cases to be detected.
634397d425dSEric W. Biederman  */
6356b03f7edSAl Viro static bool path_connected(struct vfsmount *mnt, struct dentry *dentry)
636397d425dSEric W. Biederman {
63795dd7758SEric W. Biederman 	struct super_block *sb = mnt->mnt_sb;
638397d425dSEric W. Biederman 
639402dd2cfSChristoph Hellwig 	/* Bind mounts can have disconnected paths */
640402dd2cfSChristoph Hellwig 	if (mnt->mnt_root == sb->s_root)
641397d425dSEric W. Biederman 		return true;
642397d425dSEric W. Biederman 
6436b03f7edSAl Viro 	return is_subdir(dentry, mnt->mnt_root);
644397d425dSEric W. Biederman }
645397d425dSEric W. Biederman 
6467973387aSAl Viro static void drop_links(struct nameidata *nd)
6477973387aSAl Viro {
6487973387aSAl Viro 	int i = nd->depth;
6497973387aSAl Viro 	while (i--) {
6507973387aSAl Viro 		struct saved *last = nd->stack + i;
651fceef393SAl Viro 		do_delayed_call(&last->done);
652fceef393SAl Viro 		clear_delayed_call(&last->done);
6537973387aSAl Viro 	}
6547973387aSAl Viro }
6557973387aSAl Viro 
6567973387aSAl Viro static void terminate_walk(struct nameidata *nd)
6577973387aSAl Viro {
6587973387aSAl Viro 	drop_links(nd);
6597973387aSAl Viro 	if (!(nd->flags & LOOKUP_RCU)) {
6607973387aSAl Viro 		int i;
6617973387aSAl Viro 		path_put(&nd->path);
6627973387aSAl Viro 		for (i = 0; i < nd->depth; i++)
6637973387aSAl Viro 			path_put(&nd->stack[i].link);
664bcba1e7dSAl Viro 		if (nd->state & ND_ROOT_GRABBED) {
665102b8af2SAl Viro 			path_put(&nd->root);
666bcba1e7dSAl Viro 			nd->state &= ~ND_ROOT_GRABBED;
667102b8af2SAl Viro 		}
6687973387aSAl Viro 	} else {
6697973387aSAl Viro 		nd->flags &= ~LOOKUP_RCU;
6707973387aSAl Viro 		rcu_read_unlock();
6717973387aSAl Viro 	}
6727973387aSAl Viro 	nd->depth = 0;
6737d01ef75SAl Viro 	nd->path.mnt = NULL;
6747d01ef75SAl Viro 	nd->path.dentry = NULL;
6757973387aSAl Viro }
6767973387aSAl Viro 
6777973387aSAl Viro /* path_put is needed afterwards regardless of success or failure */
6782aa38470SAl Viro static bool __legitimize_path(struct path *path, unsigned seq, unsigned mseq)
6797973387aSAl Viro {
6802aa38470SAl Viro 	int res = __legitimize_mnt(path->mnt, mseq);
6817973387aSAl Viro 	if (unlikely(res)) {
6827973387aSAl Viro 		if (res > 0)
6837973387aSAl Viro 			path->mnt = NULL;
6847973387aSAl Viro 		path->dentry = NULL;
6857973387aSAl Viro 		return false;
6867973387aSAl Viro 	}
6877973387aSAl Viro 	if (unlikely(!lockref_get_not_dead(&path->dentry->d_lockref))) {
6887973387aSAl Viro 		path->dentry = NULL;
6897973387aSAl Viro 		return false;
6907973387aSAl Viro 	}
6917973387aSAl Viro 	return !read_seqcount_retry(&path->dentry->d_seq, seq);
6927973387aSAl Viro }
6937973387aSAl Viro 
6942aa38470SAl Viro static inline bool legitimize_path(struct nameidata *nd,
6952aa38470SAl Viro 			    struct path *path, unsigned seq)
6962aa38470SAl Viro {
6975bd73286SAl Viro 	return __legitimize_path(path, seq, nd->m_seq);
6982aa38470SAl Viro }
6992aa38470SAl Viro 
7007973387aSAl Viro static bool legitimize_links(struct nameidata *nd)
7017973387aSAl Viro {
7027973387aSAl Viro 	int i;
703eacd9aa8SAl Viro 	if (unlikely(nd->flags & LOOKUP_CACHED)) {
704eacd9aa8SAl Viro 		drop_links(nd);
705eacd9aa8SAl Viro 		nd->depth = 0;
706eacd9aa8SAl Viro 		return false;
707eacd9aa8SAl Viro 	}
7087973387aSAl Viro 	for (i = 0; i < nd->depth; i++) {
7097973387aSAl Viro 		struct saved *last = nd->stack + i;
7107973387aSAl Viro 		if (unlikely(!legitimize_path(nd, &last->link, last->seq))) {
7117973387aSAl Viro 			drop_links(nd);
7127973387aSAl Viro 			nd->depth = i + 1;
7137973387aSAl Viro 			return false;
7147973387aSAl Viro 		}
7157973387aSAl Viro 	}
7167973387aSAl Viro 	return true;
7177973387aSAl Viro }
7187973387aSAl Viro 
719ee594bffSAl Viro static bool legitimize_root(struct nameidata *nd)
720ee594bffSAl Viro {
721adb21d2bSAleksa Sarai 	/*
722adb21d2bSAleksa Sarai 	 * For scoped-lookups (where nd->root has been zeroed), we need to
723adb21d2bSAleksa Sarai 	 * restart the whole lookup from scratch -- because set_root() is wrong
724adb21d2bSAleksa Sarai 	 * for these lookups (nd->dfd is the root, not the filesystem root).
725adb21d2bSAleksa Sarai 	 */
726adb21d2bSAleksa Sarai 	if (!nd->root.mnt && (nd->flags & LOOKUP_IS_SCOPED))
727adb21d2bSAleksa Sarai 		return false;
728adb21d2bSAleksa Sarai 	/* Nothing to do if nd->root is zero or is managed by the VFS user. */
729bcba1e7dSAl Viro 	if (!nd->root.mnt || (nd->state & ND_ROOT_PRESET))
730ee594bffSAl Viro 		return true;
731bcba1e7dSAl Viro 	nd->state |= ND_ROOT_GRABBED;
732ee594bffSAl Viro 	return legitimize_path(nd, &nd->root, nd->root_seq);
733ee594bffSAl Viro }
734ee594bffSAl Viro 
73519660af7SAl Viro /*
73631e6b01fSNick Piggin  * Path walking has 2 modes, rcu-walk and ref-walk (see
73719660af7SAl Viro  * Documentation/filesystems/path-lookup.txt).  In situations when we can't
73819660af7SAl Viro  * continue in RCU mode, we attempt to drop out of rcu-walk mode and grab
73957e3715cSMike Marshall  * normal reference counts on dentries and vfsmounts to transition to ref-walk
74019660af7SAl Viro  * mode.  Refcounts are grabbed at the last known good point before rcu-walk
74119660af7SAl Viro  * got stuck, so ref-walk may continue from there. If this is not successful
74219660af7SAl Viro  * (eg. a seqcount has changed), then failure is returned and it's up to caller
74319660af7SAl Viro  * to restart the path walk from the beginning in ref-walk mode.
74431e6b01fSNick Piggin  */
74531e6b01fSNick Piggin 
74631e6b01fSNick Piggin /**
747e36cffedSJens Axboe  * try_to_unlazy - try to switch to ref-walk mode.
74819660af7SAl Viro  * @nd: nameidata pathwalk data
749e36cffedSJens Axboe  * Returns: true on success, false on failure
75031e6b01fSNick Piggin  *
751e36cffedSJens Axboe  * try_to_unlazy attempts to legitimize the current nd->path and nd->root
7524675ac39SAl Viro  * for ref-walk mode.
7534675ac39SAl Viro  * Must be called from rcu-walk context.
754e36cffedSJens Axboe  * Nothing should touch nameidata between try_to_unlazy() failure and
7557973387aSAl Viro  * terminate_walk().
75631e6b01fSNick Piggin  */
757e36cffedSJens Axboe static bool try_to_unlazy(struct nameidata *nd)
75831e6b01fSNick Piggin {
75931e6b01fSNick Piggin 	struct dentry *parent = nd->path.dentry;
76031e6b01fSNick Piggin 
76131e6b01fSNick Piggin 	BUG_ON(!(nd->flags & LOOKUP_RCU));
762e5c832d5SLinus Torvalds 
763e5c832d5SLinus Torvalds 	nd->flags &= ~LOOKUP_RCU;
7647973387aSAl Viro 	if (unlikely(!legitimize_links(nd)))
7654675ac39SAl Viro 		goto out1;
76684a2bd39SAl Viro 	if (unlikely(!legitimize_path(nd, &nd->path, nd->seq)))
76784a2bd39SAl Viro 		goto out;
768ee594bffSAl Viro 	if (unlikely(!legitimize_root(nd)))
7694675ac39SAl Viro 		goto out;
7704675ac39SAl Viro 	rcu_read_unlock();
7714675ac39SAl Viro 	BUG_ON(nd->inode != parent->d_inode);
772e36cffedSJens Axboe 	return true;
7734675ac39SAl Viro 
77484a2bd39SAl Viro out1:
7754675ac39SAl Viro 	nd->path.mnt = NULL;
7764675ac39SAl Viro 	nd->path.dentry = NULL;
7774675ac39SAl Viro out:
7784675ac39SAl Viro 	rcu_read_unlock();
779e36cffedSJens Axboe 	return false;
7804675ac39SAl Viro }
7814675ac39SAl Viro 
7824675ac39SAl Viro /**
783ae66db45SAl Viro  * try_to_unlazy_next - try to switch to ref-walk mode.
7844675ac39SAl Viro  * @nd: nameidata pathwalk data
785ae66db45SAl Viro  * @dentry: next dentry to step into
786ae66db45SAl Viro  * @seq: seq number to check @dentry against
787ae66db45SAl Viro  * Returns: true on success, false on failure
7884675ac39SAl Viro  *
789ae66db45SAl Viro  * Similar to to try_to_unlazy(), but here we have the next dentry already
790ae66db45SAl Viro  * picked by rcu-walk and want to legitimize that in addition to the current
791ae66db45SAl Viro  * nd->path and nd->root for ref-walk mode.  Must be called from rcu-walk context.
792ae66db45SAl Viro  * Nothing should touch nameidata between try_to_unlazy_next() failure and
7934675ac39SAl Viro  * terminate_walk().
7944675ac39SAl Viro  */
795ae66db45SAl Viro static bool try_to_unlazy_next(struct nameidata *nd, struct dentry *dentry, unsigned seq)
7964675ac39SAl Viro {
7974675ac39SAl Viro 	BUG_ON(!(nd->flags & LOOKUP_RCU));
7984675ac39SAl Viro 
7994675ac39SAl Viro 	nd->flags &= ~LOOKUP_RCU;
8004675ac39SAl Viro 	if (unlikely(!legitimize_links(nd)))
8014675ac39SAl Viro 		goto out2;
8027973387aSAl Viro 	if (unlikely(!legitimize_mnt(nd->path.mnt, nd->m_seq)))
8037973387aSAl Viro 		goto out2;
8044675ac39SAl Viro 	if (unlikely(!lockref_get_not_dead(&nd->path.dentry->d_lockref)))
8057973387aSAl Viro 		goto out1;
80648a066e7SAl Viro 
80715570086SLinus Torvalds 	/*
8084675ac39SAl Viro 	 * We need to move both the parent and the dentry from the RCU domain
8094675ac39SAl Viro 	 * to be properly refcounted. And the sequence number in the dentry
8104675ac39SAl Viro 	 * validates *both* dentry counters, since we checked the sequence
8114675ac39SAl Viro 	 * number of the parent after we got the child sequence number. So we
8124675ac39SAl Viro 	 * know the parent must still be valid if the child sequence number is
81315570086SLinus Torvalds 	 */
8144675ac39SAl Viro 	if (unlikely(!lockref_get_not_dead(&dentry->d_lockref)))
815e5c832d5SLinus Torvalds 		goto out;
81684a2bd39SAl Viro 	if (unlikely(read_seqcount_retry(&dentry->d_seq, seq)))
81784a2bd39SAl Viro 		goto out_dput;
818e5c832d5SLinus Torvalds 	/*
819e5c832d5SLinus Torvalds 	 * Sequence counts matched. Now make sure that the root is
820e5c832d5SLinus Torvalds 	 * still valid and get it if required.
821e5c832d5SLinus Torvalds 	 */
82284a2bd39SAl Viro 	if (unlikely(!legitimize_root(nd)))
82384a2bd39SAl Viro 		goto out_dput;
8248b61e74fSAl Viro 	rcu_read_unlock();
825ae66db45SAl Viro 	return true;
82619660af7SAl Viro 
8277973387aSAl Viro out2:
8287973387aSAl Viro 	nd->path.mnt = NULL;
8297973387aSAl Viro out1:
8307973387aSAl Viro 	nd->path.dentry = NULL;
831e5c832d5SLinus Torvalds out:
8328b61e74fSAl Viro 	rcu_read_unlock();
833ae66db45SAl Viro 	return false;
83484a2bd39SAl Viro out_dput:
83584a2bd39SAl Viro 	rcu_read_unlock();
83684a2bd39SAl Viro 	dput(dentry);
837ae66db45SAl Viro 	return false;
83831e6b01fSNick Piggin }
83931e6b01fSNick Piggin 
8404ce16ef3SAl Viro static inline int d_revalidate(struct dentry *dentry, unsigned int flags)
84134286d66SNick Piggin {
842a89f8337SAl Viro 	if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE))
8434ce16ef3SAl Viro 		return dentry->d_op->d_revalidate(dentry, flags);
844a89f8337SAl Viro 	else
845a89f8337SAl Viro 		return 1;
84634286d66SNick Piggin }
84734286d66SNick Piggin 
8489f1fafeeSAl Viro /**
8499f1fafeeSAl Viro  * complete_walk - successful completion of path walk
8509f1fafeeSAl Viro  * @nd:  pointer nameidata
85139159de2SJeff Layton  *
8529f1fafeeSAl Viro  * If we had been in RCU mode, drop out of it and legitimize nd->path.
8539f1fafeeSAl Viro  * Revalidate the final result, unless we'd already done that during
8549f1fafeeSAl Viro  * the path walk or the filesystem doesn't ask for it.  Return 0 on
8559f1fafeeSAl Viro  * success, -error on failure.  In case of failure caller does not
8569f1fafeeSAl Viro  * need to drop nd->path.
85739159de2SJeff Layton  */
8589f1fafeeSAl Viro static int complete_walk(struct nameidata *nd)
85939159de2SJeff Layton {
86016c2cd71SAl Viro 	struct dentry *dentry = nd->path.dentry;
86139159de2SJeff Layton 	int status;
86239159de2SJeff Layton 
8639f1fafeeSAl Viro 	if (nd->flags & LOOKUP_RCU) {
864adb21d2bSAleksa Sarai 		/*
865adb21d2bSAleksa Sarai 		 * We don't want to zero nd->root for scoped-lookups or
866adb21d2bSAleksa Sarai 		 * externally-managed nd->root.
867adb21d2bSAleksa Sarai 		 */
868bcba1e7dSAl Viro 		if (!(nd->state & ND_ROOT_PRESET))
869bcba1e7dSAl Viro 			if (!(nd->flags & LOOKUP_IS_SCOPED))
8709f1fafeeSAl Viro 				nd->root.mnt = NULL;
8716c6ec2b0SJens Axboe 		nd->flags &= ~LOOKUP_CACHED;
872e36cffedSJens Axboe 		if (!try_to_unlazy(nd))
87348a066e7SAl Viro 			return -ECHILD;
87448a066e7SAl Viro 	}
8759f1fafeeSAl Viro 
876adb21d2bSAleksa Sarai 	if (unlikely(nd->flags & LOOKUP_IS_SCOPED)) {
877adb21d2bSAleksa Sarai 		/*
878adb21d2bSAleksa Sarai 		 * While the guarantee of LOOKUP_IS_SCOPED is (roughly) "don't
879adb21d2bSAleksa Sarai 		 * ever step outside the root during lookup" and should already
880adb21d2bSAleksa Sarai 		 * be guaranteed by the rest of namei, we want to avoid a namei
881adb21d2bSAleksa Sarai 		 * BUG resulting in userspace being given a path that was not
882adb21d2bSAleksa Sarai 		 * scoped within the root at some point during the lookup.
883adb21d2bSAleksa Sarai 		 *
884adb21d2bSAleksa Sarai 		 * So, do a final sanity-check to make sure that in the
885adb21d2bSAleksa Sarai 		 * worst-case scenario (a complete bypass of LOOKUP_IS_SCOPED)
886adb21d2bSAleksa Sarai 		 * we won't silently return an fd completely outside of the
887adb21d2bSAleksa Sarai 		 * requested root to userspace.
888adb21d2bSAleksa Sarai 		 *
889adb21d2bSAleksa Sarai 		 * Userspace could move the path outside the root after this
890adb21d2bSAleksa Sarai 		 * check, but as discussed elsewhere this is not a concern (the
891adb21d2bSAleksa Sarai 		 * resolved file was inside the root at some point).
892adb21d2bSAleksa Sarai 		 */
893adb21d2bSAleksa Sarai 		if (!path_is_under(&nd->path, &nd->root))
894adb21d2bSAleksa Sarai 			return -EXDEV;
895adb21d2bSAleksa Sarai 	}
896adb21d2bSAleksa Sarai 
897bcba1e7dSAl Viro 	if (likely(!(nd->state & ND_JUMPED)))
89839159de2SJeff Layton 		return 0;
89939159de2SJeff Layton 
900ecf3d1f1SJeff Layton 	if (likely(!(dentry->d_flags & DCACHE_OP_WEAK_REVALIDATE)))
90116c2cd71SAl Viro 		return 0;
90216c2cd71SAl Viro 
903ecf3d1f1SJeff Layton 	status = dentry->d_op->d_weak_revalidate(dentry, nd->flags);
90439159de2SJeff Layton 	if (status > 0)
90539159de2SJeff Layton 		return 0;
90639159de2SJeff Layton 
90716c2cd71SAl Viro 	if (!status)
90839159de2SJeff Layton 		status = -ESTALE;
90916c2cd71SAl Viro 
91039159de2SJeff Layton 	return status;
91139159de2SJeff Layton }
91239159de2SJeff Layton 
913740a1678SAleksa Sarai static int set_root(struct nameidata *nd)
9142a737871SAl Viro {
91531e6b01fSNick Piggin 	struct fs_struct *fs = current->fs;
9169e6697e2SAl Viro 
917adb21d2bSAleksa Sarai 	/*
918adb21d2bSAleksa Sarai 	 * Jumping to the real root in a scoped-lookup is a BUG in namei, but we
919adb21d2bSAleksa Sarai 	 * still have to ensure it doesn't happen because it will cause a breakout
920adb21d2bSAleksa Sarai 	 * from the dirfd.
921adb21d2bSAleksa Sarai 	 */
922adb21d2bSAleksa Sarai 	if (WARN_ON(nd->flags & LOOKUP_IS_SCOPED))
923adb21d2bSAleksa Sarai 		return -ENOTRECOVERABLE;
924adb21d2bSAleksa Sarai 
9259e6697e2SAl Viro 	if (nd->flags & LOOKUP_RCU) {
9268f47a016SAl Viro 		unsigned seq;
927c28cc364SNick Piggin 
928c28cc364SNick Piggin 		do {
929c28cc364SNick Piggin 			seq = read_seqcount_begin(&fs->seq);
93031e6b01fSNick Piggin 			nd->root = fs->root;
9318f47a016SAl Viro 			nd->root_seq = __read_seqcount_begin(&nd->root.dentry->d_seq);
932c28cc364SNick Piggin 		} while (read_seqcount_retry(&fs->seq, seq));
9339e6697e2SAl Viro 	} else {
9349e6697e2SAl Viro 		get_fs_root(fs, &nd->root);
935bcba1e7dSAl Viro 		nd->state |= ND_ROOT_GRABBED;
9369e6697e2SAl Viro 	}
937740a1678SAleksa Sarai 	return 0;
93831e6b01fSNick Piggin }
93931e6b01fSNick Piggin 
940248fb5b9SAl Viro static int nd_jump_root(struct nameidata *nd)
941248fb5b9SAl Viro {
942adb21d2bSAleksa Sarai 	if (unlikely(nd->flags & LOOKUP_BENEATH))
943adb21d2bSAleksa Sarai 		return -EXDEV;
94472ba2929SAleksa Sarai 	if (unlikely(nd->flags & LOOKUP_NO_XDEV)) {
94572ba2929SAleksa Sarai 		/* Absolute path arguments to path_init() are allowed. */
94672ba2929SAleksa Sarai 		if (nd->path.mnt != NULL && nd->path.mnt != nd->root.mnt)
94772ba2929SAleksa Sarai 			return -EXDEV;
94872ba2929SAleksa Sarai 	}
949740a1678SAleksa Sarai 	if (!nd->root.mnt) {
950740a1678SAleksa Sarai 		int error = set_root(nd);
951740a1678SAleksa Sarai 		if (error)
952740a1678SAleksa Sarai 			return error;
953740a1678SAleksa Sarai 	}
954248fb5b9SAl Viro 	if (nd->flags & LOOKUP_RCU) {
955248fb5b9SAl Viro 		struct dentry *d;
956248fb5b9SAl Viro 		nd->path = nd->root;
957248fb5b9SAl Viro 		d = nd->path.dentry;
958248fb5b9SAl Viro 		nd->inode = d->d_inode;
959248fb5b9SAl Viro 		nd->seq = nd->root_seq;
960248fb5b9SAl Viro 		if (unlikely(read_seqcount_retry(&d->d_seq, nd->seq)))
961248fb5b9SAl Viro 			return -ECHILD;
962248fb5b9SAl Viro 	} else {
963248fb5b9SAl Viro 		path_put(&nd->path);
964248fb5b9SAl Viro 		nd->path = nd->root;
965248fb5b9SAl Viro 		path_get(&nd->path);
966248fb5b9SAl Viro 		nd->inode = nd->path.dentry->d_inode;
967248fb5b9SAl Viro 	}
968bcba1e7dSAl Viro 	nd->state |= ND_JUMPED;
969248fb5b9SAl Viro 	return 0;
970248fb5b9SAl Viro }
971248fb5b9SAl Viro 
972b5fb63c1SChristoph Hellwig /*
9736b255391SAl Viro  * Helper to directly jump to a known parsed path from ->get_link,
974b5fb63c1SChristoph Hellwig  * caller must have taken a reference to path beforehand.
975b5fb63c1SChristoph Hellwig  */
9761bc82070SAleksa Sarai int nd_jump_link(struct path *path)
977b5fb63c1SChristoph Hellwig {
9784b99d499SAleksa Sarai 	int error = -ELOOP;
9796e77137bSAl Viro 	struct nameidata *nd = current->nameidata;
980b5fb63c1SChristoph Hellwig 
9814b99d499SAleksa Sarai 	if (unlikely(nd->flags & LOOKUP_NO_MAGICLINKS))
9824b99d499SAleksa Sarai 		goto err;
9834b99d499SAleksa Sarai 
98472ba2929SAleksa Sarai 	error = -EXDEV;
98572ba2929SAleksa Sarai 	if (unlikely(nd->flags & LOOKUP_NO_XDEV)) {
98672ba2929SAleksa Sarai 		if (nd->path.mnt != path->mnt)
98772ba2929SAleksa Sarai 			goto err;
98872ba2929SAleksa Sarai 	}
989adb21d2bSAleksa Sarai 	/* Not currently safe for scoped-lookups. */
990adb21d2bSAleksa Sarai 	if (unlikely(nd->flags & LOOKUP_IS_SCOPED))
991adb21d2bSAleksa Sarai 		goto err;
99272ba2929SAleksa Sarai 
9934b99d499SAleksa Sarai 	path_put(&nd->path);
994b5fb63c1SChristoph Hellwig 	nd->path = *path;
995b5fb63c1SChristoph Hellwig 	nd->inode = nd->path.dentry->d_inode;
996bcba1e7dSAl Viro 	nd->state |= ND_JUMPED;
9971bc82070SAleksa Sarai 	return 0;
9984b99d499SAleksa Sarai 
9994b99d499SAleksa Sarai err:
10004b99d499SAleksa Sarai 	path_put(path);
10014b99d499SAleksa Sarai 	return error;
1002b5fb63c1SChristoph Hellwig }
1003b5fb63c1SChristoph Hellwig 
1004b9ff4429SAl Viro static inline void put_link(struct nameidata *nd)
1005574197e0SAl Viro {
100621c3003dSAl Viro 	struct saved *last = nd->stack + --nd->depth;
1007fceef393SAl Viro 	do_delayed_call(&last->done);
10086548fae2SAl Viro 	if (!(nd->flags & LOOKUP_RCU))
1009b9ff4429SAl Viro 		path_put(&last->link);
1010574197e0SAl Viro }
1011574197e0SAl Viro 
1012561ec64aSLinus Torvalds int sysctl_protected_symlinks __read_mostly = 0;
1013561ec64aSLinus Torvalds int sysctl_protected_hardlinks __read_mostly = 0;
101430aba665SSalvatore Mesoraca int sysctl_protected_fifos __read_mostly;
101530aba665SSalvatore Mesoraca int sysctl_protected_regular __read_mostly;
1016800179c9SKees Cook 
1017800179c9SKees Cook /**
1018800179c9SKees Cook  * may_follow_link - Check symlink following for unsafe situations
101955852635SRandy Dunlap  * @nd: nameidata pathwalk data
1020800179c9SKees Cook  *
1021800179c9SKees Cook  * In the case of the sysctl_protected_symlinks sysctl being enabled,
1022800179c9SKees Cook  * CAP_DAC_OVERRIDE needs to be specifically ignored if the symlink is
1023800179c9SKees Cook  * in a sticky world-writable directory. This is to protect privileged
1024800179c9SKees Cook  * processes from failing races against path names that may change out
1025800179c9SKees Cook  * from under them by way of other users creating malicious symlinks.
1026800179c9SKees Cook  * It will permit symlinks to be followed only when outside a sticky
1027800179c9SKees Cook  * world-writable directory, or when the uid of the symlink and follower
1028800179c9SKees Cook  * match, or when the directory owner matches the symlink's owner.
1029800179c9SKees Cook  *
1030800179c9SKees Cook  * Returns 0 if following the symlink is allowed, -ve on error.
1031800179c9SKees Cook  */
1032ad6cc4c3SAl Viro static inline int may_follow_link(struct nameidata *nd, const struct inode *inode)
1033800179c9SKees Cook {
1034ba73d987SChristian Brauner 	struct user_namespace *mnt_userns;
1035ba73d987SChristian Brauner 	kuid_t i_uid;
1036ba73d987SChristian Brauner 
1037800179c9SKees Cook 	if (!sysctl_protected_symlinks)
1038800179c9SKees Cook 		return 0;
1039800179c9SKees Cook 
1040ba73d987SChristian Brauner 	mnt_userns = mnt_user_ns(nd->path.mnt);
1041ba73d987SChristian Brauner 	i_uid = i_uid_into_mnt(mnt_userns, inode);
1042800179c9SKees Cook 	/* Allowed if owner and follower match. */
1043ba73d987SChristian Brauner 	if (uid_eq(current_cred()->fsuid, i_uid))
1044800179c9SKees Cook 		return 0;
1045800179c9SKees Cook 
1046800179c9SKees Cook 	/* Allowed if parent directory not sticky and world-writable. */
10470f705953SAl Viro 	if ((nd->dir_mode & (S_ISVTX|S_IWOTH)) != (S_ISVTX|S_IWOTH))
1048800179c9SKees Cook 		return 0;
1049800179c9SKees Cook 
1050800179c9SKees Cook 	/* Allowed if parent directory and link owner match. */
1051ba73d987SChristian Brauner 	if (uid_valid(nd->dir_uid) && uid_eq(nd->dir_uid, i_uid))
1052800179c9SKees Cook 		return 0;
1053800179c9SKees Cook 
105431956502SAl Viro 	if (nd->flags & LOOKUP_RCU)
105531956502SAl Viro 		return -ECHILD;
105631956502SAl Viro 
1057ea841bafSRichard Guy Briggs 	audit_inode(nd->name, nd->stack[0].link.dentry, 0);
1058245d7369SKees Cook 	audit_log_path_denied(AUDIT_ANOM_LINK, "follow_link");
1059800179c9SKees Cook 	return -EACCES;
1060800179c9SKees Cook }
1061800179c9SKees Cook 
1062800179c9SKees Cook /**
1063800179c9SKees Cook  * safe_hardlink_source - Check for safe hardlink conditions
1064ba73d987SChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
1065800179c9SKees Cook  * @inode: the source inode to hardlink from
1066800179c9SKees Cook  *
1067800179c9SKees Cook  * Return false if at least one of the following conditions:
1068800179c9SKees Cook  *    - inode is not a regular file
1069800179c9SKees Cook  *    - inode is setuid
1070800179c9SKees Cook  *    - inode is setgid and group-exec
1071800179c9SKees Cook  *    - access failure for read and write
1072800179c9SKees Cook  *
1073800179c9SKees Cook  * Otherwise returns true.
1074800179c9SKees Cook  */
1075ba73d987SChristian Brauner static bool safe_hardlink_source(struct user_namespace *mnt_userns,
1076ba73d987SChristian Brauner 				 struct inode *inode)
1077800179c9SKees Cook {
1078800179c9SKees Cook 	umode_t mode = inode->i_mode;
1079800179c9SKees Cook 
1080800179c9SKees Cook 	/* Special files should not get pinned to the filesystem. */
1081800179c9SKees Cook 	if (!S_ISREG(mode))
1082800179c9SKees Cook 		return false;
1083800179c9SKees Cook 
1084800179c9SKees Cook 	/* Setuid files should not get pinned to the filesystem. */
1085800179c9SKees Cook 	if (mode & S_ISUID)
1086800179c9SKees Cook 		return false;
1087800179c9SKees Cook 
1088800179c9SKees Cook 	/* Executable setgid files should not get pinned to the filesystem. */
1089800179c9SKees Cook 	if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP))
1090800179c9SKees Cook 		return false;
1091800179c9SKees Cook 
1092800179c9SKees Cook 	/* Hardlinking to unreadable or unwritable sources is dangerous. */
1093ba73d987SChristian Brauner 	if (inode_permission(mnt_userns, inode, MAY_READ | MAY_WRITE))
1094800179c9SKees Cook 		return false;
1095800179c9SKees Cook 
1096800179c9SKees Cook 	return true;
1097800179c9SKees Cook }
1098800179c9SKees Cook 
1099800179c9SKees Cook /**
1100800179c9SKees Cook  * may_linkat - Check permissions for creating a hardlink
1101ba73d987SChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
1102800179c9SKees Cook  * @link: the source to hardlink from
1103800179c9SKees Cook  *
1104800179c9SKees Cook  * Block hardlink when all of:
1105800179c9SKees Cook  *  - sysctl_protected_hardlinks enabled
1106800179c9SKees Cook  *  - fsuid does not match inode
1107800179c9SKees Cook  *  - hardlink source is unsafe (see safe_hardlink_source() above)
1108f2ca3796SDirk Steinmetz  *  - not CAP_FOWNER in a namespace with the inode owner uid mapped
1109800179c9SKees Cook  *
1110ba73d987SChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
1111ba73d987SChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
1112ba73d987SChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
1113ba73d987SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
1114ba73d987SChristian Brauner  * raw inode simply passs init_user_ns.
1115ba73d987SChristian Brauner  *
1116800179c9SKees Cook  * Returns 0 if successful, -ve on error.
1117800179c9SKees Cook  */
1118ba73d987SChristian Brauner int may_linkat(struct user_namespace *mnt_userns, struct path *link)
1119800179c9SKees Cook {
1120593d1ce8SEric W. Biederman 	struct inode *inode = link->dentry->d_inode;
1121593d1ce8SEric W. Biederman 
1122593d1ce8SEric W. Biederman 	/* Inode writeback is not safe when the uid or gid are invalid. */
1123ba73d987SChristian Brauner 	if (!uid_valid(i_uid_into_mnt(mnt_userns, inode)) ||
1124ba73d987SChristian Brauner 	    !gid_valid(i_gid_into_mnt(mnt_userns, inode)))
1125593d1ce8SEric W. Biederman 		return -EOVERFLOW;
1126800179c9SKees Cook 
1127800179c9SKees Cook 	if (!sysctl_protected_hardlinks)
1128800179c9SKees Cook 		return 0;
1129800179c9SKees Cook 
1130800179c9SKees Cook 	/* Source inode owner (or CAP_FOWNER) can hardlink all they like,
1131800179c9SKees Cook 	 * otherwise, it must be a safe source.
1132800179c9SKees Cook 	 */
1133ba73d987SChristian Brauner 	if (safe_hardlink_source(mnt_userns, inode) ||
1134ba73d987SChristian Brauner 	    inode_owner_or_capable(mnt_userns, inode))
1135800179c9SKees Cook 		return 0;
1136800179c9SKees Cook 
1137245d7369SKees Cook 	audit_log_path_denied(AUDIT_ANOM_LINK, "linkat");
1138800179c9SKees Cook 	return -EPERM;
1139800179c9SKees Cook }
1140800179c9SKees Cook 
114130aba665SSalvatore Mesoraca /**
114230aba665SSalvatore Mesoraca  * may_create_in_sticky - Check whether an O_CREAT open in a sticky directory
114330aba665SSalvatore Mesoraca  *			  should be allowed, or not, on files that already
114430aba665SSalvatore Mesoraca  *			  exist.
1145ba73d987SChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
11462111c3c0SRandy Dunlap  * @nd: nameidata pathwalk data
114730aba665SSalvatore Mesoraca  * @inode: the inode of the file to open
114830aba665SSalvatore Mesoraca  *
114930aba665SSalvatore Mesoraca  * Block an O_CREAT open of a FIFO (or a regular file) when:
115030aba665SSalvatore Mesoraca  *   - sysctl_protected_fifos (or sysctl_protected_regular) is enabled
115130aba665SSalvatore Mesoraca  *   - the file already exists
115230aba665SSalvatore Mesoraca  *   - we are in a sticky directory
115330aba665SSalvatore Mesoraca  *   - we don't own the file
115430aba665SSalvatore Mesoraca  *   - the owner of the directory doesn't own the file
115530aba665SSalvatore Mesoraca  *   - the directory is world writable
115630aba665SSalvatore Mesoraca  * If the sysctl_protected_fifos (or sysctl_protected_regular) is set to 2
115730aba665SSalvatore Mesoraca  * the directory doesn't have to be world writable: being group writable will
115830aba665SSalvatore Mesoraca  * be enough.
115930aba665SSalvatore Mesoraca  *
1160ba73d987SChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
1161ba73d987SChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
1162ba73d987SChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
1163ba73d987SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
1164ba73d987SChristian Brauner  * raw inode simply passs init_user_ns.
1165ba73d987SChristian Brauner  *
116630aba665SSalvatore Mesoraca  * Returns 0 if the open is allowed, -ve on error.
116730aba665SSalvatore Mesoraca  */
1168ba73d987SChristian Brauner static int may_create_in_sticky(struct user_namespace *mnt_userns,
1169ba73d987SChristian Brauner 				struct nameidata *nd, struct inode *const inode)
117030aba665SSalvatore Mesoraca {
1171ba73d987SChristian Brauner 	umode_t dir_mode = nd->dir_mode;
1172ba73d987SChristian Brauner 	kuid_t dir_uid = nd->dir_uid;
1173ba73d987SChristian Brauner 
117430aba665SSalvatore Mesoraca 	if ((!sysctl_protected_fifos && S_ISFIFO(inode->i_mode)) ||
117530aba665SSalvatore Mesoraca 	    (!sysctl_protected_regular && S_ISREG(inode->i_mode)) ||
1176d0cb5018SAl Viro 	    likely(!(dir_mode & S_ISVTX)) ||
1177ba73d987SChristian Brauner 	    uid_eq(i_uid_into_mnt(mnt_userns, inode), dir_uid) ||
1178ba73d987SChristian Brauner 	    uid_eq(current_fsuid(), i_uid_into_mnt(mnt_userns, inode)))
117930aba665SSalvatore Mesoraca 		return 0;
118030aba665SSalvatore Mesoraca 
1181d0cb5018SAl Viro 	if (likely(dir_mode & 0002) ||
1182d0cb5018SAl Viro 	    (dir_mode & 0020 &&
118330aba665SSalvatore Mesoraca 	     ((sysctl_protected_fifos >= 2 && S_ISFIFO(inode->i_mode)) ||
118430aba665SSalvatore Mesoraca 	      (sysctl_protected_regular >= 2 && S_ISREG(inode->i_mode))))) {
1185245d7369SKees Cook 		const char *operation = S_ISFIFO(inode->i_mode) ?
1186245d7369SKees Cook 					"sticky_create_fifo" :
1187245d7369SKees Cook 					"sticky_create_regular";
1188245d7369SKees Cook 		audit_log_path_denied(AUDIT_ANOM_CREAT, operation);
118930aba665SSalvatore Mesoraca 		return -EACCES;
119030aba665SSalvatore Mesoraca 	}
119130aba665SSalvatore Mesoraca 	return 0;
119230aba665SSalvatore Mesoraca }
119330aba665SSalvatore Mesoraca 
1194f015f126SDavid Howells /*
1195f015f126SDavid Howells  * follow_up - Find the mountpoint of path's vfsmount
1196f015f126SDavid Howells  *
1197f015f126SDavid Howells  * Given a path, find the mountpoint of its source file system.
1198f015f126SDavid Howells  * Replace @path with the path of the mountpoint in the parent mount.
1199f015f126SDavid Howells  * Up is towards /.
1200f015f126SDavid Howells  *
1201f015f126SDavid Howells  * Return 1 if we went up a level and 0 if we were already at the
1202f015f126SDavid Howells  * root.
1203f015f126SDavid Howells  */
1204bab77ebfSAl Viro int follow_up(struct path *path)
12051da177e4SLinus Torvalds {
12060714a533SAl Viro 	struct mount *mnt = real_mount(path->mnt);
12070714a533SAl Viro 	struct mount *parent;
12081da177e4SLinus Torvalds 	struct dentry *mountpoint;
120999b7db7bSNick Piggin 
121048a066e7SAl Viro 	read_seqlock_excl(&mount_lock);
12110714a533SAl Viro 	parent = mnt->mnt_parent;
12123c0a6163SAl Viro 	if (parent == mnt) {
121348a066e7SAl Viro 		read_sequnlock_excl(&mount_lock);
12141da177e4SLinus Torvalds 		return 0;
12151da177e4SLinus Torvalds 	}
12160714a533SAl Viro 	mntget(&parent->mnt);
1217a73324daSAl Viro 	mountpoint = dget(mnt->mnt_mountpoint);
121848a066e7SAl Viro 	read_sequnlock_excl(&mount_lock);
1219bab77ebfSAl Viro 	dput(path->dentry);
1220bab77ebfSAl Viro 	path->dentry = mountpoint;
1221bab77ebfSAl Viro 	mntput(path->mnt);
12220714a533SAl Viro 	path->mnt = &parent->mnt;
12231da177e4SLinus Torvalds 	return 1;
12241da177e4SLinus Torvalds }
12254d359507SAl Viro EXPORT_SYMBOL(follow_up);
12261da177e4SLinus Torvalds 
12277ef482faSAl Viro static bool choose_mountpoint_rcu(struct mount *m, const struct path *root,
12287ef482faSAl Viro 				  struct path *path, unsigned *seqp)
12297ef482faSAl Viro {
12307ef482faSAl Viro 	while (mnt_has_parent(m)) {
12317ef482faSAl Viro 		struct dentry *mountpoint = m->mnt_mountpoint;
12327ef482faSAl Viro 
12337ef482faSAl Viro 		m = m->mnt_parent;
12347ef482faSAl Viro 		if (unlikely(root->dentry == mountpoint &&
12357ef482faSAl Viro 			     root->mnt == &m->mnt))
12367ef482faSAl Viro 			break;
12377ef482faSAl Viro 		if (mountpoint != m->mnt.mnt_root) {
12387ef482faSAl Viro 			path->mnt = &m->mnt;
12397ef482faSAl Viro 			path->dentry = mountpoint;
12407ef482faSAl Viro 			*seqp = read_seqcount_begin(&mountpoint->d_seq);
12417ef482faSAl Viro 			return true;
12427ef482faSAl Viro 		}
12437ef482faSAl Viro 	}
12447ef482faSAl Viro 	return false;
12457ef482faSAl Viro }
12467ef482faSAl Viro 
12472aa38470SAl Viro static bool choose_mountpoint(struct mount *m, const struct path *root,
12482aa38470SAl Viro 			      struct path *path)
12492aa38470SAl Viro {
12502aa38470SAl Viro 	bool found;
12512aa38470SAl Viro 
12522aa38470SAl Viro 	rcu_read_lock();
12532aa38470SAl Viro 	while (1) {
12542aa38470SAl Viro 		unsigned seq, mseq = read_seqbegin(&mount_lock);
12552aa38470SAl Viro 
12562aa38470SAl Viro 		found = choose_mountpoint_rcu(m, root, path, &seq);
12572aa38470SAl Viro 		if (unlikely(!found)) {
12582aa38470SAl Viro 			if (!read_seqretry(&mount_lock, mseq))
12592aa38470SAl Viro 				break;
12602aa38470SAl Viro 		} else {
12612aa38470SAl Viro 			if (likely(__legitimize_path(path, seq, mseq)))
12622aa38470SAl Viro 				break;
12632aa38470SAl Viro 			rcu_read_unlock();
12642aa38470SAl Viro 			path_put(path);
12652aa38470SAl Viro 			rcu_read_lock();
12662aa38470SAl Viro 		}
12672aa38470SAl Viro 	}
12682aa38470SAl Viro 	rcu_read_unlock();
12692aa38470SAl Viro 	return found;
12702aa38470SAl Viro }
12712aa38470SAl Viro 
1272b5c84bf6SNick Piggin /*
12739875cf80SDavid Howells  * Perform an automount
12749875cf80SDavid Howells  * - return -EISDIR to tell follow_managed() to stop and return the path we
12759875cf80SDavid Howells  *   were called with.
12761da177e4SLinus Torvalds  */
12771c9f5e06SAl Viro static int follow_automount(struct path *path, int *count, unsigned lookup_flags)
127831e6b01fSNick Piggin {
127925e195aaSAl Viro 	struct dentry *dentry = path->dentry;
12809875cf80SDavid Howells 
12810ec26fd0SMiklos Szeredi 	/* We don't want to mount if someone's just doing a stat -
12820ec26fd0SMiklos Szeredi 	 * unless they're stat'ing a directory and appended a '/' to
12830ec26fd0SMiklos Szeredi 	 * the name.
12840ec26fd0SMiklos Szeredi 	 *
12850ec26fd0SMiklos Szeredi 	 * We do, however, want to mount if someone wants to open or
12865a30d8a2SDavid Howells 	 * create a file of any type under the mountpoint, wants to
12870ec26fd0SMiklos Szeredi 	 * traverse through the mountpoint or wants to open the
12880ec26fd0SMiklos Szeredi 	 * mounted directory.  Also, autofs may mark negative dentries
12890ec26fd0SMiklos Szeredi 	 * as being automount points.  These will need the attentions
12900ec26fd0SMiklos Szeredi 	 * of the daemon to instantiate them before they can be used.
12915a30d8a2SDavid Howells 	 */
12921c9f5e06SAl Viro 	if (!(lookup_flags & (LOOKUP_PARENT | LOOKUP_DIRECTORY |
12935d38f049SIan Kent 			   LOOKUP_OPEN | LOOKUP_CREATE | LOOKUP_AUTOMOUNT)) &&
129425e195aaSAl Viro 	    dentry->d_inode)
12959875cf80SDavid Howells 		return -EISDIR;
12960ec26fd0SMiklos Szeredi 
12971c9f5e06SAl Viro 	if (count && (*count)++ >= MAXSYMLINKS)
12989875cf80SDavid Howells 		return -ELOOP;
12999875cf80SDavid Howells 
130025e195aaSAl Viro 	return finish_automount(dentry->d_op->d_automount(path), path);
1301ea5b778aSDavid Howells }
13029875cf80SDavid Howells 
13039875cf80SDavid Howells /*
13049deed3ebSAl Viro  * mount traversal - out-of-line part.  One note on ->d_flags accesses -
13059deed3ebSAl Viro  * dentries are pinned but not locked here, so negative dentry can go
13069deed3ebSAl Viro  * positive right under us.  Use of smp_load_acquire() provides a barrier
13079deed3ebSAl Viro  * sufficient for ->d_inode and ->d_flags consistency.
13089875cf80SDavid Howells  */
13099deed3ebSAl Viro static int __traverse_mounts(struct path *path, unsigned flags, bool *jumped,
13109deed3ebSAl Viro 			     int *count, unsigned lookup_flags)
13119875cf80SDavid Howells {
13129deed3ebSAl Viro 	struct vfsmount *mnt = path->mnt;
13139875cf80SDavid Howells 	bool need_mntput = false;
13148aef1884SAl Viro 	int ret = 0;
13159875cf80SDavid Howells 
13169deed3ebSAl Viro 	while (flags & DCACHE_MANAGED_DENTRY) {
1317cc53ce53SDavid Howells 		/* Allow the filesystem to manage the transit without i_mutex
1318cc53ce53SDavid Howells 		 * being held. */
1319d41efb52SAl Viro 		if (flags & DCACHE_MANAGE_TRANSIT) {
1320fb5f51c7SIan Kent 			ret = path->dentry->d_op->d_manage(path, false);
1321508c8772SAl Viro 			flags = smp_load_acquire(&path->dentry->d_flags);
1322cc53ce53SDavid Howells 			if (ret < 0)
13238aef1884SAl Viro 				break;
1324cc53ce53SDavid Howells 		}
1325cc53ce53SDavid Howells 
13269deed3ebSAl Viro 		if (flags & DCACHE_MOUNTED) {	// something's mounted on it..
13279875cf80SDavid Howells 			struct vfsmount *mounted = lookup_mnt(path);
13289deed3ebSAl Viro 			if (mounted) {		// ... in our namespace
13299875cf80SDavid Howells 				dput(path->dentry);
13309875cf80SDavid Howells 				if (need_mntput)
1331463ffb2eSAl Viro 					mntput(path->mnt);
1332463ffb2eSAl Viro 				path->mnt = mounted;
1333463ffb2eSAl Viro 				path->dentry = dget(mounted->mnt_root);
13349deed3ebSAl Viro 				// here we know it's positive
13359deed3ebSAl Viro 				flags = path->dentry->d_flags;
13369875cf80SDavid Howells 				need_mntput = true;
13379875cf80SDavid Howells 				continue;
1338463ffb2eSAl Viro 			}
13391da177e4SLinus Torvalds 		}
13409875cf80SDavid Howells 
13419deed3ebSAl Viro 		if (!(flags & DCACHE_NEED_AUTOMOUNT))
13429deed3ebSAl Viro 			break;
13439deed3ebSAl Viro 
13449deed3ebSAl Viro 		// uncovered automount point
13459deed3ebSAl Viro 		ret = follow_automount(path, count, lookup_flags);
13469deed3ebSAl Viro 		flags = smp_load_acquire(&path->dentry->d_flags);
13479875cf80SDavid Howells 		if (ret < 0)
13488aef1884SAl Viro 			break;
13499875cf80SDavid Howells 	}
13509875cf80SDavid Howells 
13519deed3ebSAl Viro 	if (ret == -EISDIR)
13529deed3ebSAl Viro 		ret = 0;
13539deed3ebSAl Viro 	// possible if you race with several mount --move
13549deed3ebSAl Viro 	if (need_mntput && path->mnt == mnt)
13558aef1884SAl Viro 		mntput(path->mnt);
13569deed3ebSAl Viro 	if (!ret && unlikely(d_flags_negative(flags)))
1357d41efb52SAl Viro 		ret = -ENOENT;
13589deed3ebSAl Viro 	*jumped = need_mntput;
13598402752eSAl Viro 	return ret;
13601da177e4SLinus Torvalds }
13611da177e4SLinus Torvalds 
13629deed3ebSAl Viro static inline int traverse_mounts(struct path *path, bool *jumped,
13639deed3ebSAl Viro 				  int *count, unsigned lookup_flags)
13649deed3ebSAl Viro {
13659deed3ebSAl Viro 	unsigned flags = smp_load_acquire(&path->dentry->d_flags);
13669deed3ebSAl Viro 
13679deed3ebSAl Viro 	/* fastpath */
13689deed3ebSAl Viro 	if (likely(!(flags & DCACHE_MANAGED_DENTRY))) {
13699deed3ebSAl Viro 		*jumped = false;
13709deed3ebSAl Viro 		if (unlikely(d_flags_negative(flags)))
13719deed3ebSAl Viro 			return -ENOENT;
13729deed3ebSAl Viro 		return 0;
13739deed3ebSAl Viro 	}
13749deed3ebSAl Viro 	return __traverse_mounts(path, flags, jumped, count, lookup_flags);
13759deed3ebSAl Viro }
13769deed3ebSAl Viro 
1377cc53ce53SDavid Howells int follow_down_one(struct path *path)
13781da177e4SLinus Torvalds {
13791da177e4SLinus Torvalds 	struct vfsmount *mounted;
13801da177e4SLinus Torvalds 
13811c755af4SAl Viro 	mounted = lookup_mnt(path);
13821da177e4SLinus Torvalds 	if (mounted) {
13839393bd07SAl Viro 		dput(path->dentry);
13849393bd07SAl Viro 		mntput(path->mnt);
13859393bd07SAl Viro 		path->mnt = mounted;
13869393bd07SAl Viro 		path->dentry = dget(mounted->mnt_root);
13871da177e4SLinus Torvalds 		return 1;
13881da177e4SLinus Torvalds 	}
13891da177e4SLinus Torvalds 	return 0;
13901da177e4SLinus Torvalds }
13914d359507SAl Viro EXPORT_SYMBOL(follow_down_one);
13921da177e4SLinus Torvalds 
13939875cf80SDavid Howells /*
13949deed3ebSAl Viro  * Follow down to the covering mount currently visible to userspace.  At each
13959deed3ebSAl Viro  * point, the filesystem owning that dentry may be queried as to whether the
13969deed3ebSAl Viro  * caller is permitted to proceed or not.
13979deed3ebSAl Viro  */
13989deed3ebSAl Viro int follow_down(struct path *path)
13999deed3ebSAl Viro {
14009deed3ebSAl Viro 	struct vfsmount *mnt = path->mnt;
14019deed3ebSAl Viro 	bool jumped;
14029deed3ebSAl Viro 	int ret = traverse_mounts(path, &jumped, NULL, 0);
14039deed3ebSAl Viro 
14049deed3ebSAl Viro 	if (path->mnt != mnt)
14059deed3ebSAl Viro 		mntput(mnt);
14069deed3ebSAl Viro 	return ret;
14079deed3ebSAl Viro }
14089deed3ebSAl Viro EXPORT_SYMBOL(follow_down);
14099deed3ebSAl Viro 
14109deed3ebSAl Viro /*
1411287548e4SAl Viro  * Try to skip to top of mountpoint pile in rcuwalk mode.  Fail if
1412287548e4SAl Viro  * we meet a managed dentry that would need blocking.
14139875cf80SDavid Howells  */
14149875cf80SDavid Howells static bool __follow_mount_rcu(struct nameidata *nd, struct path *path,
1415254cf582SAl Viro 			       struct inode **inode, unsigned *seqp)
14169875cf80SDavid Howells {
1417ea936aebSAl Viro 	struct dentry *dentry = path->dentry;
1418ea936aebSAl Viro 	unsigned int flags = dentry->d_flags;
1419ea936aebSAl Viro 
1420ea936aebSAl Viro 	if (likely(!(flags & DCACHE_MANAGED_DENTRY)))
1421ea936aebSAl Viro 		return true;
1422ea936aebSAl Viro 
1423ea936aebSAl Viro 	if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1424ea936aebSAl Viro 		return false;
1425ea936aebSAl Viro 
142662a7375eSIan Kent 	for (;;) {
142762a7375eSIan Kent 		/*
142862a7375eSIan Kent 		 * Don't forget we might have a non-mountpoint managed dentry
142962a7375eSIan Kent 		 * that wants to block transit.
143062a7375eSIan Kent 		 */
1431ea936aebSAl Viro 		if (unlikely(flags & DCACHE_MANAGE_TRANSIT)) {
1432ea936aebSAl Viro 			int res = dentry->d_op->d_manage(path, true);
1433ea936aebSAl Viro 			if (res)
1434ea936aebSAl Viro 				return res == -EISDIR;
1435ea936aebSAl Viro 			flags = dentry->d_flags;
1436b8faf035SNeilBrown 		}
143762a7375eSIan Kent 
1438ea936aebSAl Viro 		if (flags & DCACHE_MOUNTED) {
1439ea936aebSAl Viro 			struct mount *mounted = __lookup_mnt(path->mnt, dentry);
1440ea936aebSAl Viro 			if (mounted) {
1441c7105365SAl Viro 				path->mnt = &mounted->mnt;
1442ea936aebSAl Viro 				dentry = path->dentry = mounted->mnt.mnt_root;
1443bcba1e7dSAl Viro 				nd->state |= ND_JUMPED;
1444ea936aebSAl Viro 				*seqp = read_seqcount_begin(&dentry->d_seq);
1445ea936aebSAl Viro 				*inode = dentry->d_inode;
144659430262SLinus Torvalds 				/*
1447ea936aebSAl Viro 				 * We don't need to re-check ->d_seq after this
1448ea936aebSAl Viro 				 * ->d_inode read - there will be an RCU delay
1449ea936aebSAl Viro 				 * between mount hash removal and ->mnt_root
1450ea936aebSAl Viro 				 * becoming unpinned.
145159430262SLinus Torvalds 				 */
1452ea936aebSAl Viro 				flags = dentry->d_flags;
1453ea936aebSAl Viro 				continue;
14549875cf80SDavid Howells 			}
1455ea936aebSAl Viro 			if (read_seqretry(&mount_lock, nd->m_seq))
1456ea936aebSAl Viro 				return false;
1457ea936aebSAl Viro 		}
1458ea936aebSAl Viro 		return !(flags & DCACHE_NEED_AUTOMOUNT);
1459ea936aebSAl Viro 	}
1460287548e4SAl Viro }
1461287548e4SAl Viro 
1462db3c9adeSAl Viro static inline int handle_mounts(struct nameidata *nd, struct dentry *dentry,
1463db3c9adeSAl Viro 			  struct path *path, struct inode **inode,
1464db3c9adeSAl Viro 			  unsigned int *seqp)
1465bd7c4b50SAl Viro {
14669deed3ebSAl Viro 	bool jumped;
1467db3c9adeSAl Viro 	int ret;
1468bd7c4b50SAl Viro 
1469db3c9adeSAl Viro 	path->mnt = nd->path.mnt;
1470db3c9adeSAl Viro 	path->dentry = dentry;
1471c153007bSAl Viro 	if (nd->flags & LOOKUP_RCU) {
1472c153007bSAl Viro 		unsigned int seq = *seqp;
1473c153007bSAl Viro 		if (unlikely(!*inode))
1474c153007bSAl Viro 			return -ENOENT;
1475c153007bSAl Viro 		if (likely(__follow_mount_rcu(nd, path, inode, seqp)))
14769deed3ebSAl Viro 			return 0;
1477ae66db45SAl Viro 		if (!try_to_unlazy_next(nd, dentry, seq))
1478c153007bSAl Viro 			return -ECHILD;
1479c153007bSAl Viro 		// *path might've been clobbered by __follow_mount_rcu()
1480c153007bSAl Viro 		path->mnt = nd->path.mnt;
1481c153007bSAl Viro 		path->dentry = dentry;
1482c153007bSAl Viro 	}
14839deed3ebSAl Viro 	ret = traverse_mounts(path, &jumped, &nd->total_link_count, nd->flags);
14849deed3ebSAl Viro 	if (jumped) {
14859deed3ebSAl Viro 		if (unlikely(nd->flags & LOOKUP_NO_XDEV))
14869deed3ebSAl Viro 			ret = -EXDEV;
14879deed3ebSAl Viro 		else
1488bcba1e7dSAl Viro 			nd->state |= ND_JUMPED;
14899deed3ebSAl Viro 	}
14909deed3ebSAl Viro 	if (unlikely(ret)) {
14919deed3ebSAl Viro 		dput(path->dentry);
14929deed3ebSAl Viro 		if (path->mnt != nd->path.mnt)
14939deed3ebSAl Viro 			mntput(path->mnt);
14949deed3ebSAl Viro 	} else {
1495bd7c4b50SAl Viro 		*inode = d_backing_inode(path->dentry);
1496bd7c4b50SAl Viro 		*seqp = 0; /* out of RCU mode, so the value doesn't matter */
1497bd7c4b50SAl Viro 	}
1498bd7c4b50SAl Viro 	return ret;
1499bd7c4b50SAl Viro }
1500bd7c4b50SAl Viro 
15019875cf80SDavid Howells /*
1502f4fdace9SOleg Drokin  * This looks up the name in dcache and possibly revalidates the found dentry.
1503f4fdace9SOleg Drokin  * NULL is returned if the dentry does not exist in the cache.
1504baa03890SNick Piggin  */
1505e3c13928SAl Viro static struct dentry *lookup_dcache(const struct qstr *name,
1506e3c13928SAl Viro 				    struct dentry *dir,
15076c51e513SAl Viro 				    unsigned int flags)
1508baa03890SNick Piggin {
1509a89f8337SAl Viro 	struct dentry *dentry = d_lookup(dir, name);
1510bad61189SMiklos Szeredi 	if (dentry) {
1511a89f8337SAl Viro 		int error = d_revalidate(dentry, flags);
1512bad61189SMiklos Szeredi 		if (unlikely(error <= 0)) {
151374ff0ffcSAl Viro 			if (!error)
15145542aa2fSEric W. Biederman 				d_invalidate(dentry);
1515bad61189SMiklos Szeredi 			dput(dentry);
151674ff0ffcSAl Viro 			return ERR_PTR(error);
1517bad61189SMiklos Szeredi 		}
1518bad61189SMiklos Szeredi 	}
1519baa03890SNick Piggin 	return dentry;
1520baa03890SNick Piggin }
1521baa03890SNick Piggin 
1522baa03890SNick Piggin /*
1523a03ece5fSAl Viro  * Parent directory has inode locked exclusive.  This is one
1524a03ece5fSAl Viro  * and only case when ->lookup() gets called on non in-lookup
1525a03ece5fSAl Viro  * dentries - as the matter of fact, this only gets called
1526a03ece5fSAl Viro  * when directory is guaranteed to have no in-lookup children
1527a03ece5fSAl Viro  * at all.
152844396f4bSJosef Bacik  */
1529a03ece5fSAl Viro static struct dentry *__lookup_hash(const struct qstr *name,
1530a03ece5fSAl Viro 		struct dentry *base, unsigned int flags)
153144396f4bSJosef Bacik {
1532a03ece5fSAl Viro 	struct dentry *dentry = lookup_dcache(name, base, flags);
153344396f4bSJosef Bacik 	struct dentry *old;
1534a03ece5fSAl Viro 	struct inode *dir = base->d_inode;
1535a03ece5fSAl Viro 
1536a03ece5fSAl Viro 	if (dentry)
1537a03ece5fSAl Viro 		return dentry;
153844396f4bSJosef Bacik 
153944396f4bSJosef Bacik 	/* Don't create child dentry for a dead directory. */
1540a03ece5fSAl Viro 	if (unlikely(IS_DEADDIR(dir)))
154144396f4bSJosef Bacik 		return ERR_PTR(-ENOENT);
1542a03ece5fSAl Viro 
1543a03ece5fSAl Viro 	dentry = d_alloc(base, name);
1544a03ece5fSAl Viro 	if (unlikely(!dentry))
1545a03ece5fSAl Viro 		return ERR_PTR(-ENOMEM);
154644396f4bSJosef Bacik 
154772bd866aSAl Viro 	old = dir->i_op->lookup(dir, dentry, flags);
154844396f4bSJosef Bacik 	if (unlikely(old)) {
154944396f4bSJosef Bacik 		dput(dentry);
155044396f4bSJosef Bacik 		dentry = old;
155144396f4bSJosef Bacik 	}
155244396f4bSJosef Bacik 	return dentry;
155344396f4bSJosef Bacik }
155444396f4bSJosef Bacik 
155520e34357SAl Viro static struct dentry *lookup_fast(struct nameidata *nd,
155620e34357SAl Viro 				  struct inode **inode,
1557254cf582SAl Viro 			          unsigned *seqp)
15581da177e4SLinus Torvalds {
155931e6b01fSNick Piggin 	struct dentry *dentry, *parent = nd->path.dentry;
15605a18fff2SAl Viro 	int status = 1;
15619875cf80SDavid Howells 
15623cac260aSAl Viro 	/*
1563b04f784eSNick Piggin 	 * Rename seqlock is not required here because in the off chance
15645d0f49c1SAl Viro 	 * of a false negative due to a concurrent rename, the caller is
15655d0f49c1SAl Viro 	 * going to fall back to non-racy lookup.
1566b04f784eSNick Piggin 	 */
156731e6b01fSNick Piggin 	if (nd->flags & LOOKUP_RCU) {
156831e6b01fSNick Piggin 		unsigned seq;
1569da53be12SLinus Torvalds 		dentry = __d_lookup_rcu(parent, &nd->last, &seq);
15705d0f49c1SAl Viro 		if (unlikely(!dentry)) {
1571e36cffedSJens Axboe 			if (!try_to_unlazy(nd))
157220e34357SAl Viro 				return ERR_PTR(-ECHILD);
157320e34357SAl Viro 			return NULL;
15745d0f49c1SAl Viro 		}
15755a18fff2SAl Viro 
157612f8ad4bSLinus Torvalds 		/*
157712f8ad4bSLinus Torvalds 		 * This sequence count validates that the inode matches
157812f8ad4bSLinus Torvalds 		 * the dentry name information from lookup.
157912f8ad4bSLinus Torvalds 		 */
158063afdfc7SDavid Howells 		*inode = d_backing_inode(dentry);
15815d0f49c1SAl Viro 		if (unlikely(read_seqcount_retry(&dentry->d_seq, seq)))
158220e34357SAl Viro 			return ERR_PTR(-ECHILD);
158312f8ad4bSLinus Torvalds 
158412f8ad4bSLinus Torvalds 		/*
158512f8ad4bSLinus Torvalds 		 * This sequence count validates that the parent had no
158612f8ad4bSLinus Torvalds 		 * changes while we did the lookup of the dentry above.
158712f8ad4bSLinus Torvalds 		 *
158812f8ad4bSLinus Torvalds 		 * The memory barrier in read_seqcount_begin of child is
158912f8ad4bSLinus Torvalds 		 *  enough, we can use __read_seqcount_retry here.
159012f8ad4bSLinus Torvalds 		 */
15915d0f49c1SAl Viro 		if (unlikely(__read_seqcount_retry(&parent->d_seq, nd->seq)))
159220e34357SAl Viro 			return ERR_PTR(-ECHILD);
15935a18fff2SAl Viro 
1594254cf582SAl Viro 		*seqp = seq;
15954ce16ef3SAl Viro 		status = d_revalidate(dentry, nd->flags);
1596c153007bSAl Viro 		if (likely(status > 0))
159720e34357SAl Viro 			return dentry;
1598ae66db45SAl Viro 		if (!try_to_unlazy_next(nd, dentry, seq))
159920e34357SAl Viro 			return ERR_PTR(-ECHILD);
160026ddb45eSSteven Rostedt (VMware) 		if (status == -ECHILD)
1601209a7fb2SAl Viro 			/* we'd been told to redo it in non-rcu mode */
1602209a7fb2SAl Viro 			status = d_revalidate(dentry, nd->flags);
16035a18fff2SAl Viro 	} else {
1604e97cdc87SAl Viro 		dentry = __d_lookup(parent, &nd->last);
160581e6f520SAl Viro 		if (unlikely(!dentry))
160620e34357SAl Viro 			return NULL;
16074ce16ef3SAl Viro 		status = d_revalidate(dentry, nd->flags);
16085d0f49c1SAl Viro 	}
16095a18fff2SAl Viro 	if (unlikely(status <= 0)) {
1610e9742b53SAl Viro 		if (!status)
16115d0f49c1SAl Viro 			d_invalidate(dentry);
16125a18fff2SAl Viro 		dput(dentry);
161320e34357SAl Viro 		return ERR_PTR(status);
16145a18fff2SAl Viro 	}
161520e34357SAl Viro 	return dentry;
1616697f514dSMiklos Szeredi }
1617697f514dSMiklos Szeredi 
1618697f514dSMiklos Szeredi /* Fast lookup failed, do it the slow way */
161988d8331aSAl Viro static struct dentry *__lookup_slow(const struct qstr *name,
1620e3c13928SAl Viro 				    struct dentry *dir,
1621e3c13928SAl Viro 				    unsigned int flags)
1622697f514dSMiklos Szeredi {
162388d8331aSAl Viro 	struct dentry *dentry, *old;
16241936386eSAl Viro 	struct inode *inode = dir->d_inode;
1625d9171b93SAl Viro 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
16261936386eSAl Viro 
16271936386eSAl Viro 	/* Don't go there if it's already dead */
162894bdd655SAl Viro 	if (unlikely(IS_DEADDIR(inode)))
162988d8331aSAl Viro 		return ERR_PTR(-ENOENT);
163094bdd655SAl Viro again:
1631d9171b93SAl Viro 	dentry = d_alloc_parallel(dir, name, &wq);
163294bdd655SAl Viro 	if (IS_ERR(dentry))
163388d8331aSAl Viro 		return dentry;
163494bdd655SAl Viro 	if (unlikely(!d_in_lookup(dentry))) {
1635949a852eSAl Viro 		int error = d_revalidate(dentry, flags);
1636949a852eSAl Viro 		if (unlikely(error <= 0)) {
163794bdd655SAl Viro 			if (!error) {
1638949a852eSAl Viro 				d_invalidate(dentry);
1639949a852eSAl Viro 				dput(dentry);
164094bdd655SAl Viro 				goto again;
164194bdd655SAl Viro 			}
164294bdd655SAl Viro 			dput(dentry);
1643949a852eSAl Viro 			dentry = ERR_PTR(error);
1644949a852eSAl Viro 		}
164594bdd655SAl Viro 	} else {
16461936386eSAl Viro 		old = inode->i_op->lookup(inode, dentry, flags);
164785c7f810SAl Viro 		d_lookup_done(dentry);
16481936386eSAl Viro 		if (unlikely(old)) {
16491936386eSAl Viro 			dput(dentry);
16501936386eSAl Viro 			dentry = old;
1651949a852eSAl Viro 		}
1652949a852eSAl Viro 	}
1653e3c13928SAl Viro 	return dentry;
16541da177e4SLinus Torvalds }
16551da177e4SLinus Torvalds 
165688d8331aSAl Viro static struct dentry *lookup_slow(const struct qstr *name,
165788d8331aSAl Viro 				  struct dentry *dir,
165888d8331aSAl Viro 				  unsigned int flags)
165988d8331aSAl Viro {
166088d8331aSAl Viro 	struct inode *inode = dir->d_inode;
166188d8331aSAl Viro 	struct dentry *res;
166288d8331aSAl Viro 	inode_lock_shared(inode);
166388d8331aSAl Viro 	res = __lookup_slow(name, dir, flags);
166488d8331aSAl Viro 	inode_unlock_shared(inode);
166588d8331aSAl Viro 	return res;
166688d8331aSAl Viro }
166788d8331aSAl Viro 
1668ba73d987SChristian Brauner static inline int may_lookup(struct user_namespace *mnt_userns,
1669ba73d987SChristian Brauner 			     struct nameidata *nd)
167052094c8aSAl Viro {
167152094c8aSAl Viro 	if (nd->flags & LOOKUP_RCU) {
16727d6beb71SLinus Torvalds 		int err = inode_permission(mnt_userns, nd->inode, MAY_EXEC|MAY_NOT_BLOCK);
1673e36cffedSJens Axboe 		if (err != -ECHILD || !try_to_unlazy(nd))
167452094c8aSAl Viro 			return err;
167552094c8aSAl Viro 	}
1676ba73d987SChristian Brauner 	return inode_permission(mnt_userns, nd->inode, MAY_EXEC);
167752094c8aSAl Viro }
167852094c8aSAl Viro 
167949055906SAl Viro static int reserve_stack(struct nameidata *nd, struct path *link, unsigned seq)
1680d63ff28fSAl Viro {
168149055906SAl Viro 	if (unlikely(nd->total_link_count++ >= MAXSYMLINKS))
168249055906SAl Viro 		return -ELOOP;
16834542576bSAl Viro 
16844542576bSAl Viro 	if (likely(nd->depth != EMBEDDED_LEVELS))
16854542576bSAl Viro 		return 0;
16864542576bSAl Viro 	if (likely(nd->stack != nd->internal))
16874542576bSAl Viro 		return 0;
168860ef60c7SAl Viro 	if (likely(nd_alloc_stack(nd)))
168949055906SAl Viro 		return 0;
169060ef60c7SAl Viro 
169160ef60c7SAl Viro 	if (nd->flags & LOOKUP_RCU) {
169260ef60c7SAl Viro 		// we need to grab link before we do unlazy.  And we can't skip
169360ef60c7SAl Viro 		// unlazy even if we fail to grab the link - cleanup needs it
1694aef9404dSAl Viro 		bool grabbed_link = legitimize_path(nd, link, seq);
169560ef60c7SAl Viro 
1696e36cffedSJens Axboe 		if (!try_to_unlazy(nd) != 0 || !grabbed_link)
169760ef60c7SAl Viro 			return -ECHILD;
169860ef60c7SAl Viro 
169960ef60c7SAl Viro 		if (nd_alloc_stack(nd))
170060ef60c7SAl Viro 			return 0;
1701bc40aee0SAl Viro 	}
170260ef60c7SAl Viro 	return -ENOMEM;
170349055906SAl Viro }
170449055906SAl Viro 
170549055906SAl Viro enum {WALK_TRAILING = 1, WALK_MORE = 2, WALK_NOFOLLOW = 4};
170649055906SAl Viro 
170749055906SAl Viro static const char *pick_link(struct nameidata *nd, struct path *link,
170849055906SAl Viro 		     struct inode *inode, unsigned seq, int flags)
170949055906SAl Viro {
171049055906SAl Viro 	struct saved *last;
171149055906SAl Viro 	const char *res;
171249055906SAl Viro 	int error = reserve_stack(nd, link, seq);
171349055906SAl Viro 
171449055906SAl Viro 	if (unlikely(error)) {
171549055906SAl Viro 		if (!(nd->flags & LOOKUP_RCU))
1716cd179f44SAl Viro 			path_put(link);
171706708adbSAl Viro 		return ERR_PTR(error);
1718626de996SAl Viro 	}
1719ab104923SAl Viro 	last = nd->stack + nd->depth++;
17201cf2665bSAl Viro 	last->link = *link;
1721fceef393SAl Viro 	clear_delayed_call(&last->done);
17220450b2d1SAl Viro 	last->seq = seq;
1723ad6cc4c3SAl Viro 
1724b1a81972SAl Viro 	if (flags & WALK_TRAILING) {
1725ad6cc4c3SAl Viro 		error = may_follow_link(nd, inode);
1726ad6cc4c3SAl Viro 		if (unlikely(error))
1727ad6cc4c3SAl Viro 			return ERR_PTR(error);
1728ad6cc4c3SAl Viro 	}
1729ad6cc4c3SAl Viro 
1730dab741e0SMattias Nissler 	if (unlikely(nd->flags & LOOKUP_NO_SYMLINKS) ||
1731dab741e0SMattias Nissler 			unlikely(link->mnt->mnt_flags & MNT_NOSYMFOLLOW))
1732ad6cc4c3SAl Viro 		return ERR_PTR(-ELOOP);
1733ad6cc4c3SAl Viro 
1734ad6cc4c3SAl Viro 	if (!(nd->flags & LOOKUP_RCU)) {
1735ad6cc4c3SAl Viro 		touch_atime(&last->link);
1736ad6cc4c3SAl Viro 		cond_resched();
1737ad6cc4c3SAl Viro 	} else if (atime_needs_update(&last->link, inode)) {
1738e36cffedSJens Axboe 		if (!try_to_unlazy(nd))
1739ad6cc4c3SAl Viro 			return ERR_PTR(-ECHILD);
1740ad6cc4c3SAl Viro 		touch_atime(&last->link);
1741ad6cc4c3SAl Viro 	}
1742ad6cc4c3SAl Viro 
1743ad6cc4c3SAl Viro 	error = security_inode_follow_link(link->dentry, inode,
1744ad6cc4c3SAl Viro 					   nd->flags & LOOKUP_RCU);
1745ad6cc4c3SAl Viro 	if (unlikely(error))
1746ad6cc4c3SAl Viro 		return ERR_PTR(error);
1747ad6cc4c3SAl Viro 
1748ad6cc4c3SAl Viro 	res = READ_ONCE(inode->i_link);
1749ad6cc4c3SAl Viro 	if (!res) {
1750ad6cc4c3SAl Viro 		const char * (*get)(struct dentry *, struct inode *,
1751ad6cc4c3SAl Viro 				struct delayed_call *);
1752ad6cc4c3SAl Viro 		get = inode->i_op->get_link;
1753ad6cc4c3SAl Viro 		if (nd->flags & LOOKUP_RCU) {
1754ad6cc4c3SAl Viro 			res = get(NULL, inode, &last->done);
1755e36cffedSJens Axboe 			if (res == ERR_PTR(-ECHILD) && try_to_unlazy(nd))
1756ad6cc4c3SAl Viro 				res = get(link->dentry, inode, &last->done);
1757ad6cc4c3SAl Viro 		} else {
1758ad6cc4c3SAl Viro 			res = get(link->dentry, inode, &last->done);
1759ad6cc4c3SAl Viro 		}
1760ad6cc4c3SAl Viro 		if (!res)
1761ad6cc4c3SAl Viro 			goto all_done;
1762ad6cc4c3SAl Viro 		if (IS_ERR(res))
1763ad6cc4c3SAl Viro 			return res;
1764ad6cc4c3SAl Viro 	}
1765ad6cc4c3SAl Viro 	if (*res == '/') {
1766ad6cc4c3SAl Viro 		error = nd_jump_root(nd);
1767ad6cc4c3SAl Viro 		if (unlikely(error))
1768ad6cc4c3SAl Viro 			return ERR_PTR(error);
1769ad6cc4c3SAl Viro 		while (unlikely(*++res == '/'))
1770ad6cc4c3SAl Viro 			;
1771ad6cc4c3SAl Viro 	}
1772ad6cc4c3SAl Viro 	if (*res)
1773ad6cc4c3SAl Viro 		return res;
1774ad6cc4c3SAl Viro all_done: // pure jump
1775ad6cc4c3SAl Viro 	put_link(nd);
1776ad6cc4c3SAl Viro 	return NULL;
1777d63ff28fSAl Viro }
1778d63ff28fSAl Viro 
17793ddcd056SLinus Torvalds /*
17803ddcd056SLinus Torvalds  * Do we need to follow links? We _really_ want to be able
17813ddcd056SLinus Torvalds  * to do this check without having to look at inode->i_op,
17823ddcd056SLinus Torvalds  * so we keep a cache of "no, this doesn't need follow_link"
17833ddcd056SLinus Torvalds  * for the common case.
17843ddcd056SLinus Torvalds  */
1785b0417d2cSAl Viro static const char *step_into(struct nameidata *nd, int flags,
1786cbae4d12SAl Viro 		     struct dentry *dentry, struct inode *inode, unsigned seq)
17873ddcd056SLinus Torvalds {
1788cbae4d12SAl Viro 	struct path path;
1789cbae4d12SAl Viro 	int err = handle_mounts(nd, dentry, &path, &inode, &seq);
1790cbae4d12SAl Viro 
1791cbae4d12SAl Viro 	if (err < 0)
1792b0417d2cSAl Viro 		return ERR_PTR(err);
1793cbae4d12SAl Viro 	if (likely(!d_is_symlink(path.dentry)) ||
17948c4efe22SAl Viro 	   ((flags & WALK_TRAILING) && !(nd->flags & LOOKUP_FOLLOW)) ||
1795aca2903eSAl Viro 	   (flags & WALK_NOFOLLOW)) {
17968f64fb1cSAl Viro 		/* not a symlink or should not follow */
1797c99687a0SAl Viro 		if (!(nd->flags & LOOKUP_RCU)) {
1798c99687a0SAl Viro 			dput(nd->path.dentry);
1799c99687a0SAl Viro 			if (nd->path.mnt != path.mnt)
1800c99687a0SAl Viro 				mntput(nd->path.mnt);
1801c99687a0SAl Viro 		}
1802c99687a0SAl Viro 		nd->path = path;
18038f64fb1cSAl Viro 		nd->inode = inode;
18048f64fb1cSAl Viro 		nd->seq = seq;
1805b0417d2cSAl Viro 		return NULL;
18068f64fb1cSAl Viro 	}
1807a7f77542SAl Viro 	if (nd->flags & LOOKUP_RCU) {
180884f0cd9eSAl Viro 		/* make sure that d_is_symlink above matches inode */
1809cbae4d12SAl Viro 		if (read_seqcount_retry(&path.dentry->d_seq, seq))
1810b0417d2cSAl Viro 			return ERR_PTR(-ECHILD);
181184f0cd9eSAl Viro 	} else {
181284f0cd9eSAl Viro 		if (path.mnt == nd->path.mnt)
181384f0cd9eSAl Viro 			mntget(path.mnt);
1814a7f77542SAl Viro 	}
1815b1a81972SAl Viro 	return pick_link(nd, &path, inode, seq, flags);
18163ddcd056SLinus Torvalds }
18173ddcd056SLinus Torvalds 
1818c2df1968SAl Viro static struct dentry *follow_dotdot_rcu(struct nameidata *nd,
1819c2df1968SAl Viro 					struct inode **inodep,
1820c2df1968SAl Viro 					unsigned *seqp)
1821957dd41dSAl Viro {
182212487f30SAl Viro 	struct dentry *parent, *old;
1823957dd41dSAl Viro 
182412487f30SAl Viro 	if (path_equal(&nd->path, &nd->root))
182512487f30SAl Viro 		goto in_root;
182612487f30SAl Viro 	if (unlikely(nd->path.dentry == nd->path.mnt->mnt_root)) {
18277ef482faSAl Viro 		struct path path;
1828efe772d6SAl Viro 		unsigned seq;
18297ef482faSAl Viro 		if (!choose_mountpoint_rcu(real_mount(nd->path.mnt),
18307ef482faSAl Viro 					   &nd->root, &path, &seq))
183112487f30SAl Viro 			goto in_root;
1832efe772d6SAl Viro 		if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1833efe772d6SAl Viro 			return ERR_PTR(-ECHILD);
1834efe772d6SAl Viro 		nd->path = path;
1835efe772d6SAl Viro 		nd->inode = path.dentry->d_inode;
1836efe772d6SAl Viro 		nd->seq = seq;
1837efe772d6SAl Viro 		if (unlikely(read_seqretry(&mount_lock, nd->m_seq)))
1838efe772d6SAl Viro 			return ERR_PTR(-ECHILD);
1839efe772d6SAl Viro 		/* we know that mountpoint was pinned */
1840957dd41dSAl Viro 	}
184112487f30SAl Viro 	old = nd->path.dentry;
184212487f30SAl Viro 	parent = old->d_parent;
184312487f30SAl Viro 	*inodep = parent->d_inode;
184412487f30SAl Viro 	*seqp = read_seqcount_begin(&parent->d_seq);
184512487f30SAl Viro 	if (unlikely(read_seqcount_retry(&old->d_seq, nd->seq)))
184612487f30SAl Viro 		return ERR_PTR(-ECHILD);
184712487f30SAl Viro 	if (unlikely(!path_connected(nd->path.mnt, parent)))
184812487f30SAl Viro 		return ERR_PTR(-ECHILD);
184912487f30SAl Viro 	return parent;
185012487f30SAl Viro in_root:
1851efe772d6SAl Viro 	if (unlikely(read_seqretry(&mount_lock, nd->m_seq)))
1852efe772d6SAl Viro 		return ERR_PTR(-ECHILD);
1853957dd41dSAl Viro 	if (unlikely(nd->flags & LOOKUP_BENEATH))
18547521f22bSAl Viro 		return ERR_PTR(-ECHILD);
1855c2df1968SAl Viro 	return NULL;
1856957dd41dSAl Viro }
1857957dd41dSAl Viro 
1858c2df1968SAl Viro static struct dentry *follow_dotdot(struct nameidata *nd,
1859c2df1968SAl Viro 				 struct inode **inodep,
1860c2df1968SAl Viro 				 unsigned *seqp)
1861957dd41dSAl Viro {
186212487f30SAl Viro 	struct dentry *parent;
186312487f30SAl Viro 
1864957dd41dSAl Viro 	if (path_equal(&nd->path, &nd->root))
186512487f30SAl Viro 		goto in_root;
186612487f30SAl Viro 	if (unlikely(nd->path.dentry == nd->path.mnt->mnt_root)) {
18672aa38470SAl Viro 		struct path path;
18682aa38470SAl Viro 
18692aa38470SAl Viro 		if (!choose_mountpoint(real_mount(nd->path.mnt),
18702aa38470SAl Viro 				       &nd->root, &path))
187112487f30SAl Viro 			goto in_root;
1872165200d6SAl Viro 		path_put(&nd->path);
1873165200d6SAl Viro 		nd->path = path;
18742aa38470SAl Viro 		nd->inode = path.dentry->d_inode;
1875165200d6SAl Viro 		if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1876165200d6SAl Viro 			return ERR_PTR(-EXDEV);
187712487f30SAl Viro 	}
1878957dd41dSAl Viro 	/* rare case of legitimate dget_parent()... */
187912487f30SAl Viro 	parent = dget_parent(nd->path.dentry);
1880957dd41dSAl Viro 	if (unlikely(!path_connected(nd->path.mnt, parent))) {
1881957dd41dSAl Viro 		dput(parent);
18827521f22bSAl Viro 		return ERR_PTR(-ENOENT);
1883957dd41dSAl Viro 	}
1884c2df1968SAl Viro 	*seqp = 0;
1885c2df1968SAl Viro 	*inodep = parent->d_inode;
1886c2df1968SAl Viro 	return parent;
188712487f30SAl Viro 
188812487f30SAl Viro in_root:
1889957dd41dSAl Viro 	if (unlikely(nd->flags & LOOKUP_BENEATH))
18907521f22bSAl Viro 		return ERR_PTR(-EXDEV);
1891c2df1968SAl Viro 	dget(nd->path.dentry);
1892c2df1968SAl Viro 	return NULL;
1893957dd41dSAl Viro }
1894957dd41dSAl Viro 
18957521f22bSAl Viro static const char *handle_dots(struct nameidata *nd, int type)
1896957dd41dSAl Viro {
1897957dd41dSAl Viro 	if (type == LAST_DOTDOT) {
18987521f22bSAl Viro 		const char *error = NULL;
1899c2df1968SAl Viro 		struct dentry *parent;
1900c2df1968SAl Viro 		struct inode *inode;
1901c2df1968SAl Viro 		unsigned seq;
1902957dd41dSAl Viro 
1903957dd41dSAl Viro 		if (!nd->root.mnt) {
19047521f22bSAl Viro 			error = ERR_PTR(set_root(nd));
1905957dd41dSAl Viro 			if (error)
1906957dd41dSAl Viro 				return error;
1907957dd41dSAl Viro 		}
1908957dd41dSAl Viro 		if (nd->flags & LOOKUP_RCU)
1909c2df1968SAl Viro 			parent = follow_dotdot_rcu(nd, &inode, &seq);
1910957dd41dSAl Viro 		else
1911c2df1968SAl Viro 			parent = follow_dotdot(nd, &inode, &seq);
1912c2df1968SAl Viro 		if (IS_ERR(parent))
1913c2df1968SAl Viro 			return ERR_CAST(parent);
1914c2df1968SAl Viro 		if (unlikely(!parent))
1915c2df1968SAl Viro 			error = step_into(nd, WALK_NOFOLLOW,
1916c2df1968SAl Viro 					 nd->path.dentry, nd->inode, nd->seq);
1917c2df1968SAl Viro 		else
1918c2df1968SAl Viro 			error = step_into(nd, WALK_NOFOLLOW,
1919c2df1968SAl Viro 					 parent, inode, seq);
1920c2df1968SAl Viro 		if (unlikely(error))
1921957dd41dSAl Viro 			return error;
1922957dd41dSAl Viro 
1923957dd41dSAl Viro 		if (unlikely(nd->flags & LOOKUP_IS_SCOPED)) {
1924957dd41dSAl Viro 			/*
1925957dd41dSAl Viro 			 * If there was a racing rename or mount along our
1926957dd41dSAl Viro 			 * path, then we can't be sure that ".." hasn't jumped
1927957dd41dSAl Viro 			 * above nd->root (and so userspace should retry or use
1928957dd41dSAl Viro 			 * some fallback).
1929957dd41dSAl Viro 			 */
1930957dd41dSAl Viro 			smp_rmb();
1931957dd41dSAl Viro 			if (unlikely(__read_seqcount_retry(&mount_lock.seqcount, nd->m_seq)))
19327521f22bSAl Viro 				return ERR_PTR(-EAGAIN);
1933957dd41dSAl Viro 			if (unlikely(__read_seqcount_retry(&rename_lock.seqcount, nd->r_seq)))
19347521f22bSAl Viro 				return ERR_PTR(-EAGAIN);
1935957dd41dSAl Viro 		}
1936957dd41dSAl Viro 	}
19377521f22bSAl Viro 	return NULL;
1938957dd41dSAl Viro }
1939957dd41dSAl Viro 
194092d27016SAl Viro static const char *walk_component(struct nameidata *nd, int flags)
1941ce57dfc1SAl Viro {
1942db3c9adeSAl Viro 	struct dentry *dentry;
1943ce57dfc1SAl Viro 	struct inode *inode;
1944254cf582SAl Viro 	unsigned seq;
1945ce57dfc1SAl Viro 	/*
1946ce57dfc1SAl Viro 	 * "." and ".." are special - ".." especially so because it has
1947ce57dfc1SAl Viro 	 * to be able to know about the current root directory and
1948ce57dfc1SAl Viro 	 * parent relationships.
1949ce57dfc1SAl Viro 	 */
19504693a547SAl Viro 	if (unlikely(nd->last_type != LAST_NORM)) {
19511c4ff1a8SAl Viro 		if (!(flags & WALK_MORE) && nd->depth)
19524693a547SAl Viro 			put_link(nd);
19537521f22bSAl Viro 		return handle_dots(nd, nd->last_type);
19544693a547SAl Viro 	}
195520e34357SAl Viro 	dentry = lookup_fast(nd, &inode, &seq);
195620e34357SAl Viro 	if (IS_ERR(dentry))
195792d27016SAl Viro 		return ERR_CAST(dentry);
195820e34357SAl Viro 	if (unlikely(!dentry)) {
1959db3c9adeSAl Viro 		dentry = lookup_slow(&nd->last, nd->path.dentry, nd->flags);
1960db3c9adeSAl Viro 		if (IS_ERR(dentry))
196192d27016SAl Viro 			return ERR_CAST(dentry);
196220e34357SAl Viro 	}
196356676ec3SAl Viro 	if (!(flags & WALK_MORE) && nd->depth)
196456676ec3SAl Viro 		put_link(nd);
1965b0417d2cSAl Viro 	return step_into(nd, flags, dentry, inode, seq);
1966ce57dfc1SAl Viro }
1967ce57dfc1SAl Viro 
19681da177e4SLinus Torvalds /*
1969bfcfaa77SLinus Torvalds  * We can do the critical dentry name comparison and hashing
1970bfcfaa77SLinus Torvalds  * operations one word at a time, but we are limited to:
1971bfcfaa77SLinus Torvalds  *
1972bfcfaa77SLinus Torvalds  * - Architectures with fast unaligned word accesses. We could
1973bfcfaa77SLinus Torvalds  *   do a "get_unaligned()" if this helps and is sufficiently
1974bfcfaa77SLinus Torvalds  *   fast.
1975bfcfaa77SLinus Torvalds  *
1976bfcfaa77SLinus Torvalds  * - non-CONFIG_DEBUG_PAGEALLOC configurations (so that we
1977bfcfaa77SLinus Torvalds  *   do not trap on the (extremely unlikely) case of a page
1978bfcfaa77SLinus Torvalds  *   crossing operation.
1979bfcfaa77SLinus Torvalds  *
1980bfcfaa77SLinus Torvalds  * - Furthermore, we need an efficient 64-bit compile for the
1981bfcfaa77SLinus Torvalds  *   64-bit case in order to generate the "number of bytes in
1982bfcfaa77SLinus Torvalds  *   the final mask". Again, that could be replaced with a
1983bfcfaa77SLinus Torvalds  *   efficient population count instruction or similar.
1984bfcfaa77SLinus Torvalds  */
1985bfcfaa77SLinus Torvalds #ifdef CONFIG_DCACHE_WORD_ACCESS
1986bfcfaa77SLinus Torvalds 
1987f68e556eSLinus Torvalds #include <asm/word-at-a-time.h>
1988bfcfaa77SLinus Torvalds 
1989468a9428SGeorge Spelvin #ifdef HASH_MIX
1990bfcfaa77SLinus Torvalds 
1991468a9428SGeorge Spelvin /* Architecture provides HASH_MIX and fold_hash() in <asm/hash.h> */
1992468a9428SGeorge Spelvin 
1993468a9428SGeorge Spelvin #elif defined(CONFIG_64BIT)
19942a18da7aSGeorge Spelvin /*
19952a18da7aSGeorge Spelvin  * Register pressure in the mixing function is an issue, particularly
19962a18da7aSGeorge Spelvin  * on 32-bit x86, but almost any function requires one state value and
19972a18da7aSGeorge Spelvin  * one temporary.  Instead, use a function designed for two state values
19982a18da7aSGeorge Spelvin  * and no temporaries.
19992a18da7aSGeorge Spelvin  *
20002a18da7aSGeorge Spelvin  * This function cannot create a collision in only two iterations, so
20012a18da7aSGeorge Spelvin  * we have two iterations to achieve avalanche.  In those two iterations,
20022a18da7aSGeorge Spelvin  * we have six layers of mixing, which is enough to spread one bit's
20032a18da7aSGeorge Spelvin  * influence out to 2^6 = 64 state bits.
20042a18da7aSGeorge Spelvin  *
20052a18da7aSGeorge Spelvin  * Rotate constants are scored by considering either 64 one-bit input
20062a18da7aSGeorge Spelvin  * deltas or 64*63/2 = 2016 two-bit input deltas, and finding the
20072a18da7aSGeorge Spelvin  * probability of that delta causing a change to each of the 128 output
20082a18da7aSGeorge Spelvin  * bits, using a sample of random initial states.
20092a18da7aSGeorge Spelvin  *
20102a18da7aSGeorge Spelvin  * The Shannon entropy of the computed probabilities is then summed
20112a18da7aSGeorge Spelvin  * to produce a score.  Ideally, any input change has a 50% chance of
20122a18da7aSGeorge Spelvin  * toggling any given output bit.
20132a18da7aSGeorge Spelvin  *
20142a18da7aSGeorge Spelvin  * Mixing scores (in bits) for (12,45):
20152a18da7aSGeorge Spelvin  * Input delta: 1-bit      2-bit
20162a18da7aSGeorge Spelvin  * 1 round:     713.3    42542.6
20172a18da7aSGeorge Spelvin  * 2 rounds:   2753.7   140389.8
20182a18da7aSGeorge Spelvin  * 3 rounds:   5954.1   233458.2
20192a18da7aSGeorge Spelvin  * 4 rounds:   7862.6   256672.2
20202a18da7aSGeorge Spelvin  * Perfect:    8192     258048
20212a18da7aSGeorge Spelvin  *            (64*128) (64*63/2 * 128)
20222a18da7aSGeorge Spelvin  */
20232a18da7aSGeorge Spelvin #define HASH_MIX(x, y, a)	\
20242a18da7aSGeorge Spelvin 	(	x ^= (a),	\
20252a18da7aSGeorge Spelvin 	y ^= x,	x = rol64(x,12),\
20262a18da7aSGeorge Spelvin 	x += y,	y = rol64(y,45),\
20272a18da7aSGeorge Spelvin 	y *= 9			)
2028bfcfaa77SLinus Torvalds 
20290fed3ac8SGeorge Spelvin /*
20302a18da7aSGeorge Spelvin  * Fold two longs into one 32-bit hash value.  This must be fast, but
20312a18da7aSGeorge Spelvin  * latency isn't quite as critical, as there is a fair bit of additional
20322a18da7aSGeorge Spelvin  * work done before the hash value is used.
20330fed3ac8SGeorge Spelvin  */
20342a18da7aSGeorge Spelvin static inline unsigned int fold_hash(unsigned long x, unsigned long y)
20350fed3ac8SGeorge Spelvin {
20362a18da7aSGeorge Spelvin 	y ^= x * GOLDEN_RATIO_64;
20372a18da7aSGeorge Spelvin 	y *= GOLDEN_RATIO_64;
20382a18da7aSGeorge Spelvin 	return y >> 32;
20390fed3ac8SGeorge Spelvin }
20400fed3ac8SGeorge Spelvin 
2041bfcfaa77SLinus Torvalds #else	/* 32-bit case */
2042bfcfaa77SLinus Torvalds 
20432a18da7aSGeorge Spelvin /*
20442a18da7aSGeorge Spelvin  * Mixing scores (in bits) for (7,20):
20452a18da7aSGeorge Spelvin  * Input delta: 1-bit      2-bit
20462a18da7aSGeorge Spelvin  * 1 round:     330.3     9201.6
20472a18da7aSGeorge Spelvin  * 2 rounds:   1246.4    25475.4
20482a18da7aSGeorge Spelvin  * 3 rounds:   1907.1    31295.1
20492a18da7aSGeorge Spelvin  * 4 rounds:   2042.3    31718.6
20502a18da7aSGeorge Spelvin  * Perfect:    2048      31744
20512a18da7aSGeorge Spelvin  *            (32*64)   (32*31/2 * 64)
20522a18da7aSGeorge Spelvin  */
20532a18da7aSGeorge Spelvin #define HASH_MIX(x, y, a)	\
20542a18da7aSGeorge Spelvin 	(	x ^= (a),	\
20552a18da7aSGeorge Spelvin 	y ^= x,	x = rol32(x, 7),\
20562a18da7aSGeorge Spelvin 	x += y,	y = rol32(y,20),\
20572a18da7aSGeorge Spelvin 	y *= 9			)
2058bfcfaa77SLinus Torvalds 
20592a18da7aSGeorge Spelvin static inline unsigned int fold_hash(unsigned long x, unsigned long y)
20600fed3ac8SGeorge Spelvin {
20612a18da7aSGeorge Spelvin 	/* Use arch-optimized multiply if one exists */
20622a18da7aSGeorge Spelvin 	return __hash_32(y ^ __hash_32(x));
20630fed3ac8SGeorge Spelvin }
20640fed3ac8SGeorge Spelvin 
2065bfcfaa77SLinus Torvalds #endif
2066bfcfaa77SLinus Torvalds 
20672a18da7aSGeorge Spelvin /*
20682a18da7aSGeorge Spelvin  * Return the hash of a string of known length.  This is carfully
20692a18da7aSGeorge Spelvin  * designed to match hash_name(), which is the more critical function.
20702a18da7aSGeorge Spelvin  * In particular, we must end by hashing a final word containing 0..7
20712a18da7aSGeorge Spelvin  * payload bytes, to match the way that hash_name() iterates until it
20722a18da7aSGeorge Spelvin  * finds the delimiter after the name.
20732a18da7aSGeorge Spelvin  */
20748387ff25SLinus Torvalds unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
2075bfcfaa77SLinus Torvalds {
20768387ff25SLinus Torvalds 	unsigned long a, x = 0, y = (unsigned long)salt;
2077bfcfaa77SLinus Torvalds 
2078bfcfaa77SLinus Torvalds 	for (;;) {
2079fcfd2fbfSGeorge Spelvin 		if (!len)
2080fcfd2fbfSGeorge Spelvin 			goto done;
2081e419b4ccSLinus Torvalds 		a = load_unaligned_zeropad(name);
2082bfcfaa77SLinus Torvalds 		if (len < sizeof(unsigned long))
2083bfcfaa77SLinus Torvalds 			break;
20842a18da7aSGeorge Spelvin 		HASH_MIX(x, y, a);
2085bfcfaa77SLinus Torvalds 		name += sizeof(unsigned long);
2086bfcfaa77SLinus Torvalds 		len -= sizeof(unsigned long);
2087bfcfaa77SLinus Torvalds 	}
20882a18da7aSGeorge Spelvin 	x ^= a & bytemask_from_count(len);
2089bfcfaa77SLinus Torvalds done:
20902a18da7aSGeorge Spelvin 	return fold_hash(x, y);
2091bfcfaa77SLinus Torvalds }
2092bfcfaa77SLinus Torvalds EXPORT_SYMBOL(full_name_hash);
2093bfcfaa77SLinus Torvalds 
2094fcfd2fbfSGeorge Spelvin /* Return the "hash_len" (hash and length) of a null-terminated string */
20958387ff25SLinus Torvalds u64 hashlen_string(const void *salt, const char *name)
2096fcfd2fbfSGeorge Spelvin {
20978387ff25SLinus Torvalds 	unsigned long a = 0, x = 0, y = (unsigned long)salt;
20988387ff25SLinus Torvalds 	unsigned long adata, mask, len;
2099fcfd2fbfSGeorge Spelvin 	const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2100fcfd2fbfSGeorge Spelvin 
21018387ff25SLinus Torvalds 	len = 0;
21028387ff25SLinus Torvalds 	goto inside;
21038387ff25SLinus Torvalds 
2104fcfd2fbfSGeorge Spelvin 	do {
21052a18da7aSGeorge Spelvin 		HASH_MIX(x, y, a);
2106fcfd2fbfSGeorge Spelvin 		len += sizeof(unsigned long);
21078387ff25SLinus Torvalds inside:
2108fcfd2fbfSGeorge Spelvin 		a = load_unaligned_zeropad(name+len);
2109fcfd2fbfSGeorge Spelvin 	} while (!has_zero(a, &adata, &constants));
2110fcfd2fbfSGeorge Spelvin 
2111fcfd2fbfSGeorge Spelvin 	adata = prep_zero_mask(a, adata, &constants);
2112fcfd2fbfSGeorge Spelvin 	mask = create_zero_mask(adata);
21132a18da7aSGeorge Spelvin 	x ^= a & zero_bytemask(mask);
2114fcfd2fbfSGeorge Spelvin 
21152a18da7aSGeorge Spelvin 	return hashlen_create(fold_hash(x, y), len + find_zero(mask));
2116fcfd2fbfSGeorge Spelvin }
2117fcfd2fbfSGeorge Spelvin EXPORT_SYMBOL(hashlen_string);
2118fcfd2fbfSGeorge Spelvin 
2119bfcfaa77SLinus Torvalds /*
2120bfcfaa77SLinus Torvalds  * Calculate the length and hash of the path component, and
2121d6bb3e90SLinus Torvalds  * return the "hash_len" as the result.
2122bfcfaa77SLinus Torvalds  */
21238387ff25SLinus Torvalds static inline u64 hash_name(const void *salt, const char *name)
2124bfcfaa77SLinus Torvalds {
21258387ff25SLinus Torvalds 	unsigned long a = 0, b, x = 0, y = (unsigned long)salt;
21268387ff25SLinus Torvalds 	unsigned long adata, bdata, mask, len;
212736126f8fSLinus Torvalds 	const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2128bfcfaa77SLinus Torvalds 
21298387ff25SLinus Torvalds 	len = 0;
21308387ff25SLinus Torvalds 	goto inside;
21318387ff25SLinus Torvalds 
2132bfcfaa77SLinus Torvalds 	do {
21332a18da7aSGeorge Spelvin 		HASH_MIX(x, y, a);
2134bfcfaa77SLinus Torvalds 		len += sizeof(unsigned long);
21358387ff25SLinus Torvalds inside:
2136e419b4ccSLinus Torvalds 		a = load_unaligned_zeropad(name+len);
213736126f8fSLinus Torvalds 		b = a ^ REPEAT_BYTE('/');
213836126f8fSLinus Torvalds 	} while (!(has_zero(a, &adata, &constants) | has_zero(b, &bdata, &constants)));
2139bfcfaa77SLinus Torvalds 
214036126f8fSLinus Torvalds 	adata = prep_zero_mask(a, adata, &constants);
214136126f8fSLinus Torvalds 	bdata = prep_zero_mask(b, bdata, &constants);
214236126f8fSLinus Torvalds 	mask = create_zero_mask(adata | bdata);
21432a18da7aSGeorge Spelvin 	x ^= a & zero_bytemask(mask);
214436126f8fSLinus Torvalds 
21452a18da7aSGeorge Spelvin 	return hashlen_create(fold_hash(x, y), len + find_zero(mask));
2146bfcfaa77SLinus Torvalds }
2147bfcfaa77SLinus Torvalds 
21482a18da7aSGeorge Spelvin #else	/* !CONFIG_DCACHE_WORD_ACCESS: Slow, byte-at-a-time version */
2149bfcfaa77SLinus Torvalds 
2150fcfd2fbfSGeorge Spelvin /* Return the hash of a string of known length */
21518387ff25SLinus Torvalds unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
21520145acc2SLinus Torvalds {
21538387ff25SLinus Torvalds 	unsigned long hash = init_name_hash(salt);
21540145acc2SLinus Torvalds 	while (len--)
2155fcfd2fbfSGeorge Spelvin 		hash = partial_name_hash((unsigned char)*name++, hash);
21560145acc2SLinus Torvalds 	return end_name_hash(hash);
21570145acc2SLinus Torvalds }
2158ae942ae7SLinus Torvalds EXPORT_SYMBOL(full_name_hash);
21590145acc2SLinus Torvalds 
2160fcfd2fbfSGeorge Spelvin /* Return the "hash_len" (hash and length) of a null-terminated string */
21618387ff25SLinus Torvalds u64 hashlen_string(const void *salt, const char *name)
2162fcfd2fbfSGeorge Spelvin {
21638387ff25SLinus Torvalds 	unsigned long hash = init_name_hash(salt);
2164fcfd2fbfSGeorge Spelvin 	unsigned long len = 0, c;
2165fcfd2fbfSGeorge Spelvin 
2166fcfd2fbfSGeorge Spelvin 	c = (unsigned char)*name;
2167e0ab7af9SGeorge Spelvin 	while (c) {
2168fcfd2fbfSGeorge Spelvin 		len++;
2169fcfd2fbfSGeorge Spelvin 		hash = partial_name_hash(c, hash);
2170fcfd2fbfSGeorge Spelvin 		c = (unsigned char)name[len];
2171e0ab7af9SGeorge Spelvin 	}
2172fcfd2fbfSGeorge Spelvin 	return hashlen_create(end_name_hash(hash), len);
2173fcfd2fbfSGeorge Spelvin }
2174f2a031b6SGeorge Spelvin EXPORT_SYMBOL(hashlen_string);
2175fcfd2fbfSGeorge Spelvin 
21763ddcd056SLinus Torvalds /*
2177200e9ef7SLinus Torvalds  * We know there's a real path component here of at least
2178200e9ef7SLinus Torvalds  * one character.
2179200e9ef7SLinus Torvalds  */
21808387ff25SLinus Torvalds static inline u64 hash_name(const void *salt, const char *name)
2181200e9ef7SLinus Torvalds {
21828387ff25SLinus Torvalds 	unsigned long hash = init_name_hash(salt);
2183200e9ef7SLinus Torvalds 	unsigned long len = 0, c;
2184200e9ef7SLinus Torvalds 
2185200e9ef7SLinus Torvalds 	c = (unsigned char)*name;
2186200e9ef7SLinus Torvalds 	do {
2187200e9ef7SLinus Torvalds 		len++;
2188200e9ef7SLinus Torvalds 		hash = partial_name_hash(c, hash);
2189200e9ef7SLinus Torvalds 		c = (unsigned char)name[len];
2190200e9ef7SLinus Torvalds 	} while (c && c != '/');
2191d6bb3e90SLinus Torvalds 	return hashlen_create(end_name_hash(hash), len);
2192200e9ef7SLinus Torvalds }
2193200e9ef7SLinus Torvalds 
2194bfcfaa77SLinus Torvalds #endif
2195bfcfaa77SLinus Torvalds 
2196200e9ef7SLinus Torvalds /*
21971da177e4SLinus Torvalds  * Name resolution.
2198ea3834d9SPrasanna Meda  * This is the basic name resolution function, turning a pathname into
2199ea3834d9SPrasanna Meda  * the final dentry. We expect 'base' to be positive and a directory.
22001da177e4SLinus Torvalds  *
2201ea3834d9SPrasanna Meda  * Returns 0 and nd will have valid dentry and mnt on success.
2202ea3834d9SPrasanna Meda  * Returns error and drops reference to input namei data on failure.
22031da177e4SLinus Torvalds  */
22046de88d72SAl Viro static int link_path_walk(const char *name, struct nameidata *nd)
22051da177e4SLinus Torvalds {
2206d8d4611aSAl Viro 	int depth = 0; // depth <= nd->depth
22071da177e4SLinus Torvalds 	int err;
22081da177e4SLinus Torvalds 
2209b4c03536SAl Viro 	nd->last_type = LAST_ROOT;
2210c108837eSAl Viro 	nd->flags |= LOOKUP_PARENT;
22119b5858e9SAl Viro 	if (IS_ERR(name))
22129b5858e9SAl Viro 		return PTR_ERR(name);
22131da177e4SLinus Torvalds 	while (*name=='/')
22141da177e4SLinus Torvalds 		name++;
22151a97d899SAl Viro 	if (!*name) {
22161a97d899SAl Viro 		nd->dir_mode = 0; // short-circuit the 'hardening' idiocy
22179e18f10aSAl Viro 		return 0;
22181a97d899SAl Viro 	}
22191da177e4SLinus Torvalds 
22201da177e4SLinus Torvalds 	/* At this point we know we have a real path component. */
22211da177e4SLinus Torvalds 	for(;;) {
2222549c7297SChristian Brauner 		struct user_namespace *mnt_userns;
222392d27016SAl Viro 		const char *link;
2224d6bb3e90SLinus Torvalds 		u64 hash_len;
2225fe479a58SAl Viro 		int type;
22261da177e4SLinus Torvalds 
2227549c7297SChristian Brauner 		mnt_userns = mnt_user_ns(nd->path.mnt);
2228549c7297SChristian Brauner 		err = may_lookup(mnt_userns, nd);
22291da177e4SLinus Torvalds 		if (err)
22303595e234SAl Viro 			return err;
22311da177e4SLinus Torvalds 
22328387ff25SLinus Torvalds 		hash_len = hash_name(nd->path.dentry, name);
22331da177e4SLinus Torvalds 
2234fe479a58SAl Viro 		type = LAST_NORM;
2235d6bb3e90SLinus Torvalds 		if (name[0] == '.') switch (hashlen_len(hash_len)) {
2236fe479a58SAl Viro 			case 2:
2237200e9ef7SLinus Torvalds 				if (name[1] == '.') {
2238fe479a58SAl Viro 					type = LAST_DOTDOT;
2239bcba1e7dSAl Viro 					nd->state |= ND_JUMPED;
224016c2cd71SAl Viro 				}
2241fe479a58SAl Viro 				break;
2242fe479a58SAl Viro 			case 1:
2243fe479a58SAl Viro 				type = LAST_DOT;
2244fe479a58SAl Viro 		}
22455a202bcdSAl Viro 		if (likely(type == LAST_NORM)) {
22465a202bcdSAl Viro 			struct dentry *parent = nd->path.dentry;
2247bcba1e7dSAl Viro 			nd->state &= ~ND_JUMPED;
22485a202bcdSAl Viro 			if (unlikely(parent->d_flags & DCACHE_OP_HASH)) {
2249a060dc50SJames Hogan 				struct qstr this = { { .hash_len = hash_len }, .name = name };
2250da53be12SLinus Torvalds 				err = parent->d_op->d_hash(parent, &this);
22515a202bcdSAl Viro 				if (err < 0)
22523595e234SAl Viro 					return err;
2253d6bb3e90SLinus Torvalds 				hash_len = this.hash_len;
2254d6bb3e90SLinus Torvalds 				name = this.name;
22555a202bcdSAl Viro 			}
22565a202bcdSAl Viro 		}
2257fe479a58SAl Viro 
2258d6bb3e90SLinus Torvalds 		nd->last.hash_len = hash_len;
2259d6bb3e90SLinus Torvalds 		nd->last.name = name;
22605f4a6a69SAl Viro 		nd->last_type = type;
22615f4a6a69SAl Viro 
2262d6bb3e90SLinus Torvalds 		name += hashlen_len(hash_len);
2263d6bb3e90SLinus Torvalds 		if (!*name)
2264bdf6cbf1SAl Viro 			goto OK;
2265200e9ef7SLinus Torvalds 		/*
2266200e9ef7SLinus Torvalds 		 * If it wasn't NUL, we know it was '/'. Skip that
2267200e9ef7SLinus Torvalds 		 * slash, and continue until no more slashes.
2268200e9ef7SLinus Torvalds 		 */
2269200e9ef7SLinus Torvalds 		do {
2270d6bb3e90SLinus Torvalds 			name++;
2271d6bb3e90SLinus Torvalds 		} while (unlikely(*name == '/'));
22728620c238SAl Viro 		if (unlikely(!*name)) {
22738620c238SAl Viro OK:
2274d8d4611aSAl Viro 			/* pathname or trailing symlink, done */
2275c108837eSAl Viro 			if (!depth) {
2276549c7297SChristian Brauner 				nd->dir_uid = i_uid_into_mnt(mnt_userns, nd->inode);
22770f705953SAl Viro 				nd->dir_mode = nd->inode->i_mode;
2278c108837eSAl Viro 				nd->flags &= ~LOOKUP_PARENT;
22798620c238SAl Viro 				return 0;
2280c108837eSAl Viro 			}
22818620c238SAl Viro 			/* last component of nested symlink */
2282d8d4611aSAl Viro 			name = nd->stack[--depth].name;
22838c4efe22SAl Viro 			link = walk_component(nd, 0);
22841c4ff1a8SAl Viro 		} else {
22851c4ff1a8SAl Viro 			/* not the last component */
22868c4efe22SAl Viro 			link = walk_component(nd, WALK_MORE);
22878620c238SAl Viro 		}
228892d27016SAl Viro 		if (unlikely(link)) {
228992d27016SAl Viro 			if (IS_ERR(link))
229092d27016SAl Viro 				return PTR_ERR(link);
229192d27016SAl Viro 			/* a symlink to follow */
2292d8d4611aSAl Viro 			nd->stack[depth++].name = name;
229392d27016SAl Viro 			name = link;
22949e18f10aSAl Viro 			continue;
229548c8b0c5SAl Viro 		}
229697242f99SAl Viro 		if (unlikely(!d_can_lookup(nd->path.dentry))) {
229797242f99SAl Viro 			if (nd->flags & LOOKUP_RCU) {
2298e36cffedSJens Axboe 				if (!try_to_unlazy(nd))
229997242f99SAl Viro 					return -ECHILD;
230097242f99SAl Viro 			}
23013595e234SAl Viro 			return -ENOTDIR;
23025f4a6a69SAl Viro 		}
2303ce57dfc1SAl Viro 	}
230497242f99SAl Viro }
23051da177e4SLinus Torvalds 
2306edc2b1daSAl Viro /* must be paired with terminate_walk() */
2307c8a53ee5SAl Viro static const char *path_init(struct nameidata *nd, unsigned flags)
230831e6b01fSNick Piggin {
2309740a1678SAleksa Sarai 	int error;
2310c8a53ee5SAl Viro 	const char *s = nd->name->name;
231131e6b01fSNick Piggin 
23126c6ec2b0SJens Axboe 	/* LOOKUP_CACHED requires RCU, ask caller to retry */
23136c6ec2b0SJens Axboe 	if ((flags & (LOOKUP_RCU | LOOKUP_CACHED)) == LOOKUP_CACHED)
23146c6ec2b0SJens Axboe 		return ERR_PTR(-EAGAIN);
23156c6ec2b0SJens Axboe 
2316c0eb027eSLinus Torvalds 	if (!*s)
2317c0eb027eSLinus Torvalds 		flags &= ~LOOKUP_RCU;
2318edc2b1daSAl Viro 	if (flags & LOOKUP_RCU)
2319edc2b1daSAl Viro 		rcu_read_lock();
2320c0eb027eSLinus Torvalds 
2321bcba1e7dSAl Viro 	nd->flags = flags;
2322bcba1e7dSAl Viro 	nd->state |= ND_JUMPED;
2323ab87f9a5SAleksa Sarai 
2324ab87f9a5SAleksa Sarai 	nd->m_seq = __read_seqcount_begin(&mount_lock.seqcount);
2325ab87f9a5SAleksa Sarai 	nd->r_seq = __read_seqcount_begin(&rename_lock.seqcount);
2326ab87f9a5SAleksa Sarai 	smp_rmb();
2327ab87f9a5SAleksa Sarai 
2328bcba1e7dSAl Viro 	if (nd->state & ND_ROOT_PRESET) {
2329b18825a7SDavid Howells 		struct dentry *root = nd->root.dentry;
2330b18825a7SDavid Howells 		struct inode *inode = root->d_inode;
233193893862SAl Viro 		if (*s && unlikely(!d_can_lookup(root)))
2332368ee9baSAl Viro 			return ERR_PTR(-ENOTDIR);
23335b6ca027SAl Viro 		nd->path = nd->root;
23345b6ca027SAl Viro 		nd->inode = inode;
23355b6ca027SAl Viro 		if (flags & LOOKUP_RCU) {
2336ab87f9a5SAleksa Sarai 			nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
23378f47a016SAl Viro 			nd->root_seq = nd->seq;
23385b6ca027SAl Viro 		} else {
23395b6ca027SAl Viro 			path_get(&nd->path);
23405b6ca027SAl Viro 		}
2341368ee9baSAl Viro 		return s;
23425b6ca027SAl Viro 	}
23435b6ca027SAl Viro 
234431e6b01fSNick Piggin 	nd->root.mnt = NULL;
234531e6b01fSNick Piggin 
23468db52c7eSAleksa Sarai 	/* Absolute pathname -- fetch the root (LOOKUP_IN_ROOT uses nd->dfd). */
23478db52c7eSAleksa Sarai 	if (*s == '/' && !(flags & LOOKUP_IN_ROOT)) {
2348740a1678SAleksa Sarai 		error = nd_jump_root(nd);
2349740a1678SAleksa Sarai 		if (unlikely(error))
2350740a1678SAleksa Sarai 			return ERR_PTR(error);
2351ef55d917SAl Viro 		return s;
23528db52c7eSAleksa Sarai 	}
23538db52c7eSAleksa Sarai 
23548db52c7eSAleksa Sarai 	/* Relative pathname -- get the starting-point it is relative to. */
23558db52c7eSAleksa Sarai 	if (nd->dfd == AT_FDCWD) {
2356e41f7d4eSAl Viro 		if (flags & LOOKUP_RCU) {
235731e6b01fSNick Piggin 			struct fs_struct *fs = current->fs;
2358c28cc364SNick Piggin 			unsigned seq;
235931e6b01fSNick Piggin 
2360c28cc364SNick Piggin 			do {
2361c28cc364SNick Piggin 				seq = read_seqcount_begin(&fs->seq);
236231e6b01fSNick Piggin 				nd->path = fs->pwd;
2363ef55d917SAl Viro 				nd->inode = nd->path.dentry->d_inode;
2364c28cc364SNick Piggin 				nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
2365c28cc364SNick Piggin 			} while (read_seqcount_retry(&fs->seq, seq));
2366e41f7d4eSAl Viro 		} else {
2367e41f7d4eSAl Viro 			get_fs_pwd(current->fs, &nd->path);
2368ef55d917SAl Viro 			nd->inode = nd->path.dentry->d_inode;
2369e41f7d4eSAl Viro 		}
237031e6b01fSNick Piggin 	} else {
2371582aa64aSJeff Layton 		/* Caller must check execute permissions on the starting path component */
2372c8a53ee5SAl Viro 		struct fd f = fdget_raw(nd->dfd);
237331e6b01fSNick Piggin 		struct dentry *dentry;
237431e6b01fSNick Piggin 
23752903ff01SAl Viro 		if (!f.file)
2376368ee9baSAl Viro 			return ERR_PTR(-EBADF);
237731e6b01fSNick Piggin 
23782903ff01SAl Viro 		dentry = f.file->f_path.dentry;
237931e6b01fSNick Piggin 
2380edc2b1daSAl Viro 		if (*s && unlikely(!d_can_lookup(dentry))) {
23812903ff01SAl Viro 			fdput(f);
2382368ee9baSAl Viro 			return ERR_PTR(-ENOTDIR);
2383f52e0c11SAl Viro 		}
23842903ff01SAl Viro 
23852903ff01SAl Viro 		nd->path = f.file->f_path;
2386e41f7d4eSAl Viro 		if (flags & LOOKUP_RCU) {
238734a26b99SAl Viro 			nd->inode = nd->path.dentry->d_inode;
238834a26b99SAl Viro 			nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
23895590ff0dSUlrich Drepper 		} else {
23902903ff01SAl Viro 			path_get(&nd->path);
239134a26b99SAl Viro 			nd->inode = nd->path.dentry->d_inode;
23921da177e4SLinus Torvalds 		}
239334a26b99SAl Viro 		fdput(f);
2394e41f7d4eSAl Viro 	}
23958db52c7eSAleksa Sarai 
2396adb21d2bSAleksa Sarai 	/* For scoped-lookups we need to set the root to the dirfd as well. */
2397adb21d2bSAleksa Sarai 	if (flags & LOOKUP_IS_SCOPED) {
2398adb21d2bSAleksa Sarai 		nd->root = nd->path;
2399adb21d2bSAleksa Sarai 		if (flags & LOOKUP_RCU) {
2400adb21d2bSAleksa Sarai 			nd->root_seq = nd->seq;
2401adb21d2bSAleksa Sarai 		} else {
2402adb21d2bSAleksa Sarai 			path_get(&nd->root);
2403bcba1e7dSAl Viro 			nd->state |= ND_ROOT_GRABBED;
2404adb21d2bSAleksa Sarai 		}
2405adb21d2bSAleksa Sarai 	}
2406adb21d2bSAleksa Sarai 	return s;
24079b4a9b14SAl Viro }
24089b4a9b14SAl Viro 
24091ccac622SAl Viro static inline const char *lookup_last(struct nameidata *nd)
241095fa25d9SAl Viro {
2411bd92d7feSAl Viro 	if (nd->last_type == LAST_NORM && nd->last.name[nd->last.len])
2412bd92d7feSAl Viro 		nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
2413bd92d7feSAl Viro 
2414c108837eSAl Viro 	return walk_component(nd, WALK_TRAILING);
2415bd92d7feSAl Viro }
2416bd92d7feSAl Viro 
24174f757f3cSAl Viro static int handle_lookup_down(struct nameidata *nd)
24184f757f3cSAl Viro {
2419c153007bSAl Viro 	if (!(nd->flags & LOOKUP_RCU))
2420db3c9adeSAl Viro 		dget(nd->path.dentry);
2421b0417d2cSAl Viro 	return PTR_ERR(step_into(nd, WALK_NOFOLLOW,
2422b0417d2cSAl Viro 			nd->path.dentry, nd->inode, nd->seq));
24234f757f3cSAl Viro }
24244f757f3cSAl Viro 
24259b4a9b14SAl Viro /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
2426c8a53ee5SAl Viro static int path_lookupat(struct nameidata *nd, unsigned flags, struct path *path)
24279b4a9b14SAl Viro {
2428c8a53ee5SAl Viro 	const char *s = path_init(nd, flags);
2429bd92d7feSAl Viro 	int err;
243031e6b01fSNick Piggin 
24319b5858e9SAl Viro 	if (unlikely(flags & LOOKUP_DOWN) && !IS_ERR(s)) {
24324f757f3cSAl Viro 		err = handle_lookup_down(nd);
24335f336e72SAl Viro 		if (unlikely(err < 0))
24345f336e72SAl Viro 			s = ERR_PTR(err);
24354f757f3cSAl Viro 	}
24364f757f3cSAl Viro 
24371ccac622SAl Viro 	while (!(err = link_path_walk(s, nd)) &&
24381ccac622SAl Viro 	       (s = lookup_last(nd)) != NULL)
24391ccac622SAl Viro 		;
24404f0ed93fSAl Viro 	if (!err && unlikely(nd->flags & LOOKUP_MOUNTPOINT)) {
24414f0ed93fSAl Viro 		err = handle_lookup_down(nd);
2442bcba1e7dSAl Viro 		nd->state &= ~ND_JUMPED; // no d_weak_revalidate(), please...
24434f0ed93fSAl Viro 	}
24449f1fafeeSAl Viro 	if (!err)
24459f1fafeeSAl Viro 		err = complete_walk(nd);
2446bd92d7feSAl Viro 
2447deb106c6SAl Viro 	if (!err && nd->flags & LOOKUP_DIRECTORY)
2448deb106c6SAl Viro 		if (!d_can_lookup(nd->path.dentry))
2449bd23a539SAl Viro 			err = -ENOTDIR;
2450625b6d10SAl Viro 	if (!err) {
2451625b6d10SAl Viro 		*path = nd->path;
2452625b6d10SAl Viro 		nd->path.mnt = NULL;
2453625b6d10SAl Viro 		nd->path.dentry = NULL;
2454625b6d10SAl Viro 	}
2455deb106c6SAl Viro 	terminate_walk(nd);
2456bd92d7feSAl Viro 	return err;
245731e6b01fSNick Piggin }
245831e6b01fSNick Piggin 
245931d921c7SDavid Howells int filename_lookup(int dfd, struct filename *name, unsigned flags,
24609ad1aaa6SAl Viro 		    struct path *path, struct path *root)
2461873f1eedSJeff Layton {
2462894bc8c4SAl Viro 	int retval;
24639883d185SAl Viro 	struct nameidata nd;
2464abc9f5beSAl Viro 	if (IS_ERR(name))
2465abc9f5beSAl Viro 		return PTR_ERR(name);
246606422964SAl Viro 	set_nameidata(&nd, dfd, name, root);
2467c8a53ee5SAl Viro 	retval = path_lookupat(&nd, flags | LOOKUP_RCU, path);
2468873f1eedSJeff Layton 	if (unlikely(retval == -ECHILD))
2469c8a53ee5SAl Viro 		retval = path_lookupat(&nd, flags, path);
2470873f1eedSJeff Layton 	if (unlikely(retval == -ESTALE))
2471c8a53ee5SAl Viro 		retval = path_lookupat(&nd, flags | LOOKUP_REVAL, path);
2472873f1eedSJeff Layton 
2473873f1eedSJeff Layton 	if (likely(!retval))
2474161aff1dSAl Viro 		audit_inode(name, path->dentry,
2475161aff1dSAl Viro 			    flags & LOOKUP_MOUNTPOINT ? AUDIT_INODE_NOEVAL : 0);
24769883d185SAl Viro 	restore_nameidata();
2477e4bd1c1aSAl Viro 	putname(name);
2478873f1eedSJeff Layton 	return retval;
2479873f1eedSJeff Layton }
2480873f1eedSJeff Layton 
24818bcb77faSAl Viro /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
2482c8a53ee5SAl Viro static int path_parentat(struct nameidata *nd, unsigned flags,
2483391172c4SAl Viro 				struct path *parent)
24848bcb77faSAl Viro {
2485c8a53ee5SAl Viro 	const char *s = path_init(nd, flags);
24869b5858e9SAl Viro 	int err = link_path_walk(s, nd);
24878bcb77faSAl Viro 	if (!err)
24888bcb77faSAl Viro 		err = complete_walk(nd);
2489391172c4SAl Viro 	if (!err) {
2490391172c4SAl Viro 		*parent = nd->path;
2491391172c4SAl Viro 		nd->path.mnt = NULL;
2492391172c4SAl Viro 		nd->path.dentry = NULL;
2493391172c4SAl Viro 	}
2494deb106c6SAl Viro 	terminate_walk(nd);
24958bcb77faSAl Viro 	return err;
24968bcb77faSAl Viro }
24978bcb77faSAl Viro 
24985c31b6ceSAl Viro static struct filename *filename_parentat(int dfd, struct filename *name,
2499391172c4SAl Viro 				unsigned int flags, struct path *parent,
2500391172c4SAl Viro 				struct qstr *last, int *type)
25018bcb77faSAl Viro {
25028bcb77faSAl Viro 	int retval;
25039883d185SAl Viro 	struct nameidata nd;
25048bcb77faSAl Viro 
25055c31b6ceSAl Viro 	if (IS_ERR(name))
25065c31b6ceSAl Viro 		return name;
250706422964SAl Viro 	set_nameidata(&nd, dfd, name, NULL);
2508c8a53ee5SAl Viro 	retval = path_parentat(&nd, flags | LOOKUP_RCU, parent);
25098bcb77faSAl Viro 	if (unlikely(retval == -ECHILD))
2510c8a53ee5SAl Viro 		retval = path_parentat(&nd, flags, parent);
25118bcb77faSAl Viro 	if (unlikely(retval == -ESTALE))
2512c8a53ee5SAl Viro 		retval = path_parentat(&nd, flags | LOOKUP_REVAL, parent);
2513391172c4SAl Viro 	if (likely(!retval)) {
2514391172c4SAl Viro 		*last = nd.last;
2515391172c4SAl Viro 		*type = nd.last_type;
2516c9b07eabSAl Viro 		audit_inode(name, parent->dentry, AUDIT_INODE_PARENT);
25175c31b6ceSAl Viro 	} else {
25185c31b6ceSAl Viro 		putname(name);
25195c31b6ceSAl Viro 		name = ERR_PTR(retval);
2520391172c4SAl Viro 	}
25219883d185SAl Viro 	restore_nameidata();
25225c31b6ceSAl Viro 	return name;
25238bcb77faSAl Viro }
25248bcb77faSAl Viro 
252579714f72SAl Viro /* does lookup, returns the object with parent locked */
252679714f72SAl Viro struct dentry *kern_path_locked(const char *name, struct path *path)
25275590ff0dSUlrich Drepper {
25285c31b6ceSAl Viro 	struct filename *filename;
25295c31b6ceSAl Viro 	struct dentry *d;
2530391172c4SAl Viro 	struct qstr last;
2531391172c4SAl Viro 	int type;
253251689104SPaul Moore 
25335c31b6ceSAl Viro 	filename = filename_parentat(AT_FDCWD, getname_kernel(name), 0, path,
25345c31b6ceSAl Viro 				    &last, &type);
253551689104SPaul Moore 	if (IS_ERR(filename))
253651689104SPaul Moore 		return ERR_CAST(filename);
25375c31b6ceSAl Viro 	if (unlikely(type != LAST_NORM)) {
2538391172c4SAl Viro 		path_put(path);
25395c31b6ceSAl Viro 		putname(filename);
25405c31b6ceSAl Viro 		return ERR_PTR(-EINVAL);
254179714f72SAl Viro 	}
25425955102cSAl Viro 	inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
2543391172c4SAl Viro 	d = __lookup_hash(&last, path->dentry, 0);
254479714f72SAl Viro 	if (IS_ERR(d)) {
25455955102cSAl Viro 		inode_unlock(path->dentry->d_inode);
2546391172c4SAl Viro 		path_put(path);
254779714f72SAl Viro 	}
254851689104SPaul Moore 	putname(filename);
254979714f72SAl Viro 	return d;
25505590ff0dSUlrich Drepper }
25515590ff0dSUlrich Drepper 
2552d1811465SAl Viro int kern_path(const char *name, unsigned int flags, struct path *path)
2553d1811465SAl Viro {
2554abc9f5beSAl Viro 	return filename_lookup(AT_FDCWD, getname_kernel(name),
2555abc9f5beSAl Viro 			       flags, path, NULL);
2556d1811465SAl Viro }
25574d359507SAl Viro EXPORT_SYMBOL(kern_path);
2558d1811465SAl Viro 
255916f18200SJosef 'Jeff' Sipek /**
256016f18200SJosef 'Jeff' Sipek  * vfs_path_lookup - lookup a file path relative to a dentry-vfsmount pair
256116f18200SJosef 'Jeff' Sipek  * @dentry:  pointer to dentry of the base directory
256216f18200SJosef 'Jeff' Sipek  * @mnt: pointer to vfs mount of the base directory
256316f18200SJosef 'Jeff' Sipek  * @name: pointer to file name
256416f18200SJosef 'Jeff' Sipek  * @flags: lookup flags
2565e0a01249SAl Viro  * @path: pointer to struct path to fill
256616f18200SJosef 'Jeff' Sipek  */
256716f18200SJosef 'Jeff' Sipek int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt,
256816f18200SJosef 'Jeff' Sipek 		    const char *name, unsigned int flags,
2569e0a01249SAl Viro 		    struct path *path)
257016f18200SJosef 'Jeff' Sipek {
25719ad1aaa6SAl Viro 	struct path root = {.mnt = mnt, .dentry = dentry};
25729ad1aaa6SAl Viro 	/* the first argument of filename_lookup() is ignored with root */
2573abc9f5beSAl Viro 	return filename_lookup(AT_FDCWD, getname_kernel(name),
2574abc9f5beSAl Viro 			       flags , path, &root);
257516f18200SJosef 'Jeff' Sipek }
25764d359507SAl Viro EXPORT_SYMBOL(vfs_path_lookup);
257716f18200SJosef 'Jeff' Sipek 
2578*c2fd68b6SChristian Brauner static int lookup_one_common(struct user_namespace *mnt_userns,
2579*c2fd68b6SChristian Brauner 			     const char *name, struct dentry *base, int len,
2580*c2fd68b6SChristian Brauner 			     struct qstr *this)
25813c95f0dcSAl Viro {
25823c95f0dcSAl Viro 	this->name = name;
25833c95f0dcSAl Viro 	this->len = len;
25843c95f0dcSAl Viro 	this->hash = full_name_hash(base, name, len);
25853c95f0dcSAl Viro 	if (!len)
25863c95f0dcSAl Viro 		return -EACCES;
25873c95f0dcSAl Viro 
25883c95f0dcSAl Viro 	if (unlikely(name[0] == '.')) {
25893c95f0dcSAl Viro 		if (len < 2 || (len == 2 && name[1] == '.'))
25903c95f0dcSAl Viro 			return -EACCES;
25913c95f0dcSAl Viro 	}
25923c95f0dcSAl Viro 
25933c95f0dcSAl Viro 	while (len--) {
25943c95f0dcSAl Viro 		unsigned int c = *(const unsigned char *)name++;
25953c95f0dcSAl Viro 		if (c == '/' || c == '\0')
25963c95f0dcSAl Viro 			return -EACCES;
25973c95f0dcSAl Viro 	}
25983c95f0dcSAl Viro 	/*
25993c95f0dcSAl Viro 	 * See if the low-level filesystem might want
26003c95f0dcSAl Viro 	 * to use its own hash..
26013c95f0dcSAl Viro 	 */
26023c95f0dcSAl Viro 	if (base->d_flags & DCACHE_OP_HASH) {
26033c95f0dcSAl Viro 		int err = base->d_op->d_hash(base, this);
26043c95f0dcSAl Viro 		if (err < 0)
26053c95f0dcSAl Viro 			return err;
26063c95f0dcSAl Viro 	}
26073c95f0dcSAl Viro 
2608*c2fd68b6SChristian Brauner 	return inode_permission(mnt_userns, base->d_inode, MAY_EXEC);
26093c95f0dcSAl Viro }
26103c95f0dcSAl Viro 
2611eead1911SChristoph Hellwig /**
26120da0b7fdSDavid Howells  * try_lookup_one_len - filesystem helper to lookup single pathname component
26130da0b7fdSDavid Howells  * @name:	pathname component to lookup
26140da0b7fdSDavid Howells  * @base:	base directory to lookup from
26150da0b7fdSDavid Howells  * @len:	maximum length @len should be interpreted to
26160da0b7fdSDavid Howells  *
26170da0b7fdSDavid Howells  * Look up a dentry by name in the dcache, returning NULL if it does not
26180da0b7fdSDavid Howells  * currently exist.  The function does not try to create a dentry.
26190da0b7fdSDavid Howells  *
26200da0b7fdSDavid Howells  * Note that this routine is purely a helper for filesystem usage and should
26210da0b7fdSDavid Howells  * not be called by generic code.
26220da0b7fdSDavid Howells  *
26230da0b7fdSDavid Howells  * The caller must hold base->i_mutex.
26240da0b7fdSDavid Howells  */
26250da0b7fdSDavid Howells struct dentry *try_lookup_one_len(const char *name, struct dentry *base, int len)
26260da0b7fdSDavid Howells {
26270da0b7fdSDavid Howells 	struct qstr this;
26280da0b7fdSDavid Howells 	int err;
26290da0b7fdSDavid Howells 
26300da0b7fdSDavid Howells 	WARN_ON_ONCE(!inode_is_locked(base->d_inode));
26310da0b7fdSDavid Howells 
2632*c2fd68b6SChristian Brauner 	err = lookup_one_common(&init_user_ns, name, base, len, &this);
26330da0b7fdSDavid Howells 	if (err)
26340da0b7fdSDavid Howells 		return ERR_PTR(err);
26350da0b7fdSDavid Howells 
26360da0b7fdSDavid Howells 	return lookup_dcache(&this, base, 0);
26370da0b7fdSDavid Howells }
26380da0b7fdSDavid Howells EXPORT_SYMBOL(try_lookup_one_len);
26390da0b7fdSDavid Howells 
26400da0b7fdSDavid Howells /**
2641a6b91919SRandy Dunlap  * lookup_one_len - filesystem helper to lookup single pathname component
2642eead1911SChristoph Hellwig  * @name:	pathname component to lookup
2643eead1911SChristoph Hellwig  * @base:	base directory to lookup from
2644eead1911SChristoph Hellwig  * @len:	maximum length @len should be interpreted to
2645eead1911SChristoph Hellwig  *
2646a6b91919SRandy Dunlap  * Note that this routine is purely a helper for filesystem usage and should
26479e7543e9SAl Viro  * not be called by generic code.
2648bbddca8eSNeilBrown  *
2649bbddca8eSNeilBrown  * The caller must hold base->i_mutex.
2650eead1911SChristoph Hellwig  */
2651057f6c01SJames Morris struct dentry *lookup_one_len(const char *name, struct dentry *base, int len)
2652057f6c01SJames Morris {
26538613a209SAl Viro 	struct dentry *dentry;
2654057f6c01SJames Morris 	struct qstr this;
2655cda309deSMiklos Szeredi 	int err;
2656057f6c01SJames Morris 
26575955102cSAl Viro 	WARN_ON_ONCE(!inode_is_locked(base->d_inode));
26582f9092e1SDavid Woodhouse 
2659*c2fd68b6SChristian Brauner 	err = lookup_one_common(&init_user_ns, name, base, len, &this);
2660cda309deSMiklos Szeredi 	if (err)
2661cda309deSMiklos Szeredi 		return ERR_PTR(err);
2662cda309deSMiklos Szeredi 
26638613a209SAl Viro 	dentry = lookup_dcache(&this, base, 0);
26648613a209SAl Viro 	return dentry ? dentry : __lookup_slow(&this, base, 0);
2665057f6c01SJames Morris }
26664d359507SAl Viro EXPORT_SYMBOL(lookup_one_len);
2667057f6c01SJames Morris 
2668bbddca8eSNeilBrown /**
2669*c2fd68b6SChristian Brauner  * lookup_one - filesystem helper to lookup single pathname component
2670*c2fd68b6SChristian Brauner  * @mnt_userns:	user namespace of the mount the lookup is performed from
2671*c2fd68b6SChristian Brauner  * @name:	pathname component to lookup
2672*c2fd68b6SChristian Brauner  * @base:	base directory to lookup from
2673*c2fd68b6SChristian Brauner  * @len:	maximum length @len should be interpreted to
2674*c2fd68b6SChristian Brauner  *
2675*c2fd68b6SChristian Brauner  * Note that this routine is purely a helper for filesystem usage and should
2676*c2fd68b6SChristian Brauner  * not be called by generic code.
2677*c2fd68b6SChristian Brauner  *
2678*c2fd68b6SChristian Brauner  * The caller must hold base->i_mutex.
2679*c2fd68b6SChristian Brauner  */
2680*c2fd68b6SChristian Brauner struct dentry *lookup_one(struct user_namespace *mnt_userns, const char *name,
2681*c2fd68b6SChristian Brauner 			  struct dentry *base, int len)
2682*c2fd68b6SChristian Brauner {
2683*c2fd68b6SChristian Brauner 	struct dentry *dentry;
2684*c2fd68b6SChristian Brauner 	struct qstr this;
2685*c2fd68b6SChristian Brauner 	int err;
2686*c2fd68b6SChristian Brauner 
2687*c2fd68b6SChristian Brauner 	WARN_ON_ONCE(!inode_is_locked(base->d_inode));
2688*c2fd68b6SChristian Brauner 
2689*c2fd68b6SChristian Brauner 	err = lookup_one_common(mnt_userns, name, base, len, &this);
2690*c2fd68b6SChristian Brauner 	if (err)
2691*c2fd68b6SChristian Brauner 		return ERR_PTR(err);
2692*c2fd68b6SChristian Brauner 
2693*c2fd68b6SChristian Brauner 	dentry = lookup_dcache(&this, base, 0);
2694*c2fd68b6SChristian Brauner 	return dentry ? dentry : __lookup_slow(&this, base, 0);
2695*c2fd68b6SChristian Brauner }
2696*c2fd68b6SChristian Brauner EXPORT_SYMBOL(lookup_one);
2697*c2fd68b6SChristian Brauner 
2698*c2fd68b6SChristian Brauner /**
2699bbddca8eSNeilBrown  * lookup_one_len_unlocked - filesystem helper to lookup single pathname component
2700bbddca8eSNeilBrown  * @name:	pathname component to lookup
2701bbddca8eSNeilBrown  * @base:	base directory to lookup from
2702bbddca8eSNeilBrown  * @len:	maximum length @len should be interpreted to
2703bbddca8eSNeilBrown  *
2704bbddca8eSNeilBrown  * Note that this routine is purely a helper for filesystem usage and should
2705bbddca8eSNeilBrown  * not be called by generic code.
2706bbddca8eSNeilBrown  *
2707bbddca8eSNeilBrown  * Unlike lookup_one_len, it should be called without the parent
2708bbddca8eSNeilBrown  * i_mutex held, and will take the i_mutex itself if necessary.
2709bbddca8eSNeilBrown  */
2710bbddca8eSNeilBrown struct dentry *lookup_one_len_unlocked(const char *name,
2711bbddca8eSNeilBrown 				       struct dentry *base, int len)
2712bbddca8eSNeilBrown {
2713bbddca8eSNeilBrown 	struct qstr this;
2714bbddca8eSNeilBrown 	int err;
271520d00ee8SLinus Torvalds 	struct dentry *ret;
2716bbddca8eSNeilBrown 
2717*c2fd68b6SChristian Brauner 	err = lookup_one_common(&init_user_ns, name, base, len, &this);
2718bbddca8eSNeilBrown 	if (err)
2719bbddca8eSNeilBrown 		return ERR_PTR(err);
2720bbddca8eSNeilBrown 
272120d00ee8SLinus Torvalds 	ret = lookup_dcache(&this, base, 0);
272220d00ee8SLinus Torvalds 	if (!ret)
272320d00ee8SLinus Torvalds 		ret = lookup_slow(&this, base, 0);
272420d00ee8SLinus Torvalds 	return ret;
2725bbddca8eSNeilBrown }
2726bbddca8eSNeilBrown EXPORT_SYMBOL(lookup_one_len_unlocked);
2727bbddca8eSNeilBrown 
27286c2d4798SAl Viro /*
27296c2d4798SAl Viro  * Like lookup_one_len_unlocked(), except that it yields ERR_PTR(-ENOENT)
27306c2d4798SAl Viro  * on negatives.  Returns known positive or ERR_PTR(); that's what
27316c2d4798SAl Viro  * most of the users want.  Note that pinned negative with unlocked parent
27326c2d4798SAl Viro  * _can_ become positive at any time, so callers of lookup_one_len_unlocked()
27336c2d4798SAl Viro  * need to be very careful; pinned positives have ->d_inode stable, so
27346c2d4798SAl Viro  * this one avoids such problems.
27356c2d4798SAl Viro  */
27366c2d4798SAl Viro struct dentry *lookup_positive_unlocked(const char *name,
27376c2d4798SAl Viro 				       struct dentry *base, int len)
27386c2d4798SAl Viro {
27396c2d4798SAl Viro 	struct dentry *ret = lookup_one_len_unlocked(name, base, len);
27402fa6b1e0SAl Viro 	if (!IS_ERR(ret) && d_flags_negative(smp_load_acquire(&ret->d_flags))) {
27416c2d4798SAl Viro 		dput(ret);
27426c2d4798SAl Viro 		ret = ERR_PTR(-ENOENT);
27436c2d4798SAl Viro 	}
27446c2d4798SAl Viro 	return ret;
27456c2d4798SAl Viro }
27466c2d4798SAl Viro EXPORT_SYMBOL(lookup_positive_unlocked);
27476c2d4798SAl Viro 
2748eedf265aSEric W. Biederman #ifdef CONFIG_UNIX98_PTYS
2749eedf265aSEric W. Biederman int path_pts(struct path *path)
2750eedf265aSEric W. Biederman {
2751eedf265aSEric W. Biederman 	/* Find something mounted on "pts" in the same directory as
2752eedf265aSEric W. Biederman 	 * the input path.
2753eedf265aSEric W. Biederman 	 */
2754a6a7eb76SAl Viro 	struct dentry *parent = dget_parent(path->dentry);
2755a6a7eb76SAl Viro 	struct dentry *child;
275619f6028aSAl Viro 	struct qstr this = QSTR_INIT("pts", 3);
2757eedf265aSEric W. Biederman 
2758a6a7eb76SAl Viro 	if (unlikely(!path_connected(path->mnt, parent))) {
2759a6a7eb76SAl Viro 		dput(parent);
276063b27720SAl Viro 		return -ENOENT;
2761a6a7eb76SAl Viro 	}
276263b27720SAl Viro 	dput(path->dentry);
276363b27720SAl Viro 	path->dentry = parent;
2764eedf265aSEric W. Biederman 	child = d_hash_and_lookup(parent, &this);
2765eedf265aSEric W. Biederman 	if (!child)
2766eedf265aSEric W. Biederman 		return -ENOENT;
2767eedf265aSEric W. Biederman 
2768eedf265aSEric W. Biederman 	path->dentry = child;
2769eedf265aSEric W. Biederman 	dput(parent);
277019f6028aSAl Viro 	follow_down(path);
2771eedf265aSEric W. Biederman 	return 0;
2772eedf265aSEric W. Biederman }
2773eedf265aSEric W. Biederman #endif
2774eedf265aSEric W. Biederman 
27751fa1e7f6SAndy Whitcroft int user_path_at_empty(int dfd, const char __user *name, unsigned flags,
27761fa1e7f6SAndy Whitcroft 		 struct path *path, int *empty)
27771da177e4SLinus Torvalds {
2778abc9f5beSAl Viro 	return filename_lookup(dfd, getname_flags(name, flags, empty),
2779abc9f5beSAl Viro 			       flags, path, NULL);
27801da177e4SLinus Torvalds }
2781b853a161SAl Viro EXPORT_SYMBOL(user_path_at_empty);
27821fa1e7f6SAndy Whitcroft 
2783ba73d987SChristian Brauner int __check_sticky(struct user_namespace *mnt_userns, struct inode *dir,
2784ba73d987SChristian Brauner 		   struct inode *inode)
27851da177e4SLinus Torvalds {
27868e96e3b7SEric W. Biederman 	kuid_t fsuid = current_fsuid();
2787da9592edSDavid Howells 
2788ba73d987SChristian Brauner 	if (uid_eq(i_uid_into_mnt(mnt_userns, inode), fsuid))
27891da177e4SLinus Torvalds 		return 0;
2790ba73d987SChristian Brauner 	if (uid_eq(i_uid_into_mnt(mnt_userns, dir), fsuid))
27911da177e4SLinus Torvalds 		return 0;
2792ba73d987SChristian Brauner 	return !capable_wrt_inode_uidgid(mnt_userns, inode, CAP_FOWNER);
27931da177e4SLinus Torvalds }
2794cbdf35bcSMiklos Szeredi EXPORT_SYMBOL(__check_sticky);
27951da177e4SLinus Torvalds 
27961da177e4SLinus Torvalds /*
27971da177e4SLinus Torvalds  *	Check whether we can remove a link victim from directory dir, check
27981da177e4SLinus Torvalds  *  whether the type of victim is right.
27991da177e4SLinus Torvalds  *  1. We can't do it if dir is read-only (done in permission())
28001da177e4SLinus Torvalds  *  2. We should have write and exec permissions on dir
28011da177e4SLinus Torvalds  *  3. We can't remove anything from append-only dir
28021da177e4SLinus Torvalds  *  4. We can't do anything with immutable dir (done in permission())
28031da177e4SLinus Torvalds  *  5. If the sticky bit on dir is set we should either
28041da177e4SLinus Torvalds  *	a. be owner of dir, or
28051da177e4SLinus Torvalds  *	b. be owner of victim, or
28061da177e4SLinus Torvalds  *	c. have CAP_FOWNER capability
28071da177e4SLinus Torvalds  *  6. If the victim is append-only or immutable we can't do antyhing with
28081da177e4SLinus Torvalds  *     links pointing to it.
28090bd23d09SEric W. Biederman  *  7. If the victim has an unknown uid or gid we can't change the inode.
28100bd23d09SEric W. Biederman  *  8. If we were asked to remove a directory and victim isn't one - ENOTDIR.
28110bd23d09SEric W. Biederman  *  9. If we were asked to remove a non-directory and victim isn't one - EISDIR.
28120bd23d09SEric W. Biederman  * 10. We can't remove a root or mountpoint.
28130bd23d09SEric W. Biederman  * 11. We don't allow removal of NFS sillyrenamed files; it's handled by
28141da177e4SLinus Torvalds  *     nfs_async_unlink().
28151da177e4SLinus Torvalds  */
2816ba73d987SChristian Brauner static int may_delete(struct user_namespace *mnt_userns, struct inode *dir,
2817ba73d987SChristian Brauner 		      struct dentry *victim, bool isdir)
28181da177e4SLinus Torvalds {
281963afdfc7SDavid Howells 	struct inode *inode = d_backing_inode(victim);
28201da177e4SLinus Torvalds 	int error;
28211da177e4SLinus Torvalds 
2822b18825a7SDavid Howells 	if (d_is_negative(victim))
28231da177e4SLinus Torvalds 		return -ENOENT;
2824b18825a7SDavid Howells 	BUG_ON(!inode);
28251da177e4SLinus Torvalds 
28261da177e4SLinus Torvalds 	BUG_ON(victim->d_parent->d_inode != dir);
2827593d1ce8SEric W. Biederman 
2828593d1ce8SEric W. Biederman 	/* Inode writeback is not safe when the uid or gid are invalid. */
2829ba73d987SChristian Brauner 	if (!uid_valid(i_uid_into_mnt(mnt_userns, inode)) ||
2830ba73d987SChristian Brauner 	    !gid_valid(i_gid_into_mnt(mnt_userns, inode)))
2831593d1ce8SEric W. Biederman 		return -EOVERFLOW;
2832593d1ce8SEric W. Biederman 
28334fa6b5ecSJeff Layton 	audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
28341da177e4SLinus Torvalds 
2835ba73d987SChristian Brauner 	error = inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
28361da177e4SLinus Torvalds 	if (error)
28371da177e4SLinus Torvalds 		return error;
28381da177e4SLinus Torvalds 	if (IS_APPEND(dir))
28391da177e4SLinus Torvalds 		return -EPERM;
2840b18825a7SDavid Howells 
2841ba73d987SChristian Brauner 	if (check_sticky(mnt_userns, dir, inode) || IS_APPEND(inode) ||
2842ba73d987SChristian Brauner 	    IS_IMMUTABLE(inode) || IS_SWAPFILE(inode) ||
2843ba73d987SChristian Brauner 	    HAS_UNMAPPED_ID(mnt_userns, inode))
28441da177e4SLinus Torvalds 		return -EPERM;
28451da177e4SLinus Torvalds 	if (isdir) {
284644b1d530SMiklos Szeredi 		if (!d_is_dir(victim))
28471da177e4SLinus Torvalds 			return -ENOTDIR;
28481da177e4SLinus Torvalds 		if (IS_ROOT(victim))
28491da177e4SLinus Torvalds 			return -EBUSY;
285044b1d530SMiklos Szeredi 	} else if (d_is_dir(victim))
28511da177e4SLinus Torvalds 		return -EISDIR;
28521da177e4SLinus Torvalds 	if (IS_DEADDIR(dir))
28531da177e4SLinus Torvalds 		return -ENOENT;
28541da177e4SLinus Torvalds 	if (victim->d_flags & DCACHE_NFSFS_RENAMED)
28551da177e4SLinus Torvalds 		return -EBUSY;
28561da177e4SLinus Torvalds 	return 0;
28571da177e4SLinus Torvalds }
28581da177e4SLinus Torvalds 
28591da177e4SLinus Torvalds /*	Check whether we can create an object with dentry child in directory
28601da177e4SLinus Torvalds  *  dir.
28611da177e4SLinus Torvalds  *  1. We can't do it if child already exists (open has special treatment for
28621da177e4SLinus Torvalds  *     this case, but since we are inlined it's OK)
28631da177e4SLinus Torvalds  *  2. We can't do it if dir is read-only (done in permission())
2864036d5236SEric W. Biederman  *  3. We can't do it if the fs can't represent the fsuid or fsgid.
2865036d5236SEric W. Biederman  *  4. We should have write and exec permissions on dir
2866036d5236SEric W. Biederman  *  5. We can't do it if dir is immutable (done in permission())
28671da177e4SLinus Torvalds  */
2868ba73d987SChristian Brauner static inline int may_create(struct user_namespace *mnt_userns,
2869ba73d987SChristian Brauner 			     struct inode *dir, struct dentry *child)
28701da177e4SLinus Torvalds {
287114e972b4SJeff Layton 	audit_inode_child(dir, child, AUDIT_TYPE_CHILD_CREATE);
28721da177e4SLinus Torvalds 	if (child->d_inode)
28731da177e4SLinus Torvalds 		return -EEXIST;
28741da177e4SLinus Torvalds 	if (IS_DEADDIR(dir))
28751da177e4SLinus Torvalds 		return -ENOENT;
28768e538913SChristian Brauner 	if (!fsuidgid_has_mapping(dir->i_sb, mnt_userns))
2877036d5236SEric W. Biederman 		return -EOVERFLOW;
28788e538913SChristian Brauner 
2879ba73d987SChristian Brauner 	return inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
28801da177e4SLinus Torvalds }
28811da177e4SLinus Torvalds 
28821da177e4SLinus Torvalds /*
28831da177e4SLinus Torvalds  * p1 and p2 should be directories on the same fs.
28841da177e4SLinus Torvalds  */
28851da177e4SLinus Torvalds struct dentry *lock_rename(struct dentry *p1, struct dentry *p2)
28861da177e4SLinus Torvalds {
28871da177e4SLinus Torvalds 	struct dentry *p;
28881da177e4SLinus Torvalds 
28891da177e4SLinus Torvalds 	if (p1 == p2) {
28905955102cSAl Viro 		inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
28911da177e4SLinus Torvalds 		return NULL;
28921da177e4SLinus Torvalds 	}
28931da177e4SLinus Torvalds 
2894fc64005cSAl Viro 	mutex_lock(&p1->d_sb->s_vfs_rename_mutex);
28951da177e4SLinus Torvalds 
2896e2761a11SOGAWA Hirofumi 	p = d_ancestor(p2, p1);
2897e2761a11SOGAWA Hirofumi 	if (p) {
28985955102cSAl Viro 		inode_lock_nested(p2->d_inode, I_MUTEX_PARENT);
28995955102cSAl Viro 		inode_lock_nested(p1->d_inode, I_MUTEX_CHILD);
29001da177e4SLinus Torvalds 		return p;
29011da177e4SLinus Torvalds 	}
29021da177e4SLinus Torvalds 
2903e2761a11SOGAWA Hirofumi 	p = d_ancestor(p1, p2);
2904e2761a11SOGAWA Hirofumi 	if (p) {
29055955102cSAl Viro 		inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
29065955102cSAl Viro 		inode_lock_nested(p2->d_inode, I_MUTEX_CHILD);
29071da177e4SLinus Torvalds 		return p;
29081da177e4SLinus Torvalds 	}
29091da177e4SLinus Torvalds 
29105955102cSAl Viro 	inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
29115955102cSAl Viro 	inode_lock_nested(p2->d_inode, I_MUTEX_PARENT2);
29121da177e4SLinus Torvalds 	return NULL;
29131da177e4SLinus Torvalds }
29144d359507SAl Viro EXPORT_SYMBOL(lock_rename);
29151da177e4SLinus Torvalds 
29161da177e4SLinus Torvalds void unlock_rename(struct dentry *p1, struct dentry *p2)
29171da177e4SLinus Torvalds {
29185955102cSAl Viro 	inode_unlock(p1->d_inode);
29191da177e4SLinus Torvalds 	if (p1 != p2) {
29205955102cSAl Viro 		inode_unlock(p2->d_inode);
2921fc64005cSAl Viro 		mutex_unlock(&p1->d_sb->s_vfs_rename_mutex);
29221da177e4SLinus Torvalds 	}
29231da177e4SLinus Torvalds }
29244d359507SAl Viro EXPORT_SYMBOL(unlock_rename);
29251da177e4SLinus Torvalds 
29266521f891SChristian Brauner /**
29276521f891SChristian Brauner  * vfs_create - create new file
29286521f891SChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
29296521f891SChristian Brauner  * @dir:	inode of @dentry
29306521f891SChristian Brauner  * @dentry:	pointer to dentry of the base directory
29316521f891SChristian Brauner  * @mode:	mode of the new file
29326521f891SChristian Brauner  * @want_excl:	whether the file must not yet exist
29336521f891SChristian Brauner  *
29346521f891SChristian Brauner  * Create a new file.
29356521f891SChristian Brauner  *
29366521f891SChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
29376521f891SChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
29386521f891SChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
29396521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
29406521f891SChristian Brauner  * raw inode simply passs init_user_ns.
29416521f891SChristian Brauner  */
29426521f891SChristian Brauner int vfs_create(struct user_namespace *mnt_userns, struct inode *dir,
29436521f891SChristian Brauner 	       struct dentry *dentry, umode_t mode, bool want_excl)
29441da177e4SLinus Torvalds {
29456521f891SChristian Brauner 	int error = may_create(mnt_userns, dir, dentry);
29461da177e4SLinus Torvalds 	if (error)
29471da177e4SLinus Torvalds 		return error;
29481da177e4SLinus Torvalds 
2949acfa4380SAl Viro 	if (!dir->i_op->create)
29501da177e4SLinus Torvalds 		return -EACCES;	/* shouldn't it be ENOSYS? */
29511da177e4SLinus Torvalds 	mode &= S_IALLUGO;
29521da177e4SLinus Torvalds 	mode |= S_IFREG;
29531da177e4SLinus Torvalds 	error = security_inode_create(dir, dentry, mode);
29541da177e4SLinus Torvalds 	if (error)
29551da177e4SLinus Torvalds 		return error;
2956549c7297SChristian Brauner 	error = dir->i_op->create(mnt_userns, dir, dentry, mode, want_excl);
2957a74574aaSStephen Smalley 	if (!error)
2958f38aa942SAmy Griffis 		fsnotify_create(dir, dentry);
29591da177e4SLinus Torvalds 	return error;
29601da177e4SLinus Torvalds }
29614d359507SAl Viro EXPORT_SYMBOL(vfs_create);
29621da177e4SLinus Torvalds 
29638e6c848eSAl Viro int vfs_mkobj(struct dentry *dentry, umode_t mode,
29648e6c848eSAl Viro 		int (*f)(struct dentry *, umode_t, void *),
29658e6c848eSAl Viro 		void *arg)
29668e6c848eSAl Viro {
29678e6c848eSAl Viro 	struct inode *dir = dentry->d_parent->d_inode;
2968ba73d987SChristian Brauner 	int error = may_create(&init_user_ns, dir, dentry);
29698e6c848eSAl Viro 	if (error)
29708e6c848eSAl Viro 		return error;
29718e6c848eSAl Viro 
29728e6c848eSAl Viro 	mode &= S_IALLUGO;
29738e6c848eSAl Viro 	mode |= S_IFREG;
29748e6c848eSAl Viro 	error = security_inode_create(dir, dentry, mode);
29758e6c848eSAl Viro 	if (error)
29768e6c848eSAl Viro 		return error;
29778e6c848eSAl Viro 	error = f(dentry, mode, arg);
29788e6c848eSAl Viro 	if (!error)
29798e6c848eSAl Viro 		fsnotify_create(dir, dentry);
29808e6c848eSAl Viro 	return error;
29818e6c848eSAl Viro }
29828e6c848eSAl Viro EXPORT_SYMBOL(vfs_mkobj);
29838e6c848eSAl Viro 
2984a2982cc9SEric W. Biederman bool may_open_dev(const struct path *path)
2985a2982cc9SEric W. Biederman {
2986a2982cc9SEric W. Biederman 	return !(path->mnt->mnt_flags & MNT_NODEV) &&
2987a2982cc9SEric W. Biederman 		!(path->mnt->mnt_sb->s_iflags & SB_I_NODEV);
2988a2982cc9SEric W. Biederman }
2989a2982cc9SEric W. Biederman 
2990ba73d987SChristian Brauner static int may_open(struct user_namespace *mnt_userns, const struct path *path,
2991ba73d987SChristian Brauner 		    int acc_mode, int flag)
29921da177e4SLinus Torvalds {
29933fb64190SChristoph Hellwig 	struct dentry *dentry = path->dentry;
29941da177e4SLinus Torvalds 	struct inode *inode = dentry->d_inode;
29951da177e4SLinus Torvalds 	int error;
29961da177e4SLinus Torvalds 
29971da177e4SLinus Torvalds 	if (!inode)
29981da177e4SLinus Torvalds 		return -ENOENT;
29991da177e4SLinus Torvalds 
3000c8fe8f30SChristoph Hellwig 	switch (inode->i_mode & S_IFMT) {
3001c8fe8f30SChristoph Hellwig 	case S_IFLNK:
30021da177e4SLinus Torvalds 		return -ELOOP;
3003c8fe8f30SChristoph Hellwig 	case S_IFDIR:
3004fc4177beSKees Cook 		if (acc_mode & MAY_WRITE)
30051da177e4SLinus Torvalds 			return -EISDIR;
3006fc4177beSKees Cook 		if (acc_mode & MAY_EXEC)
3007fc4177beSKees Cook 			return -EACCES;
3008c8fe8f30SChristoph Hellwig 		break;
3009c8fe8f30SChristoph Hellwig 	case S_IFBLK:
3010c8fe8f30SChristoph Hellwig 	case S_IFCHR:
3011a2982cc9SEric W. Biederman 		if (!may_open_dev(path))
30121da177e4SLinus Torvalds 			return -EACCES;
3013633fb6acSKees Cook 		fallthrough;
3014c8fe8f30SChristoph Hellwig 	case S_IFIFO:
3015c8fe8f30SChristoph Hellwig 	case S_IFSOCK:
3016633fb6acSKees Cook 		if (acc_mode & MAY_EXEC)
3017633fb6acSKees Cook 			return -EACCES;
30181da177e4SLinus Torvalds 		flag &= ~O_TRUNC;
3019c8fe8f30SChristoph Hellwig 		break;
30200fd338b2SKees Cook 	case S_IFREG:
30210fd338b2SKees Cook 		if ((acc_mode & MAY_EXEC) && path_noexec(path))
30220fd338b2SKees Cook 			return -EACCES;
30230fd338b2SKees Cook 		break;
30244a3fd211SDave Hansen 	}
3025b41572e9SDave Hansen 
3026ba73d987SChristian Brauner 	error = inode_permission(mnt_userns, inode, MAY_OPEN | acc_mode);
3027b41572e9SDave Hansen 	if (error)
3028b41572e9SDave Hansen 		return error;
30296146f0d5SMimi Zohar 
30301da177e4SLinus Torvalds 	/*
30311da177e4SLinus Torvalds 	 * An append-only file must be opened in append mode for writing.
30321da177e4SLinus Torvalds 	 */
30331da177e4SLinus Torvalds 	if (IS_APPEND(inode)) {
30348737c930SAl Viro 		if  ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND))
30357715b521SAl Viro 			return -EPERM;
30361da177e4SLinus Torvalds 		if (flag & O_TRUNC)
30377715b521SAl Viro 			return -EPERM;
30381da177e4SLinus Torvalds 	}
30391da177e4SLinus Torvalds 
30401da177e4SLinus Torvalds 	/* O_NOATIME can only be set by the owner or superuser */
3041ba73d987SChristian Brauner 	if (flag & O_NOATIME && !inode_owner_or_capable(mnt_userns, inode))
30427715b521SAl Viro 		return -EPERM;
30431da177e4SLinus Torvalds 
3044f3c7691eSJ. Bruce Fields 	return 0;
30457715b521SAl Viro }
30467715b521SAl Viro 
3047549c7297SChristian Brauner static int handle_truncate(struct user_namespace *mnt_userns, struct file *filp)
30487715b521SAl Viro {
3049f0bb5aafSAl Viro 	const struct path *path = &filp->f_path;
30507715b521SAl Viro 	struct inode *inode = path->dentry->d_inode;
30517715b521SAl Viro 	int error = get_write_access(inode);
30521da177e4SLinus Torvalds 	if (error)
30537715b521SAl Viro 		return error;
30541da177e4SLinus Torvalds 	/*
30551da177e4SLinus Torvalds 	 * Refuse to truncate files with mandatory locks held on them.
30561da177e4SLinus Torvalds 	 */
3057d7a06983SJeff Layton 	error = locks_verify_locked(filp);
3058be6d3e56SKentaro Takeda 	if (!error)
3059ea0d3ab2STetsuo Handa 		error = security_path_truncate(path);
30601da177e4SLinus Torvalds 	if (!error) {
3061549c7297SChristian Brauner 		error = do_truncate(mnt_userns, path->dentry, 0,
3062d139d7ffSMiklos Szeredi 				    ATTR_MTIME|ATTR_CTIME|ATTR_OPEN,
3063e1181ee6SJeff Layton 				    filp);
30641da177e4SLinus Torvalds 	}
30651da177e4SLinus Torvalds 	put_write_access(inode);
3066acd0c935SMimi Zohar 	return error;
30671da177e4SLinus Torvalds }
30681da177e4SLinus Torvalds 
3069d57999e1SDave Hansen static inline int open_to_namei_flags(int flag)
3070d57999e1SDave Hansen {
30718a5e929dSAl Viro 	if ((flag & O_ACCMODE) == 3)
30728a5e929dSAl Viro 		flag--;
3073d57999e1SDave Hansen 	return flag;
3074d57999e1SDave Hansen }
3075d57999e1SDave Hansen 
3076ba73d987SChristian Brauner static int may_o_create(struct user_namespace *mnt_userns,
3077ba73d987SChristian Brauner 			const struct path *dir, struct dentry *dentry,
3078ba73d987SChristian Brauner 			umode_t mode)
3079d18e9008SMiklos Szeredi {
3080d18e9008SMiklos Szeredi 	int error = security_path_mknod(dir, dentry, mode, 0);
3081d18e9008SMiklos Szeredi 	if (error)
3082d18e9008SMiklos Szeredi 		return error;
3083d18e9008SMiklos Szeredi 
30848e538913SChristian Brauner 	if (!fsuidgid_has_mapping(dir->dentry->d_sb, mnt_userns))
30851328c727SSeth Forshee 		return -EOVERFLOW;
30861328c727SSeth Forshee 
3087ba73d987SChristian Brauner 	error = inode_permission(mnt_userns, dir->dentry->d_inode,
308847291baaSChristian Brauner 				 MAY_WRITE | MAY_EXEC);
3089d18e9008SMiklos Szeredi 	if (error)
3090d18e9008SMiklos Szeredi 		return error;
3091d18e9008SMiklos Szeredi 
3092d18e9008SMiklos Szeredi 	return security_inode_create(dir->dentry->d_inode, dentry, mode);
3093d18e9008SMiklos Szeredi }
3094d18e9008SMiklos Szeredi 
30951acf0af9SDavid Howells /*
30961acf0af9SDavid Howells  * Attempt to atomically look up, create and open a file from a negative
30971acf0af9SDavid Howells  * dentry.
30981acf0af9SDavid Howells  *
30991acf0af9SDavid Howells  * Returns 0 if successful.  The file will have been created and attached to
31001acf0af9SDavid Howells  * @file by the filesystem calling finish_open().
31011acf0af9SDavid Howells  *
310200a07c15SAl Viro  * If the file was looked up only or didn't need creating, FMODE_OPENED won't
310300a07c15SAl Viro  * be set.  The caller will need to perform the open themselves.  @path will
310400a07c15SAl Viro  * have been updated to point to the new dentry.  This may be negative.
31051acf0af9SDavid Howells  *
31061acf0af9SDavid Howells  * Returns an error code otherwise.
31071acf0af9SDavid Howells  */
3108239eb983SAl Viro static struct dentry *atomic_open(struct nameidata *nd, struct dentry *dentry,
3109239eb983SAl Viro 				  struct file *file,
31103ec2eef1SAl Viro 				  int open_flag, umode_t mode)
3111d18e9008SMiklos Szeredi {
3112d18e9008SMiklos Szeredi 	struct dentry *const DENTRY_NOT_SET = (void *) -1UL;
3113d18e9008SMiklos Szeredi 	struct inode *dir =  nd->path.dentry->d_inode;
3114d18e9008SMiklos Szeredi 	int error;
3115d18e9008SMiklos Szeredi 
3116d18e9008SMiklos Szeredi 	if (nd->flags & LOOKUP_DIRECTORY)
3117d18e9008SMiklos Szeredi 		open_flag |= O_DIRECTORY;
3118d18e9008SMiklos Szeredi 
311930d90494SAl Viro 	file->f_path.dentry = DENTRY_NOT_SET;
312030d90494SAl Viro 	file->f_path.mnt = nd->path.mnt;
31210fb1ea09SAl Viro 	error = dir->i_op->atomic_open(dir, dentry, file,
312244907d79SAl Viro 				       open_to_namei_flags(open_flag), mode);
31236fbd0714SAl Viro 	d_lookup_done(dentry);
3124384f26e2SAl Viro 	if (!error) {
312564e1ac4dSAl Viro 		if (file->f_mode & FMODE_OPENED) {
31266fb968cdSAl Viro 			if (unlikely(dentry != file->f_path.dentry)) {
31276fb968cdSAl Viro 				dput(dentry);
31286fb968cdSAl Viro 				dentry = dget(file->f_path.dentry);
31296fb968cdSAl Viro 			}
313064e1ac4dSAl Viro 		} else if (WARN_ON(file->f_path.dentry == DENTRY_NOT_SET)) {
31312675a4ebSAl Viro 			error = -EIO;
3132384f26e2SAl Viro 		} else {
313330d90494SAl Viro 			if (file->f_path.dentry) {
3134d18e9008SMiklos Szeredi 				dput(dentry);
3135d18e9008SMiklos Szeredi 				dentry = file->f_path.dentry;
313610c64ceaSAl Viro 			}
3137239eb983SAl Viro 			if (unlikely(d_is_negative(dentry)))
3138a01e718fSAl Viro 				error = -ENOENT;
3139d18e9008SMiklos Szeredi 		}
3140d18e9008SMiklos Szeredi 	}
3141239eb983SAl Viro 	if (error) {
3142d18e9008SMiklos Szeredi 		dput(dentry);
3143239eb983SAl Viro 		dentry = ERR_PTR(error);
3144239eb983SAl Viro 	}
3145239eb983SAl Viro 	return dentry;
3146d18e9008SMiklos Szeredi }
3147d18e9008SMiklos Szeredi 
314831e6b01fSNick Piggin /*
31491acf0af9SDavid Howells  * Look up and maybe create and open the last component.
3150d58ffd35SMiklos Szeredi  *
315100a07c15SAl Viro  * Must be called with parent locked (exclusive in O_CREAT case).
3152d58ffd35SMiklos Szeredi  *
315300a07c15SAl Viro  * Returns 0 on success, that is, if
315400a07c15SAl Viro  *  the file was successfully atomically created (if necessary) and opened, or
315500a07c15SAl Viro  *  the file was not completely opened at this time, though lookups and
315600a07c15SAl Viro  *  creations were performed.
315700a07c15SAl Viro  * These case are distinguished by presence of FMODE_OPENED on file->f_mode.
315800a07c15SAl Viro  * In the latter case dentry returned in @path might be negative if O_CREAT
315900a07c15SAl Viro  * hadn't been specified.
31601acf0af9SDavid Howells  *
316100a07c15SAl Viro  * An error code is returned on failure.
3162d58ffd35SMiklos Szeredi  */
3163da5ebf5aSAl Viro static struct dentry *lookup_open(struct nameidata *nd, struct file *file,
3164d58ffd35SMiklos Szeredi 				  const struct open_flags *op,
31653ec2eef1SAl Viro 				  bool got_write)
3166d58ffd35SMiklos Szeredi {
3167549c7297SChristian Brauner 	struct user_namespace *mnt_userns;
3168d58ffd35SMiklos Szeredi 	struct dentry *dir = nd->path.dentry;
316954ef4872SMiklos Szeredi 	struct inode *dir_inode = dir->d_inode;
31701643b43fSAl Viro 	int open_flag = op->open_flag;
3171d58ffd35SMiklos Szeredi 	struct dentry *dentry;
31721643b43fSAl Viro 	int error, create_error = 0;
31731643b43fSAl Viro 	umode_t mode = op->mode;
31746fbd0714SAl Viro 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
3175d58ffd35SMiklos Szeredi 
3176ce8644fcSAl Viro 	if (unlikely(IS_DEADDIR(dir_inode)))
3177da5ebf5aSAl Viro 		return ERR_PTR(-ENOENT);
3178d58ffd35SMiklos Szeredi 
317973a09dd9SAl Viro 	file->f_mode &= ~FMODE_CREATED;
31806fbd0714SAl Viro 	dentry = d_lookup(dir, &nd->last);
31816fbd0714SAl Viro 	for (;;) {
31826fbd0714SAl Viro 		if (!dentry) {
31836fbd0714SAl Viro 			dentry = d_alloc_parallel(dir, &nd->last, &wq);
3184d58ffd35SMiklos Szeredi 			if (IS_ERR(dentry))
3185da5ebf5aSAl Viro 				return dentry;
31866fbd0714SAl Viro 		}
31876fbd0714SAl Viro 		if (d_in_lookup(dentry))
31886fbd0714SAl Viro 			break;
3189d58ffd35SMiklos Szeredi 
31906fbd0714SAl Viro 		error = d_revalidate(dentry, nd->flags);
31916fbd0714SAl Viro 		if (likely(error > 0))
31926fbd0714SAl Viro 			break;
31936fbd0714SAl Viro 		if (error)
31946fbd0714SAl Viro 			goto out_dput;
31956fbd0714SAl Viro 		d_invalidate(dentry);
31966fbd0714SAl Viro 		dput(dentry);
31976fbd0714SAl Viro 		dentry = NULL;
31986fbd0714SAl Viro 	}
31996fbd0714SAl Viro 	if (dentry->d_inode) {
3200d18e9008SMiklos Szeredi 		/* Cached positive dentry: will open in f_op->open */
3201da5ebf5aSAl Viro 		return dentry;
32026c51e513SAl Viro 	}
3203d18e9008SMiklos Szeredi 
32041643b43fSAl Viro 	/*
32051643b43fSAl Viro 	 * Checking write permission is tricky, bacuse we don't know if we are
32061643b43fSAl Viro 	 * going to actually need it: O_CREAT opens should work as long as the
32071643b43fSAl Viro 	 * file exists.  But checking existence breaks atomicity.  The trick is
32081643b43fSAl Viro 	 * to check access and if not granted clear O_CREAT from the flags.
32091643b43fSAl Viro 	 *
32101643b43fSAl Viro 	 * Another problem is returing the "right" error value (e.g. for an
32111643b43fSAl Viro 	 * O_EXCL open we want to return EEXIST not EROFS).
32121643b43fSAl Viro 	 */
321399a4a90cSAl Viro 	if (unlikely(!got_write))
321499a4a90cSAl Viro 		open_flag &= ~O_TRUNC;
3215549c7297SChristian Brauner 	mnt_userns = mnt_user_ns(nd->path.mnt);
32161643b43fSAl Viro 	if (open_flag & O_CREAT) {
321799a4a90cSAl Viro 		if (open_flag & O_EXCL)
321899a4a90cSAl Viro 			open_flag &= ~O_TRUNC;
32191643b43fSAl Viro 		if (!IS_POSIXACL(dir->d_inode))
32201643b43fSAl Viro 			mode &= ~current_umask();
322199a4a90cSAl Viro 		if (likely(got_write))
3222549c7297SChristian Brauner 			create_error = may_o_create(mnt_userns, &nd->path,
3223ba73d987SChristian Brauner 						    dentry, mode);
322499a4a90cSAl Viro 		else
322599a4a90cSAl Viro 			create_error = -EROFS;
322699a4a90cSAl Viro 	}
322799a4a90cSAl Viro 	if (create_error)
32281643b43fSAl Viro 		open_flag &= ~O_CREAT;
32291643b43fSAl Viro 	if (dir_inode->i_op->atomic_open) {
3230d489cf9aSAl Viro 		dentry = atomic_open(nd, dentry, file, open_flag, mode);
3231da5ebf5aSAl Viro 		if (unlikely(create_error) && dentry == ERR_PTR(-ENOENT))
3232da5ebf5aSAl Viro 			dentry = ERR_PTR(create_error);
3233da5ebf5aSAl Viro 		return dentry;
3234239eb983SAl Viro 	}
323554ef4872SMiklos Szeredi 
32366fbd0714SAl Viro 	if (d_in_lookup(dentry)) {
323712fa5e24SAl Viro 		struct dentry *res = dir_inode->i_op->lookup(dir_inode, dentry,
323812fa5e24SAl Viro 							     nd->flags);
32396fbd0714SAl Viro 		d_lookup_done(dentry);
324012fa5e24SAl Viro 		if (unlikely(res)) {
324112fa5e24SAl Viro 			if (IS_ERR(res)) {
324212fa5e24SAl Viro 				error = PTR_ERR(res);
324312fa5e24SAl Viro 				goto out_dput;
324412fa5e24SAl Viro 			}
324512fa5e24SAl Viro 			dput(dentry);
324612fa5e24SAl Viro 			dentry = res;
324712fa5e24SAl Viro 		}
324854ef4872SMiklos Szeredi 	}
324954ef4872SMiklos Szeredi 
3250d58ffd35SMiklos Szeredi 	/* Negative dentry, just create the file */
32511643b43fSAl Viro 	if (!dentry->d_inode && (open_flag & O_CREAT)) {
325273a09dd9SAl Viro 		file->f_mode |= FMODE_CREATED;
3253ce8644fcSAl Viro 		audit_inode_child(dir_inode, dentry, AUDIT_TYPE_CHILD_CREATE);
3254ce8644fcSAl Viro 		if (!dir_inode->i_op->create) {
3255ce8644fcSAl Viro 			error = -EACCES;
3256d58ffd35SMiklos Szeredi 			goto out_dput;
325764894cf8SAl Viro 		}
3258549c7297SChristian Brauner 
3259549c7297SChristian Brauner 		error = dir_inode->i_op->create(mnt_userns, dir_inode, dentry,
3260549c7297SChristian Brauner 						mode, open_flag & O_EXCL);
3261d58ffd35SMiklos Szeredi 		if (error)
3262d58ffd35SMiklos Szeredi 			goto out_dput;
3263d58ffd35SMiklos Szeredi 	}
32641643b43fSAl Viro 	if (unlikely(create_error) && !dentry->d_inode) {
32651643b43fSAl Viro 		error = create_error;
3266d58ffd35SMiklos Szeredi 		goto out_dput;
3267d58ffd35SMiklos Szeredi 	}
3268da5ebf5aSAl Viro 	return dentry;
3269d58ffd35SMiklos Szeredi 
3270d58ffd35SMiklos Szeredi out_dput:
3271d58ffd35SMiklos Szeredi 	dput(dentry);
3272da5ebf5aSAl Viro 	return ERR_PTR(error);
3273d58ffd35SMiklos Szeredi }
3274d58ffd35SMiklos Szeredi 
3275c981a482SAl Viro static const char *open_last_lookups(struct nameidata *nd,
32763ec2eef1SAl Viro 		   struct file *file, const struct open_flags *op)
3277fb1cc555SAl Viro {
3278a1e28038SAl Viro 	struct dentry *dir = nd->path.dentry;
3279ca344a89SAl Viro 	int open_flag = op->open_flag;
328064894cf8SAl Viro 	bool got_write = false;
3281254cf582SAl Viro 	unsigned seq;
3282a1eb3315SMiklos Szeredi 	struct inode *inode;
3283da5ebf5aSAl Viro 	struct dentry *dentry;
3284b0417d2cSAl Viro 	const char *res;
3285fb1cc555SAl Viro 
3286c3e380b0SAl Viro 	nd->flags |= op->intent;
3287c3e380b0SAl Viro 
3288bc77daa7SAl Viro 	if (nd->last_type != LAST_NORM) {
328956676ec3SAl Viro 		if (nd->depth)
329056676ec3SAl Viro 			put_link(nd);
3291ff326a32SAl Viro 		return handle_dots(nd, nd->last_type);
32921f36f774SAl Viro 	}
3293a2c36b45SAl Viro 
3294ca344a89SAl Viro 	if (!(open_flag & O_CREAT)) {
3295fe2d35ffSAl Viro 		if (nd->last.name[nd->last.len])
3296fe2d35ffSAl Viro 			nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
3297fe2d35ffSAl Viro 		/* we _can_ be in RCU mode here */
329820e34357SAl Viro 		dentry = lookup_fast(nd, &inode, &seq);
329920e34357SAl Viro 		if (IS_ERR(dentry))
33001ccac622SAl Viro 			return ERR_CAST(dentry);
330120e34357SAl Viro 		if (likely(dentry))
330271574865SMiklos Szeredi 			goto finish_lookup;
330371574865SMiklos Szeredi 
33046583fe22SAl Viro 		BUG_ON(nd->flags & LOOKUP_RCU);
3305b6183df7SMiklos Szeredi 	} else {
3306fe2d35ffSAl Viro 		/* create side of things */
330772287417SAl Viro 		if (nd->flags & LOOKUP_RCU) {
3308e36cffedSJens Axboe 			if (!try_to_unlazy(nd))
3309e36cffedSJens Axboe 				return ERR_PTR(-ECHILD);
331072287417SAl Viro 		}
3311c9b07eabSAl Viro 		audit_inode(nd->name, dir, AUDIT_INODE_PARENT);
33121f36f774SAl Viro 		/* trailing slashes? */
3313deb106c6SAl Viro 		if (unlikely(nd->last.name[nd->last.len]))
33141ccac622SAl Viro 			return ERR_PTR(-EISDIR);
3315b6183df7SMiklos Szeredi 	}
33161f36f774SAl Viro 
33179cf843e3SAl Viro 	if (open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) {
3318e36cffedSJens Axboe 		got_write = !mnt_want_write(nd->path.mnt);
331964894cf8SAl Viro 		/*
332064894cf8SAl Viro 		 * do _not_ fail yet - we might not need that or fail with
332164894cf8SAl Viro 		 * a different error; let lookup_open() decide; we'll be
332264894cf8SAl Viro 		 * dropping this one anyway.
332364894cf8SAl Viro 		 */
332464894cf8SAl Viro 	}
33259cf843e3SAl Viro 	if (open_flag & O_CREAT)
33265955102cSAl Viro 		inode_lock(dir->d_inode);
33279cf843e3SAl Viro 	else
33289cf843e3SAl Viro 		inode_lock_shared(dir->d_inode);
3329da5ebf5aSAl Viro 	dentry = lookup_open(nd, file, op, got_write);
3330f7bb959dSAl Viro 	if (!IS_ERR(dentry) && (file->f_mode & FMODE_CREATED))
3331f7bb959dSAl Viro 		fsnotify_create(dir->d_inode, dentry);
33329cf843e3SAl Viro 	if (open_flag & O_CREAT)
33335955102cSAl Viro 		inode_unlock(dir->d_inode);
33349cf843e3SAl Viro 	else
33359cf843e3SAl Viro 		inode_unlock_shared(dir->d_inode);
3336fb1cc555SAl Viro 
3337c981a482SAl Viro 	if (got_write)
333859e96e65SAl Viro 		mnt_drop_write(nd->path.mnt);
33396c0d46c4SAl Viro 
334059e96e65SAl Viro 	if (IS_ERR(dentry))
334159e96e65SAl Viro 		return ERR_CAST(dentry);
334259e96e65SAl Viro 
3343973d4b73SAl Viro 	if (file->f_mode & (FMODE_OPENED | FMODE_CREATED)) {
3344e73cabffSAl Viro 		dput(nd->path.dentry);
3345e73cabffSAl Viro 		nd->path.dentry = dentry;
3346c981a482SAl Viro 		return NULL;
3347fb1cc555SAl Viro 	}
3348fb1cc555SAl Viro 
334920e34357SAl Viro finish_lookup:
335056676ec3SAl Viro 	if (nd->depth)
335156676ec3SAl Viro 		put_link(nd);
33528c4efe22SAl Viro 	res = step_into(nd, WALK_TRAILING, dentry, inode, seq);
3353ff326a32SAl Viro 	if (unlikely(res))
33541ccac622SAl Viro 		nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL);
3355b0417d2cSAl Viro 	return res;
33561ccac622SAl Viro }
335731d1726dSAl Viro 
3358c981a482SAl Viro /*
3359c981a482SAl Viro  * Handle the last step of open()
3360c981a482SAl Viro  */
3361c5971b8cSAl Viro static int do_open(struct nameidata *nd,
3362c981a482SAl Viro 		   struct file *file, const struct open_flags *op)
3363c981a482SAl Viro {
3364549c7297SChristian Brauner 	struct user_namespace *mnt_userns;
3365c981a482SAl Viro 	int open_flag = op->open_flag;
3366c981a482SAl Viro 	bool do_truncate;
3367c981a482SAl Viro 	int acc_mode;
3368c981a482SAl Viro 	int error;
3369c981a482SAl Viro 
3370ff326a32SAl Viro 	if (!(file->f_mode & (FMODE_OPENED | FMODE_CREATED))) {
3371ff326a32SAl Viro 		error = complete_walk(nd);
3372ff326a32SAl Viro 		if (error)
3373ff326a32SAl Viro 			return error;
3374ff326a32SAl Viro 	}
3375973d4b73SAl Viro 	if (!(file->f_mode & FMODE_CREATED))
337676ae2a5aSAl Viro 		audit_inode(nd->name, nd->path.dentry, 0);
3377549c7297SChristian Brauner 	mnt_userns = mnt_user_ns(nd->path.mnt);
337830aba665SSalvatore Mesoraca 	if (open_flag & O_CREAT) {
3379b94e0b32SAl Viro 		if ((open_flag & O_EXCL) && !(file->f_mode & FMODE_CREATED))
3380b94e0b32SAl Viro 			return -EEXIST;
338130aba665SSalvatore Mesoraca 		if (d_is_dir(nd->path.dentry))
3382c5971b8cSAl Viro 			return -EISDIR;
3383549c7297SChristian Brauner 		error = may_create_in_sticky(mnt_userns, nd,
338430aba665SSalvatore Mesoraca 					     d_backing_inode(nd->path.dentry));
338530aba665SSalvatore Mesoraca 		if (unlikely(error))
3386c5971b8cSAl Viro 			return error;
338730aba665SSalvatore Mesoraca 	}
338844b1d530SMiklos Szeredi 	if ((nd->flags & LOOKUP_DIRECTORY) && !d_can_lookup(nd->path.dentry))
3389c5971b8cSAl Viro 		return -ENOTDIR;
33906c0d46c4SAl Viro 
33918795e7d4SAl Viro 	do_truncate = false;
33928795e7d4SAl Viro 	acc_mode = op->acc_mode;
33935a2d3eddSAl Viro 	if (file->f_mode & FMODE_CREATED) {
33945a2d3eddSAl Viro 		/* Don't check for write permission, don't truncate */
33955a2d3eddSAl Viro 		open_flag &= ~O_TRUNC;
33965a2d3eddSAl Viro 		acc_mode = 0;
33978795e7d4SAl Viro 	} else if (d_is_reg(nd->path.dentry) && open_flag & O_TRUNC) {
33980f9d1a10SAl Viro 		error = mnt_want_write(nd->path.mnt);
33990f9d1a10SAl Viro 		if (error)
3400c5971b8cSAl Viro 			return error;
34018795e7d4SAl Viro 		do_truncate = true;
34020f9d1a10SAl Viro 	}
3403549c7297SChristian Brauner 	error = may_open(mnt_userns, &nd->path, acc_mode, open_flag);
34048795e7d4SAl Viro 	if (!error && !(file->f_mode & FMODE_OPENED))
3405ae2bb293SAl Viro 		error = vfs_open(&nd->path, file);
34068795e7d4SAl Viro 	if (!error)
34076035a27bSAl Viro 		error = ima_file_check(file, op->acc_mode);
34088795e7d4SAl Viro 	if (!error && do_truncate)
3409549c7297SChristian Brauner 		error = handle_truncate(mnt_userns, file);
3410c80567c8SAl Viro 	if (unlikely(error > 0)) {
3411c80567c8SAl Viro 		WARN_ON(1);
3412c80567c8SAl Viro 		error = -EINVAL;
3413c80567c8SAl Viro 	}
34148795e7d4SAl Viro 	if (do_truncate)
34150f9d1a10SAl Viro 		mnt_drop_write(nd->path.mnt);
3416c5971b8cSAl Viro 	return error;
3417fb1cc555SAl Viro }
3418fb1cc555SAl Viro 
34196521f891SChristian Brauner /**
34206521f891SChristian Brauner  * vfs_tmpfile - create tmpfile
34216521f891SChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
34226521f891SChristian Brauner  * @dentry:	pointer to dentry of the base directory
34236521f891SChristian Brauner  * @mode:	mode of the new tmpfile
34242111c3c0SRandy Dunlap  * @open_flag:	flags
34256521f891SChristian Brauner  *
34266521f891SChristian Brauner  * Create a temporary file.
34276521f891SChristian Brauner  *
34286521f891SChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
34296521f891SChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
34306521f891SChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
34316521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
34326521f891SChristian Brauner  * raw inode simply passs init_user_ns.
34336521f891SChristian Brauner  */
34346521f891SChristian Brauner struct dentry *vfs_tmpfile(struct user_namespace *mnt_userns,
34356521f891SChristian Brauner 			   struct dentry *dentry, umode_t mode, int open_flag)
3436af7bd4dcSAmir Goldstein {
3437af7bd4dcSAmir Goldstein 	struct dentry *child = NULL;
3438af7bd4dcSAmir Goldstein 	struct inode *dir = dentry->d_inode;
3439af7bd4dcSAmir Goldstein 	struct inode *inode;
3440af7bd4dcSAmir Goldstein 	int error;
3441af7bd4dcSAmir Goldstein 
3442af7bd4dcSAmir Goldstein 	/* we want directory to be writable */
34436521f891SChristian Brauner 	error = inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
3444af7bd4dcSAmir Goldstein 	if (error)
3445af7bd4dcSAmir Goldstein 		goto out_err;
3446af7bd4dcSAmir Goldstein 	error = -EOPNOTSUPP;
3447af7bd4dcSAmir Goldstein 	if (!dir->i_op->tmpfile)
3448af7bd4dcSAmir Goldstein 		goto out_err;
3449af7bd4dcSAmir Goldstein 	error = -ENOMEM;
3450cdf01226SDavid Howells 	child = d_alloc(dentry, &slash_name);
3451af7bd4dcSAmir Goldstein 	if (unlikely(!child))
3452af7bd4dcSAmir Goldstein 		goto out_err;
3453549c7297SChristian Brauner 	error = dir->i_op->tmpfile(mnt_userns, dir, child, mode);
3454af7bd4dcSAmir Goldstein 	if (error)
3455af7bd4dcSAmir Goldstein 		goto out_err;
3456af7bd4dcSAmir Goldstein 	error = -ENOENT;
3457af7bd4dcSAmir Goldstein 	inode = child->d_inode;
3458af7bd4dcSAmir Goldstein 	if (unlikely(!inode))
3459af7bd4dcSAmir Goldstein 		goto out_err;
3460af7bd4dcSAmir Goldstein 	if (!(open_flag & O_EXCL)) {
3461af7bd4dcSAmir Goldstein 		spin_lock(&inode->i_lock);
3462af7bd4dcSAmir Goldstein 		inode->i_state |= I_LINKABLE;
3463af7bd4dcSAmir Goldstein 		spin_unlock(&inode->i_lock);
3464af7bd4dcSAmir Goldstein 	}
3465a2d2329eSChristian Brauner 	ima_post_create_tmpfile(mnt_userns, inode);
3466af7bd4dcSAmir Goldstein 	return child;
3467af7bd4dcSAmir Goldstein 
3468af7bd4dcSAmir Goldstein out_err:
3469af7bd4dcSAmir Goldstein 	dput(child);
3470af7bd4dcSAmir Goldstein 	return ERR_PTR(error);
3471af7bd4dcSAmir Goldstein }
3472af7bd4dcSAmir Goldstein EXPORT_SYMBOL(vfs_tmpfile);
3473af7bd4dcSAmir Goldstein 
3474c8a53ee5SAl Viro static int do_tmpfile(struct nameidata *nd, unsigned flags,
347560545d0dSAl Viro 		const struct open_flags *op,
34763ec2eef1SAl Viro 		struct file *file)
347760545d0dSAl Viro {
34786521f891SChristian Brauner 	struct user_namespace *mnt_userns;
3479625b6d10SAl Viro 	struct dentry *child;
3480625b6d10SAl Viro 	struct path path;
3481c8a53ee5SAl Viro 	int error = path_lookupat(nd, flags | LOOKUP_DIRECTORY, &path);
348260545d0dSAl Viro 	if (unlikely(error))
348360545d0dSAl Viro 		return error;
3484625b6d10SAl Viro 	error = mnt_want_write(path.mnt);
348560545d0dSAl Viro 	if (unlikely(error))
348660545d0dSAl Viro 		goto out;
34876521f891SChristian Brauner 	mnt_userns = mnt_user_ns(path.mnt);
34886521f891SChristian Brauner 	child = vfs_tmpfile(mnt_userns, path.dentry, op->mode, op->open_flag);
3489af7bd4dcSAmir Goldstein 	error = PTR_ERR(child);
3490684e73beSHirofumi Nakagawa 	if (IS_ERR(child))
349160545d0dSAl Viro 		goto out2;
3492625b6d10SAl Viro 	dput(path.dentry);
3493625b6d10SAl Viro 	path.dentry = child;
3494c8a53ee5SAl Viro 	audit_inode(nd->name, child, 0);
349569a91c23SEric Rannaud 	/* Don't check for other permissions, the inode was just created */
3496549c7297SChristian Brauner 	error = may_open(mnt_userns, &path, 0, op->open_flag);
34971e8f44f1SAl Viro 	if (!error)
34981e8f44f1SAl Viro 		error = vfs_open(&path, file);
349960545d0dSAl Viro out2:
3500625b6d10SAl Viro 	mnt_drop_write(path.mnt);
350160545d0dSAl Viro out:
3502625b6d10SAl Viro 	path_put(&path);
350360545d0dSAl Viro 	return error;
350460545d0dSAl Viro }
350560545d0dSAl Viro 
35066ac08709SAl Viro static int do_o_path(struct nameidata *nd, unsigned flags, struct file *file)
35076ac08709SAl Viro {
35086ac08709SAl Viro 	struct path path;
35096ac08709SAl Viro 	int error = path_lookupat(nd, flags, &path);
35106ac08709SAl Viro 	if (!error) {
35116ac08709SAl Viro 		audit_inode(nd->name, path.dentry, 0);
3512ae2bb293SAl Viro 		error = vfs_open(&path, file);
35136ac08709SAl Viro 		path_put(&path);
35146ac08709SAl Viro 	}
35156ac08709SAl Viro 	return error;
35166ac08709SAl Viro }
35176ac08709SAl Viro 
3518c8a53ee5SAl Viro static struct file *path_openat(struct nameidata *nd,
3519c8a53ee5SAl Viro 			const struct open_flags *op, unsigned flags)
35201da177e4SLinus Torvalds {
352130d90494SAl Viro 	struct file *file;
352213aab428SAl Viro 	int error;
352331e6b01fSNick Piggin 
3524ea73ea72SAl Viro 	file = alloc_empty_file(op->open_flag, current_cred());
35251afc99beSAl Viro 	if (IS_ERR(file))
35261afc99beSAl Viro 		return file;
352731e6b01fSNick Piggin 
3528bb458c64SAl Viro 	if (unlikely(file->f_flags & __O_TMPFILE)) {
35293ec2eef1SAl Viro 		error = do_tmpfile(nd, flags, op, file);
35305f336e72SAl Viro 	} else if (unlikely(file->f_flags & O_PATH)) {
35316ac08709SAl Viro 		error = do_o_path(nd, flags, file);
35325f336e72SAl Viro 	} else {
35335f336e72SAl Viro 		const char *s = path_init(nd, flags);
35343bdba28bSAl Viro 		while (!(error = link_path_walk(s, nd)) &&
3535c5971b8cSAl Viro 		       (s = open_last_lookups(nd, file, op)) != NULL)
35361ccac622SAl Viro 			;
3537c5971b8cSAl Viro 		if (!error)
3538c5971b8cSAl Viro 			error = do_open(nd, file, op);
3539deb106c6SAl Viro 		terminate_walk(nd);
35405f336e72SAl Viro 	}
35417c1c01ecSAl Viro 	if (likely(!error)) {
3542aad888f8SAl Viro 		if (likely(file->f_mode & FMODE_OPENED))
35437c1c01ecSAl Viro 			return file;
35447c1c01ecSAl Viro 		WARN_ON(1);
35457c1c01ecSAl Viro 		error = -EINVAL;
3546015c3bbcSMiklos Szeredi 	}
35477c1c01ecSAl Viro 	fput(file);
35482675a4ebSAl Viro 	if (error == -EOPENSTALE) {
35492675a4ebSAl Viro 		if (flags & LOOKUP_RCU)
35502675a4ebSAl Viro 			error = -ECHILD;
35512675a4ebSAl Viro 		else
35522675a4ebSAl Viro 			error = -ESTALE;
35532675a4ebSAl Viro 	}
35547c1c01ecSAl Viro 	return ERR_PTR(error);
3555de459215SKirill Korotaev }
35561da177e4SLinus Torvalds 
3557669abf4eSJeff Layton struct file *do_filp_open(int dfd, struct filename *pathname,
3558f9652e10SAl Viro 		const struct open_flags *op)
355913aab428SAl Viro {
35609883d185SAl Viro 	struct nameidata nd;
3561f9652e10SAl Viro 	int flags = op->lookup_flags;
356213aab428SAl Viro 	struct file *filp;
356313aab428SAl Viro 
356406422964SAl Viro 	set_nameidata(&nd, dfd, pathname, NULL);
3565c8a53ee5SAl Viro 	filp = path_openat(&nd, op, flags | LOOKUP_RCU);
356613aab428SAl Viro 	if (unlikely(filp == ERR_PTR(-ECHILD)))
3567c8a53ee5SAl Viro 		filp = path_openat(&nd, op, flags);
356813aab428SAl Viro 	if (unlikely(filp == ERR_PTR(-ESTALE)))
3569c8a53ee5SAl Viro 		filp = path_openat(&nd, op, flags | LOOKUP_REVAL);
35709883d185SAl Viro 	restore_nameidata();
357113aab428SAl Viro 	return filp;
357213aab428SAl Viro }
357313aab428SAl Viro 
3574ffb37ca3SAl Viro struct file *do_file_open_root(const struct path *root,
3575f9652e10SAl Viro 		const char *name, const struct open_flags *op)
357673d049a4SAl Viro {
35779883d185SAl Viro 	struct nameidata nd;
357873d049a4SAl Viro 	struct file *file;
357951689104SPaul Moore 	struct filename *filename;
3580bcba1e7dSAl Viro 	int flags = op->lookup_flags;
358173d049a4SAl Viro 
3582ffb37ca3SAl Viro 	if (d_is_symlink(root->dentry) && op->intent & LOOKUP_OPEN)
358373d049a4SAl Viro 		return ERR_PTR(-ELOOP);
358473d049a4SAl Viro 
358551689104SPaul Moore 	filename = getname_kernel(name);
3586a1c83681SViresh Kumar 	if (IS_ERR(filename))
358751689104SPaul Moore 		return ERR_CAST(filename);
358851689104SPaul Moore 
358906422964SAl Viro 	set_nameidata(&nd, -1, filename, root);
3590c8a53ee5SAl Viro 	file = path_openat(&nd, op, flags | LOOKUP_RCU);
359173d049a4SAl Viro 	if (unlikely(file == ERR_PTR(-ECHILD)))
3592c8a53ee5SAl Viro 		file = path_openat(&nd, op, flags);
359373d049a4SAl Viro 	if (unlikely(file == ERR_PTR(-ESTALE)))
3594c8a53ee5SAl Viro 		file = path_openat(&nd, op, flags | LOOKUP_REVAL);
35959883d185SAl Viro 	restore_nameidata();
359651689104SPaul Moore 	putname(filename);
359773d049a4SAl Viro 	return file;
359873d049a4SAl Viro }
359973d049a4SAl Viro 
3600fa14a0b8SAl Viro static struct dentry *filename_create(int dfd, struct filename *name,
36011ac12b4bSJeff Layton 				struct path *path, unsigned int lookup_flags)
36021da177e4SLinus Torvalds {
3603c663e5d8SChristoph Hellwig 	struct dentry *dentry = ERR_PTR(-EEXIST);
3604391172c4SAl Viro 	struct qstr last;
3605391172c4SAl Viro 	int type;
3606c30dabfeSJan Kara 	int err2;
36071ac12b4bSJeff Layton 	int error;
36081ac12b4bSJeff Layton 	bool is_dir = (lookup_flags & LOOKUP_DIRECTORY);
36091ac12b4bSJeff Layton 
36101ac12b4bSJeff Layton 	/*
36111ac12b4bSJeff Layton 	 * Note that only LOOKUP_REVAL and LOOKUP_DIRECTORY matter here. Any
36121ac12b4bSJeff Layton 	 * other flags passed in are ignored!
36131ac12b4bSJeff Layton 	 */
36141ac12b4bSJeff Layton 	lookup_flags &= LOOKUP_REVAL;
36151ac12b4bSJeff Layton 
36165c31b6ceSAl Viro 	name = filename_parentat(dfd, name, lookup_flags, path, &last, &type);
36175c31b6ceSAl Viro 	if (IS_ERR(name))
36185c31b6ceSAl Viro 		return ERR_CAST(name);
36191da177e4SLinus Torvalds 
3620c663e5d8SChristoph Hellwig 	/*
3621c663e5d8SChristoph Hellwig 	 * Yucky last component or no last component at all?
3622c663e5d8SChristoph Hellwig 	 * (foo/., foo/.., /////)
3623c663e5d8SChristoph Hellwig 	 */
36245c31b6ceSAl Viro 	if (unlikely(type != LAST_NORM))
3625ed75e95dSAl Viro 		goto out;
3626c663e5d8SChristoph Hellwig 
3627c30dabfeSJan Kara 	/* don't fail immediately if it's r/o, at least try to report other errors */
3628391172c4SAl Viro 	err2 = mnt_want_write(path->mnt);
3629c663e5d8SChristoph Hellwig 	/*
3630c663e5d8SChristoph Hellwig 	 * Do the final lookup.
3631c663e5d8SChristoph Hellwig 	 */
3632391172c4SAl Viro 	lookup_flags |= LOOKUP_CREATE | LOOKUP_EXCL;
36335955102cSAl Viro 	inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
3634391172c4SAl Viro 	dentry = __lookup_hash(&last, path->dentry, lookup_flags);
36351da177e4SLinus Torvalds 	if (IS_ERR(dentry))
3636a8104a9fSAl Viro 		goto unlock;
3637c663e5d8SChristoph Hellwig 
3638a8104a9fSAl Viro 	error = -EEXIST;
3639b18825a7SDavid Howells 	if (d_is_positive(dentry))
3640a8104a9fSAl Viro 		goto fail;
3641b18825a7SDavid Howells 
3642c663e5d8SChristoph Hellwig 	/*
3643c663e5d8SChristoph Hellwig 	 * Special case - lookup gave negative, but... we had foo/bar/
3644c663e5d8SChristoph Hellwig 	 * From the vfs_mknod() POV we just have a negative dentry -
3645c663e5d8SChristoph Hellwig 	 * all is fine. Let's be bastards - you had / on the end, you've
3646c663e5d8SChristoph Hellwig 	 * been asking for (non-existent) directory. -ENOENT for you.
3647c663e5d8SChristoph Hellwig 	 */
3648391172c4SAl Viro 	if (unlikely(!is_dir && last.name[last.len])) {
3649a8104a9fSAl Viro 		error = -ENOENT;
3650ed75e95dSAl Viro 		goto fail;
3651e9baf6e5SAl Viro 	}
3652c30dabfeSJan Kara 	if (unlikely(err2)) {
3653c30dabfeSJan Kara 		error = err2;
3654a8104a9fSAl Viro 		goto fail;
3655c30dabfeSJan Kara 	}
3656181c37b6SAl Viro 	putname(name);
3657e9baf6e5SAl Viro 	return dentry;
36581da177e4SLinus Torvalds fail:
3659a8104a9fSAl Viro 	dput(dentry);
3660a8104a9fSAl Viro 	dentry = ERR_PTR(error);
3661a8104a9fSAl Viro unlock:
36625955102cSAl Viro 	inode_unlock(path->dentry->d_inode);
3663c30dabfeSJan Kara 	if (!err2)
3664391172c4SAl Viro 		mnt_drop_write(path->mnt);
3665ed75e95dSAl Viro out:
3666391172c4SAl Viro 	path_put(path);
3667181c37b6SAl Viro 	putname(name);
3668ed75e95dSAl Viro 	return dentry;
3669dae6ad8fSAl Viro }
3670fa14a0b8SAl Viro 
3671fa14a0b8SAl Viro struct dentry *kern_path_create(int dfd, const char *pathname,
3672fa14a0b8SAl Viro 				struct path *path, unsigned int lookup_flags)
3673fa14a0b8SAl Viro {
3674181c37b6SAl Viro 	return filename_create(dfd, getname_kernel(pathname),
3675181c37b6SAl Viro 				path, lookup_flags);
3676fa14a0b8SAl Viro }
3677dae6ad8fSAl Viro EXPORT_SYMBOL(kern_path_create);
3678dae6ad8fSAl Viro 
3679921a1650SAl Viro void done_path_create(struct path *path, struct dentry *dentry)
3680921a1650SAl Viro {
3681921a1650SAl Viro 	dput(dentry);
36825955102cSAl Viro 	inode_unlock(path->dentry->d_inode);
3683a8104a9fSAl Viro 	mnt_drop_write(path->mnt);
3684921a1650SAl Viro 	path_put(path);
3685921a1650SAl Viro }
3686921a1650SAl Viro EXPORT_SYMBOL(done_path_create);
3687921a1650SAl Viro 
3688520ae687SAl Viro inline struct dentry *user_path_create(int dfd, const char __user *pathname,
36891ac12b4bSJeff Layton 				struct path *path, unsigned int lookup_flags)
3690dae6ad8fSAl Viro {
3691181c37b6SAl Viro 	return filename_create(dfd, getname(pathname), path, lookup_flags);
3692dae6ad8fSAl Viro }
3693dae6ad8fSAl Viro EXPORT_SYMBOL(user_path_create);
3694dae6ad8fSAl Viro 
36956521f891SChristian Brauner /**
36966521f891SChristian Brauner  * vfs_mknod - create device node or file
36976521f891SChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
36986521f891SChristian Brauner  * @dir:	inode of @dentry
36996521f891SChristian Brauner  * @dentry:	pointer to dentry of the base directory
37006521f891SChristian Brauner  * @mode:	mode of the new device node or file
37016521f891SChristian Brauner  * @dev:	device number of device to create
37026521f891SChristian Brauner  *
37036521f891SChristian Brauner  * Create a device node or file.
37046521f891SChristian Brauner  *
37056521f891SChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
37066521f891SChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
37076521f891SChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
37086521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
37096521f891SChristian Brauner  * raw inode simply passs init_user_ns.
37106521f891SChristian Brauner  */
37116521f891SChristian Brauner int vfs_mknod(struct user_namespace *mnt_userns, struct inode *dir,
37126521f891SChristian Brauner 	      struct dentry *dentry, umode_t mode, dev_t dev)
37131da177e4SLinus Torvalds {
3714a3c751a5SMiklos Szeredi 	bool is_whiteout = S_ISCHR(mode) && dev == WHITEOUT_DEV;
37156521f891SChristian Brauner 	int error = may_create(mnt_userns, dir, dentry);
37161da177e4SLinus Torvalds 
37171da177e4SLinus Torvalds 	if (error)
37181da177e4SLinus Torvalds 		return error;
37191da177e4SLinus Torvalds 
3720a3c751a5SMiklos Szeredi 	if ((S_ISCHR(mode) || S_ISBLK(mode)) && !is_whiteout &&
3721a3c751a5SMiklos Szeredi 	    !capable(CAP_MKNOD))
37221da177e4SLinus Torvalds 		return -EPERM;
37231da177e4SLinus Torvalds 
3724acfa4380SAl Viro 	if (!dir->i_op->mknod)
37251da177e4SLinus Torvalds 		return -EPERM;
37261da177e4SLinus Torvalds 
372708ce5f16SSerge E. Hallyn 	error = devcgroup_inode_mknod(mode, dev);
372808ce5f16SSerge E. Hallyn 	if (error)
372908ce5f16SSerge E. Hallyn 		return error;
373008ce5f16SSerge E. Hallyn 
37311da177e4SLinus Torvalds 	error = security_inode_mknod(dir, dentry, mode, dev);
37321da177e4SLinus Torvalds 	if (error)
37331da177e4SLinus Torvalds 		return error;
37341da177e4SLinus Torvalds 
3735549c7297SChristian Brauner 	error = dir->i_op->mknod(mnt_userns, dir, dentry, mode, dev);
3736a74574aaSStephen Smalley 	if (!error)
3737f38aa942SAmy Griffis 		fsnotify_create(dir, dentry);
37381da177e4SLinus Torvalds 	return error;
37391da177e4SLinus Torvalds }
37404d359507SAl Viro EXPORT_SYMBOL(vfs_mknod);
37411da177e4SLinus Torvalds 
3742f69aac00SAl Viro static int may_mknod(umode_t mode)
3743463c3197SDave Hansen {
3744463c3197SDave Hansen 	switch (mode & S_IFMT) {
3745463c3197SDave Hansen 	case S_IFREG:
3746463c3197SDave Hansen 	case S_IFCHR:
3747463c3197SDave Hansen 	case S_IFBLK:
3748463c3197SDave Hansen 	case S_IFIFO:
3749463c3197SDave Hansen 	case S_IFSOCK:
3750463c3197SDave Hansen 	case 0: /* zero mode translates to S_IFREG */
3751463c3197SDave Hansen 		return 0;
3752463c3197SDave Hansen 	case S_IFDIR:
3753463c3197SDave Hansen 		return -EPERM;
3754463c3197SDave Hansen 	default:
3755463c3197SDave Hansen 		return -EINVAL;
3756463c3197SDave Hansen 	}
3757463c3197SDave Hansen }
3758463c3197SDave Hansen 
37595fee64fcSChristoph Hellwig static long do_mknodat(int dfd, const char __user *filename, umode_t mode,
376087c4e192SDominik Brodowski 		unsigned int dev)
37611da177e4SLinus Torvalds {
37626521f891SChristian Brauner 	struct user_namespace *mnt_userns;
37631da177e4SLinus Torvalds 	struct dentry *dentry;
3764dae6ad8fSAl Viro 	struct path path;
3765dae6ad8fSAl Viro 	int error;
3766972567f1SJeff Layton 	unsigned int lookup_flags = 0;
37671da177e4SLinus Torvalds 
37688e4bfca1SAl Viro 	error = may_mknod(mode);
37698e4bfca1SAl Viro 	if (error)
37708e4bfca1SAl Viro 		return error;
3771972567f1SJeff Layton retry:
3772972567f1SJeff Layton 	dentry = user_path_create(dfd, filename, &path, lookup_flags);
3773dae6ad8fSAl Viro 	if (IS_ERR(dentry))
3774dae6ad8fSAl Viro 		return PTR_ERR(dentry);
37752ad94ae6SAl Viro 
3776dae6ad8fSAl Viro 	if (!IS_POSIXACL(path.dentry->d_inode))
3777ce3b0f8dSAl Viro 		mode &= ~current_umask();
3778dae6ad8fSAl Viro 	error = security_path_mknod(&path, dentry, mode, dev);
3779be6d3e56SKentaro Takeda 	if (error)
3780a8104a9fSAl Viro 		goto out;
37816521f891SChristian Brauner 
37826521f891SChristian Brauner 	mnt_userns = mnt_user_ns(path.mnt);
37831da177e4SLinus Torvalds 	switch (mode & S_IFMT) {
37841da177e4SLinus Torvalds 		case 0: case S_IFREG:
37856521f891SChristian Brauner 			error = vfs_create(mnt_userns, path.dentry->d_inode,
37866521f891SChristian Brauner 					   dentry, mode, true);
378705d1a717SMimi Zohar 			if (!error)
3788a2d2329eSChristian Brauner 				ima_post_path_mknod(mnt_userns, dentry);
37891da177e4SLinus Torvalds 			break;
37901da177e4SLinus Torvalds 		case S_IFCHR: case S_IFBLK:
37916521f891SChristian Brauner 			error = vfs_mknod(mnt_userns, path.dentry->d_inode,
37926521f891SChristian Brauner 					  dentry, mode, new_decode_dev(dev));
37931da177e4SLinus Torvalds 			break;
37941da177e4SLinus Torvalds 		case S_IFIFO: case S_IFSOCK:
37956521f891SChristian Brauner 			error = vfs_mknod(mnt_userns, path.dentry->d_inode,
37966521f891SChristian Brauner 					  dentry, mode, 0);
37971da177e4SLinus Torvalds 			break;
37981da177e4SLinus Torvalds 	}
3799a8104a9fSAl Viro out:
3800921a1650SAl Viro 	done_path_create(&path, dentry);
3801972567f1SJeff Layton 	if (retry_estale(error, lookup_flags)) {
3802972567f1SJeff Layton 		lookup_flags |= LOOKUP_REVAL;
3803972567f1SJeff Layton 		goto retry;
3804972567f1SJeff Layton 	}
38051da177e4SLinus Torvalds 	return error;
38061da177e4SLinus Torvalds }
38071da177e4SLinus Torvalds 
380887c4e192SDominik Brodowski SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, umode_t, mode,
380987c4e192SDominik Brodowski 		unsigned int, dev)
381087c4e192SDominik Brodowski {
381187c4e192SDominik Brodowski 	return do_mknodat(dfd, filename, mode, dev);
381287c4e192SDominik Brodowski }
381387c4e192SDominik Brodowski 
38148208a22bSAl Viro SYSCALL_DEFINE3(mknod, const char __user *, filename, umode_t, mode, unsigned, dev)
38155590ff0dSUlrich Drepper {
381687c4e192SDominik Brodowski 	return do_mknodat(AT_FDCWD, filename, mode, dev);
38175590ff0dSUlrich Drepper }
38185590ff0dSUlrich Drepper 
38196521f891SChristian Brauner /**
38206521f891SChristian Brauner  * vfs_mkdir - create directory
38216521f891SChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
38226521f891SChristian Brauner  * @dir:	inode of @dentry
38236521f891SChristian Brauner  * @dentry:	pointer to dentry of the base directory
38246521f891SChristian Brauner  * @mode:	mode of the new directory
38256521f891SChristian Brauner  *
38266521f891SChristian Brauner  * Create a directory.
38276521f891SChristian Brauner  *
38286521f891SChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
38296521f891SChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
38306521f891SChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
38316521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
38326521f891SChristian Brauner  * raw inode simply passs init_user_ns.
38336521f891SChristian Brauner  */
38346521f891SChristian Brauner int vfs_mkdir(struct user_namespace *mnt_userns, struct inode *dir,
38356521f891SChristian Brauner 	      struct dentry *dentry, umode_t mode)
38361da177e4SLinus Torvalds {
38376521f891SChristian Brauner 	int error = may_create(mnt_userns, dir, dentry);
38388de52778SAl Viro 	unsigned max_links = dir->i_sb->s_max_links;
38391da177e4SLinus Torvalds 
38401da177e4SLinus Torvalds 	if (error)
38411da177e4SLinus Torvalds 		return error;
38421da177e4SLinus Torvalds 
3843acfa4380SAl Viro 	if (!dir->i_op->mkdir)
38441da177e4SLinus Torvalds 		return -EPERM;
38451da177e4SLinus Torvalds 
38461da177e4SLinus Torvalds 	mode &= (S_IRWXUGO|S_ISVTX);
38471da177e4SLinus Torvalds 	error = security_inode_mkdir(dir, dentry, mode);
38481da177e4SLinus Torvalds 	if (error)
38491da177e4SLinus Torvalds 		return error;
38501da177e4SLinus Torvalds 
38518de52778SAl Viro 	if (max_links && dir->i_nlink >= max_links)
38528de52778SAl Viro 		return -EMLINK;
38538de52778SAl Viro 
3854549c7297SChristian Brauner 	error = dir->i_op->mkdir(mnt_userns, dir, dentry, mode);
3855a74574aaSStephen Smalley 	if (!error)
3856f38aa942SAmy Griffis 		fsnotify_mkdir(dir, dentry);
38571da177e4SLinus Torvalds 	return error;
38581da177e4SLinus Torvalds }
38594d359507SAl Viro EXPORT_SYMBOL(vfs_mkdir);
38601da177e4SLinus Torvalds 
386183ff98c3SChristoph Hellwig static long do_mkdirat(int dfd, const char __user *pathname, umode_t mode)
38621da177e4SLinus Torvalds {
38636902d925SDave Hansen 	struct dentry *dentry;
3864dae6ad8fSAl Viro 	struct path path;
3865dae6ad8fSAl Viro 	int error;
3866b76d8b82SJeff Layton 	unsigned int lookup_flags = LOOKUP_DIRECTORY;
38671da177e4SLinus Torvalds 
3868b76d8b82SJeff Layton retry:
3869b76d8b82SJeff Layton 	dentry = user_path_create(dfd, pathname, &path, lookup_flags);
38706902d925SDave Hansen 	if (IS_ERR(dentry))
3871dae6ad8fSAl Viro 		return PTR_ERR(dentry);
38726902d925SDave Hansen 
3873dae6ad8fSAl Viro 	if (!IS_POSIXACL(path.dentry->d_inode))
3874ce3b0f8dSAl Viro 		mode &= ~current_umask();
3875dae6ad8fSAl Viro 	error = security_path_mkdir(&path, dentry, mode);
38766521f891SChristian Brauner 	if (!error) {
38776521f891SChristian Brauner 		struct user_namespace *mnt_userns;
38786521f891SChristian Brauner 		mnt_userns = mnt_user_ns(path.mnt);
3879549c7297SChristian Brauner 		error = vfs_mkdir(mnt_userns, path.dentry->d_inode, dentry,
3880549c7297SChristian Brauner 				  mode);
38816521f891SChristian Brauner 	}
3882921a1650SAl Viro 	done_path_create(&path, dentry);
3883b76d8b82SJeff Layton 	if (retry_estale(error, lookup_flags)) {
3884b76d8b82SJeff Layton 		lookup_flags |= LOOKUP_REVAL;
3885b76d8b82SJeff Layton 		goto retry;
3886b76d8b82SJeff Layton 	}
38871da177e4SLinus Torvalds 	return error;
38881da177e4SLinus Torvalds }
38891da177e4SLinus Torvalds 
38900101db7aSDominik Brodowski SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, umode_t, mode)
38910101db7aSDominik Brodowski {
38920101db7aSDominik Brodowski 	return do_mkdirat(dfd, pathname, mode);
38930101db7aSDominik Brodowski }
38940101db7aSDominik Brodowski 
3895a218d0fdSAl Viro SYSCALL_DEFINE2(mkdir, const char __user *, pathname, umode_t, mode)
38965590ff0dSUlrich Drepper {
38970101db7aSDominik Brodowski 	return do_mkdirat(AT_FDCWD, pathname, mode);
38985590ff0dSUlrich Drepper }
38995590ff0dSUlrich Drepper 
39006521f891SChristian Brauner /**
39016521f891SChristian Brauner  * vfs_rmdir - remove directory
39026521f891SChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
39036521f891SChristian Brauner  * @dir:	inode of @dentry
39046521f891SChristian Brauner  * @dentry:	pointer to dentry of the base directory
39056521f891SChristian Brauner  *
39066521f891SChristian Brauner  * Remove a directory.
39076521f891SChristian Brauner  *
39086521f891SChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
39096521f891SChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
39106521f891SChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
39116521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
39126521f891SChristian Brauner  * raw inode simply passs init_user_ns.
39136521f891SChristian Brauner  */
39146521f891SChristian Brauner int vfs_rmdir(struct user_namespace *mnt_userns, struct inode *dir,
39156521f891SChristian Brauner 		     struct dentry *dentry)
39161da177e4SLinus Torvalds {
39176521f891SChristian Brauner 	int error = may_delete(mnt_userns, dir, dentry, 1);
39181da177e4SLinus Torvalds 
39191da177e4SLinus Torvalds 	if (error)
39201da177e4SLinus Torvalds 		return error;
39211da177e4SLinus Torvalds 
3922acfa4380SAl Viro 	if (!dir->i_op->rmdir)
39231da177e4SLinus Torvalds 		return -EPERM;
39241da177e4SLinus Torvalds 
39251d2ef590SAl Viro 	dget(dentry);
39265955102cSAl Viro 	inode_lock(dentry->d_inode);
3927912dbc15SSage Weil 
39281da177e4SLinus Torvalds 	error = -EBUSY;
39297af1364fSEric W. Biederman 	if (is_local_mountpoint(dentry))
3930912dbc15SSage Weil 		goto out;
3931912dbc15SSage Weil 
39321da177e4SLinus Torvalds 	error = security_inode_rmdir(dir, dentry);
3933912dbc15SSage Weil 	if (error)
3934912dbc15SSage Weil 		goto out;
3935912dbc15SSage Weil 
39361da177e4SLinus Torvalds 	error = dir->i_op->rmdir(dir, dentry);
3937912dbc15SSage Weil 	if (error)
3938912dbc15SSage Weil 		goto out;
3939912dbc15SSage Weil 
39408767712fSAl Viro 	shrink_dcache_parent(dentry);
39411da177e4SLinus Torvalds 	dentry->d_inode->i_flags |= S_DEAD;
3942d83c49f3SAl Viro 	dont_mount(dentry);
39438ed936b5SEric W. Biederman 	detach_mounts(dentry);
3944116b9731SAmir Goldstein 	fsnotify_rmdir(dir, dentry);
39451da177e4SLinus Torvalds 
3946912dbc15SSage Weil out:
39475955102cSAl Viro 	inode_unlock(dentry->d_inode);
39481d2ef590SAl Viro 	dput(dentry);
3949912dbc15SSage Weil 	if (!error)
3950912dbc15SSage Weil 		d_delete(dentry);
39511da177e4SLinus Torvalds 	return error;
39521da177e4SLinus Torvalds }
39534d359507SAl Viro EXPORT_SYMBOL(vfs_rmdir);
39541da177e4SLinus Torvalds 
3955e24ab0efSChristoph Hellwig long do_rmdir(int dfd, struct filename *name)
39561da177e4SLinus Torvalds {
39576521f891SChristian Brauner 	struct user_namespace *mnt_userns;
39581da177e4SLinus Torvalds 	int error = 0;
39591da177e4SLinus Torvalds 	struct dentry *dentry;
3960f5beed75SAl Viro 	struct path path;
3961f5beed75SAl Viro 	struct qstr last;
3962f5beed75SAl Viro 	int type;
3963c6ee9206SJeff Layton 	unsigned int lookup_flags = 0;
3964c6ee9206SJeff Layton retry:
3965e24ab0efSChristoph Hellwig 	name = filename_parentat(dfd, name, lookup_flags,
3966c1d4dd27SAl Viro 				&path, &last, &type);
396791a27b2aSJeff Layton 	if (IS_ERR(name))
396891a27b2aSJeff Layton 		return PTR_ERR(name);
39691da177e4SLinus Torvalds 
3970f5beed75SAl Viro 	switch (type) {
39711da177e4SLinus Torvalds 	case LAST_DOTDOT:
39721da177e4SLinus Torvalds 		error = -ENOTEMPTY;
39731da177e4SLinus Torvalds 		goto exit1;
39741da177e4SLinus Torvalds 	case LAST_DOT:
39751da177e4SLinus Torvalds 		error = -EINVAL;
39761da177e4SLinus Torvalds 		goto exit1;
39771da177e4SLinus Torvalds 	case LAST_ROOT:
39781da177e4SLinus Torvalds 		error = -EBUSY;
39791da177e4SLinus Torvalds 		goto exit1;
39801da177e4SLinus Torvalds 	}
39810612d9fbSOGAWA Hirofumi 
3982f5beed75SAl Viro 	error = mnt_want_write(path.mnt);
3983c30dabfeSJan Kara 	if (error)
3984c30dabfeSJan Kara 		goto exit1;
39850612d9fbSOGAWA Hirofumi 
39865955102cSAl Viro 	inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
3987f5beed75SAl Viro 	dentry = __lookup_hash(&last, path.dentry, lookup_flags);
39881da177e4SLinus Torvalds 	error = PTR_ERR(dentry);
39896902d925SDave Hansen 	if (IS_ERR(dentry))
39906902d925SDave Hansen 		goto exit2;
3991e6bc45d6STheodore Ts'o 	if (!dentry->d_inode) {
3992e6bc45d6STheodore Ts'o 		error = -ENOENT;
3993e6bc45d6STheodore Ts'o 		goto exit3;
3994e6bc45d6STheodore Ts'o 	}
3995f5beed75SAl Viro 	error = security_path_rmdir(&path, dentry);
3996be6d3e56SKentaro Takeda 	if (error)
3997c30dabfeSJan Kara 		goto exit3;
39986521f891SChristian Brauner 	mnt_userns = mnt_user_ns(path.mnt);
39996521f891SChristian Brauner 	error = vfs_rmdir(mnt_userns, path.dentry->d_inode, dentry);
40000622753bSDave Hansen exit3:
40011da177e4SLinus Torvalds 	dput(dentry);
40026902d925SDave Hansen exit2:
40035955102cSAl Viro 	inode_unlock(path.dentry->d_inode);
4004f5beed75SAl Viro 	mnt_drop_write(path.mnt);
40051da177e4SLinus Torvalds exit1:
4006f5beed75SAl Viro 	path_put(&path);
4007c6ee9206SJeff Layton 	if (retry_estale(error, lookup_flags)) {
4008c6ee9206SJeff Layton 		lookup_flags |= LOOKUP_REVAL;
4009c6ee9206SJeff Layton 		goto retry;
4010c6ee9206SJeff Layton 	}
401124fb33d4SAl Viro 	putname(name);
40121da177e4SLinus Torvalds 	return error;
40131da177e4SLinus Torvalds }
40141da177e4SLinus Torvalds 
40153cdad428SHeiko Carstens SYSCALL_DEFINE1(rmdir, const char __user *, pathname)
40165590ff0dSUlrich Drepper {
4017e24ab0efSChristoph Hellwig 	return do_rmdir(AT_FDCWD, getname(pathname));
40185590ff0dSUlrich Drepper }
40195590ff0dSUlrich Drepper 
4020b21996e3SJ. Bruce Fields /**
4021b21996e3SJ. Bruce Fields  * vfs_unlink - unlink a filesystem object
40226521f891SChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
4023b21996e3SJ. Bruce Fields  * @dir:	parent directory
4024b21996e3SJ. Bruce Fields  * @dentry:	victim
4025b21996e3SJ. Bruce Fields  * @delegated_inode: returns victim inode, if the inode is delegated.
4026b21996e3SJ. Bruce Fields  *
4027b21996e3SJ. Bruce Fields  * The caller must hold dir->i_mutex.
4028b21996e3SJ. Bruce Fields  *
4029b21996e3SJ. Bruce Fields  * If vfs_unlink discovers a delegation, it will return -EWOULDBLOCK and
4030b21996e3SJ. Bruce Fields  * return a reference to the inode in delegated_inode.  The caller
4031b21996e3SJ. Bruce Fields  * should then break the delegation on that inode and retry.  Because
4032b21996e3SJ. Bruce Fields  * breaking a delegation may take a long time, the caller should drop
4033b21996e3SJ. Bruce Fields  * dir->i_mutex before doing so.
4034b21996e3SJ. Bruce Fields  *
4035b21996e3SJ. Bruce Fields  * Alternatively, a caller may pass NULL for delegated_inode.  This may
4036b21996e3SJ. Bruce Fields  * be appropriate for callers that expect the underlying filesystem not
4037b21996e3SJ. Bruce Fields  * to be NFS exported.
40386521f891SChristian Brauner  *
40396521f891SChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
40406521f891SChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
40416521f891SChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
40426521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
40436521f891SChristian Brauner  * raw inode simply passs init_user_ns.
4044b21996e3SJ. Bruce Fields  */
40456521f891SChristian Brauner int vfs_unlink(struct user_namespace *mnt_userns, struct inode *dir,
40466521f891SChristian Brauner 	       struct dentry *dentry, struct inode **delegated_inode)
40471da177e4SLinus Torvalds {
40489accbb97SJ. Bruce Fields 	struct inode *target = dentry->d_inode;
40496521f891SChristian Brauner 	int error = may_delete(mnt_userns, dir, dentry, 0);
40501da177e4SLinus Torvalds 
40511da177e4SLinus Torvalds 	if (error)
40521da177e4SLinus Torvalds 		return error;
40531da177e4SLinus Torvalds 
4054acfa4380SAl Viro 	if (!dir->i_op->unlink)
40551da177e4SLinus Torvalds 		return -EPERM;
40561da177e4SLinus Torvalds 
40575955102cSAl Viro 	inode_lock(target);
40588ed936b5SEric W. Biederman 	if (is_local_mountpoint(dentry))
40591da177e4SLinus Torvalds 		error = -EBUSY;
40601da177e4SLinus Torvalds 	else {
40611da177e4SLinus Torvalds 		error = security_inode_unlink(dir, dentry);
4062bec1052eSAl Viro 		if (!error) {
40635a14696cSJ. Bruce Fields 			error = try_break_deleg(target, delegated_inode);
40645a14696cSJ. Bruce Fields 			if (error)
4065b21996e3SJ. Bruce Fields 				goto out;
40661da177e4SLinus Torvalds 			error = dir->i_op->unlink(dir, dentry);
40678ed936b5SEric W. Biederman 			if (!error) {
4068d83c49f3SAl Viro 				dont_mount(dentry);
40698ed936b5SEric W. Biederman 				detach_mounts(dentry);
4070116b9731SAmir Goldstein 				fsnotify_unlink(dir, dentry);
40718ed936b5SEric W. Biederman 			}
4072bec1052eSAl Viro 		}
40731da177e4SLinus Torvalds 	}
4074b21996e3SJ. Bruce Fields out:
40755955102cSAl Viro 	inode_unlock(target);
40761da177e4SLinus Torvalds 
40771da177e4SLinus Torvalds 	/* We don't d_delete() NFS sillyrenamed files--they still exist. */
40781da177e4SLinus Torvalds 	if (!error && !(dentry->d_flags & DCACHE_NFSFS_RENAMED)) {
40799accbb97SJ. Bruce Fields 		fsnotify_link_count(target);
40801da177e4SLinus Torvalds 		d_delete(dentry);
40811da177e4SLinus Torvalds 	}
40820eeca283SRobert Love 
40831da177e4SLinus Torvalds 	return error;
40841da177e4SLinus Torvalds }
40854d359507SAl Viro EXPORT_SYMBOL(vfs_unlink);
40861da177e4SLinus Torvalds 
40871da177e4SLinus Torvalds /*
40881da177e4SLinus Torvalds  * Make sure that the actual truncation of the file will occur outside its
40891b1dcc1bSJes Sorensen  * directory's i_mutex.  Truncate can take a long time if there is a lot of
40901da177e4SLinus Torvalds  * writeout happening, and we don't want to prevent access to the directory
40911da177e4SLinus Torvalds  * while waiting on the I/O.
40921da177e4SLinus Torvalds  */
4093da2f1362SChristoph Hellwig long do_unlinkat(int dfd, struct filename *name)
40941da177e4SLinus Torvalds {
40952ad94ae6SAl Viro 	int error;
40961da177e4SLinus Torvalds 	struct dentry *dentry;
4097f5beed75SAl Viro 	struct path path;
4098f5beed75SAl Viro 	struct qstr last;
4099f5beed75SAl Viro 	int type;
41001da177e4SLinus Torvalds 	struct inode *inode = NULL;
4101b21996e3SJ. Bruce Fields 	struct inode *delegated_inode = NULL;
41025d18f813SJeff Layton 	unsigned int lookup_flags = 0;
41035d18f813SJeff Layton retry:
4104da2f1362SChristoph Hellwig 	name = filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
410591a27b2aSJeff Layton 	if (IS_ERR(name))
410691a27b2aSJeff Layton 		return PTR_ERR(name);
41072ad94ae6SAl Viro 
41081da177e4SLinus Torvalds 	error = -EISDIR;
4109f5beed75SAl Viro 	if (type != LAST_NORM)
41101da177e4SLinus Torvalds 		goto exit1;
41110612d9fbSOGAWA Hirofumi 
4112f5beed75SAl Viro 	error = mnt_want_write(path.mnt);
4113c30dabfeSJan Kara 	if (error)
4114c30dabfeSJan Kara 		goto exit1;
4115b21996e3SJ. Bruce Fields retry_deleg:
41165955102cSAl Viro 	inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
4117f5beed75SAl Viro 	dentry = __lookup_hash(&last, path.dentry, lookup_flags);
41181da177e4SLinus Torvalds 	error = PTR_ERR(dentry);
41191da177e4SLinus Torvalds 	if (!IS_ERR(dentry)) {
41206521f891SChristian Brauner 		struct user_namespace *mnt_userns;
41216521f891SChristian Brauner 
41221da177e4SLinus Torvalds 		/* Why not before? Because we want correct error value */
4123f5beed75SAl Viro 		if (last.name[last.len])
412450338b88STörök Edwin 			goto slashes;
41251da177e4SLinus Torvalds 		inode = dentry->d_inode;
4126b18825a7SDavid Howells 		if (d_is_negative(dentry))
4127e6bc45d6STheodore Ts'o 			goto slashes;
41287de9c6eeSAl Viro 		ihold(inode);
4129f5beed75SAl Viro 		error = security_path_unlink(&path, dentry);
4130be6d3e56SKentaro Takeda 		if (error)
4131c30dabfeSJan Kara 			goto exit2;
41326521f891SChristian Brauner 		mnt_userns = mnt_user_ns(path.mnt);
4133549c7297SChristian Brauner 		error = vfs_unlink(mnt_userns, path.dentry->d_inode, dentry,
4134549c7297SChristian Brauner 				   &delegated_inode);
41351da177e4SLinus Torvalds exit2:
41361da177e4SLinus Torvalds 		dput(dentry);
41371da177e4SLinus Torvalds 	}
41385955102cSAl Viro 	inode_unlock(path.dentry->d_inode);
41391da177e4SLinus Torvalds 	if (inode)
41401da177e4SLinus Torvalds 		iput(inode);	/* truncate the inode here */
4141b21996e3SJ. Bruce Fields 	inode = NULL;
4142b21996e3SJ. Bruce Fields 	if (delegated_inode) {
41435a14696cSJ. Bruce Fields 		error = break_deleg_wait(&delegated_inode);
4144b21996e3SJ. Bruce Fields 		if (!error)
4145b21996e3SJ. Bruce Fields 			goto retry_deleg;
4146b21996e3SJ. Bruce Fields 	}
4147f5beed75SAl Viro 	mnt_drop_write(path.mnt);
41481da177e4SLinus Torvalds exit1:
4149f5beed75SAl Viro 	path_put(&path);
41505d18f813SJeff Layton 	if (retry_estale(error, lookup_flags)) {
41515d18f813SJeff Layton 		lookup_flags |= LOOKUP_REVAL;
41525d18f813SJeff Layton 		inode = NULL;
41535d18f813SJeff Layton 		goto retry;
41545d18f813SJeff Layton 	}
4155da2f1362SChristoph Hellwig 	putname(name);
41561da177e4SLinus Torvalds 	return error;
41571da177e4SLinus Torvalds 
41581da177e4SLinus Torvalds slashes:
4159b18825a7SDavid Howells 	if (d_is_negative(dentry))
4160b18825a7SDavid Howells 		error = -ENOENT;
416144b1d530SMiklos Szeredi 	else if (d_is_dir(dentry))
4162b18825a7SDavid Howells 		error = -EISDIR;
4163b18825a7SDavid Howells 	else
4164b18825a7SDavid Howells 		error = -ENOTDIR;
41651da177e4SLinus Torvalds 	goto exit2;
41661da177e4SLinus Torvalds }
41671da177e4SLinus Torvalds 
41682e4d0924SHeiko Carstens SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag)
41695590ff0dSUlrich Drepper {
41705590ff0dSUlrich Drepper 	if ((flag & ~AT_REMOVEDIR) != 0)
41715590ff0dSUlrich Drepper 		return -EINVAL;
41725590ff0dSUlrich Drepper 
41735590ff0dSUlrich Drepper 	if (flag & AT_REMOVEDIR)
4174e24ab0efSChristoph Hellwig 		return do_rmdir(dfd, getname(pathname));
4175da2f1362SChristoph Hellwig 	return do_unlinkat(dfd, getname(pathname));
41765590ff0dSUlrich Drepper }
41775590ff0dSUlrich Drepper 
41783480b257SHeiko Carstens SYSCALL_DEFINE1(unlink, const char __user *, pathname)
41795590ff0dSUlrich Drepper {
4180da2f1362SChristoph Hellwig 	return do_unlinkat(AT_FDCWD, getname(pathname));
41815590ff0dSUlrich Drepper }
41825590ff0dSUlrich Drepper 
41836521f891SChristian Brauner /**
41846521f891SChristian Brauner  * vfs_symlink - create symlink
41856521f891SChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
41866521f891SChristian Brauner  * @dir:	inode of @dentry
41876521f891SChristian Brauner  * @dentry:	pointer to dentry of the base directory
41886521f891SChristian Brauner  * @oldname:	name of the file to link to
41896521f891SChristian Brauner  *
41906521f891SChristian Brauner  * Create a symlink.
41916521f891SChristian Brauner  *
41926521f891SChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
41936521f891SChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
41946521f891SChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
41956521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
41966521f891SChristian Brauner  * raw inode simply passs init_user_ns.
41976521f891SChristian Brauner  */
41986521f891SChristian Brauner int vfs_symlink(struct user_namespace *mnt_userns, struct inode *dir,
41996521f891SChristian Brauner 		struct dentry *dentry, const char *oldname)
42001da177e4SLinus Torvalds {
42016521f891SChristian Brauner 	int error = may_create(mnt_userns, dir, dentry);
42021da177e4SLinus Torvalds 
42031da177e4SLinus Torvalds 	if (error)
42041da177e4SLinus Torvalds 		return error;
42051da177e4SLinus Torvalds 
4206acfa4380SAl Viro 	if (!dir->i_op->symlink)
42071da177e4SLinus Torvalds 		return -EPERM;
42081da177e4SLinus Torvalds 
42091da177e4SLinus Torvalds 	error = security_inode_symlink(dir, dentry, oldname);
42101da177e4SLinus Torvalds 	if (error)
42111da177e4SLinus Torvalds 		return error;
42121da177e4SLinus Torvalds 
4213549c7297SChristian Brauner 	error = dir->i_op->symlink(mnt_userns, dir, dentry, oldname);
4214a74574aaSStephen Smalley 	if (!error)
4215f38aa942SAmy Griffis 		fsnotify_create(dir, dentry);
42161da177e4SLinus Torvalds 	return error;
42171da177e4SLinus Torvalds }
42184d359507SAl Viro EXPORT_SYMBOL(vfs_symlink);
42191da177e4SLinus Torvalds 
4220cd3acb6aSChristoph Hellwig static long do_symlinkat(const char __user *oldname, int newdfd,
4221b724e846SDominik Brodowski 		  const char __user *newname)
42221da177e4SLinus Torvalds {
42232ad94ae6SAl Viro 	int error;
422491a27b2aSJeff Layton 	struct filename *from;
42256902d925SDave Hansen 	struct dentry *dentry;
4226dae6ad8fSAl Viro 	struct path path;
4227f46d3567SJeff Layton 	unsigned int lookup_flags = 0;
42281da177e4SLinus Torvalds 
42291da177e4SLinus Torvalds 	from = getname(oldname);
42301da177e4SLinus Torvalds 	if (IS_ERR(from))
42311da177e4SLinus Torvalds 		return PTR_ERR(from);
4232f46d3567SJeff Layton retry:
4233f46d3567SJeff Layton 	dentry = user_path_create(newdfd, newname, &path, lookup_flags);
42341da177e4SLinus Torvalds 	error = PTR_ERR(dentry);
42356902d925SDave Hansen 	if (IS_ERR(dentry))
4236dae6ad8fSAl Viro 		goto out_putname;
42376902d925SDave Hansen 
423891a27b2aSJeff Layton 	error = security_path_symlink(&path, dentry, from->name);
42396521f891SChristian Brauner 	if (!error) {
42406521f891SChristian Brauner 		struct user_namespace *mnt_userns;
42416521f891SChristian Brauner 
42426521f891SChristian Brauner 		mnt_userns = mnt_user_ns(path.mnt);
42436521f891SChristian Brauner 		error = vfs_symlink(mnt_userns, path.dentry->d_inode, dentry,
42446521f891SChristian Brauner 				    from->name);
42456521f891SChristian Brauner 	}
4246921a1650SAl Viro 	done_path_create(&path, dentry);
4247f46d3567SJeff Layton 	if (retry_estale(error, lookup_flags)) {
4248f46d3567SJeff Layton 		lookup_flags |= LOOKUP_REVAL;
4249f46d3567SJeff Layton 		goto retry;
4250f46d3567SJeff Layton 	}
42516902d925SDave Hansen out_putname:
42521da177e4SLinus Torvalds 	putname(from);
42531da177e4SLinus Torvalds 	return error;
42541da177e4SLinus Torvalds }
42551da177e4SLinus Torvalds 
4256b724e846SDominik Brodowski SYSCALL_DEFINE3(symlinkat, const char __user *, oldname,
4257b724e846SDominik Brodowski 		int, newdfd, const char __user *, newname)
4258b724e846SDominik Brodowski {
4259b724e846SDominik Brodowski 	return do_symlinkat(oldname, newdfd, newname);
4260b724e846SDominik Brodowski }
4261b724e846SDominik Brodowski 
42623480b257SHeiko Carstens SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname)
42635590ff0dSUlrich Drepper {
4264b724e846SDominik Brodowski 	return do_symlinkat(oldname, AT_FDCWD, newname);
42655590ff0dSUlrich Drepper }
42665590ff0dSUlrich Drepper 
4267146a8595SJ. Bruce Fields /**
4268146a8595SJ. Bruce Fields  * vfs_link - create a new link
4269146a8595SJ. Bruce Fields  * @old_dentry:	object to be linked
42706521f891SChristian Brauner  * @mnt_userns:	the user namespace of the mount
4271146a8595SJ. Bruce Fields  * @dir:	new parent
4272146a8595SJ. Bruce Fields  * @new_dentry:	where to create the new link
4273146a8595SJ. Bruce Fields  * @delegated_inode: returns inode needing a delegation break
4274146a8595SJ. Bruce Fields  *
4275146a8595SJ. Bruce Fields  * The caller must hold dir->i_mutex
4276146a8595SJ. Bruce Fields  *
4277146a8595SJ. Bruce Fields  * If vfs_link discovers a delegation on the to-be-linked file in need
4278146a8595SJ. Bruce Fields  * of breaking, it will return -EWOULDBLOCK and return a reference to the
4279146a8595SJ. Bruce Fields  * inode in delegated_inode.  The caller should then break the delegation
4280146a8595SJ. Bruce Fields  * and retry.  Because breaking a delegation may take a long time, the
4281146a8595SJ. Bruce Fields  * caller should drop the i_mutex before doing so.
4282146a8595SJ. Bruce Fields  *
4283146a8595SJ. Bruce Fields  * Alternatively, a caller may pass NULL for delegated_inode.  This may
4284146a8595SJ. Bruce Fields  * be appropriate for callers that expect the underlying filesystem not
4285146a8595SJ. Bruce Fields  * to be NFS exported.
42866521f891SChristian Brauner  *
42876521f891SChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
42886521f891SChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
42896521f891SChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
42906521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
42916521f891SChristian Brauner  * raw inode simply passs init_user_ns.
4292146a8595SJ. Bruce Fields  */
42936521f891SChristian Brauner int vfs_link(struct dentry *old_dentry, struct user_namespace *mnt_userns,
42946521f891SChristian Brauner 	     struct inode *dir, struct dentry *new_dentry,
42956521f891SChristian Brauner 	     struct inode **delegated_inode)
42961da177e4SLinus Torvalds {
42971da177e4SLinus Torvalds 	struct inode *inode = old_dentry->d_inode;
42988de52778SAl Viro 	unsigned max_links = dir->i_sb->s_max_links;
42991da177e4SLinus Torvalds 	int error;
43001da177e4SLinus Torvalds 
43011da177e4SLinus Torvalds 	if (!inode)
43021da177e4SLinus Torvalds 		return -ENOENT;
43031da177e4SLinus Torvalds 
43046521f891SChristian Brauner 	error = may_create(mnt_userns, dir, new_dentry);
43051da177e4SLinus Torvalds 	if (error)
43061da177e4SLinus Torvalds 		return error;
43071da177e4SLinus Torvalds 
43081da177e4SLinus Torvalds 	if (dir->i_sb != inode->i_sb)
43091da177e4SLinus Torvalds 		return -EXDEV;
43101da177e4SLinus Torvalds 
43111da177e4SLinus Torvalds 	/*
43121da177e4SLinus Torvalds 	 * A link to an append-only or immutable file cannot be created.
43131da177e4SLinus Torvalds 	 */
43141da177e4SLinus Torvalds 	if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
43151da177e4SLinus Torvalds 		return -EPERM;
43160bd23d09SEric W. Biederman 	/*
43170bd23d09SEric W. Biederman 	 * Updating the link count will likely cause i_uid and i_gid to
43180bd23d09SEric W. Biederman 	 * be writen back improperly if their true value is unknown to
43190bd23d09SEric W. Biederman 	 * the vfs.
43200bd23d09SEric W. Biederman 	 */
43216521f891SChristian Brauner 	if (HAS_UNMAPPED_ID(mnt_userns, inode))
43220bd23d09SEric W. Biederman 		return -EPERM;
4323acfa4380SAl Viro 	if (!dir->i_op->link)
43241da177e4SLinus Torvalds 		return -EPERM;
43257e79eedbSTetsuo Handa 	if (S_ISDIR(inode->i_mode))
43261da177e4SLinus Torvalds 		return -EPERM;
43271da177e4SLinus Torvalds 
43281da177e4SLinus Torvalds 	error = security_inode_link(old_dentry, dir, new_dentry);
43291da177e4SLinus Torvalds 	if (error)
43301da177e4SLinus Torvalds 		return error;
43311da177e4SLinus Torvalds 
43325955102cSAl Viro 	inode_lock(inode);
4333aae8a97dSAneesh Kumar K.V 	/* Make sure we don't allow creating hardlink to an unlinked file */
4334f4e0c30cSAl Viro 	if (inode->i_nlink == 0 && !(inode->i_state & I_LINKABLE))
4335aae8a97dSAneesh Kumar K.V 		error =  -ENOENT;
43368de52778SAl Viro 	else if (max_links && inode->i_nlink >= max_links)
43378de52778SAl Viro 		error = -EMLINK;
4338146a8595SJ. Bruce Fields 	else {
4339146a8595SJ. Bruce Fields 		error = try_break_deleg(inode, delegated_inode);
4340146a8595SJ. Bruce Fields 		if (!error)
43411da177e4SLinus Torvalds 			error = dir->i_op->link(old_dentry, dir, new_dentry);
4342146a8595SJ. Bruce Fields 	}
4343f4e0c30cSAl Viro 
4344f4e0c30cSAl Viro 	if (!error && (inode->i_state & I_LINKABLE)) {
4345f4e0c30cSAl Viro 		spin_lock(&inode->i_lock);
4346f4e0c30cSAl Viro 		inode->i_state &= ~I_LINKABLE;
4347f4e0c30cSAl Viro 		spin_unlock(&inode->i_lock);
4348f4e0c30cSAl Viro 	}
43495955102cSAl Viro 	inode_unlock(inode);
4350e31e14ecSStephen Smalley 	if (!error)
43517e79eedbSTetsuo Handa 		fsnotify_link(dir, inode, new_dentry);
43521da177e4SLinus Torvalds 	return error;
43531da177e4SLinus Torvalds }
43544d359507SAl Viro EXPORT_SYMBOL(vfs_link);
43551da177e4SLinus Torvalds 
43561da177e4SLinus Torvalds /*
43571da177e4SLinus Torvalds  * Hardlinks are often used in delicate situations.  We avoid
43581da177e4SLinus Torvalds  * security-related surprises by not following symlinks on the
43591da177e4SLinus Torvalds  * newname.  --KAB
43601da177e4SLinus Torvalds  *
43611da177e4SLinus Torvalds  * We don't follow them on the oldname either to be compatible
43621da177e4SLinus Torvalds  * with linux 2.0, and to avoid hard-linking to directories
43631da177e4SLinus Torvalds  * and other special files.  --ADM
43641da177e4SLinus Torvalds  */
4365812931d6SChristoph Hellwig static int do_linkat(int olddfd, const char __user *oldname, int newdfd,
436646ea89ebSDominik Brodowski 	      const char __user *newname, int flags)
43671da177e4SLinus Torvalds {
43686521f891SChristian Brauner 	struct user_namespace *mnt_userns;
43691da177e4SLinus Torvalds 	struct dentry *new_dentry;
4370dae6ad8fSAl Viro 	struct path old_path, new_path;
4371146a8595SJ. Bruce Fields 	struct inode *delegated_inode = NULL;
437211a7b371SAneesh Kumar K.V 	int how = 0;
43731da177e4SLinus Torvalds 	int error;
43741da177e4SLinus Torvalds 
437511a7b371SAneesh Kumar K.V 	if ((flags & ~(AT_SYMLINK_FOLLOW | AT_EMPTY_PATH)) != 0)
4376c04030e1SUlrich Drepper 		return -EINVAL;
437711a7b371SAneesh Kumar K.V 	/*
4378f0cc6ffbSLinus Torvalds 	 * To use null names we require CAP_DAC_READ_SEARCH
4379f0cc6ffbSLinus Torvalds 	 * This ensures that not everyone will be able to create
4380f0cc6ffbSLinus Torvalds 	 * handlink using the passed filedescriptor.
438111a7b371SAneesh Kumar K.V 	 */
4382f0cc6ffbSLinus Torvalds 	if (flags & AT_EMPTY_PATH) {
4383f0cc6ffbSLinus Torvalds 		if (!capable(CAP_DAC_READ_SEARCH))
4384f0cc6ffbSLinus Torvalds 			return -ENOENT;
438511a7b371SAneesh Kumar K.V 		how = LOOKUP_EMPTY;
4386f0cc6ffbSLinus Torvalds 	}
4387c04030e1SUlrich Drepper 
438811a7b371SAneesh Kumar K.V 	if (flags & AT_SYMLINK_FOLLOW)
438911a7b371SAneesh Kumar K.V 		how |= LOOKUP_FOLLOW;
4390442e31caSJeff Layton retry:
439111a7b371SAneesh Kumar K.V 	error = user_path_at(olddfd, oldname, how, &old_path);
43921da177e4SLinus Torvalds 	if (error)
43932ad94ae6SAl Viro 		return error;
43942ad94ae6SAl Viro 
4395442e31caSJeff Layton 	new_dentry = user_path_create(newdfd, newname, &new_path,
4396442e31caSJeff Layton 					(how & LOOKUP_REVAL));
43971da177e4SLinus Torvalds 	error = PTR_ERR(new_dentry);
43986902d925SDave Hansen 	if (IS_ERR(new_dentry))
4399dae6ad8fSAl Viro 		goto out;
4400dae6ad8fSAl Viro 
4401dae6ad8fSAl Viro 	error = -EXDEV;
4402dae6ad8fSAl Viro 	if (old_path.mnt != new_path.mnt)
4403dae6ad8fSAl Viro 		goto out_dput;
4404549c7297SChristian Brauner 	mnt_userns = mnt_user_ns(new_path.mnt);
4405549c7297SChristian Brauner 	error = may_linkat(mnt_userns, &old_path);
4406800179c9SKees Cook 	if (unlikely(error))
4407800179c9SKees Cook 		goto out_dput;
4408dae6ad8fSAl Viro 	error = security_path_link(old_path.dentry, &new_path, new_dentry);
4409be6d3e56SKentaro Takeda 	if (error)
4410a8104a9fSAl Viro 		goto out_dput;
44116521f891SChristian Brauner 	error = vfs_link(old_path.dentry, mnt_userns, new_path.dentry->d_inode,
44126521f891SChristian Brauner 			 new_dentry, &delegated_inode);
441375c3f29dSDave Hansen out_dput:
4414921a1650SAl Viro 	done_path_create(&new_path, new_dentry);
4415146a8595SJ. Bruce Fields 	if (delegated_inode) {
4416146a8595SJ. Bruce Fields 		error = break_deleg_wait(&delegated_inode);
4417d22e6338SOleg Drokin 		if (!error) {
4418d22e6338SOleg Drokin 			path_put(&old_path);
4419146a8595SJ. Bruce Fields 			goto retry;
4420146a8595SJ. Bruce Fields 		}
4421d22e6338SOleg Drokin 	}
4422442e31caSJeff Layton 	if (retry_estale(error, how)) {
4423d22e6338SOleg Drokin 		path_put(&old_path);
4424442e31caSJeff Layton 		how |= LOOKUP_REVAL;
4425442e31caSJeff Layton 		goto retry;
4426442e31caSJeff Layton 	}
44271da177e4SLinus Torvalds out:
44282d8f3038SAl Viro 	path_put(&old_path);
44291da177e4SLinus Torvalds 
44301da177e4SLinus Torvalds 	return error;
44311da177e4SLinus Torvalds }
44321da177e4SLinus Torvalds 
443346ea89ebSDominik Brodowski SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname,
443446ea89ebSDominik Brodowski 		int, newdfd, const char __user *, newname, int, flags)
443546ea89ebSDominik Brodowski {
443646ea89ebSDominik Brodowski 	return do_linkat(olddfd, oldname, newdfd, newname, flags);
443746ea89ebSDominik Brodowski }
443846ea89ebSDominik Brodowski 
44393480b257SHeiko Carstens SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname)
44405590ff0dSUlrich Drepper {
444146ea89ebSDominik Brodowski 	return do_linkat(AT_FDCWD, oldname, AT_FDCWD, newname, 0);
44425590ff0dSUlrich Drepper }
44435590ff0dSUlrich Drepper 
4444bc27027aSMiklos Szeredi /**
4445bc27027aSMiklos Szeredi  * vfs_rename - rename a filesystem object
44462111c3c0SRandy Dunlap  * @rd:		pointer to &struct renamedata info
4447bc27027aSMiklos Szeredi  *
4448bc27027aSMiklos Szeredi  * The caller must hold multiple mutexes--see lock_rename()).
4449bc27027aSMiklos Szeredi  *
4450bc27027aSMiklos Szeredi  * If vfs_rename discovers a delegation in need of breaking at either
4451bc27027aSMiklos Szeredi  * the source or destination, it will return -EWOULDBLOCK and return a
4452bc27027aSMiklos Szeredi  * reference to the inode in delegated_inode.  The caller should then
4453bc27027aSMiklos Szeredi  * break the delegation and retry.  Because breaking a delegation may
4454bc27027aSMiklos Szeredi  * take a long time, the caller should drop all locks before doing
4455bc27027aSMiklos Szeredi  * so.
4456bc27027aSMiklos Szeredi  *
4457bc27027aSMiklos Szeredi  * Alternatively, a caller may pass NULL for delegated_inode.  This may
4458bc27027aSMiklos Szeredi  * be appropriate for callers that expect the underlying filesystem not
4459bc27027aSMiklos Szeredi  * to be NFS exported.
4460bc27027aSMiklos Szeredi  *
44611da177e4SLinus Torvalds  * The worst of all namespace operations - renaming directory. "Perverted"
44621da177e4SLinus Torvalds  * doesn't even start to describe it. Somebody in UCB had a heck of a trip...
44631da177e4SLinus Torvalds  * Problems:
44640117d427SMauro Carvalho Chehab  *
4465d03b29a2SJ. Bruce Fields  *	a) we can get into loop creation.
44661da177e4SLinus Torvalds  *	b) race potential - two innocent renames can create a loop together.
44671da177e4SLinus Torvalds  *	   That's where 4.4 screws up. Current fix: serialization on
4468a11f3a05SArjan van de Ven  *	   sb->s_vfs_rename_mutex. We might be more accurate, but that's another
44691da177e4SLinus Torvalds  *	   story.
44706cedba89SJ. Bruce Fields  *	c) we have to lock _four_ objects - parents and victim (if it exists),
44716cedba89SJ. Bruce Fields  *	   and source (if it is not a directory).
44721b1dcc1bSJes Sorensen  *	   And that - after we got ->i_mutex on parents (until then we don't know
44731da177e4SLinus Torvalds  *	   whether the target exists).  Solution: try to be smart with locking
44741da177e4SLinus Torvalds  *	   order for inodes.  We rely on the fact that tree topology may change
4475a11f3a05SArjan van de Ven  *	   only under ->s_vfs_rename_mutex _and_ that parent of the object we
44761da177e4SLinus Torvalds  *	   move will be locked.  Thus we can rank directories by the tree
44771da177e4SLinus Torvalds  *	   (ancestors first) and rank all non-directories after them.
44781da177e4SLinus Torvalds  *	   That works since everybody except rename does "lock parent, lookup,
4479a11f3a05SArjan van de Ven  *	   lock child" and rename is under ->s_vfs_rename_mutex.
44801da177e4SLinus Torvalds  *	   HOWEVER, it relies on the assumption that any object with ->lookup()
44811da177e4SLinus Torvalds  *	   has no more than 1 dentry.  If "hybrid" objects will ever appear,
44821da177e4SLinus Torvalds  *	   we'd better make sure that there's no link(2) for them.
4483e4eaac06SSage Weil  *	d) conversion from fhandle to dentry may come in the wrong moment - when
44841b1dcc1bSJes Sorensen  *	   we are removing the target. Solution: we will have to grab ->i_mutex
44851da177e4SLinus Torvalds  *	   in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on
4486c41b20e7SAdam Buchbinder  *	   ->i_mutex on parents, which works but leads to some truly excessive
44871da177e4SLinus Torvalds  *	   locking].
44881da177e4SLinus Torvalds  */
44899fe61450SChristian Brauner int vfs_rename(struct renamedata *rd)
44901da177e4SLinus Torvalds {
44911da177e4SLinus Torvalds 	int error;
44929fe61450SChristian Brauner 	struct inode *old_dir = rd->old_dir, *new_dir = rd->new_dir;
44939fe61450SChristian Brauner 	struct dentry *old_dentry = rd->old_dentry;
44949fe61450SChristian Brauner 	struct dentry *new_dentry = rd->new_dentry;
44959fe61450SChristian Brauner 	struct inode **delegated_inode = rd->delegated_inode;
44969fe61450SChristian Brauner 	unsigned int flags = rd->flags;
4497bc27027aSMiklos Szeredi 	bool is_dir = d_is_dir(old_dentry);
4498bc27027aSMiklos Szeredi 	struct inode *source = old_dentry->d_inode;
4499bc27027aSMiklos Szeredi 	struct inode *target = new_dentry->d_inode;
4500da1ce067SMiklos Szeredi 	bool new_is_dir = false;
4501da1ce067SMiklos Szeredi 	unsigned max_links = new_dir->i_sb->s_max_links;
450249d31c2fSAl Viro 	struct name_snapshot old_name;
45031da177e4SLinus Torvalds 
45048d3e2936SMiklos Szeredi 	if (source == target)
45051da177e4SLinus Torvalds 		return 0;
45061da177e4SLinus Torvalds 
45076521f891SChristian Brauner 	error = may_delete(rd->old_mnt_userns, old_dir, old_dentry, is_dir);
45081da177e4SLinus Torvalds 	if (error)
45091da177e4SLinus Torvalds 		return error;
45101da177e4SLinus Torvalds 
4511da1ce067SMiklos Szeredi 	if (!target) {
45126521f891SChristian Brauner 		error = may_create(rd->new_mnt_userns, new_dir, new_dentry);
4513da1ce067SMiklos Szeredi 	} else {
4514da1ce067SMiklos Szeredi 		new_is_dir = d_is_dir(new_dentry);
4515da1ce067SMiklos Szeredi 
4516da1ce067SMiklos Szeredi 		if (!(flags & RENAME_EXCHANGE))
45176521f891SChristian Brauner 			error = may_delete(rd->new_mnt_userns, new_dir,
45186521f891SChristian Brauner 					   new_dentry, is_dir);
4519da1ce067SMiklos Szeredi 		else
45206521f891SChristian Brauner 			error = may_delete(rd->new_mnt_userns, new_dir,
45216521f891SChristian Brauner 					   new_dentry, new_is_dir);
4522da1ce067SMiklos Szeredi 	}
45231da177e4SLinus Torvalds 	if (error)
45241da177e4SLinus Torvalds 		return error;
45251da177e4SLinus Torvalds 
45262773bf00SMiklos Szeredi 	if (!old_dir->i_op->rename)
45271da177e4SLinus Torvalds 		return -EPERM;
45281da177e4SLinus Torvalds 
4529bc27027aSMiklos Szeredi 	/*
4530bc27027aSMiklos Szeredi 	 * If we are going to change the parent - check write permissions,
4531bc27027aSMiklos Szeredi 	 * we'll need to flip '..'.
4532bc27027aSMiklos Szeredi 	 */
4533da1ce067SMiklos Szeredi 	if (new_dir != old_dir) {
4534da1ce067SMiklos Szeredi 		if (is_dir) {
45356521f891SChristian Brauner 			error = inode_permission(rd->old_mnt_userns, source,
453647291baaSChristian Brauner 						 MAY_WRITE);
4537bc27027aSMiklos Szeredi 			if (error)
4538bc27027aSMiklos Szeredi 				return error;
4539bc27027aSMiklos Szeredi 		}
4540da1ce067SMiklos Szeredi 		if ((flags & RENAME_EXCHANGE) && new_is_dir) {
45416521f891SChristian Brauner 			error = inode_permission(rd->new_mnt_userns, target,
454247291baaSChristian Brauner 						 MAY_WRITE);
4543da1ce067SMiklos Szeredi 			if (error)
4544da1ce067SMiklos Szeredi 				return error;
4545da1ce067SMiklos Szeredi 		}
4546da1ce067SMiklos Szeredi 	}
45470eeca283SRobert Love 
45480b3974ebSMiklos Szeredi 	error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,
45490b3974ebSMiklos Szeredi 				      flags);
4550bc27027aSMiklos Szeredi 	if (error)
4551bc27027aSMiklos Szeredi 		return error;
4552bc27027aSMiklos Szeredi 
455349d31c2fSAl Viro 	take_dentry_name_snapshot(&old_name, old_dentry);
4554bc27027aSMiklos Szeredi 	dget(new_dentry);
4555da1ce067SMiklos Szeredi 	if (!is_dir || (flags & RENAME_EXCHANGE))
4556bc27027aSMiklos Szeredi 		lock_two_nondirectories(source, target);
4557bc27027aSMiklos Szeredi 	else if (target)
45585955102cSAl Viro 		inode_lock(target);
4559bc27027aSMiklos Szeredi 
4560bc27027aSMiklos Szeredi 	error = -EBUSY;
45617af1364fSEric W. Biederman 	if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
4562bc27027aSMiklos Szeredi 		goto out;
4563bc27027aSMiklos Szeredi 
4564da1ce067SMiklos Szeredi 	if (max_links && new_dir != old_dir) {
4565bc27027aSMiklos Szeredi 		error = -EMLINK;
4566da1ce067SMiklos Szeredi 		if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)
4567bc27027aSMiklos Szeredi 			goto out;
4568da1ce067SMiklos Szeredi 		if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&
4569da1ce067SMiklos Szeredi 		    old_dir->i_nlink >= max_links)
4570da1ce067SMiklos Szeredi 			goto out;
4571da1ce067SMiklos Szeredi 	}
4572da1ce067SMiklos Szeredi 	if (!is_dir) {
4573bc27027aSMiklos Szeredi 		error = try_break_deleg(source, delegated_inode);
4574bc27027aSMiklos Szeredi 		if (error)
4575bc27027aSMiklos Szeredi 			goto out;
4576da1ce067SMiklos Szeredi 	}
4577da1ce067SMiklos Szeredi 	if (target && !new_is_dir) {
4578bc27027aSMiklos Szeredi 		error = try_break_deleg(target, delegated_inode);
4579bc27027aSMiklos Szeredi 		if (error)
4580bc27027aSMiklos Szeredi 			goto out;
4581bc27027aSMiklos Szeredi 	}
4582549c7297SChristian Brauner 	error = old_dir->i_op->rename(rd->new_mnt_userns, old_dir, old_dentry,
4583520c8b16SMiklos Szeredi 				      new_dir, new_dentry, flags);
4584bc27027aSMiklos Szeredi 	if (error)
4585bc27027aSMiklos Szeredi 		goto out;
4586bc27027aSMiklos Szeredi 
4587da1ce067SMiklos Szeredi 	if (!(flags & RENAME_EXCHANGE) && target) {
45888767712fSAl Viro 		if (is_dir) {
45898767712fSAl Viro 			shrink_dcache_parent(new_dentry);
4590bc27027aSMiklos Szeredi 			target->i_flags |= S_DEAD;
45918767712fSAl Viro 		}
4592bc27027aSMiklos Szeredi 		dont_mount(new_dentry);
45938ed936b5SEric W. Biederman 		detach_mounts(new_dentry);
4594bc27027aSMiklos Szeredi 	}
4595da1ce067SMiklos Szeredi 	if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {
4596da1ce067SMiklos Szeredi 		if (!(flags & RENAME_EXCHANGE))
4597bc27027aSMiklos Szeredi 			d_move(old_dentry, new_dentry);
4598da1ce067SMiklos Szeredi 		else
4599da1ce067SMiklos Szeredi 			d_exchange(old_dentry, new_dentry);
4600da1ce067SMiklos Szeredi 	}
4601bc27027aSMiklos Szeredi out:
4602da1ce067SMiklos Szeredi 	if (!is_dir || (flags & RENAME_EXCHANGE))
4603bc27027aSMiklos Szeredi 		unlock_two_nondirectories(source, target);
4604bc27027aSMiklos Szeredi 	else if (target)
46055955102cSAl Viro 		inode_unlock(target);
4606bc27027aSMiklos Szeredi 	dput(new_dentry);
4607da1ce067SMiklos Szeredi 	if (!error) {
4608f4ec3a3dSAl Viro 		fsnotify_move(old_dir, new_dir, &old_name.name, is_dir,
4609da1ce067SMiklos Szeredi 			      !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);
4610da1ce067SMiklos Szeredi 		if (flags & RENAME_EXCHANGE) {
4611f4ec3a3dSAl Viro 			fsnotify_move(new_dir, old_dir, &old_dentry->d_name,
4612da1ce067SMiklos Szeredi 				      new_is_dir, NULL, new_dentry);
4613da1ce067SMiklos Szeredi 		}
4614da1ce067SMiklos Szeredi 	}
461549d31c2fSAl Viro 	release_dentry_name_snapshot(&old_name);
46160eeca283SRobert Love 
46171da177e4SLinus Torvalds 	return error;
46181da177e4SLinus Torvalds }
46194d359507SAl Viro EXPORT_SYMBOL(vfs_rename);
46201da177e4SLinus Torvalds 
4621e886663cSJens Axboe int do_renameat2(int olddfd, struct filename *from, int newdfd,
4622e886663cSJens Axboe 		 struct filename *to, unsigned int flags)
46231da177e4SLinus Torvalds {
46249fe61450SChristian Brauner 	struct renamedata rd;
46251da177e4SLinus Torvalds 	struct dentry *old_dentry, *new_dentry;
46261da177e4SLinus Torvalds 	struct dentry *trap;
4627f5beed75SAl Viro 	struct path old_path, new_path;
4628f5beed75SAl Viro 	struct qstr old_last, new_last;
4629f5beed75SAl Viro 	int old_type, new_type;
46308e6d782cSJ. Bruce Fields 	struct inode *delegated_inode = NULL;
4631f5beed75SAl Viro 	unsigned int lookup_flags = 0, target_flags = LOOKUP_RENAME_TARGET;
4632c6a94284SJeff Layton 	bool should_retry = false;
4633e886663cSJens Axboe 	int error = -EINVAL;
4634520c8b16SMiklos Szeredi 
46350d7a8555SMiklos Szeredi 	if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
4636e886663cSJens Axboe 		goto put_both;
4637da1ce067SMiklos Szeredi 
46380d7a8555SMiklos Szeredi 	if ((flags & (RENAME_NOREPLACE | RENAME_WHITEOUT)) &&
46390d7a8555SMiklos Szeredi 	    (flags & RENAME_EXCHANGE))
4640e886663cSJens Axboe 		goto put_both;
4641520c8b16SMiklos Szeredi 
4642f5beed75SAl Viro 	if (flags & RENAME_EXCHANGE)
4643f5beed75SAl Viro 		target_flags = 0;
4644f5beed75SAl Viro 
4645c6a94284SJeff Layton retry:
4646e886663cSJens Axboe 	from = filename_parentat(olddfd, from, lookup_flags, &old_path,
4647e886663cSJens Axboe 					&old_last, &old_type);
464891a27b2aSJeff Layton 	if (IS_ERR(from)) {
464991a27b2aSJeff Layton 		error = PTR_ERR(from);
4650e886663cSJens Axboe 		goto put_new;
465191a27b2aSJeff Layton 	}
46521da177e4SLinus Torvalds 
4653e886663cSJens Axboe 	to = filename_parentat(newdfd, to, lookup_flags, &new_path, &new_last,
4654e886663cSJens Axboe 				&new_type);
465591a27b2aSJeff Layton 	if (IS_ERR(to)) {
465691a27b2aSJeff Layton 		error = PTR_ERR(to);
46571da177e4SLinus Torvalds 		goto exit1;
465891a27b2aSJeff Layton 	}
46591da177e4SLinus Torvalds 
46601da177e4SLinus Torvalds 	error = -EXDEV;
4661f5beed75SAl Viro 	if (old_path.mnt != new_path.mnt)
46621da177e4SLinus Torvalds 		goto exit2;
46631da177e4SLinus Torvalds 
46641da177e4SLinus Torvalds 	error = -EBUSY;
4665f5beed75SAl Viro 	if (old_type != LAST_NORM)
46661da177e4SLinus Torvalds 		goto exit2;
46671da177e4SLinus Torvalds 
46680a7c3937SMiklos Szeredi 	if (flags & RENAME_NOREPLACE)
46690a7c3937SMiklos Szeredi 		error = -EEXIST;
4670f5beed75SAl Viro 	if (new_type != LAST_NORM)
46711da177e4SLinus Torvalds 		goto exit2;
46721da177e4SLinus Torvalds 
4673f5beed75SAl Viro 	error = mnt_want_write(old_path.mnt);
4674c30dabfeSJan Kara 	if (error)
4675c30dabfeSJan Kara 		goto exit2;
4676c30dabfeSJan Kara 
46778e6d782cSJ. Bruce Fields retry_deleg:
4678f5beed75SAl Viro 	trap = lock_rename(new_path.dentry, old_path.dentry);
46791da177e4SLinus Torvalds 
4680f5beed75SAl Viro 	old_dentry = __lookup_hash(&old_last, old_path.dentry, lookup_flags);
46811da177e4SLinus Torvalds 	error = PTR_ERR(old_dentry);
46821da177e4SLinus Torvalds 	if (IS_ERR(old_dentry))
46831da177e4SLinus Torvalds 		goto exit3;
46841da177e4SLinus Torvalds 	/* source must exist */
46851da177e4SLinus Torvalds 	error = -ENOENT;
4686b18825a7SDavid Howells 	if (d_is_negative(old_dentry))
46871da177e4SLinus Torvalds 		goto exit4;
4688f5beed75SAl Viro 	new_dentry = __lookup_hash(&new_last, new_path.dentry, lookup_flags | target_flags);
46891da177e4SLinus Torvalds 	error = PTR_ERR(new_dentry);
46901da177e4SLinus Torvalds 	if (IS_ERR(new_dentry))
46911da177e4SLinus Torvalds 		goto exit4;
46920a7c3937SMiklos Szeredi 	error = -EEXIST;
46930a7c3937SMiklos Szeredi 	if ((flags & RENAME_NOREPLACE) && d_is_positive(new_dentry))
46940a7c3937SMiklos Szeredi 		goto exit5;
4695da1ce067SMiklos Szeredi 	if (flags & RENAME_EXCHANGE) {
4696da1ce067SMiklos Szeredi 		error = -ENOENT;
4697da1ce067SMiklos Szeredi 		if (d_is_negative(new_dentry))
4698da1ce067SMiklos Szeredi 			goto exit5;
4699da1ce067SMiklos Szeredi 
4700da1ce067SMiklos Szeredi 		if (!d_is_dir(new_dentry)) {
4701da1ce067SMiklos Szeredi 			error = -ENOTDIR;
4702f5beed75SAl Viro 			if (new_last.name[new_last.len])
4703da1ce067SMiklos Szeredi 				goto exit5;
4704da1ce067SMiklos Szeredi 		}
4705da1ce067SMiklos Szeredi 	}
47060a7c3937SMiklos Szeredi 	/* unless the source is a directory trailing slashes give -ENOTDIR */
47070a7c3937SMiklos Szeredi 	if (!d_is_dir(old_dentry)) {
47080a7c3937SMiklos Szeredi 		error = -ENOTDIR;
4709f5beed75SAl Viro 		if (old_last.name[old_last.len])
47100a7c3937SMiklos Szeredi 			goto exit5;
4711f5beed75SAl Viro 		if (!(flags & RENAME_EXCHANGE) && new_last.name[new_last.len])
47120a7c3937SMiklos Szeredi 			goto exit5;
47130a7c3937SMiklos Szeredi 	}
47140a7c3937SMiklos Szeredi 	/* source should not be ancestor of target */
47150a7c3937SMiklos Szeredi 	error = -EINVAL;
47160a7c3937SMiklos Szeredi 	if (old_dentry == trap)
47170a7c3937SMiklos Szeredi 		goto exit5;
47181da177e4SLinus Torvalds 	/* target should not be an ancestor of source */
4719da1ce067SMiklos Szeredi 	if (!(flags & RENAME_EXCHANGE))
47201da177e4SLinus Torvalds 		error = -ENOTEMPTY;
47211da177e4SLinus Torvalds 	if (new_dentry == trap)
47221da177e4SLinus Torvalds 		goto exit5;
47231da177e4SLinus Torvalds 
4724f5beed75SAl Viro 	error = security_path_rename(&old_path, old_dentry,
4725f5beed75SAl Viro 				     &new_path, new_dentry, flags);
4726be6d3e56SKentaro Takeda 	if (error)
4727c30dabfeSJan Kara 		goto exit5;
47289fe61450SChristian Brauner 
47299fe61450SChristian Brauner 	rd.old_dir	   = old_path.dentry->d_inode;
47309fe61450SChristian Brauner 	rd.old_dentry	   = old_dentry;
47316521f891SChristian Brauner 	rd.old_mnt_userns  = mnt_user_ns(old_path.mnt);
47329fe61450SChristian Brauner 	rd.new_dir	   = new_path.dentry->d_inode;
47339fe61450SChristian Brauner 	rd.new_dentry	   = new_dentry;
47346521f891SChristian Brauner 	rd.new_mnt_userns  = mnt_user_ns(new_path.mnt);
47359fe61450SChristian Brauner 	rd.delegated_inode = &delegated_inode;
47369fe61450SChristian Brauner 	rd.flags	   = flags;
47379fe61450SChristian Brauner 	error = vfs_rename(&rd);
47381da177e4SLinus Torvalds exit5:
47391da177e4SLinus Torvalds 	dput(new_dentry);
47401da177e4SLinus Torvalds exit4:
47411da177e4SLinus Torvalds 	dput(old_dentry);
47421da177e4SLinus Torvalds exit3:
4743f5beed75SAl Viro 	unlock_rename(new_path.dentry, old_path.dentry);
47448e6d782cSJ. Bruce Fields 	if (delegated_inode) {
47458e6d782cSJ. Bruce Fields 		error = break_deleg_wait(&delegated_inode);
47468e6d782cSJ. Bruce Fields 		if (!error)
47478e6d782cSJ. Bruce Fields 			goto retry_deleg;
47488e6d782cSJ. Bruce Fields 	}
4749f5beed75SAl Viro 	mnt_drop_write(old_path.mnt);
47501da177e4SLinus Torvalds exit2:
4751c6a94284SJeff Layton 	if (retry_estale(error, lookup_flags))
4752c6a94284SJeff Layton 		should_retry = true;
4753f5beed75SAl Viro 	path_put(&new_path);
47541da177e4SLinus Torvalds exit1:
4755f5beed75SAl Viro 	path_put(&old_path);
4756c6a94284SJeff Layton 	if (should_retry) {
4757c6a94284SJeff Layton 		should_retry = false;
4758c6a94284SJeff Layton 		lookup_flags |= LOOKUP_REVAL;
4759c6a94284SJeff Layton 		goto retry;
4760c6a94284SJeff Layton 	}
4761e886663cSJens Axboe put_both:
4762e886663cSJens Axboe 	if (!IS_ERR(from))
4763e886663cSJens Axboe 		putname(from);
4764e886663cSJens Axboe put_new:
4765e886663cSJens Axboe 	if (!IS_ERR(to))
4766e886663cSJens Axboe 		putname(to);
47671da177e4SLinus Torvalds 	return error;
47681da177e4SLinus Torvalds }
47691da177e4SLinus Torvalds 
4770ee81feb6SDominik Brodowski SYSCALL_DEFINE5(renameat2, int, olddfd, const char __user *, oldname,
4771ee81feb6SDominik Brodowski 		int, newdfd, const char __user *, newname, unsigned int, flags)
4772ee81feb6SDominik Brodowski {
4773e886663cSJens Axboe 	return do_renameat2(olddfd, getname(oldname), newdfd, getname(newname),
4774e886663cSJens Axboe 				flags);
4775ee81feb6SDominik Brodowski }
4776ee81feb6SDominik Brodowski 
4777520c8b16SMiklos Szeredi SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname,
4778520c8b16SMiklos Szeredi 		int, newdfd, const char __user *, newname)
4779520c8b16SMiklos Szeredi {
4780e886663cSJens Axboe 	return do_renameat2(olddfd, getname(oldname), newdfd, getname(newname),
4781e886663cSJens Axboe 				0);
4782520c8b16SMiklos Szeredi }
4783520c8b16SMiklos Szeredi 
4784a26eab24SHeiko Carstens SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname)
47855590ff0dSUlrich Drepper {
4786e886663cSJens Axboe 	return do_renameat2(AT_FDCWD, getname(oldname), AT_FDCWD,
4787e886663cSJens Axboe 				getname(newname), 0);
47885590ff0dSUlrich Drepper }
47895590ff0dSUlrich Drepper 
47905d826c84SAl Viro int readlink_copy(char __user *buffer, int buflen, const char *link)
47911da177e4SLinus Torvalds {
47925d826c84SAl Viro 	int len = PTR_ERR(link);
47931da177e4SLinus Torvalds 	if (IS_ERR(link))
47941da177e4SLinus Torvalds 		goto out;
47951da177e4SLinus Torvalds 
47961da177e4SLinus Torvalds 	len = strlen(link);
47971da177e4SLinus Torvalds 	if (len > (unsigned) buflen)
47981da177e4SLinus Torvalds 		len = buflen;
47991da177e4SLinus Torvalds 	if (copy_to_user(buffer, link, len))
48001da177e4SLinus Torvalds 		len = -EFAULT;
48011da177e4SLinus Torvalds out:
48021da177e4SLinus Torvalds 	return len;
48031da177e4SLinus Torvalds }
48041da177e4SLinus Torvalds 
4805d60874cdSMiklos Szeredi /**
4806fd4a0edfSMiklos Szeredi  * vfs_readlink - copy symlink body into userspace buffer
4807fd4a0edfSMiklos Szeredi  * @dentry: dentry on which to get symbolic link
4808fd4a0edfSMiklos Szeredi  * @buffer: user memory pointer
4809fd4a0edfSMiklos Szeredi  * @buflen: size of buffer
4810fd4a0edfSMiklos Szeredi  *
4811fd4a0edfSMiklos Szeredi  * Does not touch atime.  That's up to the caller if necessary
4812fd4a0edfSMiklos Szeredi  *
4813fd4a0edfSMiklos Szeredi  * Does not call security hook.
4814fd4a0edfSMiklos Szeredi  */
4815fd4a0edfSMiklos Szeredi int vfs_readlink(struct dentry *dentry, char __user *buffer, int buflen)
4816fd4a0edfSMiklos Szeredi {
4817fd4a0edfSMiklos Szeredi 	struct inode *inode = d_inode(dentry);
4818f2df5da6SAl Viro 	DEFINE_DELAYED_CALL(done);
4819f2df5da6SAl Viro 	const char *link;
4820f2df5da6SAl Viro 	int res;
4821fd4a0edfSMiklos Szeredi 
482276fca90eSMiklos Szeredi 	if (unlikely(!(inode->i_opflags & IOP_DEFAULT_READLINK))) {
482376fca90eSMiklos Szeredi 		if (unlikely(inode->i_op->readlink))
482476fca90eSMiklos Szeredi 			return inode->i_op->readlink(dentry, buffer, buflen);
482576fca90eSMiklos Szeredi 
482676fca90eSMiklos Szeredi 		if (!d_is_symlink(dentry))
4827fd4a0edfSMiklos Szeredi 			return -EINVAL;
4828fd4a0edfSMiklos Szeredi 
482976fca90eSMiklos Szeredi 		spin_lock(&inode->i_lock);
483076fca90eSMiklos Szeredi 		inode->i_opflags |= IOP_DEFAULT_READLINK;
483176fca90eSMiklos Szeredi 		spin_unlock(&inode->i_lock);
483276fca90eSMiklos Szeredi 	}
483376fca90eSMiklos Szeredi 
48344c4f7c19SEric Biggers 	link = READ_ONCE(inode->i_link);
4835f2df5da6SAl Viro 	if (!link) {
4836f2df5da6SAl Viro 		link = inode->i_op->get_link(dentry, inode, &done);
4837f2df5da6SAl Viro 		if (IS_ERR(link))
4838f2df5da6SAl Viro 			return PTR_ERR(link);
4839f2df5da6SAl Viro 	}
4840f2df5da6SAl Viro 	res = readlink_copy(buffer, buflen, link);
4841f2df5da6SAl Viro 	do_delayed_call(&done);
4842f2df5da6SAl Viro 	return res;
4843fd4a0edfSMiklos Szeredi }
4844fd4a0edfSMiklos Szeredi EXPORT_SYMBOL(vfs_readlink);
48451da177e4SLinus Torvalds 
4846d60874cdSMiklos Szeredi /**
4847d60874cdSMiklos Szeredi  * vfs_get_link - get symlink body
4848d60874cdSMiklos Szeredi  * @dentry: dentry on which to get symbolic link
4849d60874cdSMiklos Szeredi  * @done: caller needs to free returned data with this
4850d60874cdSMiklos Szeredi  *
4851d60874cdSMiklos Szeredi  * Calls security hook and i_op->get_link() on the supplied inode.
4852d60874cdSMiklos Szeredi  *
4853d60874cdSMiklos Szeredi  * It does not touch atime.  That's up to the caller if necessary.
4854d60874cdSMiklos Szeredi  *
4855d60874cdSMiklos Szeredi  * Does not work on "special" symlinks like /proc/$$/fd/N
4856d60874cdSMiklos Szeredi  */
4857d60874cdSMiklos Szeredi const char *vfs_get_link(struct dentry *dentry, struct delayed_call *done)
4858d60874cdSMiklos Szeredi {
4859d60874cdSMiklos Szeredi 	const char *res = ERR_PTR(-EINVAL);
4860d60874cdSMiklos Szeredi 	struct inode *inode = d_inode(dentry);
4861d60874cdSMiklos Szeredi 
4862d60874cdSMiklos Szeredi 	if (d_is_symlink(dentry)) {
4863d60874cdSMiklos Szeredi 		res = ERR_PTR(security_inode_readlink(dentry));
4864d60874cdSMiklos Szeredi 		if (!res)
4865d60874cdSMiklos Szeredi 			res = inode->i_op->get_link(dentry, inode, done);
4866d60874cdSMiklos Szeredi 	}
4867d60874cdSMiklos Szeredi 	return res;
4868d60874cdSMiklos Szeredi }
4869d60874cdSMiklos Szeredi EXPORT_SYMBOL(vfs_get_link);
4870d60874cdSMiklos Szeredi 
48711da177e4SLinus Torvalds /* get the link contents into pagecache */
48726b255391SAl Viro const char *page_get_link(struct dentry *dentry, struct inode *inode,
4873fceef393SAl Viro 			  struct delayed_call *callback)
48741da177e4SLinus Torvalds {
4875ebd09abbSDuane Griffin 	char *kaddr;
48761da177e4SLinus Torvalds 	struct page *page;
48776b255391SAl Viro 	struct address_space *mapping = inode->i_mapping;
48786b255391SAl Viro 
4879d3883d4fSAl Viro 	if (!dentry) {
4880d3883d4fSAl Viro 		page = find_get_page(mapping, 0);
4881d3883d4fSAl Viro 		if (!page)
48826b255391SAl Viro 			return ERR_PTR(-ECHILD);
4883d3883d4fSAl Viro 		if (!PageUptodate(page)) {
4884d3883d4fSAl Viro 			put_page(page);
4885d3883d4fSAl Viro 			return ERR_PTR(-ECHILD);
4886d3883d4fSAl Viro 		}
4887d3883d4fSAl Viro 	} else {
4888090d2b18SPekka Enberg 		page = read_mapping_page(mapping, 0, NULL);
48891da177e4SLinus Torvalds 		if (IS_ERR(page))
48906fe6900eSNick Piggin 			return (char*)page;
4891d3883d4fSAl Viro 	}
4892fceef393SAl Viro 	set_delayed_call(callback, page_put_link, page);
489321fc61c7SAl Viro 	BUG_ON(mapping_gfp_mask(mapping) & __GFP_HIGHMEM);
489421fc61c7SAl Viro 	kaddr = page_address(page);
48956b255391SAl Viro 	nd_terminate_link(kaddr, inode->i_size, PAGE_SIZE - 1);
4896ebd09abbSDuane Griffin 	return kaddr;
48971da177e4SLinus Torvalds }
48981da177e4SLinus Torvalds 
48996b255391SAl Viro EXPORT_SYMBOL(page_get_link);
49001da177e4SLinus Torvalds 
4901fceef393SAl Viro void page_put_link(void *arg)
49021da177e4SLinus Torvalds {
4903fceef393SAl Viro 	put_page(arg);
49041da177e4SLinus Torvalds }
49054d359507SAl Viro EXPORT_SYMBOL(page_put_link);
49061da177e4SLinus Torvalds 
4907aa80deabSAl Viro int page_readlink(struct dentry *dentry, char __user *buffer, int buflen)
4908aa80deabSAl Viro {
4909fceef393SAl Viro 	DEFINE_DELAYED_CALL(done);
49106b255391SAl Viro 	int res = readlink_copy(buffer, buflen,
49116b255391SAl Viro 				page_get_link(dentry, d_inode(dentry),
4912fceef393SAl Viro 					      &done));
4913fceef393SAl Viro 	do_delayed_call(&done);
4914aa80deabSAl Viro 	return res;
4915aa80deabSAl Viro }
4916aa80deabSAl Viro EXPORT_SYMBOL(page_readlink);
4917aa80deabSAl Viro 
491854566b2cSNick Piggin /*
491954566b2cSNick Piggin  * The nofs argument instructs pagecache_write_begin to pass AOP_FLAG_NOFS
492054566b2cSNick Piggin  */
492154566b2cSNick Piggin int __page_symlink(struct inode *inode, const char *symname, int len, int nofs)
49221da177e4SLinus Torvalds {
49231da177e4SLinus Torvalds 	struct address_space *mapping = inode->i_mapping;
49240adb25d2SKirill Korotaev 	struct page *page;
4925afddba49SNick Piggin 	void *fsdata;
4926beb497abSDmitriy Monakhov 	int err;
4927c718a975STetsuo Handa 	unsigned int flags = 0;
492854566b2cSNick Piggin 	if (nofs)
492954566b2cSNick Piggin 		flags |= AOP_FLAG_NOFS;
49301da177e4SLinus Torvalds 
49317e53cac4SNeilBrown retry:
4932afddba49SNick Piggin 	err = pagecache_write_begin(NULL, mapping, 0, len-1,
493354566b2cSNick Piggin 				flags, &page, &fsdata);
49341da177e4SLinus Torvalds 	if (err)
4935afddba49SNick Piggin 		goto fail;
4936afddba49SNick Piggin 
493721fc61c7SAl Viro 	memcpy(page_address(page), symname, len-1);
4938afddba49SNick Piggin 
4939afddba49SNick Piggin 	err = pagecache_write_end(NULL, mapping, 0, len-1, len-1,
4940afddba49SNick Piggin 							page, fsdata);
49411da177e4SLinus Torvalds 	if (err < 0)
49421da177e4SLinus Torvalds 		goto fail;
4943afddba49SNick Piggin 	if (err < len-1)
4944afddba49SNick Piggin 		goto retry;
4945afddba49SNick Piggin 
49461da177e4SLinus Torvalds 	mark_inode_dirty(inode);
49471da177e4SLinus Torvalds 	return 0;
49481da177e4SLinus Torvalds fail:
49491da177e4SLinus Torvalds 	return err;
49501da177e4SLinus Torvalds }
49514d359507SAl Viro EXPORT_SYMBOL(__page_symlink);
49521da177e4SLinus Torvalds 
49530adb25d2SKirill Korotaev int page_symlink(struct inode *inode, const char *symname, int len)
49540adb25d2SKirill Korotaev {
49550adb25d2SKirill Korotaev 	return __page_symlink(inode, symname, len,
4956c62d2555SMichal Hocko 			!mapping_gfp_constraint(inode->i_mapping, __GFP_FS));
49570adb25d2SKirill Korotaev }
49584d359507SAl Viro EXPORT_SYMBOL(page_symlink);
49590adb25d2SKirill Korotaev 
496092e1d5beSArjan van de Ven const struct inode_operations page_symlink_inode_operations = {
49616b255391SAl Viro 	.get_link	= page_get_link,
49621da177e4SLinus Torvalds };
49631da177e4SLinus Torvalds EXPORT_SYMBOL(page_symlink_inode_operations);
4964