xref: /openbmc/linux/fs/namei.c (revision 56f5746c)
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 {
258ea47ab11SAl Viro 	if (IS_ERR(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 
10239c011be1SLuis Chamberlain static int sysctl_protected_symlinks __read_mostly;
10249c011be1SLuis Chamberlain static int sysctl_protected_hardlinks __read_mostly;
10259c011be1SLuis Chamberlain static int sysctl_protected_fifos __read_mostly;
10269c011be1SLuis Chamberlain static int sysctl_protected_regular __read_mostly;
10279c011be1SLuis Chamberlain 
10289c011be1SLuis Chamberlain #ifdef CONFIG_SYSCTL
10299c011be1SLuis Chamberlain static struct ctl_table namei_sysctls[] = {
10309c011be1SLuis Chamberlain 	{
10319c011be1SLuis Chamberlain 		.procname	= "protected_symlinks",
10329c011be1SLuis Chamberlain 		.data		= &sysctl_protected_symlinks,
10339c011be1SLuis Chamberlain 		.maxlen		= sizeof(int),
10349c011be1SLuis Chamberlain 		.mode		= 0600,
10359c011be1SLuis Chamberlain 		.proc_handler	= proc_dointvec_minmax,
10369c011be1SLuis Chamberlain 		.extra1		= SYSCTL_ZERO,
10379c011be1SLuis Chamberlain 		.extra2		= SYSCTL_ONE,
10389c011be1SLuis Chamberlain 	},
10399c011be1SLuis Chamberlain 	{
10409c011be1SLuis Chamberlain 		.procname	= "protected_hardlinks",
10419c011be1SLuis Chamberlain 		.data		= &sysctl_protected_hardlinks,
10429c011be1SLuis Chamberlain 		.maxlen		= sizeof(int),
10439c011be1SLuis Chamberlain 		.mode		= 0600,
10449c011be1SLuis Chamberlain 		.proc_handler	= proc_dointvec_minmax,
10459c011be1SLuis Chamberlain 		.extra1		= SYSCTL_ZERO,
10469c011be1SLuis Chamberlain 		.extra2		= SYSCTL_ONE,
10479c011be1SLuis Chamberlain 	},
10489c011be1SLuis Chamberlain 	{
10499c011be1SLuis Chamberlain 		.procname	= "protected_fifos",
10509c011be1SLuis Chamberlain 		.data		= &sysctl_protected_fifos,
10519c011be1SLuis Chamberlain 		.maxlen		= sizeof(int),
10529c011be1SLuis Chamberlain 		.mode		= 0600,
10539c011be1SLuis Chamberlain 		.proc_handler	= proc_dointvec_minmax,
10549c011be1SLuis Chamberlain 		.extra1		= SYSCTL_ZERO,
10559c011be1SLuis Chamberlain 		.extra2		= SYSCTL_TWO,
10569c011be1SLuis Chamberlain 	},
10579c011be1SLuis Chamberlain 	{
10589c011be1SLuis Chamberlain 		.procname	= "protected_regular",
10599c011be1SLuis Chamberlain 		.data		= &sysctl_protected_regular,
10609c011be1SLuis Chamberlain 		.maxlen		= sizeof(int),
10619c011be1SLuis Chamberlain 		.mode		= 0600,
10629c011be1SLuis Chamberlain 		.proc_handler	= proc_dointvec_minmax,
10639c011be1SLuis Chamberlain 		.extra1		= SYSCTL_ZERO,
10649c011be1SLuis Chamberlain 		.extra2		= SYSCTL_TWO,
10659c011be1SLuis Chamberlain 	},
10669c011be1SLuis Chamberlain 	{ }
10679c011be1SLuis Chamberlain };
10689c011be1SLuis Chamberlain 
10699c011be1SLuis Chamberlain static int __init init_fs_namei_sysctls(void)
10709c011be1SLuis Chamberlain {
10719c011be1SLuis Chamberlain 	register_sysctl_init("fs", namei_sysctls);
10729c011be1SLuis Chamberlain 	return 0;
10739c011be1SLuis Chamberlain }
10749c011be1SLuis Chamberlain fs_initcall(init_fs_namei_sysctls);
10759c011be1SLuis Chamberlain 
10769c011be1SLuis Chamberlain #endif /* CONFIG_SYSCTL */
1077800179c9SKees Cook 
1078800179c9SKees Cook /**
1079800179c9SKees Cook  * may_follow_link - Check symlink following for unsafe situations
108055852635SRandy Dunlap  * @nd: nameidata pathwalk data
1081800179c9SKees Cook  *
1082800179c9SKees Cook  * In the case of the sysctl_protected_symlinks sysctl being enabled,
1083800179c9SKees Cook  * CAP_DAC_OVERRIDE needs to be specifically ignored if the symlink is
1084800179c9SKees Cook  * in a sticky world-writable directory. This is to protect privileged
1085800179c9SKees Cook  * processes from failing races against path names that may change out
1086800179c9SKees Cook  * from under them by way of other users creating malicious symlinks.
1087800179c9SKees Cook  * It will permit symlinks to be followed only when outside a sticky
1088800179c9SKees Cook  * world-writable directory, or when the uid of the symlink and follower
1089800179c9SKees Cook  * match, or when the directory owner matches the symlink's owner.
1090800179c9SKees Cook  *
1091800179c9SKees Cook  * Returns 0 if following the symlink is allowed, -ve on error.
1092800179c9SKees Cook  */
1093ad6cc4c3SAl Viro static inline int may_follow_link(struct nameidata *nd, const struct inode *inode)
1094800179c9SKees Cook {
1095ba73d987SChristian Brauner 	struct user_namespace *mnt_userns;
1096ba73d987SChristian Brauner 	kuid_t i_uid;
1097ba73d987SChristian Brauner 
1098800179c9SKees Cook 	if (!sysctl_protected_symlinks)
1099800179c9SKees Cook 		return 0;
1100800179c9SKees Cook 
1101ba73d987SChristian Brauner 	mnt_userns = mnt_user_ns(nd->path.mnt);
1102ba73d987SChristian Brauner 	i_uid = i_uid_into_mnt(mnt_userns, inode);
1103800179c9SKees Cook 	/* Allowed if owner and follower match. */
1104ba73d987SChristian Brauner 	if (uid_eq(current_cred()->fsuid, i_uid))
1105800179c9SKees Cook 		return 0;
1106800179c9SKees Cook 
1107800179c9SKees Cook 	/* Allowed if parent directory not sticky and world-writable. */
11080f705953SAl Viro 	if ((nd->dir_mode & (S_ISVTX|S_IWOTH)) != (S_ISVTX|S_IWOTH))
1109800179c9SKees Cook 		return 0;
1110800179c9SKees Cook 
1111800179c9SKees Cook 	/* Allowed if parent directory and link owner match. */
1112ba73d987SChristian Brauner 	if (uid_valid(nd->dir_uid) && uid_eq(nd->dir_uid, i_uid))
1113800179c9SKees Cook 		return 0;
1114800179c9SKees Cook 
111531956502SAl Viro 	if (nd->flags & LOOKUP_RCU)
111631956502SAl Viro 		return -ECHILD;
111731956502SAl Viro 
1118ea841bafSRichard Guy Briggs 	audit_inode(nd->name, nd->stack[0].link.dentry, 0);
1119245d7369SKees Cook 	audit_log_path_denied(AUDIT_ANOM_LINK, "follow_link");
1120800179c9SKees Cook 	return -EACCES;
1121800179c9SKees Cook }
1122800179c9SKees Cook 
1123800179c9SKees Cook /**
1124800179c9SKees Cook  * safe_hardlink_source - Check for safe hardlink conditions
1125ba73d987SChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
1126800179c9SKees Cook  * @inode: the source inode to hardlink from
1127800179c9SKees Cook  *
1128800179c9SKees Cook  * Return false if at least one of the following conditions:
1129800179c9SKees Cook  *    - inode is not a regular file
1130800179c9SKees Cook  *    - inode is setuid
1131800179c9SKees Cook  *    - inode is setgid and group-exec
1132800179c9SKees Cook  *    - access failure for read and write
1133800179c9SKees Cook  *
1134800179c9SKees Cook  * Otherwise returns true.
1135800179c9SKees Cook  */
1136ba73d987SChristian Brauner static bool safe_hardlink_source(struct user_namespace *mnt_userns,
1137ba73d987SChristian Brauner 				 struct inode *inode)
1138800179c9SKees Cook {
1139800179c9SKees Cook 	umode_t mode = inode->i_mode;
1140800179c9SKees Cook 
1141800179c9SKees Cook 	/* Special files should not get pinned to the filesystem. */
1142800179c9SKees Cook 	if (!S_ISREG(mode))
1143800179c9SKees Cook 		return false;
1144800179c9SKees Cook 
1145800179c9SKees Cook 	/* Setuid files should not get pinned to the filesystem. */
1146800179c9SKees Cook 	if (mode & S_ISUID)
1147800179c9SKees Cook 		return false;
1148800179c9SKees Cook 
1149800179c9SKees Cook 	/* Executable setgid files should not get pinned to the filesystem. */
1150800179c9SKees Cook 	if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP))
1151800179c9SKees Cook 		return false;
1152800179c9SKees Cook 
1153800179c9SKees Cook 	/* Hardlinking to unreadable or unwritable sources is dangerous. */
1154ba73d987SChristian Brauner 	if (inode_permission(mnt_userns, inode, MAY_READ | MAY_WRITE))
1155800179c9SKees Cook 		return false;
1156800179c9SKees Cook 
1157800179c9SKees Cook 	return true;
1158800179c9SKees Cook }
1159800179c9SKees Cook 
1160800179c9SKees Cook /**
1161800179c9SKees Cook  * may_linkat - Check permissions for creating a hardlink
1162ba73d987SChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
1163800179c9SKees Cook  * @link: the source to hardlink from
1164800179c9SKees Cook  *
1165800179c9SKees Cook  * Block hardlink when all of:
1166800179c9SKees Cook  *  - sysctl_protected_hardlinks enabled
1167800179c9SKees Cook  *  - fsuid does not match inode
1168800179c9SKees Cook  *  - hardlink source is unsafe (see safe_hardlink_source() above)
1169f2ca3796SDirk Steinmetz  *  - not CAP_FOWNER in a namespace with the inode owner uid mapped
1170800179c9SKees Cook  *
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  *
1177800179c9SKees Cook  * Returns 0 if successful, -ve on error.
1178800179c9SKees Cook  */
1179ba73d987SChristian Brauner int may_linkat(struct user_namespace *mnt_userns, struct path *link)
1180800179c9SKees Cook {
1181593d1ce8SEric W. Biederman 	struct inode *inode = link->dentry->d_inode;
1182593d1ce8SEric W. Biederman 
1183593d1ce8SEric W. Biederman 	/* Inode writeback is not safe when the uid or gid are invalid. */
1184ba73d987SChristian Brauner 	if (!uid_valid(i_uid_into_mnt(mnt_userns, inode)) ||
1185ba73d987SChristian Brauner 	    !gid_valid(i_gid_into_mnt(mnt_userns, inode)))
1186593d1ce8SEric W. Biederman 		return -EOVERFLOW;
1187800179c9SKees Cook 
1188800179c9SKees Cook 	if (!sysctl_protected_hardlinks)
1189800179c9SKees Cook 		return 0;
1190800179c9SKees Cook 
1191800179c9SKees Cook 	/* Source inode owner (or CAP_FOWNER) can hardlink all they like,
1192800179c9SKees Cook 	 * otherwise, it must be a safe source.
1193800179c9SKees Cook 	 */
1194ba73d987SChristian Brauner 	if (safe_hardlink_source(mnt_userns, inode) ||
1195ba73d987SChristian Brauner 	    inode_owner_or_capable(mnt_userns, inode))
1196800179c9SKees Cook 		return 0;
1197800179c9SKees Cook 
1198245d7369SKees Cook 	audit_log_path_denied(AUDIT_ANOM_LINK, "linkat");
1199800179c9SKees Cook 	return -EPERM;
1200800179c9SKees Cook }
1201800179c9SKees Cook 
120230aba665SSalvatore Mesoraca /**
120330aba665SSalvatore Mesoraca  * may_create_in_sticky - Check whether an O_CREAT open in a sticky directory
120430aba665SSalvatore Mesoraca  *			  should be allowed, or not, on files that already
120530aba665SSalvatore Mesoraca  *			  exist.
1206ba73d987SChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
12072111c3c0SRandy Dunlap  * @nd: nameidata pathwalk data
120830aba665SSalvatore Mesoraca  * @inode: the inode of the file to open
120930aba665SSalvatore Mesoraca  *
121030aba665SSalvatore Mesoraca  * Block an O_CREAT open of a FIFO (or a regular file) when:
121130aba665SSalvatore Mesoraca  *   - sysctl_protected_fifos (or sysctl_protected_regular) is enabled
121230aba665SSalvatore Mesoraca  *   - the file already exists
121330aba665SSalvatore Mesoraca  *   - we are in a sticky directory
121430aba665SSalvatore Mesoraca  *   - we don't own the file
121530aba665SSalvatore Mesoraca  *   - the owner of the directory doesn't own the file
121630aba665SSalvatore Mesoraca  *   - the directory is world writable
121730aba665SSalvatore Mesoraca  * If the sysctl_protected_fifos (or sysctl_protected_regular) is set to 2
121830aba665SSalvatore Mesoraca  * the directory doesn't have to be world writable: being group writable will
121930aba665SSalvatore Mesoraca  * be enough.
122030aba665SSalvatore Mesoraca  *
1221ba73d987SChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
1222ba73d987SChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
1223ba73d987SChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
1224ba73d987SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
1225ba73d987SChristian Brauner  * raw inode simply passs init_user_ns.
1226ba73d987SChristian Brauner  *
122730aba665SSalvatore Mesoraca  * Returns 0 if the open is allowed, -ve on error.
122830aba665SSalvatore Mesoraca  */
1229ba73d987SChristian Brauner static int may_create_in_sticky(struct user_namespace *mnt_userns,
1230ba73d987SChristian Brauner 				struct nameidata *nd, struct inode *const inode)
123130aba665SSalvatore Mesoraca {
1232ba73d987SChristian Brauner 	umode_t dir_mode = nd->dir_mode;
1233ba73d987SChristian Brauner 	kuid_t dir_uid = nd->dir_uid;
1234ba73d987SChristian Brauner 
123530aba665SSalvatore Mesoraca 	if ((!sysctl_protected_fifos && S_ISFIFO(inode->i_mode)) ||
123630aba665SSalvatore Mesoraca 	    (!sysctl_protected_regular && S_ISREG(inode->i_mode)) ||
1237d0cb5018SAl Viro 	    likely(!(dir_mode & S_ISVTX)) ||
1238ba73d987SChristian Brauner 	    uid_eq(i_uid_into_mnt(mnt_userns, inode), dir_uid) ||
1239ba73d987SChristian Brauner 	    uid_eq(current_fsuid(), i_uid_into_mnt(mnt_userns, inode)))
124030aba665SSalvatore Mesoraca 		return 0;
124130aba665SSalvatore Mesoraca 
1242d0cb5018SAl Viro 	if (likely(dir_mode & 0002) ||
1243d0cb5018SAl Viro 	    (dir_mode & 0020 &&
124430aba665SSalvatore Mesoraca 	     ((sysctl_protected_fifos >= 2 && S_ISFIFO(inode->i_mode)) ||
124530aba665SSalvatore Mesoraca 	      (sysctl_protected_regular >= 2 && S_ISREG(inode->i_mode))))) {
1246245d7369SKees Cook 		const char *operation = S_ISFIFO(inode->i_mode) ?
1247245d7369SKees Cook 					"sticky_create_fifo" :
1248245d7369SKees Cook 					"sticky_create_regular";
1249245d7369SKees Cook 		audit_log_path_denied(AUDIT_ANOM_CREAT, operation);
125030aba665SSalvatore Mesoraca 		return -EACCES;
125130aba665SSalvatore Mesoraca 	}
125230aba665SSalvatore Mesoraca 	return 0;
125330aba665SSalvatore Mesoraca }
125430aba665SSalvatore Mesoraca 
1255f015f126SDavid Howells /*
1256f015f126SDavid Howells  * follow_up - Find the mountpoint of path's vfsmount
1257f015f126SDavid Howells  *
1258f015f126SDavid Howells  * Given a path, find the mountpoint of its source file system.
1259f015f126SDavid Howells  * Replace @path with the path of the mountpoint in the parent mount.
1260f015f126SDavid Howells  * Up is towards /.
1261f015f126SDavid Howells  *
1262f015f126SDavid Howells  * Return 1 if we went up a level and 0 if we were already at the
1263f015f126SDavid Howells  * root.
1264f015f126SDavid Howells  */
1265bab77ebfSAl Viro int follow_up(struct path *path)
12661da177e4SLinus Torvalds {
12670714a533SAl Viro 	struct mount *mnt = real_mount(path->mnt);
12680714a533SAl Viro 	struct mount *parent;
12691da177e4SLinus Torvalds 	struct dentry *mountpoint;
127099b7db7bSNick Piggin 
127148a066e7SAl Viro 	read_seqlock_excl(&mount_lock);
12720714a533SAl Viro 	parent = mnt->mnt_parent;
12733c0a6163SAl Viro 	if (parent == mnt) {
127448a066e7SAl Viro 		read_sequnlock_excl(&mount_lock);
12751da177e4SLinus Torvalds 		return 0;
12761da177e4SLinus Torvalds 	}
12770714a533SAl Viro 	mntget(&parent->mnt);
1278a73324daSAl Viro 	mountpoint = dget(mnt->mnt_mountpoint);
127948a066e7SAl Viro 	read_sequnlock_excl(&mount_lock);
1280bab77ebfSAl Viro 	dput(path->dentry);
1281bab77ebfSAl Viro 	path->dentry = mountpoint;
1282bab77ebfSAl Viro 	mntput(path->mnt);
12830714a533SAl Viro 	path->mnt = &parent->mnt;
12841da177e4SLinus Torvalds 	return 1;
12851da177e4SLinus Torvalds }
12864d359507SAl Viro EXPORT_SYMBOL(follow_up);
12871da177e4SLinus Torvalds 
12887ef482faSAl Viro static bool choose_mountpoint_rcu(struct mount *m, const struct path *root,
12897ef482faSAl Viro 				  struct path *path, unsigned *seqp)
12907ef482faSAl Viro {
12917ef482faSAl Viro 	while (mnt_has_parent(m)) {
12927ef482faSAl Viro 		struct dentry *mountpoint = m->mnt_mountpoint;
12937ef482faSAl Viro 
12947ef482faSAl Viro 		m = m->mnt_parent;
12957ef482faSAl Viro 		if (unlikely(root->dentry == mountpoint &&
12967ef482faSAl Viro 			     root->mnt == &m->mnt))
12977ef482faSAl Viro 			break;
12987ef482faSAl Viro 		if (mountpoint != m->mnt.mnt_root) {
12997ef482faSAl Viro 			path->mnt = &m->mnt;
13007ef482faSAl Viro 			path->dentry = mountpoint;
13017ef482faSAl Viro 			*seqp = read_seqcount_begin(&mountpoint->d_seq);
13027ef482faSAl Viro 			return true;
13037ef482faSAl Viro 		}
13047ef482faSAl Viro 	}
13057ef482faSAl Viro 	return false;
13067ef482faSAl Viro }
13077ef482faSAl Viro 
13082aa38470SAl Viro static bool choose_mountpoint(struct mount *m, const struct path *root,
13092aa38470SAl Viro 			      struct path *path)
13102aa38470SAl Viro {
13112aa38470SAl Viro 	bool found;
13122aa38470SAl Viro 
13132aa38470SAl Viro 	rcu_read_lock();
13142aa38470SAl Viro 	while (1) {
13152aa38470SAl Viro 		unsigned seq, mseq = read_seqbegin(&mount_lock);
13162aa38470SAl Viro 
13172aa38470SAl Viro 		found = choose_mountpoint_rcu(m, root, path, &seq);
13182aa38470SAl Viro 		if (unlikely(!found)) {
13192aa38470SAl Viro 			if (!read_seqretry(&mount_lock, mseq))
13202aa38470SAl Viro 				break;
13212aa38470SAl Viro 		} else {
13222aa38470SAl Viro 			if (likely(__legitimize_path(path, seq, mseq)))
13232aa38470SAl Viro 				break;
13242aa38470SAl Viro 			rcu_read_unlock();
13252aa38470SAl Viro 			path_put(path);
13262aa38470SAl Viro 			rcu_read_lock();
13272aa38470SAl Viro 		}
13282aa38470SAl Viro 	}
13292aa38470SAl Viro 	rcu_read_unlock();
13302aa38470SAl Viro 	return found;
13312aa38470SAl Viro }
13322aa38470SAl Viro 
1333b5c84bf6SNick Piggin /*
13349875cf80SDavid Howells  * Perform an automount
13359875cf80SDavid Howells  * - return -EISDIR to tell follow_managed() to stop and return the path we
13369875cf80SDavid Howells  *   were called with.
13371da177e4SLinus Torvalds  */
13381c9f5e06SAl Viro static int follow_automount(struct path *path, int *count, unsigned lookup_flags)
133931e6b01fSNick Piggin {
134025e195aaSAl Viro 	struct dentry *dentry = path->dentry;
13419875cf80SDavid Howells 
13420ec26fd0SMiklos Szeredi 	/* We don't want to mount if someone's just doing a stat -
13430ec26fd0SMiklos Szeredi 	 * unless they're stat'ing a directory and appended a '/' to
13440ec26fd0SMiklos Szeredi 	 * the name.
13450ec26fd0SMiklos Szeredi 	 *
13460ec26fd0SMiklos Szeredi 	 * We do, however, want to mount if someone wants to open or
13475a30d8a2SDavid Howells 	 * create a file of any type under the mountpoint, wants to
13480ec26fd0SMiklos Szeredi 	 * traverse through the mountpoint or wants to open the
13490ec26fd0SMiklos Szeredi 	 * mounted directory.  Also, autofs may mark negative dentries
13500ec26fd0SMiklos Szeredi 	 * as being automount points.  These will need the attentions
13510ec26fd0SMiklos Szeredi 	 * of the daemon to instantiate them before they can be used.
13525a30d8a2SDavid Howells 	 */
13531c9f5e06SAl Viro 	if (!(lookup_flags & (LOOKUP_PARENT | LOOKUP_DIRECTORY |
13545d38f049SIan Kent 			   LOOKUP_OPEN | LOOKUP_CREATE | LOOKUP_AUTOMOUNT)) &&
135525e195aaSAl Viro 	    dentry->d_inode)
13569875cf80SDavid Howells 		return -EISDIR;
13570ec26fd0SMiklos Szeredi 
13581c9f5e06SAl Viro 	if (count && (*count)++ >= MAXSYMLINKS)
13599875cf80SDavid Howells 		return -ELOOP;
13609875cf80SDavid Howells 
136125e195aaSAl Viro 	return finish_automount(dentry->d_op->d_automount(path), path);
1362ea5b778aSDavid Howells }
13639875cf80SDavid Howells 
13649875cf80SDavid Howells /*
13659deed3ebSAl Viro  * mount traversal - out-of-line part.  One note on ->d_flags accesses -
13669deed3ebSAl Viro  * dentries are pinned but not locked here, so negative dentry can go
13679deed3ebSAl Viro  * positive right under us.  Use of smp_load_acquire() provides a barrier
13689deed3ebSAl Viro  * sufficient for ->d_inode and ->d_flags consistency.
13699875cf80SDavid Howells  */
13709deed3ebSAl Viro static int __traverse_mounts(struct path *path, unsigned flags, bool *jumped,
13719deed3ebSAl Viro 			     int *count, unsigned lookup_flags)
13729875cf80SDavid Howells {
13739deed3ebSAl Viro 	struct vfsmount *mnt = path->mnt;
13749875cf80SDavid Howells 	bool need_mntput = false;
13758aef1884SAl Viro 	int ret = 0;
13769875cf80SDavid Howells 
13779deed3ebSAl Viro 	while (flags & DCACHE_MANAGED_DENTRY) {
1378cc53ce53SDavid Howells 		/* Allow the filesystem to manage the transit without i_mutex
1379cc53ce53SDavid Howells 		 * being held. */
1380d41efb52SAl Viro 		if (flags & DCACHE_MANAGE_TRANSIT) {
1381fb5f51c7SIan Kent 			ret = path->dentry->d_op->d_manage(path, false);
1382508c8772SAl Viro 			flags = smp_load_acquire(&path->dentry->d_flags);
1383cc53ce53SDavid Howells 			if (ret < 0)
13848aef1884SAl Viro 				break;
1385cc53ce53SDavid Howells 		}
1386cc53ce53SDavid Howells 
13879deed3ebSAl Viro 		if (flags & DCACHE_MOUNTED) {	// something's mounted on it..
13889875cf80SDavid Howells 			struct vfsmount *mounted = lookup_mnt(path);
13899deed3ebSAl Viro 			if (mounted) {		// ... in our namespace
13909875cf80SDavid Howells 				dput(path->dentry);
13919875cf80SDavid Howells 				if (need_mntput)
1392463ffb2eSAl Viro 					mntput(path->mnt);
1393463ffb2eSAl Viro 				path->mnt = mounted;
1394463ffb2eSAl Viro 				path->dentry = dget(mounted->mnt_root);
13959deed3ebSAl Viro 				// here we know it's positive
13969deed3ebSAl Viro 				flags = path->dentry->d_flags;
13979875cf80SDavid Howells 				need_mntput = true;
13989875cf80SDavid Howells 				continue;
1399463ffb2eSAl Viro 			}
14001da177e4SLinus Torvalds 		}
14019875cf80SDavid Howells 
14029deed3ebSAl Viro 		if (!(flags & DCACHE_NEED_AUTOMOUNT))
14039deed3ebSAl Viro 			break;
14049deed3ebSAl Viro 
14059deed3ebSAl Viro 		// uncovered automount point
14069deed3ebSAl Viro 		ret = follow_automount(path, count, lookup_flags);
14079deed3ebSAl Viro 		flags = smp_load_acquire(&path->dentry->d_flags);
14089875cf80SDavid Howells 		if (ret < 0)
14098aef1884SAl Viro 			break;
14109875cf80SDavid Howells 	}
14119875cf80SDavid Howells 
14129deed3ebSAl Viro 	if (ret == -EISDIR)
14139deed3ebSAl Viro 		ret = 0;
14149deed3ebSAl Viro 	// possible if you race with several mount --move
14159deed3ebSAl Viro 	if (need_mntput && path->mnt == mnt)
14168aef1884SAl Viro 		mntput(path->mnt);
14179deed3ebSAl Viro 	if (!ret && unlikely(d_flags_negative(flags)))
1418d41efb52SAl Viro 		ret = -ENOENT;
14199deed3ebSAl Viro 	*jumped = need_mntput;
14208402752eSAl Viro 	return ret;
14211da177e4SLinus Torvalds }
14221da177e4SLinus Torvalds 
14239deed3ebSAl Viro static inline int traverse_mounts(struct path *path, bool *jumped,
14249deed3ebSAl Viro 				  int *count, unsigned lookup_flags)
14259deed3ebSAl Viro {
14269deed3ebSAl Viro 	unsigned flags = smp_load_acquire(&path->dentry->d_flags);
14279deed3ebSAl Viro 
14289deed3ebSAl Viro 	/* fastpath */
14299deed3ebSAl Viro 	if (likely(!(flags & DCACHE_MANAGED_DENTRY))) {
14309deed3ebSAl Viro 		*jumped = false;
14319deed3ebSAl Viro 		if (unlikely(d_flags_negative(flags)))
14329deed3ebSAl Viro 			return -ENOENT;
14339deed3ebSAl Viro 		return 0;
14349deed3ebSAl Viro 	}
14359deed3ebSAl Viro 	return __traverse_mounts(path, flags, jumped, count, lookup_flags);
14369deed3ebSAl Viro }
14379deed3ebSAl Viro 
1438cc53ce53SDavid Howells int follow_down_one(struct path *path)
14391da177e4SLinus Torvalds {
14401da177e4SLinus Torvalds 	struct vfsmount *mounted;
14411da177e4SLinus Torvalds 
14421c755af4SAl Viro 	mounted = lookup_mnt(path);
14431da177e4SLinus Torvalds 	if (mounted) {
14449393bd07SAl Viro 		dput(path->dentry);
14459393bd07SAl Viro 		mntput(path->mnt);
14469393bd07SAl Viro 		path->mnt = mounted;
14479393bd07SAl Viro 		path->dentry = dget(mounted->mnt_root);
14481da177e4SLinus Torvalds 		return 1;
14491da177e4SLinus Torvalds 	}
14501da177e4SLinus Torvalds 	return 0;
14511da177e4SLinus Torvalds }
14524d359507SAl Viro EXPORT_SYMBOL(follow_down_one);
14531da177e4SLinus Torvalds 
14549875cf80SDavid Howells /*
14559deed3ebSAl Viro  * Follow down to the covering mount currently visible to userspace.  At each
14569deed3ebSAl Viro  * point, the filesystem owning that dentry may be queried as to whether the
14579deed3ebSAl Viro  * caller is permitted to proceed or not.
14589deed3ebSAl Viro  */
14599deed3ebSAl Viro int follow_down(struct path *path)
14609deed3ebSAl Viro {
14619deed3ebSAl Viro 	struct vfsmount *mnt = path->mnt;
14629deed3ebSAl Viro 	bool jumped;
14639deed3ebSAl Viro 	int ret = traverse_mounts(path, &jumped, NULL, 0);
14649deed3ebSAl Viro 
14659deed3ebSAl Viro 	if (path->mnt != mnt)
14669deed3ebSAl Viro 		mntput(mnt);
14679deed3ebSAl Viro 	return ret;
14689deed3ebSAl Viro }
14699deed3ebSAl Viro EXPORT_SYMBOL(follow_down);
14709deed3ebSAl Viro 
14719deed3ebSAl Viro /*
1472287548e4SAl Viro  * Try to skip to top of mountpoint pile in rcuwalk mode.  Fail if
1473287548e4SAl Viro  * we meet a managed dentry that would need blocking.
14749875cf80SDavid Howells  */
14759875cf80SDavid Howells static bool __follow_mount_rcu(struct nameidata *nd, struct path *path,
1476254cf582SAl Viro 			       struct inode **inode, unsigned *seqp)
14779875cf80SDavid Howells {
1478ea936aebSAl Viro 	struct dentry *dentry = path->dentry;
1479ea936aebSAl Viro 	unsigned int flags = dentry->d_flags;
1480ea936aebSAl Viro 
1481ea936aebSAl Viro 	if (likely(!(flags & DCACHE_MANAGED_DENTRY)))
1482ea936aebSAl Viro 		return true;
1483ea936aebSAl Viro 
1484ea936aebSAl Viro 	if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1485ea936aebSAl Viro 		return false;
1486ea936aebSAl Viro 
148762a7375eSIan Kent 	for (;;) {
148862a7375eSIan Kent 		/*
148962a7375eSIan Kent 		 * Don't forget we might have a non-mountpoint managed dentry
149062a7375eSIan Kent 		 * that wants to block transit.
149162a7375eSIan Kent 		 */
1492ea936aebSAl Viro 		if (unlikely(flags & DCACHE_MANAGE_TRANSIT)) {
1493ea936aebSAl Viro 			int res = dentry->d_op->d_manage(path, true);
1494ea936aebSAl Viro 			if (res)
1495ea936aebSAl Viro 				return res == -EISDIR;
1496ea936aebSAl Viro 			flags = dentry->d_flags;
1497b8faf035SNeilBrown 		}
149862a7375eSIan Kent 
1499ea936aebSAl Viro 		if (flags & DCACHE_MOUNTED) {
1500ea936aebSAl Viro 			struct mount *mounted = __lookup_mnt(path->mnt, dentry);
1501ea936aebSAl Viro 			if (mounted) {
1502c7105365SAl Viro 				path->mnt = &mounted->mnt;
1503ea936aebSAl Viro 				dentry = path->dentry = mounted->mnt.mnt_root;
1504bcba1e7dSAl Viro 				nd->state |= ND_JUMPED;
1505ea936aebSAl Viro 				*seqp = read_seqcount_begin(&dentry->d_seq);
1506ea936aebSAl Viro 				*inode = dentry->d_inode;
150759430262SLinus Torvalds 				/*
1508ea936aebSAl Viro 				 * We don't need to re-check ->d_seq after this
1509ea936aebSAl Viro 				 * ->d_inode read - there will be an RCU delay
1510ea936aebSAl Viro 				 * between mount hash removal and ->mnt_root
1511ea936aebSAl Viro 				 * becoming unpinned.
151259430262SLinus Torvalds 				 */
1513ea936aebSAl Viro 				flags = dentry->d_flags;
1514ea936aebSAl Viro 				continue;
15159875cf80SDavid Howells 			}
1516ea936aebSAl Viro 			if (read_seqretry(&mount_lock, nd->m_seq))
1517ea936aebSAl Viro 				return false;
1518ea936aebSAl Viro 		}
1519ea936aebSAl Viro 		return !(flags & DCACHE_NEED_AUTOMOUNT);
1520ea936aebSAl Viro 	}
1521287548e4SAl Viro }
1522287548e4SAl Viro 
1523db3c9adeSAl Viro static inline int handle_mounts(struct nameidata *nd, struct dentry *dentry,
1524db3c9adeSAl Viro 			  struct path *path, struct inode **inode,
1525db3c9adeSAl Viro 			  unsigned int *seqp)
1526bd7c4b50SAl Viro {
15279deed3ebSAl Viro 	bool jumped;
1528db3c9adeSAl Viro 	int ret;
1529bd7c4b50SAl Viro 
1530db3c9adeSAl Viro 	path->mnt = nd->path.mnt;
1531db3c9adeSAl Viro 	path->dentry = dentry;
1532c153007bSAl Viro 	if (nd->flags & LOOKUP_RCU) {
1533c153007bSAl Viro 		unsigned int seq = *seqp;
1534c153007bSAl Viro 		if (unlikely(!*inode))
1535c153007bSAl Viro 			return -ENOENT;
1536c153007bSAl Viro 		if (likely(__follow_mount_rcu(nd, path, inode, seqp)))
15379deed3ebSAl Viro 			return 0;
1538ae66db45SAl Viro 		if (!try_to_unlazy_next(nd, dentry, seq))
1539c153007bSAl Viro 			return -ECHILD;
1540c153007bSAl Viro 		// *path might've been clobbered by __follow_mount_rcu()
1541c153007bSAl Viro 		path->mnt = nd->path.mnt;
1542c153007bSAl Viro 		path->dentry = dentry;
1543c153007bSAl Viro 	}
15449deed3ebSAl Viro 	ret = traverse_mounts(path, &jumped, &nd->total_link_count, nd->flags);
15459deed3ebSAl Viro 	if (jumped) {
15469deed3ebSAl Viro 		if (unlikely(nd->flags & LOOKUP_NO_XDEV))
15479deed3ebSAl Viro 			ret = -EXDEV;
15489deed3ebSAl Viro 		else
1549bcba1e7dSAl Viro 			nd->state |= ND_JUMPED;
15509deed3ebSAl Viro 	}
15519deed3ebSAl Viro 	if (unlikely(ret)) {
15529deed3ebSAl Viro 		dput(path->dentry);
15539deed3ebSAl Viro 		if (path->mnt != nd->path.mnt)
15549deed3ebSAl Viro 			mntput(path->mnt);
15559deed3ebSAl Viro 	} else {
1556bd7c4b50SAl Viro 		*inode = d_backing_inode(path->dentry);
1557bd7c4b50SAl Viro 		*seqp = 0; /* out of RCU mode, so the value doesn't matter */
1558bd7c4b50SAl Viro 	}
1559bd7c4b50SAl Viro 	return ret;
1560bd7c4b50SAl Viro }
1561bd7c4b50SAl Viro 
15629875cf80SDavid Howells /*
1563f4fdace9SOleg Drokin  * This looks up the name in dcache and possibly revalidates the found dentry.
1564f4fdace9SOleg Drokin  * NULL is returned if the dentry does not exist in the cache.
1565baa03890SNick Piggin  */
1566e3c13928SAl Viro static struct dentry *lookup_dcache(const struct qstr *name,
1567e3c13928SAl Viro 				    struct dentry *dir,
15686c51e513SAl Viro 				    unsigned int flags)
1569baa03890SNick Piggin {
1570a89f8337SAl Viro 	struct dentry *dentry = d_lookup(dir, name);
1571bad61189SMiklos Szeredi 	if (dentry) {
1572a89f8337SAl Viro 		int error = d_revalidate(dentry, flags);
1573bad61189SMiklos Szeredi 		if (unlikely(error <= 0)) {
157474ff0ffcSAl Viro 			if (!error)
15755542aa2fSEric W. Biederman 				d_invalidate(dentry);
1576bad61189SMiklos Szeredi 			dput(dentry);
157774ff0ffcSAl Viro 			return ERR_PTR(error);
1578bad61189SMiklos Szeredi 		}
1579bad61189SMiklos Szeredi 	}
1580baa03890SNick Piggin 	return dentry;
1581baa03890SNick Piggin }
1582baa03890SNick Piggin 
1583baa03890SNick Piggin /*
1584a03ece5fSAl Viro  * Parent directory has inode locked exclusive.  This is one
1585a03ece5fSAl Viro  * and only case when ->lookup() gets called on non in-lookup
1586a03ece5fSAl Viro  * dentries - as the matter of fact, this only gets called
1587a03ece5fSAl Viro  * when directory is guaranteed to have no in-lookup children
1588a03ece5fSAl Viro  * at all.
158944396f4bSJosef Bacik  */
1590a03ece5fSAl Viro static struct dentry *__lookup_hash(const struct qstr *name,
1591a03ece5fSAl Viro 		struct dentry *base, unsigned int flags)
159244396f4bSJosef Bacik {
1593a03ece5fSAl Viro 	struct dentry *dentry = lookup_dcache(name, base, flags);
159444396f4bSJosef Bacik 	struct dentry *old;
1595a03ece5fSAl Viro 	struct inode *dir = base->d_inode;
1596a03ece5fSAl Viro 
1597a03ece5fSAl Viro 	if (dentry)
1598a03ece5fSAl Viro 		return dentry;
159944396f4bSJosef Bacik 
160044396f4bSJosef Bacik 	/* Don't create child dentry for a dead directory. */
1601a03ece5fSAl Viro 	if (unlikely(IS_DEADDIR(dir)))
160244396f4bSJosef Bacik 		return ERR_PTR(-ENOENT);
1603a03ece5fSAl Viro 
1604a03ece5fSAl Viro 	dentry = d_alloc(base, name);
1605a03ece5fSAl Viro 	if (unlikely(!dentry))
1606a03ece5fSAl Viro 		return ERR_PTR(-ENOMEM);
160744396f4bSJosef Bacik 
160872bd866aSAl Viro 	old = dir->i_op->lookup(dir, dentry, flags);
160944396f4bSJosef Bacik 	if (unlikely(old)) {
161044396f4bSJosef Bacik 		dput(dentry);
161144396f4bSJosef Bacik 		dentry = old;
161244396f4bSJosef Bacik 	}
161344396f4bSJosef Bacik 	return dentry;
161444396f4bSJosef Bacik }
161544396f4bSJosef Bacik 
161620e34357SAl Viro static struct dentry *lookup_fast(struct nameidata *nd,
161720e34357SAl Viro 				  struct inode **inode,
1618254cf582SAl Viro 			          unsigned *seqp)
16191da177e4SLinus Torvalds {
162031e6b01fSNick Piggin 	struct dentry *dentry, *parent = nd->path.dentry;
16215a18fff2SAl Viro 	int status = 1;
16229875cf80SDavid Howells 
16233cac260aSAl Viro 	/*
1624b04f784eSNick Piggin 	 * Rename seqlock is not required here because in the off chance
16255d0f49c1SAl Viro 	 * of a false negative due to a concurrent rename, the caller is
16265d0f49c1SAl Viro 	 * going to fall back to non-racy lookup.
1627b04f784eSNick Piggin 	 */
162831e6b01fSNick Piggin 	if (nd->flags & LOOKUP_RCU) {
162931e6b01fSNick Piggin 		unsigned seq;
1630da53be12SLinus Torvalds 		dentry = __d_lookup_rcu(parent, &nd->last, &seq);
16315d0f49c1SAl Viro 		if (unlikely(!dentry)) {
1632e36cffedSJens Axboe 			if (!try_to_unlazy(nd))
163320e34357SAl Viro 				return ERR_PTR(-ECHILD);
163420e34357SAl Viro 			return NULL;
16355d0f49c1SAl Viro 		}
16365a18fff2SAl Viro 
163712f8ad4bSLinus Torvalds 		/*
163812f8ad4bSLinus Torvalds 		 * This sequence count validates that the inode matches
163912f8ad4bSLinus Torvalds 		 * the dentry name information from lookup.
164012f8ad4bSLinus Torvalds 		 */
164163afdfc7SDavid Howells 		*inode = d_backing_inode(dentry);
16425d0f49c1SAl Viro 		if (unlikely(read_seqcount_retry(&dentry->d_seq, seq)))
164320e34357SAl Viro 			return ERR_PTR(-ECHILD);
164412f8ad4bSLinus Torvalds 
164512f8ad4bSLinus Torvalds 		/*
164612f8ad4bSLinus Torvalds 		 * This sequence count validates that the parent had no
164712f8ad4bSLinus Torvalds 		 * changes while we did the lookup of the dentry above.
164812f8ad4bSLinus Torvalds 		 *
164912f8ad4bSLinus Torvalds 		 * The memory barrier in read_seqcount_begin of child is
165012f8ad4bSLinus Torvalds 		 *  enough, we can use __read_seqcount_retry here.
165112f8ad4bSLinus Torvalds 		 */
16525d0f49c1SAl Viro 		if (unlikely(__read_seqcount_retry(&parent->d_seq, nd->seq)))
165320e34357SAl Viro 			return ERR_PTR(-ECHILD);
16545a18fff2SAl Viro 
1655254cf582SAl Viro 		*seqp = seq;
16564ce16ef3SAl Viro 		status = d_revalidate(dentry, nd->flags);
1657c153007bSAl Viro 		if (likely(status > 0))
165820e34357SAl Viro 			return dentry;
1659ae66db45SAl Viro 		if (!try_to_unlazy_next(nd, dentry, seq))
166020e34357SAl Viro 			return ERR_PTR(-ECHILD);
166126ddb45eSSteven Rostedt (VMware) 		if (status == -ECHILD)
1662209a7fb2SAl Viro 			/* we'd been told to redo it in non-rcu mode */
1663209a7fb2SAl Viro 			status = d_revalidate(dentry, nd->flags);
16645a18fff2SAl Viro 	} else {
1665e97cdc87SAl Viro 		dentry = __d_lookup(parent, &nd->last);
166681e6f520SAl Viro 		if (unlikely(!dentry))
166720e34357SAl Viro 			return NULL;
16684ce16ef3SAl Viro 		status = d_revalidate(dentry, nd->flags);
16695d0f49c1SAl Viro 	}
16705a18fff2SAl Viro 	if (unlikely(status <= 0)) {
1671e9742b53SAl Viro 		if (!status)
16725d0f49c1SAl Viro 			d_invalidate(dentry);
16735a18fff2SAl Viro 		dput(dentry);
167420e34357SAl Viro 		return ERR_PTR(status);
16755a18fff2SAl Viro 	}
167620e34357SAl Viro 	return dentry;
1677697f514dSMiklos Szeredi }
1678697f514dSMiklos Szeredi 
1679697f514dSMiklos Szeredi /* Fast lookup failed, do it the slow way */
168088d8331aSAl Viro static struct dentry *__lookup_slow(const struct qstr *name,
1681e3c13928SAl Viro 				    struct dentry *dir,
1682e3c13928SAl Viro 				    unsigned int flags)
1683697f514dSMiklos Szeredi {
168488d8331aSAl Viro 	struct dentry *dentry, *old;
16851936386eSAl Viro 	struct inode *inode = dir->d_inode;
1686d9171b93SAl Viro 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
16871936386eSAl Viro 
16881936386eSAl Viro 	/* Don't go there if it's already dead */
168994bdd655SAl Viro 	if (unlikely(IS_DEADDIR(inode)))
169088d8331aSAl Viro 		return ERR_PTR(-ENOENT);
169194bdd655SAl Viro again:
1692d9171b93SAl Viro 	dentry = d_alloc_parallel(dir, name, &wq);
169394bdd655SAl Viro 	if (IS_ERR(dentry))
169488d8331aSAl Viro 		return dentry;
169594bdd655SAl Viro 	if (unlikely(!d_in_lookup(dentry))) {
1696949a852eSAl Viro 		int error = d_revalidate(dentry, flags);
1697949a852eSAl Viro 		if (unlikely(error <= 0)) {
169894bdd655SAl Viro 			if (!error) {
1699949a852eSAl Viro 				d_invalidate(dentry);
1700949a852eSAl Viro 				dput(dentry);
170194bdd655SAl Viro 				goto again;
170294bdd655SAl Viro 			}
170394bdd655SAl Viro 			dput(dentry);
1704949a852eSAl Viro 			dentry = ERR_PTR(error);
1705949a852eSAl Viro 		}
170694bdd655SAl Viro 	} else {
17071936386eSAl Viro 		old = inode->i_op->lookup(inode, dentry, flags);
170885c7f810SAl Viro 		d_lookup_done(dentry);
17091936386eSAl Viro 		if (unlikely(old)) {
17101936386eSAl Viro 			dput(dentry);
17111936386eSAl Viro 			dentry = old;
1712949a852eSAl Viro 		}
1713949a852eSAl Viro 	}
1714e3c13928SAl Viro 	return dentry;
17151da177e4SLinus Torvalds }
17161da177e4SLinus Torvalds 
171788d8331aSAl Viro static struct dentry *lookup_slow(const struct qstr *name,
171888d8331aSAl Viro 				  struct dentry *dir,
171988d8331aSAl Viro 				  unsigned int flags)
172088d8331aSAl Viro {
172188d8331aSAl Viro 	struct inode *inode = dir->d_inode;
172288d8331aSAl Viro 	struct dentry *res;
172388d8331aSAl Viro 	inode_lock_shared(inode);
172488d8331aSAl Viro 	res = __lookup_slow(name, dir, flags);
172588d8331aSAl Viro 	inode_unlock_shared(inode);
172688d8331aSAl Viro 	return res;
172788d8331aSAl Viro }
172888d8331aSAl Viro 
1729ba73d987SChristian Brauner static inline int may_lookup(struct user_namespace *mnt_userns,
1730ba73d987SChristian Brauner 			     struct nameidata *nd)
173152094c8aSAl Viro {
173252094c8aSAl Viro 	if (nd->flags & LOOKUP_RCU) {
17337d6beb71SLinus Torvalds 		int err = inode_permission(mnt_userns, nd->inode, MAY_EXEC|MAY_NOT_BLOCK);
1734e36cffedSJens Axboe 		if (err != -ECHILD || !try_to_unlazy(nd))
173552094c8aSAl Viro 			return err;
173652094c8aSAl Viro 	}
1737ba73d987SChristian Brauner 	return inode_permission(mnt_userns, nd->inode, MAY_EXEC);
173852094c8aSAl Viro }
173952094c8aSAl Viro 
174049055906SAl Viro static int reserve_stack(struct nameidata *nd, struct path *link, unsigned seq)
1741d63ff28fSAl Viro {
174249055906SAl Viro 	if (unlikely(nd->total_link_count++ >= MAXSYMLINKS))
174349055906SAl Viro 		return -ELOOP;
17444542576bSAl Viro 
17454542576bSAl Viro 	if (likely(nd->depth != EMBEDDED_LEVELS))
17464542576bSAl Viro 		return 0;
17474542576bSAl Viro 	if (likely(nd->stack != nd->internal))
17484542576bSAl Viro 		return 0;
174960ef60c7SAl Viro 	if (likely(nd_alloc_stack(nd)))
175049055906SAl Viro 		return 0;
175160ef60c7SAl Viro 
175260ef60c7SAl Viro 	if (nd->flags & LOOKUP_RCU) {
175360ef60c7SAl Viro 		// we need to grab link before we do unlazy.  And we can't skip
175460ef60c7SAl Viro 		// unlazy even if we fail to grab the link - cleanup needs it
1755aef9404dSAl Viro 		bool grabbed_link = legitimize_path(nd, link, seq);
175660ef60c7SAl Viro 
1757e36cffedSJens Axboe 		if (!try_to_unlazy(nd) != 0 || !grabbed_link)
175860ef60c7SAl Viro 			return -ECHILD;
175960ef60c7SAl Viro 
176060ef60c7SAl Viro 		if (nd_alloc_stack(nd))
176160ef60c7SAl Viro 			return 0;
1762bc40aee0SAl Viro 	}
176360ef60c7SAl Viro 	return -ENOMEM;
176449055906SAl Viro }
176549055906SAl Viro 
176649055906SAl Viro enum {WALK_TRAILING = 1, WALK_MORE = 2, WALK_NOFOLLOW = 4};
176749055906SAl Viro 
176849055906SAl Viro static const char *pick_link(struct nameidata *nd, struct path *link,
176949055906SAl Viro 		     struct inode *inode, unsigned seq, int flags)
177049055906SAl Viro {
177149055906SAl Viro 	struct saved *last;
177249055906SAl Viro 	const char *res;
177349055906SAl Viro 	int error = reserve_stack(nd, link, seq);
177449055906SAl Viro 
177549055906SAl Viro 	if (unlikely(error)) {
177649055906SAl Viro 		if (!(nd->flags & LOOKUP_RCU))
1777cd179f44SAl Viro 			path_put(link);
177806708adbSAl Viro 		return ERR_PTR(error);
1779626de996SAl Viro 	}
1780ab104923SAl Viro 	last = nd->stack + nd->depth++;
17811cf2665bSAl Viro 	last->link = *link;
1782fceef393SAl Viro 	clear_delayed_call(&last->done);
17830450b2d1SAl Viro 	last->seq = seq;
1784ad6cc4c3SAl Viro 
1785b1a81972SAl Viro 	if (flags & WALK_TRAILING) {
1786ad6cc4c3SAl Viro 		error = may_follow_link(nd, inode);
1787ad6cc4c3SAl Viro 		if (unlikely(error))
1788ad6cc4c3SAl Viro 			return ERR_PTR(error);
1789ad6cc4c3SAl Viro 	}
1790ad6cc4c3SAl Viro 
1791dab741e0SMattias Nissler 	if (unlikely(nd->flags & LOOKUP_NO_SYMLINKS) ||
1792dab741e0SMattias Nissler 			unlikely(link->mnt->mnt_flags & MNT_NOSYMFOLLOW))
1793ad6cc4c3SAl Viro 		return ERR_PTR(-ELOOP);
1794ad6cc4c3SAl Viro 
1795ad6cc4c3SAl Viro 	if (!(nd->flags & LOOKUP_RCU)) {
1796ad6cc4c3SAl Viro 		touch_atime(&last->link);
1797ad6cc4c3SAl Viro 		cond_resched();
1798ad6cc4c3SAl Viro 	} else if (atime_needs_update(&last->link, inode)) {
1799e36cffedSJens Axboe 		if (!try_to_unlazy(nd))
1800ad6cc4c3SAl Viro 			return ERR_PTR(-ECHILD);
1801ad6cc4c3SAl Viro 		touch_atime(&last->link);
1802ad6cc4c3SAl Viro 	}
1803ad6cc4c3SAl Viro 
1804ad6cc4c3SAl Viro 	error = security_inode_follow_link(link->dentry, inode,
1805ad6cc4c3SAl Viro 					   nd->flags & LOOKUP_RCU);
1806ad6cc4c3SAl Viro 	if (unlikely(error))
1807ad6cc4c3SAl Viro 		return ERR_PTR(error);
1808ad6cc4c3SAl Viro 
1809ad6cc4c3SAl Viro 	res = READ_ONCE(inode->i_link);
1810ad6cc4c3SAl Viro 	if (!res) {
1811ad6cc4c3SAl Viro 		const char * (*get)(struct dentry *, struct inode *,
1812ad6cc4c3SAl Viro 				struct delayed_call *);
1813ad6cc4c3SAl Viro 		get = inode->i_op->get_link;
1814ad6cc4c3SAl Viro 		if (nd->flags & LOOKUP_RCU) {
1815ad6cc4c3SAl Viro 			res = get(NULL, inode, &last->done);
1816e36cffedSJens Axboe 			if (res == ERR_PTR(-ECHILD) && try_to_unlazy(nd))
1817ad6cc4c3SAl Viro 				res = get(link->dentry, inode, &last->done);
1818ad6cc4c3SAl Viro 		} else {
1819ad6cc4c3SAl Viro 			res = get(link->dentry, inode, &last->done);
1820ad6cc4c3SAl Viro 		}
1821ad6cc4c3SAl Viro 		if (!res)
1822ad6cc4c3SAl Viro 			goto all_done;
1823ad6cc4c3SAl Viro 		if (IS_ERR(res))
1824ad6cc4c3SAl Viro 			return res;
1825ad6cc4c3SAl Viro 	}
1826ad6cc4c3SAl Viro 	if (*res == '/') {
1827ad6cc4c3SAl Viro 		error = nd_jump_root(nd);
1828ad6cc4c3SAl Viro 		if (unlikely(error))
1829ad6cc4c3SAl Viro 			return ERR_PTR(error);
1830ad6cc4c3SAl Viro 		while (unlikely(*++res == '/'))
1831ad6cc4c3SAl Viro 			;
1832ad6cc4c3SAl Viro 	}
1833ad6cc4c3SAl Viro 	if (*res)
1834ad6cc4c3SAl Viro 		return res;
1835ad6cc4c3SAl Viro all_done: // pure jump
1836ad6cc4c3SAl Viro 	put_link(nd);
1837ad6cc4c3SAl Viro 	return NULL;
1838d63ff28fSAl Viro }
1839d63ff28fSAl Viro 
18403ddcd056SLinus Torvalds /*
18413ddcd056SLinus Torvalds  * Do we need to follow links? We _really_ want to be able
18423ddcd056SLinus Torvalds  * to do this check without having to look at inode->i_op,
18433ddcd056SLinus Torvalds  * so we keep a cache of "no, this doesn't need follow_link"
18443ddcd056SLinus Torvalds  * for the common case.
18453ddcd056SLinus Torvalds  */
1846b0417d2cSAl Viro static const char *step_into(struct nameidata *nd, int flags,
1847cbae4d12SAl Viro 		     struct dentry *dentry, struct inode *inode, unsigned seq)
18483ddcd056SLinus Torvalds {
1849cbae4d12SAl Viro 	struct path path;
1850cbae4d12SAl Viro 	int err = handle_mounts(nd, dentry, &path, &inode, &seq);
1851cbae4d12SAl Viro 
1852cbae4d12SAl Viro 	if (err < 0)
1853b0417d2cSAl Viro 		return ERR_PTR(err);
1854cbae4d12SAl Viro 	if (likely(!d_is_symlink(path.dentry)) ||
18558c4efe22SAl Viro 	   ((flags & WALK_TRAILING) && !(nd->flags & LOOKUP_FOLLOW)) ||
1856aca2903eSAl Viro 	   (flags & WALK_NOFOLLOW)) {
18578f64fb1cSAl Viro 		/* not a symlink or should not follow */
1858c99687a0SAl Viro 		if (!(nd->flags & LOOKUP_RCU)) {
1859c99687a0SAl Viro 			dput(nd->path.dentry);
1860c99687a0SAl Viro 			if (nd->path.mnt != path.mnt)
1861c99687a0SAl Viro 				mntput(nd->path.mnt);
1862c99687a0SAl Viro 		}
1863c99687a0SAl Viro 		nd->path = path;
18648f64fb1cSAl Viro 		nd->inode = inode;
18658f64fb1cSAl Viro 		nd->seq = seq;
1866b0417d2cSAl Viro 		return NULL;
18678f64fb1cSAl Viro 	}
1868a7f77542SAl Viro 	if (nd->flags & LOOKUP_RCU) {
186984f0cd9eSAl Viro 		/* make sure that d_is_symlink above matches inode */
1870cbae4d12SAl Viro 		if (read_seqcount_retry(&path.dentry->d_seq, seq))
1871b0417d2cSAl Viro 			return ERR_PTR(-ECHILD);
187284f0cd9eSAl Viro 	} else {
187384f0cd9eSAl Viro 		if (path.mnt == nd->path.mnt)
187484f0cd9eSAl Viro 			mntget(path.mnt);
1875a7f77542SAl Viro 	}
1876b1a81972SAl Viro 	return pick_link(nd, &path, inode, seq, flags);
18773ddcd056SLinus Torvalds }
18783ddcd056SLinus Torvalds 
1879c2df1968SAl Viro static struct dentry *follow_dotdot_rcu(struct nameidata *nd,
1880c2df1968SAl Viro 					struct inode **inodep,
1881c2df1968SAl Viro 					unsigned *seqp)
1882957dd41dSAl Viro {
188312487f30SAl Viro 	struct dentry *parent, *old;
1884957dd41dSAl Viro 
188512487f30SAl Viro 	if (path_equal(&nd->path, &nd->root))
188612487f30SAl Viro 		goto in_root;
188712487f30SAl Viro 	if (unlikely(nd->path.dentry == nd->path.mnt->mnt_root)) {
18887ef482faSAl Viro 		struct path path;
1889efe772d6SAl Viro 		unsigned seq;
18907ef482faSAl Viro 		if (!choose_mountpoint_rcu(real_mount(nd->path.mnt),
18917ef482faSAl Viro 					   &nd->root, &path, &seq))
189212487f30SAl Viro 			goto in_root;
1893efe772d6SAl Viro 		if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1894efe772d6SAl Viro 			return ERR_PTR(-ECHILD);
1895efe772d6SAl Viro 		nd->path = path;
1896efe772d6SAl Viro 		nd->inode = path.dentry->d_inode;
1897efe772d6SAl Viro 		nd->seq = seq;
1898efe772d6SAl Viro 		if (unlikely(read_seqretry(&mount_lock, nd->m_seq)))
1899efe772d6SAl Viro 			return ERR_PTR(-ECHILD);
1900efe772d6SAl Viro 		/* we know that mountpoint was pinned */
1901957dd41dSAl Viro 	}
190212487f30SAl Viro 	old = nd->path.dentry;
190312487f30SAl Viro 	parent = old->d_parent;
190412487f30SAl Viro 	*inodep = parent->d_inode;
190512487f30SAl Viro 	*seqp = read_seqcount_begin(&parent->d_seq);
190612487f30SAl Viro 	if (unlikely(read_seqcount_retry(&old->d_seq, nd->seq)))
190712487f30SAl Viro 		return ERR_PTR(-ECHILD);
190812487f30SAl Viro 	if (unlikely(!path_connected(nd->path.mnt, parent)))
190912487f30SAl Viro 		return ERR_PTR(-ECHILD);
191012487f30SAl Viro 	return parent;
191112487f30SAl Viro in_root:
1912efe772d6SAl Viro 	if (unlikely(read_seqretry(&mount_lock, nd->m_seq)))
1913efe772d6SAl Viro 		return ERR_PTR(-ECHILD);
1914957dd41dSAl Viro 	if (unlikely(nd->flags & LOOKUP_BENEATH))
19157521f22bSAl Viro 		return ERR_PTR(-ECHILD);
1916c2df1968SAl Viro 	return NULL;
1917957dd41dSAl Viro }
1918957dd41dSAl Viro 
1919c2df1968SAl Viro static struct dentry *follow_dotdot(struct nameidata *nd,
1920c2df1968SAl Viro 				 struct inode **inodep,
1921c2df1968SAl Viro 				 unsigned *seqp)
1922957dd41dSAl Viro {
192312487f30SAl Viro 	struct dentry *parent;
192412487f30SAl Viro 
1925957dd41dSAl Viro 	if (path_equal(&nd->path, &nd->root))
192612487f30SAl Viro 		goto in_root;
192712487f30SAl Viro 	if (unlikely(nd->path.dentry == nd->path.mnt->mnt_root)) {
19282aa38470SAl Viro 		struct path path;
19292aa38470SAl Viro 
19302aa38470SAl Viro 		if (!choose_mountpoint(real_mount(nd->path.mnt),
19312aa38470SAl Viro 				       &nd->root, &path))
193212487f30SAl Viro 			goto in_root;
1933165200d6SAl Viro 		path_put(&nd->path);
1934165200d6SAl Viro 		nd->path = path;
19352aa38470SAl Viro 		nd->inode = path.dentry->d_inode;
1936165200d6SAl Viro 		if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1937165200d6SAl Viro 			return ERR_PTR(-EXDEV);
193812487f30SAl Viro 	}
1939957dd41dSAl Viro 	/* rare case of legitimate dget_parent()... */
194012487f30SAl Viro 	parent = dget_parent(nd->path.dentry);
1941957dd41dSAl Viro 	if (unlikely(!path_connected(nd->path.mnt, parent))) {
1942957dd41dSAl Viro 		dput(parent);
19437521f22bSAl Viro 		return ERR_PTR(-ENOENT);
1944957dd41dSAl Viro 	}
1945c2df1968SAl Viro 	*seqp = 0;
1946c2df1968SAl Viro 	*inodep = parent->d_inode;
1947c2df1968SAl Viro 	return parent;
194812487f30SAl Viro 
194912487f30SAl Viro in_root:
1950957dd41dSAl Viro 	if (unlikely(nd->flags & LOOKUP_BENEATH))
19517521f22bSAl Viro 		return ERR_PTR(-EXDEV);
1952c2df1968SAl Viro 	dget(nd->path.dentry);
1953c2df1968SAl Viro 	return NULL;
1954957dd41dSAl Viro }
1955957dd41dSAl Viro 
19567521f22bSAl Viro static const char *handle_dots(struct nameidata *nd, int type)
1957957dd41dSAl Viro {
1958957dd41dSAl Viro 	if (type == LAST_DOTDOT) {
19597521f22bSAl Viro 		const char *error = NULL;
1960c2df1968SAl Viro 		struct dentry *parent;
1961c2df1968SAl Viro 		struct inode *inode;
1962c2df1968SAl Viro 		unsigned seq;
1963957dd41dSAl Viro 
1964957dd41dSAl Viro 		if (!nd->root.mnt) {
19657521f22bSAl Viro 			error = ERR_PTR(set_root(nd));
1966957dd41dSAl Viro 			if (error)
1967957dd41dSAl Viro 				return error;
1968957dd41dSAl Viro 		}
1969957dd41dSAl Viro 		if (nd->flags & LOOKUP_RCU)
1970c2df1968SAl Viro 			parent = follow_dotdot_rcu(nd, &inode, &seq);
1971957dd41dSAl Viro 		else
1972c2df1968SAl Viro 			parent = follow_dotdot(nd, &inode, &seq);
1973c2df1968SAl Viro 		if (IS_ERR(parent))
1974c2df1968SAl Viro 			return ERR_CAST(parent);
1975c2df1968SAl Viro 		if (unlikely(!parent))
1976c2df1968SAl Viro 			error = step_into(nd, WALK_NOFOLLOW,
1977c2df1968SAl Viro 					 nd->path.dentry, nd->inode, nd->seq);
1978c2df1968SAl Viro 		else
1979c2df1968SAl Viro 			error = step_into(nd, WALK_NOFOLLOW,
1980c2df1968SAl Viro 					 parent, inode, seq);
1981c2df1968SAl Viro 		if (unlikely(error))
1982957dd41dSAl Viro 			return error;
1983957dd41dSAl Viro 
1984957dd41dSAl Viro 		if (unlikely(nd->flags & LOOKUP_IS_SCOPED)) {
1985957dd41dSAl Viro 			/*
1986957dd41dSAl Viro 			 * If there was a racing rename or mount along our
1987957dd41dSAl Viro 			 * path, then we can't be sure that ".." hasn't jumped
1988957dd41dSAl Viro 			 * above nd->root (and so userspace should retry or use
1989957dd41dSAl Viro 			 * some fallback).
1990957dd41dSAl Viro 			 */
1991957dd41dSAl Viro 			smp_rmb();
1992957dd41dSAl Viro 			if (unlikely(__read_seqcount_retry(&mount_lock.seqcount, nd->m_seq)))
19937521f22bSAl Viro 				return ERR_PTR(-EAGAIN);
1994957dd41dSAl Viro 			if (unlikely(__read_seqcount_retry(&rename_lock.seqcount, nd->r_seq)))
19957521f22bSAl Viro 				return ERR_PTR(-EAGAIN);
1996957dd41dSAl Viro 		}
1997957dd41dSAl Viro 	}
19987521f22bSAl Viro 	return NULL;
1999957dd41dSAl Viro }
2000957dd41dSAl Viro 
200192d27016SAl Viro static const char *walk_component(struct nameidata *nd, int flags)
2002ce57dfc1SAl Viro {
2003db3c9adeSAl Viro 	struct dentry *dentry;
2004ce57dfc1SAl Viro 	struct inode *inode;
2005254cf582SAl Viro 	unsigned seq;
2006ce57dfc1SAl Viro 	/*
2007ce57dfc1SAl Viro 	 * "." and ".." are special - ".." especially so because it has
2008ce57dfc1SAl Viro 	 * to be able to know about the current root directory and
2009ce57dfc1SAl Viro 	 * parent relationships.
2010ce57dfc1SAl Viro 	 */
20114693a547SAl Viro 	if (unlikely(nd->last_type != LAST_NORM)) {
20121c4ff1a8SAl Viro 		if (!(flags & WALK_MORE) && nd->depth)
20134693a547SAl Viro 			put_link(nd);
20147521f22bSAl Viro 		return handle_dots(nd, nd->last_type);
20154693a547SAl Viro 	}
201620e34357SAl Viro 	dentry = lookup_fast(nd, &inode, &seq);
201720e34357SAl Viro 	if (IS_ERR(dentry))
201892d27016SAl Viro 		return ERR_CAST(dentry);
201920e34357SAl Viro 	if (unlikely(!dentry)) {
2020db3c9adeSAl Viro 		dentry = lookup_slow(&nd->last, nd->path.dentry, nd->flags);
2021db3c9adeSAl Viro 		if (IS_ERR(dentry))
202292d27016SAl Viro 			return ERR_CAST(dentry);
202320e34357SAl Viro 	}
202456676ec3SAl Viro 	if (!(flags & WALK_MORE) && nd->depth)
202556676ec3SAl Viro 		put_link(nd);
2026b0417d2cSAl Viro 	return step_into(nd, flags, dentry, inode, seq);
2027ce57dfc1SAl Viro }
2028ce57dfc1SAl Viro 
20291da177e4SLinus Torvalds /*
2030bfcfaa77SLinus Torvalds  * We can do the critical dentry name comparison and hashing
2031bfcfaa77SLinus Torvalds  * operations one word at a time, but we are limited to:
2032bfcfaa77SLinus Torvalds  *
2033bfcfaa77SLinus Torvalds  * - Architectures with fast unaligned word accesses. We could
2034bfcfaa77SLinus Torvalds  *   do a "get_unaligned()" if this helps and is sufficiently
2035bfcfaa77SLinus Torvalds  *   fast.
2036bfcfaa77SLinus Torvalds  *
2037bfcfaa77SLinus Torvalds  * - non-CONFIG_DEBUG_PAGEALLOC configurations (so that we
2038bfcfaa77SLinus Torvalds  *   do not trap on the (extremely unlikely) case of a page
2039bfcfaa77SLinus Torvalds  *   crossing operation.
2040bfcfaa77SLinus Torvalds  *
2041bfcfaa77SLinus Torvalds  * - Furthermore, we need an efficient 64-bit compile for the
2042bfcfaa77SLinus Torvalds  *   64-bit case in order to generate the "number of bytes in
2043bfcfaa77SLinus Torvalds  *   the final mask". Again, that could be replaced with a
2044bfcfaa77SLinus Torvalds  *   efficient population count instruction or similar.
2045bfcfaa77SLinus Torvalds  */
2046bfcfaa77SLinus Torvalds #ifdef CONFIG_DCACHE_WORD_ACCESS
2047bfcfaa77SLinus Torvalds 
2048f68e556eSLinus Torvalds #include <asm/word-at-a-time.h>
2049bfcfaa77SLinus Torvalds 
2050468a9428SGeorge Spelvin #ifdef HASH_MIX
2051bfcfaa77SLinus Torvalds 
2052468a9428SGeorge Spelvin /* Architecture provides HASH_MIX and fold_hash() in <asm/hash.h> */
2053468a9428SGeorge Spelvin 
2054468a9428SGeorge Spelvin #elif defined(CONFIG_64BIT)
20552a18da7aSGeorge Spelvin /*
20562a18da7aSGeorge Spelvin  * Register pressure in the mixing function is an issue, particularly
20572a18da7aSGeorge Spelvin  * on 32-bit x86, but almost any function requires one state value and
20582a18da7aSGeorge Spelvin  * one temporary.  Instead, use a function designed for two state values
20592a18da7aSGeorge Spelvin  * and no temporaries.
20602a18da7aSGeorge Spelvin  *
20612a18da7aSGeorge Spelvin  * This function cannot create a collision in only two iterations, so
20622a18da7aSGeorge Spelvin  * we have two iterations to achieve avalanche.  In those two iterations,
20632a18da7aSGeorge Spelvin  * we have six layers of mixing, which is enough to spread one bit's
20642a18da7aSGeorge Spelvin  * influence out to 2^6 = 64 state bits.
20652a18da7aSGeorge Spelvin  *
20662a18da7aSGeorge Spelvin  * Rotate constants are scored by considering either 64 one-bit input
20672a18da7aSGeorge Spelvin  * deltas or 64*63/2 = 2016 two-bit input deltas, and finding the
20682a18da7aSGeorge Spelvin  * probability of that delta causing a change to each of the 128 output
20692a18da7aSGeorge Spelvin  * bits, using a sample of random initial states.
20702a18da7aSGeorge Spelvin  *
20712a18da7aSGeorge Spelvin  * The Shannon entropy of the computed probabilities is then summed
20722a18da7aSGeorge Spelvin  * to produce a score.  Ideally, any input change has a 50% chance of
20732a18da7aSGeorge Spelvin  * toggling any given output bit.
20742a18da7aSGeorge Spelvin  *
20752a18da7aSGeorge Spelvin  * Mixing scores (in bits) for (12,45):
20762a18da7aSGeorge Spelvin  * Input delta: 1-bit      2-bit
20772a18da7aSGeorge Spelvin  * 1 round:     713.3    42542.6
20782a18da7aSGeorge Spelvin  * 2 rounds:   2753.7   140389.8
20792a18da7aSGeorge Spelvin  * 3 rounds:   5954.1   233458.2
20802a18da7aSGeorge Spelvin  * 4 rounds:   7862.6   256672.2
20812a18da7aSGeorge Spelvin  * Perfect:    8192     258048
20822a18da7aSGeorge Spelvin  *            (64*128) (64*63/2 * 128)
20832a18da7aSGeorge Spelvin  */
20842a18da7aSGeorge Spelvin #define HASH_MIX(x, y, a)	\
20852a18da7aSGeorge Spelvin 	(	x ^= (a),	\
20862a18da7aSGeorge Spelvin 	y ^= x,	x = rol64(x,12),\
20872a18da7aSGeorge Spelvin 	x += y,	y = rol64(y,45),\
20882a18da7aSGeorge Spelvin 	y *= 9			)
2089bfcfaa77SLinus Torvalds 
20900fed3ac8SGeorge Spelvin /*
20912a18da7aSGeorge Spelvin  * Fold two longs into one 32-bit hash value.  This must be fast, but
20922a18da7aSGeorge Spelvin  * latency isn't quite as critical, as there is a fair bit of additional
20932a18da7aSGeorge Spelvin  * work done before the hash value is used.
20940fed3ac8SGeorge Spelvin  */
20952a18da7aSGeorge Spelvin static inline unsigned int fold_hash(unsigned long x, unsigned long y)
20960fed3ac8SGeorge Spelvin {
20972a18da7aSGeorge Spelvin 	y ^= x * GOLDEN_RATIO_64;
20982a18da7aSGeorge Spelvin 	y *= GOLDEN_RATIO_64;
20992a18da7aSGeorge Spelvin 	return y >> 32;
21000fed3ac8SGeorge Spelvin }
21010fed3ac8SGeorge Spelvin 
2102bfcfaa77SLinus Torvalds #else	/* 32-bit case */
2103bfcfaa77SLinus Torvalds 
21042a18da7aSGeorge Spelvin /*
21052a18da7aSGeorge Spelvin  * Mixing scores (in bits) for (7,20):
21062a18da7aSGeorge Spelvin  * Input delta: 1-bit      2-bit
21072a18da7aSGeorge Spelvin  * 1 round:     330.3     9201.6
21082a18da7aSGeorge Spelvin  * 2 rounds:   1246.4    25475.4
21092a18da7aSGeorge Spelvin  * 3 rounds:   1907.1    31295.1
21102a18da7aSGeorge Spelvin  * 4 rounds:   2042.3    31718.6
21112a18da7aSGeorge Spelvin  * Perfect:    2048      31744
21122a18da7aSGeorge Spelvin  *            (32*64)   (32*31/2 * 64)
21132a18da7aSGeorge Spelvin  */
21142a18da7aSGeorge Spelvin #define HASH_MIX(x, y, a)	\
21152a18da7aSGeorge Spelvin 	(	x ^= (a),	\
21162a18da7aSGeorge Spelvin 	y ^= x,	x = rol32(x, 7),\
21172a18da7aSGeorge Spelvin 	x += y,	y = rol32(y,20),\
21182a18da7aSGeorge Spelvin 	y *= 9			)
2119bfcfaa77SLinus Torvalds 
21202a18da7aSGeorge Spelvin static inline unsigned int fold_hash(unsigned long x, unsigned long y)
21210fed3ac8SGeorge Spelvin {
21222a18da7aSGeorge Spelvin 	/* Use arch-optimized multiply if one exists */
21232a18da7aSGeorge Spelvin 	return __hash_32(y ^ __hash_32(x));
21240fed3ac8SGeorge Spelvin }
21250fed3ac8SGeorge Spelvin 
2126bfcfaa77SLinus Torvalds #endif
2127bfcfaa77SLinus Torvalds 
21282a18da7aSGeorge Spelvin /*
21292a18da7aSGeorge Spelvin  * Return the hash of a string of known length.  This is carfully
21302a18da7aSGeorge Spelvin  * designed to match hash_name(), which is the more critical function.
21312a18da7aSGeorge Spelvin  * In particular, we must end by hashing a final word containing 0..7
21322a18da7aSGeorge Spelvin  * payload bytes, to match the way that hash_name() iterates until it
21332a18da7aSGeorge Spelvin  * finds the delimiter after the name.
21342a18da7aSGeorge Spelvin  */
21358387ff25SLinus Torvalds unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
2136bfcfaa77SLinus Torvalds {
21378387ff25SLinus Torvalds 	unsigned long a, x = 0, y = (unsigned long)salt;
2138bfcfaa77SLinus Torvalds 
2139bfcfaa77SLinus Torvalds 	for (;;) {
2140fcfd2fbfSGeorge Spelvin 		if (!len)
2141fcfd2fbfSGeorge Spelvin 			goto done;
2142e419b4ccSLinus Torvalds 		a = load_unaligned_zeropad(name);
2143bfcfaa77SLinus Torvalds 		if (len < sizeof(unsigned long))
2144bfcfaa77SLinus Torvalds 			break;
21452a18da7aSGeorge Spelvin 		HASH_MIX(x, y, a);
2146bfcfaa77SLinus Torvalds 		name += sizeof(unsigned long);
2147bfcfaa77SLinus Torvalds 		len -= sizeof(unsigned long);
2148bfcfaa77SLinus Torvalds 	}
21492a18da7aSGeorge Spelvin 	x ^= a & bytemask_from_count(len);
2150bfcfaa77SLinus Torvalds done:
21512a18da7aSGeorge Spelvin 	return fold_hash(x, y);
2152bfcfaa77SLinus Torvalds }
2153bfcfaa77SLinus Torvalds EXPORT_SYMBOL(full_name_hash);
2154bfcfaa77SLinus Torvalds 
2155fcfd2fbfSGeorge Spelvin /* Return the "hash_len" (hash and length) of a null-terminated string */
21568387ff25SLinus Torvalds u64 hashlen_string(const void *salt, const char *name)
2157fcfd2fbfSGeorge Spelvin {
21588387ff25SLinus Torvalds 	unsigned long a = 0, x = 0, y = (unsigned long)salt;
21598387ff25SLinus Torvalds 	unsigned long adata, mask, len;
2160fcfd2fbfSGeorge Spelvin 	const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2161fcfd2fbfSGeorge Spelvin 
21628387ff25SLinus Torvalds 	len = 0;
21638387ff25SLinus Torvalds 	goto inside;
21648387ff25SLinus Torvalds 
2165fcfd2fbfSGeorge Spelvin 	do {
21662a18da7aSGeorge Spelvin 		HASH_MIX(x, y, a);
2167fcfd2fbfSGeorge Spelvin 		len += sizeof(unsigned long);
21688387ff25SLinus Torvalds inside:
2169fcfd2fbfSGeorge Spelvin 		a = load_unaligned_zeropad(name+len);
2170fcfd2fbfSGeorge Spelvin 	} while (!has_zero(a, &adata, &constants));
2171fcfd2fbfSGeorge Spelvin 
2172fcfd2fbfSGeorge Spelvin 	adata = prep_zero_mask(a, adata, &constants);
2173fcfd2fbfSGeorge Spelvin 	mask = create_zero_mask(adata);
21742a18da7aSGeorge Spelvin 	x ^= a & zero_bytemask(mask);
2175fcfd2fbfSGeorge Spelvin 
21762a18da7aSGeorge Spelvin 	return hashlen_create(fold_hash(x, y), len + find_zero(mask));
2177fcfd2fbfSGeorge Spelvin }
2178fcfd2fbfSGeorge Spelvin EXPORT_SYMBOL(hashlen_string);
2179fcfd2fbfSGeorge Spelvin 
2180bfcfaa77SLinus Torvalds /*
2181bfcfaa77SLinus Torvalds  * Calculate the length and hash of the path component, and
2182d6bb3e90SLinus Torvalds  * return the "hash_len" as the result.
2183bfcfaa77SLinus Torvalds  */
21848387ff25SLinus Torvalds static inline u64 hash_name(const void *salt, const char *name)
2185bfcfaa77SLinus Torvalds {
21868387ff25SLinus Torvalds 	unsigned long a = 0, b, x = 0, y = (unsigned long)salt;
21878387ff25SLinus Torvalds 	unsigned long adata, bdata, mask, len;
218836126f8fSLinus Torvalds 	const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2189bfcfaa77SLinus Torvalds 
21908387ff25SLinus Torvalds 	len = 0;
21918387ff25SLinus Torvalds 	goto inside;
21928387ff25SLinus Torvalds 
2193bfcfaa77SLinus Torvalds 	do {
21942a18da7aSGeorge Spelvin 		HASH_MIX(x, y, a);
2195bfcfaa77SLinus Torvalds 		len += sizeof(unsigned long);
21968387ff25SLinus Torvalds inside:
2197e419b4ccSLinus Torvalds 		a = load_unaligned_zeropad(name+len);
219836126f8fSLinus Torvalds 		b = a ^ REPEAT_BYTE('/');
219936126f8fSLinus Torvalds 	} while (!(has_zero(a, &adata, &constants) | has_zero(b, &bdata, &constants)));
2200bfcfaa77SLinus Torvalds 
220136126f8fSLinus Torvalds 	adata = prep_zero_mask(a, adata, &constants);
220236126f8fSLinus Torvalds 	bdata = prep_zero_mask(b, bdata, &constants);
220336126f8fSLinus Torvalds 	mask = create_zero_mask(adata | bdata);
22042a18da7aSGeorge Spelvin 	x ^= a & zero_bytemask(mask);
220536126f8fSLinus Torvalds 
22062a18da7aSGeorge Spelvin 	return hashlen_create(fold_hash(x, y), len + find_zero(mask));
2207bfcfaa77SLinus Torvalds }
2208bfcfaa77SLinus Torvalds 
22092a18da7aSGeorge Spelvin #else	/* !CONFIG_DCACHE_WORD_ACCESS: Slow, byte-at-a-time version */
2210bfcfaa77SLinus Torvalds 
2211fcfd2fbfSGeorge Spelvin /* Return the hash of a string of known length */
22128387ff25SLinus Torvalds unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
22130145acc2SLinus Torvalds {
22148387ff25SLinus Torvalds 	unsigned long hash = init_name_hash(salt);
22150145acc2SLinus Torvalds 	while (len--)
2216fcfd2fbfSGeorge Spelvin 		hash = partial_name_hash((unsigned char)*name++, hash);
22170145acc2SLinus Torvalds 	return end_name_hash(hash);
22180145acc2SLinus Torvalds }
2219ae942ae7SLinus Torvalds EXPORT_SYMBOL(full_name_hash);
22200145acc2SLinus Torvalds 
2221fcfd2fbfSGeorge Spelvin /* Return the "hash_len" (hash and length) of a null-terminated string */
22228387ff25SLinus Torvalds u64 hashlen_string(const void *salt, const char *name)
2223fcfd2fbfSGeorge Spelvin {
22248387ff25SLinus Torvalds 	unsigned long hash = init_name_hash(salt);
2225fcfd2fbfSGeorge Spelvin 	unsigned long len = 0, c;
2226fcfd2fbfSGeorge Spelvin 
2227fcfd2fbfSGeorge Spelvin 	c = (unsigned char)*name;
2228e0ab7af9SGeorge Spelvin 	while (c) {
2229fcfd2fbfSGeorge Spelvin 		len++;
2230fcfd2fbfSGeorge Spelvin 		hash = partial_name_hash(c, hash);
2231fcfd2fbfSGeorge Spelvin 		c = (unsigned char)name[len];
2232e0ab7af9SGeorge Spelvin 	}
2233fcfd2fbfSGeorge Spelvin 	return hashlen_create(end_name_hash(hash), len);
2234fcfd2fbfSGeorge Spelvin }
2235f2a031b6SGeorge Spelvin EXPORT_SYMBOL(hashlen_string);
2236fcfd2fbfSGeorge Spelvin 
22373ddcd056SLinus Torvalds /*
2238200e9ef7SLinus Torvalds  * We know there's a real path component here of at least
2239200e9ef7SLinus Torvalds  * one character.
2240200e9ef7SLinus Torvalds  */
22418387ff25SLinus Torvalds static inline u64 hash_name(const void *salt, const char *name)
2242200e9ef7SLinus Torvalds {
22438387ff25SLinus Torvalds 	unsigned long hash = init_name_hash(salt);
2244200e9ef7SLinus Torvalds 	unsigned long len = 0, c;
2245200e9ef7SLinus Torvalds 
2246200e9ef7SLinus Torvalds 	c = (unsigned char)*name;
2247200e9ef7SLinus Torvalds 	do {
2248200e9ef7SLinus Torvalds 		len++;
2249200e9ef7SLinus Torvalds 		hash = partial_name_hash(c, hash);
2250200e9ef7SLinus Torvalds 		c = (unsigned char)name[len];
2251200e9ef7SLinus Torvalds 	} while (c && c != '/');
2252d6bb3e90SLinus Torvalds 	return hashlen_create(end_name_hash(hash), len);
2253200e9ef7SLinus Torvalds }
2254200e9ef7SLinus Torvalds 
2255bfcfaa77SLinus Torvalds #endif
2256bfcfaa77SLinus Torvalds 
2257200e9ef7SLinus Torvalds /*
22581da177e4SLinus Torvalds  * Name resolution.
2259ea3834d9SPrasanna Meda  * This is the basic name resolution function, turning a pathname into
2260ea3834d9SPrasanna Meda  * the final dentry. We expect 'base' to be positive and a directory.
22611da177e4SLinus Torvalds  *
2262ea3834d9SPrasanna Meda  * Returns 0 and nd will have valid dentry and mnt on success.
2263ea3834d9SPrasanna Meda  * Returns error and drops reference to input namei data on failure.
22641da177e4SLinus Torvalds  */
22656de88d72SAl Viro static int link_path_walk(const char *name, struct nameidata *nd)
22661da177e4SLinus Torvalds {
2267d8d4611aSAl Viro 	int depth = 0; // depth <= nd->depth
22681da177e4SLinus Torvalds 	int err;
22691da177e4SLinus Torvalds 
2270b4c03536SAl Viro 	nd->last_type = LAST_ROOT;
2271c108837eSAl Viro 	nd->flags |= LOOKUP_PARENT;
22729b5858e9SAl Viro 	if (IS_ERR(name))
22739b5858e9SAl Viro 		return PTR_ERR(name);
22741da177e4SLinus Torvalds 	while (*name=='/')
22751da177e4SLinus Torvalds 		name++;
22761a97d899SAl Viro 	if (!*name) {
22771a97d899SAl Viro 		nd->dir_mode = 0; // short-circuit the 'hardening' idiocy
22789e18f10aSAl Viro 		return 0;
22791a97d899SAl Viro 	}
22801da177e4SLinus Torvalds 
22811da177e4SLinus Torvalds 	/* At this point we know we have a real path component. */
22821da177e4SLinus Torvalds 	for(;;) {
2283549c7297SChristian Brauner 		struct user_namespace *mnt_userns;
228492d27016SAl Viro 		const char *link;
2285d6bb3e90SLinus Torvalds 		u64 hash_len;
2286fe479a58SAl Viro 		int type;
22871da177e4SLinus Torvalds 
2288549c7297SChristian Brauner 		mnt_userns = mnt_user_ns(nd->path.mnt);
2289549c7297SChristian Brauner 		err = may_lookup(mnt_userns, nd);
22901da177e4SLinus Torvalds 		if (err)
22913595e234SAl Viro 			return err;
22921da177e4SLinus Torvalds 
22938387ff25SLinus Torvalds 		hash_len = hash_name(nd->path.dentry, name);
22941da177e4SLinus Torvalds 
2295fe479a58SAl Viro 		type = LAST_NORM;
2296d6bb3e90SLinus Torvalds 		if (name[0] == '.') switch (hashlen_len(hash_len)) {
2297fe479a58SAl Viro 			case 2:
2298200e9ef7SLinus Torvalds 				if (name[1] == '.') {
2299fe479a58SAl Viro 					type = LAST_DOTDOT;
2300bcba1e7dSAl Viro 					nd->state |= ND_JUMPED;
230116c2cd71SAl Viro 				}
2302fe479a58SAl Viro 				break;
2303fe479a58SAl Viro 			case 1:
2304fe479a58SAl Viro 				type = LAST_DOT;
2305fe479a58SAl Viro 		}
23065a202bcdSAl Viro 		if (likely(type == LAST_NORM)) {
23075a202bcdSAl Viro 			struct dentry *parent = nd->path.dentry;
2308bcba1e7dSAl Viro 			nd->state &= ~ND_JUMPED;
23095a202bcdSAl Viro 			if (unlikely(parent->d_flags & DCACHE_OP_HASH)) {
2310a060dc50SJames Hogan 				struct qstr this = { { .hash_len = hash_len }, .name = name };
2311da53be12SLinus Torvalds 				err = parent->d_op->d_hash(parent, &this);
23125a202bcdSAl Viro 				if (err < 0)
23133595e234SAl Viro 					return err;
2314d6bb3e90SLinus Torvalds 				hash_len = this.hash_len;
2315d6bb3e90SLinus Torvalds 				name = this.name;
23165a202bcdSAl Viro 			}
23175a202bcdSAl Viro 		}
2318fe479a58SAl Viro 
2319d6bb3e90SLinus Torvalds 		nd->last.hash_len = hash_len;
2320d6bb3e90SLinus Torvalds 		nd->last.name = name;
23215f4a6a69SAl Viro 		nd->last_type = type;
23225f4a6a69SAl Viro 
2323d6bb3e90SLinus Torvalds 		name += hashlen_len(hash_len);
2324d6bb3e90SLinus Torvalds 		if (!*name)
2325bdf6cbf1SAl Viro 			goto OK;
2326200e9ef7SLinus Torvalds 		/*
2327200e9ef7SLinus Torvalds 		 * If it wasn't NUL, we know it was '/'. Skip that
2328200e9ef7SLinus Torvalds 		 * slash, and continue until no more slashes.
2329200e9ef7SLinus Torvalds 		 */
2330200e9ef7SLinus Torvalds 		do {
2331d6bb3e90SLinus Torvalds 			name++;
2332d6bb3e90SLinus Torvalds 		} while (unlikely(*name == '/'));
23338620c238SAl Viro 		if (unlikely(!*name)) {
23348620c238SAl Viro OK:
2335d8d4611aSAl Viro 			/* pathname or trailing symlink, done */
2336c108837eSAl Viro 			if (!depth) {
2337549c7297SChristian Brauner 				nd->dir_uid = i_uid_into_mnt(mnt_userns, nd->inode);
23380f705953SAl Viro 				nd->dir_mode = nd->inode->i_mode;
2339c108837eSAl Viro 				nd->flags &= ~LOOKUP_PARENT;
23408620c238SAl Viro 				return 0;
2341c108837eSAl Viro 			}
23428620c238SAl Viro 			/* last component of nested symlink */
2343d8d4611aSAl Viro 			name = nd->stack[--depth].name;
23448c4efe22SAl Viro 			link = walk_component(nd, 0);
23451c4ff1a8SAl Viro 		} else {
23461c4ff1a8SAl Viro 			/* not the last component */
23478c4efe22SAl Viro 			link = walk_component(nd, WALK_MORE);
23488620c238SAl Viro 		}
234992d27016SAl Viro 		if (unlikely(link)) {
235092d27016SAl Viro 			if (IS_ERR(link))
235192d27016SAl Viro 				return PTR_ERR(link);
235292d27016SAl Viro 			/* a symlink to follow */
2353d8d4611aSAl Viro 			nd->stack[depth++].name = name;
235492d27016SAl Viro 			name = link;
23559e18f10aSAl Viro 			continue;
235648c8b0c5SAl Viro 		}
235797242f99SAl Viro 		if (unlikely(!d_can_lookup(nd->path.dentry))) {
235897242f99SAl Viro 			if (nd->flags & LOOKUP_RCU) {
2359e36cffedSJens Axboe 				if (!try_to_unlazy(nd))
236097242f99SAl Viro 					return -ECHILD;
236197242f99SAl Viro 			}
23623595e234SAl Viro 			return -ENOTDIR;
23635f4a6a69SAl Viro 		}
2364ce57dfc1SAl Viro 	}
236597242f99SAl Viro }
23661da177e4SLinus Torvalds 
2367edc2b1daSAl Viro /* must be paired with terminate_walk() */
2368c8a53ee5SAl Viro static const char *path_init(struct nameidata *nd, unsigned flags)
236931e6b01fSNick Piggin {
2370740a1678SAleksa Sarai 	int error;
2371c8a53ee5SAl Viro 	const char *s = nd->name->name;
237231e6b01fSNick Piggin 
23736c6ec2b0SJens Axboe 	/* LOOKUP_CACHED requires RCU, ask caller to retry */
23746c6ec2b0SJens Axboe 	if ((flags & (LOOKUP_RCU | LOOKUP_CACHED)) == LOOKUP_CACHED)
23756c6ec2b0SJens Axboe 		return ERR_PTR(-EAGAIN);
23766c6ec2b0SJens Axboe 
2377c0eb027eSLinus Torvalds 	if (!*s)
2378c0eb027eSLinus Torvalds 		flags &= ~LOOKUP_RCU;
2379edc2b1daSAl Viro 	if (flags & LOOKUP_RCU)
2380edc2b1daSAl Viro 		rcu_read_lock();
2381c0eb027eSLinus Torvalds 
2382bcba1e7dSAl Viro 	nd->flags = flags;
2383bcba1e7dSAl Viro 	nd->state |= ND_JUMPED;
2384ab87f9a5SAleksa Sarai 
2385ab87f9a5SAleksa Sarai 	nd->m_seq = __read_seqcount_begin(&mount_lock.seqcount);
2386ab87f9a5SAleksa Sarai 	nd->r_seq = __read_seqcount_begin(&rename_lock.seqcount);
2387ab87f9a5SAleksa Sarai 	smp_rmb();
2388ab87f9a5SAleksa Sarai 
2389bcba1e7dSAl Viro 	if (nd->state & ND_ROOT_PRESET) {
2390b18825a7SDavid Howells 		struct dentry *root = nd->root.dentry;
2391b18825a7SDavid Howells 		struct inode *inode = root->d_inode;
239293893862SAl Viro 		if (*s && unlikely(!d_can_lookup(root)))
2393368ee9baSAl Viro 			return ERR_PTR(-ENOTDIR);
23945b6ca027SAl Viro 		nd->path = nd->root;
23955b6ca027SAl Viro 		nd->inode = inode;
23965b6ca027SAl Viro 		if (flags & LOOKUP_RCU) {
2397ab87f9a5SAleksa Sarai 			nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
23988f47a016SAl Viro 			nd->root_seq = nd->seq;
23995b6ca027SAl Viro 		} else {
24005b6ca027SAl Viro 			path_get(&nd->path);
24015b6ca027SAl Viro 		}
2402368ee9baSAl Viro 		return s;
24035b6ca027SAl Viro 	}
24045b6ca027SAl Viro 
240531e6b01fSNick Piggin 	nd->root.mnt = NULL;
240631e6b01fSNick Piggin 
24078db52c7eSAleksa Sarai 	/* Absolute pathname -- fetch the root (LOOKUP_IN_ROOT uses nd->dfd). */
24088db52c7eSAleksa Sarai 	if (*s == '/' && !(flags & LOOKUP_IN_ROOT)) {
2409740a1678SAleksa Sarai 		error = nd_jump_root(nd);
2410740a1678SAleksa Sarai 		if (unlikely(error))
2411740a1678SAleksa Sarai 			return ERR_PTR(error);
2412ef55d917SAl Viro 		return s;
24138db52c7eSAleksa Sarai 	}
24148db52c7eSAleksa Sarai 
24158db52c7eSAleksa Sarai 	/* Relative pathname -- get the starting-point it is relative to. */
24168db52c7eSAleksa Sarai 	if (nd->dfd == AT_FDCWD) {
2417e41f7d4eSAl Viro 		if (flags & LOOKUP_RCU) {
241831e6b01fSNick Piggin 			struct fs_struct *fs = current->fs;
2419c28cc364SNick Piggin 			unsigned seq;
242031e6b01fSNick Piggin 
2421c28cc364SNick Piggin 			do {
2422c28cc364SNick Piggin 				seq = read_seqcount_begin(&fs->seq);
242331e6b01fSNick Piggin 				nd->path = fs->pwd;
2424ef55d917SAl Viro 				nd->inode = nd->path.dentry->d_inode;
2425c28cc364SNick Piggin 				nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
2426c28cc364SNick Piggin 			} while (read_seqcount_retry(&fs->seq, seq));
2427e41f7d4eSAl Viro 		} else {
2428e41f7d4eSAl Viro 			get_fs_pwd(current->fs, &nd->path);
2429ef55d917SAl Viro 			nd->inode = nd->path.dentry->d_inode;
2430e41f7d4eSAl Viro 		}
243131e6b01fSNick Piggin 	} else {
2432582aa64aSJeff Layton 		/* Caller must check execute permissions on the starting path component */
2433c8a53ee5SAl Viro 		struct fd f = fdget_raw(nd->dfd);
243431e6b01fSNick Piggin 		struct dentry *dentry;
243531e6b01fSNick Piggin 
24362903ff01SAl Viro 		if (!f.file)
2437368ee9baSAl Viro 			return ERR_PTR(-EBADF);
243831e6b01fSNick Piggin 
24392903ff01SAl Viro 		dentry = f.file->f_path.dentry;
244031e6b01fSNick Piggin 
2441edc2b1daSAl Viro 		if (*s && unlikely(!d_can_lookup(dentry))) {
24422903ff01SAl Viro 			fdput(f);
2443368ee9baSAl Viro 			return ERR_PTR(-ENOTDIR);
2444f52e0c11SAl Viro 		}
24452903ff01SAl Viro 
24462903ff01SAl Viro 		nd->path = f.file->f_path;
2447e41f7d4eSAl Viro 		if (flags & LOOKUP_RCU) {
244834a26b99SAl Viro 			nd->inode = nd->path.dentry->d_inode;
244934a26b99SAl Viro 			nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
24505590ff0dSUlrich Drepper 		} else {
24512903ff01SAl Viro 			path_get(&nd->path);
245234a26b99SAl Viro 			nd->inode = nd->path.dentry->d_inode;
24531da177e4SLinus Torvalds 		}
245434a26b99SAl Viro 		fdput(f);
2455e41f7d4eSAl Viro 	}
24568db52c7eSAleksa Sarai 
2457adb21d2bSAleksa Sarai 	/* For scoped-lookups we need to set the root to the dirfd as well. */
2458adb21d2bSAleksa Sarai 	if (flags & LOOKUP_IS_SCOPED) {
2459adb21d2bSAleksa Sarai 		nd->root = nd->path;
2460adb21d2bSAleksa Sarai 		if (flags & LOOKUP_RCU) {
2461adb21d2bSAleksa Sarai 			nd->root_seq = nd->seq;
2462adb21d2bSAleksa Sarai 		} else {
2463adb21d2bSAleksa Sarai 			path_get(&nd->root);
2464bcba1e7dSAl Viro 			nd->state |= ND_ROOT_GRABBED;
2465adb21d2bSAleksa Sarai 		}
2466adb21d2bSAleksa Sarai 	}
2467adb21d2bSAleksa Sarai 	return s;
24689b4a9b14SAl Viro }
24699b4a9b14SAl Viro 
24701ccac622SAl Viro static inline const char *lookup_last(struct nameidata *nd)
247195fa25d9SAl Viro {
2472bd92d7feSAl Viro 	if (nd->last_type == LAST_NORM && nd->last.name[nd->last.len])
2473bd92d7feSAl Viro 		nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
2474bd92d7feSAl Viro 
2475c108837eSAl Viro 	return walk_component(nd, WALK_TRAILING);
2476bd92d7feSAl Viro }
2477bd92d7feSAl Viro 
24784f757f3cSAl Viro static int handle_lookup_down(struct nameidata *nd)
24794f757f3cSAl Viro {
2480c153007bSAl Viro 	if (!(nd->flags & LOOKUP_RCU))
2481db3c9adeSAl Viro 		dget(nd->path.dentry);
2482b0417d2cSAl Viro 	return PTR_ERR(step_into(nd, WALK_NOFOLLOW,
2483b0417d2cSAl Viro 			nd->path.dentry, nd->inode, nd->seq));
24844f757f3cSAl Viro }
24854f757f3cSAl Viro 
24869b4a9b14SAl Viro /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
2487c8a53ee5SAl Viro static int path_lookupat(struct nameidata *nd, unsigned flags, struct path *path)
24889b4a9b14SAl Viro {
2489c8a53ee5SAl Viro 	const char *s = path_init(nd, flags);
2490bd92d7feSAl Viro 	int err;
249131e6b01fSNick Piggin 
24929b5858e9SAl Viro 	if (unlikely(flags & LOOKUP_DOWN) && !IS_ERR(s)) {
24934f757f3cSAl Viro 		err = handle_lookup_down(nd);
24945f336e72SAl Viro 		if (unlikely(err < 0))
24955f336e72SAl Viro 			s = ERR_PTR(err);
24964f757f3cSAl Viro 	}
24974f757f3cSAl Viro 
24981ccac622SAl Viro 	while (!(err = link_path_walk(s, nd)) &&
24991ccac622SAl Viro 	       (s = lookup_last(nd)) != NULL)
25001ccac622SAl Viro 		;
25014f0ed93fSAl Viro 	if (!err && unlikely(nd->flags & LOOKUP_MOUNTPOINT)) {
25024f0ed93fSAl Viro 		err = handle_lookup_down(nd);
2503bcba1e7dSAl Viro 		nd->state &= ~ND_JUMPED; // no d_weak_revalidate(), please...
25044f0ed93fSAl Viro 	}
25059f1fafeeSAl Viro 	if (!err)
25069f1fafeeSAl Viro 		err = complete_walk(nd);
2507bd92d7feSAl Viro 
2508deb106c6SAl Viro 	if (!err && nd->flags & LOOKUP_DIRECTORY)
2509deb106c6SAl Viro 		if (!d_can_lookup(nd->path.dentry))
2510bd23a539SAl Viro 			err = -ENOTDIR;
2511625b6d10SAl Viro 	if (!err) {
2512625b6d10SAl Viro 		*path = nd->path;
2513625b6d10SAl Viro 		nd->path.mnt = NULL;
2514625b6d10SAl Viro 		nd->path.dentry = NULL;
2515625b6d10SAl Viro 	}
2516deb106c6SAl Viro 	terminate_walk(nd);
2517bd92d7feSAl Viro 	return err;
251831e6b01fSNick Piggin }
251931e6b01fSNick Piggin 
2520794ebceaSStephen Brennan int filename_lookup(int dfd, struct filename *name, unsigned flags,
25219ad1aaa6SAl Viro 		    struct path *path, struct path *root)
2522873f1eedSJeff Layton {
2523894bc8c4SAl Viro 	int retval;
25249883d185SAl Viro 	struct nameidata nd;
2525abc9f5beSAl Viro 	if (IS_ERR(name))
2526abc9f5beSAl Viro 		return PTR_ERR(name);
252706422964SAl Viro 	set_nameidata(&nd, dfd, name, root);
2528c8a53ee5SAl Viro 	retval = path_lookupat(&nd, flags | LOOKUP_RCU, path);
2529873f1eedSJeff Layton 	if (unlikely(retval == -ECHILD))
2530c8a53ee5SAl Viro 		retval = path_lookupat(&nd, flags, path);
2531873f1eedSJeff Layton 	if (unlikely(retval == -ESTALE))
2532c8a53ee5SAl Viro 		retval = path_lookupat(&nd, flags | LOOKUP_REVAL, path);
2533873f1eedSJeff Layton 
2534873f1eedSJeff Layton 	if (likely(!retval))
2535161aff1dSAl Viro 		audit_inode(name, path->dentry,
2536161aff1dSAl Viro 			    flags & LOOKUP_MOUNTPOINT ? AUDIT_INODE_NOEVAL : 0);
25379883d185SAl Viro 	restore_nameidata();
2538020250f3SDmitry Kadashev 	return retval;
2539020250f3SDmitry Kadashev }
2540020250f3SDmitry Kadashev 
25418bcb77faSAl Viro /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
2542c8a53ee5SAl Viro static int path_parentat(struct nameidata *nd, unsigned flags,
2543391172c4SAl Viro 				struct path *parent)
25448bcb77faSAl Viro {
2545c8a53ee5SAl Viro 	const char *s = path_init(nd, flags);
25469b5858e9SAl Viro 	int err = link_path_walk(s, nd);
25478bcb77faSAl Viro 	if (!err)
25488bcb77faSAl Viro 		err = complete_walk(nd);
2549391172c4SAl Viro 	if (!err) {
2550391172c4SAl Viro 		*parent = nd->path;
2551391172c4SAl Viro 		nd->path.mnt = NULL;
2552391172c4SAl Viro 		nd->path.dentry = NULL;
2553391172c4SAl Viro 	}
2554deb106c6SAl Viro 	terminate_walk(nd);
25558bcb77faSAl Viro 	return err;
25568bcb77faSAl Viro }
25578bcb77faSAl Viro 
25580766ec82SStephen Brennan /* Note: this does not consume "name" */
2559c5f563f9SAl Viro static int filename_parentat(int dfd, struct filename *name,
2560391172c4SAl Viro 			     unsigned int flags, struct path *parent,
2561391172c4SAl Viro 			     struct qstr *last, int *type)
25628bcb77faSAl Viro {
25638bcb77faSAl Viro 	int retval;
25649883d185SAl Viro 	struct nameidata nd;
25658bcb77faSAl Viro 
25665c31b6ceSAl Viro 	if (IS_ERR(name))
25670ee50b47SDmitry Kadashev 		return PTR_ERR(name);
256806422964SAl Viro 	set_nameidata(&nd, dfd, name, NULL);
2569c8a53ee5SAl Viro 	retval = path_parentat(&nd, flags | LOOKUP_RCU, parent);
25708bcb77faSAl Viro 	if (unlikely(retval == -ECHILD))
2571c8a53ee5SAl Viro 		retval = path_parentat(&nd, flags, parent);
25728bcb77faSAl Viro 	if (unlikely(retval == -ESTALE))
2573c8a53ee5SAl Viro 		retval = path_parentat(&nd, flags | LOOKUP_REVAL, parent);
2574391172c4SAl Viro 	if (likely(!retval)) {
2575391172c4SAl Viro 		*last = nd.last;
2576391172c4SAl Viro 		*type = nd.last_type;
2577c9b07eabSAl Viro 		audit_inode(name, parent->dentry, AUDIT_INODE_PARENT);
2578391172c4SAl Viro 	}
25799883d185SAl Viro 	restore_nameidata();
25800ee50b47SDmitry Kadashev 	return retval;
25810ee50b47SDmitry Kadashev }
25820ee50b47SDmitry Kadashev 
258379714f72SAl Viro /* does lookup, returns the object with parent locked */
25840766ec82SStephen Brennan static struct dentry *__kern_path_locked(struct filename *name, struct path *path)
25855590ff0dSUlrich Drepper {
25865c31b6ceSAl Viro 	struct dentry *d;
2587391172c4SAl Viro 	struct qstr last;
25880ee50b47SDmitry Kadashev 	int type, error;
258951689104SPaul Moore 
2590c5f563f9SAl Viro 	error = filename_parentat(AT_FDCWD, name, 0, path, &last, &type);
25910ee50b47SDmitry Kadashev 	if (error)
25920ee50b47SDmitry Kadashev 		return ERR_PTR(error);
25935c31b6ceSAl Viro 	if (unlikely(type != LAST_NORM)) {
2594391172c4SAl Viro 		path_put(path);
25955c31b6ceSAl Viro 		return ERR_PTR(-EINVAL);
259679714f72SAl Viro 	}
25975955102cSAl Viro 	inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
2598391172c4SAl Viro 	d = __lookup_hash(&last, path->dentry, 0);
259979714f72SAl Viro 	if (IS_ERR(d)) {
26005955102cSAl Viro 		inode_unlock(path->dentry->d_inode);
2601391172c4SAl Viro 		path_put(path);
260279714f72SAl Viro 	}
260379714f72SAl Viro 	return d;
26045590ff0dSUlrich Drepper }
26055590ff0dSUlrich Drepper 
26060766ec82SStephen Brennan struct dentry *kern_path_locked(const char *name, struct path *path)
26070766ec82SStephen Brennan {
26080766ec82SStephen Brennan 	struct filename *filename = getname_kernel(name);
26090766ec82SStephen Brennan 	struct dentry *res = __kern_path_locked(filename, path);
26100766ec82SStephen Brennan 
26110766ec82SStephen Brennan 	putname(filename);
26120766ec82SStephen Brennan 	return res;
26130766ec82SStephen Brennan }
26140766ec82SStephen Brennan 
2615d1811465SAl Viro int kern_path(const char *name, unsigned int flags, struct path *path)
2616d1811465SAl Viro {
2617794ebceaSStephen Brennan 	struct filename *filename = getname_kernel(name);
2618794ebceaSStephen Brennan 	int ret = filename_lookup(AT_FDCWD, filename, flags, path, NULL);
2619794ebceaSStephen Brennan 
2620794ebceaSStephen Brennan 	putname(filename);
2621794ebceaSStephen Brennan 	return ret;
2622794ebceaSStephen Brennan 
2623d1811465SAl Viro }
26244d359507SAl Viro EXPORT_SYMBOL(kern_path);
2625d1811465SAl Viro 
262616f18200SJosef 'Jeff' Sipek /**
262716f18200SJosef 'Jeff' Sipek  * vfs_path_lookup - lookup a file path relative to a dentry-vfsmount pair
262816f18200SJosef 'Jeff' Sipek  * @dentry:  pointer to dentry of the base directory
262916f18200SJosef 'Jeff' Sipek  * @mnt: pointer to vfs mount of the base directory
263016f18200SJosef 'Jeff' Sipek  * @name: pointer to file name
263116f18200SJosef 'Jeff' Sipek  * @flags: lookup flags
2632e0a01249SAl Viro  * @path: pointer to struct path to fill
263316f18200SJosef 'Jeff' Sipek  */
263416f18200SJosef 'Jeff' Sipek int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt,
263516f18200SJosef 'Jeff' Sipek 		    const char *name, unsigned int flags,
2636e0a01249SAl Viro 		    struct path *path)
263716f18200SJosef 'Jeff' Sipek {
2638794ebceaSStephen Brennan 	struct filename *filename;
26399ad1aaa6SAl Viro 	struct path root = {.mnt = mnt, .dentry = dentry};
2640794ebceaSStephen Brennan 	int ret;
2641794ebceaSStephen Brennan 
2642794ebceaSStephen Brennan 	filename = getname_kernel(name);
26439ad1aaa6SAl Viro 	/* the first argument of filename_lookup() is ignored with root */
2644794ebceaSStephen Brennan 	ret = filename_lookup(AT_FDCWD, filename, flags, path, &root);
2645794ebceaSStephen Brennan 	putname(filename);
2646794ebceaSStephen Brennan 	return ret;
264716f18200SJosef 'Jeff' Sipek }
26484d359507SAl Viro EXPORT_SYMBOL(vfs_path_lookup);
264916f18200SJosef 'Jeff' Sipek 
2650c2fd68b6SChristian Brauner static int lookup_one_common(struct user_namespace *mnt_userns,
2651c2fd68b6SChristian Brauner 			     const char *name, struct dentry *base, int len,
2652c2fd68b6SChristian Brauner 			     struct qstr *this)
26533c95f0dcSAl Viro {
26543c95f0dcSAl Viro 	this->name = name;
26553c95f0dcSAl Viro 	this->len = len;
26563c95f0dcSAl Viro 	this->hash = full_name_hash(base, name, len);
26573c95f0dcSAl Viro 	if (!len)
26583c95f0dcSAl Viro 		return -EACCES;
26593c95f0dcSAl Viro 
26603c95f0dcSAl Viro 	if (unlikely(name[0] == '.')) {
26613c95f0dcSAl Viro 		if (len < 2 || (len == 2 && name[1] == '.'))
26623c95f0dcSAl Viro 			return -EACCES;
26633c95f0dcSAl Viro 	}
26643c95f0dcSAl Viro 
26653c95f0dcSAl Viro 	while (len--) {
26663c95f0dcSAl Viro 		unsigned int c = *(const unsigned char *)name++;
26673c95f0dcSAl Viro 		if (c == '/' || c == '\0')
26683c95f0dcSAl Viro 			return -EACCES;
26693c95f0dcSAl Viro 	}
26703c95f0dcSAl Viro 	/*
26713c95f0dcSAl Viro 	 * See if the low-level filesystem might want
26723c95f0dcSAl Viro 	 * to use its own hash..
26733c95f0dcSAl Viro 	 */
26743c95f0dcSAl Viro 	if (base->d_flags & DCACHE_OP_HASH) {
26753c95f0dcSAl Viro 		int err = base->d_op->d_hash(base, this);
26763c95f0dcSAl Viro 		if (err < 0)
26773c95f0dcSAl Viro 			return err;
26783c95f0dcSAl Viro 	}
26793c95f0dcSAl Viro 
2680c2fd68b6SChristian Brauner 	return inode_permission(mnt_userns, base->d_inode, MAY_EXEC);
26813c95f0dcSAl Viro }
26823c95f0dcSAl Viro 
2683eead1911SChristoph Hellwig /**
26840da0b7fdSDavid Howells  * try_lookup_one_len - filesystem helper to lookup single pathname component
26850da0b7fdSDavid Howells  * @name:	pathname component to lookup
26860da0b7fdSDavid Howells  * @base:	base directory to lookup from
26870da0b7fdSDavid Howells  * @len:	maximum length @len should be interpreted to
26880da0b7fdSDavid Howells  *
26890da0b7fdSDavid Howells  * Look up a dentry by name in the dcache, returning NULL if it does not
26900da0b7fdSDavid Howells  * currently exist.  The function does not try to create a dentry.
26910da0b7fdSDavid Howells  *
26920da0b7fdSDavid Howells  * Note that this routine is purely a helper for filesystem usage and should
26930da0b7fdSDavid Howells  * not be called by generic code.
26940da0b7fdSDavid Howells  *
26950da0b7fdSDavid Howells  * The caller must hold base->i_mutex.
26960da0b7fdSDavid Howells  */
26970da0b7fdSDavid Howells struct dentry *try_lookup_one_len(const char *name, struct dentry *base, int len)
26980da0b7fdSDavid Howells {
26990da0b7fdSDavid Howells 	struct qstr this;
27000da0b7fdSDavid Howells 	int err;
27010da0b7fdSDavid Howells 
27020da0b7fdSDavid Howells 	WARN_ON_ONCE(!inode_is_locked(base->d_inode));
27030da0b7fdSDavid Howells 
2704c2fd68b6SChristian Brauner 	err = lookup_one_common(&init_user_ns, name, base, len, &this);
27050da0b7fdSDavid Howells 	if (err)
27060da0b7fdSDavid Howells 		return ERR_PTR(err);
27070da0b7fdSDavid Howells 
27080da0b7fdSDavid Howells 	return lookup_dcache(&this, base, 0);
27090da0b7fdSDavid Howells }
27100da0b7fdSDavid Howells EXPORT_SYMBOL(try_lookup_one_len);
27110da0b7fdSDavid Howells 
27120da0b7fdSDavid Howells /**
2713a6b91919SRandy Dunlap  * lookup_one_len - filesystem helper to lookup single pathname component
2714eead1911SChristoph Hellwig  * @name:	pathname component to lookup
2715eead1911SChristoph Hellwig  * @base:	base directory to lookup from
2716eead1911SChristoph Hellwig  * @len:	maximum length @len should be interpreted to
2717eead1911SChristoph Hellwig  *
2718a6b91919SRandy Dunlap  * Note that this routine is purely a helper for filesystem usage and should
27199e7543e9SAl Viro  * not be called by generic code.
2720bbddca8eSNeilBrown  *
2721bbddca8eSNeilBrown  * The caller must hold base->i_mutex.
2722eead1911SChristoph Hellwig  */
2723057f6c01SJames Morris struct dentry *lookup_one_len(const char *name, struct dentry *base, int len)
2724057f6c01SJames Morris {
27258613a209SAl Viro 	struct dentry *dentry;
2726057f6c01SJames Morris 	struct qstr this;
2727cda309deSMiklos Szeredi 	int err;
2728057f6c01SJames Morris 
27295955102cSAl Viro 	WARN_ON_ONCE(!inode_is_locked(base->d_inode));
27302f9092e1SDavid Woodhouse 
2731c2fd68b6SChristian Brauner 	err = lookup_one_common(&init_user_ns, name, base, len, &this);
2732cda309deSMiklos Szeredi 	if (err)
2733cda309deSMiklos Szeredi 		return ERR_PTR(err);
2734cda309deSMiklos Szeredi 
27358613a209SAl Viro 	dentry = lookup_dcache(&this, base, 0);
27368613a209SAl Viro 	return dentry ? dentry : __lookup_slow(&this, base, 0);
2737057f6c01SJames Morris }
27384d359507SAl Viro EXPORT_SYMBOL(lookup_one_len);
2739057f6c01SJames Morris 
2740bbddca8eSNeilBrown /**
2741c2fd68b6SChristian Brauner  * lookup_one - filesystem helper to lookup single pathname component
2742c2fd68b6SChristian Brauner  * @mnt_userns:	user namespace of the mount the lookup is performed from
2743c2fd68b6SChristian Brauner  * @name:	pathname component to lookup
2744c2fd68b6SChristian Brauner  * @base:	base directory to lookup from
2745c2fd68b6SChristian Brauner  * @len:	maximum length @len should be interpreted to
2746c2fd68b6SChristian Brauner  *
2747c2fd68b6SChristian Brauner  * Note that this routine is purely a helper for filesystem usage and should
2748c2fd68b6SChristian Brauner  * not be called by generic code.
2749c2fd68b6SChristian Brauner  *
2750c2fd68b6SChristian Brauner  * The caller must hold base->i_mutex.
2751c2fd68b6SChristian Brauner  */
2752c2fd68b6SChristian Brauner struct dentry *lookup_one(struct user_namespace *mnt_userns, const char *name,
2753c2fd68b6SChristian Brauner 			  struct dentry *base, int len)
2754c2fd68b6SChristian Brauner {
2755c2fd68b6SChristian Brauner 	struct dentry *dentry;
2756c2fd68b6SChristian Brauner 	struct qstr this;
2757c2fd68b6SChristian Brauner 	int err;
2758c2fd68b6SChristian Brauner 
2759c2fd68b6SChristian Brauner 	WARN_ON_ONCE(!inode_is_locked(base->d_inode));
2760c2fd68b6SChristian Brauner 
2761c2fd68b6SChristian Brauner 	err = lookup_one_common(mnt_userns, name, base, len, &this);
2762c2fd68b6SChristian Brauner 	if (err)
2763c2fd68b6SChristian Brauner 		return ERR_PTR(err);
2764c2fd68b6SChristian Brauner 
2765c2fd68b6SChristian Brauner 	dentry = lookup_dcache(&this, base, 0);
2766c2fd68b6SChristian Brauner 	return dentry ? dentry : __lookup_slow(&this, base, 0);
2767c2fd68b6SChristian Brauner }
2768c2fd68b6SChristian Brauner EXPORT_SYMBOL(lookup_one);
2769c2fd68b6SChristian Brauner 
2770c2fd68b6SChristian Brauner /**
2771bbddca8eSNeilBrown  * lookup_one_len_unlocked - filesystem helper to lookup single pathname component
2772bbddca8eSNeilBrown  * @name:	pathname component to lookup
2773bbddca8eSNeilBrown  * @base:	base directory to lookup from
2774bbddca8eSNeilBrown  * @len:	maximum length @len should be interpreted to
2775bbddca8eSNeilBrown  *
2776bbddca8eSNeilBrown  * Note that this routine is purely a helper for filesystem usage and should
2777bbddca8eSNeilBrown  * not be called by generic code.
2778bbddca8eSNeilBrown  *
2779bbddca8eSNeilBrown  * Unlike lookup_one_len, it should be called without the parent
2780bbddca8eSNeilBrown  * i_mutex held, and will take the i_mutex itself if necessary.
2781bbddca8eSNeilBrown  */
2782bbddca8eSNeilBrown struct dentry *lookup_one_len_unlocked(const char *name,
2783bbddca8eSNeilBrown 				       struct dentry *base, int len)
2784bbddca8eSNeilBrown {
2785bbddca8eSNeilBrown 	struct qstr this;
2786bbddca8eSNeilBrown 	int err;
278720d00ee8SLinus Torvalds 	struct dentry *ret;
2788bbddca8eSNeilBrown 
2789c2fd68b6SChristian Brauner 	err = lookup_one_common(&init_user_ns, name, base, len, &this);
2790bbddca8eSNeilBrown 	if (err)
2791bbddca8eSNeilBrown 		return ERR_PTR(err);
2792bbddca8eSNeilBrown 
279320d00ee8SLinus Torvalds 	ret = lookup_dcache(&this, base, 0);
279420d00ee8SLinus Torvalds 	if (!ret)
279520d00ee8SLinus Torvalds 		ret = lookup_slow(&this, base, 0);
279620d00ee8SLinus Torvalds 	return ret;
2797bbddca8eSNeilBrown }
2798bbddca8eSNeilBrown EXPORT_SYMBOL(lookup_one_len_unlocked);
2799bbddca8eSNeilBrown 
28006c2d4798SAl Viro /*
28016c2d4798SAl Viro  * Like lookup_one_len_unlocked(), except that it yields ERR_PTR(-ENOENT)
28026c2d4798SAl Viro  * on negatives.  Returns known positive or ERR_PTR(); that's what
28036c2d4798SAl Viro  * most of the users want.  Note that pinned negative with unlocked parent
28046c2d4798SAl Viro  * _can_ become positive at any time, so callers of lookup_one_len_unlocked()
28056c2d4798SAl Viro  * need to be very careful; pinned positives have ->d_inode stable, so
28066c2d4798SAl Viro  * this one avoids such problems.
28076c2d4798SAl Viro  */
28086c2d4798SAl Viro struct dentry *lookup_positive_unlocked(const char *name,
28096c2d4798SAl Viro 				       struct dentry *base, int len)
28106c2d4798SAl Viro {
28116c2d4798SAl Viro 	struct dentry *ret = lookup_one_len_unlocked(name, base, len);
28122fa6b1e0SAl Viro 	if (!IS_ERR(ret) && d_flags_negative(smp_load_acquire(&ret->d_flags))) {
28136c2d4798SAl Viro 		dput(ret);
28146c2d4798SAl Viro 		ret = ERR_PTR(-ENOENT);
28156c2d4798SAl Viro 	}
28166c2d4798SAl Viro 	return ret;
28176c2d4798SAl Viro }
28186c2d4798SAl Viro EXPORT_SYMBOL(lookup_positive_unlocked);
28196c2d4798SAl Viro 
2820eedf265aSEric W. Biederman #ifdef CONFIG_UNIX98_PTYS
2821eedf265aSEric W. Biederman int path_pts(struct path *path)
2822eedf265aSEric W. Biederman {
2823eedf265aSEric W. Biederman 	/* Find something mounted on "pts" in the same directory as
2824eedf265aSEric W. Biederman 	 * the input path.
2825eedf265aSEric W. Biederman 	 */
2826a6a7eb76SAl Viro 	struct dentry *parent = dget_parent(path->dentry);
2827a6a7eb76SAl Viro 	struct dentry *child;
282819f6028aSAl Viro 	struct qstr this = QSTR_INIT("pts", 3);
2829eedf265aSEric W. Biederman 
2830a6a7eb76SAl Viro 	if (unlikely(!path_connected(path->mnt, parent))) {
2831a6a7eb76SAl Viro 		dput(parent);
283263b27720SAl Viro 		return -ENOENT;
2833a6a7eb76SAl Viro 	}
283463b27720SAl Viro 	dput(path->dentry);
283563b27720SAl Viro 	path->dentry = parent;
2836eedf265aSEric W. Biederman 	child = d_hash_and_lookup(parent, &this);
2837eedf265aSEric W. Biederman 	if (!child)
2838eedf265aSEric W. Biederman 		return -ENOENT;
2839eedf265aSEric W. Biederman 
2840eedf265aSEric W. Biederman 	path->dentry = child;
2841eedf265aSEric W. Biederman 	dput(parent);
284219f6028aSAl Viro 	follow_down(path);
2843eedf265aSEric W. Biederman 	return 0;
2844eedf265aSEric W. Biederman }
2845eedf265aSEric W. Biederman #endif
2846eedf265aSEric W. Biederman 
28471fa1e7f6SAndy Whitcroft int user_path_at_empty(int dfd, const char __user *name, unsigned flags,
28481fa1e7f6SAndy Whitcroft 		 struct path *path, int *empty)
28491da177e4SLinus Torvalds {
2850794ebceaSStephen Brennan 	struct filename *filename = getname_flags(name, flags, empty);
2851794ebceaSStephen Brennan 	int ret = filename_lookup(dfd, filename, flags, path, NULL);
2852794ebceaSStephen Brennan 
2853794ebceaSStephen Brennan 	putname(filename);
2854794ebceaSStephen Brennan 	return ret;
28551da177e4SLinus Torvalds }
2856b853a161SAl Viro EXPORT_SYMBOL(user_path_at_empty);
28571fa1e7f6SAndy Whitcroft 
2858ba73d987SChristian Brauner int __check_sticky(struct user_namespace *mnt_userns, struct inode *dir,
2859ba73d987SChristian Brauner 		   struct inode *inode)
28601da177e4SLinus Torvalds {
28618e96e3b7SEric W. Biederman 	kuid_t fsuid = current_fsuid();
2862da9592edSDavid Howells 
2863ba73d987SChristian Brauner 	if (uid_eq(i_uid_into_mnt(mnt_userns, inode), fsuid))
28641da177e4SLinus Torvalds 		return 0;
2865ba73d987SChristian Brauner 	if (uid_eq(i_uid_into_mnt(mnt_userns, dir), fsuid))
28661da177e4SLinus Torvalds 		return 0;
2867ba73d987SChristian Brauner 	return !capable_wrt_inode_uidgid(mnt_userns, inode, CAP_FOWNER);
28681da177e4SLinus Torvalds }
2869cbdf35bcSMiklos Szeredi EXPORT_SYMBOL(__check_sticky);
28701da177e4SLinus Torvalds 
28711da177e4SLinus Torvalds /*
28721da177e4SLinus Torvalds  *	Check whether we can remove a link victim from directory dir, check
28731da177e4SLinus Torvalds  *  whether the type of victim is right.
28741da177e4SLinus Torvalds  *  1. We can't do it if dir is read-only (done in permission())
28751da177e4SLinus Torvalds  *  2. We should have write and exec permissions on dir
28761da177e4SLinus Torvalds  *  3. We can't remove anything from append-only dir
28771da177e4SLinus Torvalds  *  4. We can't do anything with immutable dir (done in permission())
28781da177e4SLinus Torvalds  *  5. If the sticky bit on dir is set we should either
28791da177e4SLinus Torvalds  *	a. be owner of dir, or
28801da177e4SLinus Torvalds  *	b. be owner of victim, or
28811da177e4SLinus Torvalds  *	c. have CAP_FOWNER capability
28821da177e4SLinus Torvalds  *  6. If the victim is append-only or immutable we can't do antyhing with
28831da177e4SLinus Torvalds  *     links pointing to it.
28840bd23d09SEric W. Biederman  *  7. If the victim has an unknown uid or gid we can't change the inode.
28850bd23d09SEric W. Biederman  *  8. If we were asked to remove a directory and victim isn't one - ENOTDIR.
28860bd23d09SEric W. Biederman  *  9. If we were asked to remove a non-directory and victim isn't one - EISDIR.
28870bd23d09SEric W. Biederman  * 10. We can't remove a root or mountpoint.
28880bd23d09SEric W. Biederman  * 11. We don't allow removal of NFS sillyrenamed files; it's handled by
28891da177e4SLinus Torvalds  *     nfs_async_unlink().
28901da177e4SLinus Torvalds  */
2891ba73d987SChristian Brauner static int may_delete(struct user_namespace *mnt_userns, struct inode *dir,
2892ba73d987SChristian Brauner 		      struct dentry *victim, bool isdir)
28931da177e4SLinus Torvalds {
289463afdfc7SDavid Howells 	struct inode *inode = d_backing_inode(victim);
28951da177e4SLinus Torvalds 	int error;
28961da177e4SLinus Torvalds 
2897b18825a7SDavid Howells 	if (d_is_negative(victim))
28981da177e4SLinus Torvalds 		return -ENOENT;
2899b18825a7SDavid Howells 	BUG_ON(!inode);
29001da177e4SLinus Torvalds 
29011da177e4SLinus Torvalds 	BUG_ON(victim->d_parent->d_inode != dir);
2902593d1ce8SEric W. Biederman 
2903593d1ce8SEric W. Biederman 	/* Inode writeback is not safe when the uid or gid are invalid. */
2904ba73d987SChristian Brauner 	if (!uid_valid(i_uid_into_mnt(mnt_userns, inode)) ||
2905ba73d987SChristian Brauner 	    !gid_valid(i_gid_into_mnt(mnt_userns, inode)))
2906593d1ce8SEric W. Biederman 		return -EOVERFLOW;
2907593d1ce8SEric W. Biederman 
29084fa6b5ecSJeff Layton 	audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
29091da177e4SLinus Torvalds 
2910ba73d987SChristian Brauner 	error = inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
29111da177e4SLinus Torvalds 	if (error)
29121da177e4SLinus Torvalds 		return error;
29131da177e4SLinus Torvalds 	if (IS_APPEND(dir))
29141da177e4SLinus Torvalds 		return -EPERM;
2915b18825a7SDavid Howells 
2916ba73d987SChristian Brauner 	if (check_sticky(mnt_userns, dir, inode) || IS_APPEND(inode) ||
2917ba73d987SChristian Brauner 	    IS_IMMUTABLE(inode) || IS_SWAPFILE(inode) ||
2918ba73d987SChristian Brauner 	    HAS_UNMAPPED_ID(mnt_userns, inode))
29191da177e4SLinus Torvalds 		return -EPERM;
29201da177e4SLinus Torvalds 	if (isdir) {
292144b1d530SMiklos Szeredi 		if (!d_is_dir(victim))
29221da177e4SLinus Torvalds 			return -ENOTDIR;
29231da177e4SLinus Torvalds 		if (IS_ROOT(victim))
29241da177e4SLinus Torvalds 			return -EBUSY;
292544b1d530SMiklos Szeredi 	} else if (d_is_dir(victim))
29261da177e4SLinus Torvalds 		return -EISDIR;
29271da177e4SLinus Torvalds 	if (IS_DEADDIR(dir))
29281da177e4SLinus Torvalds 		return -ENOENT;
29291da177e4SLinus Torvalds 	if (victim->d_flags & DCACHE_NFSFS_RENAMED)
29301da177e4SLinus Torvalds 		return -EBUSY;
29311da177e4SLinus Torvalds 	return 0;
29321da177e4SLinus Torvalds }
29331da177e4SLinus Torvalds 
29341da177e4SLinus Torvalds /*	Check whether we can create an object with dentry child in directory
29351da177e4SLinus Torvalds  *  dir.
29361da177e4SLinus Torvalds  *  1. We can't do it if child already exists (open has special treatment for
29371da177e4SLinus Torvalds  *     this case, but since we are inlined it's OK)
29381da177e4SLinus Torvalds  *  2. We can't do it if dir is read-only (done in permission())
2939036d5236SEric W. Biederman  *  3. We can't do it if the fs can't represent the fsuid or fsgid.
2940036d5236SEric W. Biederman  *  4. We should have write and exec permissions on dir
2941036d5236SEric W. Biederman  *  5. We can't do it if dir is immutable (done in permission())
29421da177e4SLinus Torvalds  */
2943ba73d987SChristian Brauner static inline int may_create(struct user_namespace *mnt_userns,
2944ba73d987SChristian Brauner 			     struct inode *dir, struct dentry *child)
29451da177e4SLinus Torvalds {
294614e972b4SJeff Layton 	audit_inode_child(dir, child, AUDIT_TYPE_CHILD_CREATE);
29471da177e4SLinus Torvalds 	if (child->d_inode)
29481da177e4SLinus Torvalds 		return -EEXIST;
29491da177e4SLinus Torvalds 	if (IS_DEADDIR(dir))
29501da177e4SLinus Torvalds 		return -ENOENT;
29518e538913SChristian Brauner 	if (!fsuidgid_has_mapping(dir->i_sb, mnt_userns))
2952036d5236SEric W. Biederman 		return -EOVERFLOW;
29538e538913SChristian Brauner 
2954ba73d987SChristian Brauner 	return inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
29551da177e4SLinus Torvalds }
29561da177e4SLinus Torvalds 
29571da177e4SLinus Torvalds /*
29581da177e4SLinus Torvalds  * p1 and p2 should be directories on the same fs.
29591da177e4SLinus Torvalds  */
29601da177e4SLinus Torvalds struct dentry *lock_rename(struct dentry *p1, struct dentry *p2)
29611da177e4SLinus Torvalds {
29621da177e4SLinus Torvalds 	struct dentry *p;
29631da177e4SLinus Torvalds 
29641da177e4SLinus Torvalds 	if (p1 == p2) {
29655955102cSAl Viro 		inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
29661da177e4SLinus Torvalds 		return NULL;
29671da177e4SLinus Torvalds 	}
29681da177e4SLinus Torvalds 
2969fc64005cSAl Viro 	mutex_lock(&p1->d_sb->s_vfs_rename_mutex);
29701da177e4SLinus Torvalds 
2971e2761a11SOGAWA Hirofumi 	p = d_ancestor(p2, p1);
2972e2761a11SOGAWA Hirofumi 	if (p) {
29735955102cSAl Viro 		inode_lock_nested(p2->d_inode, I_MUTEX_PARENT);
29745955102cSAl Viro 		inode_lock_nested(p1->d_inode, I_MUTEX_CHILD);
29751da177e4SLinus Torvalds 		return p;
29761da177e4SLinus Torvalds 	}
29771da177e4SLinus Torvalds 
2978e2761a11SOGAWA Hirofumi 	p = d_ancestor(p1, p2);
2979e2761a11SOGAWA Hirofumi 	if (p) {
29805955102cSAl Viro 		inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
29815955102cSAl Viro 		inode_lock_nested(p2->d_inode, I_MUTEX_CHILD);
29821da177e4SLinus Torvalds 		return p;
29831da177e4SLinus Torvalds 	}
29841da177e4SLinus Torvalds 
29855955102cSAl Viro 	inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
29865955102cSAl Viro 	inode_lock_nested(p2->d_inode, I_MUTEX_PARENT2);
29871da177e4SLinus Torvalds 	return NULL;
29881da177e4SLinus Torvalds }
29894d359507SAl Viro EXPORT_SYMBOL(lock_rename);
29901da177e4SLinus Torvalds 
29911da177e4SLinus Torvalds void unlock_rename(struct dentry *p1, struct dentry *p2)
29921da177e4SLinus Torvalds {
29935955102cSAl Viro 	inode_unlock(p1->d_inode);
29941da177e4SLinus Torvalds 	if (p1 != p2) {
29955955102cSAl Viro 		inode_unlock(p2->d_inode);
2996fc64005cSAl Viro 		mutex_unlock(&p1->d_sb->s_vfs_rename_mutex);
29971da177e4SLinus Torvalds 	}
29981da177e4SLinus Torvalds }
29994d359507SAl Viro EXPORT_SYMBOL(unlock_rename);
30001da177e4SLinus Torvalds 
30016521f891SChristian Brauner /**
30026521f891SChristian Brauner  * vfs_create - create new file
30036521f891SChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
30046521f891SChristian Brauner  * @dir:	inode of @dentry
30056521f891SChristian Brauner  * @dentry:	pointer to dentry of the base directory
30066521f891SChristian Brauner  * @mode:	mode of the new file
30076521f891SChristian Brauner  * @want_excl:	whether the file must not yet exist
30086521f891SChristian Brauner  *
30096521f891SChristian Brauner  * Create a new file.
30106521f891SChristian Brauner  *
30116521f891SChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
30126521f891SChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
30136521f891SChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
30146521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
30156521f891SChristian Brauner  * raw inode simply passs init_user_ns.
30166521f891SChristian Brauner  */
30176521f891SChristian Brauner int vfs_create(struct user_namespace *mnt_userns, struct inode *dir,
30186521f891SChristian Brauner 	       struct dentry *dentry, umode_t mode, bool want_excl)
30191da177e4SLinus Torvalds {
30206521f891SChristian Brauner 	int error = may_create(mnt_userns, dir, dentry);
30211da177e4SLinus Torvalds 	if (error)
30221da177e4SLinus Torvalds 		return error;
30231da177e4SLinus Torvalds 
3024acfa4380SAl Viro 	if (!dir->i_op->create)
30251da177e4SLinus Torvalds 		return -EACCES;	/* shouldn't it be ENOSYS? */
30261da177e4SLinus Torvalds 	mode &= S_IALLUGO;
30271da177e4SLinus Torvalds 	mode |= S_IFREG;
30281da177e4SLinus Torvalds 	error = security_inode_create(dir, dentry, mode);
30291da177e4SLinus Torvalds 	if (error)
30301da177e4SLinus Torvalds 		return error;
3031549c7297SChristian Brauner 	error = dir->i_op->create(mnt_userns, dir, dentry, mode, want_excl);
3032a74574aaSStephen Smalley 	if (!error)
3033f38aa942SAmy Griffis 		fsnotify_create(dir, dentry);
30341da177e4SLinus Torvalds 	return error;
30351da177e4SLinus Torvalds }
30364d359507SAl Viro EXPORT_SYMBOL(vfs_create);
30371da177e4SLinus Torvalds 
30388e6c848eSAl Viro int vfs_mkobj(struct dentry *dentry, umode_t mode,
30398e6c848eSAl Viro 		int (*f)(struct dentry *, umode_t, void *),
30408e6c848eSAl Viro 		void *arg)
30418e6c848eSAl Viro {
30428e6c848eSAl Viro 	struct inode *dir = dentry->d_parent->d_inode;
3043ba73d987SChristian Brauner 	int error = may_create(&init_user_ns, dir, dentry);
30448e6c848eSAl Viro 	if (error)
30458e6c848eSAl Viro 		return error;
30468e6c848eSAl Viro 
30478e6c848eSAl Viro 	mode &= S_IALLUGO;
30488e6c848eSAl Viro 	mode |= S_IFREG;
30498e6c848eSAl Viro 	error = security_inode_create(dir, dentry, mode);
30508e6c848eSAl Viro 	if (error)
30518e6c848eSAl Viro 		return error;
30528e6c848eSAl Viro 	error = f(dentry, mode, arg);
30538e6c848eSAl Viro 	if (!error)
30548e6c848eSAl Viro 		fsnotify_create(dir, dentry);
30558e6c848eSAl Viro 	return error;
30568e6c848eSAl Viro }
30578e6c848eSAl Viro EXPORT_SYMBOL(vfs_mkobj);
30588e6c848eSAl Viro 
3059a2982cc9SEric W. Biederman bool may_open_dev(const struct path *path)
3060a2982cc9SEric W. Biederman {
3061a2982cc9SEric W. Biederman 	return !(path->mnt->mnt_flags & MNT_NODEV) &&
3062a2982cc9SEric W. Biederman 		!(path->mnt->mnt_sb->s_iflags & SB_I_NODEV);
3063a2982cc9SEric W. Biederman }
3064a2982cc9SEric W. Biederman 
3065ba73d987SChristian Brauner static int may_open(struct user_namespace *mnt_userns, const struct path *path,
3066ba73d987SChristian Brauner 		    int acc_mode, int flag)
30671da177e4SLinus Torvalds {
30683fb64190SChristoph Hellwig 	struct dentry *dentry = path->dentry;
30691da177e4SLinus Torvalds 	struct inode *inode = dentry->d_inode;
30701da177e4SLinus Torvalds 	int error;
30711da177e4SLinus Torvalds 
30721da177e4SLinus Torvalds 	if (!inode)
30731da177e4SLinus Torvalds 		return -ENOENT;
30741da177e4SLinus Torvalds 
3075c8fe8f30SChristoph Hellwig 	switch (inode->i_mode & S_IFMT) {
3076c8fe8f30SChristoph Hellwig 	case S_IFLNK:
30771da177e4SLinus Torvalds 		return -ELOOP;
3078c8fe8f30SChristoph Hellwig 	case S_IFDIR:
3079fc4177beSKees Cook 		if (acc_mode & MAY_WRITE)
30801da177e4SLinus Torvalds 			return -EISDIR;
3081fc4177beSKees Cook 		if (acc_mode & MAY_EXEC)
3082fc4177beSKees Cook 			return -EACCES;
3083c8fe8f30SChristoph Hellwig 		break;
3084c8fe8f30SChristoph Hellwig 	case S_IFBLK:
3085c8fe8f30SChristoph Hellwig 	case S_IFCHR:
3086a2982cc9SEric W. Biederman 		if (!may_open_dev(path))
30871da177e4SLinus Torvalds 			return -EACCES;
3088633fb6acSKees Cook 		fallthrough;
3089c8fe8f30SChristoph Hellwig 	case S_IFIFO:
3090c8fe8f30SChristoph Hellwig 	case S_IFSOCK:
3091633fb6acSKees Cook 		if (acc_mode & MAY_EXEC)
3092633fb6acSKees Cook 			return -EACCES;
30931da177e4SLinus Torvalds 		flag &= ~O_TRUNC;
3094c8fe8f30SChristoph Hellwig 		break;
30950fd338b2SKees Cook 	case S_IFREG:
30960fd338b2SKees Cook 		if ((acc_mode & MAY_EXEC) && path_noexec(path))
30970fd338b2SKees Cook 			return -EACCES;
30980fd338b2SKees Cook 		break;
30994a3fd211SDave Hansen 	}
3100b41572e9SDave Hansen 
3101ba73d987SChristian Brauner 	error = inode_permission(mnt_userns, inode, MAY_OPEN | acc_mode);
3102b41572e9SDave Hansen 	if (error)
3103b41572e9SDave Hansen 		return error;
31046146f0d5SMimi Zohar 
31051da177e4SLinus Torvalds 	/*
31061da177e4SLinus Torvalds 	 * An append-only file must be opened in append mode for writing.
31071da177e4SLinus Torvalds 	 */
31081da177e4SLinus Torvalds 	if (IS_APPEND(inode)) {
31098737c930SAl Viro 		if  ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND))
31107715b521SAl Viro 			return -EPERM;
31111da177e4SLinus Torvalds 		if (flag & O_TRUNC)
31127715b521SAl Viro 			return -EPERM;
31131da177e4SLinus Torvalds 	}
31141da177e4SLinus Torvalds 
31151da177e4SLinus Torvalds 	/* O_NOATIME can only be set by the owner or superuser */
3116ba73d987SChristian Brauner 	if (flag & O_NOATIME && !inode_owner_or_capable(mnt_userns, inode))
31177715b521SAl Viro 		return -EPERM;
31181da177e4SLinus Torvalds 
3119f3c7691eSJ. Bruce Fields 	return 0;
31207715b521SAl Viro }
31217715b521SAl Viro 
3122549c7297SChristian Brauner static int handle_truncate(struct user_namespace *mnt_userns, struct file *filp)
31237715b521SAl Viro {
3124f0bb5aafSAl Viro 	const struct path *path = &filp->f_path;
31257715b521SAl Viro 	struct inode *inode = path->dentry->d_inode;
31267715b521SAl Viro 	int error = get_write_access(inode);
31271da177e4SLinus Torvalds 	if (error)
31287715b521SAl Viro 		return error;
3129482e0007SJeff Layton 
3130ea0d3ab2STetsuo Handa 	error = security_path_truncate(path);
31311da177e4SLinus Torvalds 	if (!error) {
3132549c7297SChristian Brauner 		error = do_truncate(mnt_userns, path->dentry, 0,
3133d139d7ffSMiklos Szeredi 				    ATTR_MTIME|ATTR_CTIME|ATTR_OPEN,
3134e1181ee6SJeff Layton 				    filp);
31351da177e4SLinus Torvalds 	}
31361da177e4SLinus Torvalds 	put_write_access(inode);
3137acd0c935SMimi Zohar 	return error;
31381da177e4SLinus Torvalds }
31391da177e4SLinus Torvalds 
3140d57999e1SDave Hansen static inline int open_to_namei_flags(int flag)
3141d57999e1SDave Hansen {
31428a5e929dSAl Viro 	if ((flag & O_ACCMODE) == 3)
31438a5e929dSAl Viro 		flag--;
3144d57999e1SDave Hansen 	return flag;
3145d57999e1SDave Hansen }
3146d57999e1SDave Hansen 
3147ba73d987SChristian Brauner static int may_o_create(struct user_namespace *mnt_userns,
3148ba73d987SChristian Brauner 			const struct path *dir, struct dentry *dentry,
3149ba73d987SChristian Brauner 			umode_t mode)
3150d18e9008SMiklos Szeredi {
3151d18e9008SMiklos Szeredi 	int error = security_path_mknod(dir, dentry, mode, 0);
3152d18e9008SMiklos Szeredi 	if (error)
3153d18e9008SMiklos Szeredi 		return error;
3154d18e9008SMiklos Szeredi 
31558e538913SChristian Brauner 	if (!fsuidgid_has_mapping(dir->dentry->d_sb, mnt_userns))
31561328c727SSeth Forshee 		return -EOVERFLOW;
31571328c727SSeth Forshee 
3158ba73d987SChristian Brauner 	error = inode_permission(mnt_userns, dir->dentry->d_inode,
315947291baaSChristian Brauner 				 MAY_WRITE | MAY_EXEC);
3160d18e9008SMiklos Szeredi 	if (error)
3161d18e9008SMiklos Szeredi 		return error;
3162d18e9008SMiklos Szeredi 
3163d18e9008SMiklos Szeredi 	return security_inode_create(dir->dentry->d_inode, dentry, mode);
3164d18e9008SMiklos Szeredi }
3165d18e9008SMiklos Szeredi 
31661acf0af9SDavid Howells /*
31671acf0af9SDavid Howells  * Attempt to atomically look up, create and open a file from a negative
31681acf0af9SDavid Howells  * dentry.
31691acf0af9SDavid Howells  *
31701acf0af9SDavid Howells  * Returns 0 if successful.  The file will have been created and attached to
31711acf0af9SDavid Howells  * @file by the filesystem calling finish_open().
31721acf0af9SDavid Howells  *
317300a07c15SAl Viro  * If the file was looked up only or didn't need creating, FMODE_OPENED won't
317400a07c15SAl Viro  * be set.  The caller will need to perform the open themselves.  @path will
317500a07c15SAl Viro  * have been updated to point to the new dentry.  This may be negative.
31761acf0af9SDavid Howells  *
31771acf0af9SDavid Howells  * Returns an error code otherwise.
31781acf0af9SDavid Howells  */
3179239eb983SAl Viro static struct dentry *atomic_open(struct nameidata *nd, struct dentry *dentry,
3180239eb983SAl Viro 				  struct file *file,
31813ec2eef1SAl Viro 				  int open_flag, umode_t mode)
3182d18e9008SMiklos Szeredi {
3183d18e9008SMiklos Szeredi 	struct dentry *const DENTRY_NOT_SET = (void *) -1UL;
3184d18e9008SMiklos Szeredi 	struct inode *dir =  nd->path.dentry->d_inode;
3185d18e9008SMiklos Szeredi 	int error;
3186d18e9008SMiklos Szeredi 
3187d18e9008SMiklos Szeredi 	if (nd->flags & LOOKUP_DIRECTORY)
3188d18e9008SMiklos Szeredi 		open_flag |= O_DIRECTORY;
3189d18e9008SMiklos Szeredi 
319030d90494SAl Viro 	file->f_path.dentry = DENTRY_NOT_SET;
319130d90494SAl Viro 	file->f_path.mnt = nd->path.mnt;
31920fb1ea09SAl Viro 	error = dir->i_op->atomic_open(dir, dentry, file,
319344907d79SAl Viro 				       open_to_namei_flags(open_flag), mode);
31946fbd0714SAl Viro 	d_lookup_done(dentry);
3195384f26e2SAl Viro 	if (!error) {
319664e1ac4dSAl Viro 		if (file->f_mode & FMODE_OPENED) {
31976fb968cdSAl Viro 			if (unlikely(dentry != file->f_path.dentry)) {
31986fb968cdSAl Viro 				dput(dentry);
31996fb968cdSAl Viro 				dentry = dget(file->f_path.dentry);
32006fb968cdSAl Viro 			}
320164e1ac4dSAl Viro 		} else if (WARN_ON(file->f_path.dentry == DENTRY_NOT_SET)) {
32022675a4ebSAl Viro 			error = -EIO;
3203384f26e2SAl Viro 		} else {
320430d90494SAl Viro 			if (file->f_path.dentry) {
3205d18e9008SMiklos Szeredi 				dput(dentry);
3206d18e9008SMiklos Szeredi 				dentry = file->f_path.dentry;
320710c64ceaSAl Viro 			}
3208239eb983SAl Viro 			if (unlikely(d_is_negative(dentry)))
3209a01e718fSAl Viro 				error = -ENOENT;
3210d18e9008SMiklos Szeredi 		}
3211d18e9008SMiklos Szeredi 	}
3212239eb983SAl Viro 	if (error) {
3213d18e9008SMiklos Szeredi 		dput(dentry);
3214239eb983SAl Viro 		dentry = ERR_PTR(error);
3215239eb983SAl Viro 	}
3216239eb983SAl Viro 	return dentry;
3217d18e9008SMiklos Szeredi }
3218d18e9008SMiklos Szeredi 
321931e6b01fSNick Piggin /*
32201acf0af9SDavid Howells  * Look up and maybe create and open the last component.
3221d58ffd35SMiklos Szeredi  *
322200a07c15SAl Viro  * Must be called with parent locked (exclusive in O_CREAT case).
3223d58ffd35SMiklos Szeredi  *
322400a07c15SAl Viro  * Returns 0 on success, that is, if
322500a07c15SAl Viro  *  the file was successfully atomically created (if necessary) and opened, or
322600a07c15SAl Viro  *  the file was not completely opened at this time, though lookups and
322700a07c15SAl Viro  *  creations were performed.
322800a07c15SAl Viro  * These case are distinguished by presence of FMODE_OPENED on file->f_mode.
322900a07c15SAl Viro  * In the latter case dentry returned in @path might be negative if O_CREAT
323000a07c15SAl Viro  * hadn't been specified.
32311acf0af9SDavid Howells  *
323200a07c15SAl Viro  * An error code is returned on failure.
3233d58ffd35SMiklos Szeredi  */
3234da5ebf5aSAl Viro static struct dentry *lookup_open(struct nameidata *nd, struct file *file,
3235d58ffd35SMiklos Szeredi 				  const struct open_flags *op,
32363ec2eef1SAl Viro 				  bool got_write)
3237d58ffd35SMiklos Szeredi {
3238549c7297SChristian Brauner 	struct user_namespace *mnt_userns;
3239d58ffd35SMiklos Szeredi 	struct dentry *dir = nd->path.dentry;
324054ef4872SMiklos Szeredi 	struct inode *dir_inode = dir->d_inode;
32411643b43fSAl Viro 	int open_flag = op->open_flag;
3242d58ffd35SMiklos Szeredi 	struct dentry *dentry;
32431643b43fSAl Viro 	int error, create_error = 0;
32441643b43fSAl Viro 	umode_t mode = op->mode;
32456fbd0714SAl Viro 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
3246d58ffd35SMiklos Szeredi 
3247ce8644fcSAl Viro 	if (unlikely(IS_DEADDIR(dir_inode)))
3248da5ebf5aSAl Viro 		return ERR_PTR(-ENOENT);
3249d58ffd35SMiklos Szeredi 
325073a09dd9SAl Viro 	file->f_mode &= ~FMODE_CREATED;
32516fbd0714SAl Viro 	dentry = d_lookup(dir, &nd->last);
32526fbd0714SAl Viro 	for (;;) {
32536fbd0714SAl Viro 		if (!dentry) {
32546fbd0714SAl Viro 			dentry = d_alloc_parallel(dir, &nd->last, &wq);
3255d58ffd35SMiklos Szeredi 			if (IS_ERR(dentry))
3256da5ebf5aSAl Viro 				return dentry;
32576fbd0714SAl Viro 		}
32586fbd0714SAl Viro 		if (d_in_lookup(dentry))
32596fbd0714SAl Viro 			break;
3260d58ffd35SMiklos Szeredi 
32616fbd0714SAl Viro 		error = d_revalidate(dentry, nd->flags);
32626fbd0714SAl Viro 		if (likely(error > 0))
32636fbd0714SAl Viro 			break;
32646fbd0714SAl Viro 		if (error)
32656fbd0714SAl Viro 			goto out_dput;
32666fbd0714SAl Viro 		d_invalidate(dentry);
32676fbd0714SAl Viro 		dput(dentry);
32686fbd0714SAl Viro 		dentry = NULL;
32696fbd0714SAl Viro 	}
32706fbd0714SAl Viro 	if (dentry->d_inode) {
3271d18e9008SMiklos Szeredi 		/* Cached positive dentry: will open in f_op->open */
3272da5ebf5aSAl Viro 		return dentry;
32736c51e513SAl Viro 	}
3274d18e9008SMiklos Szeredi 
32751643b43fSAl Viro 	/*
32761643b43fSAl Viro 	 * Checking write permission is tricky, bacuse we don't know if we are
32771643b43fSAl Viro 	 * going to actually need it: O_CREAT opens should work as long as the
32781643b43fSAl Viro 	 * file exists.  But checking existence breaks atomicity.  The trick is
32791643b43fSAl Viro 	 * to check access and if not granted clear O_CREAT from the flags.
32801643b43fSAl Viro 	 *
32811643b43fSAl Viro 	 * Another problem is returing the "right" error value (e.g. for an
32821643b43fSAl Viro 	 * O_EXCL open we want to return EEXIST not EROFS).
32831643b43fSAl Viro 	 */
328499a4a90cSAl Viro 	if (unlikely(!got_write))
328599a4a90cSAl Viro 		open_flag &= ~O_TRUNC;
3286549c7297SChristian Brauner 	mnt_userns = mnt_user_ns(nd->path.mnt);
32871643b43fSAl Viro 	if (open_flag & O_CREAT) {
328899a4a90cSAl Viro 		if (open_flag & O_EXCL)
328999a4a90cSAl Viro 			open_flag &= ~O_TRUNC;
32901643b43fSAl Viro 		if (!IS_POSIXACL(dir->d_inode))
32911643b43fSAl Viro 			mode &= ~current_umask();
329299a4a90cSAl Viro 		if (likely(got_write))
3293549c7297SChristian Brauner 			create_error = may_o_create(mnt_userns, &nd->path,
3294ba73d987SChristian Brauner 						    dentry, mode);
329599a4a90cSAl Viro 		else
329699a4a90cSAl Viro 			create_error = -EROFS;
329799a4a90cSAl Viro 	}
329899a4a90cSAl Viro 	if (create_error)
32991643b43fSAl Viro 		open_flag &= ~O_CREAT;
33001643b43fSAl Viro 	if (dir_inode->i_op->atomic_open) {
3301d489cf9aSAl Viro 		dentry = atomic_open(nd, dentry, file, open_flag, mode);
3302da5ebf5aSAl Viro 		if (unlikely(create_error) && dentry == ERR_PTR(-ENOENT))
3303da5ebf5aSAl Viro 			dentry = ERR_PTR(create_error);
3304da5ebf5aSAl Viro 		return dentry;
3305239eb983SAl Viro 	}
330654ef4872SMiklos Szeredi 
33076fbd0714SAl Viro 	if (d_in_lookup(dentry)) {
330812fa5e24SAl Viro 		struct dentry *res = dir_inode->i_op->lookup(dir_inode, dentry,
330912fa5e24SAl Viro 							     nd->flags);
33106fbd0714SAl Viro 		d_lookup_done(dentry);
331112fa5e24SAl Viro 		if (unlikely(res)) {
331212fa5e24SAl Viro 			if (IS_ERR(res)) {
331312fa5e24SAl Viro 				error = PTR_ERR(res);
331412fa5e24SAl Viro 				goto out_dput;
331512fa5e24SAl Viro 			}
331612fa5e24SAl Viro 			dput(dentry);
331712fa5e24SAl Viro 			dentry = res;
331812fa5e24SAl Viro 		}
331954ef4872SMiklos Szeredi 	}
332054ef4872SMiklos Szeredi 
3321d58ffd35SMiklos Szeredi 	/* Negative dentry, just create the file */
33221643b43fSAl Viro 	if (!dentry->d_inode && (open_flag & O_CREAT)) {
332373a09dd9SAl Viro 		file->f_mode |= FMODE_CREATED;
3324ce8644fcSAl Viro 		audit_inode_child(dir_inode, dentry, AUDIT_TYPE_CHILD_CREATE);
3325ce8644fcSAl Viro 		if (!dir_inode->i_op->create) {
3326ce8644fcSAl Viro 			error = -EACCES;
3327d58ffd35SMiklos Szeredi 			goto out_dput;
332864894cf8SAl Viro 		}
3329549c7297SChristian Brauner 
3330549c7297SChristian Brauner 		error = dir_inode->i_op->create(mnt_userns, dir_inode, dentry,
3331549c7297SChristian Brauner 						mode, open_flag & O_EXCL);
3332d58ffd35SMiklos Szeredi 		if (error)
3333d58ffd35SMiklos Szeredi 			goto out_dput;
3334d58ffd35SMiklos Szeredi 	}
33351643b43fSAl Viro 	if (unlikely(create_error) && !dentry->d_inode) {
33361643b43fSAl Viro 		error = create_error;
3337d58ffd35SMiklos Szeredi 		goto out_dput;
3338d58ffd35SMiklos Szeredi 	}
3339da5ebf5aSAl Viro 	return dentry;
3340d58ffd35SMiklos Szeredi 
3341d58ffd35SMiklos Szeredi out_dput:
3342d58ffd35SMiklos Szeredi 	dput(dentry);
3343da5ebf5aSAl Viro 	return ERR_PTR(error);
3344d58ffd35SMiklos Szeredi }
3345d58ffd35SMiklos Szeredi 
3346c981a482SAl Viro static const char *open_last_lookups(struct nameidata *nd,
33473ec2eef1SAl Viro 		   struct file *file, const struct open_flags *op)
3348fb1cc555SAl Viro {
3349a1e28038SAl Viro 	struct dentry *dir = nd->path.dentry;
3350ca344a89SAl Viro 	int open_flag = op->open_flag;
335164894cf8SAl Viro 	bool got_write = false;
3352254cf582SAl Viro 	unsigned seq;
3353a1eb3315SMiklos Szeredi 	struct inode *inode;
3354da5ebf5aSAl Viro 	struct dentry *dentry;
3355b0417d2cSAl Viro 	const char *res;
3356fb1cc555SAl Viro 
3357c3e380b0SAl Viro 	nd->flags |= op->intent;
3358c3e380b0SAl Viro 
3359bc77daa7SAl Viro 	if (nd->last_type != LAST_NORM) {
336056676ec3SAl Viro 		if (nd->depth)
336156676ec3SAl Viro 			put_link(nd);
3362ff326a32SAl Viro 		return handle_dots(nd, nd->last_type);
33631f36f774SAl Viro 	}
3364a2c36b45SAl Viro 
3365ca344a89SAl Viro 	if (!(open_flag & O_CREAT)) {
3366fe2d35ffSAl Viro 		if (nd->last.name[nd->last.len])
3367fe2d35ffSAl Viro 			nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
3368fe2d35ffSAl Viro 		/* we _can_ be in RCU mode here */
336920e34357SAl Viro 		dentry = lookup_fast(nd, &inode, &seq);
337020e34357SAl Viro 		if (IS_ERR(dentry))
33711ccac622SAl Viro 			return ERR_CAST(dentry);
337220e34357SAl Viro 		if (likely(dentry))
337371574865SMiklos Szeredi 			goto finish_lookup;
337471574865SMiklos Szeredi 
33756583fe22SAl Viro 		BUG_ON(nd->flags & LOOKUP_RCU);
3376b6183df7SMiklos Szeredi 	} else {
3377fe2d35ffSAl Viro 		/* create side of things */
337872287417SAl Viro 		if (nd->flags & LOOKUP_RCU) {
3379e36cffedSJens Axboe 			if (!try_to_unlazy(nd))
3380e36cffedSJens Axboe 				return ERR_PTR(-ECHILD);
338172287417SAl Viro 		}
3382c9b07eabSAl Viro 		audit_inode(nd->name, dir, AUDIT_INODE_PARENT);
33831f36f774SAl Viro 		/* trailing slashes? */
3384deb106c6SAl Viro 		if (unlikely(nd->last.name[nd->last.len]))
33851ccac622SAl Viro 			return ERR_PTR(-EISDIR);
3386b6183df7SMiklos Szeredi 	}
33871f36f774SAl Viro 
33889cf843e3SAl Viro 	if (open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) {
3389e36cffedSJens Axboe 		got_write = !mnt_want_write(nd->path.mnt);
339064894cf8SAl Viro 		/*
339164894cf8SAl Viro 		 * do _not_ fail yet - we might not need that or fail with
339264894cf8SAl Viro 		 * a different error; let lookup_open() decide; we'll be
339364894cf8SAl Viro 		 * dropping this one anyway.
339464894cf8SAl Viro 		 */
339564894cf8SAl Viro 	}
33969cf843e3SAl Viro 	if (open_flag & O_CREAT)
33975955102cSAl Viro 		inode_lock(dir->d_inode);
33989cf843e3SAl Viro 	else
33999cf843e3SAl Viro 		inode_lock_shared(dir->d_inode);
3400da5ebf5aSAl Viro 	dentry = lookup_open(nd, file, op, got_write);
3401f7bb959dSAl Viro 	if (!IS_ERR(dentry) && (file->f_mode & FMODE_CREATED))
3402f7bb959dSAl Viro 		fsnotify_create(dir->d_inode, dentry);
34039cf843e3SAl Viro 	if (open_flag & O_CREAT)
34045955102cSAl Viro 		inode_unlock(dir->d_inode);
34059cf843e3SAl Viro 	else
34069cf843e3SAl Viro 		inode_unlock_shared(dir->d_inode);
3407fb1cc555SAl Viro 
3408c981a482SAl Viro 	if (got_write)
340959e96e65SAl Viro 		mnt_drop_write(nd->path.mnt);
34106c0d46c4SAl Viro 
341159e96e65SAl Viro 	if (IS_ERR(dentry))
341259e96e65SAl Viro 		return ERR_CAST(dentry);
341359e96e65SAl Viro 
3414973d4b73SAl Viro 	if (file->f_mode & (FMODE_OPENED | FMODE_CREATED)) {
3415e73cabffSAl Viro 		dput(nd->path.dentry);
3416e73cabffSAl Viro 		nd->path.dentry = dentry;
3417c981a482SAl Viro 		return NULL;
3418fb1cc555SAl Viro 	}
3419fb1cc555SAl Viro 
342020e34357SAl Viro finish_lookup:
342156676ec3SAl Viro 	if (nd->depth)
342256676ec3SAl Viro 		put_link(nd);
34238c4efe22SAl Viro 	res = step_into(nd, WALK_TRAILING, dentry, inode, seq);
3424ff326a32SAl Viro 	if (unlikely(res))
34251ccac622SAl Viro 		nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL);
3426b0417d2cSAl Viro 	return res;
34271ccac622SAl Viro }
342831d1726dSAl Viro 
3429c981a482SAl Viro /*
3430c981a482SAl Viro  * Handle the last step of open()
3431c981a482SAl Viro  */
3432c5971b8cSAl Viro static int do_open(struct nameidata *nd,
3433c981a482SAl Viro 		   struct file *file, const struct open_flags *op)
3434c981a482SAl Viro {
3435549c7297SChristian Brauner 	struct user_namespace *mnt_userns;
3436c981a482SAl Viro 	int open_flag = op->open_flag;
3437c981a482SAl Viro 	bool do_truncate;
3438c981a482SAl Viro 	int acc_mode;
3439c981a482SAl Viro 	int error;
3440c981a482SAl Viro 
3441ff326a32SAl Viro 	if (!(file->f_mode & (FMODE_OPENED | FMODE_CREATED))) {
3442ff326a32SAl Viro 		error = complete_walk(nd);
3443ff326a32SAl Viro 		if (error)
3444ff326a32SAl Viro 			return error;
3445ff326a32SAl Viro 	}
3446973d4b73SAl Viro 	if (!(file->f_mode & FMODE_CREATED))
344776ae2a5aSAl Viro 		audit_inode(nd->name, nd->path.dentry, 0);
3448549c7297SChristian Brauner 	mnt_userns = mnt_user_ns(nd->path.mnt);
344930aba665SSalvatore Mesoraca 	if (open_flag & O_CREAT) {
3450b94e0b32SAl Viro 		if ((open_flag & O_EXCL) && !(file->f_mode & FMODE_CREATED))
3451b94e0b32SAl Viro 			return -EEXIST;
345230aba665SSalvatore Mesoraca 		if (d_is_dir(nd->path.dentry))
3453c5971b8cSAl Viro 			return -EISDIR;
3454549c7297SChristian Brauner 		error = may_create_in_sticky(mnt_userns, nd,
345530aba665SSalvatore Mesoraca 					     d_backing_inode(nd->path.dentry));
345630aba665SSalvatore Mesoraca 		if (unlikely(error))
3457c5971b8cSAl Viro 			return error;
345830aba665SSalvatore Mesoraca 	}
345944b1d530SMiklos Szeredi 	if ((nd->flags & LOOKUP_DIRECTORY) && !d_can_lookup(nd->path.dentry))
3460c5971b8cSAl Viro 		return -ENOTDIR;
34616c0d46c4SAl Viro 
34628795e7d4SAl Viro 	do_truncate = false;
34638795e7d4SAl Viro 	acc_mode = op->acc_mode;
34645a2d3eddSAl Viro 	if (file->f_mode & FMODE_CREATED) {
34655a2d3eddSAl Viro 		/* Don't check for write permission, don't truncate */
34665a2d3eddSAl Viro 		open_flag &= ~O_TRUNC;
34675a2d3eddSAl Viro 		acc_mode = 0;
34688795e7d4SAl Viro 	} else if (d_is_reg(nd->path.dentry) && open_flag & O_TRUNC) {
34690f9d1a10SAl Viro 		error = mnt_want_write(nd->path.mnt);
34700f9d1a10SAl Viro 		if (error)
3471c5971b8cSAl Viro 			return error;
34728795e7d4SAl Viro 		do_truncate = true;
34730f9d1a10SAl Viro 	}
3474549c7297SChristian Brauner 	error = may_open(mnt_userns, &nd->path, acc_mode, open_flag);
34758795e7d4SAl Viro 	if (!error && !(file->f_mode & FMODE_OPENED))
3476ae2bb293SAl Viro 		error = vfs_open(&nd->path, file);
34778795e7d4SAl Viro 	if (!error)
34786035a27bSAl Viro 		error = ima_file_check(file, op->acc_mode);
34798795e7d4SAl Viro 	if (!error && do_truncate)
3480549c7297SChristian Brauner 		error = handle_truncate(mnt_userns, file);
3481c80567c8SAl Viro 	if (unlikely(error > 0)) {
3482c80567c8SAl Viro 		WARN_ON(1);
3483c80567c8SAl Viro 		error = -EINVAL;
3484c80567c8SAl Viro 	}
34858795e7d4SAl Viro 	if (do_truncate)
34860f9d1a10SAl Viro 		mnt_drop_write(nd->path.mnt);
3487c5971b8cSAl Viro 	return error;
3488fb1cc555SAl Viro }
3489fb1cc555SAl Viro 
34906521f891SChristian Brauner /**
34916521f891SChristian Brauner  * vfs_tmpfile - create tmpfile
34926521f891SChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
34936521f891SChristian Brauner  * @dentry:	pointer to dentry of the base directory
34946521f891SChristian Brauner  * @mode:	mode of the new tmpfile
34952111c3c0SRandy Dunlap  * @open_flag:	flags
34966521f891SChristian Brauner  *
34976521f891SChristian Brauner  * Create a temporary file.
34986521f891SChristian Brauner  *
34996521f891SChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
35006521f891SChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
35016521f891SChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
35026521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
35036521f891SChristian Brauner  * raw inode simply passs init_user_ns.
35046521f891SChristian Brauner  */
35056521f891SChristian Brauner struct dentry *vfs_tmpfile(struct user_namespace *mnt_userns,
35066521f891SChristian Brauner 			   struct dentry *dentry, umode_t mode, int open_flag)
3507af7bd4dcSAmir Goldstein {
3508af7bd4dcSAmir Goldstein 	struct dentry *child = NULL;
3509af7bd4dcSAmir Goldstein 	struct inode *dir = dentry->d_inode;
3510af7bd4dcSAmir Goldstein 	struct inode *inode;
3511af7bd4dcSAmir Goldstein 	int error;
3512af7bd4dcSAmir Goldstein 
3513af7bd4dcSAmir Goldstein 	/* we want directory to be writable */
35146521f891SChristian Brauner 	error = inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
3515af7bd4dcSAmir Goldstein 	if (error)
3516af7bd4dcSAmir Goldstein 		goto out_err;
3517af7bd4dcSAmir Goldstein 	error = -EOPNOTSUPP;
3518af7bd4dcSAmir Goldstein 	if (!dir->i_op->tmpfile)
3519af7bd4dcSAmir Goldstein 		goto out_err;
3520af7bd4dcSAmir Goldstein 	error = -ENOMEM;
3521cdf01226SDavid Howells 	child = d_alloc(dentry, &slash_name);
3522af7bd4dcSAmir Goldstein 	if (unlikely(!child))
3523af7bd4dcSAmir Goldstein 		goto out_err;
3524549c7297SChristian Brauner 	error = dir->i_op->tmpfile(mnt_userns, dir, child, mode);
3525af7bd4dcSAmir Goldstein 	if (error)
3526af7bd4dcSAmir Goldstein 		goto out_err;
3527af7bd4dcSAmir Goldstein 	error = -ENOENT;
3528af7bd4dcSAmir Goldstein 	inode = child->d_inode;
3529af7bd4dcSAmir Goldstein 	if (unlikely(!inode))
3530af7bd4dcSAmir Goldstein 		goto out_err;
3531af7bd4dcSAmir Goldstein 	if (!(open_flag & O_EXCL)) {
3532af7bd4dcSAmir Goldstein 		spin_lock(&inode->i_lock);
3533af7bd4dcSAmir Goldstein 		inode->i_state |= I_LINKABLE;
3534af7bd4dcSAmir Goldstein 		spin_unlock(&inode->i_lock);
3535af7bd4dcSAmir Goldstein 	}
3536a2d2329eSChristian Brauner 	ima_post_create_tmpfile(mnt_userns, inode);
3537af7bd4dcSAmir Goldstein 	return child;
3538af7bd4dcSAmir Goldstein 
3539af7bd4dcSAmir Goldstein out_err:
3540af7bd4dcSAmir Goldstein 	dput(child);
3541af7bd4dcSAmir Goldstein 	return ERR_PTR(error);
3542af7bd4dcSAmir Goldstein }
3543af7bd4dcSAmir Goldstein EXPORT_SYMBOL(vfs_tmpfile);
3544af7bd4dcSAmir Goldstein 
3545c8a53ee5SAl Viro static int do_tmpfile(struct nameidata *nd, unsigned flags,
354660545d0dSAl Viro 		const struct open_flags *op,
35473ec2eef1SAl Viro 		struct file *file)
354860545d0dSAl Viro {
35496521f891SChristian Brauner 	struct user_namespace *mnt_userns;
3550625b6d10SAl Viro 	struct dentry *child;
3551625b6d10SAl Viro 	struct path path;
3552c8a53ee5SAl Viro 	int error = path_lookupat(nd, flags | LOOKUP_DIRECTORY, &path);
355360545d0dSAl Viro 	if (unlikely(error))
355460545d0dSAl Viro 		return error;
3555625b6d10SAl Viro 	error = mnt_want_write(path.mnt);
355660545d0dSAl Viro 	if (unlikely(error))
355760545d0dSAl Viro 		goto out;
35586521f891SChristian Brauner 	mnt_userns = mnt_user_ns(path.mnt);
35596521f891SChristian Brauner 	child = vfs_tmpfile(mnt_userns, path.dentry, op->mode, op->open_flag);
3560af7bd4dcSAmir Goldstein 	error = PTR_ERR(child);
3561684e73beSHirofumi Nakagawa 	if (IS_ERR(child))
356260545d0dSAl Viro 		goto out2;
3563625b6d10SAl Viro 	dput(path.dentry);
3564625b6d10SAl Viro 	path.dentry = child;
3565c8a53ee5SAl Viro 	audit_inode(nd->name, child, 0);
356669a91c23SEric Rannaud 	/* Don't check for other permissions, the inode was just created */
3567549c7297SChristian Brauner 	error = may_open(mnt_userns, &path, 0, op->open_flag);
35681e8f44f1SAl Viro 	if (!error)
35691e8f44f1SAl Viro 		error = vfs_open(&path, file);
357060545d0dSAl Viro out2:
3571625b6d10SAl Viro 	mnt_drop_write(path.mnt);
357260545d0dSAl Viro out:
3573625b6d10SAl Viro 	path_put(&path);
357460545d0dSAl Viro 	return error;
357560545d0dSAl Viro }
357660545d0dSAl Viro 
35776ac08709SAl Viro static int do_o_path(struct nameidata *nd, unsigned flags, struct file *file)
35786ac08709SAl Viro {
35796ac08709SAl Viro 	struct path path;
35806ac08709SAl Viro 	int error = path_lookupat(nd, flags, &path);
35816ac08709SAl Viro 	if (!error) {
35826ac08709SAl Viro 		audit_inode(nd->name, path.dentry, 0);
3583ae2bb293SAl Viro 		error = vfs_open(&path, file);
35846ac08709SAl Viro 		path_put(&path);
35856ac08709SAl Viro 	}
35866ac08709SAl Viro 	return error;
35876ac08709SAl Viro }
35886ac08709SAl Viro 
3589c8a53ee5SAl Viro static struct file *path_openat(struct nameidata *nd,
3590c8a53ee5SAl Viro 			const struct open_flags *op, unsigned flags)
35911da177e4SLinus Torvalds {
359230d90494SAl Viro 	struct file *file;
359313aab428SAl Viro 	int error;
359431e6b01fSNick Piggin 
3595ea73ea72SAl Viro 	file = alloc_empty_file(op->open_flag, current_cred());
35961afc99beSAl Viro 	if (IS_ERR(file))
35971afc99beSAl Viro 		return file;
359831e6b01fSNick Piggin 
3599bb458c64SAl Viro 	if (unlikely(file->f_flags & __O_TMPFILE)) {
36003ec2eef1SAl Viro 		error = do_tmpfile(nd, flags, op, file);
36015f336e72SAl Viro 	} else if (unlikely(file->f_flags & O_PATH)) {
36026ac08709SAl Viro 		error = do_o_path(nd, flags, file);
36035f336e72SAl Viro 	} else {
36045f336e72SAl Viro 		const char *s = path_init(nd, flags);
36053bdba28bSAl Viro 		while (!(error = link_path_walk(s, nd)) &&
3606c5971b8cSAl Viro 		       (s = open_last_lookups(nd, file, op)) != NULL)
36071ccac622SAl Viro 			;
3608c5971b8cSAl Viro 		if (!error)
3609c5971b8cSAl Viro 			error = do_open(nd, file, op);
3610deb106c6SAl Viro 		terminate_walk(nd);
36115f336e72SAl Viro 	}
36127c1c01ecSAl Viro 	if (likely(!error)) {
3613aad888f8SAl Viro 		if (likely(file->f_mode & FMODE_OPENED))
36147c1c01ecSAl Viro 			return file;
36157c1c01ecSAl Viro 		WARN_ON(1);
36167c1c01ecSAl Viro 		error = -EINVAL;
3617015c3bbcSMiklos Szeredi 	}
36187c1c01ecSAl Viro 	fput(file);
36192675a4ebSAl Viro 	if (error == -EOPENSTALE) {
36202675a4ebSAl Viro 		if (flags & LOOKUP_RCU)
36212675a4ebSAl Viro 			error = -ECHILD;
36222675a4ebSAl Viro 		else
36232675a4ebSAl Viro 			error = -ESTALE;
36242675a4ebSAl Viro 	}
36257c1c01ecSAl Viro 	return ERR_PTR(error);
3626de459215SKirill Korotaev }
36271da177e4SLinus Torvalds 
3628669abf4eSJeff Layton struct file *do_filp_open(int dfd, struct filename *pathname,
3629f9652e10SAl Viro 		const struct open_flags *op)
363013aab428SAl Viro {
36319883d185SAl Viro 	struct nameidata nd;
3632f9652e10SAl Viro 	int flags = op->lookup_flags;
363313aab428SAl Viro 	struct file *filp;
363413aab428SAl Viro 
363506422964SAl Viro 	set_nameidata(&nd, dfd, pathname, NULL);
3636c8a53ee5SAl Viro 	filp = path_openat(&nd, op, flags | LOOKUP_RCU);
363713aab428SAl Viro 	if (unlikely(filp == ERR_PTR(-ECHILD)))
3638c8a53ee5SAl Viro 		filp = path_openat(&nd, op, flags);
363913aab428SAl Viro 	if (unlikely(filp == ERR_PTR(-ESTALE)))
3640c8a53ee5SAl Viro 		filp = path_openat(&nd, op, flags | LOOKUP_REVAL);
36419883d185SAl Viro 	restore_nameidata();
364213aab428SAl Viro 	return filp;
364313aab428SAl Viro }
364413aab428SAl Viro 
3645ffb37ca3SAl Viro struct file *do_file_open_root(const struct path *root,
3646f9652e10SAl Viro 		const char *name, const struct open_flags *op)
364773d049a4SAl Viro {
36489883d185SAl Viro 	struct nameidata nd;
364973d049a4SAl Viro 	struct file *file;
365051689104SPaul Moore 	struct filename *filename;
3651bcba1e7dSAl Viro 	int flags = op->lookup_flags;
365273d049a4SAl Viro 
3653ffb37ca3SAl Viro 	if (d_is_symlink(root->dentry) && op->intent & LOOKUP_OPEN)
365473d049a4SAl Viro 		return ERR_PTR(-ELOOP);
365573d049a4SAl Viro 
365651689104SPaul Moore 	filename = getname_kernel(name);
3657a1c83681SViresh Kumar 	if (IS_ERR(filename))
365851689104SPaul Moore 		return ERR_CAST(filename);
365951689104SPaul Moore 
366006422964SAl Viro 	set_nameidata(&nd, -1, filename, root);
3661c8a53ee5SAl Viro 	file = path_openat(&nd, op, flags | LOOKUP_RCU);
366273d049a4SAl Viro 	if (unlikely(file == ERR_PTR(-ECHILD)))
3663c8a53ee5SAl Viro 		file = path_openat(&nd, op, flags);
366473d049a4SAl Viro 	if (unlikely(file == ERR_PTR(-ESTALE)))
3665c8a53ee5SAl Viro 		file = path_openat(&nd, op, flags | LOOKUP_REVAL);
36669883d185SAl Viro 	restore_nameidata();
366751689104SPaul Moore 	putname(filename);
366873d049a4SAl Viro 	return file;
366973d049a4SAl Viro }
367073d049a4SAl Viro 
3671b4a4f213SStephen Brennan static struct dentry *filename_create(int dfd, struct filename *name,
36721ac12b4bSJeff Layton 				      struct path *path, unsigned int lookup_flags)
36731da177e4SLinus Torvalds {
3674c663e5d8SChristoph Hellwig 	struct dentry *dentry = ERR_PTR(-EEXIST);
3675391172c4SAl Viro 	struct qstr last;
3676b3d4650dSNeilBrown 	bool want_dir = lookup_flags & LOOKUP_DIRECTORY;
3677b3d4650dSNeilBrown 	unsigned int reval_flag = lookup_flags & LOOKUP_REVAL;
3678b3d4650dSNeilBrown 	unsigned int create_flags = LOOKUP_CREATE | LOOKUP_EXCL;
3679391172c4SAl Viro 	int type;
3680c30dabfeSJan Kara 	int err2;
36811ac12b4bSJeff Layton 	int error;
36821ac12b4bSJeff Layton 
3683b3d4650dSNeilBrown 	error = filename_parentat(dfd, name, reval_flag, path, &last, &type);
36840ee50b47SDmitry Kadashev 	if (error)
36850ee50b47SDmitry Kadashev 		return ERR_PTR(error);
36861da177e4SLinus Torvalds 
3687c663e5d8SChristoph Hellwig 	/*
3688c663e5d8SChristoph Hellwig 	 * Yucky last component or no last component at all?
3689c663e5d8SChristoph Hellwig 	 * (foo/., foo/.., /////)
3690c663e5d8SChristoph Hellwig 	 */
36915c31b6ceSAl Viro 	if (unlikely(type != LAST_NORM))
3692ed75e95dSAl Viro 		goto out;
3693c663e5d8SChristoph Hellwig 
3694c30dabfeSJan Kara 	/* don't fail immediately if it's r/o, at least try to report other errors */
3695391172c4SAl Viro 	err2 = mnt_want_write(path->mnt);
3696c663e5d8SChristoph Hellwig 	/*
3697b3d4650dSNeilBrown 	 * Do the final lookup.  Suppress 'create' if there is a trailing
3698b3d4650dSNeilBrown 	 * '/', and a directory wasn't requested.
3699c663e5d8SChristoph Hellwig 	 */
3700b3d4650dSNeilBrown 	if (last.name[last.len] && !want_dir)
3701b3d4650dSNeilBrown 		create_flags = 0;
37025955102cSAl Viro 	inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
3703b3d4650dSNeilBrown 	dentry = __lookup_hash(&last, path->dentry, reval_flag | create_flags);
37041da177e4SLinus Torvalds 	if (IS_ERR(dentry))
3705a8104a9fSAl Viro 		goto unlock;
3706c663e5d8SChristoph Hellwig 
3707a8104a9fSAl Viro 	error = -EEXIST;
3708b18825a7SDavid Howells 	if (d_is_positive(dentry))
3709a8104a9fSAl Viro 		goto fail;
3710b18825a7SDavid Howells 
3711c663e5d8SChristoph Hellwig 	/*
3712c663e5d8SChristoph Hellwig 	 * Special case - lookup gave negative, but... we had foo/bar/
3713c663e5d8SChristoph Hellwig 	 * From the vfs_mknod() POV we just have a negative dentry -
3714c663e5d8SChristoph Hellwig 	 * all is fine. Let's be bastards - you had / on the end, you've
3715c663e5d8SChristoph Hellwig 	 * been asking for (non-existent) directory. -ENOENT for you.
3716c663e5d8SChristoph Hellwig 	 */
3717b3d4650dSNeilBrown 	if (unlikely(!create_flags)) {
3718a8104a9fSAl Viro 		error = -ENOENT;
3719ed75e95dSAl Viro 		goto fail;
3720e9baf6e5SAl Viro 	}
3721c30dabfeSJan Kara 	if (unlikely(err2)) {
3722c30dabfeSJan Kara 		error = err2;
3723a8104a9fSAl Viro 		goto fail;
3724c30dabfeSJan Kara 	}
3725e9baf6e5SAl Viro 	return dentry;
37261da177e4SLinus Torvalds fail:
3727a8104a9fSAl Viro 	dput(dentry);
3728a8104a9fSAl Viro 	dentry = ERR_PTR(error);
3729a8104a9fSAl Viro unlock:
37305955102cSAl Viro 	inode_unlock(path->dentry->d_inode);
3731c30dabfeSJan Kara 	if (!err2)
3732391172c4SAl Viro 		mnt_drop_write(path->mnt);
3733ed75e95dSAl Viro out:
3734391172c4SAl Viro 	path_put(path);
3735ed75e95dSAl Viro 	return dentry;
3736dae6ad8fSAl Viro }
3737fa14a0b8SAl Viro 
3738fa14a0b8SAl Viro struct dentry *kern_path_create(int dfd, const char *pathname,
3739fa14a0b8SAl Viro 				struct path *path, unsigned int lookup_flags)
3740fa14a0b8SAl Viro {
3741b4a4f213SStephen Brennan 	struct filename *filename = getname_kernel(pathname);
3742b4a4f213SStephen Brennan 	struct dentry *res = filename_create(dfd, filename, path, lookup_flags);
3743b4a4f213SStephen Brennan 
3744b4a4f213SStephen Brennan 	putname(filename);
3745b4a4f213SStephen Brennan 	return res;
3746fa14a0b8SAl Viro }
3747dae6ad8fSAl Viro EXPORT_SYMBOL(kern_path_create);
3748dae6ad8fSAl Viro 
3749921a1650SAl Viro void done_path_create(struct path *path, struct dentry *dentry)
3750921a1650SAl Viro {
3751921a1650SAl Viro 	dput(dentry);
37525955102cSAl Viro 	inode_unlock(path->dentry->d_inode);
3753a8104a9fSAl Viro 	mnt_drop_write(path->mnt);
3754921a1650SAl Viro 	path_put(path);
3755921a1650SAl Viro }
3756921a1650SAl Viro EXPORT_SYMBOL(done_path_create);
3757921a1650SAl Viro 
3758520ae687SAl Viro inline struct dentry *user_path_create(int dfd, const char __user *pathname,
37591ac12b4bSJeff Layton 				struct path *path, unsigned int lookup_flags)
3760dae6ad8fSAl Viro {
3761b4a4f213SStephen Brennan 	struct filename *filename = getname(pathname);
3762b4a4f213SStephen Brennan 	struct dentry *res = filename_create(dfd, filename, path, lookup_flags);
3763b4a4f213SStephen Brennan 
3764b4a4f213SStephen Brennan 	putname(filename);
3765b4a4f213SStephen Brennan 	return res;
3766dae6ad8fSAl Viro }
3767dae6ad8fSAl Viro EXPORT_SYMBOL(user_path_create);
3768dae6ad8fSAl Viro 
37696521f891SChristian Brauner /**
37706521f891SChristian Brauner  * vfs_mknod - create device node or file
37716521f891SChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
37726521f891SChristian Brauner  * @dir:	inode of @dentry
37736521f891SChristian Brauner  * @dentry:	pointer to dentry of the base directory
37746521f891SChristian Brauner  * @mode:	mode of the new device node or file
37756521f891SChristian Brauner  * @dev:	device number of device to create
37766521f891SChristian Brauner  *
37776521f891SChristian Brauner  * Create a device node or file.
37786521f891SChristian Brauner  *
37796521f891SChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
37806521f891SChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
37816521f891SChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
37826521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
37836521f891SChristian Brauner  * raw inode simply passs init_user_ns.
37846521f891SChristian Brauner  */
37856521f891SChristian Brauner int vfs_mknod(struct user_namespace *mnt_userns, struct inode *dir,
37866521f891SChristian Brauner 	      struct dentry *dentry, umode_t mode, dev_t dev)
37871da177e4SLinus Torvalds {
3788a3c751a5SMiklos Szeredi 	bool is_whiteout = S_ISCHR(mode) && dev == WHITEOUT_DEV;
37896521f891SChristian Brauner 	int error = may_create(mnt_userns, dir, dentry);
37901da177e4SLinus Torvalds 
37911da177e4SLinus Torvalds 	if (error)
37921da177e4SLinus Torvalds 		return error;
37931da177e4SLinus Torvalds 
3794a3c751a5SMiklos Szeredi 	if ((S_ISCHR(mode) || S_ISBLK(mode)) && !is_whiteout &&
3795a3c751a5SMiklos Szeredi 	    !capable(CAP_MKNOD))
37961da177e4SLinus Torvalds 		return -EPERM;
37971da177e4SLinus Torvalds 
3798acfa4380SAl Viro 	if (!dir->i_op->mknod)
37991da177e4SLinus Torvalds 		return -EPERM;
38001da177e4SLinus Torvalds 
380108ce5f16SSerge E. Hallyn 	error = devcgroup_inode_mknod(mode, dev);
380208ce5f16SSerge E. Hallyn 	if (error)
380308ce5f16SSerge E. Hallyn 		return error;
380408ce5f16SSerge E. Hallyn 
38051da177e4SLinus Torvalds 	error = security_inode_mknod(dir, dentry, mode, dev);
38061da177e4SLinus Torvalds 	if (error)
38071da177e4SLinus Torvalds 		return error;
38081da177e4SLinus Torvalds 
3809549c7297SChristian Brauner 	error = dir->i_op->mknod(mnt_userns, dir, dentry, mode, dev);
3810a74574aaSStephen Smalley 	if (!error)
3811f38aa942SAmy Griffis 		fsnotify_create(dir, dentry);
38121da177e4SLinus Torvalds 	return error;
38131da177e4SLinus Torvalds }
38144d359507SAl Viro EXPORT_SYMBOL(vfs_mknod);
38151da177e4SLinus Torvalds 
3816f69aac00SAl Viro static int may_mknod(umode_t mode)
3817463c3197SDave Hansen {
3818463c3197SDave Hansen 	switch (mode & S_IFMT) {
3819463c3197SDave Hansen 	case S_IFREG:
3820463c3197SDave Hansen 	case S_IFCHR:
3821463c3197SDave Hansen 	case S_IFBLK:
3822463c3197SDave Hansen 	case S_IFIFO:
3823463c3197SDave Hansen 	case S_IFSOCK:
3824463c3197SDave Hansen 	case 0: /* zero mode translates to S_IFREG */
3825463c3197SDave Hansen 		return 0;
3826463c3197SDave Hansen 	case S_IFDIR:
3827463c3197SDave Hansen 		return -EPERM;
3828463c3197SDave Hansen 	default:
3829463c3197SDave Hansen 		return -EINVAL;
3830463c3197SDave Hansen 	}
3831463c3197SDave Hansen }
3832463c3197SDave Hansen 
383345f30dabSDmitry Kadashev static int do_mknodat(int dfd, struct filename *name, umode_t mode,
383487c4e192SDominik Brodowski 		unsigned int dev)
38351da177e4SLinus Torvalds {
38366521f891SChristian Brauner 	struct user_namespace *mnt_userns;
38371da177e4SLinus Torvalds 	struct dentry *dentry;
3838dae6ad8fSAl Viro 	struct path path;
3839dae6ad8fSAl Viro 	int error;
3840972567f1SJeff Layton 	unsigned int lookup_flags = 0;
38411da177e4SLinus Torvalds 
38428e4bfca1SAl Viro 	error = may_mknod(mode);
38438e4bfca1SAl Viro 	if (error)
38447797251bSDmitry Kadashev 		goto out1;
3845972567f1SJeff Layton retry:
3846b4a4f213SStephen Brennan 	dentry = filename_create(dfd, name, &path, lookup_flags);
38477797251bSDmitry Kadashev 	error = PTR_ERR(dentry);
3848dae6ad8fSAl Viro 	if (IS_ERR(dentry))
38497797251bSDmitry Kadashev 		goto out1;
38502ad94ae6SAl Viro 
3851dae6ad8fSAl Viro 	if (!IS_POSIXACL(path.dentry->d_inode))
3852ce3b0f8dSAl Viro 		mode &= ~current_umask();
3853dae6ad8fSAl Viro 	error = security_path_mknod(&path, dentry, mode, dev);
3854be6d3e56SKentaro Takeda 	if (error)
38557797251bSDmitry Kadashev 		goto out2;
38566521f891SChristian Brauner 
38576521f891SChristian Brauner 	mnt_userns = mnt_user_ns(path.mnt);
38581da177e4SLinus Torvalds 	switch (mode & S_IFMT) {
38591da177e4SLinus Torvalds 		case 0: case S_IFREG:
38606521f891SChristian Brauner 			error = vfs_create(mnt_userns, path.dentry->d_inode,
38616521f891SChristian Brauner 					   dentry, mode, true);
386205d1a717SMimi Zohar 			if (!error)
3863a2d2329eSChristian Brauner 				ima_post_path_mknod(mnt_userns, dentry);
38641da177e4SLinus Torvalds 			break;
38651da177e4SLinus Torvalds 		case S_IFCHR: case S_IFBLK:
38666521f891SChristian Brauner 			error = vfs_mknod(mnt_userns, path.dentry->d_inode,
38676521f891SChristian Brauner 					  dentry, mode, new_decode_dev(dev));
38681da177e4SLinus Torvalds 			break;
38691da177e4SLinus Torvalds 		case S_IFIFO: case S_IFSOCK:
38706521f891SChristian Brauner 			error = vfs_mknod(mnt_userns, path.dentry->d_inode,
38716521f891SChristian Brauner 					  dentry, mode, 0);
38721da177e4SLinus Torvalds 			break;
38731da177e4SLinus Torvalds 	}
38747797251bSDmitry Kadashev out2:
3875921a1650SAl Viro 	done_path_create(&path, dentry);
3876972567f1SJeff Layton 	if (retry_estale(error, lookup_flags)) {
3877972567f1SJeff Layton 		lookup_flags |= LOOKUP_REVAL;
3878972567f1SJeff Layton 		goto retry;
3879972567f1SJeff Layton 	}
38807797251bSDmitry Kadashev out1:
38817797251bSDmitry Kadashev 	putname(name);
38821da177e4SLinus Torvalds 	return error;
38831da177e4SLinus Torvalds }
38841da177e4SLinus Torvalds 
388587c4e192SDominik Brodowski SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, umode_t, mode,
388687c4e192SDominik Brodowski 		unsigned int, dev)
388787c4e192SDominik Brodowski {
38887797251bSDmitry Kadashev 	return do_mknodat(dfd, getname(filename), mode, dev);
388987c4e192SDominik Brodowski }
389087c4e192SDominik Brodowski 
38918208a22bSAl Viro SYSCALL_DEFINE3(mknod, const char __user *, filename, umode_t, mode, unsigned, dev)
38925590ff0dSUlrich Drepper {
38937797251bSDmitry Kadashev 	return do_mknodat(AT_FDCWD, getname(filename), mode, dev);
38945590ff0dSUlrich Drepper }
38955590ff0dSUlrich Drepper 
38966521f891SChristian Brauner /**
38976521f891SChristian Brauner  * vfs_mkdir - create directory
38986521f891SChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
38996521f891SChristian Brauner  * @dir:	inode of @dentry
39006521f891SChristian Brauner  * @dentry:	pointer to dentry of the base directory
39016521f891SChristian Brauner  * @mode:	mode of the new directory
39026521f891SChristian Brauner  *
39036521f891SChristian Brauner  * Create a directory.
39046521f891SChristian Brauner  *
39056521f891SChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
39066521f891SChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
39076521f891SChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
39086521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
39096521f891SChristian Brauner  * raw inode simply passs init_user_ns.
39106521f891SChristian Brauner  */
39116521f891SChristian Brauner int vfs_mkdir(struct user_namespace *mnt_userns, struct inode *dir,
39126521f891SChristian Brauner 	      struct dentry *dentry, umode_t mode)
39131da177e4SLinus Torvalds {
39146521f891SChristian Brauner 	int error = may_create(mnt_userns, dir, dentry);
39158de52778SAl Viro 	unsigned max_links = dir->i_sb->s_max_links;
39161da177e4SLinus Torvalds 
39171da177e4SLinus Torvalds 	if (error)
39181da177e4SLinus Torvalds 		return error;
39191da177e4SLinus Torvalds 
3920acfa4380SAl Viro 	if (!dir->i_op->mkdir)
39211da177e4SLinus Torvalds 		return -EPERM;
39221da177e4SLinus Torvalds 
39231da177e4SLinus Torvalds 	mode &= (S_IRWXUGO|S_ISVTX);
39241da177e4SLinus Torvalds 	error = security_inode_mkdir(dir, dentry, mode);
39251da177e4SLinus Torvalds 	if (error)
39261da177e4SLinus Torvalds 		return error;
39271da177e4SLinus Torvalds 
39288de52778SAl Viro 	if (max_links && dir->i_nlink >= max_links)
39298de52778SAl Viro 		return -EMLINK;
39308de52778SAl Viro 
3931549c7297SChristian Brauner 	error = dir->i_op->mkdir(mnt_userns, dir, dentry, mode);
3932a74574aaSStephen Smalley 	if (!error)
3933f38aa942SAmy Griffis 		fsnotify_mkdir(dir, dentry);
39341da177e4SLinus Torvalds 	return error;
39351da177e4SLinus Torvalds }
39364d359507SAl Viro EXPORT_SYMBOL(vfs_mkdir);
39371da177e4SLinus Torvalds 
393845f30dabSDmitry Kadashev int do_mkdirat(int dfd, struct filename *name, umode_t mode)
39391da177e4SLinus Torvalds {
39406902d925SDave Hansen 	struct dentry *dentry;
3941dae6ad8fSAl Viro 	struct path path;
3942dae6ad8fSAl Viro 	int error;
3943b76d8b82SJeff Layton 	unsigned int lookup_flags = LOOKUP_DIRECTORY;
39441da177e4SLinus Torvalds 
3945b76d8b82SJeff Layton retry:
3946b4a4f213SStephen Brennan 	dentry = filename_create(dfd, name, &path, lookup_flags);
3947584d3226SDmitry Kadashev 	error = PTR_ERR(dentry);
39486902d925SDave Hansen 	if (IS_ERR(dentry))
3949584d3226SDmitry Kadashev 		goto out_putname;
39506902d925SDave Hansen 
3951dae6ad8fSAl Viro 	if (!IS_POSIXACL(path.dentry->d_inode))
3952ce3b0f8dSAl Viro 		mode &= ~current_umask();
3953dae6ad8fSAl Viro 	error = security_path_mkdir(&path, dentry, mode);
39546521f891SChristian Brauner 	if (!error) {
39556521f891SChristian Brauner 		struct user_namespace *mnt_userns;
39566521f891SChristian Brauner 		mnt_userns = mnt_user_ns(path.mnt);
3957549c7297SChristian Brauner 		error = vfs_mkdir(mnt_userns, path.dentry->d_inode, dentry,
3958549c7297SChristian Brauner 				  mode);
39596521f891SChristian Brauner 	}
3960921a1650SAl Viro 	done_path_create(&path, dentry);
3961b76d8b82SJeff Layton 	if (retry_estale(error, lookup_flags)) {
3962b76d8b82SJeff Layton 		lookup_flags |= LOOKUP_REVAL;
3963b76d8b82SJeff Layton 		goto retry;
3964b76d8b82SJeff Layton 	}
3965584d3226SDmitry Kadashev out_putname:
3966584d3226SDmitry Kadashev 	putname(name);
39671da177e4SLinus Torvalds 	return error;
39681da177e4SLinus Torvalds }
39691da177e4SLinus Torvalds 
39700101db7aSDominik Brodowski SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, umode_t, mode)
39710101db7aSDominik Brodowski {
3972584d3226SDmitry Kadashev 	return do_mkdirat(dfd, getname(pathname), mode);
39730101db7aSDominik Brodowski }
39740101db7aSDominik Brodowski 
3975a218d0fdSAl Viro SYSCALL_DEFINE2(mkdir, const char __user *, pathname, umode_t, mode)
39765590ff0dSUlrich Drepper {
3977584d3226SDmitry Kadashev 	return do_mkdirat(AT_FDCWD, getname(pathname), mode);
39785590ff0dSUlrich Drepper }
39795590ff0dSUlrich Drepper 
39806521f891SChristian Brauner /**
39816521f891SChristian Brauner  * vfs_rmdir - remove directory
39826521f891SChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
39836521f891SChristian Brauner  * @dir:	inode of @dentry
39846521f891SChristian Brauner  * @dentry:	pointer to dentry of the base directory
39856521f891SChristian Brauner  *
39866521f891SChristian Brauner  * Remove a directory.
39876521f891SChristian Brauner  *
39886521f891SChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
39896521f891SChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
39906521f891SChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
39916521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
39926521f891SChristian Brauner  * raw inode simply passs init_user_ns.
39936521f891SChristian Brauner  */
39946521f891SChristian Brauner int vfs_rmdir(struct user_namespace *mnt_userns, struct inode *dir,
39956521f891SChristian Brauner 		     struct dentry *dentry)
39961da177e4SLinus Torvalds {
39976521f891SChristian Brauner 	int error = may_delete(mnt_userns, dir, dentry, 1);
39981da177e4SLinus Torvalds 
39991da177e4SLinus Torvalds 	if (error)
40001da177e4SLinus Torvalds 		return error;
40011da177e4SLinus Torvalds 
4002acfa4380SAl Viro 	if (!dir->i_op->rmdir)
40031da177e4SLinus Torvalds 		return -EPERM;
40041da177e4SLinus Torvalds 
40051d2ef590SAl Viro 	dget(dentry);
40065955102cSAl Viro 	inode_lock(dentry->d_inode);
4007912dbc15SSage Weil 
40081da177e4SLinus Torvalds 	error = -EBUSY;
40091bd9c4e4SDavid Howells 	if (is_local_mountpoint(dentry) ||
40101bd9c4e4SDavid Howells 	    (dentry->d_inode->i_flags & S_KERNEL_FILE))
4011912dbc15SSage Weil 		goto out;
4012912dbc15SSage Weil 
40131da177e4SLinus Torvalds 	error = security_inode_rmdir(dir, dentry);
4014912dbc15SSage Weil 	if (error)
4015912dbc15SSage Weil 		goto out;
4016912dbc15SSage Weil 
40171da177e4SLinus Torvalds 	error = dir->i_op->rmdir(dir, dentry);
4018912dbc15SSage Weil 	if (error)
4019912dbc15SSage Weil 		goto out;
4020912dbc15SSage Weil 
40218767712fSAl Viro 	shrink_dcache_parent(dentry);
40221da177e4SLinus Torvalds 	dentry->d_inode->i_flags |= S_DEAD;
4023d83c49f3SAl Viro 	dont_mount(dentry);
40248ed936b5SEric W. Biederman 	detach_mounts(dentry);
40251da177e4SLinus Torvalds 
4026912dbc15SSage Weil out:
40275955102cSAl Viro 	inode_unlock(dentry->d_inode);
40281d2ef590SAl Viro 	dput(dentry);
4029912dbc15SSage Weil 	if (!error)
4030a37d9a17SAmir Goldstein 		d_delete_notify(dir, dentry);
40311da177e4SLinus Torvalds 	return error;
40321da177e4SLinus Torvalds }
40334d359507SAl Viro EXPORT_SYMBOL(vfs_rmdir);
40341da177e4SLinus Torvalds 
403545f30dabSDmitry Kadashev int do_rmdir(int dfd, struct filename *name)
40361da177e4SLinus Torvalds {
40376521f891SChristian Brauner 	struct user_namespace *mnt_userns;
40380ee50b47SDmitry Kadashev 	int error;
40391da177e4SLinus Torvalds 	struct dentry *dentry;
4040f5beed75SAl Viro 	struct path path;
4041f5beed75SAl Viro 	struct qstr last;
4042f5beed75SAl Viro 	int type;
4043c6ee9206SJeff Layton 	unsigned int lookup_flags = 0;
4044c6ee9206SJeff Layton retry:
4045c5f563f9SAl Viro 	error = filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
40460ee50b47SDmitry Kadashev 	if (error)
40470ee50b47SDmitry Kadashev 		goto exit1;
40481da177e4SLinus Torvalds 
4049f5beed75SAl Viro 	switch (type) {
40501da177e4SLinus Torvalds 	case LAST_DOTDOT:
40511da177e4SLinus Torvalds 		error = -ENOTEMPTY;
40520ee50b47SDmitry Kadashev 		goto exit2;
40531da177e4SLinus Torvalds 	case LAST_DOT:
40541da177e4SLinus Torvalds 		error = -EINVAL;
40550ee50b47SDmitry Kadashev 		goto exit2;
40561da177e4SLinus Torvalds 	case LAST_ROOT:
40571da177e4SLinus Torvalds 		error = -EBUSY;
40580ee50b47SDmitry Kadashev 		goto exit2;
40591da177e4SLinus Torvalds 	}
40600612d9fbSOGAWA Hirofumi 
4061f5beed75SAl Viro 	error = mnt_want_write(path.mnt);
4062c30dabfeSJan Kara 	if (error)
40630ee50b47SDmitry Kadashev 		goto exit2;
40640612d9fbSOGAWA Hirofumi 
40655955102cSAl Viro 	inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
4066f5beed75SAl Viro 	dentry = __lookup_hash(&last, path.dentry, lookup_flags);
40671da177e4SLinus Torvalds 	error = PTR_ERR(dentry);
40686902d925SDave Hansen 	if (IS_ERR(dentry))
40690ee50b47SDmitry Kadashev 		goto exit3;
4070e6bc45d6STheodore Ts'o 	if (!dentry->d_inode) {
4071e6bc45d6STheodore Ts'o 		error = -ENOENT;
40720ee50b47SDmitry Kadashev 		goto exit4;
4073e6bc45d6STheodore Ts'o 	}
4074f5beed75SAl Viro 	error = security_path_rmdir(&path, dentry);
4075be6d3e56SKentaro Takeda 	if (error)
40760ee50b47SDmitry Kadashev 		goto exit4;
40776521f891SChristian Brauner 	mnt_userns = mnt_user_ns(path.mnt);
40786521f891SChristian Brauner 	error = vfs_rmdir(mnt_userns, path.dentry->d_inode, dentry);
40790ee50b47SDmitry Kadashev exit4:
40801da177e4SLinus Torvalds 	dput(dentry);
40810ee50b47SDmitry Kadashev exit3:
40825955102cSAl Viro 	inode_unlock(path.dentry->d_inode);
4083f5beed75SAl Viro 	mnt_drop_write(path.mnt);
40840ee50b47SDmitry Kadashev exit2:
4085f5beed75SAl Viro 	path_put(&path);
4086c6ee9206SJeff Layton 	if (retry_estale(error, lookup_flags)) {
4087c6ee9206SJeff Layton 		lookup_flags |= LOOKUP_REVAL;
4088c6ee9206SJeff Layton 		goto retry;
4089c6ee9206SJeff Layton 	}
40900ee50b47SDmitry Kadashev exit1:
409124fb33d4SAl Viro 	putname(name);
40921da177e4SLinus Torvalds 	return error;
40931da177e4SLinus Torvalds }
40941da177e4SLinus Torvalds 
40953cdad428SHeiko Carstens SYSCALL_DEFINE1(rmdir, const char __user *, pathname)
40965590ff0dSUlrich Drepper {
4097e24ab0efSChristoph Hellwig 	return do_rmdir(AT_FDCWD, getname(pathname));
40985590ff0dSUlrich Drepper }
40995590ff0dSUlrich Drepper 
4100b21996e3SJ. Bruce Fields /**
4101b21996e3SJ. Bruce Fields  * vfs_unlink - unlink a filesystem object
41026521f891SChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
4103b21996e3SJ. Bruce Fields  * @dir:	parent directory
4104b21996e3SJ. Bruce Fields  * @dentry:	victim
4105b21996e3SJ. Bruce Fields  * @delegated_inode: returns victim inode, if the inode is delegated.
4106b21996e3SJ. Bruce Fields  *
4107b21996e3SJ. Bruce Fields  * The caller must hold dir->i_mutex.
4108b21996e3SJ. Bruce Fields  *
4109b21996e3SJ. Bruce Fields  * If vfs_unlink discovers a delegation, it will return -EWOULDBLOCK and
4110b21996e3SJ. Bruce Fields  * return a reference to the inode in delegated_inode.  The caller
4111b21996e3SJ. Bruce Fields  * should then break the delegation on that inode and retry.  Because
4112b21996e3SJ. Bruce Fields  * breaking a delegation may take a long time, the caller should drop
4113b21996e3SJ. Bruce Fields  * dir->i_mutex before doing so.
4114b21996e3SJ. Bruce Fields  *
4115b21996e3SJ. Bruce Fields  * Alternatively, a caller may pass NULL for delegated_inode.  This may
4116b21996e3SJ. Bruce Fields  * be appropriate for callers that expect the underlying filesystem not
4117b21996e3SJ. Bruce Fields  * to be NFS exported.
41186521f891SChristian Brauner  *
41196521f891SChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
41206521f891SChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
41216521f891SChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
41226521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
41236521f891SChristian Brauner  * raw inode simply passs init_user_ns.
4124b21996e3SJ. Bruce Fields  */
41256521f891SChristian Brauner int vfs_unlink(struct user_namespace *mnt_userns, struct inode *dir,
41266521f891SChristian Brauner 	       struct dentry *dentry, struct inode **delegated_inode)
41271da177e4SLinus Torvalds {
41289accbb97SJ. Bruce Fields 	struct inode *target = dentry->d_inode;
41296521f891SChristian Brauner 	int error = may_delete(mnt_userns, dir, dentry, 0);
41301da177e4SLinus Torvalds 
41311da177e4SLinus Torvalds 	if (error)
41321da177e4SLinus Torvalds 		return error;
41331da177e4SLinus Torvalds 
4134acfa4380SAl Viro 	if (!dir->i_op->unlink)
41351da177e4SLinus Torvalds 		return -EPERM;
41361da177e4SLinus Torvalds 
41375955102cSAl Viro 	inode_lock(target);
413851cc3a66SHugh Dickins 	if (IS_SWAPFILE(target))
413951cc3a66SHugh Dickins 		error = -EPERM;
414051cc3a66SHugh Dickins 	else if (is_local_mountpoint(dentry))
41411da177e4SLinus Torvalds 		error = -EBUSY;
41421da177e4SLinus Torvalds 	else {
41431da177e4SLinus Torvalds 		error = security_inode_unlink(dir, dentry);
4144bec1052eSAl Viro 		if (!error) {
41455a14696cSJ. Bruce Fields 			error = try_break_deleg(target, delegated_inode);
41465a14696cSJ. Bruce Fields 			if (error)
4147b21996e3SJ. Bruce Fields 				goto out;
41481da177e4SLinus Torvalds 			error = dir->i_op->unlink(dir, dentry);
41498ed936b5SEric W. Biederman 			if (!error) {
4150d83c49f3SAl Viro 				dont_mount(dentry);
41518ed936b5SEric W. Biederman 				detach_mounts(dentry);
41528ed936b5SEric W. Biederman 			}
4153bec1052eSAl Viro 		}
41541da177e4SLinus Torvalds 	}
4155b21996e3SJ. Bruce Fields out:
41565955102cSAl Viro 	inode_unlock(target);
41571da177e4SLinus Torvalds 
41581da177e4SLinus Torvalds 	/* We don't d_delete() NFS sillyrenamed files--they still exist. */
4159a37d9a17SAmir Goldstein 	if (!error && dentry->d_flags & DCACHE_NFSFS_RENAMED) {
4160a37d9a17SAmir Goldstein 		fsnotify_unlink(dir, dentry);
4161a37d9a17SAmir Goldstein 	} else if (!error) {
41629accbb97SJ. Bruce Fields 		fsnotify_link_count(target);
4163a37d9a17SAmir Goldstein 		d_delete_notify(dir, dentry);
41641da177e4SLinus Torvalds 	}
41650eeca283SRobert Love 
41661da177e4SLinus Torvalds 	return error;
41671da177e4SLinus Torvalds }
41684d359507SAl Viro EXPORT_SYMBOL(vfs_unlink);
41691da177e4SLinus Torvalds 
41701da177e4SLinus Torvalds /*
41711da177e4SLinus Torvalds  * Make sure that the actual truncation of the file will occur outside its
41721b1dcc1bSJes Sorensen  * directory's i_mutex.  Truncate can take a long time if there is a lot of
41731da177e4SLinus Torvalds  * writeout happening, and we don't want to prevent access to the directory
41741da177e4SLinus Torvalds  * while waiting on the I/O.
41751da177e4SLinus Torvalds  */
417645f30dabSDmitry Kadashev int do_unlinkat(int dfd, struct filename *name)
41771da177e4SLinus Torvalds {
41782ad94ae6SAl Viro 	int error;
41791da177e4SLinus Torvalds 	struct dentry *dentry;
4180f5beed75SAl Viro 	struct path path;
4181f5beed75SAl Viro 	struct qstr last;
4182f5beed75SAl Viro 	int type;
41831da177e4SLinus Torvalds 	struct inode *inode = NULL;
4184b21996e3SJ. Bruce Fields 	struct inode *delegated_inode = NULL;
41855d18f813SJeff Layton 	unsigned int lookup_flags = 0;
41865d18f813SJeff Layton retry:
4187c5f563f9SAl Viro 	error = filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
41880ee50b47SDmitry Kadashev 	if (error)
41890ee50b47SDmitry Kadashev 		goto exit1;
41902ad94ae6SAl Viro 
41911da177e4SLinus Torvalds 	error = -EISDIR;
4192f5beed75SAl Viro 	if (type != LAST_NORM)
41930ee50b47SDmitry Kadashev 		goto exit2;
41940612d9fbSOGAWA Hirofumi 
4195f5beed75SAl Viro 	error = mnt_want_write(path.mnt);
4196c30dabfeSJan Kara 	if (error)
41970ee50b47SDmitry Kadashev 		goto exit2;
4198b21996e3SJ. Bruce Fields retry_deleg:
41995955102cSAl Viro 	inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
4200f5beed75SAl Viro 	dentry = __lookup_hash(&last, path.dentry, lookup_flags);
42011da177e4SLinus Torvalds 	error = PTR_ERR(dentry);
42021da177e4SLinus Torvalds 	if (!IS_ERR(dentry)) {
42036521f891SChristian Brauner 		struct user_namespace *mnt_userns;
42046521f891SChristian Brauner 
42051da177e4SLinus Torvalds 		/* Why not before? Because we want correct error value */
4206f5beed75SAl Viro 		if (last.name[last.len])
420750338b88STörök Edwin 			goto slashes;
42081da177e4SLinus Torvalds 		inode = dentry->d_inode;
4209b18825a7SDavid Howells 		if (d_is_negative(dentry))
4210e6bc45d6STheodore Ts'o 			goto slashes;
42117de9c6eeSAl Viro 		ihold(inode);
4212f5beed75SAl Viro 		error = security_path_unlink(&path, dentry);
4213be6d3e56SKentaro Takeda 		if (error)
42140ee50b47SDmitry Kadashev 			goto exit3;
42156521f891SChristian Brauner 		mnt_userns = mnt_user_ns(path.mnt);
4216549c7297SChristian Brauner 		error = vfs_unlink(mnt_userns, path.dentry->d_inode, dentry,
4217549c7297SChristian Brauner 				   &delegated_inode);
42180ee50b47SDmitry Kadashev exit3:
42191da177e4SLinus Torvalds 		dput(dentry);
42201da177e4SLinus Torvalds 	}
42215955102cSAl Viro 	inode_unlock(path.dentry->d_inode);
42221da177e4SLinus Torvalds 	if (inode)
42231da177e4SLinus Torvalds 		iput(inode);	/* truncate the inode here */
4224b21996e3SJ. Bruce Fields 	inode = NULL;
4225b21996e3SJ. Bruce Fields 	if (delegated_inode) {
42265a14696cSJ. Bruce Fields 		error = break_deleg_wait(&delegated_inode);
4227b21996e3SJ. Bruce Fields 		if (!error)
4228b21996e3SJ. Bruce Fields 			goto retry_deleg;
4229b21996e3SJ. Bruce Fields 	}
4230f5beed75SAl Viro 	mnt_drop_write(path.mnt);
42310ee50b47SDmitry Kadashev exit2:
4232f5beed75SAl Viro 	path_put(&path);
42335d18f813SJeff Layton 	if (retry_estale(error, lookup_flags)) {
42345d18f813SJeff Layton 		lookup_flags |= LOOKUP_REVAL;
42355d18f813SJeff Layton 		inode = NULL;
42365d18f813SJeff Layton 		goto retry;
42375d18f813SJeff Layton 	}
42380ee50b47SDmitry Kadashev exit1:
4239da2f1362SChristoph Hellwig 	putname(name);
42401da177e4SLinus Torvalds 	return error;
42411da177e4SLinus Torvalds 
42421da177e4SLinus Torvalds slashes:
4243b18825a7SDavid Howells 	if (d_is_negative(dentry))
4244b18825a7SDavid Howells 		error = -ENOENT;
424544b1d530SMiklos Szeredi 	else if (d_is_dir(dentry))
4246b18825a7SDavid Howells 		error = -EISDIR;
4247b18825a7SDavid Howells 	else
4248b18825a7SDavid Howells 		error = -ENOTDIR;
42490ee50b47SDmitry Kadashev 	goto exit3;
42501da177e4SLinus Torvalds }
42511da177e4SLinus Torvalds 
42522e4d0924SHeiko Carstens SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag)
42535590ff0dSUlrich Drepper {
42545590ff0dSUlrich Drepper 	if ((flag & ~AT_REMOVEDIR) != 0)
42555590ff0dSUlrich Drepper 		return -EINVAL;
42565590ff0dSUlrich Drepper 
42575590ff0dSUlrich Drepper 	if (flag & AT_REMOVEDIR)
4258e24ab0efSChristoph Hellwig 		return do_rmdir(dfd, getname(pathname));
4259da2f1362SChristoph Hellwig 	return do_unlinkat(dfd, getname(pathname));
42605590ff0dSUlrich Drepper }
42615590ff0dSUlrich Drepper 
42623480b257SHeiko Carstens SYSCALL_DEFINE1(unlink, const char __user *, pathname)
42635590ff0dSUlrich Drepper {
4264da2f1362SChristoph Hellwig 	return do_unlinkat(AT_FDCWD, getname(pathname));
42655590ff0dSUlrich Drepper }
42665590ff0dSUlrich Drepper 
42676521f891SChristian Brauner /**
42686521f891SChristian Brauner  * vfs_symlink - create symlink
42696521f891SChristian Brauner  * @mnt_userns:	user namespace of the mount the inode was found from
42706521f891SChristian Brauner  * @dir:	inode of @dentry
42716521f891SChristian Brauner  * @dentry:	pointer to dentry of the base directory
42726521f891SChristian Brauner  * @oldname:	name of the file to link to
42736521f891SChristian Brauner  *
42746521f891SChristian Brauner  * Create a symlink.
42756521f891SChristian Brauner  *
42766521f891SChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
42776521f891SChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
42786521f891SChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
42796521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
42806521f891SChristian Brauner  * raw inode simply passs init_user_ns.
42816521f891SChristian Brauner  */
42826521f891SChristian Brauner int vfs_symlink(struct user_namespace *mnt_userns, struct inode *dir,
42836521f891SChristian Brauner 		struct dentry *dentry, const char *oldname)
42841da177e4SLinus Torvalds {
42856521f891SChristian Brauner 	int error = may_create(mnt_userns, dir, dentry);
42861da177e4SLinus Torvalds 
42871da177e4SLinus Torvalds 	if (error)
42881da177e4SLinus Torvalds 		return error;
42891da177e4SLinus Torvalds 
4290acfa4380SAl Viro 	if (!dir->i_op->symlink)
42911da177e4SLinus Torvalds 		return -EPERM;
42921da177e4SLinus Torvalds 
42931da177e4SLinus Torvalds 	error = security_inode_symlink(dir, dentry, oldname);
42941da177e4SLinus Torvalds 	if (error)
42951da177e4SLinus Torvalds 		return error;
42961da177e4SLinus Torvalds 
4297549c7297SChristian Brauner 	error = dir->i_op->symlink(mnt_userns, dir, dentry, oldname);
4298a74574aaSStephen Smalley 	if (!error)
4299f38aa942SAmy Griffis 		fsnotify_create(dir, dentry);
43001da177e4SLinus Torvalds 	return error;
43011da177e4SLinus Torvalds }
43024d359507SAl Viro EXPORT_SYMBOL(vfs_symlink);
43031da177e4SLinus Torvalds 
43047a8721f8SDmitry Kadashev int do_symlinkat(struct filename *from, int newdfd, struct filename *to)
43051da177e4SLinus Torvalds {
43062ad94ae6SAl Viro 	int error;
43076902d925SDave Hansen 	struct dentry *dentry;
4308dae6ad8fSAl Viro 	struct path path;
4309f46d3567SJeff Layton 	unsigned int lookup_flags = 0;
43101da177e4SLinus Torvalds 
4311da2d0cedSDmitry Kadashev 	if (IS_ERR(from)) {
4312da2d0cedSDmitry Kadashev 		error = PTR_ERR(from);
4313da2d0cedSDmitry Kadashev 		goto out_putnames;
4314da2d0cedSDmitry Kadashev 	}
4315f46d3567SJeff Layton retry:
4316b4a4f213SStephen Brennan 	dentry = filename_create(newdfd, to, &path, lookup_flags);
43171da177e4SLinus Torvalds 	error = PTR_ERR(dentry);
43186902d925SDave Hansen 	if (IS_ERR(dentry))
4319da2d0cedSDmitry Kadashev 		goto out_putnames;
43206902d925SDave Hansen 
432191a27b2aSJeff Layton 	error = security_path_symlink(&path, dentry, from->name);
43226521f891SChristian Brauner 	if (!error) {
43236521f891SChristian Brauner 		struct user_namespace *mnt_userns;
43246521f891SChristian Brauner 
43256521f891SChristian Brauner 		mnt_userns = mnt_user_ns(path.mnt);
43266521f891SChristian Brauner 		error = vfs_symlink(mnt_userns, path.dentry->d_inode, dentry,
43276521f891SChristian Brauner 				    from->name);
43286521f891SChristian Brauner 	}
4329921a1650SAl Viro 	done_path_create(&path, dentry);
4330f46d3567SJeff Layton 	if (retry_estale(error, lookup_flags)) {
4331f46d3567SJeff Layton 		lookup_flags |= LOOKUP_REVAL;
4332f46d3567SJeff Layton 		goto retry;
4333f46d3567SJeff Layton 	}
4334da2d0cedSDmitry Kadashev out_putnames:
4335da2d0cedSDmitry Kadashev 	putname(to);
43361da177e4SLinus Torvalds 	putname(from);
43371da177e4SLinus Torvalds 	return error;
43381da177e4SLinus Torvalds }
43391da177e4SLinus Torvalds 
4340b724e846SDominik Brodowski SYSCALL_DEFINE3(symlinkat, const char __user *, oldname,
4341b724e846SDominik Brodowski 		int, newdfd, const char __user *, newname)
4342b724e846SDominik Brodowski {
4343da2d0cedSDmitry Kadashev 	return do_symlinkat(getname(oldname), newdfd, getname(newname));
4344b724e846SDominik Brodowski }
4345b724e846SDominik Brodowski 
43463480b257SHeiko Carstens SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname)
43475590ff0dSUlrich Drepper {
4348da2d0cedSDmitry Kadashev 	return do_symlinkat(getname(oldname), AT_FDCWD, getname(newname));
43495590ff0dSUlrich Drepper }
43505590ff0dSUlrich Drepper 
4351146a8595SJ. Bruce Fields /**
4352146a8595SJ. Bruce Fields  * vfs_link - create a new link
4353146a8595SJ. Bruce Fields  * @old_dentry:	object to be linked
43546521f891SChristian Brauner  * @mnt_userns:	the user namespace of the mount
4355146a8595SJ. Bruce Fields  * @dir:	new parent
4356146a8595SJ. Bruce Fields  * @new_dentry:	where to create the new link
4357146a8595SJ. Bruce Fields  * @delegated_inode: returns inode needing a delegation break
4358146a8595SJ. Bruce Fields  *
4359146a8595SJ. Bruce Fields  * The caller must hold dir->i_mutex
4360146a8595SJ. Bruce Fields  *
4361146a8595SJ. Bruce Fields  * If vfs_link discovers a delegation on the to-be-linked file in need
4362146a8595SJ. Bruce Fields  * of breaking, it will return -EWOULDBLOCK and return a reference to the
4363146a8595SJ. Bruce Fields  * inode in delegated_inode.  The caller should then break the delegation
4364146a8595SJ. Bruce Fields  * and retry.  Because breaking a delegation may take a long time, the
4365146a8595SJ. Bruce Fields  * caller should drop the i_mutex before doing so.
4366146a8595SJ. Bruce Fields  *
4367146a8595SJ. Bruce Fields  * Alternatively, a caller may pass NULL for delegated_inode.  This may
4368146a8595SJ. Bruce Fields  * be appropriate for callers that expect the underlying filesystem not
4369146a8595SJ. Bruce Fields  * to be NFS exported.
43706521f891SChristian Brauner  *
43716521f891SChristian Brauner  * If the inode has been found through an idmapped mount the user namespace of
43726521f891SChristian Brauner  * the vfsmount must be passed through @mnt_userns. This function will then take
43736521f891SChristian Brauner  * care to map the inode according to @mnt_userns before checking permissions.
43746521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
43756521f891SChristian Brauner  * raw inode simply passs init_user_ns.
4376146a8595SJ. Bruce Fields  */
43776521f891SChristian Brauner int vfs_link(struct dentry *old_dentry, struct user_namespace *mnt_userns,
43786521f891SChristian Brauner 	     struct inode *dir, struct dentry *new_dentry,
43796521f891SChristian Brauner 	     struct inode **delegated_inode)
43801da177e4SLinus Torvalds {
43811da177e4SLinus Torvalds 	struct inode *inode = old_dentry->d_inode;
43828de52778SAl Viro 	unsigned max_links = dir->i_sb->s_max_links;
43831da177e4SLinus Torvalds 	int error;
43841da177e4SLinus Torvalds 
43851da177e4SLinus Torvalds 	if (!inode)
43861da177e4SLinus Torvalds 		return -ENOENT;
43871da177e4SLinus Torvalds 
43886521f891SChristian Brauner 	error = may_create(mnt_userns, dir, new_dentry);
43891da177e4SLinus Torvalds 	if (error)
43901da177e4SLinus Torvalds 		return error;
43911da177e4SLinus Torvalds 
43921da177e4SLinus Torvalds 	if (dir->i_sb != inode->i_sb)
43931da177e4SLinus Torvalds 		return -EXDEV;
43941da177e4SLinus Torvalds 
43951da177e4SLinus Torvalds 	/*
43961da177e4SLinus Torvalds 	 * A link to an append-only or immutable file cannot be created.
43971da177e4SLinus Torvalds 	 */
43981da177e4SLinus Torvalds 	if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
43991da177e4SLinus Torvalds 		return -EPERM;
44000bd23d09SEric W. Biederman 	/*
44010bd23d09SEric W. Biederman 	 * Updating the link count will likely cause i_uid and i_gid to
44020bd23d09SEric W. Biederman 	 * be writen back improperly if their true value is unknown to
44030bd23d09SEric W. Biederman 	 * the vfs.
44040bd23d09SEric W. Biederman 	 */
44056521f891SChristian Brauner 	if (HAS_UNMAPPED_ID(mnt_userns, inode))
44060bd23d09SEric W. Biederman 		return -EPERM;
4407acfa4380SAl Viro 	if (!dir->i_op->link)
44081da177e4SLinus Torvalds 		return -EPERM;
44097e79eedbSTetsuo Handa 	if (S_ISDIR(inode->i_mode))
44101da177e4SLinus Torvalds 		return -EPERM;
44111da177e4SLinus Torvalds 
44121da177e4SLinus Torvalds 	error = security_inode_link(old_dentry, dir, new_dentry);
44131da177e4SLinus Torvalds 	if (error)
44141da177e4SLinus Torvalds 		return error;
44151da177e4SLinus Torvalds 
44165955102cSAl Viro 	inode_lock(inode);
4417aae8a97dSAneesh Kumar K.V 	/* Make sure we don't allow creating hardlink to an unlinked file */
4418f4e0c30cSAl Viro 	if (inode->i_nlink == 0 && !(inode->i_state & I_LINKABLE))
4419aae8a97dSAneesh Kumar K.V 		error =  -ENOENT;
44208de52778SAl Viro 	else if (max_links && inode->i_nlink >= max_links)
44218de52778SAl Viro 		error = -EMLINK;
4422146a8595SJ. Bruce Fields 	else {
4423146a8595SJ. Bruce Fields 		error = try_break_deleg(inode, delegated_inode);
4424146a8595SJ. Bruce Fields 		if (!error)
44251da177e4SLinus Torvalds 			error = dir->i_op->link(old_dentry, dir, new_dentry);
4426146a8595SJ. Bruce Fields 	}
4427f4e0c30cSAl Viro 
4428f4e0c30cSAl Viro 	if (!error && (inode->i_state & I_LINKABLE)) {
4429f4e0c30cSAl Viro 		spin_lock(&inode->i_lock);
4430f4e0c30cSAl Viro 		inode->i_state &= ~I_LINKABLE;
4431f4e0c30cSAl Viro 		spin_unlock(&inode->i_lock);
4432f4e0c30cSAl Viro 	}
44335955102cSAl Viro 	inode_unlock(inode);
4434e31e14ecSStephen Smalley 	if (!error)
44357e79eedbSTetsuo Handa 		fsnotify_link(dir, inode, new_dentry);
44361da177e4SLinus Torvalds 	return error;
44371da177e4SLinus Torvalds }
44384d359507SAl Viro EXPORT_SYMBOL(vfs_link);
44391da177e4SLinus Torvalds 
44401da177e4SLinus Torvalds /*
44411da177e4SLinus Torvalds  * Hardlinks are often used in delicate situations.  We avoid
44421da177e4SLinus Torvalds  * security-related surprises by not following symlinks on the
44431da177e4SLinus Torvalds  * newname.  --KAB
44441da177e4SLinus Torvalds  *
44451da177e4SLinus Torvalds  * We don't follow them on the oldname either to be compatible
44461da177e4SLinus Torvalds  * with linux 2.0, and to avoid hard-linking to directories
44471da177e4SLinus Torvalds  * and other special files.  --ADM
44481da177e4SLinus Torvalds  */
4449cf30da90SDmitry Kadashev int do_linkat(int olddfd, struct filename *old, int newdfd,
4450020250f3SDmitry Kadashev 	      struct filename *new, int flags)
44511da177e4SLinus Torvalds {
44526521f891SChristian Brauner 	struct user_namespace *mnt_userns;
44531da177e4SLinus Torvalds 	struct dentry *new_dentry;
4454dae6ad8fSAl Viro 	struct path old_path, new_path;
4455146a8595SJ. Bruce Fields 	struct inode *delegated_inode = NULL;
445611a7b371SAneesh Kumar K.V 	int how = 0;
44571da177e4SLinus Torvalds 	int error;
44581da177e4SLinus Torvalds 
4459020250f3SDmitry Kadashev 	if ((flags & ~(AT_SYMLINK_FOLLOW | AT_EMPTY_PATH)) != 0) {
4460020250f3SDmitry Kadashev 		error = -EINVAL;
4461020250f3SDmitry Kadashev 		goto out_putnames;
4462020250f3SDmitry Kadashev 	}
446311a7b371SAneesh Kumar K.V 	/*
4464f0cc6ffbSLinus Torvalds 	 * To use null names we require CAP_DAC_READ_SEARCH
4465f0cc6ffbSLinus Torvalds 	 * This ensures that not everyone will be able to create
4466f0cc6ffbSLinus Torvalds 	 * handlink using the passed filedescriptor.
446711a7b371SAneesh Kumar K.V 	 */
4468020250f3SDmitry Kadashev 	if (flags & AT_EMPTY_PATH && !capable(CAP_DAC_READ_SEARCH)) {
4469020250f3SDmitry Kadashev 		error = -ENOENT;
4470020250f3SDmitry Kadashev 		goto out_putnames;
4471f0cc6ffbSLinus Torvalds 	}
4472c04030e1SUlrich Drepper 
447311a7b371SAneesh Kumar K.V 	if (flags & AT_SYMLINK_FOLLOW)
447411a7b371SAneesh Kumar K.V 		how |= LOOKUP_FOLLOW;
4475442e31caSJeff Layton retry:
4476794ebceaSStephen Brennan 	error = filename_lookup(olddfd, old, how, &old_path, NULL);
44771da177e4SLinus Torvalds 	if (error)
4478020250f3SDmitry Kadashev 		goto out_putnames;
44792ad94ae6SAl Viro 
4480b4a4f213SStephen Brennan 	new_dentry = filename_create(newdfd, new, &new_path,
4481442e31caSJeff Layton 					(how & LOOKUP_REVAL));
44821da177e4SLinus Torvalds 	error = PTR_ERR(new_dentry);
44836902d925SDave Hansen 	if (IS_ERR(new_dentry))
4484020250f3SDmitry Kadashev 		goto out_putpath;
4485dae6ad8fSAl Viro 
4486dae6ad8fSAl Viro 	error = -EXDEV;
4487dae6ad8fSAl Viro 	if (old_path.mnt != new_path.mnt)
4488dae6ad8fSAl Viro 		goto out_dput;
4489549c7297SChristian Brauner 	mnt_userns = mnt_user_ns(new_path.mnt);
4490549c7297SChristian Brauner 	error = may_linkat(mnt_userns, &old_path);
4491800179c9SKees Cook 	if (unlikely(error))
4492800179c9SKees Cook 		goto out_dput;
4493dae6ad8fSAl Viro 	error = security_path_link(old_path.dentry, &new_path, new_dentry);
4494be6d3e56SKentaro Takeda 	if (error)
4495a8104a9fSAl Viro 		goto out_dput;
44966521f891SChristian Brauner 	error = vfs_link(old_path.dentry, mnt_userns, new_path.dentry->d_inode,
44976521f891SChristian Brauner 			 new_dentry, &delegated_inode);
449875c3f29dSDave Hansen out_dput:
4499921a1650SAl Viro 	done_path_create(&new_path, new_dentry);
4500146a8595SJ. Bruce Fields 	if (delegated_inode) {
4501146a8595SJ. Bruce Fields 		error = break_deleg_wait(&delegated_inode);
4502d22e6338SOleg Drokin 		if (!error) {
4503d22e6338SOleg Drokin 			path_put(&old_path);
4504146a8595SJ. Bruce Fields 			goto retry;
4505146a8595SJ. Bruce Fields 		}
4506d22e6338SOleg Drokin 	}
4507442e31caSJeff Layton 	if (retry_estale(error, how)) {
4508d22e6338SOleg Drokin 		path_put(&old_path);
4509442e31caSJeff Layton 		how |= LOOKUP_REVAL;
4510442e31caSJeff Layton 		goto retry;
4511442e31caSJeff Layton 	}
4512020250f3SDmitry Kadashev out_putpath:
45132d8f3038SAl Viro 	path_put(&old_path);
4514020250f3SDmitry Kadashev out_putnames:
4515020250f3SDmitry Kadashev 	putname(old);
4516020250f3SDmitry Kadashev 	putname(new);
45171da177e4SLinus Torvalds 
45181da177e4SLinus Torvalds 	return error;
45191da177e4SLinus Torvalds }
45201da177e4SLinus Torvalds 
452146ea89ebSDominik Brodowski SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname,
452246ea89ebSDominik Brodowski 		int, newdfd, const char __user *, newname, int, flags)
452346ea89ebSDominik Brodowski {
4524020250f3SDmitry Kadashev 	return do_linkat(olddfd, getname_uflags(oldname, flags),
4525020250f3SDmitry Kadashev 		newdfd, getname(newname), flags);
452646ea89ebSDominik Brodowski }
452746ea89ebSDominik Brodowski 
45283480b257SHeiko Carstens SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname)
45295590ff0dSUlrich Drepper {
4530020250f3SDmitry Kadashev 	return do_linkat(AT_FDCWD, getname(oldname), AT_FDCWD, getname(newname), 0);
45315590ff0dSUlrich Drepper }
45325590ff0dSUlrich Drepper 
4533bc27027aSMiklos Szeredi /**
4534bc27027aSMiklos Szeredi  * vfs_rename - rename a filesystem object
45352111c3c0SRandy Dunlap  * @rd:		pointer to &struct renamedata info
4536bc27027aSMiklos Szeredi  *
4537bc27027aSMiklos Szeredi  * The caller must hold multiple mutexes--see lock_rename()).
4538bc27027aSMiklos Szeredi  *
4539bc27027aSMiklos Szeredi  * If vfs_rename discovers a delegation in need of breaking at either
4540bc27027aSMiklos Szeredi  * the source or destination, it will return -EWOULDBLOCK and return a
4541bc27027aSMiklos Szeredi  * reference to the inode in delegated_inode.  The caller should then
4542bc27027aSMiklos Szeredi  * break the delegation and retry.  Because breaking a delegation may
4543bc27027aSMiklos Szeredi  * take a long time, the caller should drop all locks before doing
4544bc27027aSMiklos Szeredi  * so.
4545bc27027aSMiklos Szeredi  *
4546bc27027aSMiklos Szeredi  * Alternatively, a caller may pass NULL for delegated_inode.  This may
4547bc27027aSMiklos Szeredi  * be appropriate for callers that expect the underlying filesystem not
4548bc27027aSMiklos Szeredi  * to be NFS exported.
4549bc27027aSMiklos Szeredi  *
45501da177e4SLinus Torvalds  * The worst of all namespace operations - renaming directory. "Perverted"
45511da177e4SLinus Torvalds  * doesn't even start to describe it. Somebody in UCB had a heck of a trip...
45521da177e4SLinus Torvalds  * Problems:
45530117d427SMauro Carvalho Chehab  *
4554d03b29a2SJ. Bruce Fields  *	a) we can get into loop creation.
45551da177e4SLinus Torvalds  *	b) race potential - two innocent renames can create a loop together.
45561da177e4SLinus Torvalds  *	   That's where 4.4 screws up. Current fix: serialization on
4557a11f3a05SArjan van de Ven  *	   sb->s_vfs_rename_mutex. We might be more accurate, but that's another
45581da177e4SLinus Torvalds  *	   story.
45596cedba89SJ. Bruce Fields  *	c) we have to lock _four_ objects - parents and victim (if it exists),
45606cedba89SJ. Bruce Fields  *	   and source (if it is not a directory).
45611b1dcc1bSJes Sorensen  *	   And that - after we got ->i_mutex on parents (until then we don't know
45621da177e4SLinus Torvalds  *	   whether the target exists).  Solution: try to be smart with locking
45631da177e4SLinus Torvalds  *	   order for inodes.  We rely on the fact that tree topology may change
4564a11f3a05SArjan van de Ven  *	   only under ->s_vfs_rename_mutex _and_ that parent of the object we
45651da177e4SLinus Torvalds  *	   move will be locked.  Thus we can rank directories by the tree
45661da177e4SLinus Torvalds  *	   (ancestors first) and rank all non-directories after them.
45671da177e4SLinus Torvalds  *	   That works since everybody except rename does "lock parent, lookup,
4568a11f3a05SArjan van de Ven  *	   lock child" and rename is under ->s_vfs_rename_mutex.
45691da177e4SLinus Torvalds  *	   HOWEVER, it relies on the assumption that any object with ->lookup()
45701da177e4SLinus Torvalds  *	   has no more than 1 dentry.  If "hybrid" objects will ever appear,
45711da177e4SLinus Torvalds  *	   we'd better make sure that there's no link(2) for them.
4572e4eaac06SSage Weil  *	d) conversion from fhandle to dentry may come in the wrong moment - when
45731b1dcc1bSJes Sorensen  *	   we are removing the target. Solution: we will have to grab ->i_mutex
45741da177e4SLinus Torvalds  *	   in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on
4575c41b20e7SAdam Buchbinder  *	   ->i_mutex on parents, which works but leads to some truly excessive
45761da177e4SLinus Torvalds  *	   locking].
45771da177e4SLinus Torvalds  */
45789fe61450SChristian Brauner int vfs_rename(struct renamedata *rd)
45791da177e4SLinus Torvalds {
45801da177e4SLinus Torvalds 	int error;
45819fe61450SChristian Brauner 	struct inode *old_dir = rd->old_dir, *new_dir = rd->new_dir;
45829fe61450SChristian Brauner 	struct dentry *old_dentry = rd->old_dentry;
45839fe61450SChristian Brauner 	struct dentry *new_dentry = rd->new_dentry;
45849fe61450SChristian Brauner 	struct inode **delegated_inode = rd->delegated_inode;
45859fe61450SChristian Brauner 	unsigned int flags = rd->flags;
4586bc27027aSMiklos Szeredi 	bool is_dir = d_is_dir(old_dentry);
4587bc27027aSMiklos Szeredi 	struct inode *source = old_dentry->d_inode;
4588bc27027aSMiklos Szeredi 	struct inode *target = new_dentry->d_inode;
4589da1ce067SMiklos Szeredi 	bool new_is_dir = false;
4590da1ce067SMiklos Szeredi 	unsigned max_links = new_dir->i_sb->s_max_links;
459149d31c2fSAl Viro 	struct name_snapshot old_name;
45921da177e4SLinus Torvalds 
45938d3e2936SMiklos Szeredi 	if (source == target)
45941da177e4SLinus Torvalds 		return 0;
45951da177e4SLinus Torvalds 
45966521f891SChristian Brauner 	error = may_delete(rd->old_mnt_userns, old_dir, old_dentry, is_dir);
45971da177e4SLinus Torvalds 	if (error)
45981da177e4SLinus Torvalds 		return error;
45991da177e4SLinus Torvalds 
4600da1ce067SMiklos Szeredi 	if (!target) {
46016521f891SChristian Brauner 		error = may_create(rd->new_mnt_userns, new_dir, new_dentry);
4602da1ce067SMiklos Szeredi 	} else {
4603da1ce067SMiklos Szeredi 		new_is_dir = d_is_dir(new_dentry);
4604da1ce067SMiklos Szeredi 
4605da1ce067SMiklos Szeredi 		if (!(flags & RENAME_EXCHANGE))
46066521f891SChristian Brauner 			error = may_delete(rd->new_mnt_userns, new_dir,
46076521f891SChristian Brauner 					   new_dentry, is_dir);
4608da1ce067SMiklos Szeredi 		else
46096521f891SChristian Brauner 			error = may_delete(rd->new_mnt_userns, new_dir,
46106521f891SChristian Brauner 					   new_dentry, new_is_dir);
4611da1ce067SMiklos Szeredi 	}
46121da177e4SLinus Torvalds 	if (error)
46131da177e4SLinus Torvalds 		return error;
46141da177e4SLinus Torvalds 
46152773bf00SMiklos Szeredi 	if (!old_dir->i_op->rename)
46161da177e4SLinus Torvalds 		return -EPERM;
46171da177e4SLinus Torvalds 
4618bc27027aSMiklos Szeredi 	/*
4619bc27027aSMiklos Szeredi 	 * If we are going to change the parent - check write permissions,
4620bc27027aSMiklos Szeredi 	 * we'll need to flip '..'.
4621bc27027aSMiklos Szeredi 	 */
4622da1ce067SMiklos Szeredi 	if (new_dir != old_dir) {
4623da1ce067SMiklos Szeredi 		if (is_dir) {
46246521f891SChristian Brauner 			error = inode_permission(rd->old_mnt_userns, source,
462547291baaSChristian Brauner 						 MAY_WRITE);
4626bc27027aSMiklos Szeredi 			if (error)
4627bc27027aSMiklos Szeredi 				return error;
4628bc27027aSMiklos Szeredi 		}
4629da1ce067SMiklos Szeredi 		if ((flags & RENAME_EXCHANGE) && new_is_dir) {
46306521f891SChristian Brauner 			error = inode_permission(rd->new_mnt_userns, target,
463147291baaSChristian Brauner 						 MAY_WRITE);
4632da1ce067SMiklos Szeredi 			if (error)
4633da1ce067SMiklos Szeredi 				return error;
4634da1ce067SMiklos Szeredi 		}
4635da1ce067SMiklos Szeredi 	}
46360eeca283SRobert Love 
46370b3974ebSMiklos Szeredi 	error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,
46380b3974ebSMiklos Szeredi 				      flags);
4639bc27027aSMiklos Szeredi 	if (error)
4640bc27027aSMiklos Szeredi 		return error;
4641bc27027aSMiklos Szeredi 
464249d31c2fSAl Viro 	take_dentry_name_snapshot(&old_name, old_dentry);
4643bc27027aSMiklos Szeredi 	dget(new_dentry);
4644da1ce067SMiklos Szeredi 	if (!is_dir || (flags & RENAME_EXCHANGE))
4645bc27027aSMiklos Szeredi 		lock_two_nondirectories(source, target);
4646bc27027aSMiklos Szeredi 	else if (target)
46475955102cSAl Viro 		inode_lock(target);
4648bc27027aSMiklos Szeredi 
464951cc3a66SHugh Dickins 	error = -EPERM;
465051cc3a66SHugh Dickins 	if (IS_SWAPFILE(source) || (target && IS_SWAPFILE(target)))
465151cc3a66SHugh Dickins 		goto out;
465251cc3a66SHugh Dickins 
4653bc27027aSMiklos Szeredi 	error = -EBUSY;
46547af1364fSEric W. Biederman 	if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
4655bc27027aSMiklos Szeredi 		goto out;
4656bc27027aSMiklos Szeredi 
4657da1ce067SMiklos Szeredi 	if (max_links && new_dir != old_dir) {
4658bc27027aSMiklos Szeredi 		error = -EMLINK;
4659da1ce067SMiklos Szeredi 		if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)
4660bc27027aSMiklos Szeredi 			goto out;
4661da1ce067SMiklos Szeredi 		if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&
4662da1ce067SMiklos Szeredi 		    old_dir->i_nlink >= max_links)
4663da1ce067SMiklos Szeredi 			goto out;
4664da1ce067SMiklos Szeredi 	}
4665da1ce067SMiklos Szeredi 	if (!is_dir) {
4666bc27027aSMiklos Szeredi 		error = try_break_deleg(source, delegated_inode);
4667bc27027aSMiklos Szeredi 		if (error)
4668bc27027aSMiklos Szeredi 			goto out;
4669da1ce067SMiklos Szeredi 	}
4670da1ce067SMiklos Szeredi 	if (target && !new_is_dir) {
4671bc27027aSMiklos Szeredi 		error = try_break_deleg(target, delegated_inode);
4672bc27027aSMiklos Szeredi 		if (error)
4673bc27027aSMiklos Szeredi 			goto out;
4674bc27027aSMiklos Szeredi 	}
4675549c7297SChristian Brauner 	error = old_dir->i_op->rename(rd->new_mnt_userns, old_dir, old_dentry,
4676520c8b16SMiklos Szeredi 				      new_dir, new_dentry, flags);
4677bc27027aSMiklos Szeredi 	if (error)
4678bc27027aSMiklos Szeredi 		goto out;
4679bc27027aSMiklos Szeredi 
4680da1ce067SMiklos Szeredi 	if (!(flags & RENAME_EXCHANGE) && target) {
46818767712fSAl Viro 		if (is_dir) {
46828767712fSAl Viro 			shrink_dcache_parent(new_dentry);
4683bc27027aSMiklos Szeredi 			target->i_flags |= S_DEAD;
46848767712fSAl Viro 		}
4685bc27027aSMiklos Szeredi 		dont_mount(new_dentry);
46868ed936b5SEric W. Biederman 		detach_mounts(new_dentry);
4687bc27027aSMiklos Szeredi 	}
4688da1ce067SMiklos Szeredi 	if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {
4689da1ce067SMiklos Szeredi 		if (!(flags & RENAME_EXCHANGE))
4690bc27027aSMiklos Szeredi 			d_move(old_dentry, new_dentry);
4691da1ce067SMiklos Szeredi 		else
4692da1ce067SMiklos Szeredi 			d_exchange(old_dentry, new_dentry);
4693da1ce067SMiklos Szeredi 	}
4694bc27027aSMiklos Szeredi out:
4695da1ce067SMiklos Szeredi 	if (!is_dir || (flags & RENAME_EXCHANGE))
4696bc27027aSMiklos Szeredi 		unlock_two_nondirectories(source, target);
4697bc27027aSMiklos Szeredi 	else if (target)
46985955102cSAl Viro 		inode_unlock(target);
4699bc27027aSMiklos Szeredi 	dput(new_dentry);
4700da1ce067SMiklos Szeredi 	if (!error) {
4701f4ec3a3dSAl Viro 		fsnotify_move(old_dir, new_dir, &old_name.name, is_dir,
4702da1ce067SMiklos Szeredi 			      !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);
4703da1ce067SMiklos Szeredi 		if (flags & RENAME_EXCHANGE) {
4704f4ec3a3dSAl Viro 			fsnotify_move(new_dir, old_dir, &old_dentry->d_name,
4705da1ce067SMiklos Szeredi 				      new_is_dir, NULL, new_dentry);
4706da1ce067SMiklos Szeredi 		}
4707da1ce067SMiklos Szeredi 	}
470849d31c2fSAl Viro 	release_dentry_name_snapshot(&old_name);
47090eeca283SRobert Love 
47101da177e4SLinus Torvalds 	return error;
47111da177e4SLinus Torvalds }
47124d359507SAl Viro EXPORT_SYMBOL(vfs_rename);
47131da177e4SLinus Torvalds 
4714e886663cSJens Axboe int do_renameat2(int olddfd, struct filename *from, int newdfd,
4715e886663cSJens Axboe 		 struct filename *to, unsigned int flags)
47161da177e4SLinus Torvalds {
47179fe61450SChristian Brauner 	struct renamedata rd;
47181da177e4SLinus Torvalds 	struct dentry *old_dentry, *new_dentry;
47191da177e4SLinus Torvalds 	struct dentry *trap;
4720f5beed75SAl Viro 	struct path old_path, new_path;
4721f5beed75SAl Viro 	struct qstr old_last, new_last;
4722f5beed75SAl Viro 	int old_type, new_type;
47238e6d782cSJ. Bruce Fields 	struct inode *delegated_inode = NULL;
4724f5beed75SAl Viro 	unsigned int lookup_flags = 0, target_flags = LOOKUP_RENAME_TARGET;
4725c6a94284SJeff Layton 	bool should_retry = false;
4726e886663cSJens Axboe 	int error = -EINVAL;
4727520c8b16SMiklos Szeredi 
47280d7a8555SMiklos Szeredi 	if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
47290ee50b47SDmitry Kadashev 		goto put_names;
4730da1ce067SMiklos Szeredi 
47310d7a8555SMiklos Szeredi 	if ((flags & (RENAME_NOREPLACE | RENAME_WHITEOUT)) &&
47320d7a8555SMiklos Szeredi 	    (flags & RENAME_EXCHANGE))
47330ee50b47SDmitry Kadashev 		goto put_names;
4734520c8b16SMiklos Szeredi 
4735f5beed75SAl Viro 	if (flags & RENAME_EXCHANGE)
4736f5beed75SAl Viro 		target_flags = 0;
4737f5beed75SAl Viro 
4738c6a94284SJeff Layton retry:
4739c5f563f9SAl Viro 	error = filename_parentat(olddfd, from, lookup_flags, &old_path,
4740e886663cSJens Axboe 				  &old_last, &old_type);
47410ee50b47SDmitry Kadashev 	if (error)
47420ee50b47SDmitry Kadashev 		goto put_names;
47431da177e4SLinus Torvalds 
4744c5f563f9SAl Viro 	error = filename_parentat(newdfd, to, lookup_flags, &new_path, &new_last,
4745e886663cSJens Axboe 				  &new_type);
47460ee50b47SDmitry Kadashev 	if (error)
47471da177e4SLinus Torvalds 		goto exit1;
47481da177e4SLinus Torvalds 
47491da177e4SLinus Torvalds 	error = -EXDEV;
4750f5beed75SAl Viro 	if (old_path.mnt != new_path.mnt)
47511da177e4SLinus Torvalds 		goto exit2;
47521da177e4SLinus Torvalds 
47531da177e4SLinus Torvalds 	error = -EBUSY;
4754f5beed75SAl Viro 	if (old_type != LAST_NORM)
47551da177e4SLinus Torvalds 		goto exit2;
47561da177e4SLinus Torvalds 
47570a7c3937SMiklos Szeredi 	if (flags & RENAME_NOREPLACE)
47580a7c3937SMiklos Szeredi 		error = -EEXIST;
4759f5beed75SAl Viro 	if (new_type != LAST_NORM)
47601da177e4SLinus Torvalds 		goto exit2;
47611da177e4SLinus Torvalds 
4762f5beed75SAl Viro 	error = mnt_want_write(old_path.mnt);
4763c30dabfeSJan Kara 	if (error)
4764c30dabfeSJan Kara 		goto exit2;
4765c30dabfeSJan Kara 
47668e6d782cSJ. Bruce Fields retry_deleg:
4767f5beed75SAl Viro 	trap = lock_rename(new_path.dentry, old_path.dentry);
47681da177e4SLinus Torvalds 
4769f5beed75SAl Viro 	old_dentry = __lookup_hash(&old_last, old_path.dentry, lookup_flags);
47701da177e4SLinus Torvalds 	error = PTR_ERR(old_dentry);
47711da177e4SLinus Torvalds 	if (IS_ERR(old_dentry))
47721da177e4SLinus Torvalds 		goto exit3;
47731da177e4SLinus Torvalds 	/* source must exist */
47741da177e4SLinus Torvalds 	error = -ENOENT;
4775b18825a7SDavid Howells 	if (d_is_negative(old_dentry))
47761da177e4SLinus Torvalds 		goto exit4;
4777f5beed75SAl Viro 	new_dentry = __lookup_hash(&new_last, new_path.dentry, lookup_flags | target_flags);
47781da177e4SLinus Torvalds 	error = PTR_ERR(new_dentry);
47791da177e4SLinus Torvalds 	if (IS_ERR(new_dentry))
47801da177e4SLinus Torvalds 		goto exit4;
47810a7c3937SMiklos Szeredi 	error = -EEXIST;
47820a7c3937SMiklos Szeredi 	if ((flags & RENAME_NOREPLACE) && d_is_positive(new_dentry))
47830a7c3937SMiklos Szeredi 		goto exit5;
4784da1ce067SMiklos Szeredi 	if (flags & RENAME_EXCHANGE) {
4785da1ce067SMiklos Szeredi 		error = -ENOENT;
4786da1ce067SMiklos Szeredi 		if (d_is_negative(new_dentry))
4787da1ce067SMiklos Szeredi 			goto exit5;
4788da1ce067SMiklos Szeredi 
4789da1ce067SMiklos Szeredi 		if (!d_is_dir(new_dentry)) {
4790da1ce067SMiklos Szeredi 			error = -ENOTDIR;
4791f5beed75SAl Viro 			if (new_last.name[new_last.len])
4792da1ce067SMiklos Szeredi 				goto exit5;
4793da1ce067SMiklos Szeredi 		}
4794da1ce067SMiklos Szeredi 	}
47950a7c3937SMiklos Szeredi 	/* unless the source is a directory trailing slashes give -ENOTDIR */
47960a7c3937SMiklos Szeredi 	if (!d_is_dir(old_dentry)) {
47970a7c3937SMiklos Szeredi 		error = -ENOTDIR;
4798f5beed75SAl Viro 		if (old_last.name[old_last.len])
47990a7c3937SMiklos Szeredi 			goto exit5;
4800f5beed75SAl Viro 		if (!(flags & RENAME_EXCHANGE) && new_last.name[new_last.len])
48010a7c3937SMiklos Szeredi 			goto exit5;
48020a7c3937SMiklos Szeredi 	}
48030a7c3937SMiklos Szeredi 	/* source should not be ancestor of target */
48040a7c3937SMiklos Szeredi 	error = -EINVAL;
48050a7c3937SMiklos Szeredi 	if (old_dentry == trap)
48060a7c3937SMiklos Szeredi 		goto exit5;
48071da177e4SLinus Torvalds 	/* target should not be an ancestor of source */
4808da1ce067SMiklos Szeredi 	if (!(flags & RENAME_EXCHANGE))
48091da177e4SLinus Torvalds 		error = -ENOTEMPTY;
48101da177e4SLinus Torvalds 	if (new_dentry == trap)
48111da177e4SLinus Torvalds 		goto exit5;
48121da177e4SLinus Torvalds 
4813f5beed75SAl Viro 	error = security_path_rename(&old_path, old_dentry,
4814f5beed75SAl Viro 				     &new_path, new_dentry, flags);
4815be6d3e56SKentaro Takeda 	if (error)
4816c30dabfeSJan Kara 		goto exit5;
48179fe61450SChristian Brauner 
48189fe61450SChristian Brauner 	rd.old_dir	   = old_path.dentry->d_inode;
48199fe61450SChristian Brauner 	rd.old_dentry	   = old_dentry;
48206521f891SChristian Brauner 	rd.old_mnt_userns  = mnt_user_ns(old_path.mnt);
48219fe61450SChristian Brauner 	rd.new_dir	   = new_path.dentry->d_inode;
48229fe61450SChristian Brauner 	rd.new_dentry	   = new_dentry;
48236521f891SChristian Brauner 	rd.new_mnt_userns  = mnt_user_ns(new_path.mnt);
48249fe61450SChristian Brauner 	rd.delegated_inode = &delegated_inode;
48259fe61450SChristian Brauner 	rd.flags	   = flags;
48269fe61450SChristian Brauner 	error = vfs_rename(&rd);
48271da177e4SLinus Torvalds exit5:
48281da177e4SLinus Torvalds 	dput(new_dentry);
48291da177e4SLinus Torvalds exit4:
48301da177e4SLinus Torvalds 	dput(old_dentry);
48311da177e4SLinus Torvalds exit3:
4832f5beed75SAl Viro 	unlock_rename(new_path.dentry, old_path.dentry);
48338e6d782cSJ. Bruce Fields 	if (delegated_inode) {
48348e6d782cSJ. Bruce Fields 		error = break_deleg_wait(&delegated_inode);
48358e6d782cSJ. Bruce Fields 		if (!error)
48368e6d782cSJ. Bruce Fields 			goto retry_deleg;
48378e6d782cSJ. Bruce Fields 	}
4838f5beed75SAl Viro 	mnt_drop_write(old_path.mnt);
48391da177e4SLinus Torvalds exit2:
4840c6a94284SJeff Layton 	if (retry_estale(error, lookup_flags))
4841c6a94284SJeff Layton 		should_retry = true;
4842f5beed75SAl Viro 	path_put(&new_path);
48431da177e4SLinus Torvalds exit1:
4844f5beed75SAl Viro 	path_put(&old_path);
4845c6a94284SJeff Layton 	if (should_retry) {
4846c6a94284SJeff Layton 		should_retry = false;
4847c6a94284SJeff Layton 		lookup_flags |= LOOKUP_REVAL;
4848c6a94284SJeff Layton 		goto retry;
4849c6a94284SJeff Layton 	}
48500ee50b47SDmitry Kadashev put_names:
4851e886663cSJens Axboe 	putname(from);
4852e886663cSJens Axboe 	putname(to);
48531da177e4SLinus Torvalds 	return error;
48541da177e4SLinus Torvalds }
48551da177e4SLinus Torvalds 
4856ee81feb6SDominik Brodowski SYSCALL_DEFINE5(renameat2, int, olddfd, const char __user *, oldname,
4857ee81feb6SDominik Brodowski 		int, newdfd, const char __user *, newname, unsigned int, flags)
4858ee81feb6SDominik Brodowski {
4859e886663cSJens Axboe 	return do_renameat2(olddfd, getname(oldname), newdfd, getname(newname),
4860e886663cSJens Axboe 				flags);
4861ee81feb6SDominik Brodowski }
4862ee81feb6SDominik Brodowski 
4863520c8b16SMiklos Szeredi SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname,
4864520c8b16SMiklos Szeredi 		int, newdfd, const char __user *, newname)
4865520c8b16SMiklos Szeredi {
4866e886663cSJens Axboe 	return do_renameat2(olddfd, getname(oldname), newdfd, getname(newname),
4867e886663cSJens Axboe 				0);
4868520c8b16SMiklos Szeredi }
4869520c8b16SMiklos Szeredi 
4870a26eab24SHeiko Carstens SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname)
48715590ff0dSUlrich Drepper {
4872e886663cSJens Axboe 	return do_renameat2(AT_FDCWD, getname(oldname), AT_FDCWD,
4873e886663cSJens Axboe 				getname(newname), 0);
48745590ff0dSUlrich Drepper }
48755590ff0dSUlrich Drepper 
48765d826c84SAl Viro int readlink_copy(char __user *buffer, int buflen, const char *link)
48771da177e4SLinus Torvalds {
48785d826c84SAl Viro 	int len = PTR_ERR(link);
48791da177e4SLinus Torvalds 	if (IS_ERR(link))
48801da177e4SLinus Torvalds 		goto out;
48811da177e4SLinus Torvalds 
48821da177e4SLinus Torvalds 	len = strlen(link);
48831da177e4SLinus Torvalds 	if (len > (unsigned) buflen)
48841da177e4SLinus Torvalds 		len = buflen;
48851da177e4SLinus Torvalds 	if (copy_to_user(buffer, link, len))
48861da177e4SLinus Torvalds 		len = -EFAULT;
48871da177e4SLinus Torvalds out:
48881da177e4SLinus Torvalds 	return len;
48891da177e4SLinus Torvalds }
48901da177e4SLinus Torvalds 
4891d60874cdSMiklos Szeredi /**
4892fd4a0edfSMiklos Szeredi  * vfs_readlink - copy symlink body into userspace buffer
4893fd4a0edfSMiklos Szeredi  * @dentry: dentry on which to get symbolic link
4894fd4a0edfSMiklos Szeredi  * @buffer: user memory pointer
4895fd4a0edfSMiklos Szeredi  * @buflen: size of buffer
4896fd4a0edfSMiklos Szeredi  *
4897fd4a0edfSMiklos Szeredi  * Does not touch atime.  That's up to the caller if necessary
4898fd4a0edfSMiklos Szeredi  *
4899fd4a0edfSMiklos Szeredi  * Does not call security hook.
4900fd4a0edfSMiklos Szeredi  */
4901fd4a0edfSMiklos Szeredi int vfs_readlink(struct dentry *dentry, char __user *buffer, int buflen)
4902fd4a0edfSMiklos Szeredi {
4903fd4a0edfSMiklos Szeredi 	struct inode *inode = d_inode(dentry);
4904f2df5da6SAl Viro 	DEFINE_DELAYED_CALL(done);
4905f2df5da6SAl Viro 	const char *link;
4906f2df5da6SAl Viro 	int res;
4907fd4a0edfSMiklos Szeredi 
490876fca90eSMiklos Szeredi 	if (unlikely(!(inode->i_opflags & IOP_DEFAULT_READLINK))) {
490976fca90eSMiklos Szeredi 		if (unlikely(inode->i_op->readlink))
491076fca90eSMiklos Szeredi 			return inode->i_op->readlink(dentry, buffer, buflen);
491176fca90eSMiklos Szeredi 
491276fca90eSMiklos Szeredi 		if (!d_is_symlink(dentry))
4913fd4a0edfSMiklos Szeredi 			return -EINVAL;
4914fd4a0edfSMiklos Szeredi 
491576fca90eSMiklos Szeredi 		spin_lock(&inode->i_lock);
491676fca90eSMiklos Szeredi 		inode->i_opflags |= IOP_DEFAULT_READLINK;
491776fca90eSMiklos Szeredi 		spin_unlock(&inode->i_lock);
491876fca90eSMiklos Szeredi 	}
491976fca90eSMiklos Szeredi 
49204c4f7c19SEric Biggers 	link = READ_ONCE(inode->i_link);
4921f2df5da6SAl Viro 	if (!link) {
4922f2df5da6SAl Viro 		link = inode->i_op->get_link(dentry, inode, &done);
4923f2df5da6SAl Viro 		if (IS_ERR(link))
4924f2df5da6SAl Viro 			return PTR_ERR(link);
4925f2df5da6SAl Viro 	}
4926f2df5da6SAl Viro 	res = readlink_copy(buffer, buflen, link);
4927f2df5da6SAl Viro 	do_delayed_call(&done);
4928f2df5da6SAl Viro 	return res;
4929fd4a0edfSMiklos Szeredi }
4930fd4a0edfSMiklos Szeredi EXPORT_SYMBOL(vfs_readlink);
49311da177e4SLinus Torvalds 
4932d60874cdSMiklos Szeredi /**
4933d60874cdSMiklos Szeredi  * vfs_get_link - get symlink body
4934d60874cdSMiklos Szeredi  * @dentry: dentry on which to get symbolic link
4935d60874cdSMiklos Szeredi  * @done: caller needs to free returned data with this
4936d60874cdSMiklos Szeredi  *
4937d60874cdSMiklos Szeredi  * Calls security hook and i_op->get_link() on the supplied inode.
4938d60874cdSMiklos Szeredi  *
4939d60874cdSMiklos Szeredi  * It does not touch atime.  That's up to the caller if necessary.
4940d60874cdSMiklos Szeredi  *
4941d60874cdSMiklos Szeredi  * Does not work on "special" symlinks like /proc/$$/fd/N
4942d60874cdSMiklos Szeredi  */
4943d60874cdSMiklos Szeredi const char *vfs_get_link(struct dentry *dentry, struct delayed_call *done)
4944d60874cdSMiklos Szeredi {
4945d60874cdSMiklos Szeredi 	const char *res = ERR_PTR(-EINVAL);
4946d60874cdSMiklos Szeredi 	struct inode *inode = d_inode(dentry);
4947d60874cdSMiklos Szeredi 
4948d60874cdSMiklos Szeredi 	if (d_is_symlink(dentry)) {
4949d60874cdSMiklos Szeredi 		res = ERR_PTR(security_inode_readlink(dentry));
4950d60874cdSMiklos Szeredi 		if (!res)
4951d60874cdSMiklos Szeredi 			res = inode->i_op->get_link(dentry, inode, done);
4952d60874cdSMiklos Szeredi 	}
4953d60874cdSMiklos Szeredi 	return res;
4954d60874cdSMiklos Szeredi }
4955d60874cdSMiklos Szeredi EXPORT_SYMBOL(vfs_get_link);
4956d60874cdSMiklos Szeredi 
49571da177e4SLinus Torvalds /* get the link contents into pagecache */
49586b255391SAl Viro const char *page_get_link(struct dentry *dentry, struct inode *inode,
4959fceef393SAl Viro 			  struct delayed_call *callback)
49601da177e4SLinus Torvalds {
4961ebd09abbSDuane Griffin 	char *kaddr;
49621da177e4SLinus Torvalds 	struct page *page;
49636b255391SAl Viro 	struct address_space *mapping = inode->i_mapping;
49646b255391SAl Viro 
4965d3883d4fSAl Viro 	if (!dentry) {
4966d3883d4fSAl Viro 		page = find_get_page(mapping, 0);
4967d3883d4fSAl Viro 		if (!page)
49686b255391SAl Viro 			return ERR_PTR(-ECHILD);
4969d3883d4fSAl Viro 		if (!PageUptodate(page)) {
4970d3883d4fSAl Viro 			put_page(page);
4971d3883d4fSAl Viro 			return ERR_PTR(-ECHILD);
4972d3883d4fSAl Viro 		}
4973d3883d4fSAl Viro 	} else {
4974090d2b18SPekka Enberg 		page = read_mapping_page(mapping, 0, NULL);
49751da177e4SLinus Torvalds 		if (IS_ERR(page))
49766fe6900eSNick Piggin 			return (char*)page;
4977d3883d4fSAl Viro 	}
4978fceef393SAl Viro 	set_delayed_call(callback, page_put_link, page);
497921fc61c7SAl Viro 	BUG_ON(mapping_gfp_mask(mapping) & __GFP_HIGHMEM);
498021fc61c7SAl Viro 	kaddr = page_address(page);
49816b255391SAl Viro 	nd_terminate_link(kaddr, inode->i_size, PAGE_SIZE - 1);
4982ebd09abbSDuane Griffin 	return kaddr;
49831da177e4SLinus Torvalds }
49841da177e4SLinus Torvalds 
49856b255391SAl Viro EXPORT_SYMBOL(page_get_link);
49861da177e4SLinus Torvalds 
4987fceef393SAl Viro void page_put_link(void *arg)
49881da177e4SLinus Torvalds {
4989fceef393SAl Viro 	put_page(arg);
49901da177e4SLinus Torvalds }
49914d359507SAl Viro EXPORT_SYMBOL(page_put_link);
49921da177e4SLinus Torvalds 
4993aa80deabSAl Viro int page_readlink(struct dentry *dentry, char __user *buffer, int buflen)
4994aa80deabSAl Viro {
4995fceef393SAl Viro 	DEFINE_DELAYED_CALL(done);
49966b255391SAl Viro 	int res = readlink_copy(buffer, buflen,
49976b255391SAl Viro 				page_get_link(dentry, d_inode(dentry),
4998fceef393SAl Viro 					      &done));
4999fceef393SAl Viro 	do_delayed_call(&done);
5000aa80deabSAl Viro 	return res;
5001aa80deabSAl Viro }
5002aa80deabSAl Viro EXPORT_SYMBOL(page_readlink);
5003aa80deabSAl Viro 
5004*56f5746cSMatthew Wilcox (Oracle) int page_symlink(struct inode *inode, const char *symname, int len)
50051da177e4SLinus Torvalds {
50061da177e4SLinus Torvalds 	struct address_space *mapping = inode->i_mapping;
5007*56f5746cSMatthew Wilcox (Oracle) 	bool nofs = !mapping_gfp_constraint(mapping, __GFP_FS);
50080adb25d2SKirill Korotaev 	struct page *page;
5009afddba49SNick Piggin 	void *fsdata;
5010beb497abSDmitriy Monakhov 	int err;
5011c718a975STetsuo Handa 	unsigned int flags = 0;
501254566b2cSNick Piggin 	if (nofs)
501354566b2cSNick Piggin 		flags |= AOP_FLAG_NOFS;
50141da177e4SLinus Torvalds 
50157e53cac4SNeilBrown retry:
5016afddba49SNick Piggin 	err = pagecache_write_begin(NULL, mapping, 0, len-1,
501754566b2cSNick Piggin 				flags, &page, &fsdata);
50181da177e4SLinus Torvalds 	if (err)
5019afddba49SNick Piggin 		goto fail;
5020afddba49SNick Piggin 
502121fc61c7SAl Viro 	memcpy(page_address(page), symname, len-1);
5022afddba49SNick Piggin 
5023afddba49SNick Piggin 	err = pagecache_write_end(NULL, mapping, 0, len-1, len-1,
5024afddba49SNick Piggin 							page, fsdata);
50251da177e4SLinus Torvalds 	if (err < 0)
50261da177e4SLinus Torvalds 		goto fail;
5027afddba49SNick Piggin 	if (err < len-1)
5028afddba49SNick Piggin 		goto retry;
5029afddba49SNick Piggin 
50301da177e4SLinus Torvalds 	mark_inode_dirty(inode);
50311da177e4SLinus Torvalds 	return 0;
50321da177e4SLinus Torvalds fail:
50331da177e4SLinus Torvalds 	return err;
50341da177e4SLinus Torvalds }
50354d359507SAl Viro EXPORT_SYMBOL(page_symlink);
50360adb25d2SKirill Korotaev 
503792e1d5beSArjan van de Ven const struct inode_operations page_symlink_inode_operations = {
50386b255391SAl Viro 	.get_link	= page_get_link,
50391da177e4SLinus Torvalds };
50401da177e4SLinus Torvalds EXPORT_SYMBOL(page_symlink_inode_operations);
5041