xref: /openbmc/linux/fs/namei.c (revision 0766ec82)
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 *
2078228e2c3SDmitry Kadashev getname_uflags(const char __user *filename, int uflags)
2088228e2c3SDmitry Kadashev {
2098228e2c3SDmitry Kadashev 	int flags = (uflags & AT_EMPTY_PATH) ? LOOKUP_EMPTY : 0;
2108228e2c3SDmitry Kadashev 
2118228e2c3SDmitry Kadashev 	return getname_flags(filename, flags, NULL);
2128228e2c3SDmitry Kadashev }
2138228e2c3SDmitry Kadashev 
2148228e2c3SDmitry Kadashev struct filename *
21591a27b2aSJeff Layton getname(const char __user * filename)
216f52e0c11SAl Viro {
217f7493e5dSLinus Torvalds 	return getname_flags(filename, 0, NULL);
218f52e0c11SAl Viro }
219f52e0c11SAl Viro 
220c4ad8f98SLinus Torvalds struct filename *
221c4ad8f98SLinus Torvalds getname_kernel(const char * filename)
222c4ad8f98SLinus Torvalds {
223c4ad8f98SLinus Torvalds 	struct filename *result;
22408518549SPaul Moore 	int len = strlen(filename) + 1;
225c4ad8f98SLinus Torvalds 
226c4ad8f98SLinus Torvalds 	result = __getname();
227c4ad8f98SLinus Torvalds 	if (unlikely(!result))
228c4ad8f98SLinus Torvalds 		return ERR_PTR(-ENOMEM);
229c4ad8f98SLinus Torvalds 
23008518549SPaul Moore 	if (len <= EMBEDDED_NAME_MAX) {
231fd2f7cb5SAl Viro 		result->name = (char *)result->iname;
23208518549SPaul Moore 	} else if (len <= PATH_MAX) {
23330ce4d19SAl Viro 		const size_t size = offsetof(struct filename, iname[1]);
23408518549SPaul Moore 		struct filename *tmp;
23508518549SPaul Moore 
23630ce4d19SAl Viro 		tmp = kmalloc(size, GFP_KERNEL);
23708518549SPaul Moore 		if (unlikely(!tmp)) {
23808518549SPaul Moore 			__putname(result);
23908518549SPaul Moore 			return ERR_PTR(-ENOMEM);
24008518549SPaul Moore 		}
24108518549SPaul Moore 		tmp->name = (char *)result;
24208518549SPaul Moore 		result = tmp;
24308518549SPaul Moore 	} else {
24408518549SPaul Moore 		__putname(result);
24508518549SPaul Moore 		return ERR_PTR(-ENAMETOOLONG);
24608518549SPaul Moore 	}
24708518549SPaul Moore 	memcpy((char *)result->name, filename, len);
248c4ad8f98SLinus Torvalds 	result->uptr = NULL;
249c4ad8f98SLinus Torvalds 	result->aname = NULL;
25055422d0bSPaul Moore 	result->refcnt = 1;
251fd3522fdSPaul Moore 	audit_getname(result);
252c4ad8f98SLinus Torvalds 
253c4ad8f98SLinus Torvalds 	return result;
254c4ad8f98SLinus Torvalds }
255c4ad8f98SLinus Torvalds 
25691a27b2aSJeff Layton void putname(struct filename *name)
2571da177e4SLinus Torvalds {
25891ef658fSDmitry Kadashev 	if (IS_ERR_OR_NULL(name))
25991ef658fSDmitry Kadashev 		return;
26091ef658fSDmitry Kadashev 
26155422d0bSPaul Moore 	BUG_ON(name->refcnt <= 0);
26255422d0bSPaul Moore 
26355422d0bSPaul Moore 	if (--name->refcnt > 0)
26455422d0bSPaul Moore 		return;
26555422d0bSPaul Moore 
266fd2f7cb5SAl Viro 	if (name->name != name->iname) {
26755422d0bSPaul Moore 		__putname(name->name);
26855422d0bSPaul Moore 		kfree(name);
26955422d0bSPaul Moore 	} else
27055422d0bSPaul Moore 		__putname(name);
2711da177e4SLinus Torvalds }
2721da177e4SLinus Torvalds 
27347291baaSChristian Brauner /**
27447291baaSChristian Brauner  * check_acl - perform ACL permission checking
27547291baaSChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
27647291baaSChristian Brauner  * @inode:	inode to check permissions on
27747291baaSChristian Brauner  * @mask:	right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
27847291baaSChristian Brauner  *
27947291baaSChristian Brauner  * This function performs the ACL permission checking. Since this function
28047291baaSChristian Brauner  * retrieve POSIX acls it needs to know whether it is called from a blocking or
28147291baaSChristian Brauner  * non-blocking context and thus cares about the MAY_NOT_BLOCK bit.
28247291baaSChristian Brauner  *
28347291baaSChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
28447291baaSChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
28547291baaSChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
28647291baaSChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
28747291baaSChristian Brauner  * raw inode simply passs init_user_ns.
28847291baaSChristian Brauner  */
28947291baaSChristian Brauner static int check_acl(struct user_namespace *mnt_userns,
29047291baaSChristian Brauner 		     struct inode *inode, int mask)
291e77819e5SLinus Torvalds {
29284635d68SLinus Torvalds #ifdef CONFIG_FS_POSIX_ACL
293e77819e5SLinus Torvalds 	struct posix_acl *acl;
294e77819e5SLinus Torvalds 
295e77819e5SLinus Torvalds 	if (mask & MAY_NOT_BLOCK) {
2963567866bSAl Viro 		acl = get_cached_acl_rcu(inode, ACL_TYPE_ACCESS);
2973567866bSAl Viro 	        if (!acl)
298e77819e5SLinus Torvalds 	                return -EAGAIN;
2993567866bSAl Viro 		/* no ->get_acl() calls in RCU mode... */
300b8a7a3a6SAndreas Gruenbacher 		if (is_uncached_acl(acl))
301e77819e5SLinus Torvalds 			return -ECHILD;
30247291baaSChristian Brauner 	        return posix_acl_permission(mnt_userns, inode, acl, mask);
303e77819e5SLinus Torvalds 	}
304e77819e5SLinus Torvalds 
3052982baa2SChristoph Hellwig 	acl = get_acl(inode, ACL_TYPE_ACCESS);
3064e34e719SChristoph Hellwig 	if (IS_ERR(acl))
3074e34e719SChristoph Hellwig 		return PTR_ERR(acl);
308e77819e5SLinus Torvalds 	if (acl) {
30947291baaSChristian Brauner 	        int error = posix_acl_permission(mnt_userns, inode, acl, mask);
310e77819e5SLinus Torvalds 	        posix_acl_release(acl);
311e77819e5SLinus Torvalds 	        return error;
312e77819e5SLinus Torvalds 	}
31384635d68SLinus Torvalds #endif
314e77819e5SLinus Torvalds 
315e77819e5SLinus Torvalds 	return -EAGAIN;
316e77819e5SLinus Torvalds }
317e77819e5SLinus Torvalds 
31847291baaSChristian Brauner /**
31947291baaSChristian Brauner  * acl_permission_check - perform basic UNIX permission checking
32047291baaSChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
32147291baaSChristian Brauner  * @inode:	inode to check permissions on
32247291baaSChristian Brauner  * @mask:	right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
3235fc475b7SLinus Torvalds  *
32447291baaSChristian Brauner  * This function performs the basic UNIX permission checking. Since this
32547291baaSChristian Brauner  * function may retrieve POSIX acls it needs to know whether it is called from a
32647291baaSChristian Brauner  * blocking or non-blocking context and thus cares about the MAY_NOT_BLOCK bit.
32747291baaSChristian Brauner  *
32847291baaSChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
32947291baaSChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
33047291baaSChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
33147291baaSChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
33247291baaSChristian Brauner  * raw inode simply passs init_user_ns.
3335909ccaaSLinus Torvalds  */
33447291baaSChristian Brauner static int acl_permission_check(struct user_namespace *mnt_userns,
33547291baaSChristian Brauner 				struct inode *inode, int mask)
3365909ccaaSLinus Torvalds {
33726cf46beSLinus Torvalds 	unsigned int mode = inode->i_mode;
33847291baaSChristian Brauner 	kuid_t i_uid;
3395909ccaaSLinus Torvalds 
3405fc475b7SLinus Torvalds 	/* Are we the owner? If so, ACL's don't matter */
34147291baaSChristian Brauner 	i_uid = i_uid_into_mnt(mnt_userns, inode);
34247291baaSChristian Brauner 	if (likely(uid_eq(current_fsuid(), i_uid))) {
3435fc475b7SLinus Torvalds 		mask &= 7;
3445909ccaaSLinus Torvalds 		mode >>= 6;
3455fc475b7SLinus Torvalds 		return (mask & ~mode) ? -EACCES : 0;
3465fc475b7SLinus Torvalds 	}
3475fc475b7SLinus Torvalds 
3485fc475b7SLinus Torvalds 	/* Do we have ACL's? */
349e77819e5SLinus Torvalds 	if (IS_POSIXACL(inode) && (mode & S_IRWXG)) {
35047291baaSChristian Brauner 		int error = check_acl(mnt_userns, inode, mask);
3515909ccaaSLinus Torvalds 		if (error != -EAGAIN)
3525909ccaaSLinus Torvalds 			return error;
3535909ccaaSLinus Torvalds 	}
3545909ccaaSLinus Torvalds 
3555fc475b7SLinus Torvalds 	/* Only RWX matters for group/other mode bits */
3565fc475b7SLinus Torvalds 	mask &= 7;
3575fc475b7SLinus Torvalds 
3585fc475b7SLinus Torvalds 	/*
3595fc475b7SLinus Torvalds 	 * Are the group permissions different from
3605fc475b7SLinus Torvalds 	 * the other permissions in the bits we care
3615fc475b7SLinus Torvalds 	 * about? Need to check group ownership if so.
3625fc475b7SLinus Torvalds 	 */
3635fc475b7SLinus Torvalds 	if (mask & (mode ^ (mode >> 3))) {
36447291baaSChristian Brauner 		kgid_t kgid = i_gid_into_mnt(mnt_userns, inode);
36547291baaSChristian Brauner 		if (in_group_p(kgid))
3665909ccaaSLinus Torvalds 			mode >>= 3;
3675909ccaaSLinus Torvalds 	}
3685909ccaaSLinus Torvalds 
3695fc475b7SLinus Torvalds 	/* Bits in 'mode' clear that we require? */
3705fc475b7SLinus Torvalds 	return (mask & ~mode) ? -EACCES : 0;
3715909ccaaSLinus Torvalds }
3721da177e4SLinus Torvalds 
3731da177e4SLinus Torvalds /**
3741da177e4SLinus Torvalds  * generic_permission -  check for access rights on a Posix-like filesystem
37547291baaSChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
3761da177e4SLinus Torvalds  * @inode:	inode to check access rights for
3775fc475b7SLinus Torvalds  * @mask:	right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC,
3785fc475b7SLinus Torvalds  *		%MAY_NOT_BLOCK ...)
3791da177e4SLinus Torvalds  *
3801da177e4SLinus Torvalds  * Used to check for read/write/execute permissions on a file.
3811da177e4SLinus Torvalds  * We use "fsuid" for this, letting us set arbitrary permissions
3821da177e4SLinus Torvalds  * for filesystem access without changing the "normal" uids which
383b74c79e9SNick Piggin  * are used for other things.
384b74c79e9SNick Piggin  *
385b74c79e9SNick Piggin  * generic_permission is rcu-walk aware. It returns -ECHILD in case an rcu-walk
386b74c79e9SNick Piggin  * request cannot be satisfied (eg. requires blocking or too much complexity).
387b74c79e9SNick Piggin  * It would then be called again in ref-walk mode.
38847291baaSChristian Brauner  *
38947291baaSChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
39047291baaSChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
39147291baaSChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
39247291baaSChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
39347291baaSChristian Brauner  * raw inode simply passs init_user_ns.
3941da177e4SLinus Torvalds  */
39547291baaSChristian Brauner int generic_permission(struct user_namespace *mnt_userns, struct inode *inode,
39647291baaSChristian Brauner 		       int mask)
3971da177e4SLinus Torvalds {
3985909ccaaSLinus Torvalds 	int ret;
3991da177e4SLinus Torvalds 
4001da177e4SLinus Torvalds 	/*
401948409c7SAndreas Gruenbacher 	 * Do the basic permission checks.
4021da177e4SLinus Torvalds 	 */
40347291baaSChristian Brauner 	ret = acl_permission_check(mnt_userns, inode, mask);
4045909ccaaSLinus Torvalds 	if (ret != -EACCES)
4055909ccaaSLinus Torvalds 		return ret;
4061da177e4SLinus Torvalds 
407d594e7ecSAl Viro 	if (S_ISDIR(inode->i_mode)) {
408d594e7ecSAl Viro 		/* DACs are overridable for directories */
409d594e7ecSAl Viro 		if (!(mask & MAY_WRITE))
41047291baaSChristian Brauner 			if (capable_wrt_inode_uidgid(mnt_userns, inode,
41123adbe12SAndy Lutomirski 						     CAP_DAC_READ_SEARCH))
412d594e7ecSAl Viro 				return 0;
41347291baaSChristian Brauner 		if (capable_wrt_inode_uidgid(mnt_userns, inode,
4140558c1bfSChristian Brauner 					     CAP_DAC_OVERRIDE))
4151da177e4SLinus Torvalds 			return 0;
4162a4c2242SStephen Smalley 		return -EACCES;
4172a4c2242SStephen Smalley 	}
4181da177e4SLinus Torvalds 
4191da177e4SLinus Torvalds 	/*
4201da177e4SLinus Torvalds 	 * Searching includes executable on directories, else just read.
4211da177e4SLinus Torvalds 	 */
4227ea66001SSerge E. Hallyn 	mask &= MAY_READ | MAY_WRITE | MAY_EXEC;
423d594e7ecSAl Viro 	if (mask == MAY_READ)
42447291baaSChristian Brauner 		if (capable_wrt_inode_uidgid(mnt_userns, inode,
4250558c1bfSChristian Brauner 					     CAP_DAC_READ_SEARCH))
4261da177e4SLinus Torvalds 			return 0;
4272a4c2242SStephen Smalley 	/*
4282a4c2242SStephen Smalley 	 * Read/write DACs are always overridable.
4292a4c2242SStephen Smalley 	 * Executable DACs are overridable when there is
4302a4c2242SStephen Smalley 	 * at least one exec bit set.
4312a4c2242SStephen Smalley 	 */
4322a4c2242SStephen Smalley 	if (!(mask & MAY_EXEC) || (inode->i_mode & S_IXUGO))
43347291baaSChristian Brauner 		if (capable_wrt_inode_uidgid(mnt_userns, inode,
4340558c1bfSChristian Brauner 					     CAP_DAC_OVERRIDE))
4352a4c2242SStephen Smalley 			return 0;
4361da177e4SLinus Torvalds 
4371da177e4SLinus Torvalds 	return -EACCES;
4381da177e4SLinus Torvalds }
4394d359507SAl Viro EXPORT_SYMBOL(generic_permission);
4401da177e4SLinus Torvalds 
44147291baaSChristian Brauner /**
44247291baaSChristian Brauner  * do_inode_permission - UNIX permission checking
44347291baaSChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
44447291baaSChristian Brauner  * @inode:	inode to check permissions on
44547291baaSChristian Brauner  * @mask:	right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
44647291baaSChristian Brauner  *
4473ddcd056SLinus Torvalds  * We _really_ want to just do "generic_permission()" without
4483ddcd056SLinus Torvalds  * even looking at the inode->i_op values. So we keep a cache
4493ddcd056SLinus Torvalds  * flag in inode->i_opflags, that says "this has not special
4503ddcd056SLinus Torvalds  * permission function, use the fast case".
4513ddcd056SLinus Torvalds  */
45247291baaSChristian Brauner static inline int do_inode_permission(struct user_namespace *mnt_userns,
45347291baaSChristian Brauner 				      struct inode *inode, int mask)
4543ddcd056SLinus Torvalds {
4553ddcd056SLinus Torvalds 	if (unlikely(!(inode->i_opflags & IOP_FASTPERM))) {
4563ddcd056SLinus Torvalds 		if (likely(inode->i_op->permission))
457549c7297SChristian Brauner 			return inode->i_op->permission(mnt_userns, inode, mask);
4583ddcd056SLinus Torvalds 
4593ddcd056SLinus Torvalds 		/* This gets set once for the inode lifetime */
4603ddcd056SLinus Torvalds 		spin_lock(&inode->i_lock);
4613ddcd056SLinus Torvalds 		inode->i_opflags |= IOP_FASTPERM;
4623ddcd056SLinus Torvalds 		spin_unlock(&inode->i_lock);
4633ddcd056SLinus Torvalds 	}
46447291baaSChristian Brauner 	return generic_permission(mnt_userns, inode, mask);
4653ddcd056SLinus Torvalds }
4663ddcd056SLinus Torvalds 
467cb23beb5SChristoph Hellwig /**
4680bdaea90SDavid Howells  * sb_permission - Check superblock-level permissions
4690bdaea90SDavid Howells  * @sb: Superblock of inode to check permission on
47055852635SRandy Dunlap  * @inode: Inode to check permission on
4710bdaea90SDavid Howells  * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
4720bdaea90SDavid Howells  *
4730bdaea90SDavid Howells  * Separate out file-system wide checks from inode-specific permission checks.
4740bdaea90SDavid Howells  */
4750bdaea90SDavid Howells static int sb_permission(struct super_block *sb, struct inode *inode, int mask)
4760bdaea90SDavid Howells {
4770bdaea90SDavid Howells 	if (unlikely(mask & MAY_WRITE)) {
4780bdaea90SDavid Howells 		umode_t mode = inode->i_mode;
4790bdaea90SDavid Howells 
4800bdaea90SDavid Howells 		/* Nobody gets write access to a read-only fs. */
481bc98a42cSDavid Howells 		if (sb_rdonly(sb) && (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode)))
4820bdaea90SDavid Howells 			return -EROFS;
4830bdaea90SDavid Howells 	}
4840bdaea90SDavid Howells 	return 0;
4850bdaea90SDavid Howells }
4860bdaea90SDavid Howells 
4870bdaea90SDavid Howells /**
4880bdaea90SDavid Howells  * inode_permission - Check for access rights to a given inode
48947291baaSChristian Brauner  * @mnt_userns:	User namespace of the mount the inode was found from
4900bdaea90SDavid Howells  * @inode:	Inode to check permission on
4910bdaea90SDavid Howells  * @mask:	Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
4920bdaea90SDavid Howells  *
4930bdaea90SDavid Howells  * Check for read/write/execute permissions on an inode.  We use fs[ug]id for
4940bdaea90SDavid Howells  * this, letting us set arbitrary permissions for filesystem access without
4950bdaea90SDavid Howells  * changing the "normal" UIDs which are used for other things.
4960bdaea90SDavid Howells  *
4970bdaea90SDavid Howells  * When checking for MAY_APPEND, MAY_WRITE must also be set in @mask.
4980bdaea90SDavid Howells  */
49947291baaSChristian Brauner int inode_permission(struct user_namespace *mnt_userns,
50047291baaSChristian Brauner 		     struct inode *inode, int mask)
5010bdaea90SDavid Howells {
5020bdaea90SDavid Howells 	int retval;
5030bdaea90SDavid Howells 
5040bdaea90SDavid Howells 	retval = sb_permission(inode->i_sb, inode, mask);
5050bdaea90SDavid Howells 	if (retval)
5060bdaea90SDavid Howells 		return retval;
5074bfd054aSEric Biggers 
5084bfd054aSEric Biggers 	if (unlikely(mask & MAY_WRITE)) {
5094bfd054aSEric Biggers 		/*
5104bfd054aSEric Biggers 		 * Nobody gets write access to an immutable file.
5114bfd054aSEric Biggers 		 */
5124bfd054aSEric Biggers 		if (IS_IMMUTABLE(inode))
5134bfd054aSEric Biggers 			return -EPERM;
5144bfd054aSEric Biggers 
5154bfd054aSEric Biggers 		/*
5164bfd054aSEric Biggers 		 * Updating mtime will likely cause i_uid and i_gid to be
5174bfd054aSEric Biggers 		 * written back improperly if their true value is unknown
5184bfd054aSEric Biggers 		 * to the vfs.
5194bfd054aSEric Biggers 		 */
520ba73d987SChristian Brauner 		if (HAS_UNMAPPED_ID(mnt_userns, inode))
5214bfd054aSEric Biggers 			return -EACCES;
5224bfd054aSEric Biggers 	}
5234bfd054aSEric Biggers 
52447291baaSChristian Brauner 	retval = do_inode_permission(mnt_userns, inode, mask);
5254bfd054aSEric Biggers 	if (retval)
5264bfd054aSEric Biggers 		return retval;
5274bfd054aSEric Biggers 
5284bfd054aSEric Biggers 	retval = devcgroup_inode_permission(inode, mask);
5294bfd054aSEric Biggers 	if (retval)
5304bfd054aSEric Biggers 		return retval;
5314bfd054aSEric Biggers 
5324bfd054aSEric Biggers 	return security_inode_permission(inode, mask);
5330bdaea90SDavid Howells }
5344d359507SAl Viro EXPORT_SYMBOL(inode_permission);
5350bdaea90SDavid Howells 
5360bdaea90SDavid Howells /**
5375dd784d0SJan Blunck  * path_get - get a reference to a path
5385dd784d0SJan Blunck  * @path: path to get the reference to
5395dd784d0SJan Blunck  *
5405dd784d0SJan Blunck  * Given a path increment the reference count to the dentry and the vfsmount.
5415dd784d0SJan Blunck  */
542dcf787f3SAl Viro void path_get(const struct path *path)
5435dd784d0SJan Blunck {
5445dd784d0SJan Blunck 	mntget(path->mnt);
5455dd784d0SJan Blunck 	dget(path->dentry);
5465dd784d0SJan Blunck }
5475dd784d0SJan Blunck EXPORT_SYMBOL(path_get);
5485dd784d0SJan Blunck 
5495dd784d0SJan Blunck /**
5501d957f9bSJan Blunck  * path_put - put a reference to a path
5511d957f9bSJan Blunck  * @path: path to put the reference to
5521d957f9bSJan Blunck  *
5531d957f9bSJan Blunck  * Given a path decrement the reference count to the dentry and the vfsmount.
5541d957f9bSJan Blunck  */
555dcf787f3SAl Viro void path_put(const struct path *path)
5561da177e4SLinus Torvalds {
5571d957f9bSJan Blunck 	dput(path->dentry);
5581d957f9bSJan Blunck 	mntput(path->mnt);
5591da177e4SLinus Torvalds }
5601d957f9bSJan Blunck EXPORT_SYMBOL(path_put);
5611da177e4SLinus Torvalds 
562894bc8c4SAl Viro #define EMBEDDED_LEVELS 2
5631f55a6ecSAl Viro struct nameidata {
5641f55a6ecSAl Viro 	struct path	path;
5651f55a6ecSAl Viro 	struct qstr	last;
5661f55a6ecSAl Viro 	struct path	root;
5671f55a6ecSAl Viro 	struct inode	*inode; /* path.dentry.d_inode */
568bcba1e7dSAl Viro 	unsigned int	flags, state;
569ab87f9a5SAleksa Sarai 	unsigned	seq, m_seq, r_seq;
5701f55a6ecSAl Viro 	int		last_type;
5711f55a6ecSAl Viro 	unsigned	depth;
572756daf26SNeilBrown 	int		total_link_count;
573697fc6caSAl Viro 	struct saved {
574697fc6caSAl Viro 		struct path link;
575fceef393SAl Viro 		struct delayed_call done;
576697fc6caSAl Viro 		const char *name;
5770450b2d1SAl Viro 		unsigned seq;
578894bc8c4SAl Viro 	} *stack, internal[EMBEDDED_LEVELS];
5799883d185SAl Viro 	struct filename	*name;
5809883d185SAl Viro 	struct nameidata *saved;
5819883d185SAl Viro 	unsigned	root_seq;
5829883d185SAl Viro 	int		dfd;
5830f705953SAl Viro 	kuid_t		dir_uid;
5840f705953SAl Viro 	umode_t		dir_mode;
5853859a271SKees Cook } __randomize_layout;
5861f55a6ecSAl Viro 
587bcba1e7dSAl Viro #define ND_ROOT_PRESET 1
588bcba1e7dSAl Viro #define ND_ROOT_GRABBED 2
589bcba1e7dSAl Viro #define ND_JUMPED 4
590bcba1e7dSAl Viro 
59106422964SAl Viro static void __set_nameidata(struct nameidata *p, int dfd, struct filename *name)
592894bc8c4SAl Viro {
593756daf26SNeilBrown 	struct nameidata *old = current->nameidata;
594756daf26SNeilBrown 	p->stack = p->internal;
5957962c7d1SAl Viro 	p->depth = 0;
596c8a53ee5SAl Viro 	p->dfd = dfd;
597c8a53ee5SAl Viro 	p->name = name;
5987d01ef75SAl Viro 	p->path.mnt = NULL;
5997d01ef75SAl Viro 	p->path.dentry = NULL;
600756daf26SNeilBrown 	p->total_link_count = old ? old->total_link_count : 0;
6019883d185SAl Viro 	p->saved = old;
602756daf26SNeilBrown 	current->nameidata = p;
603894bc8c4SAl Viro }
604894bc8c4SAl Viro 
60506422964SAl Viro static inline void set_nameidata(struct nameidata *p, int dfd, struct filename *name,
60606422964SAl Viro 			  const struct path *root)
60706422964SAl Viro {
60806422964SAl Viro 	__set_nameidata(p, dfd, name);
60906422964SAl Viro 	p->state = 0;
61006422964SAl Viro 	if (unlikely(root)) {
61106422964SAl Viro 		p->state = ND_ROOT_PRESET;
61206422964SAl Viro 		p->root = *root;
61306422964SAl Viro 	}
61406422964SAl Viro }
61506422964SAl Viro 
6169883d185SAl Viro static void restore_nameidata(void)
617894bc8c4SAl Viro {
6189883d185SAl Viro 	struct nameidata *now = current->nameidata, *old = now->saved;
619756daf26SNeilBrown 
620756daf26SNeilBrown 	current->nameidata = old;
621756daf26SNeilBrown 	if (old)
622756daf26SNeilBrown 		old->total_link_count = now->total_link_count;
623e1a63bbcSAl Viro 	if (now->stack != now->internal)
624756daf26SNeilBrown 		kfree(now->stack);
625894bc8c4SAl Viro }
626894bc8c4SAl Viro 
62760ef60c7SAl Viro static bool nd_alloc_stack(struct nameidata *nd)
628894bc8c4SAl Viro {
629bc40aee0SAl Viro 	struct saved *p;
630bc40aee0SAl Viro 
6316da2ec56SKees Cook 	p= kmalloc_array(MAXSYMLINKS, sizeof(struct saved),
63260ef60c7SAl Viro 			 nd->flags & LOOKUP_RCU ? GFP_ATOMIC : GFP_KERNEL);
633bc40aee0SAl Viro 	if (unlikely(!p))
63460ef60c7SAl Viro 		return false;
635894bc8c4SAl Viro 	memcpy(p, nd->internal, sizeof(nd->internal));
636894bc8c4SAl Viro 	nd->stack = p;
63760ef60c7SAl Viro 	return true;
638894bc8c4SAl Viro }
639894bc8c4SAl Viro 
640397d425dSEric W. Biederman /**
6416b03f7edSAl Viro  * path_connected - Verify that a dentry is below mnt.mnt_root
642397d425dSEric W. Biederman  *
643397d425dSEric W. Biederman  * Rename can sometimes move a file or directory outside of a bind
644397d425dSEric W. Biederman  * mount, path_connected allows those cases to be detected.
645397d425dSEric W. Biederman  */
6466b03f7edSAl Viro static bool path_connected(struct vfsmount *mnt, struct dentry *dentry)
647397d425dSEric W. Biederman {
64895dd7758SEric W. Biederman 	struct super_block *sb = mnt->mnt_sb;
649397d425dSEric W. Biederman 
650402dd2cfSChristoph Hellwig 	/* Bind mounts can have disconnected paths */
651402dd2cfSChristoph Hellwig 	if (mnt->mnt_root == sb->s_root)
652397d425dSEric W. Biederman 		return true;
653397d425dSEric W. Biederman 
6546b03f7edSAl Viro 	return is_subdir(dentry, mnt->mnt_root);
655397d425dSEric W. Biederman }
656397d425dSEric W. Biederman 
6577973387aSAl Viro static void drop_links(struct nameidata *nd)
6587973387aSAl Viro {
6597973387aSAl Viro 	int i = nd->depth;
6607973387aSAl Viro 	while (i--) {
6617973387aSAl Viro 		struct saved *last = nd->stack + i;
662fceef393SAl Viro 		do_delayed_call(&last->done);
663fceef393SAl Viro 		clear_delayed_call(&last->done);
6647973387aSAl Viro 	}
6657973387aSAl Viro }
6667973387aSAl Viro 
6677973387aSAl Viro static void terminate_walk(struct nameidata *nd)
6687973387aSAl Viro {
6697973387aSAl Viro 	drop_links(nd);
6707973387aSAl Viro 	if (!(nd->flags & LOOKUP_RCU)) {
6717973387aSAl Viro 		int i;
6727973387aSAl Viro 		path_put(&nd->path);
6737973387aSAl Viro 		for (i = 0; i < nd->depth; i++)
6747973387aSAl Viro 			path_put(&nd->stack[i].link);
675bcba1e7dSAl Viro 		if (nd->state & ND_ROOT_GRABBED) {
676102b8af2SAl Viro 			path_put(&nd->root);
677bcba1e7dSAl Viro 			nd->state &= ~ND_ROOT_GRABBED;
678102b8af2SAl Viro 		}
6797973387aSAl Viro 	} else {
6807973387aSAl Viro 		nd->flags &= ~LOOKUP_RCU;
6817973387aSAl Viro 		rcu_read_unlock();
6827973387aSAl Viro 	}
6837973387aSAl Viro 	nd->depth = 0;
6847d01ef75SAl Viro 	nd->path.mnt = NULL;
6857d01ef75SAl Viro 	nd->path.dentry = NULL;
6867973387aSAl Viro }
6877973387aSAl Viro 
6887973387aSAl Viro /* path_put is needed afterwards regardless of success or failure */
6892aa38470SAl Viro static bool __legitimize_path(struct path *path, unsigned seq, unsigned mseq)
6907973387aSAl Viro {
6912aa38470SAl Viro 	int res = __legitimize_mnt(path->mnt, mseq);
6927973387aSAl Viro 	if (unlikely(res)) {
6937973387aSAl Viro 		if (res > 0)
6947973387aSAl Viro 			path->mnt = NULL;
6957973387aSAl Viro 		path->dentry = NULL;
6967973387aSAl Viro 		return false;
6977973387aSAl Viro 	}
6987973387aSAl Viro 	if (unlikely(!lockref_get_not_dead(&path->dentry->d_lockref))) {
6997973387aSAl Viro 		path->dentry = NULL;
7007973387aSAl Viro 		return false;
7017973387aSAl Viro 	}
7027973387aSAl Viro 	return !read_seqcount_retry(&path->dentry->d_seq, seq);
7037973387aSAl Viro }
7047973387aSAl Viro 
7052aa38470SAl Viro static inline bool legitimize_path(struct nameidata *nd,
7062aa38470SAl Viro 			    struct path *path, unsigned seq)
7072aa38470SAl Viro {
7085bd73286SAl Viro 	return __legitimize_path(path, seq, nd->m_seq);
7092aa38470SAl Viro }
7102aa38470SAl Viro 
7117973387aSAl Viro static bool legitimize_links(struct nameidata *nd)
7127973387aSAl Viro {
7137973387aSAl Viro 	int i;
714eacd9aa8SAl Viro 	if (unlikely(nd->flags & LOOKUP_CACHED)) {
715eacd9aa8SAl Viro 		drop_links(nd);
716eacd9aa8SAl Viro 		nd->depth = 0;
717eacd9aa8SAl Viro 		return false;
718eacd9aa8SAl Viro 	}
7197973387aSAl Viro 	for (i = 0; i < nd->depth; i++) {
7207973387aSAl Viro 		struct saved *last = nd->stack + i;
7217973387aSAl Viro 		if (unlikely(!legitimize_path(nd, &last->link, last->seq))) {
7227973387aSAl Viro 			drop_links(nd);
7237973387aSAl Viro 			nd->depth = i + 1;
7247973387aSAl Viro 			return false;
7257973387aSAl Viro 		}
7267973387aSAl Viro 	}
7277973387aSAl Viro 	return true;
7287973387aSAl Viro }
7297973387aSAl Viro 
730ee594bffSAl Viro static bool legitimize_root(struct nameidata *nd)
731ee594bffSAl Viro {
732adb21d2bSAleksa Sarai 	/*
733adb21d2bSAleksa Sarai 	 * For scoped-lookups (where nd->root has been zeroed), we need to
734adb21d2bSAleksa Sarai 	 * restart the whole lookup from scratch -- because set_root() is wrong
735adb21d2bSAleksa Sarai 	 * for these lookups (nd->dfd is the root, not the filesystem root).
736adb21d2bSAleksa Sarai 	 */
737adb21d2bSAleksa Sarai 	if (!nd->root.mnt && (nd->flags & LOOKUP_IS_SCOPED))
738adb21d2bSAleksa Sarai 		return false;
739adb21d2bSAleksa Sarai 	/* Nothing to do if nd->root is zero or is managed by the VFS user. */
740bcba1e7dSAl Viro 	if (!nd->root.mnt || (nd->state & ND_ROOT_PRESET))
741ee594bffSAl Viro 		return true;
742bcba1e7dSAl Viro 	nd->state |= ND_ROOT_GRABBED;
743ee594bffSAl Viro 	return legitimize_path(nd, &nd->root, nd->root_seq);
744ee594bffSAl Viro }
745ee594bffSAl Viro 
74619660af7SAl Viro /*
74731e6b01fSNick Piggin  * Path walking has 2 modes, rcu-walk and ref-walk (see
74819660af7SAl Viro  * Documentation/filesystems/path-lookup.txt).  In situations when we can't
74919660af7SAl Viro  * continue in RCU mode, we attempt to drop out of rcu-walk mode and grab
75057e3715cSMike Marshall  * normal reference counts on dentries and vfsmounts to transition to ref-walk
75119660af7SAl Viro  * mode.  Refcounts are grabbed at the last known good point before rcu-walk
75219660af7SAl Viro  * got stuck, so ref-walk may continue from there. If this is not successful
75319660af7SAl Viro  * (eg. a seqcount has changed), then failure is returned and it's up to caller
75419660af7SAl Viro  * to restart the path walk from the beginning in ref-walk mode.
75531e6b01fSNick Piggin  */
75631e6b01fSNick Piggin 
75731e6b01fSNick Piggin /**
758e36cffedSJens Axboe  * try_to_unlazy - try to switch to ref-walk mode.
75919660af7SAl Viro  * @nd: nameidata pathwalk data
760e36cffedSJens Axboe  * Returns: true on success, false on failure
76131e6b01fSNick Piggin  *
762e36cffedSJens Axboe  * try_to_unlazy attempts to legitimize the current nd->path and nd->root
7634675ac39SAl Viro  * for ref-walk mode.
7644675ac39SAl Viro  * Must be called from rcu-walk context.
765e36cffedSJens Axboe  * Nothing should touch nameidata between try_to_unlazy() failure and
7667973387aSAl Viro  * terminate_walk().
76731e6b01fSNick Piggin  */
768e36cffedSJens Axboe static bool try_to_unlazy(struct nameidata *nd)
76931e6b01fSNick Piggin {
77031e6b01fSNick Piggin 	struct dentry *parent = nd->path.dentry;
77131e6b01fSNick Piggin 
77231e6b01fSNick Piggin 	BUG_ON(!(nd->flags & LOOKUP_RCU));
773e5c832d5SLinus Torvalds 
774e5c832d5SLinus Torvalds 	nd->flags &= ~LOOKUP_RCU;
7757973387aSAl Viro 	if (unlikely(!legitimize_links(nd)))
7764675ac39SAl Viro 		goto out1;
77784a2bd39SAl Viro 	if (unlikely(!legitimize_path(nd, &nd->path, nd->seq)))
77884a2bd39SAl Viro 		goto out;
779ee594bffSAl Viro 	if (unlikely(!legitimize_root(nd)))
7804675ac39SAl Viro 		goto out;
7814675ac39SAl Viro 	rcu_read_unlock();
7824675ac39SAl Viro 	BUG_ON(nd->inode != parent->d_inode);
783e36cffedSJens Axboe 	return true;
7844675ac39SAl Viro 
78584a2bd39SAl Viro out1:
7864675ac39SAl Viro 	nd->path.mnt = NULL;
7874675ac39SAl Viro 	nd->path.dentry = NULL;
7884675ac39SAl Viro out:
7894675ac39SAl Viro 	rcu_read_unlock();
790e36cffedSJens Axboe 	return false;
7914675ac39SAl Viro }
7924675ac39SAl Viro 
7934675ac39SAl Viro /**
794ae66db45SAl Viro  * try_to_unlazy_next - try to switch to ref-walk mode.
7954675ac39SAl Viro  * @nd: nameidata pathwalk data
796ae66db45SAl Viro  * @dentry: next dentry to step into
797ae66db45SAl Viro  * @seq: seq number to check @dentry against
798ae66db45SAl Viro  * Returns: true on success, false on failure
7994675ac39SAl Viro  *
800ae66db45SAl Viro  * Similar to to try_to_unlazy(), but here we have the next dentry already
801ae66db45SAl Viro  * picked by rcu-walk and want to legitimize that in addition to the current
802ae66db45SAl Viro  * nd->path and nd->root for ref-walk mode.  Must be called from rcu-walk context.
803ae66db45SAl Viro  * Nothing should touch nameidata between try_to_unlazy_next() failure and
8044675ac39SAl Viro  * terminate_walk().
8054675ac39SAl Viro  */
806ae66db45SAl Viro static bool try_to_unlazy_next(struct nameidata *nd, struct dentry *dentry, unsigned seq)
8074675ac39SAl Viro {
8084675ac39SAl Viro 	BUG_ON(!(nd->flags & LOOKUP_RCU));
8094675ac39SAl Viro 
8104675ac39SAl Viro 	nd->flags &= ~LOOKUP_RCU;
8114675ac39SAl Viro 	if (unlikely(!legitimize_links(nd)))
8124675ac39SAl Viro 		goto out2;
8137973387aSAl Viro 	if (unlikely(!legitimize_mnt(nd->path.mnt, nd->m_seq)))
8147973387aSAl Viro 		goto out2;
8154675ac39SAl Viro 	if (unlikely(!lockref_get_not_dead(&nd->path.dentry->d_lockref)))
8167973387aSAl Viro 		goto out1;
81748a066e7SAl Viro 
81815570086SLinus Torvalds 	/*
8194675ac39SAl Viro 	 * We need to move both the parent and the dentry from the RCU domain
8204675ac39SAl Viro 	 * to be properly refcounted. And the sequence number in the dentry
8214675ac39SAl Viro 	 * validates *both* dentry counters, since we checked the sequence
8224675ac39SAl Viro 	 * number of the parent after we got the child sequence number. So we
8234675ac39SAl Viro 	 * know the parent must still be valid if the child sequence number is
82415570086SLinus Torvalds 	 */
8254675ac39SAl Viro 	if (unlikely(!lockref_get_not_dead(&dentry->d_lockref)))
826e5c832d5SLinus Torvalds 		goto out;
82784a2bd39SAl Viro 	if (unlikely(read_seqcount_retry(&dentry->d_seq, seq)))
82884a2bd39SAl Viro 		goto out_dput;
829e5c832d5SLinus Torvalds 	/*
830e5c832d5SLinus Torvalds 	 * Sequence counts matched. Now make sure that the root is
831e5c832d5SLinus Torvalds 	 * still valid and get it if required.
832e5c832d5SLinus Torvalds 	 */
83384a2bd39SAl Viro 	if (unlikely(!legitimize_root(nd)))
83484a2bd39SAl Viro 		goto out_dput;
8358b61e74fSAl Viro 	rcu_read_unlock();
836ae66db45SAl Viro 	return true;
83719660af7SAl Viro 
8387973387aSAl Viro out2:
8397973387aSAl Viro 	nd->path.mnt = NULL;
8407973387aSAl Viro out1:
8417973387aSAl Viro 	nd->path.dentry = NULL;
842e5c832d5SLinus Torvalds out:
8438b61e74fSAl Viro 	rcu_read_unlock();
844ae66db45SAl Viro 	return false;
84584a2bd39SAl Viro out_dput:
84684a2bd39SAl Viro 	rcu_read_unlock();
84784a2bd39SAl Viro 	dput(dentry);
848ae66db45SAl Viro 	return false;
84931e6b01fSNick Piggin }
85031e6b01fSNick Piggin 
8514ce16ef3SAl Viro static inline int d_revalidate(struct dentry *dentry, unsigned int flags)
85234286d66SNick Piggin {
853a89f8337SAl Viro 	if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE))
8544ce16ef3SAl Viro 		return dentry->d_op->d_revalidate(dentry, flags);
855a89f8337SAl Viro 	else
856a89f8337SAl Viro 		return 1;
85734286d66SNick Piggin }
85834286d66SNick Piggin 
8599f1fafeeSAl Viro /**
8609f1fafeeSAl Viro  * complete_walk - successful completion of path walk
8619f1fafeeSAl Viro  * @nd:  pointer nameidata
86239159de2SJeff Layton  *
8639f1fafeeSAl Viro  * If we had been in RCU mode, drop out of it and legitimize nd->path.
8649f1fafeeSAl Viro  * Revalidate the final result, unless we'd already done that during
8659f1fafeeSAl Viro  * the path walk or the filesystem doesn't ask for it.  Return 0 on
8669f1fafeeSAl Viro  * success, -error on failure.  In case of failure caller does not
8679f1fafeeSAl Viro  * need to drop nd->path.
86839159de2SJeff Layton  */
8699f1fafeeSAl Viro static int complete_walk(struct nameidata *nd)
87039159de2SJeff Layton {
87116c2cd71SAl Viro 	struct dentry *dentry = nd->path.dentry;
87239159de2SJeff Layton 	int status;
87339159de2SJeff Layton 
8749f1fafeeSAl Viro 	if (nd->flags & LOOKUP_RCU) {
875adb21d2bSAleksa Sarai 		/*
876adb21d2bSAleksa Sarai 		 * We don't want to zero nd->root for scoped-lookups or
877adb21d2bSAleksa Sarai 		 * externally-managed nd->root.
878adb21d2bSAleksa Sarai 		 */
879bcba1e7dSAl Viro 		if (!(nd->state & ND_ROOT_PRESET))
880bcba1e7dSAl Viro 			if (!(nd->flags & LOOKUP_IS_SCOPED))
8819f1fafeeSAl Viro 				nd->root.mnt = NULL;
8826c6ec2b0SJens Axboe 		nd->flags &= ~LOOKUP_CACHED;
883e36cffedSJens Axboe 		if (!try_to_unlazy(nd))
88448a066e7SAl Viro 			return -ECHILD;
88548a066e7SAl Viro 	}
8869f1fafeeSAl Viro 
887adb21d2bSAleksa Sarai 	if (unlikely(nd->flags & LOOKUP_IS_SCOPED)) {
888adb21d2bSAleksa Sarai 		/*
889adb21d2bSAleksa Sarai 		 * While the guarantee of LOOKUP_IS_SCOPED is (roughly) "don't
890adb21d2bSAleksa Sarai 		 * ever step outside the root during lookup" and should already
891adb21d2bSAleksa Sarai 		 * be guaranteed by the rest of namei, we want to avoid a namei
892adb21d2bSAleksa Sarai 		 * BUG resulting in userspace being given a path that was not
893adb21d2bSAleksa Sarai 		 * scoped within the root at some point during the lookup.
894adb21d2bSAleksa Sarai 		 *
895adb21d2bSAleksa Sarai 		 * So, do a final sanity-check to make sure that in the
896adb21d2bSAleksa Sarai 		 * worst-case scenario (a complete bypass of LOOKUP_IS_SCOPED)
897adb21d2bSAleksa Sarai 		 * we won't silently return an fd completely outside of the
898adb21d2bSAleksa Sarai 		 * requested root to userspace.
899adb21d2bSAleksa Sarai 		 *
900adb21d2bSAleksa Sarai 		 * Userspace could move the path outside the root after this
901adb21d2bSAleksa Sarai 		 * check, but as discussed elsewhere this is not a concern (the
902adb21d2bSAleksa Sarai 		 * resolved file was inside the root at some point).
903adb21d2bSAleksa Sarai 		 */
904adb21d2bSAleksa Sarai 		if (!path_is_under(&nd->path, &nd->root))
905adb21d2bSAleksa Sarai 			return -EXDEV;
906adb21d2bSAleksa Sarai 	}
907adb21d2bSAleksa Sarai 
908bcba1e7dSAl Viro 	if (likely(!(nd->state & ND_JUMPED)))
90939159de2SJeff Layton 		return 0;
91039159de2SJeff Layton 
911ecf3d1f1SJeff Layton 	if (likely(!(dentry->d_flags & DCACHE_OP_WEAK_REVALIDATE)))
91216c2cd71SAl Viro 		return 0;
91316c2cd71SAl Viro 
914ecf3d1f1SJeff Layton 	status = dentry->d_op->d_weak_revalidate(dentry, nd->flags);
91539159de2SJeff Layton 	if (status > 0)
91639159de2SJeff Layton 		return 0;
91739159de2SJeff Layton 
91816c2cd71SAl Viro 	if (!status)
91939159de2SJeff Layton 		status = -ESTALE;
92016c2cd71SAl Viro 
92139159de2SJeff Layton 	return status;
92239159de2SJeff Layton }
92339159de2SJeff Layton 
924740a1678SAleksa Sarai static int set_root(struct nameidata *nd)
9252a737871SAl Viro {
92631e6b01fSNick Piggin 	struct fs_struct *fs = current->fs;
9279e6697e2SAl Viro 
928adb21d2bSAleksa Sarai 	/*
929adb21d2bSAleksa Sarai 	 * Jumping to the real root in a scoped-lookup is a BUG in namei, but we
930adb21d2bSAleksa Sarai 	 * still have to ensure it doesn't happen because it will cause a breakout
931adb21d2bSAleksa Sarai 	 * from the dirfd.
932adb21d2bSAleksa Sarai 	 */
933adb21d2bSAleksa Sarai 	if (WARN_ON(nd->flags & LOOKUP_IS_SCOPED))
934adb21d2bSAleksa Sarai 		return -ENOTRECOVERABLE;
935adb21d2bSAleksa Sarai 
9369e6697e2SAl Viro 	if (nd->flags & LOOKUP_RCU) {
9378f47a016SAl Viro 		unsigned seq;
938c28cc364SNick Piggin 
939c28cc364SNick Piggin 		do {
940c28cc364SNick Piggin 			seq = read_seqcount_begin(&fs->seq);
94131e6b01fSNick Piggin 			nd->root = fs->root;
9428f47a016SAl Viro 			nd->root_seq = __read_seqcount_begin(&nd->root.dentry->d_seq);
943c28cc364SNick Piggin 		} while (read_seqcount_retry(&fs->seq, seq));
9449e6697e2SAl Viro 	} else {
9459e6697e2SAl Viro 		get_fs_root(fs, &nd->root);
946bcba1e7dSAl Viro 		nd->state |= ND_ROOT_GRABBED;
9479e6697e2SAl Viro 	}
948740a1678SAleksa Sarai 	return 0;
94931e6b01fSNick Piggin }
95031e6b01fSNick Piggin 
951248fb5b9SAl Viro static int nd_jump_root(struct nameidata *nd)
952248fb5b9SAl Viro {
953adb21d2bSAleksa Sarai 	if (unlikely(nd->flags & LOOKUP_BENEATH))
954adb21d2bSAleksa Sarai 		return -EXDEV;
95572ba2929SAleksa Sarai 	if (unlikely(nd->flags & LOOKUP_NO_XDEV)) {
95672ba2929SAleksa Sarai 		/* Absolute path arguments to path_init() are allowed. */
95772ba2929SAleksa Sarai 		if (nd->path.mnt != NULL && nd->path.mnt != nd->root.mnt)
95872ba2929SAleksa Sarai 			return -EXDEV;
95972ba2929SAleksa Sarai 	}
960740a1678SAleksa Sarai 	if (!nd->root.mnt) {
961740a1678SAleksa Sarai 		int error = set_root(nd);
962740a1678SAleksa Sarai 		if (error)
963740a1678SAleksa Sarai 			return error;
964740a1678SAleksa Sarai 	}
965248fb5b9SAl Viro 	if (nd->flags & LOOKUP_RCU) {
966248fb5b9SAl Viro 		struct dentry *d;
967248fb5b9SAl Viro 		nd->path = nd->root;
968248fb5b9SAl Viro 		d = nd->path.dentry;
969248fb5b9SAl Viro 		nd->inode = d->d_inode;
970248fb5b9SAl Viro 		nd->seq = nd->root_seq;
971248fb5b9SAl Viro 		if (unlikely(read_seqcount_retry(&d->d_seq, nd->seq)))
972248fb5b9SAl Viro 			return -ECHILD;
973248fb5b9SAl Viro 	} else {
974248fb5b9SAl Viro 		path_put(&nd->path);
975248fb5b9SAl Viro 		nd->path = nd->root;
976248fb5b9SAl Viro 		path_get(&nd->path);
977248fb5b9SAl Viro 		nd->inode = nd->path.dentry->d_inode;
978248fb5b9SAl Viro 	}
979bcba1e7dSAl Viro 	nd->state |= ND_JUMPED;
980248fb5b9SAl Viro 	return 0;
981248fb5b9SAl Viro }
982248fb5b9SAl Viro 
983b5fb63c1SChristoph Hellwig /*
9846b255391SAl Viro  * Helper to directly jump to a known parsed path from ->get_link,
985b5fb63c1SChristoph Hellwig  * caller must have taken a reference to path beforehand.
986b5fb63c1SChristoph Hellwig  */
9871bc82070SAleksa Sarai int nd_jump_link(struct path *path)
988b5fb63c1SChristoph Hellwig {
9894b99d499SAleksa Sarai 	int error = -ELOOP;
9906e77137bSAl Viro 	struct nameidata *nd = current->nameidata;
991b5fb63c1SChristoph Hellwig 
9924b99d499SAleksa Sarai 	if (unlikely(nd->flags & LOOKUP_NO_MAGICLINKS))
9934b99d499SAleksa Sarai 		goto err;
9944b99d499SAleksa Sarai 
99572ba2929SAleksa Sarai 	error = -EXDEV;
99672ba2929SAleksa Sarai 	if (unlikely(nd->flags & LOOKUP_NO_XDEV)) {
99772ba2929SAleksa Sarai 		if (nd->path.mnt != path->mnt)
99872ba2929SAleksa Sarai 			goto err;
99972ba2929SAleksa Sarai 	}
1000adb21d2bSAleksa Sarai 	/* Not currently safe for scoped-lookups. */
1001adb21d2bSAleksa Sarai 	if (unlikely(nd->flags & LOOKUP_IS_SCOPED))
1002adb21d2bSAleksa Sarai 		goto err;
100372ba2929SAleksa Sarai 
10044b99d499SAleksa Sarai 	path_put(&nd->path);
1005b5fb63c1SChristoph Hellwig 	nd->path = *path;
1006b5fb63c1SChristoph Hellwig 	nd->inode = nd->path.dentry->d_inode;
1007bcba1e7dSAl Viro 	nd->state |= ND_JUMPED;
10081bc82070SAleksa Sarai 	return 0;
10094b99d499SAleksa Sarai 
10104b99d499SAleksa Sarai err:
10114b99d499SAleksa Sarai 	path_put(path);
10124b99d499SAleksa Sarai 	return error;
1013b5fb63c1SChristoph Hellwig }
1014b5fb63c1SChristoph Hellwig 
1015b9ff4429SAl Viro static inline void put_link(struct nameidata *nd)
1016574197e0SAl Viro {
101721c3003dSAl Viro 	struct saved *last = nd->stack + --nd->depth;
1018fceef393SAl Viro 	do_delayed_call(&last->done);
10196548fae2SAl Viro 	if (!(nd->flags & LOOKUP_RCU))
1020b9ff4429SAl Viro 		path_put(&last->link);
1021574197e0SAl Viro }
1022574197e0SAl Viro 
1023561ec64aSLinus Torvalds int sysctl_protected_symlinks __read_mostly = 0;
1024561ec64aSLinus Torvalds int sysctl_protected_hardlinks __read_mostly = 0;
102530aba665SSalvatore Mesoraca int sysctl_protected_fifos __read_mostly;
102630aba665SSalvatore Mesoraca int sysctl_protected_regular __read_mostly;
1027800179c9SKees Cook 
1028800179c9SKees Cook /**
1029800179c9SKees Cook  * may_follow_link - Check symlink following for unsafe situations
103055852635SRandy Dunlap  * @nd: nameidata pathwalk data
1031800179c9SKees Cook  *
1032800179c9SKees Cook  * In the case of the sysctl_protected_symlinks sysctl being enabled,
1033800179c9SKees Cook  * CAP_DAC_OVERRIDE needs to be specifically ignored if the symlink is
1034800179c9SKees Cook  * in a sticky world-writable directory. This is to protect privileged
1035800179c9SKees Cook  * processes from failing races against path names that may change out
1036800179c9SKees Cook  * from under them by way of other users creating malicious symlinks.
1037800179c9SKees Cook  * It will permit symlinks to be followed only when outside a sticky
1038800179c9SKees Cook  * world-writable directory, or when the uid of the symlink and follower
1039800179c9SKees Cook  * match, or when the directory owner matches the symlink's owner.
1040800179c9SKees Cook  *
1041800179c9SKees Cook  * Returns 0 if following the symlink is allowed, -ve on error.
1042800179c9SKees Cook  */
1043ad6cc4c3SAl Viro static inline int may_follow_link(struct nameidata *nd, const struct inode *inode)
1044800179c9SKees Cook {
1045ba73d987SChristian Brauner 	struct user_namespace *mnt_userns;
1046ba73d987SChristian Brauner 	kuid_t i_uid;
1047ba73d987SChristian Brauner 
1048800179c9SKees Cook 	if (!sysctl_protected_symlinks)
1049800179c9SKees Cook 		return 0;
1050800179c9SKees Cook 
1051ba73d987SChristian Brauner 	mnt_userns = mnt_user_ns(nd->path.mnt);
1052ba73d987SChristian Brauner 	i_uid = i_uid_into_mnt(mnt_userns, inode);
1053800179c9SKees Cook 	/* Allowed if owner and follower match. */
1054ba73d987SChristian Brauner 	if (uid_eq(current_cred()->fsuid, i_uid))
1055800179c9SKees Cook 		return 0;
1056800179c9SKees Cook 
1057800179c9SKees Cook 	/* Allowed if parent directory not sticky and world-writable. */
10580f705953SAl Viro 	if ((nd->dir_mode & (S_ISVTX|S_IWOTH)) != (S_ISVTX|S_IWOTH))
1059800179c9SKees Cook 		return 0;
1060800179c9SKees Cook 
1061800179c9SKees Cook 	/* Allowed if parent directory and link owner match. */
1062ba73d987SChristian Brauner 	if (uid_valid(nd->dir_uid) && uid_eq(nd->dir_uid, i_uid))
1063800179c9SKees Cook 		return 0;
1064800179c9SKees Cook 
106531956502SAl Viro 	if (nd->flags & LOOKUP_RCU)
106631956502SAl Viro 		return -ECHILD;
106731956502SAl Viro 
1068ea841bafSRichard Guy Briggs 	audit_inode(nd->name, nd->stack[0].link.dentry, 0);
1069245d7369SKees Cook 	audit_log_path_denied(AUDIT_ANOM_LINK, "follow_link");
1070800179c9SKees Cook 	return -EACCES;
1071800179c9SKees Cook }
1072800179c9SKees Cook 
1073800179c9SKees Cook /**
1074800179c9SKees Cook  * safe_hardlink_source - Check for safe hardlink conditions
1075ba73d987SChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
1076800179c9SKees Cook  * @inode: the source inode to hardlink from
1077800179c9SKees Cook  *
1078800179c9SKees Cook  * Return false if at least one of the following conditions:
1079800179c9SKees Cook  *    - inode is not a regular file
1080800179c9SKees Cook  *    - inode is setuid
1081800179c9SKees Cook  *    - inode is setgid and group-exec
1082800179c9SKees Cook  *    - access failure for read and write
1083800179c9SKees Cook  *
1084800179c9SKees Cook  * Otherwise returns true.
1085800179c9SKees Cook  */
1086ba73d987SChristian Brauner static bool safe_hardlink_source(struct user_namespace *mnt_userns,
1087ba73d987SChristian Brauner 				 struct inode *inode)
1088800179c9SKees Cook {
1089800179c9SKees Cook 	umode_t mode = inode->i_mode;
1090800179c9SKees Cook 
1091800179c9SKees Cook 	/* Special files should not get pinned to the filesystem. */
1092800179c9SKees Cook 	if (!S_ISREG(mode))
1093800179c9SKees Cook 		return false;
1094800179c9SKees Cook 
1095800179c9SKees Cook 	/* Setuid files should not get pinned to the filesystem. */
1096800179c9SKees Cook 	if (mode & S_ISUID)
1097800179c9SKees Cook 		return false;
1098800179c9SKees Cook 
1099800179c9SKees Cook 	/* Executable setgid files should not get pinned to the filesystem. */
1100800179c9SKees Cook 	if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP))
1101800179c9SKees Cook 		return false;
1102800179c9SKees Cook 
1103800179c9SKees Cook 	/* Hardlinking to unreadable or unwritable sources is dangerous. */
1104ba73d987SChristian Brauner 	if (inode_permission(mnt_userns, inode, MAY_READ | MAY_WRITE))
1105800179c9SKees Cook 		return false;
1106800179c9SKees Cook 
1107800179c9SKees Cook 	return true;
1108800179c9SKees Cook }
1109800179c9SKees Cook 
1110800179c9SKees Cook /**
1111800179c9SKees Cook  * may_linkat - Check permissions for creating a hardlink
1112ba73d987SChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
1113800179c9SKees Cook  * @link: the source to hardlink from
1114800179c9SKees Cook  *
1115800179c9SKees Cook  * Block hardlink when all of:
1116800179c9SKees Cook  *  - sysctl_protected_hardlinks enabled
1117800179c9SKees Cook  *  - fsuid does not match inode
1118800179c9SKees Cook  *  - hardlink source is unsafe (see safe_hardlink_source() above)
1119f2ca3796SDirk Steinmetz  *  - not CAP_FOWNER in a namespace with the inode owner uid mapped
1120800179c9SKees Cook  *
1121ba73d987SChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
1122ba73d987SChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
1123ba73d987SChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
1124ba73d987SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
1125ba73d987SChristian Brauner  * raw inode simply passs init_user_ns.
1126ba73d987SChristian Brauner  *
1127800179c9SKees Cook  * Returns 0 if successful, -ve on error.
1128800179c9SKees Cook  */
1129ba73d987SChristian Brauner int may_linkat(struct user_namespace *mnt_userns, struct path *link)
1130800179c9SKees Cook {
1131593d1ce8SEric W. Biederman 	struct inode *inode = link->dentry->d_inode;
1132593d1ce8SEric W. Biederman 
1133593d1ce8SEric W. Biederman 	/* Inode writeback is not safe when the uid or gid are invalid. */
1134ba73d987SChristian Brauner 	if (!uid_valid(i_uid_into_mnt(mnt_userns, inode)) ||
1135ba73d987SChristian Brauner 	    !gid_valid(i_gid_into_mnt(mnt_userns, inode)))
1136593d1ce8SEric W. Biederman 		return -EOVERFLOW;
1137800179c9SKees Cook 
1138800179c9SKees Cook 	if (!sysctl_protected_hardlinks)
1139800179c9SKees Cook 		return 0;
1140800179c9SKees Cook 
1141800179c9SKees Cook 	/* Source inode owner (or CAP_FOWNER) can hardlink all they like,
1142800179c9SKees Cook 	 * otherwise, it must be a safe source.
1143800179c9SKees Cook 	 */
1144ba73d987SChristian Brauner 	if (safe_hardlink_source(mnt_userns, inode) ||
1145ba73d987SChristian Brauner 	    inode_owner_or_capable(mnt_userns, inode))
1146800179c9SKees Cook 		return 0;
1147800179c9SKees Cook 
1148245d7369SKees Cook 	audit_log_path_denied(AUDIT_ANOM_LINK, "linkat");
1149800179c9SKees Cook 	return -EPERM;
1150800179c9SKees Cook }
1151800179c9SKees Cook 
115230aba665SSalvatore Mesoraca /**
115330aba665SSalvatore Mesoraca  * may_create_in_sticky - Check whether an O_CREAT open in a sticky directory
115430aba665SSalvatore Mesoraca  *			  should be allowed, or not, on files that already
115530aba665SSalvatore Mesoraca  *			  exist.
1156ba73d987SChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
11572111c3c0SRandy Dunlap  * @nd: nameidata pathwalk data
115830aba665SSalvatore Mesoraca  * @inode: the inode of the file to open
115930aba665SSalvatore Mesoraca  *
116030aba665SSalvatore Mesoraca  * Block an O_CREAT open of a FIFO (or a regular file) when:
116130aba665SSalvatore Mesoraca  *   - sysctl_protected_fifos (or sysctl_protected_regular) is enabled
116230aba665SSalvatore Mesoraca  *   - the file already exists
116330aba665SSalvatore Mesoraca  *   - we are in a sticky directory
116430aba665SSalvatore Mesoraca  *   - we don't own the file
116530aba665SSalvatore Mesoraca  *   - the owner of the directory doesn't own the file
116630aba665SSalvatore Mesoraca  *   - the directory is world writable
116730aba665SSalvatore Mesoraca  * If the sysctl_protected_fifos (or sysctl_protected_regular) is set to 2
116830aba665SSalvatore Mesoraca  * the directory doesn't have to be world writable: being group writable will
116930aba665SSalvatore Mesoraca  * be enough.
117030aba665SSalvatore Mesoraca  *
1171ba73d987SChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
1172ba73d987SChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
1173ba73d987SChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
1174ba73d987SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
1175ba73d987SChristian Brauner  * raw inode simply passs init_user_ns.
1176ba73d987SChristian Brauner  *
117730aba665SSalvatore Mesoraca  * Returns 0 if the open is allowed, -ve on error.
117830aba665SSalvatore Mesoraca  */
1179ba73d987SChristian Brauner static int may_create_in_sticky(struct user_namespace *mnt_userns,
1180ba73d987SChristian Brauner 				struct nameidata *nd, struct inode *const inode)
118130aba665SSalvatore Mesoraca {
1182ba73d987SChristian Brauner 	umode_t dir_mode = nd->dir_mode;
1183ba73d987SChristian Brauner 	kuid_t dir_uid = nd->dir_uid;
1184ba73d987SChristian Brauner 
118530aba665SSalvatore Mesoraca 	if ((!sysctl_protected_fifos && S_ISFIFO(inode->i_mode)) ||
118630aba665SSalvatore Mesoraca 	    (!sysctl_protected_regular && S_ISREG(inode->i_mode)) ||
1187d0cb5018SAl Viro 	    likely(!(dir_mode & S_ISVTX)) ||
1188ba73d987SChristian Brauner 	    uid_eq(i_uid_into_mnt(mnt_userns, inode), dir_uid) ||
1189ba73d987SChristian Brauner 	    uid_eq(current_fsuid(), i_uid_into_mnt(mnt_userns, inode)))
119030aba665SSalvatore Mesoraca 		return 0;
119130aba665SSalvatore Mesoraca 
1192d0cb5018SAl Viro 	if (likely(dir_mode & 0002) ||
1193d0cb5018SAl Viro 	    (dir_mode & 0020 &&
119430aba665SSalvatore Mesoraca 	     ((sysctl_protected_fifos >= 2 && S_ISFIFO(inode->i_mode)) ||
119530aba665SSalvatore Mesoraca 	      (sysctl_protected_regular >= 2 && S_ISREG(inode->i_mode))))) {
1196245d7369SKees Cook 		const char *operation = S_ISFIFO(inode->i_mode) ?
1197245d7369SKees Cook 					"sticky_create_fifo" :
1198245d7369SKees Cook 					"sticky_create_regular";
1199245d7369SKees Cook 		audit_log_path_denied(AUDIT_ANOM_CREAT, operation);
120030aba665SSalvatore Mesoraca 		return -EACCES;
120130aba665SSalvatore Mesoraca 	}
120230aba665SSalvatore Mesoraca 	return 0;
120330aba665SSalvatore Mesoraca }
120430aba665SSalvatore Mesoraca 
1205f015f126SDavid Howells /*
1206f015f126SDavid Howells  * follow_up - Find the mountpoint of path's vfsmount
1207f015f126SDavid Howells  *
1208f015f126SDavid Howells  * Given a path, find the mountpoint of its source file system.
1209f015f126SDavid Howells  * Replace @path with the path of the mountpoint in the parent mount.
1210f015f126SDavid Howells  * Up is towards /.
1211f015f126SDavid Howells  *
1212f015f126SDavid Howells  * Return 1 if we went up a level and 0 if we were already at the
1213f015f126SDavid Howells  * root.
1214f015f126SDavid Howells  */
1215bab77ebfSAl Viro int follow_up(struct path *path)
12161da177e4SLinus Torvalds {
12170714a533SAl Viro 	struct mount *mnt = real_mount(path->mnt);
12180714a533SAl Viro 	struct mount *parent;
12191da177e4SLinus Torvalds 	struct dentry *mountpoint;
122099b7db7bSNick Piggin 
122148a066e7SAl Viro 	read_seqlock_excl(&mount_lock);
12220714a533SAl Viro 	parent = mnt->mnt_parent;
12233c0a6163SAl Viro 	if (parent == mnt) {
122448a066e7SAl Viro 		read_sequnlock_excl(&mount_lock);
12251da177e4SLinus Torvalds 		return 0;
12261da177e4SLinus Torvalds 	}
12270714a533SAl Viro 	mntget(&parent->mnt);
1228a73324daSAl Viro 	mountpoint = dget(mnt->mnt_mountpoint);
122948a066e7SAl Viro 	read_sequnlock_excl(&mount_lock);
1230bab77ebfSAl Viro 	dput(path->dentry);
1231bab77ebfSAl Viro 	path->dentry = mountpoint;
1232bab77ebfSAl Viro 	mntput(path->mnt);
12330714a533SAl Viro 	path->mnt = &parent->mnt;
12341da177e4SLinus Torvalds 	return 1;
12351da177e4SLinus Torvalds }
12364d359507SAl Viro EXPORT_SYMBOL(follow_up);
12371da177e4SLinus Torvalds 
12387ef482faSAl Viro static bool choose_mountpoint_rcu(struct mount *m, const struct path *root,
12397ef482faSAl Viro 				  struct path *path, unsigned *seqp)
12407ef482faSAl Viro {
12417ef482faSAl Viro 	while (mnt_has_parent(m)) {
12427ef482faSAl Viro 		struct dentry *mountpoint = m->mnt_mountpoint;
12437ef482faSAl Viro 
12447ef482faSAl Viro 		m = m->mnt_parent;
12457ef482faSAl Viro 		if (unlikely(root->dentry == mountpoint &&
12467ef482faSAl Viro 			     root->mnt == &m->mnt))
12477ef482faSAl Viro 			break;
12487ef482faSAl Viro 		if (mountpoint != m->mnt.mnt_root) {
12497ef482faSAl Viro 			path->mnt = &m->mnt;
12507ef482faSAl Viro 			path->dentry = mountpoint;
12517ef482faSAl Viro 			*seqp = read_seqcount_begin(&mountpoint->d_seq);
12527ef482faSAl Viro 			return true;
12537ef482faSAl Viro 		}
12547ef482faSAl Viro 	}
12557ef482faSAl Viro 	return false;
12567ef482faSAl Viro }
12577ef482faSAl Viro 
12582aa38470SAl Viro static bool choose_mountpoint(struct mount *m, const struct path *root,
12592aa38470SAl Viro 			      struct path *path)
12602aa38470SAl Viro {
12612aa38470SAl Viro 	bool found;
12622aa38470SAl Viro 
12632aa38470SAl Viro 	rcu_read_lock();
12642aa38470SAl Viro 	while (1) {
12652aa38470SAl Viro 		unsigned seq, mseq = read_seqbegin(&mount_lock);
12662aa38470SAl Viro 
12672aa38470SAl Viro 		found = choose_mountpoint_rcu(m, root, path, &seq);
12682aa38470SAl Viro 		if (unlikely(!found)) {
12692aa38470SAl Viro 			if (!read_seqretry(&mount_lock, mseq))
12702aa38470SAl Viro 				break;
12712aa38470SAl Viro 		} else {
12722aa38470SAl Viro 			if (likely(__legitimize_path(path, seq, mseq)))
12732aa38470SAl Viro 				break;
12742aa38470SAl Viro 			rcu_read_unlock();
12752aa38470SAl Viro 			path_put(path);
12762aa38470SAl Viro 			rcu_read_lock();
12772aa38470SAl Viro 		}
12782aa38470SAl Viro 	}
12792aa38470SAl Viro 	rcu_read_unlock();
12802aa38470SAl Viro 	return found;
12812aa38470SAl Viro }
12822aa38470SAl Viro 
1283b5c84bf6SNick Piggin /*
12849875cf80SDavid Howells  * Perform an automount
12859875cf80SDavid Howells  * - return -EISDIR to tell follow_managed() to stop and return the path we
12869875cf80SDavid Howells  *   were called with.
12871da177e4SLinus Torvalds  */
12881c9f5e06SAl Viro static int follow_automount(struct path *path, int *count, unsigned lookup_flags)
128931e6b01fSNick Piggin {
129025e195aaSAl Viro 	struct dentry *dentry = path->dentry;
12919875cf80SDavid Howells 
12920ec26fd0SMiklos Szeredi 	/* We don't want to mount if someone's just doing a stat -
12930ec26fd0SMiklos Szeredi 	 * unless they're stat'ing a directory and appended a '/' to
12940ec26fd0SMiklos Szeredi 	 * the name.
12950ec26fd0SMiklos Szeredi 	 *
12960ec26fd0SMiklos Szeredi 	 * We do, however, want to mount if someone wants to open or
12975a30d8a2SDavid Howells 	 * create a file of any type under the mountpoint, wants to
12980ec26fd0SMiklos Szeredi 	 * traverse through the mountpoint or wants to open the
12990ec26fd0SMiklos Szeredi 	 * mounted directory.  Also, autofs may mark negative dentries
13000ec26fd0SMiklos Szeredi 	 * as being automount points.  These will need the attentions
13010ec26fd0SMiklos Szeredi 	 * of the daemon to instantiate them before they can be used.
13025a30d8a2SDavid Howells 	 */
13031c9f5e06SAl Viro 	if (!(lookup_flags & (LOOKUP_PARENT | LOOKUP_DIRECTORY |
13045d38f049SIan Kent 			   LOOKUP_OPEN | LOOKUP_CREATE | LOOKUP_AUTOMOUNT)) &&
130525e195aaSAl Viro 	    dentry->d_inode)
13069875cf80SDavid Howells 		return -EISDIR;
13070ec26fd0SMiklos Szeredi 
13081c9f5e06SAl Viro 	if (count && (*count)++ >= MAXSYMLINKS)
13099875cf80SDavid Howells 		return -ELOOP;
13109875cf80SDavid Howells 
131125e195aaSAl Viro 	return finish_automount(dentry->d_op->d_automount(path), path);
1312ea5b778aSDavid Howells }
13139875cf80SDavid Howells 
13149875cf80SDavid Howells /*
13159deed3ebSAl Viro  * mount traversal - out-of-line part.  One note on ->d_flags accesses -
13169deed3ebSAl Viro  * dentries are pinned but not locked here, so negative dentry can go
13179deed3ebSAl Viro  * positive right under us.  Use of smp_load_acquire() provides a barrier
13189deed3ebSAl Viro  * sufficient for ->d_inode and ->d_flags consistency.
13199875cf80SDavid Howells  */
13209deed3ebSAl Viro static int __traverse_mounts(struct path *path, unsigned flags, bool *jumped,
13219deed3ebSAl Viro 			     int *count, unsigned lookup_flags)
13229875cf80SDavid Howells {
13239deed3ebSAl Viro 	struct vfsmount *mnt = path->mnt;
13249875cf80SDavid Howells 	bool need_mntput = false;
13258aef1884SAl Viro 	int ret = 0;
13269875cf80SDavid Howells 
13279deed3ebSAl Viro 	while (flags & DCACHE_MANAGED_DENTRY) {
1328cc53ce53SDavid Howells 		/* Allow the filesystem to manage the transit without i_mutex
1329cc53ce53SDavid Howells 		 * being held. */
1330d41efb52SAl Viro 		if (flags & DCACHE_MANAGE_TRANSIT) {
1331fb5f51c7SIan Kent 			ret = path->dentry->d_op->d_manage(path, false);
1332508c8772SAl Viro 			flags = smp_load_acquire(&path->dentry->d_flags);
1333cc53ce53SDavid Howells 			if (ret < 0)
13348aef1884SAl Viro 				break;
1335cc53ce53SDavid Howells 		}
1336cc53ce53SDavid Howells 
13379deed3ebSAl Viro 		if (flags & DCACHE_MOUNTED) {	// something's mounted on it..
13389875cf80SDavid Howells 			struct vfsmount *mounted = lookup_mnt(path);
13399deed3ebSAl Viro 			if (mounted) {		// ... in our namespace
13409875cf80SDavid Howells 				dput(path->dentry);
13419875cf80SDavid Howells 				if (need_mntput)
1342463ffb2eSAl Viro 					mntput(path->mnt);
1343463ffb2eSAl Viro 				path->mnt = mounted;
1344463ffb2eSAl Viro 				path->dentry = dget(mounted->mnt_root);
13459deed3ebSAl Viro 				// here we know it's positive
13469deed3ebSAl Viro 				flags = path->dentry->d_flags;
13479875cf80SDavid Howells 				need_mntput = true;
13489875cf80SDavid Howells 				continue;
1349463ffb2eSAl Viro 			}
13501da177e4SLinus Torvalds 		}
13519875cf80SDavid Howells 
13529deed3ebSAl Viro 		if (!(flags & DCACHE_NEED_AUTOMOUNT))
13539deed3ebSAl Viro 			break;
13549deed3ebSAl Viro 
13559deed3ebSAl Viro 		// uncovered automount point
13569deed3ebSAl Viro 		ret = follow_automount(path, count, lookup_flags);
13579deed3ebSAl Viro 		flags = smp_load_acquire(&path->dentry->d_flags);
13589875cf80SDavid Howells 		if (ret < 0)
13598aef1884SAl Viro 			break;
13609875cf80SDavid Howells 	}
13619875cf80SDavid Howells 
13629deed3ebSAl Viro 	if (ret == -EISDIR)
13639deed3ebSAl Viro 		ret = 0;
13649deed3ebSAl Viro 	// possible if you race with several mount --move
13659deed3ebSAl Viro 	if (need_mntput && path->mnt == mnt)
13668aef1884SAl Viro 		mntput(path->mnt);
13679deed3ebSAl Viro 	if (!ret && unlikely(d_flags_negative(flags)))
1368d41efb52SAl Viro 		ret = -ENOENT;
13699deed3ebSAl Viro 	*jumped = need_mntput;
13708402752eSAl Viro 	return ret;
13711da177e4SLinus Torvalds }
13721da177e4SLinus Torvalds 
13739deed3ebSAl Viro static inline int traverse_mounts(struct path *path, bool *jumped,
13749deed3ebSAl Viro 				  int *count, unsigned lookup_flags)
13759deed3ebSAl Viro {
13769deed3ebSAl Viro 	unsigned flags = smp_load_acquire(&path->dentry->d_flags);
13779deed3ebSAl Viro 
13789deed3ebSAl Viro 	/* fastpath */
13799deed3ebSAl Viro 	if (likely(!(flags & DCACHE_MANAGED_DENTRY))) {
13809deed3ebSAl Viro 		*jumped = false;
13819deed3ebSAl Viro 		if (unlikely(d_flags_negative(flags)))
13829deed3ebSAl Viro 			return -ENOENT;
13839deed3ebSAl Viro 		return 0;
13849deed3ebSAl Viro 	}
13859deed3ebSAl Viro 	return __traverse_mounts(path, flags, jumped, count, lookup_flags);
13869deed3ebSAl Viro }
13879deed3ebSAl Viro 
1388cc53ce53SDavid Howells int follow_down_one(struct path *path)
13891da177e4SLinus Torvalds {
13901da177e4SLinus Torvalds 	struct vfsmount *mounted;
13911da177e4SLinus Torvalds 
13921c755af4SAl Viro 	mounted = lookup_mnt(path);
13931da177e4SLinus Torvalds 	if (mounted) {
13949393bd07SAl Viro 		dput(path->dentry);
13959393bd07SAl Viro 		mntput(path->mnt);
13969393bd07SAl Viro 		path->mnt = mounted;
13979393bd07SAl Viro 		path->dentry = dget(mounted->mnt_root);
13981da177e4SLinus Torvalds 		return 1;
13991da177e4SLinus Torvalds 	}
14001da177e4SLinus Torvalds 	return 0;
14011da177e4SLinus Torvalds }
14024d359507SAl Viro EXPORT_SYMBOL(follow_down_one);
14031da177e4SLinus Torvalds 
14049875cf80SDavid Howells /*
14059deed3ebSAl Viro  * Follow down to the covering mount currently visible to userspace.  At each
14069deed3ebSAl Viro  * point, the filesystem owning that dentry may be queried as to whether the
14079deed3ebSAl Viro  * caller is permitted to proceed or not.
14089deed3ebSAl Viro  */
14099deed3ebSAl Viro int follow_down(struct path *path)
14109deed3ebSAl Viro {
14119deed3ebSAl Viro 	struct vfsmount *mnt = path->mnt;
14129deed3ebSAl Viro 	bool jumped;
14139deed3ebSAl Viro 	int ret = traverse_mounts(path, &jumped, NULL, 0);
14149deed3ebSAl Viro 
14159deed3ebSAl Viro 	if (path->mnt != mnt)
14169deed3ebSAl Viro 		mntput(mnt);
14179deed3ebSAl Viro 	return ret;
14189deed3ebSAl Viro }
14199deed3ebSAl Viro EXPORT_SYMBOL(follow_down);
14209deed3ebSAl Viro 
14219deed3ebSAl Viro /*
1422287548e4SAl Viro  * Try to skip to top of mountpoint pile in rcuwalk mode.  Fail if
1423287548e4SAl Viro  * we meet a managed dentry that would need blocking.
14249875cf80SDavid Howells  */
14259875cf80SDavid Howells static bool __follow_mount_rcu(struct nameidata *nd, struct path *path,
1426254cf582SAl Viro 			       struct inode **inode, unsigned *seqp)
14279875cf80SDavid Howells {
1428ea936aebSAl Viro 	struct dentry *dentry = path->dentry;
1429ea936aebSAl Viro 	unsigned int flags = dentry->d_flags;
1430ea936aebSAl Viro 
1431ea936aebSAl Viro 	if (likely(!(flags & DCACHE_MANAGED_DENTRY)))
1432ea936aebSAl Viro 		return true;
1433ea936aebSAl Viro 
1434ea936aebSAl Viro 	if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1435ea936aebSAl Viro 		return false;
1436ea936aebSAl Viro 
143762a7375eSIan Kent 	for (;;) {
143862a7375eSIan Kent 		/*
143962a7375eSIan Kent 		 * Don't forget we might have a non-mountpoint managed dentry
144062a7375eSIan Kent 		 * that wants to block transit.
144162a7375eSIan Kent 		 */
1442ea936aebSAl Viro 		if (unlikely(flags & DCACHE_MANAGE_TRANSIT)) {
1443ea936aebSAl Viro 			int res = dentry->d_op->d_manage(path, true);
1444ea936aebSAl Viro 			if (res)
1445ea936aebSAl Viro 				return res == -EISDIR;
1446ea936aebSAl Viro 			flags = dentry->d_flags;
1447b8faf035SNeilBrown 		}
144862a7375eSIan Kent 
1449ea936aebSAl Viro 		if (flags & DCACHE_MOUNTED) {
1450ea936aebSAl Viro 			struct mount *mounted = __lookup_mnt(path->mnt, dentry);
1451ea936aebSAl Viro 			if (mounted) {
1452c7105365SAl Viro 				path->mnt = &mounted->mnt;
1453ea936aebSAl Viro 				dentry = path->dentry = mounted->mnt.mnt_root;
1454bcba1e7dSAl Viro 				nd->state |= ND_JUMPED;
1455ea936aebSAl Viro 				*seqp = read_seqcount_begin(&dentry->d_seq);
1456ea936aebSAl Viro 				*inode = dentry->d_inode;
145759430262SLinus Torvalds 				/*
1458ea936aebSAl Viro 				 * We don't need to re-check ->d_seq after this
1459ea936aebSAl Viro 				 * ->d_inode read - there will be an RCU delay
1460ea936aebSAl Viro 				 * between mount hash removal and ->mnt_root
1461ea936aebSAl Viro 				 * becoming unpinned.
146259430262SLinus Torvalds 				 */
1463ea936aebSAl Viro 				flags = dentry->d_flags;
1464ea936aebSAl Viro 				continue;
14659875cf80SDavid Howells 			}
1466ea936aebSAl Viro 			if (read_seqretry(&mount_lock, nd->m_seq))
1467ea936aebSAl Viro 				return false;
1468ea936aebSAl Viro 		}
1469ea936aebSAl Viro 		return !(flags & DCACHE_NEED_AUTOMOUNT);
1470ea936aebSAl Viro 	}
1471287548e4SAl Viro }
1472287548e4SAl Viro 
1473db3c9adeSAl Viro static inline int handle_mounts(struct nameidata *nd, struct dentry *dentry,
1474db3c9adeSAl Viro 			  struct path *path, struct inode **inode,
1475db3c9adeSAl Viro 			  unsigned int *seqp)
1476bd7c4b50SAl Viro {
14779deed3ebSAl Viro 	bool jumped;
1478db3c9adeSAl Viro 	int ret;
1479bd7c4b50SAl Viro 
1480db3c9adeSAl Viro 	path->mnt = nd->path.mnt;
1481db3c9adeSAl Viro 	path->dentry = dentry;
1482c153007bSAl Viro 	if (nd->flags & LOOKUP_RCU) {
1483c153007bSAl Viro 		unsigned int seq = *seqp;
1484c153007bSAl Viro 		if (unlikely(!*inode))
1485c153007bSAl Viro 			return -ENOENT;
1486c153007bSAl Viro 		if (likely(__follow_mount_rcu(nd, path, inode, seqp)))
14879deed3ebSAl Viro 			return 0;
1488ae66db45SAl Viro 		if (!try_to_unlazy_next(nd, dentry, seq))
1489c153007bSAl Viro 			return -ECHILD;
1490c153007bSAl Viro 		// *path might've been clobbered by __follow_mount_rcu()
1491c153007bSAl Viro 		path->mnt = nd->path.mnt;
1492c153007bSAl Viro 		path->dentry = dentry;
1493c153007bSAl Viro 	}
14949deed3ebSAl Viro 	ret = traverse_mounts(path, &jumped, &nd->total_link_count, nd->flags);
14959deed3ebSAl Viro 	if (jumped) {
14969deed3ebSAl Viro 		if (unlikely(nd->flags & LOOKUP_NO_XDEV))
14979deed3ebSAl Viro 			ret = -EXDEV;
14989deed3ebSAl Viro 		else
1499bcba1e7dSAl Viro 			nd->state |= ND_JUMPED;
15009deed3ebSAl Viro 	}
15019deed3ebSAl Viro 	if (unlikely(ret)) {
15029deed3ebSAl Viro 		dput(path->dentry);
15039deed3ebSAl Viro 		if (path->mnt != nd->path.mnt)
15049deed3ebSAl Viro 			mntput(path->mnt);
15059deed3ebSAl Viro 	} else {
1506bd7c4b50SAl Viro 		*inode = d_backing_inode(path->dentry);
1507bd7c4b50SAl Viro 		*seqp = 0; /* out of RCU mode, so the value doesn't matter */
1508bd7c4b50SAl Viro 	}
1509bd7c4b50SAl Viro 	return ret;
1510bd7c4b50SAl Viro }
1511bd7c4b50SAl Viro 
15129875cf80SDavid Howells /*
1513f4fdace9SOleg Drokin  * This looks up the name in dcache and possibly revalidates the found dentry.
1514f4fdace9SOleg Drokin  * NULL is returned if the dentry does not exist in the cache.
1515baa03890SNick Piggin  */
1516e3c13928SAl Viro static struct dentry *lookup_dcache(const struct qstr *name,
1517e3c13928SAl Viro 				    struct dentry *dir,
15186c51e513SAl Viro 				    unsigned int flags)
1519baa03890SNick Piggin {
1520a89f8337SAl Viro 	struct dentry *dentry = d_lookup(dir, name);
1521bad61189SMiklos Szeredi 	if (dentry) {
1522a89f8337SAl Viro 		int error = d_revalidate(dentry, flags);
1523bad61189SMiklos Szeredi 		if (unlikely(error <= 0)) {
152474ff0ffcSAl Viro 			if (!error)
15255542aa2fSEric W. Biederman 				d_invalidate(dentry);
1526bad61189SMiklos Szeredi 			dput(dentry);
152774ff0ffcSAl Viro 			return ERR_PTR(error);
1528bad61189SMiklos Szeredi 		}
1529bad61189SMiklos Szeredi 	}
1530baa03890SNick Piggin 	return dentry;
1531baa03890SNick Piggin }
1532baa03890SNick Piggin 
1533baa03890SNick Piggin /*
1534a03ece5fSAl Viro  * Parent directory has inode locked exclusive.  This is one
1535a03ece5fSAl Viro  * and only case when ->lookup() gets called on non in-lookup
1536a03ece5fSAl Viro  * dentries - as the matter of fact, this only gets called
1537a03ece5fSAl Viro  * when directory is guaranteed to have no in-lookup children
1538a03ece5fSAl Viro  * at all.
153944396f4bSJosef Bacik  */
1540a03ece5fSAl Viro static struct dentry *__lookup_hash(const struct qstr *name,
1541a03ece5fSAl Viro 		struct dentry *base, unsigned int flags)
154244396f4bSJosef Bacik {
1543a03ece5fSAl Viro 	struct dentry *dentry = lookup_dcache(name, base, flags);
154444396f4bSJosef Bacik 	struct dentry *old;
1545a03ece5fSAl Viro 	struct inode *dir = base->d_inode;
1546a03ece5fSAl Viro 
1547a03ece5fSAl Viro 	if (dentry)
1548a03ece5fSAl Viro 		return dentry;
154944396f4bSJosef Bacik 
155044396f4bSJosef Bacik 	/* Don't create child dentry for a dead directory. */
1551a03ece5fSAl Viro 	if (unlikely(IS_DEADDIR(dir)))
155244396f4bSJosef Bacik 		return ERR_PTR(-ENOENT);
1553a03ece5fSAl Viro 
1554a03ece5fSAl Viro 	dentry = d_alloc(base, name);
1555a03ece5fSAl Viro 	if (unlikely(!dentry))
1556a03ece5fSAl Viro 		return ERR_PTR(-ENOMEM);
155744396f4bSJosef Bacik 
155872bd866aSAl Viro 	old = dir->i_op->lookup(dir, dentry, flags);
155944396f4bSJosef Bacik 	if (unlikely(old)) {
156044396f4bSJosef Bacik 		dput(dentry);
156144396f4bSJosef Bacik 		dentry = old;
156244396f4bSJosef Bacik 	}
156344396f4bSJosef Bacik 	return dentry;
156444396f4bSJosef Bacik }
156544396f4bSJosef Bacik 
156620e34357SAl Viro static struct dentry *lookup_fast(struct nameidata *nd,
156720e34357SAl Viro 				  struct inode **inode,
1568254cf582SAl Viro 			          unsigned *seqp)
15691da177e4SLinus Torvalds {
157031e6b01fSNick Piggin 	struct dentry *dentry, *parent = nd->path.dentry;
15715a18fff2SAl Viro 	int status = 1;
15729875cf80SDavid Howells 
15733cac260aSAl Viro 	/*
1574b04f784eSNick Piggin 	 * Rename seqlock is not required here because in the off chance
15755d0f49c1SAl Viro 	 * of a false negative due to a concurrent rename, the caller is
15765d0f49c1SAl Viro 	 * going to fall back to non-racy lookup.
1577b04f784eSNick Piggin 	 */
157831e6b01fSNick Piggin 	if (nd->flags & LOOKUP_RCU) {
157931e6b01fSNick Piggin 		unsigned seq;
1580da53be12SLinus Torvalds 		dentry = __d_lookup_rcu(parent, &nd->last, &seq);
15815d0f49c1SAl Viro 		if (unlikely(!dentry)) {
1582e36cffedSJens Axboe 			if (!try_to_unlazy(nd))
158320e34357SAl Viro 				return ERR_PTR(-ECHILD);
158420e34357SAl Viro 			return NULL;
15855d0f49c1SAl Viro 		}
15865a18fff2SAl Viro 
158712f8ad4bSLinus Torvalds 		/*
158812f8ad4bSLinus Torvalds 		 * This sequence count validates that the inode matches
158912f8ad4bSLinus Torvalds 		 * the dentry name information from lookup.
159012f8ad4bSLinus Torvalds 		 */
159163afdfc7SDavid Howells 		*inode = d_backing_inode(dentry);
15925d0f49c1SAl Viro 		if (unlikely(read_seqcount_retry(&dentry->d_seq, seq)))
159320e34357SAl Viro 			return ERR_PTR(-ECHILD);
159412f8ad4bSLinus Torvalds 
159512f8ad4bSLinus Torvalds 		/*
159612f8ad4bSLinus Torvalds 		 * This sequence count validates that the parent had no
159712f8ad4bSLinus Torvalds 		 * changes while we did the lookup of the dentry above.
159812f8ad4bSLinus Torvalds 		 *
159912f8ad4bSLinus Torvalds 		 * The memory barrier in read_seqcount_begin of child is
160012f8ad4bSLinus Torvalds 		 *  enough, we can use __read_seqcount_retry here.
160112f8ad4bSLinus Torvalds 		 */
16025d0f49c1SAl Viro 		if (unlikely(__read_seqcount_retry(&parent->d_seq, nd->seq)))
160320e34357SAl Viro 			return ERR_PTR(-ECHILD);
16045a18fff2SAl Viro 
1605254cf582SAl Viro 		*seqp = seq;
16064ce16ef3SAl Viro 		status = d_revalidate(dentry, nd->flags);
1607c153007bSAl Viro 		if (likely(status > 0))
160820e34357SAl Viro 			return dentry;
1609ae66db45SAl Viro 		if (!try_to_unlazy_next(nd, dentry, seq))
161020e34357SAl Viro 			return ERR_PTR(-ECHILD);
161126ddb45eSSteven Rostedt (VMware) 		if (status == -ECHILD)
1612209a7fb2SAl Viro 			/* we'd been told to redo it in non-rcu mode */
1613209a7fb2SAl Viro 			status = d_revalidate(dentry, nd->flags);
16145a18fff2SAl Viro 	} else {
1615e97cdc87SAl Viro 		dentry = __d_lookup(parent, &nd->last);
161681e6f520SAl Viro 		if (unlikely(!dentry))
161720e34357SAl Viro 			return NULL;
16184ce16ef3SAl Viro 		status = d_revalidate(dentry, nd->flags);
16195d0f49c1SAl Viro 	}
16205a18fff2SAl Viro 	if (unlikely(status <= 0)) {
1621e9742b53SAl Viro 		if (!status)
16225d0f49c1SAl Viro 			d_invalidate(dentry);
16235a18fff2SAl Viro 		dput(dentry);
162420e34357SAl Viro 		return ERR_PTR(status);
16255a18fff2SAl Viro 	}
162620e34357SAl Viro 	return dentry;
1627697f514dSMiklos Szeredi }
1628697f514dSMiklos Szeredi 
1629697f514dSMiklos Szeredi /* Fast lookup failed, do it the slow way */
163088d8331aSAl Viro static struct dentry *__lookup_slow(const struct qstr *name,
1631e3c13928SAl Viro 				    struct dentry *dir,
1632e3c13928SAl Viro 				    unsigned int flags)
1633697f514dSMiklos Szeredi {
163488d8331aSAl Viro 	struct dentry *dentry, *old;
16351936386eSAl Viro 	struct inode *inode = dir->d_inode;
1636d9171b93SAl Viro 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
16371936386eSAl Viro 
16381936386eSAl Viro 	/* Don't go there if it's already dead */
163994bdd655SAl Viro 	if (unlikely(IS_DEADDIR(inode)))
164088d8331aSAl Viro 		return ERR_PTR(-ENOENT);
164194bdd655SAl Viro again:
1642d9171b93SAl Viro 	dentry = d_alloc_parallel(dir, name, &wq);
164394bdd655SAl Viro 	if (IS_ERR(dentry))
164488d8331aSAl Viro 		return dentry;
164594bdd655SAl Viro 	if (unlikely(!d_in_lookup(dentry))) {
1646949a852eSAl Viro 		int error = d_revalidate(dentry, flags);
1647949a852eSAl Viro 		if (unlikely(error <= 0)) {
164894bdd655SAl Viro 			if (!error) {
1649949a852eSAl Viro 				d_invalidate(dentry);
1650949a852eSAl Viro 				dput(dentry);
165194bdd655SAl Viro 				goto again;
165294bdd655SAl Viro 			}
165394bdd655SAl Viro 			dput(dentry);
1654949a852eSAl Viro 			dentry = ERR_PTR(error);
1655949a852eSAl Viro 		}
165694bdd655SAl Viro 	} else {
16571936386eSAl Viro 		old = inode->i_op->lookup(inode, dentry, flags);
165885c7f810SAl Viro 		d_lookup_done(dentry);
16591936386eSAl Viro 		if (unlikely(old)) {
16601936386eSAl Viro 			dput(dentry);
16611936386eSAl Viro 			dentry = old;
1662949a852eSAl Viro 		}
1663949a852eSAl Viro 	}
1664e3c13928SAl Viro 	return dentry;
16651da177e4SLinus Torvalds }
16661da177e4SLinus Torvalds 
166788d8331aSAl Viro static struct dentry *lookup_slow(const struct qstr *name,
166888d8331aSAl Viro 				  struct dentry *dir,
166988d8331aSAl Viro 				  unsigned int flags)
167088d8331aSAl Viro {
167188d8331aSAl Viro 	struct inode *inode = dir->d_inode;
167288d8331aSAl Viro 	struct dentry *res;
167388d8331aSAl Viro 	inode_lock_shared(inode);
167488d8331aSAl Viro 	res = __lookup_slow(name, dir, flags);
167588d8331aSAl Viro 	inode_unlock_shared(inode);
167688d8331aSAl Viro 	return res;
167788d8331aSAl Viro }
167888d8331aSAl Viro 
1679ba73d987SChristian Brauner static inline int may_lookup(struct user_namespace *mnt_userns,
1680ba73d987SChristian Brauner 			     struct nameidata *nd)
168152094c8aSAl Viro {
168252094c8aSAl Viro 	if (nd->flags & LOOKUP_RCU) {
16837d6beb71SLinus Torvalds 		int err = inode_permission(mnt_userns, nd->inode, MAY_EXEC|MAY_NOT_BLOCK);
1684e36cffedSJens Axboe 		if (err != -ECHILD || !try_to_unlazy(nd))
168552094c8aSAl Viro 			return err;
168652094c8aSAl Viro 	}
1687ba73d987SChristian Brauner 	return inode_permission(mnt_userns, nd->inode, MAY_EXEC);
168852094c8aSAl Viro }
168952094c8aSAl Viro 
169049055906SAl Viro static int reserve_stack(struct nameidata *nd, struct path *link, unsigned seq)
1691d63ff28fSAl Viro {
169249055906SAl Viro 	if (unlikely(nd->total_link_count++ >= MAXSYMLINKS))
169349055906SAl Viro 		return -ELOOP;
16944542576bSAl Viro 
16954542576bSAl Viro 	if (likely(nd->depth != EMBEDDED_LEVELS))
16964542576bSAl Viro 		return 0;
16974542576bSAl Viro 	if (likely(nd->stack != nd->internal))
16984542576bSAl Viro 		return 0;
169960ef60c7SAl Viro 	if (likely(nd_alloc_stack(nd)))
170049055906SAl Viro 		return 0;
170160ef60c7SAl Viro 
170260ef60c7SAl Viro 	if (nd->flags & LOOKUP_RCU) {
170360ef60c7SAl Viro 		// we need to grab link before we do unlazy.  And we can't skip
170460ef60c7SAl Viro 		// unlazy even if we fail to grab the link - cleanup needs it
1705aef9404dSAl Viro 		bool grabbed_link = legitimize_path(nd, link, seq);
170660ef60c7SAl Viro 
1707e36cffedSJens Axboe 		if (!try_to_unlazy(nd) != 0 || !grabbed_link)
170860ef60c7SAl Viro 			return -ECHILD;
170960ef60c7SAl Viro 
171060ef60c7SAl Viro 		if (nd_alloc_stack(nd))
171160ef60c7SAl Viro 			return 0;
1712bc40aee0SAl Viro 	}
171360ef60c7SAl Viro 	return -ENOMEM;
171449055906SAl Viro }
171549055906SAl Viro 
171649055906SAl Viro enum {WALK_TRAILING = 1, WALK_MORE = 2, WALK_NOFOLLOW = 4};
171749055906SAl Viro 
171849055906SAl Viro static const char *pick_link(struct nameidata *nd, struct path *link,
171949055906SAl Viro 		     struct inode *inode, unsigned seq, int flags)
172049055906SAl Viro {
172149055906SAl Viro 	struct saved *last;
172249055906SAl Viro 	const char *res;
172349055906SAl Viro 	int error = reserve_stack(nd, link, seq);
172449055906SAl Viro 
172549055906SAl Viro 	if (unlikely(error)) {
172649055906SAl Viro 		if (!(nd->flags & LOOKUP_RCU))
1727cd179f44SAl Viro 			path_put(link);
172806708adbSAl Viro 		return ERR_PTR(error);
1729626de996SAl Viro 	}
1730ab104923SAl Viro 	last = nd->stack + nd->depth++;
17311cf2665bSAl Viro 	last->link = *link;
1732fceef393SAl Viro 	clear_delayed_call(&last->done);
17330450b2d1SAl Viro 	last->seq = seq;
1734ad6cc4c3SAl Viro 
1735b1a81972SAl Viro 	if (flags & WALK_TRAILING) {
1736ad6cc4c3SAl Viro 		error = may_follow_link(nd, inode);
1737ad6cc4c3SAl Viro 		if (unlikely(error))
1738ad6cc4c3SAl Viro 			return ERR_PTR(error);
1739ad6cc4c3SAl Viro 	}
1740ad6cc4c3SAl Viro 
1741dab741e0SMattias Nissler 	if (unlikely(nd->flags & LOOKUP_NO_SYMLINKS) ||
1742dab741e0SMattias Nissler 			unlikely(link->mnt->mnt_flags & MNT_NOSYMFOLLOW))
1743ad6cc4c3SAl Viro 		return ERR_PTR(-ELOOP);
1744ad6cc4c3SAl Viro 
1745ad6cc4c3SAl Viro 	if (!(nd->flags & LOOKUP_RCU)) {
1746ad6cc4c3SAl Viro 		touch_atime(&last->link);
1747ad6cc4c3SAl Viro 		cond_resched();
1748ad6cc4c3SAl Viro 	} else if (atime_needs_update(&last->link, inode)) {
1749e36cffedSJens Axboe 		if (!try_to_unlazy(nd))
1750ad6cc4c3SAl Viro 			return ERR_PTR(-ECHILD);
1751ad6cc4c3SAl Viro 		touch_atime(&last->link);
1752ad6cc4c3SAl Viro 	}
1753ad6cc4c3SAl Viro 
1754ad6cc4c3SAl Viro 	error = security_inode_follow_link(link->dentry, inode,
1755ad6cc4c3SAl Viro 					   nd->flags & LOOKUP_RCU);
1756ad6cc4c3SAl Viro 	if (unlikely(error))
1757ad6cc4c3SAl Viro 		return ERR_PTR(error);
1758ad6cc4c3SAl Viro 
1759ad6cc4c3SAl Viro 	res = READ_ONCE(inode->i_link);
1760ad6cc4c3SAl Viro 	if (!res) {
1761ad6cc4c3SAl Viro 		const char * (*get)(struct dentry *, struct inode *,
1762ad6cc4c3SAl Viro 				struct delayed_call *);
1763ad6cc4c3SAl Viro 		get = inode->i_op->get_link;
1764ad6cc4c3SAl Viro 		if (nd->flags & LOOKUP_RCU) {
1765ad6cc4c3SAl Viro 			res = get(NULL, inode, &last->done);
1766e36cffedSJens Axboe 			if (res == ERR_PTR(-ECHILD) && try_to_unlazy(nd))
1767ad6cc4c3SAl Viro 				res = get(link->dentry, inode, &last->done);
1768ad6cc4c3SAl Viro 		} else {
1769ad6cc4c3SAl Viro 			res = get(link->dentry, inode, &last->done);
1770ad6cc4c3SAl Viro 		}
1771ad6cc4c3SAl Viro 		if (!res)
1772ad6cc4c3SAl Viro 			goto all_done;
1773ad6cc4c3SAl Viro 		if (IS_ERR(res))
1774ad6cc4c3SAl Viro 			return res;
1775ad6cc4c3SAl Viro 	}
1776ad6cc4c3SAl Viro 	if (*res == '/') {
1777ad6cc4c3SAl Viro 		error = nd_jump_root(nd);
1778ad6cc4c3SAl Viro 		if (unlikely(error))
1779ad6cc4c3SAl Viro 			return ERR_PTR(error);
1780ad6cc4c3SAl Viro 		while (unlikely(*++res == '/'))
1781ad6cc4c3SAl Viro 			;
1782ad6cc4c3SAl Viro 	}
1783ad6cc4c3SAl Viro 	if (*res)
1784ad6cc4c3SAl Viro 		return res;
1785ad6cc4c3SAl Viro all_done: // pure jump
1786ad6cc4c3SAl Viro 	put_link(nd);
1787ad6cc4c3SAl Viro 	return NULL;
1788d63ff28fSAl Viro }
1789d63ff28fSAl Viro 
17903ddcd056SLinus Torvalds /*
17913ddcd056SLinus Torvalds  * Do we need to follow links? We _really_ want to be able
17923ddcd056SLinus Torvalds  * to do this check without having to look at inode->i_op,
17933ddcd056SLinus Torvalds  * so we keep a cache of "no, this doesn't need follow_link"
17943ddcd056SLinus Torvalds  * for the common case.
17953ddcd056SLinus Torvalds  */
1796b0417d2cSAl Viro static const char *step_into(struct nameidata *nd, int flags,
1797cbae4d12SAl Viro 		     struct dentry *dentry, struct inode *inode, unsigned seq)
17983ddcd056SLinus Torvalds {
1799cbae4d12SAl Viro 	struct path path;
1800cbae4d12SAl Viro 	int err = handle_mounts(nd, dentry, &path, &inode, &seq);
1801cbae4d12SAl Viro 
1802cbae4d12SAl Viro 	if (err < 0)
1803b0417d2cSAl Viro 		return ERR_PTR(err);
1804cbae4d12SAl Viro 	if (likely(!d_is_symlink(path.dentry)) ||
18058c4efe22SAl Viro 	   ((flags & WALK_TRAILING) && !(nd->flags & LOOKUP_FOLLOW)) ||
1806aca2903eSAl Viro 	   (flags & WALK_NOFOLLOW)) {
18078f64fb1cSAl Viro 		/* not a symlink or should not follow */
1808c99687a0SAl Viro 		if (!(nd->flags & LOOKUP_RCU)) {
1809c99687a0SAl Viro 			dput(nd->path.dentry);
1810c99687a0SAl Viro 			if (nd->path.mnt != path.mnt)
1811c99687a0SAl Viro 				mntput(nd->path.mnt);
1812c99687a0SAl Viro 		}
1813c99687a0SAl Viro 		nd->path = path;
18148f64fb1cSAl Viro 		nd->inode = inode;
18158f64fb1cSAl Viro 		nd->seq = seq;
1816b0417d2cSAl Viro 		return NULL;
18178f64fb1cSAl Viro 	}
1818a7f77542SAl Viro 	if (nd->flags & LOOKUP_RCU) {
181984f0cd9eSAl Viro 		/* make sure that d_is_symlink above matches inode */
1820cbae4d12SAl Viro 		if (read_seqcount_retry(&path.dentry->d_seq, seq))
1821b0417d2cSAl Viro 			return ERR_PTR(-ECHILD);
182284f0cd9eSAl Viro 	} else {
182384f0cd9eSAl Viro 		if (path.mnt == nd->path.mnt)
182484f0cd9eSAl Viro 			mntget(path.mnt);
1825a7f77542SAl Viro 	}
1826b1a81972SAl Viro 	return pick_link(nd, &path, inode, seq, flags);
18273ddcd056SLinus Torvalds }
18283ddcd056SLinus Torvalds 
1829c2df1968SAl Viro static struct dentry *follow_dotdot_rcu(struct nameidata *nd,
1830c2df1968SAl Viro 					struct inode **inodep,
1831c2df1968SAl Viro 					unsigned *seqp)
1832957dd41dSAl Viro {
183312487f30SAl Viro 	struct dentry *parent, *old;
1834957dd41dSAl Viro 
183512487f30SAl Viro 	if (path_equal(&nd->path, &nd->root))
183612487f30SAl Viro 		goto in_root;
183712487f30SAl Viro 	if (unlikely(nd->path.dentry == nd->path.mnt->mnt_root)) {
18387ef482faSAl Viro 		struct path path;
1839efe772d6SAl Viro 		unsigned seq;
18407ef482faSAl Viro 		if (!choose_mountpoint_rcu(real_mount(nd->path.mnt),
18417ef482faSAl Viro 					   &nd->root, &path, &seq))
184212487f30SAl Viro 			goto in_root;
1843efe772d6SAl Viro 		if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1844efe772d6SAl Viro 			return ERR_PTR(-ECHILD);
1845efe772d6SAl Viro 		nd->path = path;
1846efe772d6SAl Viro 		nd->inode = path.dentry->d_inode;
1847efe772d6SAl Viro 		nd->seq = seq;
1848efe772d6SAl Viro 		if (unlikely(read_seqretry(&mount_lock, nd->m_seq)))
1849efe772d6SAl Viro 			return ERR_PTR(-ECHILD);
1850efe772d6SAl Viro 		/* we know that mountpoint was pinned */
1851957dd41dSAl Viro 	}
185212487f30SAl Viro 	old = nd->path.dentry;
185312487f30SAl Viro 	parent = old->d_parent;
185412487f30SAl Viro 	*inodep = parent->d_inode;
185512487f30SAl Viro 	*seqp = read_seqcount_begin(&parent->d_seq);
185612487f30SAl Viro 	if (unlikely(read_seqcount_retry(&old->d_seq, nd->seq)))
185712487f30SAl Viro 		return ERR_PTR(-ECHILD);
185812487f30SAl Viro 	if (unlikely(!path_connected(nd->path.mnt, parent)))
185912487f30SAl Viro 		return ERR_PTR(-ECHILD);
186012487f30SAl Viro 	return parent;
186112487f30SAl Viro in_root:
1862efe772d6SAl Viro 	if (unlikely(read_seqretry(&mount_lock, nd->m_seq)))
1863efe772d6SAl Viro 		return ERR_PTR(-ECHILD);
1864957dd41dSAl Viro 	if (unlikely(nd->flags & LOOKUP_BENEATH))
18657521f22bSAl Viro 		return ERR_PTR(-ECHILD);
1866c2df1968SAl Viro 	return NULL;
1867957dd41dSAl Viro }
1868957dd41dSAl Viro 
1869c2df1968SAl Viro static struct dentry *follow_dotdot(struct nameidata *nd,
1870c2df1968SAl Viro 				 struct inode **inodep,
1871c2df1968SAl Viro 				 unsigned *seqp)
1872957dd41dSAl Viro {
187312487f30SAl Viro 	struct dentry *parent;
187412487f30SAl Viro 
1875957dd41dSAl Viro 	if (path_equal(&nd->path, &nd->root))
187612487f30SAl Viro 		goto in_root;
187712487f30SAl Viro 	if (unlikely(nd->path.dentry == nd->path.mnt->mnt_root)) {
18782aa38470SAl Viro 		struct path path;
18792aa38470SAl Viro 
18802aa38470SAl Viro 		if (!choose_mountpoint(real_mount(nd->path.mnt),
18812aa38470SAl Viro 				       &nd->root, &path))
188212487f30SAl Viro 			goto in_root;
1883165200d6SAl Viro 		path_put(&nd->path);
1884165200d6SAl Viro 		nd->path = path;
18852aa38470SAl Viro 		nd->inode = path.dentry->d_inode;
1886165200d6SAl Viro 		if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1887165200d6SAl Viro 			return ERR_PTR(-EXDEV);
188812487f30SAl Viro 	}
1889957dd41dSAl Viro 	/* rare case of legitimate dget_parent()... */
189012487f30SAl Viro 	parent = dget_parent(nd->path.dentry);
1891957dd41dSAl Viro 	if (unlikely(!path_connected(nd->path.mnt, parent))) {
1892957dd41dSAl Viro 		dput(parent);
18937521f22bSAl Viro 		return ERR_PTR(-ENOENT);
1894957dd41dSAl Viro 	}
1895c2df1968SAl Viro 	*seqp = 0;
1896c2df1968SAl Viro 	*inodep = parent->d_inode;
1897c2df1968SAl Viro 	return parent;
189812487f30SAl Viro 
189912487f30SAl Viro in_root:
1900957dd41dSAl Viro 	if (unlikely(nd->flags & LOOKUP_BENEATH))
19017521f22bSAl Viro 		return ERR_PTR(-EXDEV);
1902c2df1968SAl Viro 	dget(nd->path.dentry);
1903c2df1968SAl Viro 	return NULL;
1904957dd41dSAl Viro }
1905957dd41dSAl Viro 
19067521f22bSAl Viro static const char *handle_dots(struct nameidata *nd, int type)
1907957dd41dSAl Viro {
1908957dd41dSAl Viro 	if (type == LAST_DOTDOT) {
19097521f22bSAl Viro 		const char *error = NULL;
1910c2df1968SAl Viro 		struct dentry *parent;
1911c2df1968SAl Viro 		struct inode *inode;
1912c2df1968SAl Viro 		unsigned seq;
1913957dd41dSAl Viro 
1914957dd41dSAl Viro 		if (!nd->root.mnt) {
19157521f22bSAl Viro 			error = ERR_PTR(set_root(nd));
1916957dd41dSAl Viro 			if (error)
1917957dd41dSAl Viro 				return error;
1918957dd41dSAl Viro 		}
1919957dd41dSAl Viro 		if (nd->flags & LOOKUP_RCU)
1920c2df1968SAl Viro 			parent = follow_dotdot_rcu(nd, &inode, &seq);
1921957dd41dSAl Viro 		else
1922c2df1968SAl Viro 			parent = follow_dotdot(nd, &inode, &seq);
1923c2df1968SAl Viro 		if (IS_ERR(parent))
1924c2df1968SAl Viro 			return ERR_CAST(parent);
1925c2df1968SAl Viro 		if (unlikely(!parent))
1926c2df1968SAl Viro 			error = step_into(nd, WALK_NOFOLLOW,
1927c2df1968SAl Viro 					 nd->path.dentry, nd->inode, nd->seq);
1928c2df1968SAl Viro 		else
1929c2df1968SAl Viro 			error = step_into(nd, WALK_NOFOLLOW,
1930c2df1968SAl Viro 					 parent, inode, seq);
1931c2df1968SAl Viro 		if (unlikely(error))
1932957dd41dSAl Viro 			return error;
1933957dd41dSAl Viro 
1934957dd41dSAl Viro 		if (unlikely(nd->flags & LOOKUP_IS_SCOPED)) {
1935957dd41dSAl Viro 			/*
1936957dd41dSAl Viro 			 * If there was a racing rename or mount along our
1937957dd41dSAl Viro 			 * path, then we can't be sure that ".." hasn't jumped
1938957dd41dSAl Viro 			 * above nd->root (and so userspace should retry or use
1939957dd41dSAl Viro 			 * some fallback).
1940957dd41dSAl Viro 			 */
1941957dd41dSAl Viro 			smp_rmb();
1942957dd41dSAl Viro 			if (unlikely(__read_seqcount_retry(&mount_lock.seqcount, nd->m_seq)))
19437521f22bSAl Viro 				return ERR_PTR(-EAGAIN);
1944957dd41dSAl Viro 			if (unlikely(__read_seqcount_retry(&rename_lock.seqcount, nd->r_seq)))
19457521f22bSAl Viro 				return ERR_PTR(-EAGAIN);
1946957dd41dSAl Viro 		}
1947957dd41dSAl Viro 	}
19487521f22bSAl Viro 	return NULL;
1949957dd41dSAl Viro }
1950957dd41dSAl Viro 
195192d27016SAl Viro static const char *walk_component(struct nameidata *nd, int flags)
1952ce57dfc1SAl Viro {
1953db3c9adeSAl Viro 	struct dentry *dentry;
1954ce57dfc1SAl Viro 	struct inode *inode;
1955254cf582SAl Viro 	unsigned seq;
1956ce57dfc1SAl Viro 	/*
1957ce57dfc1SAl Viro 	 * "." and ".." are special - ".." especially so because it has
1958ce57dfc1SAl Viro 	 * to be able to know about the current root directory and
1959ce57dfc1SAl Viro 	 * parent relationships.
1960ce57dfc1SAl Viro 	 */
19614693a547SAl Viro 	if (unlikely(nd->last_type != LAST_NORM)) {
19621c4ff1a8SAl Viro 		if (!(flags & WALK_MORE) && nd->depth)
19634693a547SAl Viro 			put_link(nd);
19647521f22bSAl Viro 		return handle_dots(nd, nd->last_type);
19654693a547SAl Viro 	}
196620e34357SAl Viro 	dentry = lookup_fast(nd, &inode, &seq);
196720e34357SAl Viro 	if (IS_ERR(dentry))
196892d27016SAl Viro 		return ERR_CAST(dentry);
196920e34357SAl Viro 	if (unlikely(!dentry)) {
1970db3c9adeSAl Viro 		dentry = lookup_slow(&nd->last, nd->path.dentry, nd->flags);
1971db3c9adeSAl Viro 		if (IS_ERR(dentry))
197292d27016SAl Viro 			return ERR_CAST(dentry);
197320e34357SAl Viro 	}
197456676ec3SAl Viro 	if (!(flags & WALK_MORE) && nd->depth)
197556676ec3SAl Viro 		put_link(nd);
1976b0417d2cSAl Viro 	return step_into(nd, flags, dentry, inode, seq);
1977ce57dfc1SAl Viro }
1978ce57dfc1SAl Viro 
19791da177e4SLinus Torvalds /*
1980bfcfaa77SLinus Torvalds  * We can do the critical dentry name comparison and hashing
1981bfcfaa77SLinus Torvalds  * operations one word at a time, but we are limited to:
1982bfcfaa77SLinus Torvalds  *
1983bfcfaa77SLinus Torvalds  * - Architectures with fast unaligned word accesses. We could
1984bfcfaa77SLinus Torvalds  *   do a "get_unaligned()" if this helps and is sufficiently
1985bfcfaa77SLinus Torvalds  *   fast.
1986bfcfaa77SLinus Torvalds  *
1987bfcfaa77SLinus Torvalds  * - non-CONFIG_DEBUG_PAGEALLOC configurations (so that we
1988bfcfaa77SLinus Torvalds  *   do not trap on the (extremely unlikely) case of a page
1989bfcfaa77SLinus Torvalds  *   crossing operation.
1990bfcfaa77SLinus Torvalds  *
1991bfcfaa77SLinus Torvalds  * - Furthermore, we need an efficient 64-bit compile for the
1992bfcfaa77SLinus Torvalds  *   64-bit case in order to generate the "number of bytes in
1993bfcfaa77SLinus Torvalds  *   the final mask". Again, that could be replaced with a
1994bfcfaa77SLinus Torvalds  *   efficient population count instruction or similar.
1995bfcfaa77SLinus Torvalds  */
1996bfcfaa77SLinus Torvalds #ifdef CONFIG_DCACHE_WORD_ACCESS
1997bfcfaa77SLinus Torvalds 
1998f68e556eSLinus Torvalds #include <asm/word-at-a-time.h>
1999bfcfaa77SLinus Torvalds 
2000468a9428SGeorge Spelvin #ifdef HASH_MIX
2001bfcfaa77SLinus Torvalds 
2002468a9428SGeorge Spelvin /* Architecture provides HASH_MIX and fold_hash() in <asm/hash.h> */
2003468a9428SGeorge Spelvin 
2004468a9428SGeorge Spelvin #elif defined(CONFIG_64BIT)
20052a18da7aSGeorge Spelvin /*
20062a18da7aSGeorge Spelvin  * Register pressure in the mixing function is an issue, particularly
20072a18da7aSGeorge Spelvin  * on 32-bit x86, but almost any function requires one state value and
20082a18da7aSGeorge Spelvin  * one temporary.  Instead, use a function designed for two state values
20092a18da7aSGeorge Spelvin  * and no temporaries.
20102a18da7aSGeorge Spelvin  *
20112a18da7aSGeorge Spelvin  * This function cannot create a collision in only two iterations, so
20122a18da7aSGeorge Spelvin  * we have two iterations to achieve avalanche.  In those two iterations,
20132a18da7aSGeorge Spelvin  * we have six layers of mixing, which is enough to spread one bit's
20142a18da7aSGeorge Spelvin  * influence out to 2^6 = 64 state bits.
20152a18da7aSGeorge Spelvin  *
20162a18da7aSGeorge Spelvin  * Rotate constants are scored by considering either 64 one-bit input
20172a18da7aSGeorge Spelvin  * deltas or 64*63/2 = 2016 two-bit input deltas, and finding the
20182a18da7aSGeorge Spelvin  * probability of that delta causing a change to each of the 128 output
20192a18da7aSGeorge Spelvin  * bits, using a sample of random initial states.
20202a18da7aSGeorge Spelvin  *
20212a18da7aSGeorge Spelvin  * The Shannon entropy of the computed probabilities is then summed
20222a18da7aSGeorge Spelvin  * to produce a score.  Ideally, any input change has a 50% chance of
20232a18da7aSGeorge Spelvin  * toggling any given output bit.
20242a18da7aSGeorge Spelvin  *
20252a18da7aSGeorge Spelvin  * Mixing scores (in bits) for (12,45):
20262a18da7aSGeorge Spelvin  * Input delta: 1-bit      2-bit
20272a18da7aSGeorge Spelvin  * 1 round:     713.3    42542.6
20282a18da7aSGeorge Spelvin  * 2 rounds:   2753.7   140389.8
20292a18da7aSGeorge Spelvin  * 3 rounds:   5954.1   233458.2
20302a18da7aSGeorge Spelvin  * 4 rounds:   7862.6   256672.2
20312a18da7aSGeorge Spelvin  * Perfect:    8192     258048
20322a18da7aSGeorge Spelvin  *            (64*128) (64*63/2 * 128)
20332a18da7aSGeorge Spelvin  */
20342a18da7aSGeorge Spelvin #define HASH_MIX(x, y, a)	\
20352a18da7aSGeorge Spelvin 	(	x ^= (a),	\
20362a18da7aSGeorge Spelvin 	y ^= x,	x = rol64(x,12),\
20372a18da7aSGeorge Spelvin 	x += y,	y = rol64(y,45),\
20382a18da7aSGeorge Spelvin 	y *= 9			)
2039bfcfaa77SLinus Torvalds 
20400fed3ac8SGeorge Spelvin /*
20412a18da7aSGeorge Spelvin  * Fold two longs into one 32-bit hash value.  This must be fast, but
20422a18da7aSGeorge Spelvin  * latency isn't quite as critical, as there is a fair bit of additional
20432a18da7aSGeorge Spelvin  * work done before the hash value is used.
20440fed3ac8SGeorge Spelvin  */
20452a18da7aSGeorge Spelvin static inline unsigned int fold_hash(unsigned long x, unsigned long y)
20460fed3ac8SGeorge Spelvin {
20472a18da7aSGeorge Spelvin 	y ^= x * GOLDEN_RATIO_64;
20482a18da7aSGeorge Spelvin 	y *= GOLDEN_RATIO_64;
20492a18da7aSGeorge Spelvin 	return y >> 32;
20500fed3ac8SGeorge Spelvin }
20510fed3ac8SGeorge Spelvin 
2052bfcfaa77SLinus Torvalds #else	/* 32-bit case */
2053bfcfaa77SLinus Torvalds 
20542a18da7aSGeorge Spelvin /*
20552a18da7aSGeorge Spelvin  * Mixing scores (in bits) for (7,20):
20562a18da7aSGeorge Spelvin  * Input delta: 1-bit      2-bit
20572a18da7aSGeorge Spelvin  * 1 round:     330.3     9201.6
20582a18da7aSGeorge Spelvin  * 2 rounds:   1246.4    25475.4
20592a18da7aSGeorge Spelvin  * 3 rounds:   1907.1    31295.1
20602a18da7aSGeorge Spelvin  * 4 rounds:   2042.3    31718.6
20612a18da7aSGeorge Spelvin  * Perfect:    2048      31744
20622a18da7aSGeorge Spelvin  *            (32*64)   (32*31/2 * 64)
20632a18da7aSGeorge Spelvin  */
20642a18da7aSGeorge Spelvin #define HASH_MIX(x, y, a)	\
20652a18da7aSGeorge Spelvin 	(	x ^= (a),	\
20662a18da7aSGeorge Spelvin 	y ^= x,	x = rol32(x, 7),\
20672a18da7aSGeorge Spelvin 	x += y,	y = rol32(y,20),\
20682a18da7aSGeorge Spelvin 	y *= 9			)
2069bfcfaa77SLinus Torvalds 
20702a18da7aSGeorge Spelvin static inline unsigned int fold_hash(unsigned long x, unsigned long y)
20710fed3ac8SGeorge Spelvin {
20722a18da7aSGeorge Spelvin 	/* Use arch-optimized multiply if one exists */
20732a18da7aSGeorge Spelvin 	return __hash_32(y ^ __hash_32(x));
20740fed3ac8SGeorge Spelvin }
20750fed3ac8SGeorge Spelvin 
2076bfcfaa77SLinus Torvalds #endif
2077bfcfaa77SLinus Torvalds 
20782a18da7aSGeorge Spelvin /*
20792a18da7aSGeorge Spelvin  * Return the hash of a string of known length.  This is carfully
20802a18da7aSGeorge Spelvin  * designed to match hash_name(), which is the more critical function.
20812a18da7aSGeorge Spelvin  * In particular, we must end by hashing a final word containing 0..7
20822a18da7aSGeorge Spelvin  * payload bytes, to match the way that hash_name() iterates until it
20832a18da7aSGeorge Spelvin  * finds the delimiter after the name.
20842a18da7aSGeorge Spelvin  */
20858387ff25SLinus Torvalds unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
2086bfcfaa77SLinus Torvalds {
20878387ff25SLinus Torvalds 	unsigned long a, x = 0, y = (unsigned long)salt;
2088bfcfaa77SLinus Torvalds 
2089bfcfaa77SLinus Torvalds 	for (;;) {
2090fcfd2fbfSGeorge Spelvin 		if (!len)
2091fcfd2fbfSGeorge Spelvin 			goto done;
2092e419b4ccSLinus Torvalds 		a = load_unaligned_zeropad(name);
2093bfcfaa77SLinus Torvalds 		if (len < sizeof(unsigned long))
2094bfcfaa77SLinus Torvalds 			break;
20952a18da7aSGeorge Spelvin 		HASH_MIX(x, y, a);
2096bfcfaa77SLinus Torvalds 		name += sizeof(unsigned long);
2097bfcfaa77SLinus Torvalds 		len -= sizeof(unsigned long);
2098bfcfaa77SLinus Torvalds 	}
20992a18da7aSGeorge Spelvin 	x ^= a & bytemask_from_count(len);
2100bfcfaa77SLinus Torvalds done:
21012a18da7aSGeorge Spelvin 	return fold_hash(x, y);
2102bfcfaa77SLinus Torvalds }
2103bfcfaa77SLinus Torvalds EXPORT_SYMBOL(full_name_hash);
2104bfcfaa77SLinus Torvalds 
2105fcfd2fbfSGeorge Spelvin /* Return the "hash_len" (hash and length) of a null-terminated string */
21068387ff25SLinus Torvalds u64 hashlen_string(const void *salt, const char *name)
2107fcfd2fbfSGeorge Spelvin {
21088387ff25SLinus Torvalds 	unsigned long a = 0, x = 0, y = (unsigned long)salt;
21098387ff25SLinus Torvalds 	unsigned long adata, mask, len;
2110fcfd2fbfSGeorge Spelvin 	const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2111fcfd2fbfSGeorge Spelvin 
21128387ff25SLinus Torvalds 	len = 0;
21138387ff25SLinus Torvalds 	goto inside;
21148387ff25SLinus Torvalds 
2115fcfd2fbfSGeorge Spelvin 	do {
21162a18da7aSGeorge Spelvin 		HASH_MIX(x, y, a);
2117fcfd2fbfSGeorge Spelvin 		len += sizeof(unsigned long);
21188387ff25SLinus Torvalds inside:
2119fcfd2fbfSGeorge Spelvin 		a = load_unaligned_zeropad(name+len);
2120fcfd2fbfSGeorge Spelvin 	} while (!has_zero(a, &adata, &constants));
2121fcfd2fbfSGeorge Spelvin 
2122fcfd2fbfSGeorge Spelvin 	adata = prep_zero_mask(a, adata, &constants);
2123fcfd2fbfSGeorge Spelvin 	mask = create_zero_mask(adata);
21242a18da7aSGeorge Spelvin 	x ^= a & zero_bytemask(mask);
2125fcfd2fbfSGeorge Spelvin 
21262a18da7aSGeorge Spelvin 	return hashlen_create(fold_hash(x, y), len + find_zero(mask));
2127fcfd2fbfSGeorge Spelvin }
2128fcfd2fbfSGeorge Spelvin EXPORT_SYMBOL(hashlen_string);
2129fcfd2fbfSGeorge Spelvin 
2130bfcfaa77SLinus Torvalds /*
2131bfcfaa77SLinus Torvalds  * Calculate the length and hash of the path component, and
2132d6bb3e90SLinus Torvalds  * return the "hash_len" as the result.
2133bfcfaa77SLinus Torvalds  */
21348387ff25SLinus Torvalds static inline u64 hash_name(const void *salt, const char *name)
2135bfcfaa77SLinus Torvalds {
21368387ff25SLinus Torvalds 	unsigned long a = 0, b, x = 0, y = (unsigned long)salt;
21378387ff25SLinus Torvalds 	unsigned long adata, bdata, mask, len;
213836126f8fSLinus Torvalds 	const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2139bfcfaa77SLinus Torvalds 
21408387ff25SLinus Torvalds 	len = 0;
21418387ff25SLinus Torvalds 	goto inside;
21428387ff25SLinus Torvalds 
2143bfcfaa77SLinus Torvalds 	do {
21442a18da7aSGeorge Spelvin 		HASH_MIX(x, y, a);
2145bfcfaa77SLinus Torvalds 		len += sizeof(unsigned long);
21468387ff25SLinus Torvalds inside:
2147e419b4ccSLinus Torvalds 		a = load_unaligned_zeropad(name+len);
214836126f8fSLinus Torvalds 		b = a ^ REPEAT_BYTE('/');
214936126f8fSLinus Torvalds 	} while (!(has_zero(a, &adata, &constants) | has_zero(b, &bdata, &constants)));
2150bfcfaa77SLinus Torvalds 
215136126f8fSLinus Torvalds 	adata = prep_zero_mask(a, adata, &constants);
215236126f8fSLinus Torvalds 	bdata = prep_zero_mask(b, bdata, &constants);
215336126f8fSLinus Torvalds 	mask = create_zero_mask(adata | bdata);
21542a18da7aSGeorge Spelvin 	x ^= a & zero_bytemask(mask);
215536126f8fSLinus Torvalds 
21562a18da7aSGeorge Spelvin 	return hashlen_create(fold_hash(x, y), len + find_zero(mask));
2157bfcfaa77SLinus Torvalds }
2158bfcfaa77SLinus Torvalds 
21592a18da7aSGeorge Spelvin #else	/* !CONFIG_DCACHE_WORD_ACCESS: Slow, byte-at-a-time version */
2160bfcfaa77SLinus Torvalds 
2161fcfd2fbfSGeorge Spelvin /* Return the hash of a string of known length */
21628387ff25SLinus Torvalds unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
21630145acc2SLinus Torvalds {
21648387ff25SLinus Torvalds 	unsigned long hash = init_name_hash(salt);
21650145acc2SLinus Torvalds 	while (len--)
2166fcfd2fbfSGeorge Spelvin 		hash = partial_name_hash((unsigned char)*name++, hash);
21670145acc2SLinus Torvalds 	return end_name_hash(hash);
21680145acc2SLinus Torvalds }
2169ae942ae7SLinus Torvalds EXPORT_SYMBOL(full_name_hash);
21700145acc2SLinus Torvalds 
2171fcfd2fbfSGeorge Spelvin /* Return the "hash_len" (hash and length) of a null-terminated string */
21728387ff25SLinus Torvalds u64 hashlen_string(const void *salt, const char *name)
2173fcfd2fbfSGeorge Spelvin {
21748387ff25SLinus Torvalds 	unsigned long hash = init_name_hash(salt);
2175fcfd2fbfSGeorge Spelvin 	unsigned long len = 0, c;
2176fcfd2fbfSGeorge Spelvin 
2177fcfd2fbfSGeorge Spelvin 	c = (unsigned char)*name;
2178e0ab7af9SGeorge Spelvin 	while (c) {
2179fcfd2fbfSGeorge Spelvin 		len++;
2180fcfd2fbfSGeorge Spelvin 		hash = partial_name_hash(c, hash);
2181fcfd2fbfSGeorge Spelvin 		c = (unsigned char)name[len];
2182e0ab7af9SGeorge Spelvin 	}
2183fcfd2fbfSGeorge Spelvin 	return hashlen_create(end_name_hash(hash), len);
2184fcfd2fbfSGeorge Spelvin }
2185f2a031b6SGeorge Spelvin EXPORT_SYMBOL(hashlen_string);
2186fcfd2fbfSGeorge Spelvin 
21873ddcd056SLinus Torvalds /*
2188200e9ef7SLinus Torvalds  * We know there's a real path component here of at least
2189200e9ef7SLinus Torvalds  * one character.
2190200e9ef7SLinus Torvalds  */
21918387ff25SLinus Torvalds static inline u64 hash_name(const void *salt, const char *name)
2192200e9ef7SLinus Torvalds {
21938387ff25SLinus Torvalds 	unsigned long hash = init_name_hash(salt);
2194200e9ef7SLinus Torvalds 	unsigned long len = 0, c;
2195200e9ef7SLinus Torvalds 
2196200e9ef7SLinus Torvalds 	c = (unsigned char)*name;
2197200e9ef7SLinus Torvalds 	do {
2198200e9ef7SLinus Torvalds 		len++;
2199200e9ef7SLinus Torvalds 		hash = partial_name_hash(c, hash);
2200200e9ef7SLinus Torvalds 		c = (unsigned char)name[len];
2201200e9ef7SLinus Torvalds 	} while (c && c != '/');
2202d6bb3e90SLinus Torvalds 	return hashlen_create(end_name_hash(hash), len);
2203200e9ef7SLinus Torvalds }
2204200e9ef7SLinus Torvalds 
2205bfcfaa77SLinus Torvalds #endif
2206bfcfaa77SLinus Torvalds 
2207200e9ef7SLinus Torvalds /*
22081da177e4SLinus Torvalds  * Name resolution.
2209ea3834d9SPrasanna Meda  * This is the basic name resolution function, turning a pathname into
2210ea3834d9SPrasanna Meda  * the final dentry. We expect 'base' to be positive and a directory.
22111da177e4SLinus Torvalds  *
2212ea3834d9SPrasanna Meda  * Returns 0 and nd will have valid dentry and mnt on success.
2213ea3834d9SPrasanna Meda  * Returns error and drops reference to input namei data on failure.
22141da177e4SLinus Torvalds  */
22156de88d72SAl Viro static int link_path_walk(const char *name, struct nameidata *nd)
22161da177e4SLinus Torvalds {
2217d8d4611aSAl Viro 	int depth = 0; // depth <= nd->depth
22181da177e4SLinus Torvalds 	int err;
22191da177e4SLinus Torvalds 
2220b4c03536SAl Viro 	nd->last_type = LAST_ROOT;
2221c108837eSAl Viro 	nd->flags |= LOOKUP_PARENT;
22229b5858e9SAl Viro 	if (IS_ERR(name))
22239b5858e9SAl Viro 		return PTR_ERR(name);
22241da177e4SLinus Torvalds 	while (*name=='/')
22251da177e4SLinus Torvalds 		name++;
22261a97d899SAl Viro 	if (!*name) {
22271a97d899SAl Viro 		nd->dir_mode = 0; // short-circuit the 'hardening' idiocy
22289e18f10aSAl Viro 		return 0;
22291a97d899SAl Viro 	}
22301da177e4SLinus Torvalds 
22311da177e4SLinus Torvalds 	/* At this point we know we have a real path component. */
22321da177e4SLinus Torvalds 	for(;;) {
2233549c7297SChristian Brauner 		struct user_namespace *mnt_userns;
223492d27016SAl Viro 		const char *link;
2235d6bb3e90SLinus Torvalds 		u64 hash_len;
2236fe479a58SAl Viro 		int type;
22371da177e4SLinus Torvalds 
2238549c7297SChristian Brauner 		mnt_userns = mnt_user_ns(nd->path.mnt);
2239549c7297SChristian Brauner 		err = may_lookup(mnt_userns, nd);
22401da177e4SLinus Torvalds 		if (err)
22413595e234SAl Viro 			return err;
22421da177e4SLinus Torvalds 
22438387ff25SLinus Torvalds 		hash_len = hash_name(nd->path.dentry, name);
22441da177e4SLinus Torvalds 
2245fe479a58SAl Viro 		type = LAST_NORM;
2246d6bb3e90SLinus Torvalds 		if (name[0] == '.') switch (hashlen_len(hash_len)) {
2247fe479a58SAl Viro 			case 2:
2248200e9ef7SLinus Torvalds 				if (name[1] == '.') {
2249fe479a58SAl Viro 					type = LAST_DOTDOT;
2250bcba1e7dSAl Viro 					nd->state |= ND_JUMPED;
225116c2cd71SAl Viro 				}
2252fe479a58SAl Viro 				break;
2253fe479a58SAl Viro 			case 1:
2254fe479a58SAl Viro 				type = LAST_DOT;
2255fe479a58SAl Viro 		}
22565a202bcdSAl Viro 		if (likely(type == LAST_NORM)) {
22575a202bcdSAl Viro 			struct dentry *parent = nd->path.dentry;
2258bcba1e7dSAl Viro 			nd->state &= ~ND_JUMPED;
22595a202bcdSAl Viro 			if (unlikely(parent->d_flags & DCACHE_OP_HASH)) {
2260a060dc50SJames Hogan 				struct qstr this = { { .hash_len = hash_len }, .name = name };
2261da53be12SLinus Torvalds 				err = parent->d_op->d_hash(parent, &this);
22625a202bcdSAl Viro 				if (err < 0)
22633595e234SAl Viro 					return err;
2264d6bb3e90SLinus Torvalds 				hash_len = this.hash_len;
2265d6bb3e90SLinus Torvalds 				name = this.name;
22665a202bcdSAl Viro 			}
22675a202bcdSAl Viro 		}
2268fe479a58SAl Viro 
2269d6bb3e90SLinus Torvalds 		nd->last.hash_len = hash_len;
2270d6bb3e90SLinus Torvalds 		nd->last.name = name;
22715f4a6a69SAl Viro 		nd->last_type = type;
22725f4a6a69SAl Viro 
2273d6bb3e90SLinus Torvalds 		name += hashlen_len(hash_len);
2274d6bb3e90SLinus Torvalds 		if (!*name)
2275bdf6cbf1SAl Viro 			goto OK;
2276200e9ef7SLinus Torvalds 		/*
2277200e9ef7SLinus Torvalds 		 * If it wasn't NUL, we know it was '/'. Skip that
2278200e9ef7SLinus Torvalds 		 * slash, and continue until no more slashes.
2279200e9ef7SLinus Torvalds 		 */
2280200e9ef7SLinus Torvalds 		do {
2281d6bb3e90SLinus Torvalds 			name++;
2282d6bb3e90SLinus Torvalds 		} while (unlikely(*name == '/'));
22838620c238SAl Viro 		if (unlikely(!*name)) {
22848620c238SAl Viro OK:
2285d8d4611aSAl Viro 			/* pathname or trailing symlink, done */
2286c108837eSAl Viro 			if (!depth) {
2287549c7297SChristian Brauner 				nd->dir_uid = i_uid_into_mnt(mnt_userns, nd->inode);
22880f705953SAl Viro 				nd->dir_mode = nd->inode->i_mode;
2289c108837eSAl Viro 				nd->flags &= ~LOOKUP_PARENT;
22908620c238SAl Viro 				return 0;
2291c108837eSAl Viro 			}
22928620c238SAl Viro 			/* last component of nested symlink */
2293d8d4611aSAl Viro 			name = nd->stack[--depth].name;
22948c4efe22SAl Viro 			link = walk_component(nd, 0);
22951c4ff1a8SAl Viro 		} else {
22961c4ff1a8SAl Viro 			/* not the last component */
22978c4efe22SAl Viro 			link = walk_component(nd, WALK_MORE);
22988620c238SAl Viro 		}
229992d27016SAl Viro 		if (unlikely(link)) {
230092d27016SAl Viro 			if (IS_ERR(link))
230192d27016SAl Viro 				return PTR_ERR(link);
230292d27016SAl Viro 			/* a symlink to follow */
2303d8d4611aSAl Viro 			nd->stack[depth++].name = name;
230492d27016SAl Viro 			name = link;
23059e18f10aSAl Viro 			continue;
230648c8b0c5SAl Viro 		}
230797242f99SAl Viro 		if (unlikely(!d_can_lookup(nd->path.dentry))) {
230897242f99SAl Viro 			if (nd->flags & LOOKUP_RCU) {
2309e36cffedSJens Axboe 				if (!try_to_unlazy(nd))
231097242f99SAl Viro 					return -ECHILD;
231197242f99SAl Viro 			}
23123595e234SAl Viro 			return -ENOTDIR;
23135f4a6a69SAl Viro 		}
2314ce57dfc1SAl Viro 	}
231597242f99SAl Viro }
23161da177e4SLinus Torvalds 
2317edc2b1daSAl Viro /* must be paired with terminate_walk() */
2318c8a53ee5SAl Viro static const char *path_init(struct nameidata *nd, unsigned flags)
231931e6b01fSNick Piggin {
2320740a1678SAleksa Sarai 	int error;
2321c8a53ee5SAl Viro 	const char *s = nd->name->name;
232231e6b01fSNick Piggin 
23236c6ec2b0SJens Axboe 	/* LOOKUP_CACHED requires RCU, ask caller to retry */
23246c6ec2b0SJens Axboe 	if ((flags & (LOOKUP_RCU | LOOKUP_CACHED)) == LOOKUP_CACHED)
23256c6ec2b0SJens Axboe 		return ERR_PTR(-EAGAIN);
23266c6ec2b0SJens Axboe 
2327c0eb027eSLinus Torvalds 	if (!*s)
2328c0eb027eSLinus Torvalds 		flags &= ~LOOKUP_RCU;
2329edc2b1daSAl Viro 	if (flags & LOOKUP_RCU)
2330edc2b1daSAl Viro 		rcu_read_lock();
2331c0eb027eSLinus Torvalds 
2332bcba1e7dSAl Viro 	nd->flags = flags;
2333bcba1e7dSAl Viro 	nd->state |= ND_JUMPED;
2334ab87f9a5SAleksa Sarai 
2335ab87f9a5SAleksa Sarai 	nd->m_seq = __read_seqcount_begin(&mount_lock.seqcount);
2336ab87f9a5SAleksa Sarai 	nd->r_seq = __read_seqcount_begin(&rename_lock.seqcount);
2337ab87f9a5SAleksa Sarai 	smp_rmb();
2338ab87f9a5SAleksa Sarai 
2339bcba1e7dSAl Viro 	if (nd->state & ND_ROOT_PRESET) {
2340b18825a7SDavid Howells 		struct dentry *root = nd->root.dentry;
2341b18825a7SDavid Howells 		struct inode *inode = root->d_inode;
234293893862SAl Viro 		if (*s && unlikely(!d_can_lookup(root)))
2343368ee9baSAl Viro 			return ERR_PTR(-ENOTDIR);
23445b6ca027SAl Viro 		nd->path = nd->root;
23455b6ca027SAl Viro 		nd->inode = inode;
23465b6ca027SAl Viro 		if (flags & LOOKUP_RCU) {
2347ab87f9a5SAleksa Sarai 			nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
23488f47a016SAl Viro 			nd->root_seq = nd->seq;
23495b6ca027SAl Viro 		} else {
23505b6ca027SAl Viro 			path_get(&nd->path);
23515b6ca027SAl Viro 		}
2352368ee9baSAl Viro 		return s;
23535b6ca027SAl Viro 	}
23545b6ca027SAl Viro 
235531e6b01fSNick Piggin 	nd->root.mnt = NULL;
235631e6b01fSNick Piggin 
23578db52c7eSAleksa Sarai 	/* Absolute pathname -- fetch the root (LOOKUP_IN_ROOT uses nd->dfd). */
23588db52c7eSAleksa Sarai 	if (*s == '/' && !(flags & LOOKUP_IN_ROOT)) {
2359740a1678SAleksa Sarai 		error = nd_jump_root(nd);
2360740a1678SAleksa Sarai 		if (unlikely(error))
2361740a1678SAleksa Sarai 			return ERR_PTR(error);
2362ef55d917SAl Viro 		return s;
23638db52c7eSAleksa Sarai 	}
23648db52c7eSAleksa Sarai 
23658db52c7eSAleksa Sarai 	/* Relative pathname -- get the starting-point it is relative to. */
23668db52c7eSAleksa Sarai 	if (nd->dfd == AT_FDCWD) {
2367e41f7d4eSAl Viro 		if (flags & LOOKUP_RCU) {
236831e6b01fSNick Piggin 			struct fs_struct *fs = current->fs;
2369c28cc364SNick Piggin 			unsigned seq;
237031e6b01fSNick Piggin 
2371c28cc364SNick Piggin 			do {
2372c28cc364SNick Piggin 				seq = read_seqcount_begin(&fs->seq);
237331e6b01fSNick Piggin 				nd->path = fs->pwd;
2374ef55d917SAl Viro 				nd->inode = nd->path.dentry->d_inode;
2375c28cc364SNick Piggin 				nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
2376c28cc364SNick Piggin 			} while (read_seqcount_retry(&fs->seq, seq));
2377e41f7d4eSAl Viro 		} else {
2378e41f7d4eSAl Viro 			get_fs_pwd(current->fs, &nd->path);
2379ef55d917SAl Viro 			nd->inode = nd->path.dentry->d_inode;
2380e41f7d4eSAl Viro 		}
238131e6b01fSNick Piggin 	} else {
2382582aa64aSJeff Layton 		/* Caller must check execute permissions on the starting path component */
2383c8a53ee5SAl Viro 		struct fd f = fdget_raw(nd->dfd);
238431e6b01fSNick Piggin 		struct dentry *dentry;
238531e6b01fSNick Piggin 
23862903ff01SAl Viro 		if (!f.file)
2387368ee9baSAl Viro 			return ERR_PTR(-EBADF);
238831e6b01fSNick Piggin 
23892903ff01SAl Viro 		dentry = f.file->f_path.dentry;
239031e6b01fSNick Piggin 
2391edc2b1daSAl Viro 		if (*s && unlikely(!d_can_lookup(dentry))) {
23922903ff01SAl Viro 			fdput(f);
2393368ee9baSAl Viro 			return ERR_PTR(-ENOTDIR);
2394f52e0c11SAl Viro 		}
23952903ff01SAl Viro 
23962903ff01SAl Viro 		nd->path = f.file->f_path;
2397e41f7d4eSAl Viro 		if (flags & LOOKUP_RCU) {
239834a26b99SAl Viro 			nd->inode = nd->path.dentry->d_inode;
239934a26b99SAl Viro 			nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
24005590ff0dSUlrich Drepper 		} else {
24012903ff01SAl Viro 			path_get(&nd->path);
240234a26b99SAl Viro 			nd->inode = nd->path.dentry->d_inode;
24031da177e4SLinus Torvalds 		}
240434a26b99SAl Viro 		fdput(f);
2405e41f7d4eSAl Viro 	}
24068db52c7eSAleksa Sarai 
2407adb21d2bSAleksa Sarai 	/* For scoped-lookups we need to set the root to the dirfd as well. */
2408adb21d2bSAleksa Sarai 	if (flags & LOOKUP_IS_SCOPED) {
2409adb21d2bSAleksa Sarai 		nd->root = nd->path;
2410adb21d2bSAleksa Sarai 		if (flags & LOOKUP_RCU) {
2411adb21d2bSAleksa Sarai 			nd->root_seq = nd->seq;
2412adb21d2bSAleksa Sarai 		} else {
2413adb21d2bSAleksa Sarai 			path_get(&nd->root);
2414bcba1e7dSAl Viro 			nd->state |= ND_ROOT_GRABBED;
2415adb21d2bSAleksa Sarai 		}
2416adb21d2bSAleksa Sarai 	}
2417adb21d2bSAleksa Sarai 	return s;
24189b4a9b14SAl Viro }
24199b4a9b14SAl Viro 
24201ccac622SAl Viro static inline const char *lookup_last(struct nameidata *nd)
242195fa25d9SAl Viro {
2422bd92d7feSAl Viro 	if (nd->last_type == LAST_NORM && nd->last.name[nd->last.len])
2423bd92d7feSAl Viro 		nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
2424bd92d7feSAl Viro 
2425c108837eSAl Viro 	return walk_component(nd, WALK_TRAILING);
2426bd92d7feSAl Viro }
2427bd92d7feSAl Viro 
24284f757f3cSAl Viro static int handle_lookup_down(struct nameidata *nd)
24294f757f3cSAl Viro {
2430c153007bSAl Viro 	if (!(nd->flags & LOOKUP_RCU))
2431db3c9adeSAl Viro 		dget(nd->path.dentry);
2432b0417d2cSAl Viro 	return PTR_ERR(step_into(nd, WALK_NOFOLLOW,
2433b0417d2cSAl Viro 			nd->path.dentry, nd->inode, nd->seq));
24344f757f3cSAl Viro }
24354f757f3cSAl Viro 
24369b4a9b14SAl Viro /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
2437c8a53ee5SAl Viro static int path_lookupat(struct nameidata *nd, unsigned flags, struct path *path)
24389b4a9b14SAl Viro {
2439c8a53ee5SAl Viro 	const char *s = path_init(nd, flags);
2440bd92d7feSAl Viro 	int err;
244131e6b01fSNick Piggin 
24429b5858e9SAl Viro 	if (unlikely(flags & LOOKUP_DOWN) && !IS_ERR(s)) {
24434f757f3cSAl Viro 		err = handle_lookup_down(nd);
24445f336e72SAl Viro 		if (unlikely(err < 0))
24455f336e72SAl Viro 			s = ERR_PTR(err);
24464f757f3cSAl Viro 	}
24474f757f3cSAl Viro 
24481ccac622SAl Viro 	while (!(err = link_path_walk(s, nd)) &&
24491ccac622SAl Viro 	       (s = lookup_last(nd)) != NULL)
24501ccac622SAl Viro 		;
24514f0ed93fSAl Viro 	if (!err && unlikely(nd->flags & LOOKUP_MOUNTPOINT)) {
24524f0ed93fSAl Viro 		err = handle_lookup_down(nd);
2453bcba1e7dSAl Viro 		nd->state &= ~ND_JUMPED; // no d_weak_revalidate(), please...
24544f0ed93fSAl Viro 	}
24559f1fafeeSAl Viro 	if (!err)
24569f1fafeeSAl Viro 		err = complete_walk(nd);
2457bd92d7feSAl Viro 
2458deb106c6SAl Viro 	if (!err && nd->flags & LOOKUP_DIRECTORY)
2459deb106c6SAl Viro 		if (!d_can_lookup(nd->path.dentry))
2460bd23a539SAl Viro 			err = -ENOTDIR;
2461625b6d10SAl Viro 	if (!err) {
2462625b6d10SAl Viro 		*path = nd->path;
2463625b6d10SAl Viro 		nd->path.mnt = NULL;
2464625b6d10SAl Viro 		nd->path.dentry = NULL;
2465625b6d10SAl Viro 	}
2466deb106c6SAl Viro 	terminate_walk(nd);
2467bd92d7feSAl Viro 	return err;
246831e6b01fSNick Piggin }
246931e6b01fSNick Piggin 
2470020250f3SDmitry Kadashev static int __filename_lookup(int dfd, struct filename *name, unsigned flags,
24719ad1aaa6SAl Viro 		    struct path *path, struct path *root)
2472873f1eedSJeff Layton {
2473894bc8c4SAl Viro 	int retval;
24749883d185SAl Viro 	struct nameidata nd;
2475abc9f5beSAl Viro 	if (IS_ERR(name))
2476abc9f5beSAl Viro 		return PTR_ERR(name);
247706422964SAl Viro 	set_nameidata(&nd, dfd, name, root);
2478c8a53ee5SAl Viro 	retval = path_lookupat(&nd, flags | LOOKUP_RCU, path);
2479873f1eedSJeff Layton 	if (unlikely(retval == -ECHILD))
2480c8a53ee5SAl Viro 		retval = path_lookupat(&nd, flags, path);
2481873f1eedSJeff Layton 	if (unlikely(retval == -ESTALE))
2482c8a53ee5SAl Viro 		retval = path_lookupat(&nd, flags | LOOKUP_REVAL, path);
2483873f1eedSJeff Layton 
2484873f1eedSJeff Layton 	if (likely(!retval))
2485161aff1dSAl Viro 		audit_inode(name, path->dentry,
2486161aff1dSAl Viro 			    flags & LOOKUP_MOUNTPOINT ? AUDIT_INODE_NOEVAL : 0);
24879883d185SAl Viro 	restore_nameidata();
2488020250f3SDmitry Kadashev 	return retval;
2489020250f3SDmitry Kadashev }
2490020250f3SDmitry Kadashev 
2491020250f3SDmitry Kadashev int filename_lookup(int dfd, struct filename *name, unsigned flags,
2492020250f3SDmitry Kadashev 		    struct path *path, struct path *root)
2493020250f3SDmitry Kadashev {
2494020250f3SDmitry Kadashev 	int retval = __filename_lookup(dfd, name, flags, path, root);
2495020250f3SDmitry Kadashev 
2496e4bd1c1aSAl Viro 	putname(name);
2497873f1eedSJeff Layton 	return retval;
2498873f1eedSJeff Layton }
2499873f1eedSJeff Layton 
25008bcb77faSAl Viro /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
2501c8a53ee5SAl Viro static int path_parentat(struct nameidata *nd, unsigned flags,
2502391172c4SAl Viro 				struct path *parent)
25038bcb77faSAl Viro {
2504c8a53ee5SAl Viro 	const char *s = path_init(nd, flags);
25059b5858e9SAl Viro 	int err = link_path_walk(s, nd);
25068bcb77faSAl Viro 	if (!err)
25078bcb77faSAl Viro 		err = complete_walk(nd);
2508391172c4SAl Viro 	if (!err) {
2509391172c4SAl Viro 		*parent = nd->path;
2510391172c4SAl Viro 		nd->path.mnt = NULL;
2511391172c4SAl Viro 		nd->path.dentry = NULL;
2512391172c4SAl Viro 	}
2513deb106c6SAl Viro 	terminate_walk(nd);
25148bcb77faSAl Viro 	return err;
25158bcb77faSAl Viro }
25168bcb77faSAl Viro 
2517*0766ec82SStephen Brennan /* Note: this does not consume "name" */
25180ee50b47SDmitry Kadashev static int __filename_parentat(int dfd, struct filename *name,
2519391172c4SAl Viro 			     unsigned int flags, struct path *parent,
2520391172c4SAl Viro 			     struct qstr *last, int *type)
25218bcb77faSAl Viro {
25228bcb77faSAl Viro 	int retval;
25239883d185SAl Viro 	struct nameidata nd;
25248bcb77faSAl Viro 
25255c31b6ceSAl Viro 	if (IS_ERR(name))
25260ee50b47SDmitry Kadashev 		return PTR_ERR(name);
252706422964SAl Viro 	set_nameidata(&nd, dfd, name, NULL);
2528c8a53ee5SAl Viro 	retval = path_parentat(&nd, flags | LOOKUP_RCU, parent);
25298bcb77faSAl Viro 	if (unlikely(retval == -ECHILD))
2530c8a53ee5SAl Viro 		retval = path_parentat(&nd, flags, parent);
25318bcb77faSAl Viro 	if (unlikely(retval == -ESTALE))
2532c8a53ee5SAl Viro 		retval = path_parentat(&nd, flags | LOOKUP_REVAL, parent);
2533391172c4SAl Viro 	if (likely(!retval)) {
2534391172c4SAl Viro 		*last = nd.last;
2535391172c4SAl Viro 		*type = nd.last_type;
2536c9b07eabSAl Viro 		audit_inode(name, parent->dentry, AUDIT_INODE_PARENT);
2537391172c4SAl Viro 	}
25389883d185SAl Viro 	restore_nameidata();
25390ee50b47SDmitry Kadashev 	return retval;
25400ee50b47SDmitry Kadashev }
25410ee50b47SDmitry Kadashev 
254279714f72SAl Viro /* does lookup, returns the object with parent locked */
2543*0766ec82SStephen Brennan static struct dentry *__kern_path_locked(struct filename *name, struct path *path)
25445590ff0dSUlrich Drepper {
25455c31b6ceSAl Viro 	struct dentry *d;
2546391172c4SAl Viro 	struct qstr last;
25470ee50b47SDmitry Kadashev 	int type, error;
254851689104SPaul Moore 
2549*0766ec82SStephen Brennan 	error = __filename_parentat(AT_FDCWD, name, 0, path, &last, &type);
25500ee50b47SDmitry Kadashev 	if (error)
25510ee50b47SDmitry Kadashev 		return ERR_PTR(error);
25525c31b6ceSAl Viro 	if (unlikely(type != LAST_NORM)) {
2553391172c4SAl Viro 		path_put(path);
25545c31b6ceSAl Viro 		return ERR_PTR(-EINVAL);
255579714f72SAl Viro 	}
25565955102cSAl Viro 	inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
2557391172c4SAl Viro 	d = __lookup_hash(&last, path->dentry, 0);
255879714f72SAl Viro 	if (IS_ERR(d)) {
25595955102cSAl Viro 		inode_unlock(path->dentry->d_inode);
2560391172c4SAl Viro 		path_put(path);
256179714f72SAl Viro 	}
256279714f72SAl Viro 	return d;
25635590ff0dSUlrich Drepper }
25645590ff0dSUlrich Drepper 
2565*0766ec82SStephen Brennan struct dentry *kern_path_locked(const char *name, struct path *path)
2566*0766ec82SStephen Brennan {
2567*0766ec82SStephen Brennan 	struct filename *filename = getname_kernel(name);
2568*0766ec82SStephen Brennan 	struct dentry *res = __kern_path_locked(filename, path);
2569*0766ec82SStephen Brennan 
2570*0766ec82SStephen Brennan 	putname(filename);
2571*0766ec82SStephen Brennan 	return res;
2572*0766ec82SStephen Brennan }
2573*0766ec82SStephen Brennan 
2574d1811465SAl Viro int kern_path(const char *name, unsigned int flags, struct path *path)
2575d1811465SAl Viro {
2576abc9f5beSAl Viro 	return filename_lookup(AT_FDCWD, getname_kernel(name),
2577abc9f5beSAl Viro 			       flags, path, NULL);
2578d1811465SAl Viro }
25794d359507SAl Viro EXPORT_SYMBOL(kern_path);
2580d1811465SAl Viro 
258116f18200SJosef 'Jeff' Sipek /**
258216f18200SJosef 'Jeff' Sipek  * vfs_path_lookup - lookup a file path relative to a dentry-vfsmount pair
258316f18200SJosef 'Jeff' Sipek  * @dentry:  pointer to dentry of the base directory
258416f18200SJosef 'Jeff' Sipek  * @mnt: pointer to vfs mount of the base directory
258516f18200SJosef 'Jeff' Sipek  * @name: pointer to file name
258616f18200SJosef 'Jeff' Sipek  * @flags: lookup flags
2587e0a01249SAl Viro  * @path: pointer to struct path to fill
258816f18200SJosef 'Jeff' Sipek  */
258916f18200SJosef 'Jeff' Sipek int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt,
259016f18200SJosef 'Jeff' Sipek 		    const char *name, unsigned int flags,
2591e0a01249SAl Viro 		    struct path *path)
259216f18200SJosef 'Jeff' Sipek {
25939ad1aaa6SAl Viro 	struct path root = {.mnt = mnt, .dentry = dentry};
25949ad1aaa6SAl Viro 	/* the first argument of filename_lookup() is ignored with root */
2595abc9f5beSAl Viro 	return filename_lookup(AT_FDCWD, getname_kernel(name),
2596abc9f5beSAl Viro 			       flags , path, &root);
259716f18200SJosef 'Jeff' Sipek }
25984d359507SAl Viro EXPORT_SYMBOL(vfs_path_lookup);
259916f18200SJosef 'Jeff' Sipek 
2600c2fd68b6SChristian Brauner static int lookup_one_common(struct user_namespace *mnt_userns,
2601c2fd68b6SChristian Brauner 			     const char *name, struct dentry *base, int len,
2602c2fd68b6SChristian Brauner 			     struct qstr *this)
26033c95f0dcSAl Viro {
26043c95f0dcSAl Viro 	this->name = name;
26053c95f0dcSAl Viro 	this->len = len;
26063c95f0dcSAl Viro 	this->hash = full_name_hash(base, name, len);
26073c95f0dcSAl Viro 	if (!len)
26083c95f0dcSAl Viro 		return -EACCES;
26093c95f0dcSAl Viro 
26103c95f0dcSAl Viro 	if (unlikely(name[0] == '.')) {
26113c95f0dcSAl Viro 		if (len < 2 || (len == 2 && name[1] == '.'))
26123c95f0dcSAl Viro 			return -EACCES;
26133c95f0dcSAl Viro 	}
26143c95f0dcSAl Viro 
26153c95f0dcSAl Viro 	while (len--) {
26163c95f0dcSAl Viro 		unsigned int c = *(const unsigned char *)name++;
26173c95f0dcSAl Viro 		if (c == '/' || c == '\0')
26183c95f0dcSAl Viro 			return -EACCES;
26193c95f0dcSAl Viro 	}
26203c95f0dcSAl Viro 	/*
26213c95f0dcSAl Viro 	 * See if the low-level filesystem might want
26223c95f0dcSAl Viro 	 * to use its own hash..
26233c95f0dcSAl Viro 	 */
26243c95f0dcSAl Viro 	if (base->d_flags & DCACHE_OP_HASH) {
26253c95f0dcSAl Viro 		int err = base->d_op->d_hash(base, this);
26263c95f0dcSAl Viro 		if (err < 0)
26273c95f0dcSAl Viro 			return err;
26283c95f0dcSAl Viro 	}
26293c95f0dcSAl Viro 
2630c2fd68b6SChristian Brauner 	return inode_permission(mnt_userns, base->d_inode, MAY_EXEC);
26313c95f0dcSAl Viro }
26323c95f0dcSAl Viro 
2633eead1911SChristoph Hellwig /**
26340da0b7fdSDavid Howells  * try_lookup_one_len - filesystem helper to lookup single pathname component
26350da0b7fdSDavid Howells  * @name:	pathname component to lookup
26360da0b7fdSDavid Howells  * @base:	base directory to lookup from
26370da0b7fdSDavid Howells  * @len:	maximum length @len should be interpreted to
26380da0b7fdSDavid Howells  *
26390da0b7fdSDavid Howells  * Look up a dentry by name in the dcache, returning NULL if it does not
26400da0b7fdSDavid Howells  * currently exist.  The function does not try to create a dentry.
26410da0b7fdSDavid Howells  *
26420da0b7fdSDavid Howells  * Note that this routine is purely a helper for filesystem usage and should
26430da0b7fdSDavid Howells  * not be called by generic code.
26440da0b7fdSDavid Howells  *
26450da0b7fdSDavid Howells  * The caller must hold base->i_mutex.
26460da0b7fdSDavid Howells  */
26470da0b7fdSDavid Howells struct dentry *try_lookup_one_len(const char *name, struct dentry *base, int len)
26480da0b7fdSDavid Howells {
26490da0b7fdSDavid Howells 	struct qstr this;
26500da0b7fdSDavid Howells 	int err;
26510da0b7fdSDavid Howells 
26520da0b7fdSDavid Howells 	WARN_ON_ONCE(!inode_is_locked(base->d_inode));
26530da0b7fdSDavid Howells 
2654c2fd68b6SChristian Brauner 	err = lookup_one_common(&init_user_ns, name, base, len, &this);
26550da0b7fdSDavid Howells 	if (err)
26560da0b7fdSDavid Howells 		return ERR_PTR(err);
26570da0b7fdSDavid Howells 
26580da0b7fdSDavid Howells 	return lookup_dcache(&this, base, 0);
26590da0b7fdSDavid Howells }
26600da0b7fdSDavid Howells EXPORT_SYMBOL(try_lookup_one_len);
26610da0b7fdSDavid Howells 
26620da0b7fdSDavid Howells /**
2663a6b91919SRandy Dunlap  * lookup_one_len - filesystem helper to lookup single pathname component
2664eead1911SChristoph Hellwig  * @name:	pathname component to lookup
2665eead1911SChristoph Hellwig  * @base:	base directory to lookup from
2666eead1911SChristoph Hellwig  * @len:	maximum length @len should be interpreted to
2667eead1911SChristoph Hellwig  *
2668a6b91919SRandy Dunlap  * Note that this routine is purely a helper for filesystem usage and should
26699e7543e9SAl Viro  * not be called by generic code.
2670bbddca8eSNeilBrown  *
2671bbddca8eSNeilBrown  * The caller must hold base->i_mutex.
2672eead1911SChristoph Hellwig  */
2673057f6c01SJames Morris struct dentry *lookup_one_len(const char *name, struct dentry *base, int len)
2674057f6c01SJames Morris {
26758613a209SAl Viro 	struct dentry *dentry;
2676057f6c01SJames Morris 	struct qstr this;
2677cda309deSMiklos Szeredi 	int err;
2678057f6c01SJames Morris 
26795955102cSAl Viro 	WARN_ON_ONCE(!inode_is_locked(base->d_inode));
26802f9092e1SDavid Woodhouse 
2681c2fd68b6SChristian Brauner 	err = lookup_one_common(&init_user_ns, name, base, len, &this);
2682cda309deSMiklos Szeredi 	if (err)
2683cda309deSMiklos Szeredi 		return ERR_PTR(err);
2684cda309deSMiklos Szeredi 
26858613a209SAl Viro 	dentry = lookup_dcache(&this, base, 0);
26868613a209SAl Viro 	return dentry ? dentry : __lookup_slow(&this, base, 0);
2687057f6c01SJames Morris }
26884d359507SAl Viro EXPORT_SYMBOL(lookup_one_len);
2689057f6c01SJames Morris 
2690bbddca8eSNeilBrown /**
2691c2fd68b6SChristian Brauner  * lookup_one - filesystem helper to lookup single pathname component
2692c2fd68b6SChristian Brauner  * @mnt_userns:	user namespace of the mount the lookup is performed from
2693c2fd68b6SChristian Brauner  * @name:	pathname component to lookup
2694c2fd68b6SChristian Brauner  * @base:	base directory to lookup from
2695c2fd68b6SChristian Brauner  * @len:	maximum length @len should be interpreted to
2696c2fd68b6SChristian Brauner  *
2697c2fd68b6SChristian Brauner  * Note that this routine is purely a helper for filesystem usage and should
2698c2fd68b6SChristian Brauner  * not be called by generic code.
2699c2fd68b6SChristian Brauner  *
2700c2fd68b6SChristian Brauner  * The caller must hold base->i_mutex.
2701c2fd68b6SChristian Brauner  */
2702c2fd68b6SChristian Brauner struct dentry *lookup_one(struct user_namespace *mnt_userns, const char *name,
2703c2fd68b6SChristian Brauner 			  struct dentry *base, int len)
2704c2fd68b6SChristian Brauner {
2705c2fd68b6SChristian Brauner 	struct dentry *dentry;
2706c2fd68b6SChristian Brauner 	struct qstr this;
2707c2fd68b6SChristian Brauner 	int err;
2708c2fd68b6SChristian Brauner 
2709c2fd68b6SChristian Brauner 	WARN_ON_ONCE(!inode_is_locked(base->d_inode));
2710c2fd68b6SChristian Brauner 
2711c2fd68b6SChristian Brauner 	err = lookup_one_common(mnt_userns, name, base, len, &this);
2712c2fd68b6SChristian Brauner 	if (err)
2713c2fd68b6SChristian Brauner 		return ERR_PTR(err);
2714c2fd68b6SChristian Brauner 
2715c2fd68b6SChristian Brauner 	dentry = lookup_dcache(&this, base, 0);
2716c2fd68b6SChristian Brauner 	return dentry ? dentry : __lookup_slow(&this, base, 0);
2717c2fd68b6SChristian Brauner }
2718c2fd68b6SChristian Brauner EXPORT_SYMBOL(lookup_one);
2719c2fd68b6SChristian Brauner 
2720c2fd68b6SChristian Brauner /**
2721bbddca8eSNeilBrown  * lookup_one_len_unlocked - filesystem helper to lookup single pathname component
2722bbddca8eSNeilBrown  * @name:	pathname component to lookup
2723bbddca8eSNeilBrown  * @base:	base directory to lookup from
2724bbddca8eSNeilBrown  * @len:	maximum length @len should be interpreted to
2725bbddca8eSNeilBrown  *
2726bbddca8eSNeilBrown  * Note that this routine is purely a helper for filesystem usage and should
2727bbddca8eSNeilBrown  * not be called by generic code.
2728bbddca8eSNeilBrown  *
2729bbddca8eSNeilBrown  * Unlike lookup_one_len, it should be called without the parent
2730bbddca8eSNeilBrown  * i_mutex held, and will take the i_mutex itself if necessary.
2731bbddca8eSNeilBrown  */
2732bbddca8eSNeilBrown struct dentry *lookup_one_len_unlocked(const char *name,
2733bbddca8eSNeilBrown 				       struct dentry *base, int len)
2734bbddca8eSNeilBrown {
2735bbddca8eSNeilBrown 	struct qstr this;
2736bbddca8eSNeilBrown 	int err;
273720d00ee8SLinus Torvalds 	struct dentry *ret;
2738bbddca8eSNeilBrown 
2739c2fd68b6SChristian Brauner 	err = lookup_one_common(&init_user_ns, name, base, len, &this);
2740bbddca8eSNeilBrown 	if (err)
2741bbddca8eSNeilBrown 		return ERR_PTR(err);
2742bbddca8eSNeilBrown 
274320d00ee8SLinus Torvalds 	ret = lookup_dcache(&this, base, 0);
274420d00ee8SLinus Torvalds 	if (!ret)
274520d00ee8SLinus Torvalds 		ret = lookup_slow(&this, base, 0);
274620d00ee8SLinus Torvalds 	return ret;
2747bbddca8eSNeilBrown }
2748bbddca8eSNeilBrown EXPORT_SYMBOL(lookup_one_len_unlocked);
2749bbddca8eSNeilBrown 
27506c2d4798SAl Viro /*
27516c2d4798SAl Viro  * Like lookup_one_len_unlocked(), except that it yields ERR_PTR(-ENOENT)
27526c2d4798SAl Viro  * on negatives.  Returns known positive or ERR_PTR(); that's what
27536c2d4798SAl Viro  * most of the users want.  Note that pinned negative with unlocked parent
27546c2d4798SAl Viro  * _can_ become positive at any time, so callers of lookup_one_len_unlocked()
27556c2d4798SAl Viro  * need to be very careful; pinned positives have ->d_inode stable, so
27566c2d4798SAl Viro  * this one avoids such problems.
27576c2d4798SAl Viro  */
27586c2d4798SAl Viro struct dentry *lookup_positive_unlocked(const char *name,
27596c2d4798SAl Viro 				       struct dentry *base, int len)
27606c2d4798SAl Viro {
27616c2d4798SAl Viro 	struct dentry *ret = lookup_one_len_unlocked(name, base, len);
27622fa6b1e0SAl Viro 	if (!IS_ERR(ret) && d_flags_negative(smp_load_acquire(&ret->d_flags))) {
27636c2d4798SAl Viro 		dput(ret);
27646c2d4798SAl Viro 		ret = ERR_PTR(-ENOENT);
27656c2d4798SAl Viro 	}
27666c2d4798SAl Viro 	return ret;
27676c2d4798SAl Viro }
27686c2d4798SAl Viro EXPORT_SYMBOL(lookup_positive_unlocked);
27696c2d4798SAl Viro 
2770eedf265aSEric W. Biederman #ifdef CONFIG_UNIX98_PTYS
2771eedf265aSEric W. Biederman int path_pts(struct path *path)
2772eedf265aSEric W. Biederman {
2773eedf265aSEric W. Biederman 	/* Find something mounted on "pts" in the same directory as
2774eedf265aSEric W. Biederman 	 * the input path.
2775eedf265aSEric W. Biederman 	 */
2776a6a7eb76SAl Viro 	struct dentry *parent = dget_parent(path->dentry);
2777a6a7eb76SAl Viro 	struct dentry *child;
277819f6028aSAl Viro 	struct qstr this = QSTR_INIT("pts", 3);
2779eedf265aSEric W. Biederman 
2780a6a7eb76SAl Viro 	if (unlikely(!path_connected(path->mnt, parent))) {
2781a6a7eb76SAl Viro 		dput(parent);
278263b27720SAl Viro 		return -ENOENT;
2783a6a7eb76SAl Viro 	}
278463b27720SAl Viro 	dput(path->dentry);
278563b27720SAl Viro 	path->dentry = parent;
2786eedf265aSEric W. Biederman 	child = d_hash_and_lookup(parent, &this);
2787eedf265aSEric W. Biederman 	if (!child)
2788eedf265aSEric W. Biederman 		return -ENOENT;
2789eedf265aSEric W. Biederman 
2790eedf265aSEric W. Biederman 	path->dentry = child;
2791eedf265aSEric W. Biederman 	dput(parent);
279219f6028aSAl Viro 	follow_down(path);
2793eedf265aSEric W. Biederman 	return 0;
2794eedf265aSEric W. Biederman }
2795eedf265aSEric W. Biederman #endif
2796eedf265aSEric W. Biederman 
27971fa1e7f6SAndy Whitcroft int user_path_at_empty(int dfd, const char __user *name, unsigned flags,
27981fa1e7f6SAndy Whitcroft 		 struct path *path, int *empty)
27991da177e4SLinus Torvalds {
2800abc9f5beSAl Viro 	return filename_lookup(dfd, getname_flags(name, flags, empty),
2801abc9f5beSAl Viro 			       flags, path, NULL);
28021da177e4SLinus Torvalds }
2803b853a161SAl Viro EXPORT_SYMBOL(user_path_at_empty);
28041fa1e7f6SAndy Whitcroft 
2805ba73d987SChristian Brauner int __check_sticky(struct user_namespace *mnt_userns, struct inode *dir,
2806ba73d987SChristian Brauner 		   struct inode *inode)
28071da177e4SLinus Torvalds {
28088e96e3b7SEric W. Biederman 	kuid_t fsuid = current_fsuid();
2809da9592edSDavid Howells 
2810ba73d987SChristian Brauner 	if (uid_eq(i_uid_into_mnt(mnt_userns, inode), fsuid))
28111da177e4SLinus Torvalds 		return 0;
2812ba73d987SChristian Brauner 	if (uid_eq(i_uid_into_mnt(mnt_userns, dir), fsuid))
28131da177e4SLinus Torvalds 		return 0;
2814ba73d987SChristian Brauner 	return !capable_wrt_inode_uidgid(mnt_userns, inode, CAP_FOWNER);
28151da177e4SLinus Torvalds }
2816cbdf35bcSMiklos Szeredi EXPORT_SYMBOL(__check_sticky);
28171da177e4SLinus Torvalds 
28181da177e4SLinus Torvalds /*
28191da177e4SLinus Torvalds  *	Check whether we can remove a link victim from directory dir, check
28201da177e4SLinus Torvalds  *  whether the type of victim is right.
28211da177e4SLinus Torvalds  *  1. We can't do it if dir is read-only (done in permission())
28221da177e4SLinus Torvalds  *  2. We should have write and exec permissions on dir
28231da177e4SLinus Torvalds  *  3. We can't remove anything from append-only dir
28241da177e4SLinus Torvalds  *  4. We can't do anything with immutable dir (done in permission())
28251da177e4SLinus Torvalds  *  5. If the sticky bit on dir is set we should either
28261da177e4SLinus Torvalds  *	a. be owner of dir, or
28271da177e4SLinus Torvalds  *	b. be owner of victim, or
28281da177e4SLinus Torvalds  *	c. have CAP_FOWNER capability
28291da177e4SLinus Torvalds  *  6. If the victim is append-only or immutable we can't do antyhing with
28301da177e4SLinus Torvalds  *     links pointing to it.
28310bd23d09SEric W. Biederman  *  7. If the victim has an unknown uid or gid we can't change the inode.
28320bd23d09SEric W. Biederman  *  8. If we were asked to remove a directory and victim isn't one - ENOTDIR.
28330bd23d09SEric W. Biederman  *  9. If we were asked to remove a non-directory and victim isn't one - EISDIR.
28340bd23d09SEric W. Biederman  * 10. We can't remove a root or mountpoint.
28350bd23d09SEric W. Biederman  * 11. We don't allow removal of NFS sillyrenamed files; it's handled by
28361da177e4SLinus Torvalds  *     nfs_async_unlink().
28371da177e4SLinus Torvalds  */
2838ba73d987SChristian Brauner static int may_delete(struct user_namespace *mnt_userns, struct inode *dir,
2839ba73d987SChristian Brauner 		      struct dentry *victim, bool isdir)
28401da177e4SLinus Torvalds {
284163afdfc7SDavid Howells 	struct inode *inode = d_backing_inode(victim);
28421da177e4SLinus Torvalds 	int error;
28431da177e4SLinus Torvalds 
2844b18825a7SDavid Howells 	if (d_is_negative(victim))
28451da177e4SLinus Torvalds 		return -ENOENT;
2846b18825a7SDavid Howells 	BUG_ON(!inode);
28471da177e4SLinus Torvalds 
28481da177e4SLinus Torvalds 	BUG_ON(victim->d_parent->d_inode != dir);
2849593d1ce8SEric W. Biederman 
2850593d1ce8SEric W. Biederman 	/* Inode writeback is not safe when the uid or gid are invalid. */
2851ba73d987SChristian Brauner 	if (!uid_valid(i_uid_into_mnt(mnt_userns, inode)) ||
2852ba73d987SChristian Brauner 	    !gid_valid(i_gid_into_mnt(mnt_userns, inode)))
2853593d1ce8SEric W. Biederman 		return -EOVERFLOW;
2854593d1ce8SEric W. Biederman 
28554fa6b5ecSJeff Layton 	audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
28561da177e4SLinus Torvalds 
2857ba73d987SChristian Brauner 	error = inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
28581da177e4SLinus Torvalds 	if (error)
28591da177e4SLinus Torvalds 		return error;
28601da177e4SLinus Torvalds 	if (IS_APPEND(dir))
28611da177e4SLinus Torvalds 		return -EPERM;
2862b18825a7SDavid Howells 
2863ba73d987SChristian Brauner 	if (check_sticky(mnt_userns, dir, inode) || IS_APPEND(inode) ||
2864ba73d987SChristian Brauner 	    IS_IMMUTABLE(inode) || IS_SWAPFILE(inode) ||
2865ba73d987SChristian Brauner 	    HAS_UNMAPPED_ID(mnt_userns, inode))
28661da177e4SLinus Torvalds 		return -EPERM;
28671da177e4SLinus Torvalds 	if (isdir) {
286844b1d530SMiklos Szeredi 		if (!d_is_dir(victim))
28691da177e4SLinus Torvalds 			return -ENOTDIR;
28701da177e4SLinus Torvalds 		if (IS_ROOT(victim))
28711da177e4SLinus Torvalds 			return -EBUSY;
287244b1d530SMiklos Szeredi 	} else if (d_is_dir(victim))
28731da177e4SLinus Torvalds 		return -EISDIR;
28741da177e4SLinus Torvalds 	if (IS_DEADDIR(dir))
28751da177e4SLinus Torvalds 		return -ENOENT;
28761da177e4SLinus Torvalds 	if (victim->d_flags & DCACHE_NFSFS_RENAMED)
28771da177e4SLinus Torvalds 		return -EBUSY;
28781da177e4SLinus Torvalds 	return 0;
28791da177e4SLinus Torvalds }
28801da177e4SLinus Torvalds 
28811da177e4SLinus Torvalds /*	Check whether we can create an object with dentry child in directory
28821da177e4SLinus Torvalds  *  dir.
28831da177e4SLinus Torvalds  *  1. We can't do it if child already exists (open has special treatment for
28841da177e4SLinus Torvalds  *     this case, but since we are inlined it's OK)
28851da177e4SLinus Torvalds  *  2. We can't do it if dir is read-only (done in permission())
2886036d5236SEric W. Biederman  *  3. We can't do it if the fs can't represent the fsuid or fsgid.
2887036d5236SEric W. Biederman  *  4. We should have write and exec permissions on dir
2888036d5236SEric W. Biederman  *  5. We can't do it if dir is immutable (done in permission())
28891da177e4SLinus Torvalds  */
2890ba73d987SChristian Brauner static inline int may_create(struct user_namespace *mnt_userns,
2891ba73d987SChristian Brauner 			     struct inode *dir, struct dentry *child)
28921da177e4SLinus Torvalds {
289314e972b4SJeff Layton 	audit_inode_child(dir, child, AUDIT_TYPE_CHILD_CREATE);
28941da177e4SLinus Torvalds 	if (child->d_inode)
28951da177e4SLinus Torvalds 		return -EEXIST;
28961da177e4SLinus Torvalds 	if (IS_DEADDIR(dir))
28971da177e4SLinus Torvalds 		return -ENOENT;
28988e538913SChristian Brauner 	if (!fsuidgid_has_mapping(dir->i_sb, mnt_userns))
2899036d5236SEric W. Biederman 		return -EOVERFLOW;
29008e538913SChristian Brauner 
2901ba73d987SChristian Brauner 	return inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
29021da177e4SLinus Torvalds }
29031da177e4SLinus Torvalds 
29041da177e4SLinus Torvalds /*
29051da177e4SLinus Torvalds  * p1 and p2 should be directories on the same fs.
29061da177e4SLinus Torvalds  */
29071da177e4SLinus Torvalds struct dentry *lock_rename(struct dentry *p1, struct dentry *p2)
29081da177e4SLinus Torvalds {
29091da177e4SLinus Torvalds 	struct dentry *p;
29101da177e4SLinus Torvalds 
29111da177e4SLinus Torvalds 	if (p1 == p2) {
29125955102cSAl Viro 		inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
29131da177e4SLinus Torvalds 		return NULL;
29141da177e4SLinus Torvalds 	}
29151da177e4SLinus Torvalds 
2916fc64005cSAl Viro 	mutex_lock(&p1->d_sb->s_vfs_rename_mutex);
29171da177e4SLinus Torvalds 
2918e2761a11SOGAWA Hirofumi 	p = d_ancestor(p2, p1);
2919e2761a11SOGAWA Hirofumi 	if (p) {
29205955102cSAl Viro 		inode_lock_nested(p2->d_inode, I_MUTEX_PARENT);
29215955102cSAl Viro 		inode_lock_nested(p1->d_inode, I_MUTEX_CHILD);
29221da177e4SLinus Torvalds 		return p;
29231da177e4SLinus Torvalds 	}
29241da177e4SLinus Torvalds 
2925e2761a11SOGAWA Hirofumi 	p = d_ancestor(p1, p2);
2926e2761a11SOGAWA Hirofumi 	if (p) {
29275955102cSAl Viro 		inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
29285955102cSAl Viro 		inode_lock_nested(p2->d_inode, I_MUTEX_CHILD);
29291da177e4SLinus Torvalds 		return p;
29301da177e4SLinus Torvalds 	}
29311da177e4SLinus Torvalds 
29325955102cSAl Viro 	inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
29335955102cSAl Viro 	inode_lock_nested(p2->d_inode, I_MUTEX_PARENT2);
29341da177e4SLinus Torvalds 	return NULL;
29351da177e4SLinus Torvalds }
29364d359507SAl Viro EXPORT_SYMBOL(lock_rename);
29371da177e4SLinus Torvalds 
29381da177e4SLinus Torvalds void unlock_rename(struct dentry *p1, struct dentry *p2)
29391da177e4SLinus Torvalds {
29405955102cSAl Viro 	inode_unlock(p1->d_inode);
29411da177e4SLinus Torvalds 	if (p1 != p2) {
29425955102cSAl Viro 		inode_unlock(p2->d_inode);
2943fc64005cSAl Viro 		mutex_unlock(&p1->d_sb->s_vfs_rename_mutex);
29441da177e4SLinus Torvalds 	}
29451da177e4SLinus Torvalds }
29464d359507SAl Viro EXPORT_SYMBOL(unlock_rename);
29471da177e4SLinus Torvalds 
29486521f891SChristian Brauner /**
29496521f891SChristian Brauner  * vfs_create - create new file
29506521f891SChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
29516521f891SChristian Brauner  * @dir:	inode of @dentry
29526521f891SChristian Brauner  * @dentry:	pointer to dentry of the base directory
29536521f891SChristian Brauner  * @mode:	mode of the new file
29546521f891SChristian Brauner  * @want_excl:	whether the file must not yet exist
29556521f891SChristian Brauner  *
29566521f891SChristian Brauner  * Create a new file.
29576521f891SChristian Brauner  *
29586521f891SChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
29596521f891SChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
29606521f891SChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
29616521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
29626521f891SChristian Brauner  * raw inode simply passs init_user_ns.
29636521f891SChristian Brauner  */
29646521f891SChristian Brauner int vfs_create(struct user_namespace *mnt_userns, struct inode *dir,
29656521f891SChristian Brauner 	       struct dentry *dentry, umode_t mode, bool want_excl)
29661da177e4SLinus Torvalds {
29676521f891SChristian Brauner 	int error = may_create(mnt_userns, dir, dentry);
29681da177e4SLinus Torvalds 	if (error)
29691da177e4SLinus Torvalds 		return error;
29701da177e4SLinus Torvalds 
2971acfa4380SAl Viro 	if (!dir->i_op->create)
29721da177e4SLinus Torvalds 		return -EACCES;	/* shouldn't it be ENOSYS? */
29731da177e4SLinus Torvalds 	mode &= S_IALLUGO;
29741da177e4SLinus Torvalds 	mode |= S_IFREG;
29751da177e4SLinus Torvalds 	error = security_inode_create(dir, dentry, mode);
29761da177e4SLinus Torvalds 	if (error)
29771da177e4SLinus Torvalds 		return error;
2978549c7297SChristian Brauner 	error = dir->i_op->create(mnt_userns, dir, dentry, mode, want_excl);
2979a74574aaSStephen Smalley 	if (!error)
2980f38aa942SAmy Griffis 		fsnotify_create(dir, dentry);
29811da177e4SLinus Torvalds 	return error;
29821da177e4SLinus Torvalds }
29834d359507SAl Viro EXPORT_SYMBOL(vfs_create);
29841da177e4SLinus Torvalds 
29858e6c848eSAl Viro int vfs_mkobj(struct dentry *dentry, umode_t mode,
29868e6c848eSAl Viro 		int (*f)(struct dentry *, umode_t, void *),
29878e6c848eSAl Viro 		void *arg)
29888e6c848eSAl Viro {
29898e6c848eSAl Viro 	struct inode *dir = dentry->d_parent->d_inode;
2990ba73d987SChristian Brauner 	int error = may_create(&init_user_ns, dir, dentry);
29918e6c848eSAl Viro 	if (error)
29928e6c848eSAl Viro 		return error;
29938e6c848eSAl Viro 
29948e6c848eSAl Viro 	mode &= S_IALLUGO;
29958e6c848eSAl Viro 	mode |= S_IFREG;
29968e6c848eSAl Viro 	error = security_inode_create(dir, dentry, mode);
29978e6c848eSAl Viro 	if (error)
29988e6c848eSAl Viro 		return error;
29998e6c848eSAl Viro 	error = f(dentry, mode, arg);
30008e6c848eSAl Viro 	if (!error)
30018e6c848eSAl Viro 		fsnotify_create(dir, dentry);
30028e6c848eSAl Viro 	return error;
30038e6c848eSAl Viro }
30048e6c848eSAl Viro EXPORT_SYMBOL(vfs_mkobj);
30058e6c848eSAl Viro 
3006a2982cc9SEric W. Biederman bool may_open_dev(const struct path *path)
3007a2982cc9SEric W. Biederman {
3008a2982cc9SEric W. Biederman 	return !(path->mnt->mnt_flags & MNT_NODEV) &&
3009a2982cc9SEric W. Biederman 		!(path->mnt->mnt_sb->s_iflags & SB_I_NODEV);
3010a2982cc9SEric W. Biederman }
3011a2982cc9SEric W. Biederman 
3012ba73d987SChristian Brauner static int may_open(struct user_namespace *mnt_userns, const struct path *path,
3013ba73d987SChristian Brauner 		    int acc_mode, int flag)
30141da177e4SLinus Torvalds {
30153fb64190SChristoph Hellwig 	struct dentry *dentry = path->dentry;
30161da177e4SLinus Torvalds 	struct inode *inode = dentry->d_inode;
30171da177e4SLinus Torvalds 	int error;
30181da177e4SLinus Torvalds 
30191da177e4SLinus Torvalds 	if (!inode)
30201da177e4SLinus Torvalds 		return -ENOENT;
30211da177e4SLinus Torvalds 
3022c8fe8f30SChristoph Hellwig 	switch (inode->i_mode & S_IFMT) {
3023c8fe8f30SChristoph Hellwig 	case S_IFLNK:
30241da177e4SLinus Torvalds 		return -ELOOP;
3025c8fe8f30SChristoph Hellwig 	case S_IFDIR:
3026fc4177beSKees Cook 		if (acc_mode & MAY_WRITE)
30271da177e4SLinus Torvalds 			return -EISDIR;
3028fc4177beSKees Cook 		if (acc_mode & MAY_EXEC)
3029fc4177beSKees Cook 			return -EACCES;
3030c8fe8f30SChristoph Hellwig 		break;
3031c8fe8f30SChristoph Hellwig 	case S_IFBLK:
3032c8fe8f30SChristoph Hellwig 	case S_IFCHR:
3033a2982cc9SEric W. Biederman 		if (!may_open_dev(path))
30341da177e4SLinus Torvalds 			return -EACCES;
3035633fb6acSKees Cook 		fallthrough;
3036c8fe8f30SChristoph Hellwig 	case S_IFIFO:
3037c8fe8f30SChristoph Hellwig 	case S_IFSOCK:
3038633fb6acSKees Cook 		if (acc_mode & MAY_EXEC)
3039633fb6acSKees Cook 			return -EACCES;
30401da177e4SLinus Torvalds 		flag &= ~O_TRUNC;
3041c8fe8f30SChristoph Hellwig 		break;
30420fd338b2SKees Cook 	case S_IFREG:
30430fd338b2SKees Cook 		if ((acc_mode & MAY_EXEC) && path_noexec(path))
30440fd338b2SKees Cook 			return -EACCES;
30450fd338b2SKees Cook 		break;
30464a3fd211SDave Hansen 	}
3047b41572e9SDave Hansen 
3048ba73d987SChristian Brauner 	error = inode_permission(mnt_userns, inode, MAY_OPEN | acc_mode);
3049b41572e9SDave Hansen 	if (error)
3050b41572e9SDave Hansen 		return error;
30516146f0d5SMimi Zohar 
30521da177e4SLinus Torvalds 	/*
30531da177e4SLinus Torvalds 	 * An append-only file must be opened in append mode for writing.
30541da177e4SLinus Torvalds 	 */
30551da177e4SLinus Torvalds 	if (IS_APPEND(inode)) {
30568737c930SAl Viro 		if  ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND))
30577715b521SAl Viro 			return -EPERM;
30581da177e4SLinus Torvalds 		if (flag & O_TRUNC)
30597715b521SAl Viro 			return -EPERM;
30601da177e4SLinus Torvalds 	}
30611da177e4SLinus Torvalds 
30621da177e4SLinus Torvalds 	/* O_NOATIME can only be set by the owner or superuser */
3063ba73d987SChristian Brauner 	if (flag & O_NOATIME && !inode_owner_or_capable(mnt_userns, inode))
30647715b521SAl Viro 		return -EPERM;
30651da177e4SLinus Torvalds 
3066f3c7691eSJ. Bruce Fields 	return 0;
30677715b521SAl Viro }
30687715b521SAl Viro 
3069549c7297SChristian Brauner static int handle_truncate(struct user_namespace *mnt_userns, struct file *filp)
30707715b521SAl Viro {
3071f0bb5aafSAl Viro 	const struct path *path = &filp->f_path;
30727715b521SAl Viro 	struct inode *inode = path->dentry->d_inode;
30737715b521SAl Viro 	int error = get_write_access(inode);
30741da177e4SLinus Torvalds 	if (error)
30757715b521SAl Viro 		return error;
30761da177e4SLinus Torvalds 	/*
30771da177e4SLinus Torvalds 	 * Refuse to truncate files with mandatory locks held on them.
30781da177e4SLinus Torvalds 	 */
3079ea0d3ab2STetsuo Handa 	error = security_path_truncate(path);
30801da177e4SLinus Torvalds 	if (!error) {
3081549c7297SChristian Brauner 		error = do_truncate(mnt_userns, path->dentry, 0,
3082d139d7ffSMiklos Szeredi 				    ATTR_MTIME|ATTR_CTIME|ATTR_OPEN,
3083e1181ee6SJeff Layton 				    filp);
30841da177e4SLinus Torvalds 	}
30851da177e4SLinus Torvalds 	put_write_access(inode);
3086acd0c935SMimi Zohar 	return error;
30871da177e4SLinus Torvalds }
30881da177e4SLinus Torvalds 
3089d57999e1SDave Hansen static inline int open_to_namei_flags(int flag)
3090d57999e1SDave Hansen {
30918a5e929dSAl Viro 	if ((flag & O_ACCMODE) == 3)
30928a5e929dSAl Viro 		flag--;
3093d57999e1SDave Hansen 	return flag;
3094d57999e1SDave Hansen }
3095d57999e1SDave Hansen 
3096ba73d987SChristian Brauner static int may_o_create(struct user_namespace *mnt_userns,
3097ba73d987SChristian Brauner 			const struct path *dir, struct dentry *dentry,
3098ba73d987SChristian Brauner 			umode_t mode)
3099d18e9008SMiklos Szeredi {
3100d18e9008SMiklos Szeredi 	int error = security_path_mknod(dir, dentry, mode, 0);
3101d18e9008SMiklos Szeredi 	if (error)
3102d18e9008SMiklos Szeredi 		return error;
3103d18e9008SMiklos Szeredi 
31048e538913SChristian Brauner 	if (!fsuidgid_has_mapping(dir->dentry->d_sb, mnt_userns))
31051328c727SSeth Forshee 		return -EOVERFLOW;
31061328c727SSeth Forshee 
3107ba73d987SChristian Brauner 	error = inode_permission(mnt_userns, dir->dentry->d_inode,
310847291baaSChristian Brauner 				 MAY_WRITE | MAY_EXEC);
3109d18e9008SMiklos Szeredi 	if (error)
3110d18e9008SMiklos Szeredi 		return error;
3111d18e9008SMiklos Szeredi 
3112d18e9008SMiklos Szeredi 	return security_inode_create(dir->dentry->d_inode, dentry, mode);
3113d18e9008SMiklos Szeredi }
3114d18e9008SMiklos Szeredi 
31151acf0af9SDavid Howells /*
31161acf0af9SDavid Howells  * Attempt to atomically look up, create and open a file from a negative
31171acf0af9SDavid Howells  * dentry.
31181acf0af9SDavid Howells  *
31191acf0af9SDavid Howells  * Returns 0 if successful.  The file will have been created and attached to
31201acf0af9SDavid Howells  * @file by the filesystem calling finish_open().
31211acf0af9SDavid Howells  *
312200a07c15SAl Viro  * If the file was looked up only or didn't need creating, FMODE_OPENED won't
312300a07c15SAl Viro  * be set.  The caller will need to perform the open themselves.  @path will
312400a07c15SAl Viro  * have been updated to point to the new dentry.  This may be negative.
31251acf0af9SDavid Howells  *
31261acf0af9SDavid Howells  * Returns an error code otherwise.
31271acf0af9SDavid Howells  */
3128239eb983SAl Viro static struct dentry *atomic_open(struct nameidata *nd, struct dentry *dentry,
3129239eb983SAl Viro 				  struct file *file,
31303ec2eef1SAl Viro 				  int open_flag, umode_t mode)
3131d18e9008SMiklos Szeredi {
3132d18e9008SMiklos Szeredi 	struct dentry *const DENTRY_NOT_SET = (void *) -1UL;
3133d18e9008SMiklos Szeredi 	struct inode *dir =  nd->path.dentry->d_inode;
3134d18e9008SMiklos Szeredi 	int error;
3135d18e9008SMiklos Szeredi 
3136d18e9008SMiklos Szeredi 	if (nd->flags & LOOKUP_DIRECTORY)
3137d18e9008SMiklos Szeredi 		open_flag |= O_DIRECTORY;
3138d18e9008SMiklos Szeredi 
313930d90494SAl Viro 	file->f_path.dentry = DENTRY_NOT_SET;
314030d90494SAl Viro 	file->f_path.mnt = nd->path.mnt;
31410fb1ea09SAl Viro 	error = dir->i_op->atomic_open(dir, dentry, file,
314244907d79SAl Viro 				       open_to_namei_flags(open_flag), mode);
31436fbd0714SAl Viro 	d_lookup_done(dentry);
3144384f26e2SAl Viro 	if (!error) {
314564e1ac4dSAl Viro 		if (file->f_mode & FMODE_OPENED) {
31466fb968cdSAl Viro 			if (unlikely(dentry != file->f_path.dentry)) {
31476fb968cdSAl Viro 				dput(dentry);
31486fb968cdSAl Viro 				dentry = dget(file->f_path.dentry);
31496fb968cdSAl Viro 			}
315064e1ac4dSAl Viro 		} else if (WARN_ON(file->f_path.dentry == DENTRY_NOT_SET)) {
31512675a4ebSAl Viro 			error = -EIO;
3152384f26e2SAl Viro 		} else {
315330d90494SAl Viro 			if (file->f_path.dentry) {
3154d18e9008SMiklos Szeredi 				dput(dentry);
3155d18e9008SMiklos Szeredi 				dentry = file->f_path.dentry;
315610c64ceaSAl Viro 			}
3157239eb983SAl Viro 			if (unlikely(d_is_negative(dentry)))
3158a01e718fSAl Viro 				error = -ENOENT;
3159d18e9008SMiklos Szeredi 		}
3160d18e9008SMiklos Szeredi 	}
3161239eb983SAl Viro 	if (error) {
3162d18e9008SMiklos Szeredi 		dput(dentry);
3163239eb983SAl Viro 		dentry = ERR_PTR(error);
3164239eb983SAl Viro 	}
3165239eb983SAl Viro 	return dentry;
3166d18e9008SMiklos Szeredi }
3167d18e9008SMiklos Szeredi 
316831e6b01fSNick Piggin /*
31691acf0af9SDavid Howells  * Look up and maybe create and open the last component.
3170d58ffd35SMiklos Szeredi  *
317100a07c15SAl Viro  * Must be called with parent locked (exclusive in O_CREAT case).
3172d58ffd35SMiklos Szeredi  *
317300a07c15SAl Viro  * Returns 0 on success, that is, if
317400a07c15SAl Viro  *  the file was successfully atomically created (if necessary) and opened, or
317500a07c15SAl Viro  *  the file was not completely opened at this time, though lookups and
317600a07c15SAl Viro  *  creations were performed.
317700a07c15SAl Viro  * These case are distinguished by presence of FMODE_OPENED on file->f_mode.
317800a07c15SAl Viro  * In the latter case dentry returned in @path might be negative if O_CREAT
317900a07c15SAl Viro  * hadn't been specified.
31801acf0af9SDavid Howells  *
318100a07c15SAl Viro  * An error code is returned on failure.
3182d58ffd35SMiklos Szeredi  */
3183da5ebf5aSAl Viro static struct dentry *lookup_open(struct nameidata *nd, struct file *file,
3184d58ffd35SMiklos Szeredi 				  const struct open_flags *op,
31853ec2eef1SAl Viro 				  bool got_write)
3186d58ffd35SMiklos Szeredi {
3187549c7297SChristian Brauner 	struct user_namespace *mnt_userns;
3188d58ffd35SMiklos Szeredi 	struct dentry *dir = nd->path.dentry;
318954ef4872SMiklos Szeredi 	struct inode *dir_inode = dir->d_inode;
31901643b43fSAl Viro 	int open_flag = op->open_flag;
3191d58ffd35SMiklos Szeredi 	struct dentry *dentry;
31921643b43fSAl Viro 	int error, create_error = 0;
31931643b43fSAl Viro 	umode_t mode = op->mode;
31946fbd0714SAl Viro 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
3195d58ffd35SMiklos Szeredi 
3196ce8644fcSAl Viro 	if (unlikely(IS_DEADDIR(dir_inode)))
3197da5ebf5aSAl Viro 		return ERR_PTR(-ENOENT);
3198d58ffd35SMiklos Szeredi 
319973a09dd9SAl Viro 	file->f_mode &= ~FMODE_CREATED;
32006fbd0714SAl Viro 	dentry = d_lookup(dir, &nd->last);
32016fbd0714SAl Viro 	for (;;) {
32026fbd0714SAl Viro 		if (!dentry) {
32036fbd0714SAl Viro 			dentry = d_alloc_parallel(dir, &nd->last, &wq);
3204d58ffd35SMiklos Szeredi 			if (IS_ERR(dentry))
3205da5ebf5aSAl Viro 				return dentry;
32066fbd0714SAl Viro 		}
32076fbd0714SAl Viro 		if (d_in_lookup(dentry))
32086fbd0714SAl Viro 			break;
3209d58ffd35SMiklos Szeredi 
32106fbd0714SAl Viro 		error = d_revalidate(dentry, nd->flags);
32116fbd0714SAl Viro 		if (likely(error > 0))
32126fbd0714SAl Viro 			break;
32136fbd0714SAl Viro 		if (error)
32146fbd0714SAl Viro 			goto out_dput;
32156fbd0714SAl Viro 		d_invalidate(dentry);
32166fbd0714SAl Viro 		dput(dentry);
32176fbd0714SAl Viro 		dentry = NULL;
32186fbd0714SAl Viro 	}
32196fbd0714SAl Viro 	if (dentry->d_inode) {
3220d18e9008SMiklos Szeredi 		/* Cached positive dentry: will open in f_op->open */
3221da5ebf5aSAl Viro 		return dentry;
32226c51e513SAl Viro 	}
3223d18e9008SMiklos Szeredi 
32241643b43fSAl Viro 	/*
32251643b43fSAl Viro 	 * Checking write permission is tricky, bacuse we don't know if we are
32261643b43fSAl Viro 	 * going to actually need it: O_CREAT opens should work as long as the
32271643b43fSAl Viro 	 * file exists.  But checking existence breaks atomicity.  The trick is
32281643b43fSAl Viro 	 * to check access and if not granted clear O_CREAT from the flags.
32291643b43fSAl Viro 	 *
32301643b43fSAl Viro 	 * Another problem is returing the "right" error value (e.g. for an
32311643b43fSAl Viro 	 * O_EXCL open we want to return EEXIST not EROFS).
32321643b43fSAl Viro 	 */
323399a4a90cSAl Viro 	if (unlikely(!got_write))
323499a4a90cSAl Viro 		open_flag &= ~O_TRUNC;
3235549c7297SChristian Brauner 	mnt_userns = mnt_user_ns(nd->path.mnt);
32361643b43fSAl Viro 	if (open_flag & O_CREAT) {
323799a4a90cSAl Viro 		if (open_flag & O_EXCL)
323899a4a90cSAl Viro 			open_flag &= ~O_TRUNC;
32391643b43fSAl Viro 		if (!IS_POSIXACL(dir->d_inode))
32401643b43fSAl Viro 			mode &= ~current_umask();
324199a4a90cSAl Viro 		if (likely(got_write))
3242549c7297SChristian Brauner 			create_error = may_o_create(mnt_userns, &nd->path,
3243ba73d987SChristian Brauner 						    dentry, mode);
324499a4a90cSAl Viro 		else
324599a4a90cSAl Viro 			create_error = -EROFS;
324699a4a90cSAl Viro 	}
324799a4a90cSAl Viro 	if (create_error)
32481643b43fSAl Viro 		open_flag &= ~O_CREAT;
32491643b43fSAl Viro 	if (dir_inode->i_op->atomic_open) {
3250d489cf9aSAl Viro 		dentry = atomic_open(nd, dentry, file, open_flag, mode);
3251da5ebf5aSAl Viro 		if (unlikely(create_error) && dentry == ERR_PTR(-ENOENT))
3252da5ebf5aSAl Viro 			dentry = ERR_PTR(create_error);
3253da5ebf5aSAl Viro 		return dentry;
3254239eb983SAl Viro 	}
325554ef4872SMiklos Szeredi 
32566fbd0714SAl Viro 	if (d_in_lookup(dentry)) {
325712fa5e24SAl Viro 		struct dentry *res = dir_inode->i_op->lookup(dir_inode, dentry,
325812fa5e24SAl Viro 							     nd->flags);
32596fbd0714SAl Viro 		d_lookup_done(dentry);
326012fa5e24SAl Viro 		if (unlikely(res)) {
326112fa5e24SAl Viro 			if (IS_ERR(res)) {
326212fa5e24SAl Viro 				error = PTR_ERR(res);
326312fa5e24SAl Viro 				goto out_dput;
326412fa5e24SAl Viro 			}
326512fa5e24SAl Viro 			dput(dentry);
326612fa5e24SAl Viro 			dentry = res;
326712fa5e24SAl Viro 		}
326854ef4872SMiklos Szeredi 	}
326954ef4872SMiklos Szeredi 
3270d58ffd35SMiklos Szeredi 	/* Negative dentry, just create the file */
32711643b43fSAl Viro 	if (!dentry->d_inode && (open_flag & O_CREAT)) {
327273a09dd9SAl Viro 		file->f_mode |= FMODE_CREATED;
3273ce8644fcSAl Viro 		audit_inode_child(dir_inode, dentry, AUDIT_TYPE_CHILD_CREATE);
3274ce8644fcSAl Viro 		if (!dir_inode->i_op->create) {
3275ce8644fcSAl Viro 			error = -EACCES;
3276d58ffd35SMiklos Szeredi 			goto out_dput;
327764894cf8SAl Viro 		}
3278549c7297SChristian Brauner 
3279549c7297SChristian Brauner 		error = dir_inode->i_op->create(mnt_userns, dir_inode, dentry,
3280549c7297SChristian Brauner 						mode, open_flag & O_EXCL);
3281d58ffd35SMiklos Szeredi 		if (error)
3282d58ffd35SMiklos Szeredi 			goto out_dput;
3283d58ffd35SMiklos Szeredi 	}
32841643b43fSAl Viro 	if (unlikely(create_error) && !dentry->d_inode) {
32851643b43fSAl Viro 		error = create_error;
3286d58ffd35SMiklos Szeredi 		goto out_dput;
3287d58ffd35SMiklos Szeredi 	}
3288da5ebf5aSAl Viro 	return dentry;
3289d58ffd35SMiklos Szeredi 
3290d58ffd35SMiklos Szeredi out_dput:
3291d58ffd35SMiklos Szeredi 	dput(dentry);
3292da5ebf5aSAl Viro 	return ERR_PTR(error);
3293d58ffd35SMiklos Szeredi }
3294d58ffd35SMiklos Szeredi 
3295c981a482SAl Viro static const char *open_last_lookups(struct nameidata *nd,
32963ec2eef1SAl Viro 		   struct file *file, const struct open_flags *op)
3297fb1cc555SAl Viro {
3298a1e28038SAl Viro 	struct dentry *dir = nd->path.dentry;
3299ca344a89SAl Viro 	int open_flag = op->open_flag;
330064894cf8SAl Viro 	bool got_write = false;
3301254cf582SAl Viro 	unsigned seq;
3302a1eb3315SMiklos Szeredi 	struct inode *inode;
3303da5ebf5aSAl Viro 	struct dentry *dentry;
3304b0417d2cSAl Viro 	const char *res;
3305fb1cc555SAl Viro 
3306c3e380b0SAl Viro 	nd->flags |= op->intent;
3307c3e380b0SAl Viro 
3308bc77daa7SAl Viro 	if (nd->last_type != LAST_NORM) {
330956676ec3SAl Viro 		if (nd->depth)
331056676ec3SAl Viro 			put_link(nd);
3311ff326a32SAl Viro 		return handle_dots(nd, nd->last_type);
33121f36f774SAl Viro 	}
3313a2c36b45SAl Viro 
3314ca344a89SAl Viro 	if (!(open_flag & O_CREAT)) {
3315fe2d35ffSAl Viro 		if (nd->last.name[nd->last.len])
3316fe2d35ffSAl Viro 			nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
3317fe2d35ffSAl Viro 		/* we _can_ be in RCU mode here */
331820e34357SAl Viro 		dentry = lookup_fast(nd, &inode, &seq);
331920e34357SAl Viro 		if (IS_ERR(dentry))
33201ccac622SAl Viro 			return ERR_CAST(dentry);
332120e34357SAl Viro 		if (likely(dentry))
332271574865SMiklos Szeredi 			goto finish_lookup;
332371574865SMiklos Szeredi 
33246583fe22SAl Viro 		BUG_ON(nd->flags & LOOKUP_RCU);
3325b6183df7SMiklos Szeredi 	} else {
3326fe2d35ffSAl Viro 		/* create side of things */
332772287417SAl Viro 		if (nd->flags & LOOKUP_RCU) {
3328e36cffedSJens Axboe 			if (!try_to_unlazy(nd))
3329e36cffedSJens Axboe 				return ERR_PTR(-ECHILD);
333072287417SAl Viro 		}
3331c9b07eabSAl Viro 		audit_inode(nd->name, dir, AUDIT_INODE_PARENT);
33321f36f774SAl Viro 		/* trailing slashes? */
3333deb106c6SAl Viro 		if (unlikely(nd->last.name[nd->last.len]))
33341ccac622SAl Viro 			return ERR_PTR(-EISDIR);
3335b6183df7SMiklos Szeredi 	}
33361f36f774SAl Viro 
33379cf843e3SAl Viro 	if (open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) {
3338e36cffedSJens Axboe 		got_write = !mnt_want_write(nd->path.mnt);
333964894cf8SAl Viro 		/*
334064894cf8SAl Viro 		 * do _not_ fail yet - we might not need that or fail with
334164894cf8SAl Viro 		 * a different error; let lookup_open() decide; we'll be
334264894cf8SAl Viro 		 * dropping this one anyway.
334364894cf8SAl Viro 		 */
334464894cf8SAl Viro 	}
33459cf843e3SAl Viro 	if (open_flag & O_CREAT)
33465955102cSAl Viro 		inode_lock(dir->d_inode);
33479cf843e3SAl Viro 	else
33489cf843e3SAl Viro 		inode_lock_shared(dir->d_inode);
3349da5ebf5aSAl Viro 	dentry = lookup_open(nd, file, op, got_write);
3350f7bb959dSAl Viro 	if (!IS_ERR(dentry) && (file->f_mode & FMODE_CREATED))
3351f7bb959dSAl Viro 		fsnotify_create(dir->d_inode, dentry);
33529cf843e3SAl Viro 	if (open_flag & O_CREAT)
33535955102cSAl Viro 		inode_unlock(dir->d_inode);
33549cf843e3SAl Viro 	else
33559cf843e3SAl Viro 		inode_unlock_shared(dir->d_inode);
3356fb1cc555SAl Viro 
3357c981a482SAl Viro 	if (got_write)
335859e96e65SAl Viro 		mnt_drop_write(nd->path.mnt);
33596c0d46c4SAl Viro 
336059e96e65SAl Viro 	if (IS_ERR(dentry))
336159e96e65SAl Viro 		return ERR_CAST(dentry);
336259e96e65SAl Viro 
3363973d4b73SAl Viro 	if (file->f_mode & (FMODE_OPENED | FMODE_CREATED)) {
3364e73cabffSAl Viro 		dput(nd->path.dentry);
3365e73cabffSAl Viro 		nd->path.dentry = dentry;
3366c981a482SAl Viro 		return NULL;
3367fb1cc555SAl Viro 	}
3368fb1cc555SAl Viro 
336920e34357SAl Viro finish_lookup:
337056676ec3SAl Viro 	if (nd->depth)
337156676ec3SAl Viro 		put_link(nd);
33728c4efe22SAl Viro 	res = step_into(nd, WALK_TRAILING, dentry, inode, seq);
3373ff326a32SAl Viro 	if (unlikely(res))
33741ccac622SAl Viro 		nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL);
3375b0417d2cSAl Viro 	return res;
33761ccac622SAl Viro }
337731d1726dSAl Viro 
3378c981a482SAl Viro /*
3379c981a482SAl Viro  * Handle the last step of open()
3380c981a482SAl Viro  */
3381c5971b8cSAl Viro static int do_open(struct nameidata *nd,
3382c981a482SAl Viro 		   struct file *file, const struct open_flags *op)
3383c981a482SAl Viro {
3384549c7297SChristian Brauner 	struct user_namespace *mnt_userns;
3385c981a482SAl Viro 	int open_flag = op->open_flag;
3386c981a482SAl Viro 	bool do_truncate;
3387c981a482SAl Viro 	int acc_mode;
3388c981a482SAl Viro 	int error;
3389c981a482SAl Viro 
3390ff326a32SAl Viro 	if (!(file->f_mode & (FMODE_OPENED | FMODE_CREATED))) {
3391ff326a32SAl Viro 		error = complete_walk(nd);
3392ff326a32SAl Viro 		if (error)
3393ff326a32SAl Viro 			return error;
3394ff326a32SAl Viro 	}
3395973d4b73SAl Viro 	if (!(file->f_mode & FMODE_CREATED))
339676ae2a5aSAl Viro 		audit_inode(nd->name, nd->path.dentry, 0);
3397549c7297SChristian Brauner 	mnt_userns = mnt_user_ns(nd->path.mnt);
339830aba665SSalvatore Mesoraca 	if (open_flag & O_CREAT) {
3399b94e0b32SAl Viro 		if ((open_flag & O_EXCL) && !(file->f_mode & FMODE_CREATED))
3400b94e0b32SAl Viro 			return -EEXIST;
340130aba665SSalvatore Mesoraca 		if (d_is_dir(nd->path.dentry))
3402c5971b8cSAl Viro 			return -EISDIR;
3403549c7297SChristian Brauner 		error = may_create_in_sticky(mnt_userns, nd,
340430aba665SSalvatore Mesoraca 					     d_backing_inode(nd->path.dentry));
340530aba665SSalvatore Mesoraca 		if (unlikely(error))
3406c5971b8cSAl Viro 			return error;
340730aba665SSalvatore Mesoraca 	}
340844b1d530SMiklos Szeredi 	if ((nd->flags & LOOKUP_DIRECTORY) && !d_can_lookup(nd->path.dentry))
3409c5971b8cSAl Viro 		return -ENOTDIR;
34106c0d46c4SAl Viro 
34118795e7d4SAl Viro 	do_truncate = false;
34128795e7d4SAl Viro 	acc_mode = op->acc_mode;
34135a2d3eddSAl Viro 	if (file->f_mode & FMODE_CREATED) {
34145a2d3eddSAl Viro 		/* Don't check for write permission, don't truncate */
34155a2d3eddSAl Viro 		open_flag &= ~O_TRUNC;
34165a2d3eddSAl Viro 		acc_mode = 0;
34178795e7d4SAl Viro 	} else if (d_is_reg(nd->path.dentry) && open_flag & O_TRUNC) {
34180f9d1a10SAl Viro 		error = mnt_want_write(nd->path.mnt);
34190f9d1a10SAl Viro 		if (error)
3420c5971b8cSAl Viro 			return error;
34218795e7d4SAl Viro 		do_truncate = true;
34220f9d1a10SAl Viro 	}
3423549c7297SChristian Brauner 	error = may_open(mnt_userns, &nd->path, acc_mode, open_flag);
34248795e7d4SAl Viro 	if (!error && !(file->f_mode & FMODE_OPENED))
3425ae2bb293SAl Viro 		error = vfs_open(&nd->path, file);
34268795e7d4SAl Viro 	if (!error)
34276035a27bSAl Viro 		error = ima_file_check(file, op->acc_mode);
34288795e7d4SAl Viro 	if (!error && do_truncate)
3429549c7297SChristian Brauner 		error = handle_truncate(mnt_userns, file);
3430c80567c8SAl Viro 	if (unlikely(error > 0)) {
3431c80567c8SAl Viro 		WARN_ON(1);
3432c80567c8SAl Viro 		error = -EINVAL;
3433c80567c8SAl Viro 	}
34348795e7d4SAl Viro 	if (do_truncate)
34350f9d1a10SAl Viro 		mnt_drop_write(nd->path.mnt);
3436c5971b8cSAl Viro 	return error;
3437fb1cc555SAl Viro }
3438fb1cc555SAl Viro 
34396521f891SChristian Brauner /**
34406521f891SChristian Brauner  * vfs_tmpfile - create tmpfile
34416521f891SChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
34426521f891SChristian Brauner  * @dentry:	pointer to dentry of the base directory
34436521f891SChristian Brauner  * @mode:	mode of the new tmpfile
34442111c3c0SRandy Dunlap  * @open_flag:	flags
34456521f891SChristian Brauner  *
34466521f891SChristian Brauner  * Create a temporary file.
34476521f891SChristian Brauner  *
34486521f891SChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
34496521f891SChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
34506521f891SChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
34516521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
34526521f891SChristian Brauner  * raw inode simply passs init_user_ns.
34536521f891SChristian Brauner  */
34546521f891SChristian Brauner struct dentry *vfs_tmpfile(struct user_namespace *mnt_userns,
34556521f891SChristian Brauner 			   struct dentry *dentry, umode_t mode, int open_flag)
3456af7bd4dcSAmir Goldstein {
3457af7bd4dcSAmir Goldstein 	struct dentry *child = NULL;
3458af7bd4dcSAmir Goldstein 	struct inode *dir = dentry->d_inode;
3459af7bd4dcSAmir Goldstein 	struct inode *inode;
3460af7bd4dcSAmir Goldstein 	int error;
3461af7bd4dcSAmir Goldstein 
3462af7bd4dcSAmir Goldstein 	/* we want directory to be writable */
34636521f891SChristian Brauner 	error = inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
3464af7bd4dcSAmir Goldstein 	if (error)
3465af7bd4dcSAmir Goldstein 		goto out_err;
3466af7bd4dcSAmir Goldstein 	error = -EOPNOTSUPP;
3467af7bd4dcSAmir Goldstein 	if (!dir->i_op->tmpfile)
3468af7bd4dcSAmir Goldstein 		goto out_err;
3469af7bd4dcSAmir Goldstein 	error = -ENOMEM;
3470cdf01226SDavid Howells 	child = d_alloc(dentry, &slash_name);
3471af7bd4dcSAmir Goldstein 	if (unlikely(!child))
3472af7bd4dcSAmir Goldstein 		goto out_err;
3473549c7297SChristian Brauner 	error = dir->i_op->tmpfile(mnt_userns, dir, child, mode);
3474af7bd4dcSAmir Goldstein 	if (error)
3475af7bd4dcSAmir Goldstein 		goto out_err;
3476af7bd4dcSAmir Goldstein 	error = -ENOENT;
3477af7bd4dcSAmir Goldstein 	inode = child->d_inode;
3478af7bd4dcSAmir Goldstein 	if (unlikely(!inode))
3479af7bd4dcSAmir Goldstein 		goto out_err;
3480af7bd4dcSAmir Goldstein 	if (!(open_flag & O_EXCL)) {
3481af7bd4dcSAmir Goldstein 		spin_lock(&inode->i_lock);
3482af7bd4dcSAmir Goldstein 		inode->i_state |= I_LINKABLE;
3483af7bd4dcSAmir Goldstein 		spin_unlock(&inode->i_lock);
3484af7bd4dcSAmir Goldstein 	}
3485a2d2329eSChristian Brauner 	ima_post_create_tmpfile(mnt_userns, inode);
3486af7bd4dcSAmir Goldstein 	return child;
3487af7bd4dcSAmir Goldstein 
3488af7bd4dcSAmir Goldstein out_err:
3489af7bd4dcSAmir Goldstein 	dput(child);
3490af7bd4dcSAmir Goldstein 	return ERR_PTR(error);
3491af7bd4dcSAmir Goldstein }
3492af7bd4dcSAmir Goldstein EXPORT_SYMBOL(vfs_tmpfile);
3493af7bd4dcSAmir Goldstein 
3494c8a53ee5SAl Viro static int do_tmpfile(struct nameidata *nd, unsigned flags,
349560545d0dSAl Viro 		const struct open_flags *op,
34963ec2eef1SAl Viro 		struct file *file)
349760545d0dSAl Viro {
34986521f891SChristian Brauner 	struct user_namespace *mnt_userns;
3499625b6d10SAl Viro 	struct dentry *child;
3500625b6d10SAl Viro 	struct path path;
3501c8a53ee5SAl Viro 	int error = path_lookupat(nd, flags | LOOKUP_DIRECTORY, &path);
350260545d0dSAl Viro 	if (unlikely(error))
350360545d0dSAl Viro 		return error;
3504625b6d10SAl Viro 	error = mnt_want_write(path.mnt);
350560545d0dSAl Viro 	if (unlikely(error))
350660545d0dSAl Viro 		goto out;
35076521f891SChristian Brauner 	mnt_userns = mnt_user_ns(path.mnt);
35086521f891SChristian Brauner 	child = vfs_tmpfile(mnt_userns, path.dentry, op->mode, op->open_flag);
3509af7bd4dcSAmir Goldstein 	error = PTR_ERR(child);
3510684e73beSHirofumi Nakagawa 	if (IS_ERR(child))
351160545d0dSAl Viro 		goto out2;
3512625b6d10SAl Viro 	dput(path.dentry);
3513625b6d10SAl Viro 	path.dentry = child;
3514c8a53ee5SAl Viro 	audit_inode(nd->name, child, 0);
351569a91c23SEric Rannaud 	/* Don't check for other permissions, the inode was just created */
3516549c7297SChristian Brauner 	error = may_open(mnt_userns, &path, 0, op->open_flag);
35171e8f44f1SAl Viro 	if (!error)
35181e8f44f1SAl Viro 		error = vfs_open(&path, file);
351960545d0dSAl Viro out2:
3520625b6d10SAl Viro 	mnt_drop_write(path.mnt);
352160545d0dSAl Viro out:
3522625b6d10SAl Viro 	path_put(&path);
352360545d0dSAl Viro 	return error;
352460545d0dSAl Viro }
352560545d0dSAl Viro 
35266ac08709SAl Viro static int do_o_path(struct nameidata *nd, unsigned flags, struct file *file)
35276ac08709SAl Viro {
35286ac08709SAl Viro 	struct path path;
35296ac08709SAl Viro 	int error = path_lookupat(nd, flags, &path);
35306ac08709SAl Viro 	if (!error) {
35316ac08709SAl Viro 		audit_inode(nd->name, path.dentry, 0);
3532ae2bb293SAl Viro 		error = vfs_open(&path, file);
35336ac08709SAl Viro 		path_put(&path);
35346ac08709SAl Viro 	}
35356ac08709SAl Viro 	return error;
35366ac08709SAl Viro }
35376ac08709SAl Viro 
3538c8a53ee5SAl Viro static struct file *path_openat(struct nameidata *nd,
3539c8a53ee5SAl Viro 			const struct open_flags *op, unsigned flags)
35401da177e4SLinus Torvalds {
354130d90494SAl Viro 	struct file *file;
354213aab428SAl Viro 	int error;
354331e6b01fSNick Piggin 
3544ea73ea72SAl Viro 	file = alloc_empty_file(op->open_flag, current_cred());
35451afc99beSAl Viro 	if (IS_ERR(file))
35461afc99beSAl Viro 		return file;
354731e6b01fSNick Piggin 
3548bb458c64SAl Viro 	if (unlikely(file->f_flags & __O_TMPFILE)) {
35493ec2eef1SAl Viro 		error = do_tmpfile(nd, flags, op, file);
35505f336e72SAl Viro 	} else if (unlikely(file->f_flags & O_PATH)) {
35516ac08709SAl Viro 		error = do_o_path(nd, flags, file);
35525f336e72SAl Viro 	} else {
35535f336e72SAl Viro 		const char *s = path_init(nd, flags);
35543bdba28bSAl Viro 		while (!(error = link_path_walk(s, nd)) &&
3555c5971b8cSAl Viro 		       (s = open_last_lookups(nd, file, op)) != NULL)
35561ccac622SAl Viro 			;
3557c5971b8cSAl Viro 		if (!error)
3558c5971b8cSAl Viro 			error = do_open(nd, file, op);
3559deb106c6SAl Viro 		terminate_walk(nd);
35605f336e72SAl Viro 	}
35617c1c01ecSAl Viro 	if (likely(!error)) {
3562aad888f8SAl Viro 		if (likely(file->f_mode & FMODE_OPENED))
35637c1c01ecSAl Viro 			return file;
35647c1c01ecSAl Viro 		WARN_ON(1);
35657c1c01ecSAl Viro 		error = -EINVAL;
3566015c3bbcSMiklos Szeredi 	}
35677c1c01ecSAl Viro 	fput(file);
35682675a4ebSAl Viro 	if (error == -EOPENSTALE) {
35692675a4ebSAl Viro 		if (flags & LOOKUP_RCU)
35702675a4ebSAl Viro 			error = -ECHILD;
35712675a4ebSAl Viro 		else
35722675a4ebSAl Viro 			error = -ESTALE;
35732675a4ebSAl Viro 	}
35747c1c01ecSAl Viro 	return ERR_PTR(error);
3575de459215SKirill Korotaev }
35761da177e4SLinus Torvalds 
3577669abf4eSJeff Layton struct file *do_filp_open(int dfd, struct filename *pathname,
3578f9652e10SAl Viro 		const struct open_flags *op)
357913aab428SAl Viro {
35809883d185SAl Viro 	struct nameidata nd;
3581f9652e10SAl Viro 	int flags = op->lookup_flags;
358213aab428SAl Viro 	struct file *filp;
358313aab428SAl Viro 
358406422964SAl Viro 	set_nameidata(&nd, dfd, pathname, NULL);
3585c8a53ee5SAl Viro 	filp = path_openat(&nd, op, flags | LOOKUP_RCU);
358613aab428SAl Viro 	if (unlikely(filp == ERR_PTR(-ECHILD)))
3587c8a53ee5SAl Viro 		filp = path_openat(&nd, op, flags);
358813aab428SAl Viro 	if (unlikely(filp == ERR_PTR(-ESTALE)))
3589c8a53ee5SAl Viro 		filp = path_openat(&nd, op, flags | LOOKUP_REVAL);
35909883d185SAl Viro 	restore_nameidata();
359113aab428SAl Viro 	return filp;
359213aab428SAl Viro }
359313aab428SAl Viro 
3594ffb37ca3SAl Viro struct file *do_file_open_root(const struct path *root,
3595f9652e10SAl Viro 		const char *name, const struct open_flags *op)
359673d049a4SAl Viro {
35979883d185SAl Viro 	struct nameidata nd;
359873d049a4SAl Viro 	struct file *file;
359951689104SPaul Moore 	struct filename *filename;
3600bcba1e7dSAl Viro 	int flags = op->lookup_flags;
360173d049a4SAl Viro 
3602ffb37ca3SAl Viro 	if (d_is_symlink(root->dentry) && op->intent & LOOKUP_OPEN)
360373d049a4SAl Viro 		return ERR_PTR(-ELOOP);
360473d049a4SAl Viro 
360551689104SPaul Moore 	filename = getname_kernel(name);
3606a1c83681SViresh Kumar 	if (IS_ERR(filename))
360751689104SPaul Moore 		return ERR_CAST(filename);
360851689104SPaul Moore 
360906422964SAl Viro 	set_nameidata(&nd, -1, filename, root);
3610c8a53ee5SAl Viro 	file = path_openat(&nd, op, flags | LOOKUP_RCU);
361173d049a4SAl Viro 	if (unlikely(file == ERR_PTR(-ECHILD)))
3612c8a53ee5SAl Viro 		file = path_openat(&nd, op, flags);
361373d049a4SAl Viro 	if (unlikely(file == ERR_PTR(-ESTALE)))
3614c8a53ee5SAl Viro 		file = path_openat(&nd, op, flags | LOOKUP_REVAL);
36159883d185SAl Viro 	restore_nameidata();
361651689104SPaul Moore 	putname(filename);
361773d049a4SAl Viro 	return file;
361873d049a4SAl Viro }
361973d049a4SAl Viro 
3620584d3226SDmitry Kadashev static struct dentry *__filename_create(int dfd, struct filename *name,
36211ac12b4bSJeff Layton 				struct path *path, unsigned int lookup_flags)
36221da177e4SLinus Torvalds {
3623c663e5d8SChristoph Hellwig 	struct dentry *dentry = ERR_PTR(-EEXIST);
3624391172c4SAl Viro 	struct qstr last;
3625391172c4SAl Viro 	int type;
3626c30dabfeSJan Kara 	int err2;
36271ac12b4bSJeff Layton 	int error;
36281ac12b4bSJeff Layton 	bool is_dir = (lookup_flags & LOOKUP_DIRECTORY);
36291ac12b4bSJeff Layton 
36301ac12b4bSJeff Layton 	/*
36311ac12b4bSJeff Layton 	 * Note that only LOOKUP_REVAL and LOOKUP_DIRECTORY matter here. Any
36321ac12b4bSJeff Layton 	 * other flags passed in are ignored!
36331ac12b4bSJeff Layton 	 */
36341ac12b4bSJeff Layton 	lookup_flags &= LOOKUP_REVAL;
36351ac12b4bSJeff Layton 
3636584d3226SDmitry Kadashev 	error = __filename_parentat(dfd, name, lookup_flags, path, &last, &type);
36370ee50b47SDmitry Kadashev 	if (error)
36380ee50b47SDmitry Kadashev 		return ERR_PTR(error);
36391da177e4SLinus Torvalds 
3640c663e5d8SChristoph Hellwig 	/*
3641c663e5d8SChristoph Hellwig 	 * Yucky last component or no last component at all?
3642c663e5d8SChristoph Hellwig 	 * (foo/., foo/.., /////)
3643c663e5d8SChristoph Hellwig 	 */
36445c31b6ceSAl Viro 	if (unlikely(type != LAST_NORM))
3645ed75e95dSAl Viro 		goto out;
3646c663e5d8SChristoph Hellwig 
3647c30dabfeSJan Kara 	/* don't fail immediately if it's r/o, at least try to report other errors */
3648391172c4SAl Viro 	err2 = mnt_want_write(path->mnt);
3649c663e5d8SChristoph Hellwig 	/*
3650c663e5d8SChristoph Hellwig 	 * Do the final lookup.
3651c663e5d8SChristoph Hellwig 	 */
3652391172c4SAl Viro 	lookup_flags |= LOOKUP_CREATE | LOOKUP_EXCL;
36535955102cSAl Viro 	inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
3654391172c4SAl Viro 	dentry = __lookup_hash(&last, path->dentry, lookup_flags);
36551da177e4SLinus Torvalds 	if (IS_ERR(dentry))
3656a8104a9fSAl Viro 		goto unlock;
3657c663e5d8SChristoph Hellwig 
3658a8104a9fSAl Viro 	error = -EEXIST;
3659b18825a7SDavid Howells 	if (d_is_positive(dentry))
3660a8104a9fSAl Viro 		goto fail;
3661b18825a7SDavid Howells 
3662c663e5d8SChristoph Hellwig 	/*
3663c663e5d8SChristoph Hellwig 	 * Special case - lookup gave negative, but... we had foo/bar/
3664c663e5d8SChristoph Hellwig 	 * From the vfs_mknod() POV we just have a negative dentry -
3665c663e5d8SChristoph Hellwig 	 * all is fine. Let's be bastards - you had / on the end, you've
3666c663e5d8SChristoph Hellwig 	 * been asking for (non-existent) directory. -ENOENT for you.
3667c663e5d8SChristoph Hellwig 	 */
3668391172c4SAl Viro 	if (unlikely(!is_dir && last.name[last.len])) {
3669a8104a9fSAl Viro 		error = -ENOENT;
3670ed75e95dSAl Viro 		goto fail;
3671e9baf6e5SAl Viro 	}
3672c30dabfeSJan Kara 	if (unlikely(err2)) {
3673c30dabfeSJan Kara 		error = err2;
3674a8104a9fSAl Viro 		goto fail;
3675c30dabfeSJan Kara 	}
3676e9baf6e5SAl Viro 	return dentry;
36771da177e4SLinus Torvalds fail:
3678a8104a9fSAl Viro 	dput(dentry);
3679a8104a9fSAl Viro 	dentry = ERR_PTR(error);
3680a8104a9fSAl Viro unlock:
36815955102cSAl Viro 	inode_unlock(path->dentry->d_inode);
3682c30dabfeSJan Kara 	if (!err2)
3683391172c4SAl Viro 		mnt_drop_write(path->mnt);
3684ed75e95dSAl Viro out:
3685391172c4SAl Viro 	path_put(path);
3686ed75e95dSAl Viro 	return dentry;
3687dae6ad8fSAl Viro }
3688fa14a0b8SAl Viro 
3689584d3226SDmitry Kadashev static inline struct dentry *filename_create(int dfd, struct filename *name,
3690584d3226SDmitry Kadashev 				struct path *path, unsigned int lookup_flags)
3691584d3226SDmitry Kadashev {
3692584d3226SDmitry Kadashev 	struct dentry *res = __filename_create(dfd, name, path, lookup_flags);
3693584d3226SDmitry Kadashev 
3694584d3226SDmitry Kadashev 	putname(name);
3695584d3226SDmitry Kadashev 	return res;
3696584d3226SDmitry Kadashev }
3697584d3226SDmitry Kadashev 
3698fa14a0b8SAl Viro struct dentry *kern_path_create(int dfd, const char *pathname,
3699fa14a0b8SAl Viro 				struct path *path, unsigned int lookup_flags)
3700fa14a0b8SAl Viro {
3701181c37b6SAl Viro 	return filename_create(dfd, getname_kernel(pathname),
3702181c37b6SAl Viro 				path, lookup_flags);
3703fa14a0b8SAl Viro }
3704dae6ad8fSAl Viro EXPORT_SYMBOL(kern_path_create);
3705dae6ad8fSAl Viro 
3706921a1650SAl Viro void done_path_create(struct path *path, struct dentry *dentry)
3707921a1650SAl Viro {
3708921a1650SAl Viro 	dput(dentry);
37095955102cSAl Viro 	inode_unlock(path->dentry->d_inode);
3710a8104a9fSAl Viro 	mnt_drop_write(path->mnt);
3711921a1650SAl Viro 	path_put(path);
3712921a1650SAl Viro }
3713921a1650SAl Viro EXPORT_SYMBOL(done_path_create);
3714921a1650SAl Viro 
3715520ae687SAl Viro inline struct dentry *user_path_create(int dfd, const char __user *pathname,
37161ac12b4bSJeff Layton 				struct path *path, unsigned int lookup_flags)
3717dae6ad8fSAl Viro {
3718181c37b6SAl Viro 	return filename_create(dfd, getname(pathname), path, lookup_flags);
3719dae6ad8fSAl Viro }
3720dae6ad8fSAl Viro EXPORT_SYMBOL(user_path_create);
3721dae6ad8fSAl Viro 
37226521f891SChristian Brauner /**
37236521f891SChristian Brauner  * vfs_mknod - create device node or file
37246521f891SChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
37256521f891SChristian Brauner  * @dir:	inode of @dentry
37266521f891SChristian Brauner  * @dentry:	pointer to dentry of the base directory
37276521f891SChristian Brauner  * @mode:	mode of the new device node or file
37286521f891SChristian Brauner  * @dev:	device number of device to create
37296521f891SChristian Brauner  *
37306521f891SChristian Brauner  * Create a device node or file.
37316521f891SChristian Brauner  *
37326521f891SChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
37336521f891SChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
37346521f891SChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
37356521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
37366521f891SChristian Brauner  * raw inode simply passs init_user_ns.
37376521f891SChristian Brauner  */
37386521f891SChristian Brauner int vfs_mknod(struct user_namespace *mnt_userns, struct inode *dir,
37396521f891SChristian Brauner 	      struct dentry *dentry, umode_t mode, dev_t dev)
37401da177e4SLinus Torvalds {
3741a3c751a5SMiklos Szeredi 	bool is_whiteout = S_ISCHR(mode) && dev == WHITEOUT_DEV;
37426521f891SChristian Brauner 	int error = may_create(mnt_userns, dir, dentry);
37431da177e4SLinus Torvalds 
37441da177e4SLinus Torvalds 	if (error)
37451da177e4SLinus Torvalds 		return error;
37461da177e4SLinus Torvalds 
3747a3c751a5SMiklos Szeredi 	if ((S_ISCHR(mode) || S_ISBLK(mode)) && !is_whiteout &&
3748a3c751a5SMiklos Szeredi 	    !capable(CAP_MKNOD))
37491da177e4SLinus Torvalds 		return -EPERM;
37501da177e4SLinus Torvalds 
3751acfa4380SAl Viro 	if (!dir->i_op->mknod)
37521da177e4SLinus Torvalds 		return -EPERM;
37531da177e4SLinus Torvalds 
375408ce5f16SSerge E. Hallyn 	error = devcgroup_inode_mknod(mode, dev);
375508ce5f16SSerge E. Hallyn 	if (error)
375608ce5f16SSerge E. Hallyn 		return error;
375708ce5f16SSerge E. Hallyn 
37581da177e4SLinus Torvalds 	error = security_inode_mknod(dir, dentry, mode, dev);
37591da177e4SLinus Torvalds 	if (error)
37601da177e4SLinus Torvalds 		return error;
37611da177e4SLinus Torvalds 
3762549c7297SChristian Brauner 	error = dir->i_op->mknod(mnt_userns, dir, dentry, mode, dev);
3763a74574aaSStephen Smalley 	if (!error)
3764f38aa942SAmy Griffis 		fsnotify_create(dir, dentry);
37651da177e4SLinus Torvalds 	return error;
37661da177e4SLinus Torvalds }
37674d359507SAl Viro EXPORT_SYMBOL(vfs_mknod);
37681da177e4SLinus Torvalds 
3769f69aac00SAl Viro static int may_mknod(umode_t mode)
3770463c3197SDave Hansen {
3771463c3197SDave Hansen 	switch (mode & S_IFMT) {
3772463c3197SDave Hansen 	case S_IFREG:
3773463c3197SDave Hansen 	case S_IFCHR:
3774463c3197SDave Hansen 	case S_IFBLK:
3775463c3197SDave Hansen 	case S_IFIFO:
3776463c3197SDave Hansen 	case S_IFSOCK:
3777463c3197SDave Hansen 	case 0: /* zero mode translates to S_IFREG */
3778463c3197SDave Hansen 		return 0;
3779463c3197SDave Hansen 	case S_IFDIR:
3780463c3197SDave Hansen 		return -EPERM;
3781463c3197SDave Hansen 	default:
3782463c3197SDave Hansen 		return -EINVAL;
3783463c3197SDave Hansen 	}
3784463c3197SDave Hansen }
3785463c3197SDave Hansen 
378645f30dabSDmitry Kadashev static int do_mknodat(int dfd, struct filename *name, umode_t mode,
378787c4e192SDominik Brodowski 		unsigned int dev)
37881da177e4SLinus Torvalds {
37896521f891SChristian Brauner 	struct user_namespace *mnt_userns;
37901da177e4SLinus Torvalds 	struct dentry *dentry;
3791dae6ad8fSAl Viro 	struct path path;
3792dae6ad8fSAl Viro 	int error;
3793972567f1SJeff Layton 	unsigned int lookup_flags = 0;
37941da177e4SLinus Torvalds 
37958e4bfca1SAl Viro 	error = may_mknod(mode);
37968e4bfca1SAl Viro 	if (error)
37977797251bSDmitry Kadashev 		goto out1;
3798972567f1SJeff Layton retry:
37997797251bSDmitry Kadashev 	dentry = __filename_create(dfd, name, &path, lookup_flags);
38007797251bSDmitry Kadashev 	error = PTR_ERR(dentry);
3801dae6ad8fSAl Viro 	if (IS_ERR(dentry))
38027797251bSDmitry Kadashev 		goto out1;
38032ad94ae6SAl Viro 
3804dae6ad8fSAl Viro 	if (!IS_POSIXACL(path.dentry->d_inode))
3805ce3b0f8dSAl Viro 		mode &= ~current_umask();
3806dae6ad8fSAl Viro 	error = security_path_mknod(&path, dentry, mode, dev);
3807be6d3e56SKentaro Takeda 	if (error)
38087797251bSDmitry Kadashev 		goto out2;
38096521f891SChristian Brauner 
38106521f891SChristian Brauner 	mnt_userns = mnt_user_ns(path.mnt);
38111da177e4SLinus Torvalds 	switch (mode & S_IFMT) {
38121da177e4SLinus Torvalds 		case 0: case S_IFREG:
38136521f891SChristian Brauner 			error = vfs_create(mnt_userns, path.dentry->d_inode,
38146521f891SChristian Brauner 					   dentry, mode, true);
381505d1a717SMimi Zohar 			if (!error)
3816a2d2329eSChristian Brauner 				ima_post_path_mknod(mnt_userns, dentry);
38171da177e4SLinus Torvalds 			break;
38181da177e4SLinus Torvalds 		case S_IFCHR: case S_IFBLK:
38196521f891SChristian Brauner 			error = vfs_mknod(mnt_userns, path.dentry->d_inode,
38206521f891SChristian Brauner 					  dentry, mode, new_decode_dev(dev));
38211da177e4SLinus Torvalds 			break;
38221da177e4SLinus Torvalds 		case S_IFIFO: case S_IFSOCK:
38236521f891SChristian Brauner 			error = vfs_mknod(mnt_userns, path.dentry->d_inode,
38246521f891SChristian Brauner 					  dentry, mode, 0);
38251da177e4SLinus Torvalds 			break;
38261da177e4SLinus Torvalds 	}
38277797251bSDmitry Kadashev out2:
3828921a1650SAl Viro 	done_path_create(&path, dentry);
3829972567f1SJeff Layton 	if (retry_estale(error, lookup_flags)) {
3830972567f1SJeff Layton 		lookup_flags |= LOOKUP_REVAL;
3831972567f1SJeff Layton 		goto retry;
3832972567f1SJeff Layton 	}
38337797251bSDmitry Kadashev out1:
38347797251bSDmitry Kadashev 	putname(name);
38351da177e4SLinus Torvalds 	return error;
38361da177e4SLinus Torvalds }
38371da177e4SLinus Torvalds 
383887c4e192SDominik Brodowski SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, umode_t, mode,
383987c4e192SDominik Brodowski 		unsigned int, dev)
384087c4e192SDominik Brodowski {
38417797251bSDmitry Kadashev 	return do_mknodat(dfd, getname(filename), mode, dev);
384287c4e192SDominik Brodowski }
384387c4e192SDominik Brodowski 
38448208a22bSAl Viro SYSCALL_DEFINE3(mknod, const char __user *, filename, umode_t, mode, unsigned, dev)
38455590ff0dSUlrich Drepper {
38467797251bSDmitry Kadashev 	return do_mknodat(AT_FDCWD, getname(filename), mode, dev);
38475590ff0dSUlrich Drepper }
38485590ff0dSUlrich Drepper 
38496521f891SChristian Brauner /**
38506521f891SChristian Brauner  * vfs_mkdir - create directory
38516521f891SChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
38526521f891SChristian Brauner  * @dir:	inode of @dentry
38536521f891SChristian Brauner  * @dentry:	pointer to dentry of the base directory
38546521f891SChristian Brauner  * @mode:	mode of the new directory
38556521f891SChristian Brauner  *
38566521f891SChristian Brauner  * Create a directory.
38576521f891SChristian Brauner  *
38586521f891SChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
38596521f891SChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
38606521f891SChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
38616521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
38626521f891SChristian Brauner  * raw inode simply passs init_user_ns.
38636521f891SChristian Brauner  */
38646521f891SChristian Brauner int vfs_mkdir(struct user_namespace *mnt_userns, struct inode *dir,
38656521f891SChristian Brauner 	      struct dentry *dentry, umode_t mode)
38661da177e4SLinus Torvalds {
38676521f891SChristian Brauner 	int error = may_create(mnt_userns, dir, dentry);
38688de52778SAl Viro 	unsigned max_links = dir->i_sb->s_max_links;
38691da177e4SLinus Torvalds 
38701da177e4SLinus Torvalds 	if (error)
38711da177e4SLinus Torvalds 		return error;
38721da177e4SLinus Torvalds 
3873acfa4380SAl Viro 	if (!dir->i_op->mkdir)
38741da177e4SLinus Torvalds 		return -EPERM;
38751da177e4SLinus Torvalds 
38761da177e4SLinus Torvalds 	mode &= (S_IRWXUGO|S_ISVTX);
38771da177e4SLinus Torvalds 	error = security_inode_mkdir(dir, dentry, mode);
38781da177e4SLinus Torvalds 	if (error)
38791da177e4SLinus Torvalds 		return error;
38801da177e4SLinus Torvalds 
38818de52778SAl Viro 	if (max_links && dir->i_nlink >= max_links)
38828de52778SAl Viro 		return -EMLINK;
38838de52778SAl Viro 
3884549c7297SChristian Brauner 	error = dir->i_op->mkdir(mnt_userns, dir, dentry, mode);
3885a74574aaSStephen Smalley 	if (!error)
3886f38aa942SAmy Griffis 		fsnotify_mkdir(dir, dentry);
38871da177e4SLinus Torvalds 	return error;
38881da177e4SLinus Torvalds }
38894d359507SAl Viro EXPORT_SYMBOL(vfs_mkdir);
38901da177e4SLinus Torvalds 
389145f30dabSDmitry Kadashev int do_mkdirat(int dfd, struct filename *name, umode_t mode)
38921da177e4SLinus Torvalds {
38936902d925SDave Hansen 	struct dentry *dentry;
3894dae6ad8fSAl Viro 	struct path path;
3895dae6ad8fSAl Viro 	int error;
3896b76d8b82SJeff Layton 	unsigned int lookup_flags = LOOKUP_DIRECTORY;
38971da177e4SLinus Torvalds 
3898b76d8b82SJeff Layton retry:
3899584d3226SDmitry Kadashev 	dentry = __filename_create(dfd, name, &path, lookup_flags);
3900584d3226SDmitry Kadashev 	error = PTR_ERR(dentry);
39016902d925SDave Hansen 	if (IS_ERR(dentry))
3902584d3226SDmitry Kadashev 		goto out_putname;
39036902d925SDave Hansen 
3904dae6ad8fSAl Viro 	if (!IS_POSIXACL(path.dentry->d_inode))
3905ce3b0f8dSAl Viro 		mode &= ~current_umask();
3906dae6ad8fSAl Viro 	error = security_path_mkdir(&path, dentry, mode);
39076521f891SChristian Brauner 	if (!error) {
39086521f891SChristian Brauner 		struct user_namespace *mnt_userns;
39096521f891SChristian Brauner 		mnt_userns = mnt_user_ns(path.mnt);
3910549c7297SChristian Brauner 		error = vfs_mkdir(mnt_userns, path.dentry->d_inode, dentry,
3911549c7297SChristian Brauner 				  mode);
39126521f891SChristian Brauner 	}
3913921a1650SAl Viro 	done_path_create(&path, dentry);
3914b76d8b82SJeff Layton 	if (retry_estale(error, lookup_flags)) {
3915b76d8b82SJeff Layton 		lookup_flags |= LOOKUP_REVAL;
3916b76d8b82SJeff Layton 		goto retry;
3917b76d8b82SJeff Layton 	}
3918584d3226SDmitry Kadashev out_putname:
3919584d3226SDmitry Kadashev 	putname(name);
39201da177e4SLinus Torvalds 	return error;
39211da177e4SLinus Torvalds }
39221da177e4SLinus Torvalds 
39230101db7aSDominik Brodowski SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, umode_t, mode)
39240101db7aSDominik Brodowski {
3925584d3226SDmitry Kadashev 	return do_mkdirat(dfd, getname(pathname), mode);
39260101db7aSDominik Brodowski }
39270101db7aSDominik Brodowski 
3928a218d0fdSAl Viro SYSCALL_DEFINE2(mkdir, const char __user *, pathname, umode_t, mode)
39295590ff0dSUlrich Drepper {
3930584d3226SDmitry Kadashev 	return do_mkdirat(AT_FDCWD, getname(pathname), mode);
39315590ff0dSUlrich Drepper }
39325590ff0dSUlrich Drepper 
39336521f891SChristian Brauner /**
39346521f891SChristian Brauner  * vfs_rmdir - remove directory
39356521f891SChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
39366521f891SChristian Brauner  * @dir:	inode of @dentry
39376521f891SChristian Brauner  * @dentry:	pointer to dentry of the base directory
39386521f891SChristian Brauner  *
39396521f891SChristian Brauner  * Remove a directory.
39406521f891SChristian Brauner  *
39416521f891SChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
39426521f891SChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
39436521f891SChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
39446521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
39456521f891SChristian Brauner  * raw inode simply passs init_user_ns.
39466521f891SChristian Brauner  */
39476521f891SChristian Brauner int vfs_rmdir(struct user_namespace *mnt_userns, struct inode *dir,
39486521f891SChristian Brauner 		     struct dentry *dentry)
39491da177e4SLinus Torvalds {
39506521f891SChristian Brauner 	int error = may_delete(mnt_userns, dir, dentry, 1);
39511da177e4SLinus Torvalds 
39521da177e4SLinus Torvalds 	if (error)
39531da177e4SLinus Torvalds 		return error;
39541da177e4SLinus Torvalds 
3955acfa4380SAl Viro 	if (!dir->i_op->rmdir)
39561da177e4SLinus Torvalds 		return -EPERM;
39571da177e4SLinus Torvalds 
39581d2ef590SAl Viro 	dget(dentry);
39595955102cSAl Viro 	inode_lock(dentry->d_inode);
3960912dbc15SSage Weil 
39611da177e4SLinus Torvalds 	error = -EBUSY;
39627af1364fSEric W. Biederman 	if (is_local_mountpoint(dentry))
3963912dbc15SSage Weil 		goto out;
3964912dbc15SSage Weil 
39651da177e4SLinus Torvalds 	error = security_inode_rmdir(dir, dentry);
3966912dbc15SSage Weil 	if (error)
3967912dbc15SSage Weil 		goto out;
3968912dbc15SSage Weil 
39691da177e4SLinus Torvalds 	error = dir->i_op->rmdir(dir, dentry);
3970912dbc15SSage Weil 	if (error)
3971912dbc15SSage Weil 		goto out;
3972912dbc15SSage Weil 
39738767712fSAl Viro 	shrink_dcache_parent(dentry);
39741da177e4SLinus Torvalds 	dentry->d_inode->i_flags |= S_DEAD;
3975d83c49f3SAl Viro 	dont_mount(dentry);
39768ed936b5SEric W. Biederman 	detach_mounts(dentry);
3977116b9731SAmir Goldstein 	fsnotify_rmdir(dir, dentry);
39781da177e4SLinus Torvalds 
3979912dbc15SSage Weil out:
39805955102cSAl Viro 	inode_unlock(dentry->d_inode);
39811d2ef590SAl Viro 	dput(dentry);
3982912dbc15SSage Weil 	if (!error)
3983912dbc15SSage Weil 		d_delete(dentry);
39841da177e4SLinus Torvalds 	return error;
39851da177e4SLinus Torvalds }
39864d359507SAl Viro EXPORT_SYMBOL(vfs_rmdir);
39871da177e4SLinus Torvalds 
398845f30dabSDmitry Kadashev int do_rmdir(int dfd, struct filename *name)
39891da177e4SLinus Torvalds {
39906521f891SChristian Brauner 	struct user_namespace *mnt_userns;
39910ee50b47SDmitry Kadashev 	int error;
39921da177e4SLinus Torvalds 	struct dentry *dentry;
3993f5beed75SAl Viro 	struct path path;
3994f5beed75SAl Viro 	struct qstr last;
3995f5beed75SAl Viro 	int type;
3996c6ee9206SJeff Layton 	unsigned int lookup_flags = 0;
3997c6ee9206SJeff Layton retry:
39980ee50b47SDmitry Kadashev 	error = __filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
39990ee50b47SDmitry Kadashev 	if (error)
40000ee50b47SDmitry Kadashev 		goto exit1;
40011da177e4SLinus Torvalds 
4002f5beed75SAl Viro 	switch (type) {
40031da177e4SLinus Torvalds 	case LAST_DOTDOT:
40041da177e4SLinus Torvalds 		error = -ENOTEMPTY;
40050ee50b47SDmitry Kadashev 		goto exit2;
40061da177e4SLinus Torvalds 	case LAST_DOT:
40071da177e4SLinus Torvalds 		error = -EINVAL;
40080ee50b47SDmitry Kadashev 		goto exit2;
40091da177e4SLinus Torvalds 	case LAST_ROOT:
40101da177e4SLinus Torvalds 		error = -EBUSY;
40110ee50b47SDmitry Kadashev 		goto exit2;
40121da177e4SLinus Torvalds 	}
40130612d9fbSOGAWA Hirofumi 
4014f5beed75SAl Viro 	error = mnt_want_write(path.mnt);
4015c30dabfeSJan Kara 	if (error)
40160ee50b47SDmitry Kadashev 		goto exit2;
40170612d9fbSOGAWA Hirofumi 
40185955102cSAl Viro 	inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
4019f5beed75SAl Viro 	dentry = __lookup_hash(&last, path.dentry, lookup_flags);
40201da177e4SLinus Torvalds 	error = PTR_ERR(dentry);
40216902d925SDave Hansen 	if (IS_ERR(dentry))
40220ee50b47SDmitry Kadashev 		goto exit3;
4023e6bc45d6STheodore Ts'o 	if (!dentry->d_inode) {
4024e6bc45d6STheodore Ts'o 		error = -ENOENT;
40250ee50b47SDmitry Kadashev 		goto exit4;
4026e6bc45d6STheodore Ts'o 	}
4027f5beed75SAl Viro 	error = security_path_rmdir(&path, dentry);
4028be6d3e56SKentaro Takeda 	if (error)
40290ee50b47SDmitry Kadashev 		goto exit4;
40306521f891SChristian Brauner 	mnt_userns = mnt_user_ns(path.mnt);
40316521f891SChristian Brauner 	error = vfs_rmdir(mnt_userns, path.dentry->d_inode, dentry);
40320ee50b47SDmitry Kadashev exit4:
40331da177e4SLinus Torvalds 	dput(dentry);
40340ee50b47SDmitry Kadashev exit3:
40355955102cSAl Viro 	inode_unlock(path.dentry->d_inode);
4036f5beed75SAl Viro 	mnt_drop_write(path.mnt);
40370ee50b47SDmitry Kadashev exit2:
4038f5beed75SAl Viro 	path_put(&path);
4039c6ee9206SJeff Layton 	if (retry_estale(error, lookup_flags)) {
4040c6ee9206SJeff Layton 		lookup_flags |= LOOKUP_REVAL;
4041c6ee9206SJeff Layton 		goto retry;
4042c6ee9206SJeff Layton 	}
40430ee50b47SDmitry Kadashev exit1:
404424fb33d4SAl Viro 	putname(name);
40451da177e4SLinus Torvalds 	return error;
40461da177e4SLinus Torvalds }
40471da177e4SLinus Torvalds 
40483cdad428SHeiko Carstens SYSCALL_DEFINE1(rmdir, const char __user *, pathname)
40495590ff0dSUlrich Drepper {
4050e24ab0efSChristoph Hellwig 	return do_rmdir(AT_FDCWD, getname(pathname));
40515590ff0dSUlrich Drepper }
40525590ff0dSUlrich Drepper 
4053b21996e3SJ. Bruce Fields /**
4054b21996e3SJ. Bruce Fields  * vfs_unlink - unlink a filesystem object
40556521f891SChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
4056b21996e3SJ. Bruce Fields  * @dir:	parent directory
4057b21996e3SJ. Bruce Fields  * @dentry:	victim
4058b21996e3SJ. Bruce Fields  * @delegated_inode: returns victim inode, if the inode is delegated.
4059b21996e3SJ. Bruce Fields  *
4060b21996e3SJ. Bruce Fields  * The caller must hold dir->i_mutex.
4061b21996e3SJ. Bruce Fields  *
4062b21996e3SJ. Bruce Fields  * If vfs_unlink discovers a delegation, it will return -EWOULDBLOCK and
4063b21996e3SJ. Bruce Fields  * return a reference to the inode in delegated_inode.  The caller
4064b21996e3SJ. Bruce Fields  * should then break the delegation on that inode and retry.  Because
4065b21996e3SJ. Bruce Fields  * breaking a delegation may take a long time, the caller should drop
4066b21996e3SJ. Bruce Fields  * dir->i_mutex before doing so.
4067b21996e3SJ. Bruce Fields  *
4068b21996e3SJ. Bruce Fields  * Alternatively, a caller may pass NULL for delegated_inode.  This may
4069b21996e3SJ. Bruce Fields  * be appropriate for callers that expect the underlying filesystem not
4070b21996e3SJ. Bruce Fields  * to be NFS exported.
40716521f891SChristian Brauner  *
40726521f891SChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
40736521f891SChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
40746521f891SChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
40756521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
40766521f891SChristian Brauner  * raw inode simply passs init_user_ns.
4077b21996e3SJ. Bruce Fields  */
40786521f891SChristian Brauner int vfs_unlink(struct user_namespace *mnt_userns, struct inode *dir,
40796521f891SChristian Brauner 	       struct dentry *dentry, struct inode **delegated_inode)
40801da177e4SLinus Torvalds {
40819accbb97SJ. Bruce Fields 	struct inode *target = dentry->d_inode;
40826521f891SChristian Brauner 	int error = may_delete(mnt_userns, dir, dentry, 0);
40831da177e4SLinus Torvalds 
40841da177e4SLinus Torvalds 	if (error)
40851da177e4SLinus Torvalds 		return error;
40861da177e4SLinus Torvalds 
4087acfa4380SAl Viro 	if (!dir->i_op->unlink)
40881da177e4SLinus Torvalds 		return -EPERM;
40891da177e4SLinus Torvalds 
40905955102cSAl Viro 	inode_lock(target);
409151cc3a66SHugh Dickins 	if (IS_SWAPFILE(target))
409251cc3a66SHugh Dickins 		error = -EPERM;
409351cc3a66SHugh Dickins 	else if (is_local_mountpoint(dentry))
40941da177e4SLinus Torvalds 		error = -EBUSY;
40951da177e4SLinus Torvalds 	else {
40961da177e4SLinus Torvalds 		error = security_inode_unlink(dir, dentry);
4097bec1052eSAl Viro 		if (!error) {
40985a14696cSJ. Bruce Fields 			error = try_break_deleg(target, delegated_inode);
40995a14696cSJ. Bruce Fields 			if (error)
4100b21996e3SJ. Bruce Fields 				goto out;
41011da177e4SLinus Torvalds 			error = dir->i_op->unlink(dir, dentry);
41028ed936b5SEric W. Biederman 			if (!error) {
4103d83c49f3SAl Viro 				dont_mount(dentry);
41048ed936b5SEric W. Biederman 				detach_mounts(dentry);
4105116b9731SAmir Goldstein 				fsnotify_unlink(dir, dentry);
41068ed936b5SEric W. Biederman 			}
4107bec1052eSAl Viro 		}
41081da177e4SLinus Torvalds 	}
4109b21996e3SJ. Bruce Fields out:
41105955102cSAl Viro 	inode_unlock(target);
41111da177e4SLinus Torvalds 
41121da177e4SLinus Torvalds 	/* We don't d_delete() NFS sillyrenamed files--they still exist. */
41131da177e4SLinus Torvalds 	if (!error && !(dentry->d_flags & DCACHE_NFSFS_RENAMED)) {
41149accbb97SJ. Bruce Fields 		fsnotify_link_count(target);
41151da177e4SLinus Torvalds 		d_delete(dentry);
41161da177e4SLinus Torvalds 	}
41170eeca283SRobert Love 
41181da177e4SLinus Torvalds 	return error;
41191da177e4SLinus Torvalds }
41204d359507SAl Viro EXPORT_SYMBOL(vfs_unlink);
41211da177e4SLinus Torvalds 
41221da177e4SLinus Torvalds /*
41231da177e4SLinus Torvalds  * Make sure that the actual truncation of the file will occur outside its
41241b1dcc1bSJes Sorensen  * directory's i_mutex.  Truncate can take a long time if there is a lot of
41251da177e4SLinus Torvalds  * writeout happening, and we don't want to prevent access to the directory
41261da177e4SLinus Torvalds  * while waiting on the I/O.
41271da177e4SLinus Torvalds  */
412845f30dabSDmitry Kadashev int do_unlinkat(int dfd, struct filename *name)
41291da177e4SLinus Torvalds {
41302ad94ae6SAl Viro 	int error;
41311da177e4SLinus Torvalds 	struct dentry *dentry;
4132f5beed75SAl Viro 	struct path path;
4133f5beed75SAl Viro 	struct qstr last;
4134f5beed75SAl Viro 	int type;
41351da177e4SLinus Torvalds 	struct inode *inode = NULL;
4136b21996e3SJ. Bruce Fields 	struct inode *delegated_inode = NULL;
41375d18f813SJeff Layton 	unsigned int lookup_flags = 0;
41385d18f813SJeff Layton retry:
41390ee50b47SDmitry Kadashev 	error = __filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
41400ee50b47SDmitry Kadashev 	if (error)
41410ee50b47SDmitry Kadashev 		goto exit1;
41422ad94ae6SAl Viro 
41431da177e4SLinus Torvalds 	error = -EISDIR;
4144f5beed75SAl Viro 	if (type != LAST_NORM)
41450ee50b47SDmitry Kadashev 		goto exit2;
41460612d9fbSOGAWA Hirofumi 
4147f5beed75SAl Viro 	error = mnt_want_write(path.mnt);
4148c30dabfeSJan Kara 	if (error)
41490ee50b47SDmitry Kadashev 		goto exit2;
4150b21996e3SJ. Bruce Fields retry_deleg:
41515955102cSAl Viro 	inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
4152f5beed75SAl Viro 	dentry = __lookup_hash(&last, path.dentry, lookup_flags);
41531da177e4SLinus Torvalds 	error = PTR_ERR(dentry);
41541da177e4SLinus Torvalds 	if (!IS_ERR(dentry)) {
41556521f891SChristian Brauner 		struct user_namespace *mnt_userns;
41566521f891SChristian Brauner 
41571da177e4SLinus Torvalds 		/* Why not before? Because we want correct error value */
4158f5beed75SAl Viro 		if (last.name[last.len])
415950338b88STörök Edwin 			goto slashes;
41601da177e4SLinus Torvalds 		inode = dentry->d_inode;
4161b18825a7SDavid Howells 		if (d_is_negative(dentry))
4162e6bc45d6STheodore Ts'o 			goto slashes;
41637de9c6eeSAl Viro 		ihold(inode);
4164f5beed75SAl Viro 		error = security_path_unlink(&path, dentry);
4165be6d3e56SKentaro Takeda 		if (error)
41660ee50b47SDmitry Kadashev 			goto exit3;
41676521f891SChristian Brauner 		mnt_userns = mnt_user_ns(path.mnt);
4168549c7297SChristian Brauner 		error = vfs_unlink(mnt_userns, path.dentry->d_inode, dentry,
4169549c7297SChristian Brauner 				   &delegated_inode);
41700ee50b47SDmitry Kadashev exit3:
41711da177e4SLinus Torvalds 		dput(dentry);
41721da177e4SLinus Torvalds 	}
41735955102cSAl Viro 	inode_unlock(path.dentry->d_inode);
41741da177e4SLinus Torvalds 	if (inode)
41751da177e4SLinus Torvalds 		iput(inode);	/* truncate the inode here */
4176b21996e3SJ. Bruce Fields 	inode = NULL;
4177b21996e3SJ. Bruce Fields 	if (delegated_inode) {
41785a14696cSJ. Bruce Fields 		error = break_deleg_wait(&delegated_inode);
4179b21996e3SJ. Bruce Fields 		if (!error)
4180b21996e3SJ. Bruce Fields 			goto retry_deleg;
4181b21996e3SJ. Bruce Fields 	}
4182f5beed75SAl Viro 	mnt_drop_write(path.mnt);
41830ee50b47SDmitry Kadashev exit2:
4184f5beed75SAl Viro 	path_put(&path);
41855d18f813SJeff Layton 	if (retry_estale(error, lookup_flags)) {
41865d18f813SJeff Layton 		lookup_flags |= LOOKUP_REVAL;
41875d18f813SJeff Layton 		inode = NULL;
41885d18f813SJeff Layton 		goto retry;
41895d18f813SJeff Layton 	}
41900ee50b47SDmitry Kadashev exit1:
4191da2f1362SChristoph Hellwig 	putname(name);
41921da177e4SLinus Torvalds 	return error;
41931da177e4SLinus Torvalds 
41941da177e4SLinus Torvalds slashes:
4195b18825a7SDavid Howells 	if (d_is_negative(dentry))
4196b18825a7SDavid Howells 		error = -ENOENT;
419744b1d530SMiklos Szeredi 	else if (d_is_dir(dentry))
4198b18825a7SDavid Howells 		error = -EISDIR;
4199b18825a7SDavid Howells 	else
4200b18825a7SDavid Howells 		error = -ENOTDIR;
42010ee50b47SDmitry Kadashev 	goto exit3;
42021da177e4SLinus Torvalds }
42031da177e4SLinus Torvalds 
42042e4d0924SHeiko Carstens SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag)
42055590ff0dSUlrich Drepper {
42065590ff0dSUlrich Drepper 	if ((flag & ~AT_REMOVEDIR) != 0)
42075590ff0dSUlrich Drepper 		return -EINVAL;
42085590ff0dSUlrich Drepper 
42095590ff0dSUlrich Drepper 	if (flag & AT_REMOVEDIR)
4210e24ab0efSChristoph Hellwig 		return do_rmdir(dfd, getname(pathname));
4211da2f1362SChristoph Hellwig 	return do_unlinkat(dfd, getname(pathname));
42125590ff0dSUlrich Drepper }
42135590ff0dSUlrich Drepper 
42143480b257SHeiko Carstens SYSCALL_DEFINE1(unlink, const char __user *, pathname)
42155590ff0dSUlrich Drepper {
4216da2f1362SChristoph Hellwig 	return do_unlinkat(AT_FDCWD, getname(pathname));
42175590ff0dSUlrich Drepper }
42185590ff0dSUlrich Drepper 
42196521f891SChristian Brauner /**
42206521f891SChristian Brauner  * vfs_symlink - create symlink
42216521f891SChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
42226521f891SChristian Brauner  * @dir:	inode of @dentry
42236521f891SChristian Brauner  * @dentry:	pointer to dentry of the base directory
42246521f891SChristian Brauner  * @oldname:	name of the file to link to
42256521f891SChristian Brauner  *
42266521f891SChristian Brauner  * Create a symlink.
42276521f891SChristian Brauner  *
42286521f891SChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
42296521f891SChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
42306521f891SChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
42316521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
42326521f891SChristian Brauner  * raw inode simply passs init_user_ns.
42336521f891SChristian Brauner  */
42346521f891SChristian Brauner int vfs_symlink(struct user_namespace *mnt_userns, struct inode *dir,
42356521f891SChristian Brauner 		struct dentry *dentry, const char *oldname)
42361da177e4SLinus Torvalds {
42376521f891SChristian Brauner 	int error = may_create(mnt_userns, dir, dentry);
42381da177e4SLinus Torvalds 
42391da177e4SLinus Torvalds 	if (error)
42401da177e4SLinus Torvalds 		return error;
42411da177e4SLinus Torvalds 
4242acfa4380SAl Viro 	if (!dir->i_op->symlink)
42431da177e4SLinus Torvalds 		return -EPERM;
42441da177e4SLinus Torvalds 
42451da177e4SLinus Torvalds 	error = security_inode_symlink(dir, dentry, oldname);
42461da177e4SLinus Torvalds 	if (error)
42471da177e4SLinus Torvalds 		return error;
42481da177e4SLinus Torvalds 
4249549c7297SChristian Brauner 	error = dir->i_op->symlink(mnt_userns, dir, dentry, oldname);
4250a74574aaSStephen Smalley 	if (!error)
4251f38aa942SAmy Griffis 		fsnotify_create(dir, dentry);
42521da177e4SLinus Torvalds 	return error;
42531da177e4SLinus Torvalds }
42544d359507SAl Viro EXPORT_SYMBOL(vfs_symlink);
42551da177e4SLinus Torvalds 
42567a8721f8SDmitry Kadashev int do_symlinkat(struct filename *from, int newdfd, struct filename *to)
42571da177e4SLinus Torvalds {
42582ad94ae6SAl Viro 	int error;
42596902d925SDave Hansen 	struct dentry *dentry;
4260dae6ad8fSAl Viro 	struct path path;
4261f46d3567SJeff Layton 	unsigned int lookup_flags = 0;
42621da177e4SLinus Torvalds 
4263da2d0cedSDmitry Kadashev 	if (IS_ERR(from)) {
4264da2d0cedSDmitry Kadashev 		error = PTR_ERR(from);
4265da2d0cedSDmitry Kadashev 		goto out_putnames;
4266da2d0cedSDmitry Kadashev 	}
4267f46d3567SJeff Layton retry:
4268da2d0cedSDmitry Kadashev 	dentry = __filename_create(newdfd, to, &path, lookup_flags);
42691da177e4SLinus Torvalds 	error = PTR_ERR(dentry);
42706902d925SDave Hansen 	if (IS_ERR(dentry))
4271da2d0cedSDmitry Kadashev 		goto out_putnames;
42726902d925SDave Hansen 
427391a27b2aSJeff Layton 	error = security_path_symlink(&path, dentry, from->name);
42746521f891SChristian Brauner 	if (!error) {
42756521f891SChristian Brauner 		struct user_namespace *mnt_userns;
42766521f891SChristian Brauner 
42776521f891SChristian Brauner 		mnt_userns = mnt_user_ns(path.mnt);
42786521f891SChristian Brauner 		error = vfs_symlink(mnt_userns, path.dentry->d_inode, dentry,
42796521f891SChristian Brauner 				    from->name);
42806521f891SChristian Brauner 	}
4281921a1650SAl Viro 	done_path_create(&path, dentry);
4282f46d3567SJeff Layton 	if (retry_estale(error, lookup_flags)) {
4283f46d3567SJeff Layton 		lookup_flags |= LOOKUP_REVAL;
4284f46d3567SJeff Layton 		goto retry;
4285f46d3567SJeff Layton 	}
4286da2d0cedSDmitry Kadashev out_putnames:
4287da2d0cedSDmitry Kadashev 	putname(to);
42881da177e4SLinus Torvalds 	putname(from);
42891da177e4SLinus Torvalds 	return error;
42901da177e4SLinus Torvalds }
42911da177e4SLinus Torvalds 
4292b724e846SDominik Brodowski SYSCALL_DEFINE3(symlinkat, const char __user *, oldname,
4293b724e846SDominik Brodowski 		int, newdfd, const char __user *, newname)
4294b724e846SDominik Brodowski {
4295da2d0cedSDmitry Kadashev 	return do_symlinkat(getname(oldname), newdfd, getname(newname));
4296b724e846SDominik Brodowski }
4297b724e846SDominik Brodowski 
42983480b257SHeiko Carstens SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname)
42995590ff0dSUlrich Drepper {
4300da2d0cedSDmitry Kadashev 	return do_symlinkat(getname(oldname), AT_FDCWD, getname(newname));
43015590ff0dSUlrich Drepper }
43025590ff0dSUlrich Drepper 
4303146a8595SJ. Bruce Fields /**
4304146a8595SJ. Bruce Fields  * vfs_link - create a new link
4305146a8595SJ. Bruce Fields  * @old_dentry:	object to be linked
43066521f891SChristian Brauner  * @mnt_userns:	the user namespace of the mount
4307146a8595SJ. Bruce Fields  * @dir:	new parent
4308146a8595SJ. Bruce Fields  * @new_dentry:	where to create the new link
4309146a8595SJ. Bruce Fields  * @delegated_inode: returns inode needing a delegation break
4310146a8595SJ. Bruce Fields  *
4311146a8595SJ. Bruce Fields  * The caller must hold dir->i_mutex
4312146a8595SJ. Bruce Fields  *
4313146a8595SJ. Bruce Fields  * If vfs_link discovers a delegation on the to-be-linked file in need
4314146a8595SJ. Bruce Fields  * of breaking, it will return -EWOULDBLOCK and return a reference to the
4315146a8595SJ. Bruce Fields  * inode in delegated_inode.  The caller should then break the delegation
4316146a8595SJ. Bruce Fields  * and retry.  Because breaking a delegation may take a long time, the
4317146a8595SJ. Bruce Fields  * caller should drop the i_mutex before doing so.
4318146a8595SJ. Bruce Fields  *
4319146a8595SJ. Bruce Fields  * Alternatively, a caller may pass NULL for delegated_inode.  This may
4320146a8595SJ. Bruce Fields  * be appropriate for callers that expect the underlying filesystem not
4321146a8595SJ. Bruce Fields  * to be NFS exported.
43226521f891SChristian Brauner  *
43236521f891SChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
43246521f891SChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
43256521f891SChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
43266521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
43276521f891SChristian Brauner  * raw inode simply passs init_user_ns.
4328146a8595SJ. Bruce Fields  */
43296521f891SChristian Brauner int vfs_link(struct dentry *old_dentry, struct user_namespace *mnt_userns,
43306521f891SChristian Brauner 	     struct inode *dir, struct dentry *new_dentry,
43316521f891SChristian Brauner 	     struct inode **delegated_inode)
43321da177e4SLinus Torvalds {
43331da177e4SLinus Torvalds 	struct inode *inode = old_dentry->d_inode;
43348de52778SAl Viro 	unsigned max_links = dir->i_sb->s_max_links;
43351da177e4SLinus Torvalds 	int error;
43361da177e4SLinus Torvalds 
43371da177e4SLinus Torvalds 	if (!inode)
43381da177e4SLinus Torvalds 		return -ENOENT;
43391da177e4SLinus Torvalds 
43406521f891SChristian Brauner 	error = may_create(mnt_userns, dir, new_dentry);
43411da177e4SLinus Torvalds 	if (error)
43421da177e4SLinus Torvalds 		return error;
43431da177e4SLinus Torvalds 
43441da177e4SLinus Torvalds 	if (dir->i_sb != inode->i_sb)
43451da177e4SLinus Torvalds 		return -EXDEV;
43461da177e4SLinus Torvalds 
43471da177e4SLinus Torvalds 	/*
43481da177e4SLinus Torvalds 	 * A link to an append-only or immutable file cannot be created.
43491da177e4SLinus Torvalds 	 */
43501da177e4SLinus Torvalds 	if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
43511da177e4SLinus Torvalds 		return -EPERM;
43520bd23d09SEric W. Biederman 	/*
43530bd23d09SEric W. Biederman 	 * Updating the link count will likely cause i_uid and i_gid to
43540bd23d09SEric W. Biederman 	 * be writen back improperly if their true value is unknown to
43550bd23d09SEric W. Biederman 	 * the vfs.
43560bd23d09SEric W. Biederman 	 */
43576521f891SChristian Brauner 	if (HAS_UNMAPPED_ID(mnt_userns, inode))
43580bd23d09SEric W. Biederman 		return -EPERM;
4359acfa4380SAl Viro 	if (!dir->i_op->link)
43601da177e4SLinus Torvalds 		return -EPERM;
43617e79eedbSTetsuo Handa 	if (S_ISDIR(inode->i_mode))
43621da177e4SLinus Torvalds 		return -EPERM;
43631da177e4SLinus Torvalds 
43641da177e4SLinus Torvalds 	error = security_inode_link(old_dentry, dir, new_dentry);
43651da177e4SLinus Torvalds 	if (error)
43661da177e4SLinus Torvalds 		return error;
43671da177e4SLinus Torvalds 
43685955102cSAl Viro 	inode_lock(inode);
4369aae8a97dSAneesh Kumar K.V 	/* Make sure we don't allow creating hardlink to an unlinked file */
4370f4e0c30cSAl Viro 	if (inode->i_nlink == 0 && !(inode->i_state & I_LINKABLE))
4371aae8a97dSAneesh Kumar K.V 		error =  -ENOENT;
43728de52778SAl Viro 	else if (max_links && inode->i_nlink >= max_links)
43738de52778SAl Viro 		error = -EMLINK;
4374146a8595SJ. Bruce Fields 	else {
4375146a8595SJ. Bruce Fields 		error = try_break_deleg(inode, delegated_inode);
4376146a8595SJ. Bruce Fields 		if (!error)
43771da177e4SLinus Torvalds 			error = dir->i_op->link(old_dentry, dir, new_dentry);
4378146a8595SJ. Bruce Fields 	}
4379f4e0c30cSAl Viro 
4380f4e0c30cSAl Viro 	if (!error && (inode->i_state & I_LINKABLE)) {
4381f4e0c30cSAl Viro 		spin_lock(&inode->i_lock);
4382f4e0c30cSAl Viro 		inode->i_state &= ~I_LINKABLE;
4383f4e0c30cSAl Viro 		spin_unlock(&inode->i_lock);
4384f4e0c30cSAl Viro 	}
43855955102cSAl Viro 	inode_unlock(inode);
4386e31e14ecSStephen Smalley 	if (!error)
43877e79eedbSTetsuo Handa 		fsnotify_link(dir, inode, new_dentry);
43881da177e4SLinus Torvalds 	return error;
43891da177e4SLinus Torvalds }
43904d359507SAl Viro EXPORT_SYMBOL(vfs_link);
43911da177e4SLinus Torvalds 
43921da177e4SLinus Torvalds /*
43931da177e4SLinus Torvalds  * Hardlinks are often used in delicate situations.  We avoid
43941da177e4SLinus Torvalds  * security-related surprises by not following symlinks on the
43951da177e4SLinus Torvalds  * newname.  --KAB
43961da177e4SLinus Torvalds  *
43971da177e4SLinus Torvalds  * We don't follow them on the oldname either to be compatible
43981da177e4SLinus Torvalds  * with linux 2.0, and to avoid hard-linking to directories
43991da177e4SLinus Torvalds  * and other special files.  --ADM
44001da177e4SLinus Torvalds  */
4401cf30da90SDmitry Kadashev int do_linkat(int olddfd, struct filename *old, int newdfd,
4402020250f3SDmitry Kadashev 	      struct filename *new, int flags)
44031da177e4SLinus Torvalds {
44046521f891SChristian Brauner 	struct user_namespace *mnt_userns;
44051da177e4SLinus Torvalds 	struct dentry *new_dentry;
4406dae6ad8fSAl Viro 	struct path old_path, new_path;
4407146a8595SJ. Bruce Fields 	struct inode *delegated_inode = NULL;
440811a7b371SAneesh Kumar K.V 	int how = 0;
44091da177e4SLinus Torvalds 	int error;
44101da177e4SLinus Torvalds 
4411020250f3SDmitry Kadashev 	if ((flags & ~(AT_SYMLINK_FOLLOW | AT_EMPTY_PATH)) != 0) {
4412020250f3SDmitry Kadashev 		error = -EINVAL;
4413020250f3SDmitry Kadashev 		goto out_putnames;
4414020250f3SDmitry Kadashev 	}
441511a7b371SAneesh Kumar K.V 	/*
4416f0cc6ffbSLinus Torvalds 	 * To use null names we require CAP_DAC_READ_SEARCH
4417f0cc6ffbSLinus Torvalds 	 * This ensures that not everyone will be able to create
4418f0cc6ffbSLinus Torvalds 	 * handlink using the passed filedescriptor.
441911a7b371SAneesh Kumar K.V 	 */
4420020250f3SDmitry Kadashev 	if (flags & AT_EMPTY_PATH && !capable(CAP_DAC_READ_SEARCH)) {
4421020250f3SDmitry Kadashev 		error = -ENOENT;
4422020250f3SDmitry Kadashev 		goto out_putnames;
4423f0cc6ffbSLinus Torvalds 	}
4424c04030e1SUlrich Drepper 
442511a7b371SAneesh Kumar K.V 	if (flags & AT_SYMLINK_FOLLOW)
442611a7b371SAneesh Kumar K.V 		how |= LOOKUP_FOLLOW;
4427442e31caSJeff Layton retry:
4428020250f3SDmitry Kadashev 	error = __filename_lookup(olddfd, old, how, &old_path, NULL);
44291da177e4SLinus Torvalds 	if (error)
4430020250f3SDmitry Kadashev 		goto out_putnames;
44312ad94ae6SAl Viro 
4432020250f3SDmitry Kadashev 	new_dentry = __filename_create(newdfd, new, &new_path,
4433442e31caSJeff Layton 					(how & LOOKUP_REVAL));
44341da177e4SLinus Torvalds 	error = PTR_ERR(new_dentry);
44356902d925SDave Hansen 	if (IS_ERR(new_dentry))
4436020250f3SDmitry Kadashev 		goto out_putpath;
4437dae6ad8fSAl Viro 
4438dae6ad8fSAl Viro 	error = -EXDEV;
4439dae6ad8fSAl Viro 	if (old_path.mnt != new_path.mnt)
4440dae6ad8fSAl Viro 		goto out_dput;
4441549c7297SChristian Brauner 	mnt_userns = mnt_user_ns(new_path.mnt);
4442549c7297SChristian Brauner 	error = may_linkat(mnt_userns, &old_path);
4443800179c9SKees Cook 	if (unlikely(error))
4444800179c9SKees Cook 		goto out_dput;
4445dae6ad8fSAl Viro 	error = security_path_link(old_path.dentry, &new_path, new_dentry);
4446be6d3e56SKentaro Takeda 	if (error)
4447a8104a9fSAl Viro 		goto out_dput;
44486521f891SChristian Brauner 	error = vfs_link(old_path.dentry, mnt_userns, new_path.dentry->d_inode,
44496521f891SChristian Brauner 			 new_dentry, &delegated_inode);
445075c3f29dSDave Hansen out_dput:
4451921a1650SAl Viro 	done_path_create(&new_path, new_dentry);
4452146a8595SJ. Bruce Fields 	if (delegated_inode) {
4453146a8595SJ. Bruce Fields 		error = break_deleg_wait(&delegated_inode);
4454d22e6338SOleg Drokin 		if (!error) {
4455d22e6338SOleg Drokin 			path_put(&old_path);
4456146a8595SJ. Bruce Fields 			goto retry;
4457146a8595SJ. Bruce Fields 		}
4458d22e6338SOleg Drokin 	}
4459442e31caSJeff Layton 	if (retry_estale(error, how)) {
4460d22e6338SOleg Drokin 		path_put(&old_path);
4461442e31caSJeff Layton 		how |= LOOKUP_REVAL;
4462442e31caSJeff Layton 		goto retry;
4463442e31caSJeff Layton 	}
4464020250f3SDmitry Kadashev out_putpath:
44652d8f3038SAl Viro 	path_put(&old_path);
4466020250f3SDmitry Kadashev out_putnames:
4467020250f3SDmitry Kadashev 	putname(old);
4468020250f3SDmitry Kadashev 	putname(new);
44691da177e4SLinus Torvalds 
44701da177e4SLinus Torvalds 	return error;
44711da177e4SLinus Torvalds }
44721da177e4SLinus Torvalds 
447346ea89ebSDominik Brodowski SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname,
447446ea89ebSDominik Brodowski 		int, newdfd, const char __user *, newname, int, flags)
447546ea89ebSDominik Brodowski {
4476020250f3SDmitry Kadashev 	return do_linkat(olddfd, getname_uflags(oldname, flags),
4477020250f3SDmitry Kadashev 		newdfd, getname(newname), flags);
447846ea89ebSDominik Brodowski }
447946ea89ebSDominik Brodowski 
44803480b257SHeiko Carstens SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname)
44815590ff0dSUlrich Drepper {
4482020250f3SDmitry Kadashev 	return do_linkat(AT_FDCWD, getname(oldname), AT_FDCWD, getname(newname), 0);
44835590ff0dSUlrich Drepper }
44845590ff0dSUlrich Drepper 
4485bc27027aSMiklos Szeredi /**
4486bc27027aSMiklos Szeredi  * vfs_rename - rename a filesystem object
44872111c3c0SRandy Dunlap  * @rd:		pointer to &struct renamedata info
4488bc27027aSMiklos Szeredi  *
4489bc27027aSMiklos Szeredi  * The caller must hold multiple mutexes--see lock_rename()).
4490bc27027aSMiklos Szeredi  *
4491bc27027aSMiklos Szeredi  * If vfs_rename discovers a delegation in need of breaking at either
4492bc27027aSMiklos Szeredi  * the source or destination, it will return -EWOULDBLOCK and return a
4493bc27027aSMiklos Szeredi  * reference to the inode in delegated_inode.  The caller should then
4494bc27027aSMiklos Szeredi  * break the delegation and retry.  Because breaking a delegation may
4495bc27027aSMiklos Szeredi  * take a long time, the caller should drop all locks before doing
4496bc27027aSMiklos Szeredi  * so.
4497bc27027aSMiklos Szeredi  *
4498bc27027aSMiklos Szeredi  * Alternatively, a caller may pass NULL for delegated_inode.  This may
4499bc27027aSMiklos Szeredi  * be appropriate for callers that expect the underlying filesystem not
4500bc27027aSMiklos Szeredi  * to be NFS exported.
4501bc27027aSMiklos Szeredi  *
45021da177e4SLinus Torvalds  * The worst of all namespace operations - renaming directory. "Perverted"
45031da177e4SLinus Torvalds  * doesn't even start to describe it. Somebody in UCB had a heck of a trip...
45041da177e4SLinus Torvalds  * Problems:
45050117d427SMauro Carvalho Chehab  *
4506d03b29a2SJ. Bruce Fields  *	a) we can get into loop creation.
45071da177e4SLinus Torvalds  *	b) race potential - two innocent renames can create a loop together.
45081da177e4SLinus Torvalds  *	   That's where 4.4 screws up. Current fix: serialization on
4509a11f3a05SArjan van de Ven  *	   sb->s_vfs_rename_mutex. We might be more accurate, but that's another
45101da177e4SLinus Torvalds  *	   story.
45116cedba89SJ. Bruce Fields  *	c) we have to lock _four_ objects - parents and victim (if it exists),
45126cedba89SJ. Bruce Fields  *	   and source (if it is not a directory).
45131b1dcc1bSJes Sorensen  *	   And that - after we got ->i_mutex on parents (until then we don't know
45141da177e4SLinus Torvalds  *	   whether the target exists).  Solution: try to be smart with locking
45151da177e4SLinus Torvalds  *	   order for inodes.  We rely on the fact that tree topology may change
4516a11f3a05SArjan van de Ven  *	   only under ->s_vfs_rename_mutex _and_ that parent of the object we
45171da177e4SLinus Torvalds  *	   move will be locked.  Thus we can rank directories by the tree
45181da177e4SLinus Torvalds  *	   (ancestors first) and rank all non-directories after them.
45191da177e4SLinus Torvalds  *	   That works since everybody except rename does "lock parent, lookup,
4520a11f3a05SArjan van de Ven  *	   lock child" and rename is under ->s_vfs_rename_mutex.
45211da177e4SLinus Torvalds  *	   HOWEVER, it relies on the assumption that any object with ->lookup()
45221da177e4SLinus Torvalds  *	   has no more than 1 dentry.  If "hybrid" objects will ever appear,
45231da177e4SLinus Torvalds  *	   we'd better make sure that there's no link(2) for them.
4524e4eaac06SSage Weil  *	d) conversion from fhandle to dentry may come in the wrong moment - when
45251b1dcc1bSJes Sorensen  *	   we are removing the target. Solution: we will have to grab ->i_mutex
45261da177e4SLinus Torvalds  *	   in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on
4527c41b20e7SAdam Buchbinder  *	   ->i_mutex on parents, which works but leads to some truly excessive
45281da177e4SLinus Torvalds  *	   locking].
45291da177e4SLinus Torvalds  */
45309fe61450SChristian Brauner int vfs_rename(struct renamedata *rd)
45311da177e4SLinus Torvalds {
45321da177e4SLinus Torvalds 	int error;
45339fe61450SChristian Brauner 	struct inode *old_dir = rd->old_dir, *new_dir = rd->new_dir;
45349fe61450SChristian Brauner 	struct dentry *old_dentry = rd->old_dentry;
45359fe61450SChristian Brauner 	struct dentry *new_dentry = rd->new_dentry;
45369fe61450SChristian Brauner 	struct inode **delegated_inode = rd->delegated_inode;
45379fe61450SChristian Brauner 	unsigned int flags = rd->flags;
4538bc27027aSMiklos Szeredi 	bool is_dir = d_is_dir(old_dentry);
4539bc27027aSMiklos Szeredi 	struct inode *source = old_dentry->d_inode;
4540bc27027aSMiklos Szeredi 	struct inode *target = new_dentry->d_inode;
4541da1ce067SMiklos Szeredi 	bool new_is_dir = false;
4542da1ce067SMiklos Szeredi 	unsigned max_links = new_dir->i_sb->s_max_links;
454349d31c2fSAl Viro 	struct name_snapshot old_name;
45441da177e4SLinus Torvalds 
45458d3e2936SMiklos Szeredi 	if (source == target)
45461da177e4SLinus Torvalds 		return 0;
45471da177e4SLinus Torvalds 
45486521f891SChristian Brauner 	error = may_delete(rd->old_mnt_userns, old_dir, old_dentry, is_dir);
45491da177e4SLinus Torvalds 	if (error)
45501da177e4SLinus Torvalds 		return error;
45511da177e4SLinus Torvalds 
4552da1ce067SMiklos Szeredi 	if (!target) {
45536521f891SChristian Brauner 		error = may_create(rd->new_mnt_userns, new_dir, new_dentry);
4554da1ce067SMiklos Szeredi 	} else {
4555da1ce067SMiklos Szeredi 		new_is_dir = d_is_dir(new_dentry);
4556da1ce067SMiklos Szeredi 
4557da1ce067SMiklos Szeredi 		if (!(flags & RENAME_EXCHANGE))
45586521f891SChristian Brauner 			error = may_delete(rd->new_mnt_userns, new_dir,
45596521f891SChristian Brauner 					   new_dentry, is_dir);
4560da1ce067SMiklos Szeredi 		else
45616521f891SChristian Brauner 			error = may_delete(rd->new_mnt_userns, new_dir,
45626521f891SChristian Brauner 					   new_dentry, new_is_dir);
4563da1ce067SMiklos Szeredi 	}
45641da177e4SLinus Torvalds 	if (error)
45651da177e4SLinus Torvalds 		return error;
45661da177e4SLinus Torvalds 
45672773bf00SMiklos Szeredi 	if (!old_dir->i_op->rename)
45681da177e4SLinus Torvalds 		return -EPERM;
45691da177e4SLinus Torvalds 
4570bc27027aSMiklos Szeredi 	/*
4571bc27027aSMiklos Szeredi 	 * If we are going to change the parent - check write permissions,
4572bc27027aSMiklos Szeredi 	 * we'll need to flip '..'.
4573bc27027aSMiklos Szeredi 	 */
4574da1ce067SMiklos Szeredi 	if (new_dir != old_dir) {
4575da1ce067SMiklos Szeredi 		if (is_dir) {
45766521f891SChristian Brauner 			error = inode_permission(rd->old_mnt_userns, source,
457747291baaSChristian Brauner 						 MAY_WRITE);
4578bc27027aSMiklos Szeredi 			if (error)
4579bc27027aSMiklos Szeredi 				return error;
4580bc27027aSMiklos Szeredi 		}
4581da1ce067SMiklos Szeredi 		if ((flags & RENAME_EXCHANGE) && new_is_dir) {
45826521f891SChristian Brauner 			error = inode_permission(rd->new_mnt_userns, target,
458347291baaSChristian Brauner 						 MAY_WRITE);
4584da1ce067SMiklos Szeredi 			if (error)
4585da1ce067SMiklos Szeredi 				return error;
4586da1ce067SMiklos Szeredi 		}
4587da1ce067SMiklos Szeredi 	}
45880eeca283SRobert Love 
45890b3974ebSMiklos Szeredi 	error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,
45900b3974ebSMiklos Szeredi 				      flags);
4591bc27027aSMiklos Szeredi 	if (error)
4592bc27027aSMiklos Szeredi 		return error;
4593bc27027aSMiklos Szeredi 
459449d31c2fSAl Viro 	take_dentry_name_snapshot(&old_name, old_dentry);
4595bc27027aSMiklos Szeredi 	dget(new_dentry);
4596da1ce067SMiklos Szeredi 	if (!is_dir || (flags & RENAME_EXCHANGE))
4597bc27027aSMiklos Szeredi 		lock_two_nondirectories(source, target);
4598bc27027aSMiklos Szeredi 	else if (target)
45995955102cSAl Viro 		inode_lock(target);
4600bc27027aSMiklos Szeredi 
460151cc3a66SHugh Dickins 	error = -EPERM;
460251cc3a66SHugh Dickins 	if (IS_SWAPFILE(source) || (target && IS_SWAPFILE(target)))
460351cc3a66SHugh Dickins 		goto out;
460451cc3a66SHugh Dickins 
4605bc27027aSMiklos Szeredi 	error = -EBUSY;
46067af1364fSEric W. Biederman 	if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
4607bc27027aSMiklos Szeredi 		goto out;
4608bc27027aSMiklos Szeredi 
4609da1ce067SMiklos Szeredi 	if (max_links && new_dir != old_dir) {
4610bc27027aSMiklos Szeredi 		error = -EMLINK;
4611da1ce067SMiklos Szeredi 		if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)
4612bc27027aSMiklos Szeredi 			goto out;
4613da1ce067SMiklos Szeredi 		if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&
4614da1ce067SMiklos Szeredi 		    old_dir->i_nlink >= max_links)
4615da1ce067SMiklos Szeredi 			goto out;
4616da1ce067SMiklos Szeredi 	}
4617da1ce067SMiklos Szeredi 	if (!is_dir) {
4618bc27027aSMiklos Szeredi 		error = try_break_deleg(source, delegated_inode);
4619bc27027aSMiklos Szeredi 		if (error)
4620bc27027aSMiklos Szeredi 			goto out;
4621da1ce067SMiklos Szeredi 	}
4622da1ce067SMiklos Szeredi 	if (target && !new_is_dir) {
4623bc27027aSMiklos Szeredi 		error = try_break_deleg(target, delegated_inode);
4624bc27027aSMiklos Szeredi 		if (error)
4625bc27027aSMiklos Szeredi 			goto out;
4626bc27027aSMiklos Szeredi 	}
4627549c7297SChristian Brauner 	error = old_dir->i_op->rename(rd->new_mnt_userns, old_dir, old_dentry,
4628520c8b16SMiklos Szeredi 				      new_dir, new_dentry, flags);
4629bc27027aSMiklos Szeredi 	if (error)
4630bc27027aSMiklos Szeredi 		goto out;
4631bc27027aSMiklos Szeredi 
4632da1ce067SMiklos Szeredi 	if (!(flags & RENAME_EXCHANGE) && target) {
46338767712fSAl Viro 		if (is_dir) {
46348767712fSAl Viro 			shrink_dcache_parent(new_dentry);
4635bc27027aSMiklos Szeredi 			target->i_flags |= S_DEAD;
46368767712fSAl Viro 		}
4637bc27027aSMiklos Szeredi 		dont_mount(new_dentry);
46388ed936b5SEric W. Biederman 		detach_mounts(new_dentry);
4639bc27027aSMiklos Szeredi 	}
4640da1ce067SMiklos Szeredi 	if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {
4641da1ce067SMiklos Szeredi 		if (!(flags & RENAME_EXCHANGE))
4642bc27027aSMiklos Szeredi 			d_move(old_dentry, new_dentry);
4643da1ce067SMiklos Szeredi 		else
4644da1ce067SMiklos Szeredi 			d_exchange(old_dentry, new_dentry);
4645da1ce067SMiklos Szeredi 	}
4646bc27027aSMiklos Szeredi out:
4647da1ce067SMiklos Szeredi 	if (!is_dir || (flags & RENAME_EXCHANGE))
4648bc27027aSMiklos Szeredi 		unlock_two_nondirectories(source, target);
4649bc27027aSMiklos Szeredi 	else if (target)
46505955102cSAl Viro 		inode_unlock(target);
4651bc27027aSMiklos Szeredi 	dput(new_dentry);
4652da1ce067SMiklos Szeredi 	if (!error) {
4653f4ec3a3dSAl Viro 		fsnotify_move(old_dir, new_dir, &old_name.name, is_dir,
4654da1ce067SMiklos Szeredi 			      !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);
4655da1ce067SMiklos Szeredi 		if (flags & RENAME_EXCHANGE) {
4656f4ec3a3dSAl Viro 			fsnotify_move(new_dir, old_dir, &old_dentry->d_name,
4657da1ce067SMiklos Szeredi 				      new_is_dir, NULL, new_dentry);
4658da1ce067SMiklos Szeredi 		}
4659da1ce067SMiklos Szeredi 	}
466049d31c2fSAl Viro 	release_dentry_name_snapshot(&old_name);
46610eeca283SRobert Love 
46621da177e4SLinus Torvalds 	return error;
46631da177e4SLinus Torvalds }
46644d359507SAl Viro EXPORT_SYMBOL(vfs_rename);
46651da177e4SLinus Torvalds 
4666e886663cSJens Axboe int do_renameat2(int olddfd, struct filename *from, int newdfd,
4667e886663cSJens Axboe 		 struct filename *to, unsigned int flags)
46681da177e4SLinus Torvalds {
46699fe61450SChristian Brauner 	struct renamedata rd;
46701da177e4SLinus Torvalds 	struct dentry *old_dentry, *new_dentry;
46711da177e4SLinus Torvalds 	struct dentry *trap;
4672f5beed75SAl Viro 	struct path old_path, new_path;
4673f5beed75SAl Viro 	struct qstr old_last, new_last;
4674f5beed75SAl Viro 	int old_type, new_type;
46758e6d782cSJ. Bruce Fields 	struct inode *delegated_inode = NULL;
4676f5beed75SAl Viro 	unsigned int lookup_flags = 0, target_flags = LOOKUP_RENAME_TARGET;
4677c6a94284SJeff Layton 	bool should_retry = false;
4678e886663cSJens Axboe 	int error = -EINVAL;
4679520c8b16SMiklos Szeredi 
46800d7a8555SMiklos Szeredi 	if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
46810ee50b47SDmitry Kadashev 		goto put_names;
4682da1ce067SMiklos Szeredi 
46830d7a8555SMiklos Szeredi 	if ((flags & (RENAME_NOREPLACE | RENAME_WHITEOUT)) &&
46840d7a8555SMiklos Szeredi 	    (flags & RENAME_EXCHANGE))
46850ee50b47SDmitry Kadashev 		goto put_names;
4686520c8b16SMiklos Szeredi 
4687f5beed75SAl Viro 	if (flags & RENAME_EXCHANGE)
4688f5beed75SAl Viro 		target_flags = 0;
4689f5beed75SAl Viro 
4690c6a94284SJeff Layton retry:
46910ee50b47SDmitry Kadashev 	error = __filename_parentat(olddfd, from, lookup_flags, &old_path,
4692e886663cSJens Axboe 					&old_last, &old_type);
46930ee50b47SDmitry Kadashev 	if (error)
46940ee50b47SDmitry Kadashev 		goto put_names;
46951da177e4SLinus Torvalds 
46960ee50b47SDmitry Kadashev 	error = __filename_parentat(newdfd, to, lookup_flags, &new_path, &new_last,
4697e886663cSJens Axboe 				&new_type);
46980ee50b47SDmitry Kadashev 	if (error)
46991da177e4SLinus Torvalds 		goto exit1;
47001da177e4SLinus Torvalds 
47011da177e4SLinus Torvalds 	error = -EXDEV;
4702f5beed75SAl Viro 	if (old_path.mnt != new_path.mnt)
47031da177e4SLinus Torvalds 		goto exit2;
47041da177e4SLinus Torvalds 
47051da177e4SLinus Torvalds 	error = -EBUSY;
4706f5beed75SAl Viro 	if (old_type != LAST_NORM)
47071da177e4SLinus Torvalds 		goto exit2;
47081da177e4SLinus Torvalds 
47090a7c3937SMiklos Szeredi 	if (flags & RENAME_NOREPLACE)
47100a7c3937SMiklos Szeredi 		error = -EEXIST;
4711f5beed75SAl Viro 	if (new_type != LAST_NORM)
47121da177e4SLinus Torvalds 		goto exit2;
47131da177e4SLinus Torvalds 
4714f5beed75SAl Viro 	error = mnt_want_write(old_path.mnt);
4715c30dabfeSJan Kara 	if (error)
4716c30dabfeSJan Kara 		goto exit2;
4717c30dabfeSJan Kara 
47188e6d782cSJ. Bruce Fields retry_deleg:
4719f5beed75SAl Viro 	trap = lock_rename(new_path.dentry, old_path.dentry);
47201da177e4SLinus Torvalds 
4721f5beed75SAl Viro 	old_dentry = __lookup_hash(&old_last, old_path.dentry, lookup_flags);
47221da177e4SLinus Torvalds 	error = PTR_ERR(old_dentry);
47231da177e4SLinus Torvalds 	if (IS_ERR(old_dentry))
47241da177e4SLinus Torvalds 		goto exit3;
47251da177e4SLinus Torvalds 	/* source must exist */
47261da177e4SLinus Torvalds 	error = -ENOENT;
4727b18825a7SDavid Howells 	if (d_is_negative(old_dentry))
47281da177e4SLinus Torvalds 		goto exit4;
4729f5beed75SAl Viro 	new_dentry = __lookup_hash(&new_last, new_path.dentry, lookup_flags | target_flags);
47301da177e4SLinus Torvalds 	error = PTR_ERR(new_dentry);
47311da177e4SLinus Torvalds 	if (IS_ERR(new_dentry))
47321da177e4SLinus Torvalds 		goto exit4;
47330a7c3937SMiklos Szeredi 	error = -EEXIST;
47340a7c3937SMiklos Szeredi 	if ((flags & RENAME_NOREPLACE) && d_is_positive(new_dentry))
47350a7c3937SMiklos Szeredi 		goto exit5;
4736da1ce067SMiklos Szeredi 	if (flags & RENAME_EXCHANGE) {
4737da1ce067SMiklos Szeredi 		error = -ENOENT;
4738da1ce067SMiklos Szeredi 		if (d_is_negative(new_dentry))
4739da1ce067SMiklos Szeredi 			goto exit5;
4740da1ce067SMiklos Szeredi 
4741da1ce067SMiklos Szeredi 		if (!d_is_dir(new_dentry)) {
4742da1ce067SMiklos Szeredi 			error = -ENOTDIR;
4743f5beed75SAl Viro 			if (new_last.name[new_last.len])
4744da1ce067SMiklos Szeredi 				goto exit5;
4745da1ce067SMiklos Szeredi 		}
4746da1ce067SMiklos Szeredi 	}
47470a7c3937SMiklos Szeredi 	/* unless the source is a directory trailing slashes give -ENOTDIR */
47480a7c3937SMiklos Szeredi 	if (!d_is_dir(old_dentry)) {
47490a7c3937SMiklos Szeredi 		error = -ENOTDIR;
4750f5beed75SAl Viro 		if (old_last.name[old_last.len])
47510a7c3937SMiklos Szeredi 			goto exit5;
4752f5beed75SAl Viro 		if (!(flags & RENAME_EXCHANGE) && new_last.name[new_last.len])
47530a7c3937SMiklos Szeredi 			goto exit5;
47540a7c3937SMiklos Szeredi 	}
47550a7c3937SMiklos Szeredi 	/* source should not be ancestor of target */
47560a7c3937SMiklos Szeredi 	error = -EINVAL;
47570a7c3937SMiklos Szeredi 	if (old_dentry == trap)
47580a7c3937SMiklos Szeredi 		goto exit5;
47591da177e4SLinus Torvalds 	/* target should not be an ancestor of source */
4760da1ce067SMiklos Szeredi 	if (!(flags & RENAME_EXCHANGE))
47611da177e4SLinus Torvalds 		error = -ENOTEMPTY;
47621da177e4SLinus Torvalds 	if (new_dentry == trap)
47631da177e4SLinus Torvalds 		goto exit5;
47641da177e4SLinus Torvalds 
4765f5beed75SAl Viro 	error = security_path_rename(&old_path, old_dentry,
4766f5beed75SAl Viro 				     &new_path, new_dentry, flags);
4767be6d3e56SKentaro Takeda 	if (error)
4768c30dabfeSJan Kara 		goto exit5;
47699fe61450SChristian Brauner 
47709fe61450SChristian Brauner 	rd.old_dir	   = old_path.dentry->d_inode;
47719fe61450SChristian Brauner 	rd.old_dentry	   = old_dentry;
47726521f891SChristian Brauner 	rd.old_mnt_userns  = mnt_user_ns(old_path.mnt);
47739fe61450SChristian Brauner 	rd.new_dir	   = new_path.dentry->d_inode;
47749fe61450SChristian Brauner 	rd.new_dentry	   = new_dentry;
47756521f891SChristian Brauner 	rd.new_mnt_userns  = mnt_user_ns(new_path.mnt);
47769fe61450SChristian Brauner 	rd.delegated_inode = &delegated_inode;
47779fe61450SChristian Brauner 	rd.flags	   = flags;
47789fe61450SChristian Brauner 	error = vfs_rename(&rd);
47791da177e4SLinus Torvalds exit5:
47801da177e4SLinus Torvalds 	dput(new_dentry);
47811da177e4SLinus Torvalds exit4:
47821da177e4SLinus Torvalds 	dput(old_dentry);
47831da177e4SLinus Torvalds exit3:
4784f5beed75SAl Viro 	unlock_rename(new_path.dentry, old_path.dentry);
47858e6d782cSJ. Bruce Fields 	if (delegated_inode) {
47868e6d782cSJ. Bruce Fields 		error = break_deleg_wait(&delegated_inode);
47878e6d782cSJ. Bruce Fields 		if (!error)
47888e6d782cSJ. Bruce Fields 			goto retry_deleg;
47898e6d782cSJ. Bruce Fields 	}
4790f5beed75SAl Viro 	mnt_drop_write(old_path.mnt);
47911da177e4SLinus Torvalds exit2:
4792c6a94284SJeff Layton 	if (retry_estale(error, lookup_flags))
4793c6a94284SJeff Layton 		should_retry = true;
4794f5beed75SAl Viro 	path_put(&new_path);
47951da177e4SLinus Torvalds exit1:
4796f5beed75SAl Viro 	path_put(&old_path);
4797c6a94284SJeff Layton 	if (should_retry) {
4798c6a94284SJeff Layton 		should_retry = false;
4799c6a94284SJeff Layton 		lookup_flags |= LOOKUP_REVAL;
4800c6a94284SJeff Layton 		goto retry;
4801c6a94284SJeff Layton 	}
48020ee50b47SDmitry Kadashev put_names:
4803e886663cSJens Axboe 	putname(from);
4804e886663cSJens Axboe 	putname(to);
48051da177e4SLinus Torvalds 	return error;
48061da177e4SLinus Torvalds }
48071da177e4SLinus Torvalds 
4808ee81feb6SDominik Brodowski SYSCALL_DEFINE5(renameat2, int, olddfd, const char __user *, oldname,
4809ee81feb6SDominik Brodowski 		int, newdfd, const char __user *, newname, unsigned int, flags)
4810ee81feb6SDominik Brodowski {
4811e886663cSJens Axboe 	return do_renameat2(olddfd, getname(oldname), newdfd, getname(newname),
4812e886663cSJens Axboe 				flags);
4813ee81feb6SDominik Brodowski }
4814ee81feb6SDominik Brodowski 
4815520c8b16SMiklos Szeredi SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname,
4816520c8b16SMiklos Szeredi 		int, newdfd, const char __user *, newname)
4817520c8b16SMiklos Szeredi {
4818e886663cSJens Axboe 	return do_renameat2(olddfd, getname(oldname), newdfd, getname(newname),
4819e886663cSJens Axboe 				0);
4820520c8b16SMiklos Szeredi }
4821520c8b16SMiklos Szeredi 
4822a26eab24SHeiko Carstens SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname)
48235590ff0dSUlrich Drepper {
4824e886663cSJens Axboe 	return do_renameat2(AT_FDCWD, getname(oldname), AT_FDCWD,
4825e886663cSJens Axboe 				getname(newname), 0);
48265590ff0dSUlrich Drepper }
48275590ff0dSUlrich Drepper 
48285d826c84SAl Viro int readlink_copy(char __user *buffer, int buflen, const char *link)
48291da177e4SLinus Torvalds {
48305d826c84SAl Viro 	int len = PTR_ERR(link);
48311da177e4SLinus Torvalds 	if (IS_ERR(link))
48321da177e4SLinus Torvalds 		goto out;
48331da177e4SLinus Torvalds 
48341da177e4SLinus Torvalds 	len = strlen(link);
48351da177e4SLinus Torvalds 	if (len > (unsigned) buflen)
48361da177e4SLinus Torvalds 		len = buflen;
48371da177e4SLinus Torvalds 	if (copy_to_user(buffer, link, len))
48381da177e4SLinus Torvalds 		len = -EFAULT;
48391da177e4SLinus Torvalds out:
48401da177e4SLinus Torvalds 	return len;
48411da177e4SLinus Torvalds }
48421da177e4SLinus Torvalds 
4843d60874cdSMiklos Szeredi /**
4844fd4a0edfSMiklos Szeredi  * vfs_readlink - copy symlink body into userspace buffer
4845fd4a0edfSMiklos Szeredi  * @dentry: dentry on which to get symbolic link
4846fd4a0edfSMiklos Szeredi  * @buffer: user memory pointer
4847fd4a0edfSMiklos Szeredi  * @buflen: size of buffer
4848fd4a0edfSMiklos Szeredi  *
4849fd4a0edfSMiklos Szeredi  * Does not touch atime.  That's up to the caller if necessary
4850fd4a0edfSMiklos Szeredi  *
4851fd4a0edfSMiklos Szeredi  * Does not call security hook.
4852fd4a0edfSMiklos Szeredi  */
4853fd4a0edfSMiklos Szeredi int vfs_readlink(struct dentry *dentry, char __user *buffer, int buflen)
4854fd4a0edfSMiklos Szeredi {
4855fd4a0edfSMiklos Szeredi 	struct inode *inode = d_inode(dentry);
4856f2df5da6SAl Viro 	DEFINE_DELAYED_CALL(done);
4857f2df5da6SAl Viro 	const char *link;
4858f2df5da6SAl Viro 	int res;
4859fd4a0edfSMiklos Szeredi 
486076fca90eSMiklos Szeredi 	if (unlikely(!(inode->i_opflags & IOP_DEFAULT_READLINK))) {
486176fca90eSMiklos Szeredi 		if (unlikely(inode->i_op->readlink))
486276fca90eSMiklos Szeredi 			return inode->i_op->readlink(dentry, buffer, buflen);
486376fca90eSMiklos Szeredi 
486476fca90eSMiklos Szeredi 		if (!d_is_symlink(dentry))
4865fd4a0edfSMiklos Szeredi 			return -EINVAL;
4866fd4a0edfSMiklos Szeredi 
486776fca90eSMiklos Szeredi 		spin_lock(&inode->i_lock);
486876fca90eSMiklos Szeredi 		inode->i_opflags |= IOP_DEFAULT_READLINK;
486976fca90eSMiklos Szeredi 		spin_unlock(&inode->i_lock);
487076fca90eSMiklos Szeredi 	}
487176fca90eSMiklos Szeredi 
48724c4f7c19SEric Biggers 	link = READ_ONCE(inode->i_link);
4873f2df5da6SAl Viro 	if (!link) {
4874f2df5da6SAl Viro 		link = inode->i_op->get_link(dentry, inode, &done);
4875f2df5da6SAl Viro 		if (IS_ERR(link))
4876f2df5da6SAl Viro 			return PTR_ERR(link);
4877f2df5da6SAl Viro 	}
4878f2df5da6SAl Viro 	res = readlink_copy(buffer, buflen, link);
4879f2df5da6SAl Viro 	do_delayed_call(&done);
4880f2df5da6SAl Viro 	return res;
4881fd4a0edfSMiklos Szeredi }
4882fd4a0edfSMiklos Szeredi EXPORT_SYMBOL(vfs_readlink);
48831da177e4SLinus Torvalds 
4884d60874cdSMiklos Szeredi /**
4885d60874cdSMiklos Szeredi  * vfs_get_link - get symlink body
4886d60874cdSMiklos Szeredi  * @dentry: dentry on which to get symbolic link
4887d60874cdSMiklos Szeredi  * @done: caller needs to free returned data with this
4888d60874cdSMiklos Szeredi  *
4889d60874cdSMiklos Szeredi  * Calls security hook and i_op->get_link() on the supplied inode.
4890d60874cdSMiklos Szeredi  *
4891d60874cdSMiklos Szeredi  * It does not touch atime.  That's up to the caller if necessary.
4892d60874cdSMiklos Szeredi  *
4893d60874cdSMiklos Szeredi  * Does not work on "special" symlinks like /proc/$$/fd/N
4894d60874cdSMiklos Szeredi  */
4895d60874cdSMiklos Szeredi const char *vfs_get_link(struct dentry *dentry, struct delayed_call *done)
4896d60874cdSMiklos Szeredi {
4897d60874cdSMiklos Szeredi 	const char *res = ERR_PTR(-EINVAL);
4898d60874cdSMiklos Szeredi 	struct inode *inode = d_inode(dentry);
4899d60874cdSMiklos Szeredi 
4900d60874cdSMiklos Szeredi 	if (d_is_symlink(dentry)) {
4901d60874cdSMiklos Szeredi 		res = ERR_PTR(security_inode_readlink(dentry));
4902d60874cdSMiklos Szeredi 		if (!res)
4903d60874cdSMiklos Szeredi 			res = inode->i_op->get_link(dentry, inode, done);
4904d60874cdSMiklos Szeredi 	}
4905d60874cdSMiklos Szeredi 	return res;
4906d60874cdSMiklos Szeredi }
4907d60874cdSMiklos Szeredi EXPORT_SYMBOL(vfs_get_link);
4908d60874cdSMiklos Szeredi 
49091da177e4SLinus Torvalds /* get the link contents into pagecache */
49106b255391SAl Viro const char *page_get_link(struct dentry *dentry, struct inode *inode,
4911fceef393SAl Viro 			  struct delayed_call *callback)
49121da177e4SLinus Torvalds {
4913ebd09abbSDuane Griffin 	char *kaddr;
49141da177e4SLinus Torvalds 	struct page *page;
49156b255391SAl Viro 	struct address_space *mapping = inode->i_mapping;
49166b255391SAl Viro 
4917d3883d4fSAl Viro 	if (!dentry) {
4918d3883d4fSAl Viro 		page = find_get_page(mapping, 0);
4919d3883d4fSAl Viro 		if (!page)
49206b255391SAl Viro 			return ERR_PTR(-ECHILD);
4921d3883d4fSAl Viro 		if (!PageUptodate(page)) {
4922d3883d4fSAl Viro 			put_page(page);
4923d3883d4fSAl Viro 			return ERR_PTR(-ECHILD);
4924d3883d4fSAl Viro 		}
4925d3883d4fSAl Viro 	} else {
4926090d2b18SPekka Enberg 		page = read_mapping_page(mapping, 0, NULL);
49271da177e4SLinus Torvalds 		if (IS_ERR(page))
49286fe6900eSNick Piggin 			return (char*)page;
4929d3883d4fSAl Viro 	}
4930fceef393SAl Viro 	set_delayed_call(callback, page_put_link, page);
493121fc61c7SAl Viro 	BUG_ON(mapping_gfp_mask(mapping) & __GFP_HIGHMEM);
493221fc61c7SAl Viro 	kaddr = page_address(page);
49336b255391SAl Viro 	nd_terminate_link(kaddr, inode->i_size, PAGE_SIZE - 1);
4934ebd09abbSDuane Griffin 	return kaddr;
49351da177e4SLinus Torvalds }
49361da177e4SLinus Torvalds 
49376b255391SAl Viro EXPORT_SYMBOL(page_get_link);
49381da177e4SLinus Torvalds 
4939fceef393SAl Viro void page_put_link(void *arg)
49401da177e4SLinus Torvalds {
4941fceef393SAl Viro 	put_page(arg);
49421da177e4SLinus Torvalds }
49434d359507SAl Viro EXPORT_SYMBOL(page_put_link);
49441da177e4SLinus Torvalds 
4945aa80deabSAl Viro int page_readlink(struct dentry *dentry, char __user *buffer, int buflen)
4946aa80deabSAl Viro {
4947fceef393SAl Viro 	DEFINE_DELAYED_CALL(done);
49486b255391SAl Viro 	int res = readlink_copy(buffer, buflen,
49496b255391SAl Viro 				page_get_link(dentry, d_inode(dentry),
4950fceef393SAl Viro 					      &done));
4951fceef393SAl Viro 	do_delayed_call(&done);
4952aa80deabSAl Viro 	return res;
4953aa80deabSAl Viro }
4954aa80deabSAl Viro EXPORT_SYMBOL(page_readlink);
4955aa80deabSAl Viro 
495654566b2cSNick Piggin /*
495754566b2cSNick Piggin  * The nofs argument instructs pagecache_write_begin to pass AOP_FLAG_NOFS
495854566b2cSNick Piggin  */
495954566b2cSNick Piggin int __page_symlink(struct inode *inode, const char *symname, int len, int nofs)
49601da177e4SLinus Torvalds {
49611da177e4SLinus Torvalds 	struct address_space *mapping = inode->i_mapping;
49620adb25d2SKirill Korotaev 	struct page *page;
4963afddba49SNick Piggin 	void *fsdata;
4964beb497abSDmitriy Monakhov 	int err;
4965c718a975STetsuo Handa 	unsigned int flags = 0;
496654566b2cSNick Piggin 	if (nofs)
496754566b2cSNick Piggin 		flags |= AOP_FLAG_NOFS;
49681da177e4SLinus Torvalds 
49697e53cac4SNeilBrown retry:
4970afddba49SNick Piggin 	err = pagecache_write_begin(NULL, mapping, 0, len-1,
497154566b2cSNick Piggin 				flags, &page, &fsdata);
49721da177e4SLinus Torvalds 	if (err)
4973afddba49SNick Piggin 		goto fail;
4974afddba49SNick Piggin 
497521fc61c7SAl Viro 	memcpy(page_address(page), symname, len-1);
4976afddba49SNick Piggin 
4977afddba49SNick Piggin 	err = pagecache_write_end(NULL, mapping, 0, len-1, len-1,
4978afddba49SNick Piggin 							page, fsdata);
49791da177e4SLinus Torvalds 	if (err < 0)
49801da177e4SLinus Torvalds 		goto fail;
4981afddba49SNick Piggin 	if (err < len-1)
4982afddba49SNick Piggin 		goto retry;
4983afddba49SNick Piggin 
49841da177e4SLinus Torvalds 	mark_inode_dirty(inode);
49851da177e4SLinus Torvalds 	return 0;
49861da177e4SLinus Torvalds fail:
49871da177e4SLinus Torvalds 	return err;
49881da177e4SLinus Torvalds }
49894d359507SAl Viro EXPORT_SYMBOL(__page_symlink);
49901da177e4SLinus Torvalds 
49910adb25d2SKirill Korotaev int page_symlink(struct inode *inode, const char *symname, int len)
49920adb25d2SKirill Korotaev {
49930adb25d2SKirill Korotaev 	return __page_symlink(inode, symname, len,
4994c62d2555SMichal Hocko 			!mapping_gfp_constraint(inode->i_mapping, __GFP_FS));
49950adb25d2SKirill Korotaev }
49964d359507SAl Viro EXPORT_SYMBOL(page_symlink);
49970adb25d2SKirill Korotaev 
499892e1d5beSArjan van de Ven const struct inode_operations page_symlink_inode_operations = {
49996b255391SAl Viro 	.get_link	= page_get_link,
50001da177e4SLinus Torvalds };
50011da177e4SLinus Torvalds EXPORT_SYMBOL(page_symlink_inode_operations);
5002