xref: /openbmc/linux/fs/namei.c (revision 35931eb3)
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>
235970e15dSJeff Layton #include <linux/filelock.h>
241da177e4SLinus Torvalds #include <linux/namei.h>
251da177e4SLinus Torvalds #include <linux/pagemap.h>
262d878178SMatthew Wilcox (Oracle) #include <linux/sched/mm.h>
270eeca283SRobert Love #include <linux/fsnotify.h>
281da177e4SLinus Torvalds #include <linux/personality.h>
291da177e4SLinus Torvalds #include <linux/security.h>
306146f0d5SMimi Zohar #include <linux/ima.h>
311da177e4SLinus Torvalds #include <linux/syscalls.h>
321da177e4SLinus Torvalds #include <linux/mount.h>
331da177e4SLinus Torvalds #include <linux/audit.h>
3416f7e0feSRandy Dunlap #include <linux/capability.h>
35834f2a4aSTrond Myklebust #include <linux/file.h>
365590ff0dSUlrich Drepper #include <linux/fcntl.h>
3708ce5f16SSerge E. Hallyn #include <linux/device_cgroup.h>
385ad4e53bSAl Viro #include <linux/fs_struct.h>
39e77819e5SLinus Torvalds #include <linux/posix_acl.h>
4099d263d4SLinus Torvalds #include <linux/hash.h>
412a18da7aSGeorge Spelvin #include <linux/bitops.h>
42aeaa4a79SEric W. Biederman #include <linux/init_task.h>
437c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
441da177e4SLinus Torvalds 
45e81e3f4dSEric Paris #include "internal.h"
46c7105365SAl Viro #include "mount.h"
47e81e3f4dSEric Paris 
481da177e4SLinus Torvalds /* [Feb-1997 T. Schoebel-Theuer]
491da177e4SLinus Torvalds  * Fundamental changes in the pathname lookup mechanisms (namei)
501da177e4SLinus Torvalds  * were necessary because of omirr.  The reason is that omirr needs
511da177e4SLinus Torvalds  * to know the _real_ pathname, not the user-supplied one, in case
521da177e4SLinus Torvalds  * of symlinks (and also when transname replacements occur).
531da177e4SLinus Torvalds  *
541da177e4SLinus Torvalds  * The new code replaces the old recursive symlink resolution with
551da177e4SLinus Torvalds  * an iterative one (in case of non-nested symlink chains).  It does
561da177e4SLinus Torvalds  * this with calls to <fs>_follow_link().
571da177e4SLinus Torvalds  * As a side effect, dir_namei(), _namei() and follow_link() are now
581da177e4SLinus Torvalds  * replaced with a single function lookup_dentry() that can handle all
591da177e4SLinus Torvalds  * the special cases of the former code.
601da177e4SLinus Torvalds  *
611da177e4SLinus Torvalds  * With the new dcache, the pathname is stored at each inode, at least as
621da177e4SLinus Torvalds  * long as the refcount of the inode is positive.  As a side effect, the
631da177e4SLinus Torvalds  * size of the dcache depends on the inode cache and thus is dynamic.
641da177e4SLinus Torvalds  *
651da177e4SLinus Torvalds  * [29-Apr-1998 C. Scott Ananian] Updated above description of symlink
661da177e4SLinus Torvalds  * resolution to correspond with current state of the code.
671da177e4SLinus Torvalds  *
681da177e4SLinus Torvalds  * Note that the symlink resolution is not *completely* iterative.
691da177e4SLinus Torvalds  * There is still a significant amount of tail- and mid- recursion in
701da177e4SLinus Torvalds  * the algorithm.  Also, note that <fs>_readlink() is not used in
711da177e4SLinus Torvalds  * lookup_dentry(): lookup_dentry() on the result of <fs>_readlink()
721da177e4SLinus Torvalds  * may return different results than <fs>_follow_link().  Many virtual
731da177e4SLinus Torvalds  * filesystems (including /proc) exhibit this behavior.
741da177e4SLinus Torvalds  */
751da177e4SLinus Torvalds 
761da177e4SLinus Torvalds /* [24-Feb-97 T. Schoebel-Theuer] Side effects caused by new implementation:
771da177e4SLinus Torvalds  * New symlink semantics: when open() is called with flags O_CREAT | O_EXCL
781da177e4SLinus Torvalds  * and the name already exists in form of a symlink, try to create the new
791da177e4SLinus Torvalds  * name indicated by the symlink. The old code always complained that the
801da177e4SLinus Torvalds  * name already exists, due to not following the symlink even if its target
811da177e4SLinus Torvalds  * is nonexistent.  The new semantics affects also mknod() and link() when
8225985edcSLucas De Marchi  * the name is a symlink pointing to a non-existent name.
831da177e4SLinus Torvalds  *
841da177e4SLinus Torvalds  * I don't know which semantics is the right one, since I have no access
851da177e4SLinus Torvalds  * to standards. But I found by trial that HP-UX 9.0 has the full "new"
861da177e4SLinus Torvalds  * semantics implemented, while SunOS 4.1.1 and Solaris (SunOS 5.4) have the
871da177e4SLinus Torvalds  * "old" one. Personally, I think the new semantics is much more logical.
881da177e4SLinus Torvalds  * Note that "ln old new" where "new" is a symlink pointing to a non-existing
891da177e4SLinus Torvalds  * file does succeed in both HP-UX and SunOs, but not in Solaris
901da177e4SLinus Torvalds  * and in the old Linux semantics.
911da177e4SLinus Torvalds  */
921da177e4SLinus Torvalds 
931da177e4SLinus Torvalds /* [16-Dec-97 Kevin Buhr] For security reasons, we change some symlink
941da177e4SLinus Torvalds  * semantics.  See the comments in "open_namei" and "do_link" below.
951da177e4SLinus Torvalds  *
961da177e4SLinus Torvalds  * [10-Sep-98 Alan Modra] Another symlink change.
971da177e4SLinus Torvalds  */
981da177e4SLinus Torvalds 
991da177e4SLinus Torvalds /* [Feb-Apr 2000 AV] Complete rewrite. Rules for symlinks:
1001da177e4SLinus Torvalds  *	inside the path - always follow.
1011da177e4SLinus Torvalds  *	in the last component in creation/removal/renaming - never follow.
1021da177e4SLinus Torvalds  *	if LOOKUP_FOLLOW passed - follow.
1031da177e4SLinus Torvalds  *	if the pathname has trailing slashes - follow.
1041da177e4SLinus Torvalds  *	otherwise - don't follow.
1051da177e4SLinus Torvalds  * (applied in that order).
1061da177e4SLinus Torvalds  *
1071da177e4SLinus Torvalds  * [Jun 2000 AV] Inconsistent behaviour of open() in case if flags==O_CREAT
1081da177e4SLinus Torvalds  * restored for 2.4. This is the last surviving part of old 4.2BSD bug.
1091da177e4SLinus Torvalds  * During the 2.4 we need to fix the userland stuff depending on it -
1101da177e4SLinus Torvalds  * hopefully we will be able to get rid of that wart in 2.5. So far only
1111da177e4SLinus Torvalds  * XEmacs seems to be relying on it...
1121da177e4SLinus Torvalds  */
1131da177e4SLinus Torvalds /*
1141da177e4SLinus Torvalds  * [Sep 2001 AV] Single-semaphore locking scheme (kudos to David Holland)
115a11f3a05SArjan van de Ven  * implemented.  Let's see if raised priority of ->s_vfs_rename_mutex gives
1161da177e4SLinus Torvalds  * any extra contention...
1171da177e4SLinus Torvalds  */
1181da177e4SLinus Torvalds 
1191da177e4SLinus Torvalds /* In order to reduce some races, while at the same time doing additional
1201da177e4SLinus Torvalds  * checking and hopefully speeding things up, we copy filenames to the
1211da177e4SLinus Torvalds  * kernel data space before using them..
1221da177e4SLinus Torvalds  *
1231da177e4SLinus Torvalds  * POSIX.1 2.4: an empty pathname is invalid (ENOENT).
1241da177e4SLinus Torvalds  * PATH_MAX includes the nul terminator --RR.
1251da177e4SLinus Torvalds  */
1267950e385SJeff Layton 
127fd2f7cb5SAl Viro #define EMBEDDED_NAME_MAX	(PATH_MAX - offsetof(struct filename, iname))
12891a27b2aSJeff Layton 
12951f39a1fSDavid Drysdale struct filename *
13091a27b2aSJeff Layton getname_flags(const char __user *filename, int flags, int *empty)
13191a27b2aSJeff Layton {
13294b5d262SAl Viro 	struct filename *result;
1337950e385SJeff Layton 	char *kname;
13494b5d262SAl Viro 	int len;
1351da177e4SLinus Torvalds 
1367ac86265SJeff Layton 	result = audit_reusename(filename);
1377ac86265SJeff Layton 	if (result)
1387ac86265SJeff Layton 		return result;
1397ac86265SJeff Layton 
1407950e385SJeff Layton 	result = __getname();
1413f9f0aa6SLinus Torvalds 	if (unlikely(!result))
1424043cde8SEric Paris 		return ERR_PTR(-ENOMEM);
1431da177e4SLinus Torvalds 
1447950e385SJeff Layton 	/*
1457950e385SJeff Layton 	 * First, try to embed the struct filename inside the names_cache
1467950e385SJeff Layton 	 * allocation
1477950e385SJeff Layton 	 */
148fd2f7cb5SAl Viro 	kname = (char *)result->iname;
14991a27b2aSJeff Layton 	result->name = kname;
1507950e385SJeff Layton 
15194b5d262SAl Viro 	len = strncpy_from_user(kname, filename, EMBEDDED_NAME_MAX);
15291a27b2aSJeff Layton 	if (unlikely(len < 0)) {
15394b5d262SAl Viro 		__putname(result);
15494b5d262SAl Viro 		return ERR_PTR(len);
15591a27b2aSJeff Layton 	}
1563f9f0aa6SLinus Torvalds 
1577950e385SJeff Layton 	/*
1587950e385SJeff Layton 	 * Uh-oh. We have a name that's approaching PATH_MAX. Allocate a
1597950e385SJeff Layton 	 * separate struct filename so we can dedicate the entire
1607950e385SJeff Layton 	 * names_cache allocation for the pathname, and re-do the copy from
1617950e385SJeff Layton 	 * userland.
1627950e385SJeff Layton 	 */
16394b5d262SAl Viro 	if (unlikely(len == EMBEDDED_NAME_MAX)) {
164fd2f7cb5SAl Viro 		const size_t size = offsetof(struct filename, iname[1]);
1657950e385SJeff Layton 		kname = (char *)result;
1667950e385SJeff Layton 
167fd2f7cb5SAl Viro 		/*
168fd2f7cb5SAl Viro 		 * size is chosen that way we to guarantee that
169fd2f7cb5SAl Viro 		 * result->iname[0] is within the same object and that
170fd2f7cb5SAl Viro 		 * kname can't be equal to result->iname, no matter what.
171fd2f7cb5SAl Viro 		 */
172fd2f7cb5SAl Viro 		result = kzalloc(size, GFP_KERNEL);
17394b5d262SAl Viro 		if (unlikely(!result)) {
17494b5d262SAl Viro 			__putname(kname);
17594b5d262SAl Viro 			return ERR_PTR(-ENOMEM);
1767950e385SJeff Layton 		}
1777950e385SJeff Layton 		result->name = kname;
17894b5d262SAl Viro 		len = strncpy_from_user(kname, filename, PATH_MAX);
17994b5d262SAl Viro 		if (unlikely(len < 0)) {
18094b5d262SAl Viro 			__putname(kname);
18194b5d262SAl Viro 			kfree(result);
18294b5d262SAl Viro 			return ERR_PTR(len);
18394b5d262SAl Viro 		}
18494b5d262SAl Viro 		if (unlikely(len == PATH_MAX)) {
18594b5d262SAl Viro 			__putname(kname);
18694b5d262SAl Viro 			kfree(result);
18794b5d262SAl Viro 			return ERR_PTR(-ENAMETOOLONG);
18894b5d262SAl Viro 		}
1897950e385SJeff Layton 	}
1907950e385SJeff Layton 
19194b5d262SAl Viro 	result->refcnt = 1;
1923f9f0aa6SLinus Torvalds 	/* The empty path is special. */
1933f9f0aa6SLinus Torvalds 	if (unlikely(!len)) {
1943f9f0aa6SLinus Torvalds 		if (empty)
1951fa1e7f6SAndy Whitcroft 			*empty = 1;
19694b5d262SAl Viro 		if (!(flags & LOOKUP_EMPTY)) {
19794b5d262SAl Viro 			putname(result);
19894b5d262SAl Viro 			return ERR_PTR(-ENOENT);
1991da177e4SLinus Torvalds 		}
20094b5d262SAl Viro 	}
2017950e385SJeff Layton 
2027950e385SJeff Layton 	result->uptr = filename;
203c4ad8f98SLinus Torvalds 	result->aname = NULL;
2041da177e4SLinus Torvalds 	audit_getname(result);
2051da177e4SLinus Torvalds 	return result;
2063f9f0aa6SLinus Torvalds }
2073f9f0aa6SLinus Torvalds 
20891a27b2aSJeff Layton struct filename *
2098228e2c3SDmitry Kadashev getname_uflags(const char __user *filename, int uflags)
2108228e2c3SDmitry Kadashev {
2118228e2c3SDmitry Kadashev 	int flags = (uflags & AT_EMPTY_PATH) ? LOOKUP_EMPTY : 0;
2128228e2c3SDmitry Kadashev 
2138228e2c3SDmitry Kadashev 	return getname_flags(filename, flags, NULL);
2148228e2c3SDmitry Kadashev }
2158228e2c3SDmitry Kadashev 
2168228e2c3SDmitry Kadashev struct filename *
21791a27b2aSJeff Layton getname(const char __user * filename)
218f52e0c11SAl Viro {
219f7493e5dSLinus Torvalds 	return getname_flags(filename, 0, NULL);
220f52e0c11SAl Viro }
221f52e0c11SAl Viro 
222c4ad8f98SLinus Torvalds struct filename *
223c4ad8f98SLinus Torvalds getname_kernel(const char * filename)
224c4ad8f98SLinus Torvalds {
225c4ad8f98SLinus Torvalds 	struct filename *result;
22608518549SPaul Moore 	int len = strlen(filename) + 1;
227c4ad8f98SLinus Torvalds 
228c4ad8f98SLinus Torvalds 	result = __getname();
229c4ad8f98SLinus Torvalds 	if (unlikely(!result))
230c4ad8f98SLinus Torvalds 		return ERR_PTR(-ENOMEM);
231c4ad8f98SLinus Torvalds 
23208518549SPaul Moore 	if (len <= EMBEDDED_NAME_MAX) {
233fd2f7cb5SAl Viro 		result->name = (char *)result->iname;
23408518549SPaul Moore 	} else if (len <= PATH_MAX) {
23530ce4d19SAl Viro 		const size_t size = offsetof(struct filename, iname[1]);
23608518549SPaul Moore 		struct filename *tmp;
23708518549SPaul Moore 
23830ce4d19SAl Viro 		tmp = kmalloc(size, GFP_KERNEL);
23908518549SPaul Moore 		if (unlikely(!tmp)) {
24008518549SPaul Moore 			__putname(result);
24108518549SPaul Moore 			return ERR_PTR(-ENOMEM);
24208518549SPaul Moore 		}
24308518549SPaul Moore 		tmp->name = (char *)result;
24408518549SPaul Moore 		result = tmp;
24508518549SPaul Moore 	} else {
24608518549SPaul Moore 		__putname(result);
24708518549SPaul Moore 		return ERR_PTR(-ENAMETOOLONG);
24808518549SPaul Moore 	}
24908518549SPaul Moore 	memcpy((char *)result->name, filename, len);
250c4ad8f98SLinus Torvalds 	result->uptr = NULL;
251c4ad8f98SLinus Torvalds 	result->aname = NULL;
25255422d0bSPaul Moore 	result->refcnt = 1;
253fd3522fdSPaul Moore 	audit_getname(result);
254c4ad8f98SLinus Torvalds 
255c4ad8f98SLinus Torvalds 	return result;
256c4ad8f98SLinus Torvalds }
25774d7970fSNamjae Jeon EXPORT_SYMBOL(getname_kernel);
258c4ad8f98SLinus Torvalds 
25991a27b2aSJeff Layton void putname(struct filename *name)
2601da177e4SLinus Torvalds {
261ea47ab11SAl Viro 	if (IS_ERR(name))
26291ef658fSDmitry Kadashev 		return;
26391ef658fSDmitry Kadashev 
26455422d0bSPaul Moore 	BUG_ON(name->refcnt <= 0);
26555422d0bSPaul Moore 
26655422d0bSPaul Moore 	if (--name->refcnt > 0)
26755422d0bSPaul Moore 		return;
26855422d0bSPaul Moore 
269fd2f7cb5SAl Viro 	if (name->name != name->iname) {
27055422d0bSPaul Moore 		__putname(name->name);
27155422d0bSPaul Moore 		kfree(name);
27255422d0bSPaul Moore 	} else
27355422d0bSPaul Moore 		__putname(name);
2741da177e4SLinus Torvalds }
27574d7970fSNamjae Jeon EXPORT_SYMBOL(putname);
2761da177e4SLinus Torvalds 
27747291baaSChristian Brauner /**
27847291baaSChristian Brauner  * check_acl - perform ACL permission checking
279700b7940SChristian Brauner  * @idmap:	idmap of the mount the inode was found from
28047291baaSChristian Brauner  * @inode:	inode to check permissions on
28147291baaSChristian Brauner  * @mask:	right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
28247291baaSChristian Brauner  *
28347291baaSChristian Brauner  * This function performs the ACL permission checking. Since this function
28447291baaSChristian Brauner  * retrieve POSIX acls it needs to know whether it is called from a blocking or
28547291baaSChristian Brauner  * non-blocking context and thus cares about the MAY_NOT_BLOCK bit.
28647291baaSChristian Brauner  *
287700b7940SChristian Brauner  * If the inode has been found through an idmapped mount the idmap of
288700b7940SChristian Brauner  * the vfsmount must be passed through @idmap. This function will then take
289700b7940SChristian Brauner  * care to map the inode according to @idmap before checking permissions.
29047291baaSChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
291700b7940SChristian Brauner  * raw inode simply passs @nop_mnt_idmap.
29247291baaSChristian Brauner  */
293700b7940SChristian Brauner static int check_acl(struct mnt_idmap *idmap,
29447291baaSChristian Brauner 		     struct inode *inode, int mask)
295e77819e5SLinus Torvalds {
29684635d68SLinus Torvalds #ifdef CONFIG_FS_POSIX_ACL
297e77819e5SLinus Torvalds 	struct posix_acl *acl;
298e77819e5SLinus Torvalds 
299e77819e5SLinus Torvalds 	if (mask & MAY_NOT_BLOCK) {
3003567866bSAl Viro 		acl = get_cached_acl_rcu(inode, ACL_TYPE_ACCESS);
3013567866bSAl Viro 	        if (!acl)
302e77819e5SLinus Torvalds 	                return -EAGAIN;
303cac2f8b8SChristian Brauner 		/* no ->get_inode_acl() calls in RCU mode... */
304b8a7a3a6SAndreas Gruenbacher 		if (is_uncached_acl(acl))
305e77819e5SLinus Torvalds 			return -ECHILD;
306700b7940SChristian Brauner 	        return posix_acl_permission(idmap, inode, acl, mask);
307e77819e5SLinus Torvalds 	}
308e77819e5SLinus Torvalds 
309cac2f8b8SChristian Brauner 	acl = get_inode_acl(inode, ACL_TYPE_ACCESS);
3104e34e719SChristoph Hellwig 	if (IS_ERR(acl))
3114e34e719SChristoph Hellwig 		return PTR_ERR(acl);
312e77819e5SLinus Torvalds 	if (acl) {
313700b7940SChristian Brauner 	        int error = posix_acl_permission(idmap, inode, acl, mask);
314e77819e5SLinus Torvalds 	        posix_acl_release(acl);
315e77819e5SLinus Torvalds 	        return error;
316e77819e5SLinus Torvalds 	}
31784635d68SLinus Torvalds #endif
318e77819e5SLinus Torvalds 
319e77819e5SLinus Torvalds 	return -EAGAIN;
320e77819e5SLinus Torvalds }
321e77819e5SLinus Torvalds 
32247291baaSChristian Brauner /**
32347291baaSChristian Brauner  * acl_permission_check - perform basic UNIX permission checking
324700b7940SChristian Brauner  * @idmap:	idmap of the mount the inode was found from
32547291baaSChristian Brauner  * @inode:	inode to check permissions on
32647291baaSChristian Brauner  * @mask:	right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
3275fc475b7SLinus Torvalds  *
32847291baaSChristian Brauner  * This function performs the basic UNIX permission checking. Since this
32947291baaSChristian Brauner  * function may retrieve POSIX acls it needs to know whether it is called from a
33047291baaSChristian Brauner  * blocking or non-blocking context and thus cares about the MAY_NOT_BLOCK bit.
33147291baaSChristian Brauner  *
332700b7940SChristian Brauner  * If the inode has been found through an idmapped mount the idmap of
333700b7940SChristian Brauner  * the vfsmount must be passed through @idmap. This function will then take
334700b7940SChristian Brauner  * care to map the inode according to @idmap before checking permissions.
33547291baaSChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
336700b7940SChristian Brauner  * raw inode simply passs @nop_mnt_idmap.
3375909ccaaSLinus Torvalds  */
338700b7940SChristian Brauner static int acl_permission_check(struct mnt_idmap *idmap,
33947291baaSChristian Brauner 				struct inode *inode, int mask)
3405909ccaaSLinus Torvalds {
34126cf46beSLinus Torvalds 	unsigned int mode = inode->i_mode;
342a2bd096fSChristian Brauner 	vfsuid_t vfsuid;
3435909ccaaSLinus Torvalds 
3445fc475b7SLinus Torvalds 	/* Are we the owner? If so, ACL's don't matter */
345e67fe633SChristian Brauner 	vfsuid = i_uid_into_vfsuid(idmap, inode);
346a2bd096fSChristian Brauner 	if (likely(vfsuid_eq_kuid(vfsuid, current_fsuid()))) {
3475fc475b7SLinus Torvalds 		mask &= 7;
3485909ccaaSLinus Torvalds 		mode >>= 6;
3495fc475b7SLinus Torvalds 		return (mask & ~mode) ? -EACCES : 0;
3505fc475b7SLinus Torvalds 	}
3515fc475b7SLinus Torvalds 
3525fc475b7SLinus Torvalds 	/* Do we have ACL's? */
353e77819e5SLinus Torvalds 	if (IS_POSIXACL(inode) && (mode & S_IRWXG)) {
354700b7940SChristian Brauner 		int error = check_acl(idmap, inode, mask);
3555909ccaaSLinus Torvalds 		if (error != -EAGAIN)
3565909ccaaSLinus Torvalds 			return error;
3575909ccaaSLinus Torvalds 	}
3585909ccaaSLinus Torvalds 
3595fc475b7SLinus Torvalds 	/* Only RWX matters for group/other mode bits */
3605fc475b7SLinus Torvalds 	mask &= 7;
3615fc475b7SLinus Torvalds 
3625fc475b7SLinus Torvalds 	/*
3635fc475b7SLinus Torvalds 	 * Are the group permissions different from
3645fc475b7SLinus Torvalds 	 * the other permissions in the bits we care
3655fc475b7SLinus Torvalds 	 * about? Need to check group ownership if so.
3665fc475b7SLinus Torvalds 	 */
3675fc475b7SLinus Torvalds 	if (mask & (mode ^ (mode >> 3))) {
368e67fe633SChristian Brauner 		vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
369a2bd096fSChristian Brauner 		if (vfsgid_in_group_p(vfsgid))
3705909ccaaSLinus Torvalds 			mode >>= 3;
3715909ccaaSLinus Torvalds 	}
3725909ccaaSLinus Torvalds 
3735fc475b7SLinus Torvalds 	/* Bits in 'mode' clear that we require? */
3745fc475b7SLinus Torvalds 	return (mask & ~mode) ? -EACCES : 0;
3755909ccaaSLinus Torvalds }
3761da177e4SLinus Torvalds 
3771da177e4SLinus Torvalds /**
3781da177e4SLinus Torvalds  * generic_permission -  check for access rights on a Posix-like filesystem
3794609e1f1SChristian Brauner  * @idmap:	idmap of the mount the inode was found from
3801da177e4SLinus Torvalds  * @inode:	inode to check access rights for
3815fc475b7SLinus Torvalds  * @mask:	right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC,
3825fc475b7SLinus Torvalds  *		%MAY_NOT_BLOCK ...)
3831da177e4SLinus Torvalds  *
3841da177e4SLinus Torvalds  * Used to check for read/write/execute permissions on a file.
3851da177e4SLinus Torvalds  * We use "fsuid" for this, letting us set arbitrary permissions
3861da177e4SLinus Torvalds  * for filesystem access without changing the "normal" uids which
387b74c79e9SNick Piggin  * are used for other things.
388b74c79e9SNick Piggin  *
389b74c79e9SNick Piggin  * generic_permission is rcu-walk aware. It returns -ECHILD in case an rcu-walk
390b74c79e9SNick Piggin  * request cannot be satisfied (eg. requires blocking or too much complexity).
391b74c79e9SNick Piggin  * It would then be called again in ref-walk mode.
39247291baaSChristian Brauner  *
3934609e1f1SChristian Brauner  * If the inode has been found through an idmapped mount the idmap of
3944609e1f1SChristian Brauner  * the vfsmount must be passed through @idmap. This function will then take
3954609e1f1SChristian Brauner  * care to map the inode according to @idmap before checking permissions.
39647291baaSChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
3974609e1f1SChristian Brauner  * raw inode simply passs @nop_mnt_idmap.
3981da177e4SLinus Torvalds  */
3994609e1f1SChristian Brauner int generic_permission(struct mnt_idmap *idmap, struct inode *inode,
40047291baaSChristian Brauner 		       int mask)
4011da177e4SLinus Torvalds {
4025909ccaaSLinus Torvalds 	int ret;
4031da177e4SLinus Torvalds 
4041da177e4SLinus Torvalds 	/*
405948409c7SAndreas Gruenbacher 	 * Do the basic permission checks.
4061da177e4SLinus Torvalds 	 */
407700b7940SChristian Brauner 	ret = acl_permission_check(idmap, inode, mask);
4085909ccaaSLinus Torvalds 	if (ret != -EACCES)
4095909ccaaSLinus Torvalds 		return ret;
4101da177e4SLinus Torvalds 
411d594e7ecSAl Viro 	if (S_ISDIR(inode->i_mode)) {
412d594e7ecSAl Viro 		/* DACs are overridable for directories */
413d594e7ecSAl Viro 		if (!(mask & MAY_WRITE))
4149452e93eSChristian Brauner 			if (capable_wrt_inode_uidgid(idmap, inode,
41523adbe12SAndy Lutomirski 						     CAP_DAC_READ_SEARCH))
416d594e7ecSAl Viro 				return 0;
4179452e93eSChristian Brauner 		if (capable_wrt_inode_uidgid(idmap, inode,
4180558c1bfSChristian Brauner 					     CAP_DAC_OVERRIDE))
4191da177e4SLinus Torvalds 			return 0;
4202a4c2242SStephen Smalley 		return -EACCES;
4212a4c2242SStephen Smalley 	}
4221da177e4SLinus Torvalds 
4231da177e4SLinus Torvalds 	/*
4241da177e4SLinus Torvalds 	 * Searching includes executable on directories, else just read.
4251da177e4SLinus Torvalds 	 */
4267ea66001SSerge E. Hallyn 	mask &= MAY_READ | MAY_WRITE | MAY_EXEC;
427d594e7ecSAl Viro 	if (mask == MAY_READ)
4289452e93eSChristian Brauner 		if (capable_wrt_inode_uidgid(idmap, inode,
4290558c1bfSChristian Brauner 					     CAP_DAC_READ_SEARCH))
4301da177e4SLinus Torvalds 			return 0;
4312a4c2242SStephen Smalley 	/*
4322a4c2242SStephen Smalley 	 * Read/write DACs are always overridable.
4332a4c2242SStephen Smalley 	 * Executable DACs are overridable when there is
4342a4c2242SStephen Smalley 	 * at least one exec bit set.
4352a4c2242SStephen Smalley 	 */
4362a4c2242SStephen Smalley 	if (!(mask & MAY_EXEC) || (inode->i_mode & S_IXUGO))
4379452e93eSChristian Brauner 		if (capable_wrt_inode_uidgid(idmap, inode,
4380558c1bfSChristian Brauner 					     CAP_DAC_OVERRIDE))
4392a4c2242SStephen Smalley 			return 0;
4401da177e4SLinus Torvalds 
4411da177e4SLinus Torvalds 	return -EACCES;
4421da177e4SLinus Torvalds }
4434d359507SAl Viro EXPORT_SYMBOL(generic_permission);
4441da177e4SLinus Torvalds 
44547291baaSChristian Brauner /**
44647291baaSChristian Brauner  * do_inode_permission - UNIX permission checking
4474609e1f1SChristian Brauner  * @idmap:	idmap of the mount the inode was found from
44847291baaSChristian Brauner  * @inode:	inode to check permissions on
44947291baaSChristian Brauner  * @mask:	right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
45047291baaSChristian Brauner  *
4513ddcd056SLinus Torvalds  * We _really_ want to just do "generic_permission()" without
4523ddcd056SLinus Torvalds  * even looking at the inode->i_op values. So we keep a cache
4533ddcd056SLinus Torvalds  * flag in inode->i_opflags, that says "this has not special
4543ddcd056SLinus Torvalds  * permission function, use the fast case".
4553ddcd056SLinus Torvalds  */
4564609e1f1SChristian Brauner static inline int do_inode_permission(struct mnt_idmap *idmap,
45747291baaSChristian Brauner 				      struct inode *inode, int mask)
4583ddcd056SLinus Torvalds {
4593ddcd056SLinus Torvalds 	if (unlikely(!(inode->i_opflags & IOP_FASTPERM))) {
4603ddcd056SLinus Torvalds 		if (likely(inode->i_op->permission))
4614609e1f1SChristian Brauner 			return inode->i_op->permission(idmap, inode, mask);
4623ddcd056SLinus Torvalds 
4633ddcd056SLinus Torvalds 		/* This gets set once for the inode lifetime */
4643ddcd056SLinus Torvalds 		spin_lock(&inode->i_lock);
4653ddcd056SLinus Torvalds 		inode->i_opflags |= IOP_FASTPERM;
4663ddcd056SLinus Torvalds 		spin_unlock(&inode->i_lock);
4673ddcd056SLinus Torvalds 	}
4684609e1f1SChristian Brauner 	return generic_permission(idmap, inode, mask);
4693ddcd056SLinus Torvalds }
4703ddcd056SLinus Torvalds 
471cb23beb5SChristoph Hellwig /**
4720bdaea90SDavid Howells  * sb_permission - Check superblock-level permissions
4730bdaea90SDavid Howells  * @sb: Superblock of inode to check permission on
47455852635SRandy Dunlap  * @inode: Inode to check permission on
4750bdaea90SDavid Howells  * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
4760bdaea90SDavid Howells  *
4770bdaea90SDavid Howells  * Separate out file-system wide checks from inode-specific permission checks.
4780bdaea90SDavid Howells  */
4790bdaea90SDavid Howells static int sb_permission(struct super_block *sb, struct inode *inode, int mask)
4800bdaea90SDavid Howells {
4810bdaea90SDavid Howells 	if (unlikely(mask & MAY_WRITE)) {
4820bdaea90SDavid Howells 		umode_t mode = inode->i_mode;
4830bdaea90SDavid Howells 
4840bdaea90SDavid Howells 		/* Nobody gets write access to a read-only fs. */
485bc98a42cSDavid Howells 		if (sb_rdonly(sb) && (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode)))
4860bdaea90SDavid Howells 			return -EROFS;
4870bdaea90SDavid Howells 	}
4880bdaea90SDavid Howells 	return 0;
4890bdaea90SDavid Howells }
4900bdaea90SDavid Howells 
4910bdaea90SDavid Howells /**
4920bdaea90SDavid Howells  * inode_permission - Check for access rights to a given inode
4934609e1f1SChristian Brauner  * @idmap:	idmap of the mount the inode was found from
4940bdaea90SDavid Howells  * @inode:	Inode to check permission on
4950bdaea90SDavid Howells  * @mask:	Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
4960bdaea90SDavid Howells  *
4970bdaea90SDavid Howells  * Check for read/write/execute permissions on an inode.  We use fs[ug]id for
4980bdaea90SDavid Howells  * this, letting us set arbitrary permissions for filesystem access without
4990bdaea90SDavid Howells  * changing the "normal" UIDs which are used for other things.
5000bdaea90SDavid Howells  *
5010bdaea90SDavid Howells  * When checking for MAY_APPEND, MAY_WRITE must also be set in @mask.
5020bdaea90SDavid Howells  */
5034609e1f1SChristian Brauner int inode_permission(struct mnt_idmap *idmap,
50447291baaSChristian Brauner 		     struct inode *inode, int mask)
5050bdaea90SDavid Howells {
5060bdaea90SDavid Howells 	int retval;
5070bdaea90SDavid Howells 
5080bdaea90SDavid Howells 	retval = sb_permission(inode->i_sb, inode, mask);
5090bdaea90SDavid Howells 	if (retval)
5100bdaea90SDavid Howells 		return retval;
5114bfd054aSEric Biggers 
5124bfd054aSEric Biggers 	if (unlikely(mask & MAY_WRITE)) {
5134bfd054aSEric Biggers 		/*
5144bfd054aSEric Biggers 		 * Nobody gets write access to an immutable file.
5154bfd054aSEric Biggers 		 */
5164bfd054aSEric Biggers 		if (IS_IMMUTABLE(inode))
5174bfd054aSEric Biggers 			return -EPERM;
5184bfd054aSEric Biggers 
5194bfd054aSEric Biggers 		/*
5204bfd054aSEric Biggers 		 * Updating mtime will likely cause i_uid and i_gid to be
5214bfd054aSEric Biggers 		 * written back improperly if their true value is unknown
5224bfd054aSEric Biggers 		 * to the vfs.
5234bfd054aSEric Biggers 		 */
5244609e1f1SChristian Brauner 		if (HAS_UNMAPPED_ID(idmap, inode))
5254bfd054aSEric Biggers 			return -EACCES;
5264bfd054aSEric Biggers 	}
5274bfd054aSEric Biggers 
5284609e1f1SChristian Brauner 	retval = do_inode_permission(idmap, inode, mask);
5294bfd054aSEric Biggers 	if (retval)
5304bfd054aSEric Biggers 		return retval;
5314bfd054aSEric Biggers 
5324bfd054aSEric Biggers 	retval = devcgroup_inode_permission(inode, mask);
5334bfd054aSEric Biggers 	if (retval)
5344bfd054aSEric Biggers 		return retval;
5354bfd054aSEric Biggers 
5364bfd054aSEric Biggers 	return security_inode_permission(inode, mask);
5370bdaea90SDavid Howells }
5384d359507SAl Viro EXPORT_SYMBOL(inode_permission);
5390bdaea90SDavid Howells 
5400bdaea90SDavid Howells /**
5415dd784d0SJan Blunck  * path_get - get a reference to a path
5425dd784d0SJan Blunck  * @path: path to get the reference to
5435dd784d0SJan Blunck  *
5445dd784d0SJan Blunck  * Given a path increment the reference count to the dentry and the vfsmount.
5455dd784d0SJan Blunck  */
546dcf787f3SAl Viro void path_get(const struct path *path)
5475dd784d0SJan Blunck {
5485dd784d0SJan Blunck 	mntget(path->mnt);
5495dd784d0SJan Blunck 	dget(path->dentry);
5505dd784d0SJan Blunck }
5515dd784d0SJan Blunck EXPORT_SYMBOL(path_get);
5525dd784d0SJan Blunck 
5535dd784d0SJan Blunck /**
5541d957f9bSJan Blunck  * path_put - put a reference to a path
5551d957f9bSJan Blunck  * @path: path to put the reference to
5561d957f9bSJan Blunck  *
5571d957f9bSJan Blunck  * Given a path decrement the reference count to the dentry and the vfsmount.
5581d957f9bSJan Blunck  */
559dcf787f3SAl Viro void path_put(const struct path *path)
5601da177e4SLinus Torvalds {
5611d957f9bSJan Blunck 	dput(path->dentry);
5621d957f9bSJan Blunck 	mntput(path->mnt);
5631da177e4SLinus Torvalds }
5641d957f9bSJan Blunck EXPORT_SYMBOL(path_put);
5651da177e4SLinus Torvalds 
566894bc8c4SAl Viro #define EMBEDDED_LEVELS 2
5671f55a6ecSAl Viro struct nameidata {
5681f55a6ecSAl Viro 	struct path	path;
5691f55a6ecSAl Viro 	struct qstr	last;
5701f55a6ecSAl Viro 	struct path	root;
5711f55a6ecSAl Viro 	struct inode	*inode; /* path.dentry.d_inode */
572bcba1e7dSAl Viro 	unsigned int	flags, state;
57303fa86e9SAl Viro 	unsigned	seq, next_seq, m_seq, r_seq;
5741f55a6ecSAl Viro 	int		last_type;
5751f55a6ecSAl Viro 	unsigned	depth;
576756daf26SNeilBrown 	int		total_link_count;
577697fc6caSAl Viro 	struct saved {
578697fc6caSAl Viro 		struct path link;
579fceef393SAl Viro 		struct delayed_call done;
580697fc6caSAl Viro 		const char *name;
5810450b2d1SAl Viro 		unsigned seq;
582894bc8c4SAl Viro 	} *stack, internal[EMBEDDED_LEVELS];
5839883d185SAl Viro 	struct filename	*name;
5849883d185SAl Viro 	struct nameidata *saved;
5859883d185SAl Viro 	unsigned	root_seq;
5869883d185SAl Viro 	int		dfd;
587a2bd096fSChristian Brauner 	vfsuid_t	dir_vfsuid;
5880f705953SAl Viro 	umode_t		dir_mode;
5893859a271SKees Cook } __randomize_layout;
5901f55a6ecSAl Viro 
591bcba1e7dSAl Viro #define ND_ROOT_PRESET 1
592bcba1e7dSAl Viro #define ND_ROOT_GRABBED 2
593bcba1e7dSAl Viro #define ND_JUMPED 4
594bcba1e7dSAl Viro 
59506422964SAl Viro static void __set_nameidata(struct nameidata *p, int dfd, struct filename *name)
596894bc8c4SAl Viro {
597756daf26SNeilBrown 	struct nameidata *old = current->nameidata;
598756daf26SNeilBrown 	p->stack = p->internal;
5997962c7d1SAl Viro 	p->depth = 0;
600c8a53ee5SAl Viro 	p->dfd = dfd;
601c8a53ee5SAl Viro 	p->name = name;
6027d01ef75SAl Viro 	p->path.mnt = NULL;
6037d01ef75SAl Viro 	p->path.dentry = NULL;
604756daf26SNeilBrown 	p->total_link_count = old ? old->total_link_count : 0;
6059883d185SAl Viro 	p->saved = old;
606756daf26SNeilBrown 	current->nameidata = p;
607894bc8c4SAl Viro }
608894bc8c4SAl Viro 
60906422964SAl Viro static inline void set_nameidata(struct nameidata *p, int dfd, struct filename *name,
61006422964SAl Viro 			  const struct path *root)
61106422964SAl Viro {
61206422964SAl Viro 	__set_nameidata(p, dfd, name);
61306422964SAl Viro 	p->state = 0;
61406422964SAl Viro 	if (unlikely(root)) {
61506422964SAl Viro 		p->state = ND_ROOT_PRESET;
61606422964SAl Viro 		p->root = *root;
61706422964SAl Viro 	}
61806422964SAl Viro }
61906422964SAl Viro 
6209883d185SAl Viro static void restore_nameidata(void)
621894bc8c4SAl Viro {
6229883d185SAl Viro 	struct nameidata *now = current->nameidata, *old = now->saved;
623756daf26SNeilBrown 
624756daf26SNeilBrown 	current->nameidata = old;
625756daf26SNeilBrown 	if (old)
626756daf26SNeilBrown 		old->total_link_count = now->total_link_count;
627e1a63bbcSAl Viro 	if (now->stack != now->internal)
628756daf26SNeilBrown 		kfree(now->stack);
629894bc8c4SAl Viro }
630894bc8c4SAl Viro 
63160ef60c7SAl Viro static bool nd_alloc_stack(struct nameidata *nd)
632894bc8c4SAl Viro {
633bc40aee0SAl Viro 	struct saved *p;
634bc40aee0SAl Viro 
6356da2ec56SKees Cook 	p= kmalloc_array(MAXSYMLINKS, sizeof(struct saved),
63660ef60c7SAl Viro 			 nd->flags & LOOKUP_RCU ? GFP_ATOMIC : GFP_KERNEL);
637bc40aee0SAl Viro 	if (unlikely(!p))
63860ef60c7SAl Viro 		return false;
639894bc8c4SAl Viro 	memcpy(p, nd->internal, sizeof(nd->internal));
640894bc8c4SAl Viro 	nd->stack = p;
64160ef60c7SAl Viro 	return true;
642894bc8c4SAl Viro }
643894bc8c4SAl Viro 
644397d425dSEric W. Biederman /**
6456b03f7edSAl Viro  * path_connected - Verify that a dentry is below mnt.mnt_root
646*35931eb3SMatthew Wilcox (Oracle)  * @mnt: The mountpoint to check.
647*35931eb3SMatthew Wilcox (Oracle)  * @dentry: The dentry to check.
648397d425dSEric W. Biederman  *
649397d425dSEric W. Biederman  * Rename can sometimes move a file or directory outside of a bind
650397d425dSEric W. Biederman  * mount, path_connected allows those cases to be detected.
651397d425dSEric W. Biederman  */
6526b03f7edSAl Viro static bool path_connected(struct vfsmount *mnt, struct dentry *dentry)
653397d425dSEric W. Biederman {
65495dd7758SEric W. Biederman 	struct super_block *sb = mnt->mnt_sb;
655397d425dSEric W. Biederman 
656402dd2cfSChristoph Hellwig 	/* Bind mounts can have disconnected paths */
657402dd2cfSChristoph Hellwig 	if (mnt->mnt_root == sb->s_root)
658397d425dSEric W. Biederman 		return true;
659397d425dSEric W. Biederman 
6606b03f7edSAl Viro 	return is_subdir(dentry, mnt->mnt_root);
661397d425dSEric W. Biederman }
662397d425dSEric W. Biederman 
6637973387aSAl Viro static void drop_links(struct nameidata *nd)
6647973387aSAl Viro {
6657973387aSAl Viro 	int i = nd->depth;
6667973387aSAl Viro 	while (i--) {
6677973387aSAl Viro 		struct saved *last = nd->stack + i;
668fceef393SAl Viro 		do_delayed_call(&last->done);
669fceef393SAl Viro 		clear_delayed_call(&last->done);
6707973387aSAl Viro 	}
6717973387aSAl Viro }
6727973387aSAl Viro 
6736e180327SAl Viro static void leave_rcu(struct nameidata *nd)
6746e180327SAl Viro {
6756e180327SAl Viro 	nd->flags &= ~LOOKUP_RCU;
67603fa86e9SAl Viro 	nd->seq = nd->next_seq = 0;
6776e180327SAl Viro 	rcu_read_unlock();
6786e180327SAl Viro }
6796e180327SAl Viro 
6807973387aSAl Viro static void terminate_walk(struct nameidata *nd)
6817973387aSAl Viro {
6827973387aSAl Viro 	drop_links(nd);
6837973387aSAl Viro 	if (!(nd->flags & LOOKUP_RCU)) {
6847973387aSAl Viro 		int i;
6857973387aSAl Viro 		path_put(&nd->path);
6867973387aSAl Viro 		for (i = 0; i < nd->depth; i++)
6877973387aSAl Viro 			path_put(&nd->stack[i].link);
688bcba1e7dSAl Viro 		if (nd->state & ND_ROOT_GRABBED) {
689102b8af2SAl Viro 			path_put(&nd->root);
690bcba1e7dSAl Viro 			nd->state &= ~ND_ROOT_GRABBED;
691102b8af2SAl Viro 		}
6927973387aSAl Viro 	} else {
6936e180327SAl Viro 		leave_rcu(nd);
6947973387aSAl Viro 	}
6957973387aSAl Viro 	nd->depth = 0;
6967d01ef75SAl Viro 	nd->path.mnt = NULL;
6977d01ef75SAl Viro 	nd->path.dentry = NULL;
6987973387aSAl Viro }
6997973387aSAl Viro 
7007973387aSAl Viro /* path_put is needed afterwards regardless of success or failure */
7012aa38470SAl Viro static bool __legitimize_path(struct path *path, unsigned seq, unsigned mseq)
7027973387aSAl Viro {
7032aa38470SAl Viro 	int res = __legitimize_mnt(path->mnt, mseq);
7047973387aSAl Viro 	if (unlikely(res)) {
7057973387aSAl Viro 		if (res > 0)
7067973387aSAl Viro 			path->mnt = NULL;
7077973387aSAl Viro 		path->dentry = NULL;
7087973387aSAl Viro 		return false;
7097973387aSAl Viro 	}
7107973387aSAl Viro 	if (unlikely(!lockref_get_not_dead(&path->dentry->d_lockref))) {
7117973387aSAl Viro 		path->dentry = NULL;
7127973387aSAl Viro 		return false;
7137973387aSAl Viro 	}
7147973387aSAl Viro 	return !read_seqcount_retry(&path->dentry->d_seq, seq);
7157973387aSAl Viro }
7167973387aSAl Viro 
7172aa38470SAl Viro static inline bool legitimize_path(struct nameidata *nd,
7182aa38470SAl Viro 			    struct path *path, unsigned seq)
7192aa38470SAl Viro {
7205bd73286SAl Viro 	return __legitimize_path(path, seq, nd->m_seq);
7212aa38470SAl Viro }
7222aa38470SAl Viro 
7237973387aSAl Viro static bool legitimize_links(struct nameidata *nd)
7247973387aSAl Viro {
7257973387aSAl Viro 	int i;
726eacd9aa8SAl Viro 	if (unlikely(nd->flags & LOOKUP_CACHED)) {
727eacd9aa8SAl Viro 		drop_links(nd);
728eacd9aa8SAl Viro 		nd->depth = 0;
729eacd9aa8SAl Viro 		return false;
730eacd9aa8SAl Viro 	}
7317973387aSAl Viro 	for (i = 0; i < nd->depth; i++) {
7327973387aSAl Viro 		struct saved *last = nd->stack + i;
7337973387aSAl Viro 		if (unlikely(!legitimize_path(nd, &last->link, last->seq))) {
7347973387aSAl Viro 			drop_links(nd);
7357973387aSAl Viro 			nd->depth = i + 1;
7367973387aSAl Viro 			return false;
7377973387aSAl Viro 		}
7387973387aSAl Viro 	}
7397973387aSAl Viro 	return true;
7407973387aSAl Viro }
7417973387aSAl Viro 
742ee594bffSAl Viro static bool legitimize_root(struct nameidata *nd)
743ee594bffSAl Viro {
744adb21d2bSAleksa Sarai 	/* Nothing to do if nd->root is zero or is managed by the VFS user. */
745bcba1e7dSAl Viro 	if (!nd->root.mnt || (nd->state & ND_ROOT_PRESET))
746ee594bffSAl Viro 		return true;
747bcba1e7dSAl Viro 	nd->state |= ND_ROOT_GRABBED;
748ee594bffSAl Viro 	return legitimize_path(nd, &nd->root, nd->root_seq);
749ee594bffSAl Viro }
750ee594bffSAl Viro 
75119660af7SAl Viro /*
75231e6b01fSNick Piggin  * Path walking has 2 modes, rcu-walk and ref-walk (see
75319660af7SAl Viro  * Documentation/filesystems/path-lookup.txt).  In situations when we can't
75419660af7SAl Viro  * continue in RCU mode, we attempt to drop out of rcu-walk mode and grab
75557e3715cSMike Marshall  * normal reference counts on dentries and vfsmounts to transition to ref-walk
75619660af7SAl Viro  * mode.  Refcounts are grabbed at the last known good point before rcu-walk
75719660af7SAl Viro  * got stuck, so ref-walk may continue from there. If this is not successful
75819660af7SAl Viro  * (eg. a seqcount has changed), then failure is returned and it's up to caller
75919660af7SAl Viro  * to restart the path walk from the beginning in ref-walk mode.
76031e6b01fSNick Piggin  */
76131e6b01fSNick Piggin 
76231e6b01fSNick Piggin /**
763e36cffedSJens Axboe  * try_to_unlazy - try to switch to ref-walk mode.
76419660af7SAl Viro  * @nd: nameidata pathwalk data
765e36cffedSJens Axboe  * Returns: true on success, false on failure
76631e6b01fSNick Piggin  *
767e36cffedSJens Axboe  * try_to_unlazy attempts to legitimize the current nd->path and nd->root
7684675ac39SAl Viro  * for ref-walk mode.
7694675ac39SAl Viro  * Must be called from rcu-walk context.
770e36cffedSJens Axboe  * Nothing should touch nameidata between try_to_unlazy() failure and
7717973387aSAl Viro  * terminate_walk().
77231e6b01fSNick Piggin  */
773e36cffedSJens Axboe static bool try_to_unlazy(struct nameidata *nd)
77431e6b01fSNick Piggin {
77531e6b01fSNick Piggin 	struct dentry *parent = nd->path.dentry;
77631e6b01fSNick Piggin 
77731e6b01fSNick Piggin 	BUG_ON(!(nd->flags & LOOKUP_RCU));
778e5c832d5SLinus Torvalds 
7797973387aSAl Viro 	if (unlikely(!legitimize_links(nd)))
7804675ac39SAl Viro 		goto out1;
78184a2bd39SAl Viro 	if (unlikely(!legitimize_path(nd, &nd->path, nd->seq)))
78284a2bd39SAl Viro 		goto out;
783ee594bffSAl Viro 	if (unlikely(!legitimize_root(nd)))
7844675ac39SAl Viro 		goto out;
7856e180327SAl Viro 	leave_rcu(nd);
7864675ac39SAl Viro 	BUG_ON(nd->inode != parent->d_inode);
787e36cffedSJens Axboe 	return true;
7884675ac39SAl Viro 
78984a2bd39SAl Viro out1:
7904675ac39SAl Viro 	nd->path.mnt = NULL;
7914675ac39SAl Viro 	nd->path.dentry = NULL;
7924675ac39SAl Viro out:
7936e180327SAl Viro 	leave_rcu(nd);
794e36cffedSJens Axboe 	return false;
7954675ac39SAl Viro }
7964675ac39SAl Viro 
7974675ac39SAl Viro /**
798ae66db45SAl Viro  * try_to_unlazy_next - try to switch to ref-walk mode.
7994675ac39SAl Viro  * @nd: nameidata pathwalk data
800ae66db45SAl Viro  * @dentry: next dentry to step into
801ae66db45SAl Viro  * Returns: true on success, false on failure
8024675ac39SAl Viro  *
80330476f7eSTom Rix  * Similar to try_to_unlazy(), but here we have the next dentry already
804ae66db45SAl Viro  * picked by rcu-walk and want to legitimize that in addition to the current
805ae66db45SAl Viro  * nd->path and nd->root for ref-walk mode.  Must be called from rcu-walk context.
806ae66db45SAl Viro  * Nothing should touch nameidata between try_to_unlazy_next() failure and
8074675ac39SAl Viro  * terminate_walk().
8084675ac39SAl Viro  */
80903fa86e9SAl Viro static bool try_to_unlazy_next(struct nameidata *nd, struct dentry *dentry)
8104675ac39SAl Viro {
8117e4745a0SAl Viro 	int res;
8124675ac39SAl Viro 	BUG_ON(!(nd->flags & LOOKUP_RCU));
8134675ac39SAl Viro 
8144675ac39SAl Viro 	if (unlikely(!legitimize_links(nd)))
8154675ac39SAl Viro 		goto out2;
8167e4745a0SAl Viro 	res = __legitimize_mnt(nd->path.mnt, nd->m_seq);
8177e4745a0SAl Viro 	if (unlikely(res)) {
8187e4745a0SAl Viro 		if (res > 0)
8197973387aSAl Viro 			goto out2;
8207e4745a0SAl Viro 		goto out1;
8217e4745a0SAl Viro 	}
8224675ac39SAl Viro 	if (unlikely(!lockref_get_not_dead(&nd->path.dentry->d_lockref)))
8237973387aSAl Viro 		goto out1;
82448a066e7SAl Viro 
82515570086SLinus Torvalds 	/*
8264675ac39SAl Viro 	 * We need to move both the parent and the dentry from the RCU domain
8274675ac39SAl Viro 	 * to be properly refcounted. And the sequence number in the dentry
8284675ac39SAl Viro 	 * validates *both* dentry counters, since we checked the sequence
8294675ac39SAl Viro 	 * number of the parent after we got the child sequence number. So we
8304675ac39SAl Viro 	 * know the parent must still be valid if the child sequence number is
83115570086SLinus Torvalds 	 */
8324675ac39SAl Viro 	if (unlikely(!lockref_get_not_dead(&dentry->d_lockref)))
833e5c832d5SLinus Torvalds 		goto out;
83403fa86e9SAl Viro 	if (read_seqcount_retry(&dentry->d_seq, nd->next_seq))
83584a2bd39SAl Viro 		goto out_dput;
836e5c832d5SLinus Torvalds 	/*
837e5c832d5SLinus Torvalds 	 * Sequence counts matched. Now make sure that the root is
838e5c832d5SLinus Torvalds 	 * still valid and get it if required.
839e5c832d5SLinus Torvalds 	 */
84084a2bd39SAl Viro 	if (unlikely(!legitimize_root(nd)))
84184a2bd39SAl Viro 		goto out_dput;
8426e180327SAl Viro 	leave_rcu(nd);
843ae66db45SAl Viro 	return true;
84419660af7SAl Viro 
8457973387aSAl Viro out2:
8467973387aSAl Viro 	nd->path.mnt = NULL;
8477973387aSAl Viro out1:
8487973387aSAl Viro 	nd->path.dentry = NULL;
849e5c832d5SLinus Torvalds out:
8506e180327SAl Viro 	leave_rcu(nd);
851ae66db45SAl Viro 	return false;
85284a2bd39SAl Viro out_dput:
8536e180327SAl Viro 	leave_rcu(nd);
85484a2bd39SAl Viro 	dput(dentry);
855ae66db45SAl Viro 	return false;
85631e6b01fSNick Piggin }
85731e6b01fSNick Piggin 
8584ce16ef3SAl Viro static inline int d_revalidate(struct dentry *dentry, unsigned int flags)
85934286d66SNick Piggin {
860a89f8337SAl Viro 	if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE))
8614ce16ef3SAl Viro 		return dentry->d_op->d_revalidate(dentry, flags);
862a89f8337SAl Viro 	else
863a89f8337SAl Viro 		return 1;
86434286d66SNick Piggin }
86534286d66SNick Piggin 
8669f1fafeeSAl Viro /**
8679f1fafeeSAl Viro  * complete_walk - successful completion of path walk
8689f1fafeeSAl Viro  * @nd:  pointer nameidata
86939159de2SJeff Layton  *
8709f1fafeeSAl Viro  * If we had been in RCU mode, drop out of it and legitimize nd->path.
8719f1fafeeSAl Viro  * Revalidate the final result, unless we'd already done that during
8729f1fafeeSAl Viro  * the path walk or the filesystem doesn't ask for it.  Return 0 on
8739f1fafeeSAl Viro  * success, -error on failure.  In case of failure caller does not
8749f1fafeeSAl Viro  * need to drop nd->path.
87539159de2SJeff Layton  */
8769f1fafeeSAl Viro static int complete_walk(struct nameidata *nd)
87739159de2SJeff Layton {
87816c2cd71SAl Viro 	struct dentry *dentry = nd->path.dentry;
87939159de2SJeff Layton 	int status;
88039159de2SJeff Layton 
8819f1fafeeSAl Viro 	if (nd->flags & LOOKUP_RCU) {
882adb21d2bSAleksa Sarai 		/*
883adb21d2bSAleksa Sarai 		 * We don't want to zero nd->root for scoped-lookups or
884adb21d2bSAleksa Sarai 		 * externally-managed nd->root.
885adb21d2bSAleksa Sarai 		 */
886bcba1e7dSAl Viro 		if (!(nd->state & ND_ROOT_PRESET))
887bcba1e7dSAl Viro 			if (!(nd->flags & LOOKUP_IS_SCOPED))
8889f1fafeeSAl Viro 				nd->root.mnt = NULL;
8896c6ec2b0SJens Axboe 		nd->flags &= ~LOOKUP_CACHED;
890e36cffedSJens Axboe 		if (!try_to_unlazy(nd))
89148a066e7SAl Viro 			return -ECHILD;
89248a066e7SAl Viro 	}
8939f1fafeeSAl Viro 
894adb21d2bSAleksa Sarai 	if (unlikely(nd->flags & LOOKUP_IS_SCOPED)) {
895adb21d2bSAleksa Sarai 		/*
896adb21d2bSAleksa Sarai 		 * While the guarantee of LOOKUP_IS_SCOPED is (roughly) "don't
897adb21d2bSAleksa Sarai 		 * ever step outside the root during lookup" and should already
898adb21d2bSAleksa Sarai 		 * be guaranteed by the rest of namei, we want to avoid a namei
899adb21d2bSAleksa Sarai 		 * BUG resulting in userspace being given a path that was not
900adb21d2bSAleksa Sarai 		 * scoped within the root at some point during the lookup.
901adb21d2bSAleksa Sarai 		 *
902adb21d2bSAleksa Sarai 		 * So, do a final sanity-check to make sure that in the
903adb21d2bSAleksa Sarai 		 * worst-case scenario (a complete bypass of LOOKUP_IS_SCOPED)
904adb21d2bSAleksa Sarai 		 * we won't silently return an fd completely outside of the
905adb21d2bSAleksa Sarai 		 * requested root to userspace.
906adb21d2bSAleksa Sarai 		 *
907adb21d2bSAleksa Sarai 		 * Userspace could move the path outside the root after this
908adb21d2bSAleksa Sarai 		 * check, but as discussed elsewhere this is not a concern (the
909adb21d2bSAleksa Sarai 		 * resolved file was inside the root at some point).
910adb21d2bSAleksa Sarai 		 */
911adb21d2bSAleksa Sarai 		if (!path_is_under(&nd->path, &nd->root))
912adb21d2bSAleksa Sarai 			return -EXDEV;
913adb21d2bSAleksa Sarai 	}
914adb21d2bSAleksa Sarai 
915bcba1e7dSAl Viro 	if (likely(!(nd->state & ND_JUMPED)))
91639159de2SJeff Layton 		return 0;
91739159de2SJeff Layton 
918ecf3d1f1SJeff Layton 	if (likely(!(dentry->d_flags & DCACHE_OP_WEAK_REVALIDATE)))
91916c2cd71SAl Viro 		return 0;
92016c2cd71SAl Viro 
921ecf3d1f1SJeff Layton 	status = dentry->d_op->d_weak_revalidate(dentry, nd->flags);
92239159de2SJeff Layton 	if (status > 0)
92339159de2SJeff Layton 		return 0;
92439159de2SJeff Layton 
92516c2cd71SAl Viro 	if (!status)
92639159de2SJeff Layton 		status = -ESTALE;
92716c2cd71SAl Viro 
92839159de2SJeff Layton 	return status;
92939159de2SJeff Layton }
93039159de2SJeff Layton 
931740a1678SAleksa Sarai static int set_root(struct nameidata *nd)
9322a737871SAl Viro {
93331e6b01fSNick Piggin 	struct fs_struct *fs = current->fs;
9349e6697e2SAl Viro 
935adb21d2bSAleksa Sarai 	/*
936adb21d2bSAleksa Sarai 	 * Jumping to the real root in a scoped-lookup is a BUG in namei, but we
937adb21d2bSAleksa Sarai 	 * still have to ensure it doesn't happen because it will cause a breakout
938adb21d2bSAleksa Sarai 	 * from the dirfd.
939adb21d2bSAleksa Sarai 	 */
940adb21d2bSAleksa Sarai 	if (WARN_ON(nd->flags & LOOKUP_IS_SCOPED))
941adb21d2bSAleksa Sarai 		return -ENOTRECOVERABLE;
942adb21d2bSAleksa Sarai 
9439e6697e2SAl Viro 	if (nd->flags & LOOKUP_RCU) {
9448f47a016SAl Viro 		unsigned seq;
945c28cc364SNick Piggin 
946c28cc364SNick Piggin 		do {
947c28cc364SNick Piggin 			seq = read_seqcount_begin(&fs->seq);
94831e6b01fSNick Piggin 			nd->root = fs->root;
9498f47a016SAl Viro 			nd->root_seq = __read_seqcount_begin(&nd->root.dentry->d_seq);
950c28cc364SNick Piggin 		} while (read_seqcount_retry(&fs->seq, seq));
9519e6697e2SAl Viro 	} else {
9529e6697e2SAl Viro 		get_fs_root(fs, &nd->root);
953bcba1e7dSAl Viro 		nd->state |= ND_ROOT_GRABBED;
9549e6697e2SAl Viro 	}
955740a1678SAleksa Sarai 	return 0;
95631e6b01fSNick Piggin }
95731e6b01fSNick Piggin 
958248fb5b9SAl Viro static int nd_jump_root(struct nameidata *nd)
959248fb5b9SAl Viro {
960adb21d2bSAleksa Sarai 	if (unlikely(nd->flags & LOOKUP_BENEATH))
961adb21d2bSAleksa Sarai 		return -EXDEV;
96272ba2929SAleksa Sarai 	if (unlikely(nd->flags & LOOKUP_NO_XDEV)) {
96372ba2929SAleksa Sarai 		/* Absolute path arguments to path_init() are allowed. */
96472ba2929SAleksa Sarai 		if (nd->path.mnt != NULL && nd->path.mnt != nd->root.mnt)
96572ba2929SAleksa Sarai 			return -EXDEV;
96672ba2929SAleksa Sarai 	}
967740a1678SAleksa Sarai 	if (!nd->root.mnt) {
968740a1678SAleksa Sarai 		int error = set_root(nd);
969740a1678SAleksa Sarai 		if (error)
970740a1678SAleksa Sarai 			return error;
971740a1678SAleksa Sarai 	}
972248fb5b9SAl Viro 	if (nd->flags & LOOKUP_RCU) {
973248fb5b9SAl Viro 		struct dentry *d;
974248fb5b9SAl Viro 		nd->path = nd->root;
975248fb5b9SAl Viro 		d = nd->path.dentry;
976248fb5b9SAl Viro 		nd->inode = d->d_inode;
977248fb5b9SAl Viro 		nd->seq = nd->root_seq;
97882ef0698SAl Viro 		if (read_seqcount_retry(&d->d_seq, nd->seq))
979248fb5b9SAl Viro 			return -ECHILD;
980248fb5b9SAl Viro 	} else {
981248fb5b9SAl Viro 		path_put(&nd->path);
982248fb5b9SAl Viro 		nd->path = nd->root;
983248fb5b9SAl Viro 		path_get(&nd->path);
984248fb5b9SAl Viro 		nd->inode = nd->path.dentry->d_inode;
985248fb5b9SAl Viro 	}
986bcba1e7dSAl Viro 	nd->state |= ND_JUMPED;
987248fb5b9SAl Viro 	return 0;
988248fb5b9SAl Viro }
989248fb5b9SAl Viro 
990b5fb63c1SChristoph Hellwig /*
9916b255391SAl Viro  * Helper to directly jump to a known parsed path from ->get_link,
992b5fb63c1SChristoph Hellwig  * caller must have taken a reference to path beforehand.
993b5fb63c1SChristoph Hellwig  */
994ea4af4aaSAl Viro int nd_jump_link(const struct path *path)
995b5fb63c1SChristoph Hellwig {
9964b99d499SAleksa Sarai 	int error = -ELOOP;
9976e77137bSAl Viro 	struct nameidata *nd = current->nameidata;
998b5fb63c1SChristoph Hellwig 
9994b99d499SAleksa Sarai 	if (unlikely(nd->flags & LOOKUP_NO_MAGICLINKS))
10004b99d499SAleksa Sarai 		goto err;
10014b99d499SAleksa Sarai 
100272ba2929SAleksa Sarai 	error = -EXDEV;
100372ba2929SAleksa Sarai 	if (unlikely(nd->flags & LOOKUP_NO_XDEV)) {
100472ba2929SAleksa Sarai 		if (nd->path.mnt != path->mnt)
100572ba2929SAleksa Sarai 			goto err;
100672ba2929SAleksa Sarai 	}
1007adb21d2bSAleksa Sarai 	/* Not currently safe for scoped-lookups. */
1008adb21d2bSAleksa Sarai 	if (unlikely(nd->flags & LOOKUP_IS_SCOPED))
1009adb21d2bSAleksa Sarai 		goto err;
101072ba2929SAleksa Sarai 
10114b99d499SAleksa Sarai 	path_put(&nd->path);
1012b5fb63c1SChristoph Hellwig 	nd->path = *path;
1013b5fb63c1SChristoph Hellwig 	nd->inode = nd->path.dentry->d_inode;
1014bcba1e7dSAl Viro 	nd->state |= ND_JUMPED;
10151bc82070SAleksa Sarai 	return 0;
10164b99d499SAleksa Sarai 
10174b99d499SAleksa Sarai err:
10184b99d499SAleksa Sarai 	path_put(path);
10194b99d499SAleksa Sarai 	return error;
1020b5fb63c1SChristoph Hellwig }
1021b5fb63c1SChristoph Hellwig 
1022b9ff4429SAl Viro static inline void put_link(struct nameidata *nd)
1023574197e0SAl Viro {
102421c3003dSAl Viro 	struct saved *last = nd->stack + --nd->depth;
1025fceef393SAl Viro 	do_delayed_call(&last->done);
10266548fae2SAl Viro 	if (!(nd->flags & LOOKUP_RCU))
1027b9ff4429SAl Viro 		path_put(&last->link);
1028574197e0SAl Viro }
1029574197e0SAl Viro 
10309c011be1SLuis Chamberlain static int sysctl_protected_symlinks __read_mostly;
10319c011be1SLuis Chamberlain static int sysctl_protected_hardlinks __read_mostly;
10329c011be1SLuis Chamberlain static int sysctl_protected_fifos __read_mostly;
10339c011be1SLuis Chamberlain static int sysctl_protected_regular __read_mostly;
10349c011be1SLuis Chamberlain 
10359c011be1SLuis Chamberlain #ifdef CONFIG_SYSCTL
10369c011be1SLuis Chamberlain static struct ctl_table namei_sysctls[] = {
10379c011be1SLuis Chamberlain 	{
10389c011be1SLuis Chamberlain 		.procname	= "protected_symlinks",
10399c011be1SLuis Chamberlain 		.data		= &sysctl_protected_symlinks,
10409c011be1SLuis Chamberlain 		.maxlen		= sizeof(int),
1041c7031c14SJulius Hemanth Pitti 		.mode		= 0644,
10429c011be1SLuis Chamberlain 		.proc_handler	= proc_dointvec_minmax,
10439c011be1SLuis Chamberlain 		.extra1		= SYSCTL_ZERO,
10449c011be1SLuis Chamberlain 		.extra2		= SYSCTL_ONE,
10459c011be1SLuis Chamberlain 	},
10469c011be1SLuis Chamberlain 	{
10479c011be1SLuis Chamberlain 		.procname	= "protected_hardlinks",
10489c011be1SLuis Chamberlain 		.data		= &sysctl_protected_hardlinks,
10499c011be1SLuis Chamberlain 		.maxlen		= sizeof(int),
1050c7031c14SJulius Hemanth Pitti 		.mode		= 0644,
10519c011be1SLuis Chamberlain 		.proc_handler	= proc_dointvec_minmax,
10529c011be1SLuis Chamberlain 		.extra1		= SYSCTL_ZERO,
10539c011be1SLuis Chamberlain 		.extra2		= SYSCTL_ONE,
10549c011be1SLuis Chamberlain 	},
10559c011be1SLuis Chamberlain 	{
10569c011be1SLuis Chamberlain 		.procname	= "protected_fifos",
10579c011be1SLuis Chamberlain 		.data		= &sysctl_protected_fifos,
10589c011be1SLuis Chamberlain 		.maxlen		= sizeof(int),
1059c7031c14SJulius Hemanth Pitti 		.mode		= 0644,
10609c011be1SLuis Chamberlain 		.proc_handler	= proc_dointvec_minmax,
10619c011be1SLuis Chamberlain 		.extra1		= SYSCTL_ZERO,
10629c011be1SLuis Chamberlain 		.extra2		= SYSCTL_TWO,
10639c011be1SLuis Chamberlain 	},
10649c011be1SLuis Chamberlain 	{
10659c011be1SLuis Chamberlain 		.procname	= "protected_regular",
10669c011be1SLuis Chamberlain 		.data		= &sysctl_protected_regular,
10679c011be1SLuis Chamberlain 		.maxlen		= sizeof(int),
1068c7031c14SJulius Hemanth Pitti 		.mode		= 0644,
10699c011be1SLuis Chamberlain 		.proc_handler	= proc_dointvec_minmax,
10709c011be1SLuis Chamberlain 		.extra1		= SYSCTL_ZERO,
10719c011be1SLuis Chamberlain 		.extra2		= SYSCTL_TWO,
10729c011be1SLuis Chamberlain 	},
10739c011be1SLuis Chamberlain 	{ }
10749c011be1SLuis Chamberlain };
10759c011be1SLuis Chamberlain 
10769c011be1SLuis Chamberlain static int __init init_fs_namei_sysctls(void)
10779c011be1SLuis Chamberlain {
10789c011be1SLuis Chamberlain 	register_sysctl_init("fs", namei_sysctls);
10799c011be1SLuis Chamberlain 	return 0;
10809c011be1SLuis Chamberlain }
10819c011be1SLuis Chamberlain fs_initcall(init_fs_namei_sysctls);
10829c011be1SLuis Chamberlain 
10839c011be1SLuis Chamberlain #endif /* CONFIG_SYSCTL */
1084800179c9SKees Cook 
1085800179c9SKees Cook /**
1086800179c9SKees Cook  * may_follow_link - Check symlink following for unsafe situations
108755852635SRandy Dunlap  * @nd: nameidata pathwalk data
1088*35931eb3SMatthew Wilcox (Oracle)  * @inode: Used for idmapping.
1089800179c9SKees Cook  *
1090800179c9SKees Cook  * In the case of the sysctl_protected_symlinks sysctl being enabled,
1091800179c9SKees Cook  * CAP_DAC_OVERRIDE needs to be specifically ignored if the symlink is
1092800179c9SKees Cook  * in a sticky world-writable directory. This is to protect privileged
1093800179c9SKees Cook  * processes from failing races against path names that may change out
1094800179c9SKees Cook  * from under them by way of other users creating malicious symlinks.
1095800179c9SKees Cook  * It will permit symlinks to be followed only when outside a sticky
1096800179c9SKees Cook  * world-writable directory, or when the uid of the symlink and follower
1097800179c9SKees Cook  * match, or when the directory owner matches the symlink's owner.
1098800179c9SKees Cook  *
1099800179c9SKees Cook  * Returns 0 if following the symlink is allowed, -ve on error.
1100800179c9SKees Cook  */
1101ad6cc4c3SAl Viro static inline int may_follow_link(struct nameidata *nd, const struct inode *inode)
1102800179c9SKees Cook {
1103e67fe633SChristian Brauner 	struct mnt_idmap *idmap;
1104a2bd096fSChristian Brauner 	vfsuid_t vfsuid;
1105ba73d987SChristian Brauner 
1106800179c9SKees Cook 	if (!sysctl_protected_symlinks)
1107800179c9SKees Cook 		return 0;
1108800179c9SKees Cook 
1109e67fe633SChristian Brauner 	idmap = mnt_idmap(nd->path.mnt);
1110e67fe633SChristian Brauner 	vfsuid = i_uid_into_vfsuid(idmap, inode);
1111800179c9SKees Cook 	/* Allowed if owner and follower match. */
1112a2bd096fSChristian Brauner 	if (vfsuid_eq_kuid(vfsuid, current_fsuid()))
1113800179c9SKees Cook 		return 0;
1114800179c9SKees Cook 
1115800179c9SKees Cook 	/* Allowed if parent directory not sticky and world-writable. */
11160f705953SAl Viro 	if ((nd->dir_mode & (S_ISVTX|S_IWOTH)) != (S_ISVTX|S_IWOTH))
1117800179c9SKees Cook 		return 0;
1118800179c9SKees Cook 
1119800179c9SKees Cook 	/* Allowed if parent directory and link owner match. */
1120a2bd096fSChristian Brauner 	if (vfsuid_valid(nd->dir_vfsuid) && vfsuid_eq(nd->dir_vfsuid, vfsuid))
1121800179c9SKees Cook 		return 0;
1122800179c9SKees Cook 
112331956502SAl Viro 	if (nd->flags & LOOKUP_RCU)
112431956502SAl Viro 		return -ECHILD;
112531956502SAl Viro 
1126ea841bafSRichard Guy Briggs 	audit_inode(nd->name, nd->stack[0].link.dentry, 0);
1127245d7369SKees Cook 	audit_log_path_denied(AUDIT_ANOM_LINK, "follow_link");
1128800179c9SKees Cook 	return -EACCES;
1129800179c9SKees Cook }
1130800179c9SKees Cook 
1131800179c9SKees Cook /**
1132800179c9SKees Cook  * safe_hardlink_source - Check for safe hardlink conditions
11334609e1f1SChristian Brauner  * @idmap: idmap of the mount the inode was found from
1134800179c9SKees Cook  * @inode: the source inode to hardlink from
1135800179c9SKees Cook  *
1136800179c9SKees Cook  * Return false if at least one of the following conditions:
1137800179c9SKees Cook  *    - inode is not a regular file
1138800179c9SKees Cook  *    - inode is setuid
1139800179c9SKees Cook  *    - inode is setgid and group-exec
1140800179c9SKees Cook  *    - access failure for read and write
1141800179c9SKees Cook  *
1142800179c9SKees Cook  * Otherwise returns true.
1143800179c9SKees Cook  */
11444609e1f1SChristian Brauner static bool safe_hardlink_source(struct mnt_idmap *idmap,
1145ba73d987SChristian Brauner 				 struct inode *inode)
1146800179c9SKees Cook {
1147800179c9SKees Cook 	umode_t mode = inode->i_mode;
1148800179c9SKees Cook 
1149800179c9SKees Cook 	/* Special files should not get pinned to the filesystem. */
1150800179c9SKees Cook 	if (!S_ISREG(mode))
1151800179c9SKees Cook 		return false;
1152800179c9SKees Cook 
1153800179c9SKees Cook 	/* Setuid files should not get pinned to the filesystem. */
1154800179c9SKees Cook 	if (mode & S_ISUID)
1155800179c9SKees Cook 		return false;
1156800179c9SKees Cook 
1157800179c9SKees Cook 	/* Executable setgid files should not get pinned to the filesystem. */
1158800179c9SKees Cook 	if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP))
1159800179c9SKees Cook 		return false;
1160800179c9SKees Cook 
1161800179c9SKees Cook 	/* Hardlinking to unreadable or unwritable sources is dangerous. */
11624609e1f1SChristian Brauner 	if (inode_permission(idmap, inode, MAY_READ | MAY_WRITE))
1163800179c9SKees Cook 		return false;
1164800179c9SKees Cook 
1165800179c9SKees Cook 	return true;
1166800179c9SKees Cook }
1167800179c9SKees Cook 
1168800179c9SKees Cook /**
1169800179c9SKees Cook  * may_linkat - Check permissions for creating a hardlink
11704609e1f1SChristian Brauner  * @idmap: idmap of the mount the inode was found from
1171800179c9SKees Cook  * @link:  the source to hardlink from
1172800179c9SKees Cook  *
1173800179c9SKees Cook  * Block hardlink when all of:
1174800179c9SKees Cook  *  - sysctl_protected_hardlinks enabled
1175800179c9SKees Cook  *  - fsuid does not match inode
1176800179c9SKees Cook  *  - hardlink source is unsafe (see safe_hardlink_source() above)
1177f2ca3796SDirk Steinmetz  *  - not CAP_FOWNER in a namespace with the inode owner uid mapped
1178800179c9SKees Cook  *
11794609e1f1SChristian Brauner  * If the inode has been found through an idmapped mount the idmap of
11804609e1f1SChristian Brauner  * the vfsmount must be passed through @idmap. This function will then take
11814609e1f1SChristian Brauner  * care to map the inode according to @idmap before checking permissions.
1182ba73d987SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
11834609e1f1SChristian Brauner  * raw inode simply pass @nop_mnt_idmap.
1184ba73d987SChristian Brauner  *
1185800179c9SKees Cook  * Returns 0 if successful, -ve on error.
1186800179c9SKees Cook  */
11874609e1f1SChristian Brauner int may_linkat(struct mnt_idmap *idmap, const struct path *link)
1188800179c9SKees Cook {
1189593d1ce8SEric W. Biederman 	struct inode *inode = link->dentry->d_inode;
1190593d1ce8SEric W. Biederman 
1191593d1ce8SEric W. Biederman 	/* Inode writeback is not safe when the uid or gid are invalid. */
1192e67fe633SChristian Brauner 	if (!vfsuid_valid(i_uid_into_vfsuid(idmap, inode)) ||
1193e67fe633SChristian Brauner 	    !vfsgid_valid(i_gid_into_vfsgid(idmap, inode)))
1194593d1ce8SEric W. Biederman 		return -EOVERFLOW;
1195800179c9SKees Cook 
1196800179c9SKees Cook 	if (!sysctl_protected_hardlinks)
1197800179c9SKees Cook 		return 0;
1198800179c9SKees Cook 
1199800179c9SKees Cook 	/* Source inode owner (or CAP_FOWNER) can hardlink all they like,
1200800179c9SKees Cook 	 * otherwise, it must be a safe source.
1201800179c9SKees Cook 	 */
12024609e1f1SChristian Brauner 	if (safe_hardlink_source(idmap, inode) ||
120301beba79SChristian Brauner 	    inode_owner_or_capable(idmap, inode))
1204800179c9SKees Cook 		return 0;
1205800179c9SKees Cook 
1206245d7369SKees Cook 	audit_log_path_denied(AUDIT_ANOM_LINK, "linkat");
1207800179c9SKees Cook 	return -EPERM;
1208800179c9SKees Cook }
1209800179c9SKees Cook 
121030aba665SSalvatore Mesoraca /**
121130aba665SSalvatore Mesoraca  * may_create_in_sticky - Check whether an O_CREAT open in a sticky directory
121230aba665SSalvatore Mesoraca  *			  should be allowed, or not, on files that already
121330aba665SSalvatore Mesoraca  *			  exist.
1214e67fe633SChristian Brauner  * @idmap: idmap of the mount the inode was found from
12152111c3c0SRandy Dunlap  * @nd: nameidata pathwalk data
121630aba665SSalvatore Mesoraca  * @inode: the inode of the file to open
121730aba665SSalvatore Mesoraca  *
121830aba665SSalvatore Mesoraca  * Block an O_CREAT open of a FIFO (or a regular file) when:
121930aba665SSalvatore Mesoraca  *   - sysctl_protected_fifos (or sysctl_protected_regular) is enabled
122030aba665SSalvatore Mesoraca  *   - the file already exists
122130aba665SSalvatore Mesoraca  *   - we are in a sticky directory
122230aba665SSalvatore Mesoraca  *   - we don't own the file
122330aba665SSalvatore Mesoraca  *   - the owner of the directory doesn't own the file
122430aba665SSalvatore Mesoraca  *   - the directory is world writable
122530aba665SSalvatore Mesoraca  * If the sysctl_protected_fifos (or sysctl_protected_regular) is set to 2
122630aba665SSalvatore Mesoraca  * the directory doesn't have to be world writable: being group writable will
122730aba665SSalvatore Mesoraca  * be enough.
122830aba665SSalvatore Mesoraca  *
1229e67fe633SChristian Brauner  * If the inode has been found through an idmapped mount the idmap of
1230e67fe633SChristian Brauner  * the vfsmount must be passed through @idmap. This function will then take
1231e67fe633SChristian Brauner  * care to map the inode according to @idmap before checking permissions.
1232ba73d987SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
1233e67fe633SChristian Brauner  * raw inode simply pass @nop_mnt_idmap.
1234ba73d987SChristian Brauner  *
123530aba665SSalvatore Mesoraca  * Returns 0 if the open is allowed, -ve on error.
123630aba665SSalvatore Mesoraca  */
1237e67fe633SChristian Brauner static int may_create_in_sticky(struct mnt_idmap *idmap,
1238ba73d987SChristian Brauner 				struct nameidata *nd, struct inode *const inode)
123930aba665SSalvatore Mesoraca {
1240ba73d987SChristian Brauner 	umode_t dir_mode = nd->dir_mode;
1241a2bd096fSChristian Brauner 	vfsuid_t dir_vfsuid = nd->dir_vfsuid;
1242ba73d987SChristian Brauner 
124330aba665SSalvatore Mesoraca 	if ((!sysctl_protected_fifos && S_ISFIFO(inode->i_mode)) ||
124430aba665SSalvatore Mesoraca 	    (!sysctl_protected_regular && S_ISREG(inode->i_mode)) ||
1245d0cb5018SAl Viro 	    likely(!(dir_mode & S_ISVTX)) ||
1246e67fe633SChristian Brauner 	    vfsuid_eq(i_uid_into_vfsuid(idmap, inode), dir_vfsuid) ||
1247e67fe633SChristian Brauner 	    vfsuid_eq_kuid(i_uid_into_vfsuid(idmap, inode), current_fsuid()))
124830aba665SSalvatore Mesoraca 		return 0;
124930aba665SSalvatore Mesoraca 
1250d0cb5018SAl Viro 	if (likely(dir_mode & 0002) ||
1251d0cb5018SAl Viro 	    (dir_mode & 0020 &&
125230aba665SSalvatore Mesoraca 	     ((sysctl_protected_fifos >= 2 && S_ISFIFO(inode->i_mode)) ||
125330aba665SSalvatore Mesoraca 	      (sysctl_protected_regular >= 2 && S_ISREG(inode->i_mode))))) {
1254245d7369SKees Cook 		const char *operation = S_ISFIFO(inode->i_mode) ?
1255245d7369SKees Cook 					"sticky_create_fifo" :
1256245d7369SKees Cook 					"sticky_create_regular";
1257245d7369SKees Cook 		audit_log_path_denied(AUDIT_ANOM_CREAT, operation);
125830aba665SSalvatore Mesoraca 		return -EACCES;
125930aba665SSalvatore Mesoraca 	}
126030aba665SSalvatore Mesoraca 	return 0;
126130aba665SSalvatore Mesoraca }
126230aba665SSalvatore Mesoraca 
1263f015f126SDavid Howells /*
1264f015f126SDavid Howells  * follow_up - Find the mountpoint of path's vfsmount
1265f015f126SDavid Howells  *
1266f015f126SDavid Howells  * Given a path, find the mountpoint of its source file system.
1267f015f126SDavid Howells  * Replace @path with the path of the mountpoint in the parent mount.
1268f015f126SDavid Howells  * Up is towards /.
1269f015f126SDavid Howells  *
1270f015f126SDavid Howells  * Return 1 if we went up a level and 0 if we were already at the
1271f015f126SDavid Howells  * root.
1272f015f126SDavid Howells  */
1273bab77ebfSAl Viro int follow_up(struct path *path)
12741da177e4SLinus Torvalds {
12750714a533SAl Viro 	struct mount *mnt = real_mount(path->mnt);
12760714a533SAl Viro 	struct mount *parent;
12771da177e4SLinus Torvalds 	struct dentry *mountpoint;
127899b7db7bSNick Piggin 
127948a066e7SAl Viro 	read_seqlock_excl(&mount_lock);
12800714a533SAl Viro 	parent = mnt->mnt_parent;
12813c0a6163SAl Viro 	if (parent == mnt) {
128248a066e7SAl Viro 		read_sequnlock_excl(&mount_lock);
12831da177e4SLinus Torvalds 		return 0;
12841da177e4SLinus Torvalds 	}
12850714a533SAl Viro 	mntget(&parent->mnt);
1286a73324daSAl Viro 	mountpoint = dget(mnt->mnt_mountpoint);
128748a066e7SAl Viro 	read_sequnlock_excl(&mount_lock);
1288bab77ebfSAl Viro 	dput(path->dentry);
1289bab77ebfSAl Viro 	path->dentry = mountpoint;
1290bab77ebfSAl Viro 	mntput(path->mnt);
12910714a533SAl Viro 	path->mnt = &parent->mnt;
12921da177e4SLinus Torvalds 	return 1;
12931da177e4SLinus Torvalds }
12944d359507SAl Viro EXPORT_SYMBOL(follow_up);
12951da177e4SLinus Torvalds 
12967ef482faSAl Viro static bool choose_mountpoint_rcu(struct mount *m, const struct path *root,
12977ef482faSAl Viro 				  struct path *path, unsigned *seqp)
12987ef482faSAl Viro {
12997ef482faSAl Viro 	while (mnt_has_parent(m)) {
13007ef482faSAl Viro 		struct dentry *mountpoint = m->mnt_mountpoint;
13017ef482faSAl Viro 
13027ef482faSAl Viro 		m = m->mnt_parent;
13037ef482faSAl Viro 		if (unlikely(root->dentry == mountpoint &&
13047ef482faSAl Viro 			     root->mnt == &m->mnt))
13057ef482faSAl Viro 			break;
13067ef482faSAl Viro 		if (mountpoint != m->mnt.mnt_root) {
13077ef482faSAl Viro 			path->mnt = &m->mnt;
13087ef482faSAl Viro 			path->dentry = mountpoint;
13097ef482faSAl Viro 			*seqp = read_seqcount_begin(&mountpoint->d_seq);
13107ef482faSAl Viro 			return true;
13117ef482faSAl Viro 		}
13127ef482faSAl Viro 	}
13137ef482faSAl Viro 	return false;
13147ef482faSAl Viro }
13157ef482faSAl Viro 
13162aa38470SAl Viro static bool choose_mountpoint(struct mount *m, const struct path *root,
13172aa38470SAl Viro 			      struct path *path)
13182aa38470SAl Viro {
13192aa38470SAl Viro 	bool found;
13202aa38470SAl Viro 
13212aa38470SAl Viro 	rcu_read_lock();
13222aa38470SAl Viro 	while (1) {
13232aa38470SAl Viro 		unsigned seq, mseq = read_seqbegin(&mount_lock);
13242aa38470SAl Viro 
13252aa38470SAl Viro 		found = choose_mountpoint_rcu(m, root, path, &seq);
13262aa38470SAl Viro 		if (unlikely(!found)) {
13272aa38470SAl Viro 			if (!read_seqretry(&mount_lock, mseq))
13282aa38470SAl Viro 				break;
13292aa38470SAl Viro 		} else {
13302aa38470SAl Viro 			if (likely(__legitimize_path(path, seq, mseq)))
13312aa38470SAl Viro 				break;
13322aa38470SAl Viro 			rcu_read_unlock();
13332aa38470SAl Viro 			path_put(path);
13342aa38470SAl Viro 			rcu_read_lock();
13352aa38470SAl Viro 		}
13362aa38470SAl Viro 	}
13372aa38470SAl Viro 	rcu_read_unlock();
13382aa38470SAl Viro 	return found;
13392aa38470SAl Viro }
13402aa38470SAl Viro 
1341b5c84bf6SNick Piggin /*
13429875cf80SDavid Howells  * Perform an automount
13439875cf80SDavid Howells  * - return -EISDIR to tell follow_managed() to stop and return the path we
13449875cf80SDavid Howells  *   were called with.
13451da177e4SLinus Torvalds  */
13461c9f5e06SAl Viro static int follow_automount(struct path *path, int *count, unsigned lookup_flags)
134731e6b01fSNick Piggin {
134825e195aaSAl Viro 	struct dentry *dentry = path->dentry;
13499875cf80SDavid Howells 
13500ec26fd0SMiklos Szeredi 	/* We don't want to mount if someone's just doing a stat -
13510ec26fd0SMiklos Szeredi 	 * unless they're stat'ing a directory and appended a '/' to
13520ec26fd0SMiklos Szeredi 	 * the name.
13530ec26fd0SMiklos Szeredi 	 *
13540ec26fd0SMiklos Szeredi 	 * We do, however, want to mount if someone wants to open or
13555a30d8a2SDavid Howells 	 * create a file of any type under the mountpoint, wants to
13560ec26fd0SMiklos Szeredi 	 * traverse through the mountpoint or wants to open the
13570ec26fd0SMiklos Szeredi 	 * mounted directory.  Also, autofs may mark negative dentries
13580ec26fd0SMiklos Szeredi 	 * as being automount points.  These will need the attentions
13590ec26fd0SMiklos Szeredi 	 * of the daemon to instantiate them before they can be used.
13605a30d8a2SDavid Howells 	 */
13611c9f5e06SAl Viro 	if (!(lookup_flags & (LOOKUP_PARENT | LOOKUP_DIRECTORY |
13625d38f049SIan Kent 			   LOOKUP_OPEN | LOOKUP_CREATE | LOOKUP_AUTOMOUNT)) &&
136325e195aaSAl Viro 	    dentry->d_inode)
13649875cf80SDavid Howells 		return -EISDIR;
13650ec26fd0SMiklos Szeredi 
13661c9f5e06SAl Viro 	if (count && (*count)++ >= MAXSYMLINKS)
13679875cf80SDavid Howells 		return -ELOOP;
13689875cf80SDavid Howells 
136925e195aaSAl Viro 	return finish_automount(dentry->d_op->d_automount(path), path);
1370ea5b778aSDavid Howells }
13719875cf80SDavid Howells 
13729875cf80SDavid Howells /*
13739deed3ebSAl Viro  * mount traversal - out-of-line part.  One note on ->d_flags accesses -
13749deed3ebSAl Viro  * dentries are pinned but not locked here, so negative dentry can go
13759deed3ebSAl Viro  * positive right under us.  Use of smp_load_acquire() provides a barrier
13769deed3ebSAl Viro  * sufficient for ->d_inode and ->d_flags consistency.
13779875cf80SDavid Howells  */
13789deed3ebSAl Viro static int __traverse_mounts(struct path *path, unsigned flags, bool *jumped,
13799deed3ebSAl Viro 			     int *count, unsigned lookup_flags)
13809875cf80SDavid Howells {
13819deed3ebSAl Viro 	struct vfsmount *mnt = path->mnt;
13829875cf80SDavid Howells 	bool need_mntput = false;
13838aef1884SAl Viro 	int ret = 0;
13849875cf80SDavid Howells 
13859deed3ebSAl Viro 	while (flags & DCACHE_MANAGED_DENTRY) {
1386cc53ce53SDavid Howells 		/* Allow the filesystem to manage the transit without i_mutex
1387cc53ce53SDavid Howells 		 * being held. */
1388d41efb52SAl Viro 		if (flags & DCACHE_MANAGE_TRANSIT) {
1389fb5f51c7SIan Kent 			ret = path->dentry->d_op->d_manage(path, false);
1390508c8772SAl Viro 			flags = smp_load_acquire(&path->dentry->d_flags);
1391cc53ce53SDavid Howells 			if (ret < 0)
13928aef1884SAl Viro 				break;
1393cc53ce53SDavid Howells 		}
1394cc53ce53SDavid Howells 
13959deed3ebSAl Viro 		if (flags & DCACHE_MOUNTED) {	// something's mounted on it..
13969875cf80SDavid Howells 			struct vfsmount *mounted = lookup_mnt(path);
13979deed3ebSAl Viro 			if (mounted) {		// ... in our namespace
13989875cf80SDavid Howells 				dput(path->dentry);
13999875cf80SDavid Howells 				if (need_mntput)
1400463ffb2eSAl Viro 					mntput(path->mnt);
1401463ffb2eSAl Viro 				path->mnt = mounted;
1402463ffb2eSAl Viro 				path->dentry = dget(mounted->mnt_root);
14039deed3ebSAl Viro 				// here we know it's positive
14049deed3ebSAl Viro 				flags = path->dentry->d_flags;
14059875cf80SDavid Howells 				need_mntput = true;
14069875cf80SDavid Howells 				continue;
1407463ffb2eSAl Viro 			}
14081da177e4SLinus Torvalds 		}
14099875cf80SDavid Howells 
14109deed3ebSAl Viro 		if (!(flags & DCACHE_NEED_AUTOMOUNT))
14119deed3ebSAl Viro 			break;
14129deed3ebSAl Viro 
14139deed3ebSAl Viro 		// uncovered automount point
14149deed3ebSAl Viro 		ret = follow_automount(path, count, lookup_flags);
14159deed3ebSAl Viro 		flags = smp_load_acquire(&path->dentry->d_flags);
14169875cf80SDavid Howells 		if (ret < 0)
14178aef1884SAl Viro 			break;
14189875cf80SDavid Howells 	}
14199875cf80SDavid Howells 
14209deed3ebSAl Viro 	if (ret == -EISDIR)
14219deed3ebSAl Viro 		ret = 0;
14229deed3ebSAl Viro 	// possible if you race with several mount --move
14239deed3ebSAl Viro 	if (need_mntput && path->mnt == mnt)
14248aef1884SAl Viro 		mntput(path->mnt);
14259deed3ebSAl Viro 	if (!ret && unlikely(d_flags_negative(flags)))
1426d41efb52SAl Viro 		ret = -ENOENT;
14279deed3ebSAl Viro 	*jumped = need_mntput;
14288402752eSAl Viro 	return ret;
14291da177e4SLinus Torvalds }
14301da177e4SLinus Torvalds 
14319deed3ebSAl Viro static inline int traverse_mounts(struct path *path, bool *jumped,
14329deed3ebSAl Viro 				  int *count, unsigned lookup_flags)
14339deed3ebSAl Viro {
14349deed3ebSAl Viro 	unsigned flags = smp_load_acquire(&path->dentry->d_flags);
14359deed3ebSAl Viro 
14369deed3ebSAl Viro 	/* fastpath */
14379deed3ebSAl Viro 	if (likely(!(flags & DCACHE_MANAGED_DENTRY))) {
14389deed3ebSAl Viro 		*jumped = false;
14399deed3ebSAl Viro 		if (unlikely(d_flags_negative(flags)))
14409deed3ebSAl Viro 			return -ENOENT;
14419deed3ebSAl Viro 		return 0;
14429deed3ebSAl Viro 	}
14439deed3ebSAl Viro 	return __traverse_mounts(path, flags, jumped, count, lookup_flags);
14449deed3ebSAl Viro }
14459deed3ebSAl Viro 
1446cc53ce53SDavid Howells int follow_down_one(struct path *path)
14471da177e4SLinus Torvalds {
14481da177e4SLinus Torvalds 	struct vfsmount *mounted;
14491da177e4SLinus Torvalds 
14501c755af4SAl Viro 	mounted = lookup_mnt(path);
14511da177e4SLinus Torvalds 	if (mounted) {
14529393bd07SAl Viro 		dput(path->dentry);
14539393bd07SAl Viro 		mntput(path->mnt);
14549393bd07SAl Viro 		path->mnt = mounted;
14559393bd07SAl Viro 		path->dentry = dget(mounted->mnt_root);
14561da177e4SLinus Torvalds 		return 1;
14571da177e4SLinus Torvalds 	}
14581da177e4SLinus Torvalds 	return 0;
14591da177e4SLinus Torvalds }
14604d359507SAl Viro EXPORT_SYMBOL(follow_down_one);
14611da177e4SLinus Torvalds 
14629875cf80SDavid Howells /*
14639deed3ebSAl Viro  * Follow down to the covering mount currently visible to userspace.  At each
14649deed3ebSAl Viro  * point, the filesystem owning that dentry may be queried as to whether the
14659deed3ebSAl Viro  * caller is permitted to proceed or not.
14669deed3ebSAl Viro  */
1467e1f19857SRichard Weinberger int follow_down(struct path *path, unsigned int flags)
14689deed3ebSAl Viro {
14699deed3ebSAl Viro 	struct vfsmount *mnt = path->mnt;
14709deed3ebSAl Viro 	bool jumped;
1471e1f19857SRichard Weinberger 	int ret = traverse_mounts(path, &jumped, NULL, flags);
14729deed3ebSAl Viro 
14739deed3ebSAl Viro 	if (path->mnt != mnt)
14749deed3ebSAl Viro 		mntput(mnt);
14759deed3ebSAl Viro 	return ret;
14769deed3ebSAl Viro }
14779deed3ebSAl Viro EXPORT_SYMBOL(follow_down);
14789deed3ebSAl Viro 
14799deed3ebSAl Viro /*
1480287548e4SAl Viro  * Try to skip to top of mountpoint pile in rcuwalk mode.  Fail if
1481287548e4SAl Viro  * we meet a managed dentry that would need blocking.
14829875cf80SDavid Howells  */
14833bd8bc89SAl Viro static bool __follow_mount_rcu(struct nameidata *nd, struct path *path)
14849875cf80SDavid Howells {
1485ea936aebSAl Viro 	struct dentry *dentry = path->dentry;
1486ea936aebSAl Viro 	unsigned int flags = dentry->d_flags;
1487ea936aebSAl Viro 
1488ea936aebSAl Viro 	if (likely(!(flags & DCACHE_MANAGED_DENTRY)))
1489ea936aebSAl Viro 		return true;
1490ea936aebSAl Viro 
1491ea936aebSAl Viro 	if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1492ea936aebSAl Viro 		return false;
1493ea936aebSAl Viro 
149462a7375eSIan Kent 	for (;;) {
149562a7375eSIan Kent 		/*
149662a7375eSIan Kent 		 * Don't forget we might have a non-mountpoint managed dentry
149762a7375eSIan Kent 		 * that wants to block transit.
149862a7375eSIan Kent 		 */
1499ea936aebSAl Viro 		if (unlikely(flags & DCACHE_MANAGE_TRANSIT)) {
1500ea936aebSAl Viro 			int res = dentry->d_op->d_manage(path, true);
1501ea936aebSAl Viro 			if (res)
1502ea936aebSAl Viro 				return res == -EISDIR;
1503ea936aebSAl Viro 			flags = dentry->d_flags;
1504b8faf035SNeilBrown 		}
150562a7375eSIan Kent 
1506ea936aebSAl Viro 		if (flags & DCACHE_MOUNTED) {
1507ea936aebSAl Viro 			struct mount *mounted = __lookup_mnt(path->mnt, dentry);
1508ea936aebSAl Viro 			if (mounted) {
1509c7105365SAl Viro 				path->mnt = &mounted->mnt;
1510ea936aebSAl Viro 				dentry = path->dentry = mounted->mnt.mnt_root;
1511bcba1e7dSAl Viro 				nd->state |= ND_JUMPED;
151203fa86e9SAl Viro 				nd->next_seq = read_seqcount_begin(&dentry->d_seq);
1513ea936aebSAl Viro 				flags = dentry->d_flags;
151403fa86e9SAl Viro 				// makes sure that non-RCU pathwalk could reach
151503fa86e9SAl Viro 				// this state.
151620aac6c6SAl Viro 				if (read_seqretry(&mount_lock, nd->m_seq))
151720aac6c6SAl Viro 					return false;
1518ea936aebSAl Viro 				continue;
15199875cf80SDavid Howells 			}
1520ea936aebSAl Viro 			if (read_seqretry(&mount_lock, nd->m_seq))
1521ea936aebSAl Viro 				return false;
1522ea936aebSAl Viro 		}
1523ea936aebSAl Viro 		return !(flags & DCACHE_NEED_AUTOMOUNT);
1524ea936aebSAl Viro 	}
1525287548e4SAl Viro }
1526287548e4SAl Viro 
1527db3c9adeSAl Viro static inline int handle_mounts(struct nameidata *nd, struct dentry *dentry,
15283bd8bc89SAl Viro 			  struct path *path)
1529bd7c4b50SAl Viro {
15309deed3ebSAl Viro 	bool jumped;
1531db3c9adeSAl Viro 	int ret;
1532bd7c4b50SAl Viro 
1533db3c9adeSAl Viro 	path->mnt = nd->path.mnt;
1534db3c9adeSAl Viro 	path->dentry = dentry;
1535c153007bSAl Viro 	if (nd->flags & LOOKUP_RCU) {
153603fa86e9SAl Viro 		unsigned int seq = nd->next_seq;
15373bd8bc89SAl Viro 		if (likely(__follow_mount_rcu(nd, path)))
15389deed3ebSAl Viro 			return 0;
153903fa86e9SAl Viro 		// *path and nd->next_seq might've been clobbered
1540c153007bSAl Viro 		path->mnt = nd->path.mnt;
1541c153007bSAl Viro 		path->dentry = dentry;
154203fa86e9SAl Viro 		nd->next_seq = seq;
154303fa86e9SAl Viro 		if (!try_to_unlazy_next(nd, dentry))
154403fa86e9SAl Viro 			return -ECHILD;
1545c153007bSAl Viro 	}
15469deed3ebSAl Viro 	ret = traverse_mounts(path, &jumped, &nd->total_link_count, nd->flags);
15479deed3ebSAl Viro 	if (jumped) {
15489deed3ebSAl Viro 		if (unlikely(nd->flags & LOOKUP_NO_XDEV))
15499deed3ebSAl Viro 			ret = -EXDEV;
15509deed3ebSAl Viro 		else
1551bcba1e7dSAl Viro 			nd->state |= ND_JUMPED;
15529deed3ebSAl Viro 	}
15539deed3ebSAl Viro 	if (unlikely(ret)) {
15549deed3ebSAl Viro 		dput(path->dentry);
15559deed3ebSAl Viro 		if (path->mnt != nd->path.mnt)
15569deed3ebSAl Viro 			mntput(path->mnt);
1557bd7c4b50SAl Viro 	}
1558bd7c4b50SAl Viro 	return ret;
1559bd7c4b50SAl Viro }
1560bd7c4b50SAl Viro 
15619875cf80SDavid Howells /*
1562f4fdace9SOleg Drokin  * This looks up the name in dcache and possibly revalidates the found dentry.
1563f4fdace9SOleg Drokin  * NULL is returned if the dentry does not exist in the cache.
1564baa03890SNick Piggin  */
1565e3c13928SAl Viro static struct dentry *lookup_dcache(const struct qstr *name,
1566e3c13928SAl Viro 				    struct dentry *dir,
15676c51e513SAl Viro 				    unsigned int flags)
1568baa03890SNick Piggin {
1569a89f8337SAl Viro 	struct dentry *dentry = d_lookup(dir, name);
1570bad61189SMiklos Szeredi 	if (dentry) {
1571a89f8337SAl Viro 		int error = d_revalidate(dentry, flags);
1572bad61189SMiklos Szeredi 		if (unlikely(error <= 0)) {
157374ff0ffcSAl Viro 			if (!error)
15745542aa2fSEric W. Biederman 				d_invalidate(dentry);
1575bad61189SMiklos Szeredi 			dput(dentry);
157674ff0ffcSAl Viro 			return ERR_PTR(error);
1577bad61189SMiklos Szeredi 		}
1578bad61189SMiklos Szeredi 	}
1579baa03890SNick Piggin 	return dentry;
1580baa03890SNick Piggin }
1581baa03890SNick Piggin 
1582baa03890SNick Piggin /*
1583a03ece5fSAl Viro  * Parent directory has inode locked exclusive.  This is one
1584a03ece5fSAl Viro  * and only case when ->lookup() gets called on non in-lookup
1585a03ece5fSAl Viro  * dentries - as the matter of fact, this only gets called
1586a03ece5fSAl Viro  * when directory is guaranteed to have no in-lookup children
1587a03ece5fSAl Viro  * at all.
158844396f4bSJosef Bacik  */
158974d7970fSNamjae Jeon struct dentry *lookup_one_qstr_excl(const struct qstr *name,
159074d7970fSNamjae Jeon 				    struct dentry *base,
159174d7970fSNamjae Jeon 				    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 }
161574d7970fSNamjae Jeon EXPORT_SYMBOL(lookup_one_qstr_excl);
161644396f4bSJosef Bacik 
16174cb64024SAl Viro static struct dentry *lookup_fast(struct nameidata *nd)
16181da177e4SLinus Torvalds {
161931e6b01fSNick Piggin 	struct dentry *dentry, *parent = nd->path.dentry;
16205a18fff2SAl Viro 	int status = 1;
16219875cf80SDavid Howells 
16223cac260aSAl Viro 	/*
1623b04f784eSNick Piggin 	 * Rename seqlock is not required here because in the off chance
16245d0f49c1SAl Viro 	 * of a false negative due to a concurrent rename, the caller is
16255d0f49c1SAl Viro 	 * going to fall back to non-racy lookup.
1626b04f784eSNick Piggin 	 */
162731e6b01fSNick Piggin 	if (nd->flags & LOOKUP_RCU) {
162803fa86e9SAl Viro 		dentry = __d_lookup_rcu(parent, &nd->last, &nd->next_seq);
16295d0f49c1SAl Viro 		if (unlikely(!dentry)) {
1630e36cffedSJens Axboe 			if (!try_to_unlazy(nd))
163120e34357SAl Viro 				return ERR_PTR(-ECHILD);
163220e34357SAl Viro 			return NULL;
16335d0f49c1SAl Viro 		}
16345a18fff2SAl Viro 
163512f8ad4bSLinus Torvalds 		/*
163612f8ad4bSLinus Torvalds 		 * This sequence count validates that the parent had no
163712f8ad4bSLinus Torvalds 		 * changes while we did the lookup of the dentry above.
163812f8ad4bSLinus Torvalds 		 */
16394cb64024SAl Viro 		if (read_seqcount_retry(&parent->d_seq, nd->seq))
164020e34357SAl Viro 			return ERR_PTR(-ECHILD);
16415a18fff2SAl Viro 
16424ce16ef3SAl Viro 		status = d_revalidate(dentry, nd->flags);
1643c153007bSAl Viro 		if (likely(status > 0))
164420e34357SAl Viro 			return dentry;
164503fa86e9SAl Viro 		if (!try_to_unlazy_next(nd, dentry))
164620e34357SAl Viro 			return ERR_PTR(-ECHILD);
164726ddb45eSSteven Rostedt (VMware) 		if (status == -ECHILD)
1648209a7fb2SAl Viro 			/* we'd been told to redo it in non-rcu mode */
1649209a7fb2SAl Viro 			status = d_revalidate(dentry, nd->flags);
16505a18fff2SAl Viro 	} else {
1651e97cdc87SAl Viro 		dentry = __d_lookup(parent, &nd->last);
165281e6f520SAl Viro 		if (unlikely(!dentry))
165320e34357SAl Viro 			return NULL;
16544ce16ef3SAl Viro 		status = d_revalidate(dentry, nd->flags);
16555d0f49c1SAl Viro 	}
16565a18fff2SAl Viro 	if (unlikely(status <= 0)) {
1657e9742b53SAl Viro 		if (!status)
16585d0f49c1SAl Viro 			d_invalidate(dentry);
16595a18fff2SAl Viro 		dput(dentry);
166020e34357SAl Viro 		return ERR_PTR(status);
16615a18fff2SAl Viro 	}
166220e34357SAl Viro 	return dentry;
1663697f514dSMiklos Szeredi }
1664697f514dSMiklos Szeredi 
1665697f514dSMiklos Szeredi /* Fast lookup failed, do it the slow way */
166688d8331aSAl Viro static struct dentry *__lookup_slow(const struct qstr *name,
1667e3c13928SAl Viro 				    struct dentry *dir,
1668e3c13928SAl Viro 				    unsigned int flags)
1669697f514dSMiklos Szeredi {
167088d8331aSAl Viro 	struct dentry *dentry, *old;
16711936386eSAl Viro 	struct inode *inode = dir->d_inode;
1672d9171b93SAl Viro 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
16731936386eSAl Viro 
16741936386eSAl Viro 	/* Don't go there if it's already dead */
167594bdd655SAl Viro 	if (unlikely(IS_DEADDIR(inode)))
167688d8331aSAl Viro 		return ERR_PTR(-ENOENT);
167794bdd655SAl Viro again:
1678d9171b93SAl Viro 	dentry = d_alloc_parallel(dir, name, &wq);
167994bdd655SAl Viro 	if (IS_ERR(dentry))
168088d8331aSAl Viro 		return dentry;
168194bdd655SAl Viro 	if (unlikely(!d_in_lookup(dentry))) {
1682949a852eSAl Viro 		int error = d_revalidate(dentry, flags);
1683949a852eSAl Viro 		if (unlikely(error <= 0)) {
168494bdd655SAl Viro 			if (!error) {
1685949a852eSAl Viro 				d_invalidate(dentry);
1686949a852eSAl Viro 				dput(dentry);
168794bdd655SAl Viro 				goto again;
168894bdd655SAl Viro 			}
168994bdd655SAl Viro 			dput(dentry);
1690949a852eSAl Viro 			dentry = ERR_PTR(error);
1691949a852eSAl Viro 		}
169294bdd655SAl Viro 	} else {
16931936386eSAl Viro 		old = inode->i_op->lookup(inode, dentry, flags);
169485c7f810SAl Viro 		d_lookup_done(dentry);
16951936386eSAl Viro 		if (unlikely(old)) {
16961936386eSAl Viro 			dput(dentry);
16971936386eSAl Viro 			dentry = old;
1698949a852eSAl Viro 		}
1699949a852eSAl Viro 	}
1700e3c13928SAl Viro 	return dentry;
17011da177e4SLinus Torvalds }
17021da177e4SLinus Torvalds 
170388d8331aSAl Viro static struct dentry *lookup_slow(const struct qstr *name,
170488d8331aSAl Viro 				  struct dentry *dir,
170588d8331aSAl Viro 				  unsigned int flags)
170688d8331aSAl Viro {
170788d8331aSAl Viro 	struct inode *inode = dir->d_inode;
170888d8331aSAl Viro 	struct dentry *res;
170988d8331aSAl Viro 	inode_lock_shared(inode);
171088d8331aSAl Viro 	res = __lookup_slow(name, dir, flags);
171188d8331aSAl Viro 	inode_unlock_shared(inode);
171288d8331aSAl Viro 	return res;
171388d8331aSAl Viro }
171488d8331aSAl Viro 
17154609e1f1SChristian Brauner static inline int may_lookup(struct mnt_idmap *idmap,
1716ba73d987SChristian Brauner 			     struct nameidata *nd)
171752094c8aSAl Viro {
171852094c8aSAl Viro 	if (nd->flags & LOOKUP_RCU) {
17194609e1f1SChristian Brauner 		int err = inode_permission(idmap, nd->inode, MAY_EXEC|MAY_NOT_BLOCK);
1720e36cffedSJens Axboe 		if (err != -ECHILD || !try_to_unlazy(nd))
172152094c8aSAl Viro 			return err;
172252094c8aSAl Viro 	}
17234609e1f1SChristian Brauner 	return inode_permission(idmap, nd->inode, MAY_EXEC);
172452094c8aSAl Viro }
172552094c8aSAl Viro 
172603fa86e9SAl Viro static int reserve_stack(struct nameidata *nd, struct path *link)
1727d63ff28fSAl Viro {
172849055906SAl Viro 	if (unlikely(nd->total_link_count++ >= MAXSYMLINKS))
172949055906SAl Viro 		return -ELOOP;
17304542576bSAl Viro 
17314542576bSAl Viro 	if (likely(nd->depth != EMBEDDED_LEVELS))
17324542576bSAl Viro 		return 0;
17334542576bSAl Viro 	if (likely(nd->stack != nd->internal))
17344542576bSAl Viro 		return 0;
173560ef60c7SAl Viro 	if (likely(nd_alloc_stack(nd)))
173649055906SAl Viro 		return 0;
173760ef60c7SAl Viro 
173860ef60c7SAl Viro 	if (nd->flags & LOOKUP_RCU) {
173960ef60c7SAl Viro 		// we need to grab link before we do unlazy.  And we can't skip
174060ef60c7SAl Viro 		// unlazy even if we fail to grab the link - cleanup needs it
174103fa86e9SAl Viro 		bool grabbed_link = legitimize_path(nd, link, nd->next_seq);
174260ef60c7SAl Viro 
1743e5ca024eSAl Viro 		if (!try_to_unlazy(nd) || !grabbed_link)
174460ef60c7SAl Viro 			return -ECHILD;
174560ef60c7SAl Viro 
174660ef60c7SAl Viro 		if (nd_alloc_stack(nd))
174760ef60c7SAl Viro 			return 0;
1748bc40aee0SAl Viro 	}
174960ef60c7SAl Viro 	return -ENOMEM;
175049055906SAl Viro }
175149055906SAl Viro 
175249055906SAl Viro enum {WALK_TRAILING = 1, WALK_MORE = 2, WALK_NOFOLLOW = 4};
175349055906SAl Viro 
175449055906SAl Viro static const char *pick_link(struct nameidata *nd, struct path *link,
175503fa86e9SAl Viro 		     struct inode *inode, int flags)
175649055906SAl Viro {
175749055906SAl Viro 	struct saved *last;
175849055906SAl Viro 	const char *res;
175903fa86e9SAl Viro 	int error = reserve_stack(nd, link);
176049055906SAl Viro 
176149055906SAl Viro 	if (unlikely(error)) {
176249055906SAl Viro 		if (!(nd->flags & LOOKUP_RCU))
1763cd179f44SAl Viro 			path_put(link);
176406708adbSAl Viro 		return ERR_PTR(error);
1765626de996SAl Viro 	}
1766ab104923SAl Viro 	last = nd->stack + nd->depth++;
17671cf2665bSAl Viro 	last->link = *link;
1768fceef393SAl Viro 	clear_delayed_call(&last->done);
176903fa86e9SAl Viro 	last->seq = nd->next_seq;
1770ad6cc4c3SAl Viro 
1771b1a81972SAl Viro 	if (flags & WALK_TRAILING) {
1772ad6cc4c3SAl Viro 		error = may_follow_link(nd, inode);
1773ad6cc4c3SAl Viro 		if (unlikely(error))
1774ad6cc4c3SAl Viro 			return ERR_PTR(error);
1775ad6cc4c3SAl Viro 	}
1776ad6cc4c3SAl Viro 
1777dab741e0SMattias Nissler 	if (unlikely(nd->flags & LOOKUP_NO_SYMLINKS) ||
1778dab741e0SMattias Nissler 			unlikely(link->mnt->mnt_flags & MNT_NOSYMFOLLOW))
1779ad6cc4c3SAl Viro 		return ERR_PTR(-ELOOP);
1780ad6cc4c3SAl Viro 
1781ad6cc4c3SAl Viro 	if (!(nd->flags & LOOKUP_RCU)) {
1782ad6cc4c3SAl Viro 		touch_atime(&last->link);
1783ad6cc4c3SAl Viro 		cond_resched();
1784ad6cc4c3SAl Viro 	} else if (atime_needs_update(&last->link, inode)) {
1785e36cffedSJens Axboe 		if (!try_to_unlazy(nd))
1786ad6cc4c3SAl Viro 			return ERR_PTR(-ECHILD);
1787ad6cc4c3SAl Viro 		touch_atime(&last->link);
1788ad6cc4c3SAl Viro 	}
1789ad6cc4c3SAl Viro 
1790ad6cc4c3SAl Viro 	error = security_inode_follow_link(link->dentry, inode,
1791ad6cc4c3SAl Viro 					   nd->flags & LOOKUP_RCU);
1792ad6cc4c3SAl Viro 	if (unlikely(error))
1793ad6cc4c3SAl Viro 		return ERR_PTR(error);
1794ad6cc4c3SAl Viro 
1795ad6cc4c3SAl Viro 	res = READ_ONCE(inode->i_link);
1796ad6cc4c3SAl Viro 	if (!res) {
1797ad6cc4c3SAl Viro 		const char * (*get)(struct dentry *, struct inode *,
1798ad6cc4c3SAl Viro 				struct delayed_call *);
1799ad6cc4c3SAl Viro 		get = inode->i_op->get_link;
1800ad6cc4c3SAl Viro 		if (nd->flags & LOOKUP_RCU) {
1801ad6cc4c3SAl Viro 			res = get(NULL, inode, &last->done);
1802e36cffedSJens Axboe 			if (res == ERR_PTR(-ECHILD) && try_to_unlazy(nd))
1803ad6cc4c3SAl Viro 				res = get(link->dentry, inode, &last->done);
1804ad6cc4c3SAl Viro 		} else {
1805ad6cc4c3SAl Viro 			res = get(link->dentry, inode, &last->done);
1806ad6cc4c3SAl Viro 		}
1807ad6cc4c3SAl Viro 		if (!res)
1808ad6cc4c3SAl Viro 			goto all_done;
1809ad6cc4c3SAl Viro 		if (IS_ERR(res))
1810ad6cc4c3SAl Viro 			return res;
1811ad6cc4c3SAl Viro 	}
1812ad6cc4c3SAl Viro 	if (*res == '/') {
1813ad6cc4c3SAl Viro 		error = nd_jump_root(nd);
1814ad6cc4c3SAl Viro 		if (unlikely(error))
1815ad6cc4c3SAl Viro 			return ERR_PTR(error);
1816ad6cc4c3SAl Viro 		while (unlikely(*++res == '/'))
1817ad6cc4c3SAl Viro 			;
1818ad6cc4c3SAl Viro 	}
1819ad6cc4c3SAl Viro 	if (*res)
1820ad6cc4c3SAl Viro 		return res;
1821ad6cc4c3SAl Viro all_done: // pure jump
1822ad6cc4c3SAl Viro 	put_link(nd);
1823ad6cc4c3SAl Viro 	return NULL;
1824d63ff28fSAl Viro }
1825d63ff28fSAl Viro 
18263ddcd056SLinus Torvalds /*
18273ddcd056SLinus Torvalds  * Do we need to follow links? We _really_ want to be able
18283ddcd056SLinus Torvalds  * to do this check without having to look at inode->i_op,
18293ddcd056SLinus Torvalds  * so we keep a cache of "no, this doesn't need follow_link"
18303ddcd056SLinus Torvalds  * for the common case.
183103fa86e9SAl Viro  *
183203fa86e9SAl Viro  * NOTE: dentry must be what nd->next_seq had been sampled from.
18333ddcd056SLinus Torvalds  */
1834b0417d2cSAl Viro static const char *step_into(struct nameidata *nd, int flags,
1835a4f5b521SAl Viro 		     struct dentry *dentry)
18363ddcd056SLinus Torvalds {
1837cbae4d12SAl Viro 	struct path path;
1838a4f5b521SAl Viro 	struct inode *inode;
18393bd8bc89SAl Viro 	int err = handle_mounts(nd, dentry, &path);
1840cbae4d12SAl Viro 
1841cbae4d12SAl Viro 	if (err < 0)
1842b0417d2cSAl Viro 		return ERR_PTR(err);
18433bd8bc89SAl Viro 	inode = path.dentry->d_inode;
1844cbae4d12SAl Viro 	if (likely(!d_is_symlink(path.dentry)) ||
18458c4efe22SAl Viro 	   ((flags & WALK_TRAILING) && !(nd->flags & LOOKUP_FOLLOW)) ||
1846aca2903eSAl Viro 	   (flags & WALK_NOFOLLOW)) {
18478f64fb1cSAl Viro 		/* not a symlink or should not follow */
18483bd8bc89SAl Viro 		if (nd->flags & LOOKUP_RCU) {
18493bd8bc89SAl Viro 			if (read_seqcount_retry(&path.dentry->d_seq, nd->next_seq))
18503bd8bc89SAl Viro 				return ERR_PTR(-ECHILD);
18513bd8bc89SAl Viro 			if (unlikely(!inode))
18523bd8bc89SAl Viro 				return ERR_PTR(-ENOENT);
18533bd8bc89SAl Viro 		} else {
1854c99687a0SAl Viro 			dput(nd->path.dentry);
1855c99687a0SAl Viro 			if (nd->path.mnt != path.mnt)
1856c99687a0SAl Viro 				mntput(nd->path.mnt);
1857c99687a0SAl Viro 		}
1858c99687a0SAl Viro 		nd->path = path;
18598f64fb1cSAl Viro 		nd->inode = inode;
186003fa86e9SAl Viro 		nd->seq = nd->next_seq;
1861b0417d2cSAl Viro 		return NULL;
18628f64fb1cSAl Viro 	}
1863a7f77542SAl Viro 	if (nd->flags & LOOKUP_RCU) {
186484f0cd9eSAl Viro 		/* make sure that d_is_symlink above matches inode */
186503fa86e9SAl Viro 		if (read_seqcount_retry(&path.dentry->d_seq, nd->next_seq))
1866b0417d2cSAl Viro 			return ERR_PTR(-ECHILD);
186784f0cd9eSAl Viro 	} else {
186884f0cd9eSAl Viro 		if (path.mnt == nd->path.mnt)
186984f0cd9eSAl Viro 			mntget(path.mnt);
1870a7f77542SAl Viro 	}
187103fa86e9SAl Viro 	return pick_link(nd, &path, inode, flags);
18723ddcd056SLinus Torvalds }
18733ddcd056SLinus Torvalds 
1874b16c001dSAl Viro static struct dentry *follow_dotdot_rcu(struct nameidata *nd)
1875957dd41dSAl Viro {
187612487f30SAl Viro 	struct dentry *parent, *old;
1877957dd41dSAl Viro 
187812487f30SAl Viro 	if (path_equal(&nd->path, &nd->root))
187912487f30SAl Viro 		goto in_root;
188012487f30SAl Viro 	if (unlikely(nd->path.dentry == nd->path.mnt->mnt_root)) {
18817ef482faSAl Viro 		struct path path;
1882efe772d6SAl Viro 		unsigned seq;
18837ef482faSAl Viro 		if (!choose_mountpoint_rcu(real_mount(nd->path.mnt),
18847ef482faSAl Viro 					   &nd->root, &path, &seq))
188512487f30SAl Viro 			goto in_root;
1886efe772d6SAl Viro 		if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1887efe772d6SAl Viro 			return ERR_PTR(-ECHILD);
1888efe772d6SAl Viro 		nd->path = path;
1889efe772d6SAl Viro 		nd->inode = path.dentry->d_inode;
1890efe772d6SAl Viro 		nd->seq = seq;
189103fa86e9SAl Viro 		// makes sure that non-RCU pathwalk could reach this state
189282ef0698SAl Viro 		if (read_seqretry(&mount_lock, nd->m_seq))
1893efe772d6SAl Viro 			return ERR_PTR(-ECHILD);
1894efe772d6SAl Viro 		/* we know that mountpoint was pinned */
1895957dd41dSAl Viro 	}
189612487f30SAl Viro 	old = nd->path.dentry;
189712487f30SAl Viro 	parent = old->d_parent;
189803fa86e9SAl Viro 	nd->next_seq = read_seqcount_begin(&parent->d_seq);
189903fa86e9SAl Viro 	// makes sure that non-RCU pathwalk could reach this state
190082ef0698SAl Viro 	if (read_seqcount_retry(&old->d_seq, nd->seq))
190112487f30SAl Viro 		return ERR_PTR(-ECHILD);
190212487f30SAl Viro 	if (unlikely(!path_connected(nd->path.mnt, parent)))
190312487f30SAl Viro 		return ERR_PTR(-ECHILD);
190412487f30SAl Viro 	return parent;
190512487f30SAl Viro in_root:
190682ef0698SAl Viro 	if (read_seqretry(&mount_lock, nd->m_seq))
1907efe772d6SAl Viro 		return ERR_PTR(-ECHILD);
1908957dd41dSAl Viro 	if (unlikely(nd->flags & LOOKUP_BENEATH))
19097521f22bSAl Viro 		return ERR_PTR(-ECHILD);
191003fa86e9SAl Viro 	nd->next_seq = nd->seq;
191151c6546cSAl Viro 	return nd->path.dentry;
1912957dd41dSAl Viro }
1913957dd41dSAl Viro 
1914b16c001dSAl Viro static struct dentry *follow_dotdot(struct nameidata *nd)
1915957dd41dSAl Viro {
191612487f30SAl Viro 	struct dentry *parent;
191712487f30SAl Viro 
1918957dd41dSAl Viro 	if (path_equal(&nd->path, &nd->root))
191912487f30SAl Viro 		goto in_root;
192012487f30SAl Viro 	if (unlikely(nd->path.dentry == nd->path.mnt->mnt_root)) {
19212aa38470SAl Viro 		struct path path;
19222aa38470SAl Viro 
19232aa38470SAl Viro 		if (!choose_mountpoint(real_mount(nd->path.mnt),
19242aa38470SAl Viro 				       &nd->root, &path))
192512487f30SAl Viro 			goto in_root;
1926165200d6SAl Viro 		path_put(&nd->path);
1927165200d6SAl Viro 		nd->path = path;
19282aa38470SAl Viro 		nd->inode = path.dentry->d_inode;
1929165200d6SAl Viro 		if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1930165200d6SAl Viro 			return ERR_PTR(-EXDEV);
193112487f30SAl Viro 	}
1932957dd41dSAl Viro 	/* rare case of legitimate dget_parent()... */
193312487f30SAl Viro 	parent = dget_parent(nd->path.dentry);
1934957dd41dSAl Viro 	if (unlikely(!path_connected(nd->path.mnt, parent))) {
1935957dd41dSAl Viro 		dput(parent);
19367521f22bSAl Viro 		return ERR_PTR(-ENOENT);
1937957dd41dSAl Viro 	}
1938c2df1968SAl Viro 	return parent;
193912487f30SAl Viro 
194012487f30SAl Viro in_root:
1941957dd41dSAl Viro 	if (unlikely(nd->flags & LOOKUP_BENEATH))
19427521f22bSAl Viro 		return ERR_PTR(-EXDEV);
194351c6546cSAl Viro 	return dget(nd->path.dentry);
1944957dd41dSAl Viro }
1945957dd41dSAl Viro 
19467521f22bSAl Viro static const char *handle_dots(struct nameidata *nd, int type)
1947957dd41dSAl Viro {
1948957dd41dSAl Viro 	if (type == LAST_DOTDOT) {
19497521f22bSAl Viro 		const char *error = NULL;
1950c2df1968SAl Viro 		struct dentry *parent;
1951957dd41dSAl Viro 
1952957dd41dSAl Viro 		if (!nd->root.mnt) {
19537521f22bSAl Viro 			error = ERR_PTR(set_root(nd));
1954957dd41dSAl Viro 			if (error)
1955957dd41dSAl Viro 				return error;
1956957dd41dSAl Viro 		}
1957957dd41dSAl Viro 		if (nd->flags & LOOKUP_RCU)
1958b16c001dSAl Viro 			parent = follow_dotdot_rcu(nd);
1959957dd41dSAl Viro 		else
1960b16c001dSAl Viro 			parent = follow_dotdot(nd);
1961c2df1968SAl Viro 		if (IS_ERR(parent))
1962c2df1968SAl Viro 			return ERR_CAST(parent);
1963a4f5b521SAl Viro 		error = step_into(nd, WALK_NOFOLLOW, parent);
1964c2df1968SAl Viro 		if (unlikely(error))
1965957dd41dSAl Viro 			return error;
1966957dd41dSAl Viro 
1967957dd41dSAl Viro 		if (unlikely(nd->flags & LOOKUP_IS_SCOPED)) {
1968957dd41dSAl Viro 			/*
1969957dd41dSAl Viro 			 * If there was a racing rename or mount along our
1970957dd41dSAl Viro 			 * path, then we can't be sure that ".." hasn't jumped
1971957dd41dSAl Viro 			 * above nd->root (and so userspace should retry or use
1972957dd41dSAl Viro 			 * some fallback).
1973957dd41dSAl Viro 			 */
1974957dd41dSAl Viro 			smp_rmb();
197582ef0698SAl Viro 			if (__read_seqcount_retry(&mount_lock.seqcount, nd->m_seq))
19767521f22bSAl Viro 				return ERR_PTR(-EAGAIN);
197782ef0698SAl Viro 			if (__read_seqcount_retry(&rename_lock.seqcount, nd->r_seq))
19787521f22bSAl Viro 				return ERR_PTR(-EAGAIN);
1979957dd41dSAl Viro 		}
1980957dd41dSAl Viro 	}
19817521f22bSAl Viro 	return NULL;
1982957dd41dSAl Viro }
1983957dd41dSAl Viro 
198492d27016SAl Viro static const char *walk_component(struct nameidata *nd, int flags)
1985ce57dfc1SAl Viro {
1986db3c9adeSAl Viro 	struct dentry *dentry;
1987ce57dfc1SAl Viro 	/*
1988ce57dfc1SAl Viro 	 * "." and ".." are special - ".." especially so because it has
1989ce57dfc1SAl Viro 	 * to be able to know about the current root directory and
1990ce57dfc1SAl Viro 	 * parent relationships.
1991ce57dfc1SAl Viro 	 */
19924693a547SAl Viro 	if (unlikely(nd->last_type != LAST_NORM)) {
19931c4ff1a8SAl Viro 		if (!(flags & WALK_MORE) && nd->depth)
19944693a547SAl Viro 			put_link(nd);
19957521f22bSAl Viro 		return handle_dots(nd, nd->last_type);
19964693a547SAl Viro 	}
19974cb64024SAl Viro 	dentry = lookup_fast(nd);
199820e34357SAl Viro 	if (IS_ERR(dentry))
199992d27016SAl Viro 		return ERR_CAST(dentry);
200020e34357SAl Viro 	if (unlikely(!dentry)) {
2001db3c9adeSAl Viro 		dentry = lookup_slow(&nd->last, nd->path.dentry, nd->flags);
2002db3c9adeSAl Viro 		if (IS_ERR(dentry))
200392d27016SAl Viro 			return ERR_CAST(dentry);
200420e34357SAl Viro 	}
200556676ec3SAl Viro 	if (!(flags & WALK_MORE) && nd->depth)
200656676ec3SAl Viro 		put_link(nd);
2007a4f5b521SAl Viro 	return step_into(nd, flags, dentry);
2008ce57dfc1SAl Viro }
2009ce57dfc1SAl Viro 
20101da177e4SLinus Torvalds /*
2011bfcfaa77SLinus Torvalds  * We can do the critical dentry name comparison and hashing
2012bfcfaa77SLinus Torvalds  * operations one word at a time, but we are limited to:
2013bfcfaa77SLinus Torvalds  *
2014bfcfaa77SLinus Torvalds  * - Architectures with fast unaligned word accesses. We could
2015bfcfaa77SLinus Torvalds  *   do a "get_unaligned()" if this helps and is sufficiently
2016bfcfaa77SLinus Torvalds  *   fast.
2017bfcfaa77SLinus Torvalds  *
2018bfcfaa77SLinus Torvalds  * - non-CONFIG_DEBUG_PAGEALLOC configurations (so that we
2019bfcfaa77SLinus Torvalds  *   do not trap on the (extremely unlikely) case of a page
2020bfcfaa77SLinus Torvalds  *   crossing operation.
2021bfcfaa77SLinus Torvalds  *
2022bfcfaa77SLinus Torvalds  * - Furthermore, we need an efficient 64-bit compile for the
2023bfcfaa77SLinus Torvalds  *   64-bit case in order to generate the "number of bytes in
2024bfcfaa77SLinus Torvalds  *   the final mask". Again, that could be replaced with a
2025bfcfaa77SLinus Torvalds  *   efficient population count instruction or similar.
2026bfcfaa77SLinus Torvalds  */
2027bfcfaa77SLinus Torvalds #ifdef CONFIG_DCACHE_WORD_ACCESS
2028bfcfaa77SLinus Torvalds 
2029f68e556eSLinus Torvalds #include <asm/word-at-a-time.h>
2030bfcfaa77SLinus Torvalds 
2031468a9428SGeorge Spelvin #ifdef HASH_MIX
2032bfcfaa77SLinus Torvalds 
2033468a9428SGeorge Spelvin /* Architecture provides HASH_MIX and fold_hash() in <asm/hash.h> */
2034468a9428SGeorge Spelvin 
2035468a9428SGeorge Spelvin #elif defined(CONFIG_64BIT)
20362a18da7aSGeorge Spelvin /*
20372a18da7aSGeorge Spelvin  * Register pressure in the mixing function is an issue, particularly
20382a18da7aSGeorge Spelvin  * on 32-bit x86, but almost any function requires one state value and
20392a18da7aSGeorge Spelvin  * one temporary.  Instead, use a function designed for two state values
20402a18da7aSGeorge Spelvin  * and no temporaries.
20412a18da7aSGeorge Spelvin  *
20422a18da7aSGeorge Spelvin  * This function cannot create a collision in only two iterations, so
20432a18da7aSGeorge Spelvin  * we have two iterations to achieve avalanche.  In those two iterations,
20442a18da7aSGeorge Spelvin  * we have six layers of mixing, which is enough to spread one bit's
20452a18da7aSGeorge Spelvin  * influence out to 2^6 = 64 state bits.
20462a18da7aSGeorge Spelvin  *
20472a18da7aSGeorge Spelvin  * Rotate constants are scored by considering either 64 one-bit input
20482a18da7aSGeorge Spelvin  * deltas or 64*63/2 = 2016 two-bit input deltas, and finding the
20492a18da7aSGeorge Spelvin  * probability of that delta causing a change to each of the 128 output
20502a18da7aSGeorge Spelvin  * bits, using a sample of random initial states.
20512a18da7aSGeorge Spelvin  *
20522a18da7aSGeorge Spelvin  * The Shannon entropy of the computed probabilities is then summed
20532a18da7aSGeorge Spelvin  * to produce a score.  Ideally, any input change has a 50% chance of
20542a18da7aSGeorge Spelvin  * toggling any given output bit.
20552a18da7aSGeorge Spelvin  *
20562a18da7aSGeorge Spelvin  * Mixing scores (in bits) for (12,45):
20572a18da7aSGeorge Spelvin  * Input delta: 1-bit      2-bit
20582a18da7aSGeorge Spelvin  * 1 round:     713.3    42542.6
20592a18da7aSGeorge Spelvin  * 2 rounds:   2753.7   140389.8
20602a18da7aSGeorge Spelvin  * 3 rounds:   5954.1   233458.2
20612a18da7aSGeorge Spelvin  * 4 rounds:   7862.6   256672.2
20622a18da7aSGeorge Spelvin  * Perfect:    8192     258048
20632a18da7aSGeorge Spelvin  *            (64*128) (64*63/2 * 128)
20642a18da7aSGeorge Spelvin  */
20652a18da7aSGeorge Spelvin #define HASH_MIX(x, y, a)	\
20662a18da7aSGeorge Spelvin 	(	x ^= (a),	\
20672a18da7aSGeorge Spelvin 	y ^= x,	x = rol64(x,12),\
20682a18da7aSGeorge Spelvin 	x += y,	y = rol64(y,45),\
20692a18da7aSGeorge Spelvin 	y *= 9			)
2070bfcfaa77SLinus Torvalds 
20710fed3ac8SGeorge Spelvin /*
20722a18da7aSGeorge Spelvin  * Fold two longs into one 32-bit hash value.  This must be fast, but
20732a18da7aSGeorge Spelvin  * latency isn't quite as critical, as there is a fair bit of additional
20742a18da7aSGeorge Spelvin  * work done before the hash value is used.
20750fed3ac8SGeorge Spelvin  */
20762a18da7aSGeorge Spelvin static inline unsigned int fold_hash(unsigned long x, unsigned long y)
20770fed3ac8SGeorge Spelvin {
20782a18da7aSGeorge Spelvin 	y ^= x * GOLDEN_RATIO_64;
20792a18da7aSGeorge Spelvin 	y *= GOLDEN_RATIO_64;
20802a18da7aSGeorge Spelvin 	return y >> 32;
20810fed3ac8SGeorge Spelvin }
20820fed3ac8SGeorge Spelvin 
2083bfcfaa77SLinus Torvalds #else	/* 32-bit case */
2084bfcfaa77SLinus Torvalds 
20852a18da7aSGeorge Spelvin /*
20862a18da7aSGeorge Spelvin  * Mixing scores (in bits) for (7,20):
20872a18da7aSGeorge Spelvin  * Input delta: 1-bit      2-bit
20882a18da7aSGeorge Spelvin  * 1 round:     330.3     9201.6
20892a18da7aSGeorge Spelvin  * 2 rounds:   1246.4    25475.4
20902a18da7aSGeorge Spelvin  * 3 rounds:   1907.1    31295.1
20912a18da7aSGeorge Spelvin  * 4 rounds:   2042.3    31718.6
20922a18da7aSGeorge Spelvin  * Perfect:    2048      31744
20932a18da7aSGeorge Spelvin  *            (32*64)   (32*31/2 * 64)
20942a18da7aSGeorge Spelvin  */
20952a18da7aSGeorge Spelvin #define HASH_MIX(x, y, a)	\
20962a18da7aSGeorge Spelvin 	(	x ^= (a),	\
20972a18da7aSGeorge Spelvin 	y ^= x,	x = rol32(x, 7),\
20982a18da7aSGeorge Spelvin 	x += y,	y = rol32(y,20),\
20992a18da7aSGeorge Spelvin 	y *= 9			)
2100bfcfaa77SLinus Torvalds 
21012a18da7aSGeorge Spelvin static inline unsigned int fold_hash(unsigned long x, unsigned long y)
21020fed3ac8SGeorge Spelvin {
21032a18da7aSGeorge Spelvin 	/* Use arch-optimized multiply if one exists */
21042a18da7aSGeorge Spelvin 	return __hash_32(y ^ __hash_32(x));
21050fed3ac8SGeorge Spelvin }
21060fed3ac8SGeorge Spelvin 
2107bfcfaa77SLinus Torvalds #endif
2108bfcfaa77SLinus Torvalds 
21092a18da7aSGeorge Spelvin /*
21102a18da7aSGeorge Spelvin  * Return the hash of a string of known length.  This is carfully
21112a18da7aSGeorge Spelvin  * designed to match hash_name(), which is the more critical function.
21122a18da7aSGeorge Spelvin  * In particular, we must end by hashing a final word containing 0..7
21132a18da7aSGeorge Spelvin  * payload bytes, to match the way that hash_name() iterates until it
21142a18da7aSGeorge Spelvin  * finds the delimiter after the name.
21152a18da7aSGeorge Spelvin  */
21168387ff25SLinus Torvalds unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
2117bfcfaa77SLinus Torvalds {
21188387ff25SLinus Torvalds 	unsigned long a, x = 0, y = (unsigned long)salt;
2119bfcfaa77SLinus Torvalds 
2120bfcfaa77SLinus Torvalds 	for (;;) {
2121fcfd2fbfSGeorge Spelvin 		if (!len)
2122fcfd2fbfSGeorge Spelvin 			goto done;
2123e419b4ccSLinus Torvalds 		a = load_unaligned_zeropad(name);
2124bfcfaa77SLinus Torvalds 		if (len < sizeof(unsigned long))
2125bfcfaa77SLinus Torvalds 			break;
21262a18da7aSGeorge Spelvin 		HASH_MIX(x, y, a);
2127bfcfaa77SLinus Torvalds 		name += sizeof(unsigned long);
2128bfcfaa77SLinus Torvalds 		len -= sizeof(unsigned long);
2129bfcfaa77SLinus Torvalds 	}
21302a18da7aSGeorge Spelvin 	x ^= a & bytemask_from_count(len);
2131bfcfaa77SLinus Torvalds done:
21322a18da7aSGeorge Spelvin 	return fold_hash(x, y);
2133bfcfaa77SLinus Torvalds }
2134bfcfaa77SLinus Torvalds EXPORT_SYMBOL(full_name_hash);
2135bfcfaa77SLinus Torvalds 
2136fcfd2fbfSGeorge Spelvin /* Return the "hash_len" (hash and length) of a null-terminated string */
21378387ff25SLinus Torvalds u64 hashlen_string(const void *salt, const char *name)
2138fcfd2fbfSGeorge Spelvin {
21398387ff25SLinus Torvalds 	unsigned long a = 0, x = 0, y = (unsigned long)salt;
21408387ff25SLinus Torvalds 	unsigned long adata, mask, len;
2141fcfd2fbfSGeorge Spelvin 	const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2142fcfd2fbfSGeorge Spelvin 
21438387ff25SLinus Torvalds 	len = 0;
21448387ff25SLinus Torvalds 	goto inside;
21458387ff25SLinus Torvalds 
2146fcfd2fbfSGeorge Spelvin 	do {
21472a18da7aSGeorge Spelvin 		HASH_MIX(x, y, a);
2148fcfd2fbfSGeorge Spelvin 		len += sizeof(unsigned long);
21498387ff25SLinus Torvalds inside:
2150fcfd2fbfSGeorge Spelvin 		a = load_unaligned_zeropad(name+len);
2151fcfd2fbfSGeorge Spelvin 	} while (!has_zero(a, &adata, &constants));
2152fcfd2fbfSGeorge Spelvin 
2153fcfd2fbfSGeorge Spelvin 	adata = prep_zero_mask(a, adata, &constants);
2154fcfd2fbfSGeorge Spelvin 	mask = create_zero_mask(adata);
21552a18da7aSGeorge Spelvin 	x ^= a & zero_bytemask(mask);
2156fcfd2fbfSGeorge Spelvin 
21572a18da7aSGeorge Spelvin 	return hashlen_create(fold_hash(x, y), len + find_zero(mask));
2158fcfd2fbfSGeorge Spelvin }
2159fcfd2fbfSGeorge Spelvin EXPORT_SYMBOL(hashlen_string);
2160fcfd2fbfSGeorge Spelvin 
2161bfcfaa77SLinus Torvalds /*
2162bfcfaa77SLinus Torvalds  * Calculate the length and hash of the path component, and
2163d6bb3e90SLinus Torvalds  * return the "hash_len" as the result.
2164bfcfaa77SLinus Torvalds  */
21658387ff25SLinus Torvalds static inline u64 hash_name(const void *salt, const char *name)
2166bfcfaa77SLinus Torvalds {
21678387ff25SLinus Torvalds 	unsigned long a = 0, b, x = 0, y = (unsigned long)salt;
21688387ff25SLinus Torvalds 	unsigned long adata, bdata, mask, len;
216936126f8fSLinus Torvalds 	const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2170bfcfaa77SLinus Torvalds 
21718387ff25SLinus Torvalds 	len = 0;
21728387ff25SLinus Torvalds 	goto inside;
21738387ff25SLinus Torvalds 
2174bfcfaa77SLinus Torvalds 	do {
21752a18da7aSGeorge Spelvin 		HASH_MIX(x, y, a);
2176bfcfaa77SLinus Torvalds 		len += sizeof(unsigned long);
21778387ff25SLinus Torvalds inside:
2178e419b4ccSLinus Torvalds 		a = load_unaligned_zeropad(name+len);
217936126f8fSLinus Torvalds 		b = a ^ REPEAT_BYTE('/');
218036126f8fSLinus Torvalds 	} while (!(has_zero(a, &adata, &constants) | has_zero(b, &bdata, &constants)));
2181bfcfaa77SLinus Torvalds 
218236126f8fSLinus Torvalds 	adata = prep_zero_mask(a, adata, &constants);
218336126f8fSLinus Torvalds 	bdata = prep_zero_mask(b, bdata, &constants);
218436126f8fSLinus Torvalds 	mask = create_zero_mask(adata | bdata);
21852a18da7aSGeorge Spelvin 	x ^= a & zero_bytemask(mask);
218636126f8fSLinus Torvalds 
21872a18da7aSGeorge Spelvin 	return hashlen_create(fold_hash(x, y), len + find_zero(mask));
2188bfcfaa77SLinus Torvalds }
2189bfcfaa77SLinus Torvalds 
21902a18da7aSGeorge Spelvin #else	/* !CONFIG_DCACHE_WORD_ACCESS: Slow, byte-at-a-time version */
2191bfcfaa77SLinus Torvalds 
2192fcfd2fbfSGeorge Spelvin /* Return the hash of a string of known length */
21938387ff25SLinus Torvalds unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
21940145acc2SLinus Torvalds {
21958387ff25SLinus Torvalds 	unsigned long hash = init_name_hash(salt);
21960145acc2SLinus Torvalds 	while (len--)
2197fcfd2fbfSGeorge Spelvin 		hash = partial_name_hash((unsigned char)*name++, hash);
21980145acc2SLinus Torvalds 	return end_name_hash(hash);
21990145acc2SLinus Torvalds }
2200ae942ae7SLinus Torvalds EXPORT_SYMBOL(full_name_hash);
22010145acc2SLinus Torvalds 
2202fcfd2fbfSGeorge Spelvin /* Return the "hash_len" (hash and length) of a null-terminated string */
22038387ff25SLinus Torvalds u64 hashlen_string(const void *salt, const char *name)
2204fcfd2fbfSGeorge Spelvin {
22058387ff25SLinus Torvalds 	unsigned long hash = init_name_hash(salt);
2206fcfd2fbfSGeorge Spelvin 	unsigned long len = 0, c;
2207fcfd2fbfSGeorge Spelvin 
2208fcfd2fbfSGeorge Spelvin 	c = (unsigned char)*name;
2209e0ab7af9SGeorge Spelvin 	while (c) {
2210fcfd2fbfSGeorge Spelvin 		len++;
2211fcfd2fbfSGeorge Spelvin 		hash = partial_name_hash(c, hash);
2212fcfd2fbfSGeorge Spelvin 		c = (unsigned char)name[len];
2213e0ab7af9SGeorge Spelvin 	}
2214fcfd2fbfSGeorge Spelvin 	return hashlen_create(end_name_hash(hash), len);
2215fcfd2fbfSGeorge Spelvin }
2216f2a031b6SGeorge Spelvin EXPORT_SYMBOL(hashlen_string);
2217fcfd2fbfSGeorge Spelvin 
22183ddcd056SLinus Torvalds /*
2219200e9ef7SLinus Torvalds  * We know there's a real path component here of at least
2220200e9ef7SLinus Torvalds  * one character.
2221200e9ef7SLinus Torvalds  */
22228387ff25SLinus Torvalds static inline u64 hash_name(const void *salt, const char *name)
2223200e9ef7SLinus Torvalds {
22248387ff25SLinus Torvalds 	unsigned long hash = init_name_hash(salt);
2225200e9ef7SLinus Torvalds 	unsigned long len = 0, c;
2226200e9ef7SLinus Torvalds 
2227200e9ef7SLinus Torvalds 	c = (unsigned char)*name;
2228200e9ef7SLinus Torvalds 	do {
2229200e9ef7SLinus Torvalds 		len++;
2230200e9ef7SLinus Torvalds 		hash = partial_name_hash(c, hash);
2231200e9ef7SLinus Torvalds 		c = (unsigned char)name[len];
2232200e9ef7SLinus Torvalds 	} while (c && c != '/');
2233d6bb3e90SLinus Torvalds 	return hashlen_create(end_name_hash(hash), len);
2234200e9ef7SLinus Torvalds }
2235200e9ef7SLinus Torvalds 
2236bfcfaa77SLinus Torvalds #endif
2237bfcfaa77SLinus Torvalds 
2238200e9ef7SLinus Torvalds /*
22391da177e4SLinus Torvalds  * Name resolution.
2240ea3834d9SPrasanna Meda  * This is the basic name resolution function, turning a pathname into
2241ea3834d9SPrasanna Meda  * the final dentry. We expect 'base' to be positive and a directory.
22421da177e4SLinus Torvalds  *
2243ea3834d9SPrasanna Meda  * Returns 0 and nd will have valid dentry and mnt on success.
2244ea3834d9SPrasanna Meda  * Returns error and drops reference to input namei data on failure.
22451da177e4SLinus Torvalds  */
22466de88d72SAl Viro static int link_path_walk(const char *name, struct nameidata *nd)
22471da177e4SLinus Torvalds {
2248d8d4611aSAl Viro 	int depth = 0; // depth <= nd->depth
22491da177e4SLinus Torvalds 	int err;
22501da177e4SLinus Torvalds 
2251b4c03536SAl Viro 	nd->last_type = LAST_ROOT;
2252c108837eSAl Viro 	nd->flags |= LOOKUP_PARENT;
22539b5858e9SAl Viro 	if (IS_ERR(name))
22549b5858e9SAl Viro 		return PTR_ERR(name);
22551da177e4SLinus Torvalds 	while (*name=='/')
22561da177e4SLinus Torvalds 		name++;
22571a97d899SAl Viro 	if (!*name) {
22581a97d899SAl Viro 		nd->dir_mode = 0; // short-circuit the 'hardening' idiocy
22599e18f10aSAl Viro 		return 0;
22601a97d899SAl Viro 	}
22611da177e4SLinus Torvalds 
22621da177e4SLinus Torvalds 	/* At this point we know we have a real path component. */
22631da177e4SLinus Torvalds 	for(;;) {
22644609e1f1SChristian Brauner 		struct mnt_idmap *idmap;
226592d27016SAl Viro 		const char *link;
2266d6bb3e90SLinus Torvalds 		u64 hash_len;
2267fe479a58SAl Viro 		int type;
22681da177e4SLinus Torvalds 
22694609e1f1SChristian Brauner 		idmap = mnt_idmap(nd->path.mnt);
22704609e1f1SChristian Brauner 		err = may_lookup(idmap, nd);
22711da177e4SLinus Torvalds 		if (err)
22723595e234SAl Viro 			return err;
22731da177e4SLinus Torvalds 
22748387ff25SLinus Torvalds 		hash_len = hash_name(nd->path.dentry, name);
22751da177e4SLinus Torvalds 
2276fe479a58SAl Viro 		type = LAST_NORM;
2277d6bb3e90SLinus Torvalds 		if (name[0] == '.') switch (hashlen_len(hash_len)) {
2278fe479a58SAl Viro 			case 2:
2279200e9ef7SLinus Torvalds 				if (name[1] == '.') {
2280fe479a58SAl Viro 					type = LAST_DOTDOT;
2281bcba1e7dSAl Viro 					nd->state |= ND_JUMPED;
228216c2cd71SAl Viro 				}
2283fe479a58SAl Viro 				break;
2284fe479a58SAl Viro 			case 1:
2285fe479a58SAl Viro 				type = LAST_DOT;
2286fe479a58SAl Viro 		}
22875a202bcdSAl Viro 		if (likely(type == LAST_NORM)) {
22885a202bcdSAl Viro 			struct dentry *parent = nd->path.dentry;
2289bcba1e7dSAl Viro 			nd->state &= ~ND_JUMPED;
22905a202bcdSAl Viro 			if (unlikely(parent->d_flags & DCACHE_OP_HASH)) {
2291a060dc50SJames Hogan 				struct qstr this = { { .hash_len = hash_len }, .name = name };
2292da53be12SLinus Torvalds 				err = parent->d_op->d_hash(parent, &this);
22935a202bcdSAl Viro 				if (err < 0)
22943595e234SAl Viro 					return err;
2295d6bb3e90SLinus Torvalds 				hash_len = this.hash_len;
2296d6bb3e90SLinus Torvalds 				name = this.name;
22975a202bcdSAl Viro 			}
22985a202bcdSAl Viro 		}
2299fe479a58SAl Viro 
2300d6bb3e90SLinus Torvalds 		nd->last.hash_len = hash_len;
2301d6bb3e90SLinus Torvalds 		nd->last.name = name;
23025f4a6a69SAl Viro 		nd->last_type = type;
23035f4a6a69SAl Viro 
2304d6bb3e90SLinus Torvalds 		name += hashlen_len(hash_len);
2305d6bb3e90SLinus Torvalds 		if (!*name)
2306bdf6cbf1SAl Viro 			goto OK;
2307200e9ef7SLinus Torvalds 		/*
2308200e9ef7SLinus Torvalds 		 * If it wasn't NUL, we know it was '/'. Skip that
2309200e9ef7SLinus Torvalds 		 * slash, and continue until no more slashes.
2310200e9ef7SLinus Torvalds 		 */
2311200e9ef7SLinus Torvalds 		do {
2312d6bb3e90SLinus Torvalds 			name++;
2313d6bb3e90SLinus Torvalds 		} while (unlikely(*name == '/'));
23148620c238SAl Viro 		if (unlikely(!*name)) {
23158620c238SAl Viro OK:
2316d8d4611aSAl Viro 			/* pathname or trailing symlink, done */
2317c108837eSAl Viro 			if (!depth) {
2318e67fe633SChristian Brauner 				nd->dir_vfsuid = i_uid_into_vfsuid(idmap, nd->inode);
23190f705953SAl Viro 				nd->dir_mode = nd->inode->i_mode;
2320c108837eSAl Viro 				nd->flags &= ~LOOKUP_PARENT;
23218620c238SAl Viro 				return 0;
2322c108837eSAl Viro 			}
23238620c238SAl Viro 			/* last component of nested symlink */
2324d8d4611aSAl Viro 			name = nd->stack[--depth].name;
23258c4efe22SAl Viro 			link = walk_component(nd, 0);
23261c4ff1a8SAl Viro 		} else {
23271c4ff1a8SAl Viro 			/* not the last component */
23288c4efe22SAl Viro 			link = walk_component(nd, WALK_MORE);
23298620c238SAl Viro 		}
233092d27016SAl Viro 		if (unlikely(link)) {
233192d27016SAl Viro 			if (IS_ERR(link))
233292d27016SAl Viro 				return PTR_ERR(link);
233392d27016SAl Viro 			/* a symlink to follow */
2334d8d4611aSAl Viro 			nd->stack[depth++].name = name;
233592d27016SAl Viro 			name = link;
23369e18f10aSAl Viro 			continue;
233748c8b0c5SAl Viro 		}
233897242f99SAl Viro 		if (unlikely(!d_can_lookup(nd->path.dentry))) {
233997242f99SAl Viro 			if (nd->flags & LOOKUP_RCU) {
2340e36cffedSJens Axboe 				if (!try_to_unlazy(nd))
234197242f99SAl Viro 					return -ECHILD;
234297242f99SAl Viro 			}
23433595e234SAl Viro 			return -ENOTDIR;
23445f4a6a69SAl Viro 		}
2345ce57dfc1SAl Viro 	}
234697242f99SAl Viro }
23471da177e4SLinus Torvalds 
2348edc2b1daSAl Viro /* must be paired with terminate_walk() */
2349c8a53ee5SAl Viro static const char *path_init(struct nameidata *nd, unsigned flags)
235031e6b01fSNick Piggin {
2351740a1678SAleksa Sarai 	int error;
2352c8a53ee5SAl Viro 	const char *s = nd->name->name;
235331e6b01fSNick Piggin 
23546c6ec2b0SJens Axboe 	/* LOOKUP_CACHED requires RCU, ask caller to retry */
23556c6ec2b0SJens Axboe 	if ((flags & (LOOKUP_RCU | LOOKUP_CACHED)) == LOOKUP_CACHED)
23566c6ec2b0SJens Axboe 		return ERR_PTR(-EAGAIN);
23576c6ec2b0SJens Axboe 
2358c0eb027eSLinus Torvalds 	if (!*s)
2359c0eb027eSLinus Torvalds 		flags &= ~LOOKUP_RCU;
2360edc2b1daSAl Viro 	if (flags & LOOKUP_RCU)
2361edc2b1daSAl Viro 		rcu_read_lock();
236203fa86e9SAl Viro 	else
236303fa86e9SAl Viro 		nd->seq = nd->next_seq = 0;
2364c0eb027eSLinus Torvalds 
2365bcba1e7dSAl Viro 	nd->flags = flags;
2366bcba1e7dSAl Viro 	nd->state |= ND_JUMPED;
2367ab87f9a5SAleksa Sarai 
2368ab87f9a5SAleksa Sarai 	nd->m_seq = __read_seqcount_begin(&mount_lock.seqcount);
2369ab87f9a5SAleksa Sarai 	nd->r_seq = __read_seqcount_begin(&rename_lock.seqcount);
2370ab87f9a5SAleksa Sarai 	smp_rmb();
2371ab87f9a5SAleksa Sarai 
2372bcba1e7dSAl Viro 	if (nd->state & ND_ROOT_PRESET) {
2373b18825a7SDavid Howells 		struct dentry *root = nd->root.dentry;
2374b18825a7SDavid Howells 		struct inode *inode = root->d_inode;
237593893862SAl Viro 		if (*s && unlikely(!d_can_lookup(root)))
2376368ee9baSAl Viro 			return ERR_PTR(-ENOTDIR);
23775b6ca027SAl Viro 		nd->path = nd->root;
23785b6ca027SAl Viro 		nd->inode = inode;
23795b6ca027SAl Viro 		if (flags & LOOKUP_RCU) {
2380ab87f9a5SAleksa Sarai 			nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
23818f47a016SAl Viro 			nd->root_seq = nd->seq;
23825b6ca027SAl Viro 		} else {
23835b6ca027SAl Viro 			path_get(&nd->path);
23845b6ca027SAl Viro 		}
2385368ee9baSAl Viro 		return s;
23865b6ca027SAl Viro 	}
23875b6ca027SAl Viro 
238831e6b01fSNick Piggin 	nd->root.mnt = NULL;
238931e6b01fSNick Piggin 
23908db52c7eSAleksa Sarai 	/* Absolute pathname -- fetch the root (LOOKUP_IN_ROOT uses nd->dfd). */
23918db52c7eSAleksa Sarai 	if (*s == '/' && !(flags & LOOKUP_IN_ROOT)) {
2392740a1678SAleksa Sarai 		error = nd_jump_root(nd);
2393740a1678SAleksa Sarai 		if (unlikely(error))
2394740a1678SAleksa Sarai 			return ERR_PTR(error);
2395ef55d917SAl Viro 		return s;
23968db52c7eSAleksa Sarai 	}
23978db52c7eSAleksa Sarai 
23988db52c7eSAleksa Sarai 	/* Relative pathname -- get the starting-point it is relative to. */
23998db52c7eSAleksa Sarai 	if (nd->dfd == AT_FDCWD) {
2400e41f7d4eSAl Viro 		if (flags & LOOKUP_RCU) {
240131e6b01fSNick Piggin 			struct fs_struct *fs = current->fs;
2402c28cc364SNick Piggin 			unsigned seq;
240331e6b01fSNick Piggin 
2404c28cc364SNick Piggin 			do {
2405c28cc364SNick Piggin 				seq = read_seqcount_begin(&fs->seq);
240631e6b01fSNick Piggin 				nd->path = fs->pwd;
2407ef55d917SAl Viro 				nd->inode = nd->path.dentry->d_inode;
2408c28cc364SNick Piggin 				nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
2409c28cc364SNick Piggin 			} while (read_seqcount_retry(&fs->seq, seq));
2410e41f7d4eSAl Viro 		} else {
2411e41f7d4eSAl Viro 			get_fs_pwd(current->fs, &nd->path);
2412ef55d917SAl Viro 			nd->inode = nd->path.dentry->d_inode;
2413e41f7d4eSAl Viro 		}
241431e6b01fSNick Piggin 	} else {
2415582aa64aSJeff Layton 		/* Caller must check execute permissions on the starting path component */
2416c8a53ee5SAl Viro 		struct fd f = fdget_raw(nd->dfd);
241731e6b01fSNick Piggin 		struct dentry *dentry;
241831e6b01fSNick Piggin 
24192903ff01SAl Viro 		if (!f.file)
2420368ee9baSAl Viro 			return ERR_PTR(-EBADF);
242131e6b01fSNick Piggin 
24222903ff01SAl Viro 		dentry = f.file->f_path.dentry;
242331e6b01fSNick Piggin 
2424edc2b1daSAl Viro 		if (*s && unlikely(!d_can_lookup(dentry))) {
24252903ff01SAl Viro 			fdput(f);
2426368ee9baSAl Viro 			return ERR_PTR(-ENOTDIR);
2427f52e0c11SAl Viro 		}
24282903ff01SAl Viro 
24292903ff01SAl Viro 		nd->path = f.file->f_path;
2430e41f7d4eSAl Viro 		if (flags & LOOKUP_RCU) {
243134a26b99SAl Viro 			nd->inode = nd->path.dentry->d_inode;
243234a26b99SAl Viro 			nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
24335590ff0dSUlrich Drepper 		} else {
24342903ff01SAl Viro 			path_get(&nd->path);
243534a26b99SAl Viro 			nd->inode = nd->path.dentry->d_inode;
24361da177e4SLinus Torvalds 		}
243734a26b99SAl Viro 		fdput(f);
2438e41f7d4eSAl Viro 	}
24398db52c7eSAleksa Sarai 
2440adb21d2bSAleksa Sarai 	/* For scoped-lookups we need to set the root to the dirfd as well. */
2441adb21d2bSAleksa Sarai 	if (flags & LOOKUP_IS_SCOPED) {
2442adb21d2bSAleksa Sarai 		nd->root = nd->path;
2443adb21d2bSAleksa Sarai 		if (flags & LOOKUP_RCU) {
2444adb21d2bSAleksa Sarai 			nd->root_seq = nd->seq;
2445adb21d2bSAleksa Sarai 		} else {
2446adb21d2bSAleksa Sarai 			path_get(&nd->root);
2447bcba1e7dSAl Viro 			nd->state |= ND_ROOT_GRABBED;
2448adb21d2bSAleksa Sarai 		}
2449adb21d2bSAleksa Sarai 	}
2450adb21d2bSAleksa Sarai 	return s;
24519b4a9b14SAl Viro }
24529b4a9b14SAl Viro 
24531ccac622SAl Viro static inline const char *lookup_last(struct nameidata *nd)
245495fa25d9SAl Viro {
2455bd92d7feSAl Viro 	if (nd->last_type == LAST_NORM && nd->last.name[nd->last.len])
2456bd92d7feSAl Viro 		nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
2457bd92d7feSAl Viro 
2458c108837eSAl Viro 	return walk_component(nd, WALK_TRAILING);
2459bd92d7feSAl Viro }
2460bd92d7feSAl Viro 
24614f757f3cSAl Viro static int handle_lookup_down(struct nameidata *nd)
24624f757f3cSAl Viro {
2463c153007bSAl Viro 	if (!(nd->flags & LOOKUP_RCU))
2464db3c9adeSAl Viro 		dget(nd->path.dentry);
246503fa86e9SAl Viro 	nd->next_seq = nd->seq;
2466a4f5b521SAl Viro 	return PTR_ERR(step_into(nd, WALK_NOFOLLOW, nd->path.dentry));
24674f757f3cSAl Viro }
24684f757f3cSAl Viro 
24699b4a9b14SAl Viro /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
2470c8a53ee5SAl Viro static int path_lookupat(struct nameidata *nd, unsigned flags, struct path *path)
24719b4a9b14SAl Viro {
2472c8a53ee5SAl Viro 	const char *s = path_init(nd, flags);
2473bd92d7feSAl Viro 	int err;
247431e6b01fSNick Piggin 
24759b5858e9SAl Viro 	if (unlikely(flags & LOOKUP_DOWN) && !IS_ERR(s)) {
24764f757f3cSAl Viro 		err = handle_lookup_down(nd);
24775f336e72SAl Viro 		if (unlikely(err < 0))
24785f336e72SAl Viro 			s = ERR_PTR(err);
24794f757f3cSAl Viro 	}
24804f757f3cSAl Viro 
24811ccac622SAl Viro 	while (!(err = link_path_walk(s, nd)) &&
24821ccac622SAl Viro 	       (s = lookup_last(nd)) != NULL)
24831ccac622SAl Viro 		;
24844f0ed93fSAl Viro 	if (!err && unlikely(nd->flags & LOOKUP_MOUNTPOINT)) {
24854f0ed93fSAl Viro 		err = handle_lookup_down(nd);
2486bcba1e7dSAl Viro 		nd->state &= ~ND_JUMPED; // no d_weak_revalidate(), please...
24874f0ed93fSAl Viro 	}
24889f1fafeeSAl Viro 	if (!err)
24899f1fafeeSAl Viro 		err = complete_walk(nd);
2490bd92d7feSAl Viro 
2491deb106c6SAl Viro 	if (!err && nd->flags & LOOKUP_DIRECTORY)
2492deb106c6SAl Viro 		if (!d_can_lookup(nd->path.dentry))
2493bd23a539SAl Viro 			err = -ENOTDIR;
2494625b6d10SAl Viro 	if (!err) {
2495625b6d10SAl Viro 		*path = nd->path;
2496625b6d10SAl Viro 		nd->path.mnt = NULL;
2497625b6d10SAl Viro 		nd->path.dentry = NULL;
2498625b6d10SAl Viro 	}
2499deb106c6SAl Viro 	terminate_walk(nd);
2500bd92d7feSAl Viro 	return err;
250131e6b01fSNick Piggin }
250231e6b01fSNick Piggin 
2503794ebceaSStephen Brennan int filename_lookup(int dfd, struct filename *name, unsigned flags,
25049ad1aaa6SAl Viro 		    struct path *path, struct path *root)
2505873f1eedSJeff Layton {
2506894bc8c4SAl Viro 	int retval;
25079883d185SAl Viro 	struct nameidata nd;
2508abc9f5beSAl Viro 	if (IS_ERR(name))
2509abc9f5beSAl Viro 		return PTR_ERR(name);
251006422964SAl Viro 	set_nameidata(&nd, dfd, name, root);
2511c8a53ee5SAl Viro 	retval = path_lookupat(&nd, flags | LOOKUP_RCU, path);
2512873f1eedSJeff Layton 	if (unlikely(retval == -ECHILD))
2513c8a53ee5SAl Viro 		retval = path_lookupat(&nd, flags, path);
2514873f1eedSJeff Layton 	if (unlikely(retval == -ESTALE))
2515c8a53ee5SAl Viro 		retval = path_lookupat(&nd, flags | LOOKUP_REVAL, path);
2516873f1eedSJeff Layton 
2517873f1eedSJeff Layton 	if (likely(!retval))
2518161aff1dSAl Viro 		audit_inode(name, path->dentry,
2519161aff1dSAl Viro 			    flags & LOOKUP_MOUNTPOINT ? AUDIT_INODE_NOEVAL : 0);
25209883d185SAl Viro 	restore_nameidata();
2521020250f3SDmitry Kadashev 	return retval;
2522020250f3SDmitry Kadashev }
2523020250f3SDmitry Kadashev 
25248bcb77faSAl Viro /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
2525c8a53ee5SAl Viro static int path_parentat(struct nameidata *nd, unsigned flags,
2526391172c4SAl Viro 				struct path *parent)
25278bcb77faSAl Viro {
2528c8a53ee5SAl Viro 	const char *s = path_init(nd, flags);
25299b5858e9SAl Viro 	int err = link_path_walk(s, nd);
25308bcb77faSAl Viro 	if (!err)
25318bcb77faSAl Viro 		err = complete_walk(nd);
2532391172c4SAl Viro 	if (!err) {
2533391172c4SAl Viro 		*parent = nd->path;
2534391172c4SAl Viro 		nd->path.mnt = NULL;
2535391172c4SAl Viro 		nd->path.dentry = NULL;
2536391172c4SAl Viro 	}
2537deb106c6SAl Viro 	terminate_walk(nd);
25388bcb77faSAl Viro 	return err;
25398bcb77faSAl Viro }
25408bcb77faSAl Viro 
25410766ec82SStephen Brennan /* Note: this does not consume "name" */
254274d7970fSNamjae Jeon static int __filename_parentat(int dfd, struct filename *name,
2543391172c4SAl Viro 			       unsigned int flags, struct path *parent,
254474d7970fSNamjae Jeon 			       struct qstr *last, int *type,
254574d7970fSNamjae Jeon 			       const struct path *root)
25468bcb77faSAl Viro {
25478bcb77faSAl Viro 	int retval;
25489883d185SAl Viro 	struct nameidata nd;
25498bcb77faSAl Viro 
25505c31b6ceSAl Viro 	if (IS_ERR(name))
25510ee50b47SDmitry Kadashev 		return PTR_ERR(name);
255274d7970fSNamjae Jeon 	set_nameidata(&nd, dfd, name, root);
2553c8a53ee5SAl Viro 	retval = path_parentat(&nd, flags | LOOKUP_RCU, parent);
25548bcb77faSAl Viro 	if (unlikely(retval == -ECHILD))
2555c8a53ee5SAl Viro 		retval = path_parentat(&nd, flags, parent);
25568bcb77faSAl Viro 	if (unlikely(retval == -ESTALE))
2557c8a53ee5SAl Viro 		retval = path_parentat(&nd, flags | LOOKUP_REVAL, parent);
2558391172c4SAl Viro 	if (likely(!retval)) {
2559391172c4SAl Viro 		*last = nd.last;
2560391172c4SAl Viro 		*type = nd.last_type;
2561c9b07eabSAl Viro 		audit_inode(name, parent->dentry, AUDIT_INODE_PARENT);
2562391172c4SAl Viro 	}
25639883d185SAl Viro 	restore_nameidata();
25640ee50b47SDmitry Kadashev 	return retval;
25650ee50b47SDmitry Kadashev }
25660ee50b47SDmitry Kadashev 
256774d7970fSNamjae Jeon static int filename_parentat(int dfd, struct filename *name,
256874d7970fSNamjae Jeon 			     unsigned int flags, struct path *parent,
256974d7970fSNamjae Jeon 			     struct qstr *last, int *type)
257074d7970fSNamjae Jeon {
257174d7970fSNamjae Jeon 	return __filename_parentat(dfd, name, flags, parent, last, type, NULL);
257274d7970fSNamjae Jeon }
257374d7970fSNamjae Jeon 
257479714f72SAl Viro /* does lookup, returns the object with parent locked */
25750766ec82SStephen Brennan static struct dentry *__kern_path_locked(struct filename *name, struct path *path)
25765590ff0dSUlrich Drepper {
25775c31b6ceSAl Viro 	struct dentry *d;
2578391172c4SAl Viro 	struct qstr last;
25790ee50b47SDmitry Kadashev 	int type, error;
258051689104SPaul Moore 
2581c5f563f9SAl Viro 	error = filename_parentat(AT_FDCWD, name, 0, path, &last, &type);
25820ee50b47SDmitry Kadashev 	if (error)
25830ee50b47SDmitry Kadashev 		return ERR_PTR(error);
25845c31b6ceSAl Viro 	if (unlikely(type != LAST_NORM)) {
2585391172c4SAl Viro 		path_put(path);
25865c31b6ceSAl Viro 		return ERR_PTR(-EINVAL);
258779714f72SAl Viro 	}
25885955102cSAl Viro 	inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
258974d7970fSNamjae Jeon 	d = lookup_one_qstr_excl(&last, path->dentry, 0);
259079714f72SAl Viro 	if (IS_ERR(d)) {
25915955102cSAl Viro 		inode_unlock(path->dentry->d_inode);
2592391172c4SAl Viro 		path_put(path);
259379714f72SAl Viro 	}
259479714f72SAl Viro 	return d;
25955590ff0dSUlrich Drepper }
25965590ff0dSUlrich Drepper 
25970766ec82SStephen Brennan struct dentry *kern_path_locked(const char *name, struct path *path)
25980766ec82SStephen Brennan {
25990766ec82SStephen Brennan 	struct filename *filename = getname_kernel(name);
26000766ec82SStephen Brennan 	struct dentry *res = __kern_path_locked(filename, path);
26010766ec82SStephen Brennan 
26020766ec82SStephen Brennan 	putname(filename);
26030766ec82SStephen Brennan 	return res;
26040766ec82SStephen Brennan }
26050766ec82SStephen Brennan 
2606d1811465SAl Viro int kern_path(const char *name, unsigned int flags, struct path *path)
2607d1811465SAl Viro {
2608794ebceaSStephen Brennan 	struct filename *filename = getname_kernel(name);
2609794ebceaSStephen Brennan 	int ret = filename_lookup(AT_FDCWD, filename, flags, path, NULL);
2610794ebceaSStephen Brennan 
2611794ebceaSStephen Brennan 	putname(filename);
2612794ebceaSStephen Brennan 	return ret;
2613794ebceaSStephen Brennan 
2614d1811465SAl Viro }
26154d359507SAl Viro EXPORT_SYMBOL(kern_path);
2616d1811465SAl Viro 
261716f18200SJosef 'Jeff' Sipek /**
261874d7970fSNamjae Jeon  * vfs_path_parent_lookup - lookup a parent path relative to a dentry-vfsmount pair
261974d7970fSNamjae Jeon  * @filename: filename structure
262074d7970fSNamjae Jeon  * @flags: lookup flags
262174d7970fSNamjae Jeon  * @parent: pointer to struct path to fill
262274d7970fSNamjae Jeon  * @last: last component
262374d7970fSNamjae Jeon  * @type: type of the last component
262474d7970fSNamjae Jeon  * @root: pointer to struct path of the base directory
262574d7970fSNamjae Jeon  */
262674d7970fSNamjae Jeon int vfs_path_parent_lookup(struct filename *filename, unsigned int flags,
262774d7970fSNamjae Jeon 			   struct path *parent, struct qstr *last, int *type,
262874d7970fSNamjae Jeon 			   const struct path *root)
262974d7970fSNamjae Jeon {
263074d7970fSNamjae Jeon 	return  __filename_parentat(AT_FDCWD, filename, flags, parent, last,
263174d7970fSNamjae Jeon 				    type, root);
263274d7970fSNamjae Jeon }
263374d7970fSNamjae Jeon EXPORT_SYMBOL(vfs_path_parent_lookup);
263474d7970fSNamjae Jeon 
263574d7970fSNamjae Jeon /**
263616f18200SJosef 'Jeff' Sipek  * vfs_path_lookup - lookup a file path relative to a dentry-vfsmount pair
263716f18200SJosef 'Jeff' Sipek  * @dentry:  pointer to dentry of the base directory
263816f18200SJosef 'Jeff' Sipek  * @mnt: pointer to vfs mount of the base directory
263916f18200SJosef 'Jeff' Sipek  * @name: pointer to file name
264016f18200SJosef 'Jeff' Sipek  * @flags: lookup flags
2641e0a01249SAl Viro  * @path: pointer to struct path to fill
264216f18200SJosef 'Jeff' Sipek  */
264316f18200SJosef 'Jeff' Sipek int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt,
264416f18200SJosef 'Jeff' Sipek 		    const char *name, unsigned int flags,
2645e0a01249SAl Viro 		    struct path *path)
264616f18200SJosef 'Jeff' Sipek {
2647794ebceaSStephen Brennan 	struct filename *filename;
26489ad1aaa6SAl Viro 	struct path root = {.mnt = mnt, .dentry = dentry};
2649794ebceaSStephen Brennan 	int ret;
2650794ebceaSStephen Brennan 
2651794ebceaSStephen Brennan 	filename = getname_kernel(name);
26529ad1aaa6SAl Viro 	/* the first argument of filename_lookup() is ignored with root */
2653794ebceaSStephen Brennan 	ret = filename_lookup(AT_FDCWD, filename, flags, path, &root);
2654794ebceaSStephen Brennan 	putname(filename);
2655794ebceaSStephen Brennan 	return ret;
265616f18200SJosef 'Jeff' Sipek }
26574d359507SAl Viro EXPORT_SYMBOL(vfs_path_lookup);
265816f18200SJosef 'Jeff' Sipek 
26594609e1f1SChristian Brauner static int lookup_one_common(struct mnt_idmap *idmap,
2660c2fd68b6SChristian Brauner 			     const char *name, struct dentry *base, int len,
2661c2fd68b6SChristian Brauner 			     struct qstr *this)
26623c95f0dcSAl Viro {
26633c95f0dcSAl Viro 	this->name = name;
26643c95f0dcSAl Viro 	this->len = len;
26653c95f0dcSAl Viro 	this->hash = full_name_hash(base, name, len);
26663c95f0dcSAl Viro 	if (!len)
26673c95f0dcSAl Viro 		return -EACCES;
26683c95f0dcSAl Viro 
26693c95f0dcSAl Viro 	if (unlikely(name[0] == '.')) {
26703c95f0dcSAl Viro 		if (len < 2 || (len == 2 && name[1] == '.'))
26713c95f0dcSAl Viro 			return -EACCES;
26723c95f0dcSAl Viro 	}
26733c95f0dcSAl Viro 
26743c95f0dcSAl Viro 	while (len--) {
26753c95f0dcSAl Viro 		unsigned int c = *(const unsigned char *)name++;
26763c95f0dcSAl Viro 		if (c == '/' || c == '\0')
26773c95f0dcSAl Viro 			return -EACCES;
26783c95f0dcSAl Viro 	}
26793c95f0dcSAl Viro 	/*
26803c95f0dcSAl Viro 	 * See if the low-level filesystem might want
26813c95f0dcSAl Viro 	 * to use its own hash..
26823c95f0dcSAl Viro 	 */
26833c95f0dcSAl Viro 	if (base->d_flags & DCACHE_OP_HASH) {
26843c95f0dcSAl Viro 		int err = base->d_op->d_hash(base, this);
26853c95f0dcSAl Viro 		if (err < 0)
26863c95f0dcSAl Viro 			return err;
26873c95f0dcSAl Viro 	}
26883c95f0dcSAl Viro 
26894609e1f1SChristian Brauner 	return inode_permission(idmap, base->d_inode, MAY_EXEC);
26903c95f0dcSAl Viro }
26913c95f0dcSAl Viro 
2692eead1911SChristoph Hellwig /**
26930da0b7fdSDavid Howells  * try_lookup_one_len - filesystem helper to lookup single pathname component
26940da0b7fdSDavid Howells  * @name:	pathname component to lookup
26950da0b7fdSDavid Howells  * @base:	base directory to lookup from
26960da0b7fdSDavid Howells  * @len:	maximum length @len should be interpreted to
26970da0b7fdSDavid Howells  *
26980da0b7fdSDavid Howells  * Look up a dentry by name in the dcache, returning NULL if it does not
26990da0b7fdSDavid Howells  * currently exist.  The function does not try to create a dentry.
27000da0b7fdSDavid Howells  *
27010da0b7fdSDavid Howells  * Note that this routine is purely a helper for filesystem usage and should
27020da0b7fdSDavid Howells  * not be called by generic code.
27030da0b7fdSDavid Howells  *
27040da0b7fdSDavid Howells  * The caller must hold base->i_mutex.
27050da0b7fdSDavid Howells  */
27060da0b7fdSDavid Howells struct dentry *try_lookup_one_len(const char *name, struct dentry *base, int len)
27070da0b7fdSDavid Howells {
27080da0b7fdSDavid Howells 	struct qstr this;
27090da0b7fdSDavid Howells 	int err;
27100da0b7fdSDavid Howells 
27110da0b7fdSDavid Howells 	WARN_ON_ONCE(!inode_is_locked(base->d_inode));
27120da0b7fdSDavid Howells 
27134609e1f1SChristian Brauner 	err = lookup_one_common(&nop_mnt_idmap, name, base, len, &this);
27140da0b7fdSDavid Howells 	if (err)
27150da0b7fdSDavid Howells 		return ERR_PTR(err);
27160da0b7fdSDavid Howells 
27170da0b7fdSDavid Howells 	return lookup_dcache(&this, base, 0);
27180da0b7fdSDavid Howells }
27190da0b7fdSDavid Howells EXPORT_SYMBOL(try_lookup_one_len);
27200da0b7fdSDavid Howells 
27210da0b7fdSDavid Howells /**
2722a6b91919SRandy Dunlap  * lookup_one_len - filesystem helper to lookup single pathname component
2723eead1911SChristoph Hellwig  * @name:	pathname component to lookup
2724eead1911SChristoph Hellwig  * @base:	base directory to lookup from
2725eead1911SChristoph Hellwig  * @len:	maximum length @len should be interpreted to
2726eead1911SChristoph Hellwig  *
2727a6b91919SRandy Dunlap  * Note that this routine is purely a helper for filesystem usage and should
27289e7543e9SAl Viro  * not be called by generic code.
2729bbddca8eSNeilBrown  *
2730bbddca8eSNeilBrown  * The caller must hold base->i_mutex.
2731eead1911SChristoph Hellwig  */
2732057f6c01SJames Morris struct dentry *lookup_one_len(const char *name, struct dentry *base, int len)
2733057f6c01SJames Morris {
27348613a209SAl Viro 	struct dentry *dentry;
2735057f6c01SJames Morris 	struct qstr this;
2736cda309deSMiklos Szeredi 	int err;
2737057f6c01SJames Morris 
27385955102cSAl Viro 	WARN_ON_ONCE(!inode_is_locked(base->d_inode));
27392f9092e1SDavid Woodhouse 
27404609e1f1SChristian Brauner 	err = lookup_one_common(&nop_mnt_idmap, name, base, len, &this);
2741cda309deSMiklos Szeredi 	if (err)
2742cda309deSMiklos Szeredi 		return ERR_PTR(err);
2743cda309deSMiklos Szeredi 
27448613a209SAl Viro 	dentry = lookup_dcache(&this, base, 0);
27458613a209SAl Viro 	return dentry ? dentry : __lookup_slow(&this, base, 0);
2746057f6c01SJames Morris }
27474d359507SAl Viro EXPORT_SYMBOL(lookup_one_len);
2748057f6c01SJames Morris 
2749bbddca8eSNeilBrown /**
2750c2fd68b6SChristian Brauner  * lookup_one - filesystem helper to lookup single pathname component
27514609e1f1SChristian Brauner  * @idmap:	idmap of the mount the lookup is performed from
2752c2fd68b6SChristian Brauner  * @name:	pathname component to lookup
2753c2fd68b6SChristian Brauner  * @base:	base directory to lookup from
2754c2fd68b6SChristian Brauner  * @len:	maximum length @len should be interpreted to
2755c2fd68b6SChristian Brauner  *
2756c2fd68b6SChristian Brauner  * Note that this routine is purely a helper for filesystem usage and should
2757c2fd68b6SChristian Brauner  * not be called by generic code.
2758c2fd68b6SChristian Brauner  *
2759c2fd68b6SChristian Brauner  * The caller must hold base->i_mutex.
2760c2fd68b6SChristian Brauner  */
27614609e1f1SChristian Brauner struct dentry *lookup_one(struct mnt_idmap *idmap, const char *name,
2762c2fd68b6SChristian Brauner 			  struct dentry *base, int len)
2763c2fd68b6SChristian Brauner {
2764c2fd68b6SChristian Brauner 	struct dentry *dentry;
2765c2fd68b6SChristian Brauner 	struct qstr this;
2766c2fd68b6SChristian Brauner 	int err;
2767c2fd68b6SChristian Brauner 
2768c2fd68b6SChristian Brauner 	WARN_ON_ONCE(!inode_is_locked(base->d_inode));
2769c2fd68b6SChristian Brauner 
27704609e1f1SChristian Brauner 	err = lookup_one_common(idmap, name, base, len, &this);
2771c2fd68b6SChristian Brauner 	if (err)
2772c2fd68b6SChristian Brauner 		return ERR_PTR(err);
2773c2fd68b6SChristian Brauner 
2774c2fd68b6SChristian Brauner 	dentry = lookup_dcache(&this, base, 0);
2775c2fd68b6SChristian Brauner 	return dentry ? dentry : __lookup_slow(&this, base, 0);
2776c2fd68b6SChristian Brauner }
2777c2fd68b6SChristian Brauner EXPORT_SYMBOL(lookup_one);
2778c2fd68b6SChristian Brauner 
2779c2fd68b6SChristian Brauner /**
278000675017SChristian Brauner  * lookup_one_unlocked - filesystem helper to lookup single pathname component
27814609e1f1SChristian Brauner  * @idmap:	idmap of the mount the lookup is performed from
278200675017SChristian Brauner  * @name:	pathname component to lookup
278300675017SChristian Brauner  * @base:	base directory to lookup from
278400675017SChristian Brauner  * @len:	maximum length @len should be interpreted to
278500675017SChristian Brauner  *
278600675017SChristian Brauner  * Note that this routine is purely a helper for filesystem usage and should
278700675017SChristian Brauner  * not be called by generic code.
278800675017SChristian Brauner  *
278900675017SChristian Brauner  * Unlike lookup_one_len, it should be called without the parent
279000675017SChristian Brauner  * i_mutex held, and will take the i_mutex itself if necessary.
279100675017SChristian Brauner  */
27924609e1f1SChristian Brauner struct dentry *lookup_one_unlocked(struct mnt_idmap *idmap,
279300675017SChristian Brauner 				   const char *name, struct dentry *base,
279400675017SChristian Brauner 				   int len)
279500675017SChristian Brauner {
279600675017SChristian Brauner 	struct qstr this;
279700675017SChristian Brauner 	int err;
279800675017SChristian Brauner 	struct dentry *ret;
279900675017SChristian Brauner 
28004609e1f1SChristian Brauner 	err = lookup_one_common(idmap, name, base, len, &this);
280100675017SChristian Brauner 	if (err)
280200675017SChristian Brauner 		return ERR_PTR(err);
280300675017SChristian Brauner 
280400675017SChristian Brauner 	ret = lookup_dcache(&this, base, 0);
280500675017SChristian Brauner 	if (!ret)
280600675017SChristian Brauner 		ret = lookup_slow(&this, base, 0);
280700675017SChristian Brauner 	return ret;
280800675017SChristian Brauner }
280900675017SChristian Brauner EXPORT_SYMBOL(lookup_one_unlocked);
281000675017SChristian Brauner 
281100675017SChristian Brauner /**
281200675017SChristian Brauner  * lookup_one_positive_unlocked - filesystem helper to lookup single
281300675017SChristian Brauner  *				  pathname component
28144609e1f1SChristian Brauner  * @idmap:	idmap of the mount the lookup is performed from
281500675017SChristian Brauner  * @name:	pathname component to lookup
281600675017SChristian Brauner  * @base:	base directory to lookup from
281700675017SChristian Brauner  * @len:	maximum length @len should be interpreted to
281800675017SChristian Brauner  *
281900675017SChristian Brauner  * This helper will yield ERR_PTR(-ENOENT) on negatives. The helper returns
282000675017SChristian Brauner  * known positive or ERR_PTR(). This is what most of the users want.
282100675017SChristian Brauner  *
282200675017SChristian Brauner  * Note that pinned negative with unlocked parent _can_ become positive at any
282300675017SChristian Brauner  * time, so callers of lookup_one_unlocked() need to be very careful; pinned
282400675017SChristian Brauner  * positives have >d_inode stable, so this one avoids such problems.
282500675017SChristian Brauner  *
282600675017SChristian Brauner  * Note that this routine is purely a helper for filesystem usage and should
282700675017SChristian Brauner  * not be called by generic code.
282800675017SChristian Brauner  *
282900675017SChristian Brauner  * The helper should be called without i_mutex held.
283000675017SChristian Brauner  */
28314609e1f1SChristian Brauner struct dentry *lookup_one_positive_unlocked(struct mnt_idmap *idmap,
283200675017SChristian Brauner 					    const char *name,
283300675017SChristian Brauner 					    struct dentry *base, int len)
283400675017SChristian Brauner {
28354609e1f1SChristian Brauner 	struct dentry *ret = lookup_one_unlocked(idmap, name, base, len);
283600675017SChristian Brauner 
283700675017SChristian Brauner 	if (!IS_ERR(ret) && d_flags_negative(smp_load_acquire(&ret->d_flags))) {
283800675017SChristian Brauner 		dput(ret);
283900675017SChristian Brauner 		ret = ERR_PTR(-ENOENT);
284000675017SChristian Brauner 	}
284100675017SChristian Brauner 	return ret;
284200675017SChristian Brauner }
284300675017SChristian Brauner EXPORT_SYMBOL(lookup_one_positive_unlocked);
284400675017SChristian Brauner 
284500675017SChristian Brauner /**
2846bbddca8eSNeilBrown  * lookup_one_len_unlocked - filesystem helper to lookup single pathname component
2847bbddca8eSNeilBrown  * @name:	pathname component to lookup
2848bbddca8eSNeilBrown  * @base:	base directory to lookup from
2849bbddca8eSNeilBrown  * @len:	maximum length @len should be interpreted to
2850bbddca8eSNeilBrown  *
2851bbddca8eSNeilBrown  * Note that this routine is purely a helper for filesystem usage and should
2852bbddca8eSNeilBrown  * not be called by generic code.
2853bbddca8eSNeilBrown  *
2854bbddca8eSNeilBrown  * Unlike lookup_one_len, it should be called without the parent
2855bbddca8eSNeilBrown  * i_mutex held, and will take the i_mutex itself if necessary.
2856bbddca8eSNeilBrown  */
2857bbddca8eSNeilBrown struct dentry *lookup_one_len_unlocked(const char *name,
2858bbddca8eSNeilBrown 				       struct dentry *base, int len)
2859bbddca8eSNeilBrown {
28604609e1f1SChristian Brauner 	return lookup_one_unlocked(&nop_mnt_idmap, name, base, len);
2861bbddca8eSNeilBrown }
2862bbddca8eSNeilBrown EXPORT_SYMBOL(lookup_one_len_unlocked);
2863bbddca8eSNeilBrown 
28646c2d4798SAl Viro /*
28656c2d4798SAl Viro  * Like lookup_one_len_unlocked(), except that it yields ERR_PTR(-ENOENT)
28666c2d4798SAl Viro  * on negatives.  Returns known positive or ERR_PTR(); that's what
28676c2d4798SAl Viro  * most of the users want.  Note that pinned negative with unlocked parent
28686c2d4798SAl Viro  * _can_ become positive at any time, so callers of lookup_one_len_unlocked()
28696c2d4798SAl Viro  * need to be very careful; pinned positives have ->d_inode stable, so
28706c2d4798SAl Viro  * this one avoids such problems.
28716c2d4798SAl Viro  */
28726c2d4798SAl Viro struct dentry *lookup_positive_unlocked(const char *name,
28736c2d4798SAl Viro 				       struct dentry *base, int len)
28746c2d4798SAl Viro {
28754609e1f1SChristian Brauner 	return lookup_one_positive_unlocked(&nop_mnt_idmap, name, base, len);
28766c2d4798SAl Viro }
28776c2d4798SAl Viro EXPORT_SYMBOL(lookup_positive_unlocked);
28786c2d4798SAl Viro 
2879eedf265aSEric W. Biederman #ifdef CONFIG_UNIX98_PTYS
2880eedf265aSEric W. Biederman int path_pts(struct path *path)
2881eedf265aSEric W. Biederman {
2882eedf265aSEric W. Biederman 	/* Find something mounted on "pts" in the same directory as
2883eedf265aSEric W. Biederman 	 * the input path.
2884eedf265aSEric W. Biederman 	 */
2885a6a7eb76SAl Viro 	struct dentry *parent = dget_parent(path->dentry);
2886a6a7eb76SAl Viro 	struct dentry *child;
288719f6028aSAl Viro 	struct qstr this = QSTR_INIT("pts", 3);
2888eedf265aSEric W. Biederman 
2889a6a7eb76SAl Viro 	if (unlikely(!path_connected(path->mnt, parent))) {
2890a6a7eb76SAl Viro 		dput(parent);
289163b27720SAl Viro 		return -ENOENT;
2892a6a7eb76SAl Viro 	}
289363b27720SAl Viro 	dput(path->dentry);
289463b27720SAl Viro 	path->dentry = parent;
2895eedf265aSEric W. Biederman 	child = d_hash_and_lookup(parent, &this);
28960d5a4f8fSWang Ming 	if (IS_ERR_OR_NULL(child))
2897eedf265aSEric W. Biederman 		return -ENOENT;
2898eedf265aSEric W. Biederman 
2899eedf265aSEric W. Biederman 	path->dentry = child;
2900eedf265aSEric W. Biederman 	dput(parent);
2901e1f19857SRichard Weinberger 	follow_down(path, 0);
2902eedf265aSEric W. Biederman 	return 0;
2903eedf265aSEric W. Biederman }
2904eedf265aSEric W. Biederman #endif
2905eedf265aSEric W. Biederman 
29061fa1e7f6SAndy Whitcroft int user_path_at_empty(int dfd, const char __user *name, unsigned flags,
29071fa1e7f6SAndy Whitcroft 		 struct path *path, int *empty)
29081da177e4SLinus Torvalds {
2909794ebceaSStephen Brennan 	struct filename *filename = getname_flags(name, flags, empty);
2910794ebceaSStephen Brennan 	int ret = filename_lookup(dfd, filename, flags, path, NULL);
2911794ebceaSStephen Brennan 
2912794ebceaSStephen Brennan 	putname(filename);
2913794ebceaSStephen Brennan 	return ret;
29141da177e4SLinus Torvalds }
2915b853a161SAl Viro EXPORT_SYMBOL(user_path_at_empty);
29161fa1e7f6SAndy Whitcroft 
29179452e93eSChristian Brauner int __check_sticky(struct mnt_idmap *idmap, struct inode *dir,
2918ba73d987SChristian Brauner 		   struct inode *inode)
29191da177e4SLinus Torvalds {
29208e96e3b7SEric W. Biederman 	kuid_t fsuid = current_fsuid();
2921da9592edSDavid Howells 
2922e67fe633SChristian Brauner 	if (vfsuid_eq_kuid(i_uid_into_vfsuid(idmap, inode), fsuid))
29231da177e4SLinus Torvalds 		return 0;
2924e67fe633SChristian Brauner 	if (vfsuid_eq_kuid(i_uid_into_vfsuid(idmap, dir), fsuid))
29251da177e4SLinus Torvalds 		return 0;
29269452e93eSChristian Brauner 	return !capable_wrt_inode_uidgid(idmap, inode, CAP_FOWNER);
29271da177e4SLinus Torvalds }
2928cbdf35bcSMiklos Szeredi EXPORT_SYMBOL(__check_sticky);
29291da177e4SLinus Torvalds 
29301da177e4SLinus Torvalds /*
29311da177e4SLinus Torvalds  *	Check whether we can remove a link victim from directory dir, check
29321da177e4SLinus Torvalds  *  whether the type of victim is right.
29331da177e4SLinus Torvalds  *  1. We can't do it if dir is read-only (done in permission())
29341da177e4SLinus Torvalds  *  2. We should have write and exec permissions on dir
29351da177e4SLinus Torvalds  *  3. We can't remove anything from append-only dir
29361da177e4SLinus Torvalds  *  4. We can't do anything with immutable dir (done in permission())
29371da177e4SLinus Torvalds  *  5. If the sticky bit on dir is set we should either
29381da177e4SLinus Torvalds  *	a. be owner of dir, or
29391da177e4SLinus Torvalds  *	b. be owner of victim, or
29401da177e4SLinus Torvalds  *	c. have CAP_FOWNER capability
29411da177e4SLinus Torvalds  *  6. If the victim is append-only or immutable we can't do antyhing with
29421da177e4SLinus Torvalds  *     links pointing to it.
29430bd23d09SEric W. Biederman  *  7. If the victim has an unknown uid or gid we can't change the inode.
29440bd23d09SEric W. Biederman  *  8. If we were asked to remove a directory and victim isn't one - ENOTDIR.
29450bd23d09SEric W. Biederman  *  9. If we were asked to remove a non-directory and victim isn't one - EISDIR.
29460bd23d09SEric W. Biederman  * 10. We can't remove a root or mountpoint.
29470bd23d09SEric W. Biederman  * 11. We don't allow removal of NFS sillyrenamed files; it's handled by
29481da177e4SLinus Torvalds  *     nfs_async_unlink().
29491da177e4SLinus Torvalds  */
29504609e1f1SChristian Brauner static int may_delete(struct mnt_idmap *idmap, struct inode *dir,
2951ba73d987SChristian Brauner 		      struct dentry *victim, bool isdir)
29521da177e4SLinus Torvalds {
295363afdfc7SDavid Howells 	struct inode *inode = d_backing_inode(victim);
29541da177e4SLinus Torvalds 	int error;
29551da177e4SLinus Torvalds 
2956b18825a7SDavid Howells 	if (d_is_negative(victim))
29571da177e4SLinus Torvalds 		return -ENOENT;
2958b18825a7SDavid Howells 	BUG_ON(!inode);
29591da177e4SLinus Torvalds 
29601da177e4SLinus Torvalds 	BUG_ON(victim->d_parent->d_inode != dir);
2961593d1ce8SEric W. Biederman 
2962593d1ce8SEric W. Biederman 	/* Inode writeback is not safe when the uid or gid are invalid. */
2963e67fe633SChristian Brauner 	if (!vfsuid_valid(i_uid_into_vfsuid(idmap, inode)) ||
2964e67fe633SChristian Brauner 	    !vfsgid_valid(i_gid_into_vfsgid(idmap, inode)))
2965593d1ce8SEric W. Biederman 		return -EOVERFLOW;
2966593d1ce8SEric W. Biederman 
29674fa6b5ecSJeff Layton 	audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
29681da177e4SLinus Torvalds 
29694609e1f1SChristian Brauner 	error = inode_permission(idmap, dir, MAY_WRITE | MAY_EXEC);
29701da177e4SLinus Torvalds 	if (error)
29711da177e4SLinus Torvalds 		return error;
29721da177e4SLinus Torvalds 	if (IS_APPEND(dir))
29731da177e4SLinus Torvalds 		return -EPERM;
2974b18825a7SDavid Howells 
29759452e93eSChristian Brauner 	if (check_sticky(idmap, dir, inode) || IS_APPEND(inode) ||
2976ba73d987SChristian Brauner 	    IS_IMMUTABLE(inode) || IS_SWAPFILE(inode) ||
29774609e1f1SChristian Brauner 	    HAS_UNMAPPED_ID(idmap, inode))
29781da177e4SLinus Torvalds 		return -EPERM;
29791da177e4SLinus Torvalds 	if (isdir) {
298044b1d530SMiklos Szeredi 		if (!d_is_dir(victim))
29811da177e4SLinus Torvalds 			return -ENOTDIR;
29821da177e4SLinus Torvalds 		if (IS_ROOT(victim))
29831da177e4SLinus Torvalds 			return -EBUSY;
298444b1d530SMiklos Szeredi 	} else if (d_is_dir(victim))
29851da177e4SLinus Torvalds 		return -EISDIR;
29861da177e4SLinus Torvalds 	if (IS_DEADDIR(dir))
29871da177e4SLinus Torvalds 		return -ENOENT;
29881da177e4SLinus Torvalds 	if (victim->d_flags & DCACHE_NFSFS_RENAMED)
29891da177e4SLinus Torvalds 		return -EBUSY;
29901da177e4SLinus Torvalds 	return 0;
29911da177e4SLinus Torvalds }
29921da177e4SLinus Torvalds 
29931da177e4SLinus Torvalds /*	Check whether we can create an object with dentry child in directory
29941da177e4SLinus Torvalds  *  dir.
29951da177e4SLinus Torvalds  *  1. We can't do it if child already exists (open has special treatment for
29961da177e4SLinus Torvalds  *     this case, but since we are inlined it's OK)
29971da177e4SLinus Torvalds  *  2. We can't do it if dir is read-only (done in permission())
2998036d5236SEric W. Biederman  *  3. We can't do it if the fs can't represent the fsuid or fsgid.
2999036d5236SEric W. Biederman  *  4. We should have write and exec permissions on dir
3000036d5236SEric W. Biederman  *  5. We can't do it if dir is immutable (done in permission())
30011da177e4SLinus Torvalds  */
30024609e1f1SChristian Brauner static inline int may_create(struct mnt_idmap *idmap,
3003ba73d987SChristian Brauner 			     struct inode *dir, struct dentry *child)
30041da177e4SLinus Torvalds {
300514e972b4SJeff Layton 	audit_inode_child(dir, child, AUDIT_TYPE_CHILD_CREATE);
30061da177e4SLinus Torvalds 	if (child->d_inode)
30071da177e4SLinus Torvalds 		return -EEXIST;
30081da177e4SLinus Torvalds 	if (IS_DEADDIR(dir))
30091da177e4SLinus Torvalds 		return -ENOENT;
30104609e1f1SChristian Brauner 	if (!fsuidgid_has_mapping(dir->i_sb, idmap))
3011036d5236SEric W. Biederman 		return -EOVERFLOW;
30128e538913SChristian Brauner 
30134609e1f1SChristian Brauner 	return inode_permission(idmap, dir, MAY_WRITE | MAY_EXEC);
30141da177e4SLinus Torvalds }
30151da177e4SLinus Torvalds 
30169bc37e04SAl Viro static struct dentry *lock_two_directories(struct dentry *p1, struct dentry *p2)
30171da177e4SLinus Torvalds {
30181da177e4SLinus Torvalds 	struct dentry *p;
30191da177e4SLinus Torvalds 
3020e2761a11SOGAWA Hirofumi 	p = d_ancestor(p2, p1);
3021e2761a11SOGAWA Hirofumi 	if (p) {
30225955102cSAl Viro 		inode_lock_nested(p2->d_inode, I_MUTEX_PARENT);
30235955102cSAl Viro 		inode_lock_nested(p1->d_inode, I_MUTEX_CHILD);
30241da177e4SLinus Torvalds 		return p;
30251da177e4SLinus Torvalds 	}
30261da177e4SLinus Torvalds 
3027e2761a11SOGAWA Hirofumi 	p = d_ancestor(p1, p2);
3028e2761a11SOGAWA Hirofumi 	if (p) {
30295955102cSAl Viro 		inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
30305955102cSAl Viro 		inode_lock_nested(p2->d_inode, I_MUTEX_CHILD);
30311da177e4SLinus Torvalds 		return p;
30321da177e4SLinus Torvalds 	}
30331da177e4SLinus Torvalds 
3034f23ce757SJan Kara 	lock_two_inodes(p1->d_inode, p2->d_inode,
3035f23ce757SJan Kara 			I_MUTEX_PARENT, I_MUTEX_PARENT2);
30361da177e4SLinus Torvalds 	return NULL;
30371da177e4SLinus Torvalds }
30389bc37e04SAl Viro 
30399bc37e04SAl Viro /*
30409bc37e04SAl Viro  * p1 and p2 should be directories on the same fs.
30419bc37e04SAl Viro  */
30429bc37e04SAl Viro struct dentry *lock_rename(struct dentry *p1, struct dentry *p2)
30439bc37e04SAl Viro {
30449bc37e04SAl Viro 	if (p1 == p2) {
30459bc37e04SAl Viro 		inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
30469bc37e04SAl Viro 		return NULL;
30479bc37e04SAl Viro 	}
30489bc37e04SAl Viro 
30499bc37e04SAl Viro 	mutex_lock(&p1->d_sb->s_vfs_rename_mutex);
30509bc37e04SAl Viro 	return lock_two_directories(p1, p2);
30519bc37e04SAl Viro }
30524d359507SAl Viro EXPORT_SYMBOL(lock_rename);
30531da177e4SLinus Torvalds 
30549bc37e04SAl Viro /*
30559bc37e04SAl Viro  * c1 and p2 should be on the same fs.
30569bc37e04SAl Viro  */
30579bc37e04SAl Viro struct dentry *lock_rename_child(struct dentry *c1, struct dentry *p2)
30589bc37e04SAl Viro {
30599bc37e04SAl Viro 	if (READ_ONCE(c1->d_parent) == p2) {
30609bc37e04SAl Viro 		/*
30619bc37e04SAl Viro 		 * hopefully won't need to touch ->s_vfs_rename_mutex at all.
30629bc37e04SAl Viro 		 */
30639bc37e04SAl Viro 		inode_lock_nested(p2->d_inode, I_MUTEX_PARENT);
30649bc37e04SAl Viro 		/*
30659bc37e04SAl Viro 		 * now that p2 is locked, nobody can move in or out of it,
30669bc37e04SAl Viro 		 * so the test below is safe.
30679bc37e04SAl Viro 		 */
30689bc37e04SAl Viro 		if (likely(c1->d_parent == p2))
30699bc37e04SAl Viro 			return NULL;
30709bc37e04SAl Viro 
30719bc37e04SAl Viro 		/*
30729bc37e04SAl Viro 		 * c1 got moved out of p2 while we'd been taking locks;
30739bc37e04SAl Viro 		 * unlock and fall back to slow case.
30749bc37e04SAl Viro 		 */
30759bc37e04SAl Viro 		inode_unlock(p2->d_inode);
30769bc37e04SAl Viro 	}
30779bc37e04SAl Viro 
30789bc37e04SAl Viro 	mutex_lock(&c1->d_sb->s_vfs_rename_mutex);
30799bc37e04SAl Viro 	/*
30809bc37e04SAl Viro 	 * nobody can move out of any directories on this fs.
30819bc37e04SAl Viro 	 */
30829bc37e04SAl Viro 	if (likely(c1->d_parent != p2))
30839bc37e04SAl Viro 		return lock_two_directories(c1->d_parent, p2);
30849bc37e04SAl Viro 
30859bc37e04SAl Viro 	/*
30869bc37e04SAl Viro 	 * c1 got moved into p2 while we were taking locks;
30879bc37e04SAl Viro 	 * we need p2 locked and ->s_vfs_rename_mutex unlocked,
30889bc37e04SAl Viro 	 * for consistency with lock_rename().
30899bc37e04SAl Viro 	 */
30909bc37e04SAl Viro 	inode_lock_nested(p2->d_inode, I_MUTEX_PARENT);
30919bc37e04SAl Viro 	mutex_unlock(&c1->d_sb->s_vfs_rename_mutex);
30929bc37e04SAl Viro 	return NULL;
30939bc37e04SAl Viro }
30949bc37e04SAl Viro EXPORT_SYMBOL(lock_rename_child);
30959bc37e04SAl Viro 
30961da177e4SLinus Torvalds void unlock_rename(struct dentry *p1, struct dentry *p2)
30971da177e4SLinus Torvalds {
30985955102cSAl Viro 	inode_unlock(p1->d_inode);
30991da177e4SLinus Torvalds 	if (p1 != p2) {
31005955102cSAl Viro 		inode_unlock(p2->d_inode);
3101fc64005cSAl Viro 		mutex_unlock(&p1->d_sb->s_vfs_rename_mutex);
31021da177e4SLinus Torvalds 	}
31031da177e4SLinus Torvalds }
31044d359507SAl Viro EXPORT_SYMBOL(unlock_rename);
31051da177e4SLinus Torvalds 
31066521f891SChristian Brauner /**
31071639a49cSYang Xu  * mode_strip_umask - handle vfs umask stripping
31081639a49cSYang Xu  * @dir:	parent directory of the new inode
31091639a49cSYang Xu  * @mode:	mode of the new inode to be created in @dir
31101639a49cSYang Xu  *
31111639a49cSYang Xu  * Umask stripping depends on whether or not the filesystem supports POSIX
31121639a49cSYang Xu  * ACLs. If the filesystem doesn't support it umask stripping is done directly
31131639a49cSYang Xu  * in here. If the filesystem does support POSIX ACLs umask stripping is
31141639a49cSYang Xu  * deferred until the filesystem calls posix_acl_create().
31151639a49cSYang Xu  *
31161639a49cSYang Xu  * Returns: mode
31171639a49cSYang Xu  */
31181639a49cSYang Xu static inline umode_t mode_strip_umask(const struct inode *dir, umode_t mode)
31191639a49cSYang Xu {
31201639a49cSYang Xu 	if (!IS_POSIXACL(dir))
31211639a49cSYang Xu 		mode &= ~current_umask();
31221639a49cSYang Xu 	return mode;
31231639a49cSYang Xu }
31241639a49cSYang Xu 
31251639a49cSYang Xu /**
31261639a49cSYang Xu  * vfs_prepare_mode - prepare the mode to be used for a new inode
31279452e93eSChristian Brauner  * @idmap:	idmap of the mount the inode was found from
31281639a49cSYang Xu  * @dir:	parent directory of the new inode
31291639a49cSYang Xu  * @mode:	mode of the new inode
31301639a49cSYang Xu  * @mask_perms:	allowed permission by the vfs
31311639a49cSYang Xu  * @type:	type of file to be created
31321639a49cSYang Xu  *
31331639a49cSYang Xu  * This helper consolidates and enforces vfs restrictions on the @mode of a new
31341639a49cSYang Xu  * object to be created.
31351639a49cSYang Xu  *
31361639a49cSYang Xu  * Umask stripping depends on whether the filesystem supports POSIX ACLs (see
31371639a49cSYang Xu  * the kernel documentation for mode_strip_umask()). Moving umask stripping
31381639a49cSYang Xu  * after setgid stripping allows the same ordering for both non-POSIX ACL and
31391639a49cSYang Xu  * POSIX ACL supporting filesystems.
31401639a49cSYang Xu  *
31411639a49cSYang Xu  * Note that it's currently valid for @type to be 0 if a directory is created.
31421639a49cSYang Xu  * Filesystems raise that flag individually and we need to check whether each
31431639a49cSYang Xu  * filesystem can deal with receiving S_IFDIR from the vfs before we enforce a
31441639a49cSYang Xu  * non-zero type.
31451639a49cSYang Xu  *
31461639a49cSYang Xu  * Returns: mode to be passed to the filesystem
31471639a49cSYang Xu  */
31489452e93eSChristian Brauner static inline umode_t vfs_prepare_mode(struct mnt_idmap *idmap,
31491639a49cSYang Xu 				       const struct inode *dir, umode_t mode,
31501639a49cSYang Xu 				       umode_t mask_perms, umode_t type)
31511639a49cSYang Xu {
31529452e93eSChristian Brauner 	mode = mode_strip_sgid(idmap, dir, mode);
31531639a49cSYang Xu 	mode = mode_strip_umask(dir, mode);
31541639a49cSYang Xu 
31551639a49cSYang Xu 	/*
31561639a49cSYang Xu 	 * Apply the vfs mandated allowed permission mask and set the type of
31571639a49cSYang Xu 	 * file to be created before we call into the filesystem.
31581639a49cSYang Xu 	 */
31591639a49cSYang Xu 	mode &= (mask_perms & ~S_IFMT);
31601639a49cSYang Xu 	mode |= (type & S_IFMT);
31611639a49cSYang Xu 
31621639a49cSYang Xu 	return mode;
31631639a49cSYang Xu }
31641639a49cSYang Xu 
31651639a49cSYang Xu /**
31666521f891SChristian Brauner  * vfs_create - create new file
3167abf08576SChristian Brauner  * @idmap:	idmap of the mount the inode was found from
31686521f891SChristian Brauner  * @dir:	inode of @dentry
31696521f891SChristian Brauner  * @dentry:	pointer to dentry of the base directory
31706521f891SChristian Brauner  * @mode:	mode of the new file
31716521f891SChristian Brauner  * @want_excl:	whether the file must not yet exist
31726521f891SChristian Brauner  *
31736521f891SChristian Brauner  * Create a new file.
31746521f891SChristian Brauner  *
3175abf08576SChristian Brauner  * If the inode has been found through an idmapped mount the idmap of
3176abf08576SChristian Brauner  * the vfsmount must be passed through @idmap. This function will then take
3177abf08576SChristian Brauner  * care to map the inode according to @idmap before checking permissions.
31786521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
3179abf08576SChristian Brauner  * raw inode simply passs @nop_mnt_idmap.
31806521f891SChristian Brauner  */
3181abf08576SChristian Brauner int vfs_create(struct mnt_idmap *idmap, struct inode *dir,
31826521f891SChristian Brauner 	       struct dentry *dentry, umode_t mode, bool want_excl)
31831da177e4SLinus Torvalds {
3184abf08576SChristian Brauner 	int error;
3185abf08576SChristian Brauner 
31864609e1f1SChristian Brauner 	error = may_create(idmap, dir, dentry);
31871da177e4SLinus Torvalds 	if (error)
31881da177e4SLinus Torvalds 		return error;
31891da177e4SLinus Torvalds 
3190acfa4380SAl Viro 	if (!dir->i_op->create)
31911da177e4SLinus Torvalds 		return -EACCES;	/* shouldn't it be ENOSYS? */
31921639a49cSYang Xu 
31939452e93eSChristian Brauner 	mode = vfs_prepare_mode(idmap, dir, mode, S_IALLUGO, S_IFREG);
31941da177e4SLinus Torvalds 	error = security_inode_create(dir, dentry, mode);
31951da177e4SLinus Torvalds 	if (error)
31961da177e4SLinus Torvalds 		return error;
31976c960e68SChristian Brauner 	error = dir->i_op->create(idmap, dir, dentry, mode, want_excl);
3198a74574aaSStephen Smalley 	if (!error)
3199f38aa942SAmy Griffis 		fsnotify_create(dir, dentry);
32001da177e4SLinus Torvalds 	return error;
32011da177e4SLinus Torvalds }
32024d359507SAl Viro EXPORT_SYMBOL(vfs_create);
32031da177e4SLinus Torvalds 
32048e6c848eSAl Viro int vfs_mkobj(struct dentry *dentry, umode_t mode,
32058e6c848eSAl Viro 		int (*f)(struct dentry *, umode_t, void *),
32068e6c848eSAl Viro 		void *arg)
32078e6c848eSAl Viro {
32088e6c848eSAl Viro 	struct inode *dir = dentry->d_parent->d_inode;
32094609e1f1SChristian Brauner 	int error = may_create(&nop_mnt_idmap, dir, dentry);
32108e6c848eSAl Viro 	if (error)
32118e6c848eSAl Viro 		return error;
32128e6c848eSAl Viro 
32138e6c848eSAl Viro 	mode &= S_IALLUGO;
32148e6c848eSAl Viro 	mode |= S_IFREG;
32158e6c848eSAl Viro 	error = security_inode_create(dir, dentry, mode);
32168e6c848eSAl Viro 	if (error)
32178e6c848eSAl Viro 		return error;
32188e6c848eSAl Viro 	error = f(dentry, mode, arg);
32198e6c848eSAl Viro 	if (!error)
32208e6c848eSAl Viro 		fsnotify_create(dir, dentry);
32218e6c848eSAl Viro 	return error;
32228e6c848eSAl Viro }
32238e6c848eSAl Viro EXPORT_SYMBOL(vfs_mkobj);
32248e6c848eSAl Viro 
3225a2982cc9SEric W. Biederman bool may_open_dev(const struct path *path)
3226a2982cc9SEric W. Biederman {
3227a2982cc9SEric W. Biederman 	return !(path->mnt->mnt_flags & MNT_NODEV) &&
3228a2982cc9SEric W. Biederman 		!(path->mnt->mnt_sb->s_iflags & SB_I_NODEV);
3229a2982cc9SEric W. Biederman }
3230a2982cc9SEric W. Biederman 
32314609e1f1SChristian Brauner static int may_open(struct mnt_idmap *idmap, const struct path *path,
3232ba73d987SChristian Brauner 		    int acc_mode, int flag)
32331da177e4SLinus Torvalds {
32343fb64190SChristoph Hellwig 	struct dentry *dentry = path->dentry;
32351da177e4SLinus Torvalds 	struct inode *inode = dentry->d_inode;
32361da177e4SLinus Torvalds 	int error;
32371da177e4SLinus Torvalds 
32381da177e4SLinus Torvalds 	if (!inode)
32391da177e4SLinus Torvalds 		return -ENOENT;
32401da177e4SLinus Torvalds 
3241c8fe8f30SChristoph Hellwig 	switch (inode->i_mode & S_IFMT) {
3242c8fe8f30SChristoph Hellwig 	case S_IFLNK:
32431da177e4SLinus Torvalds 		return -ELOOP;
3244c8fe8f30SChristoph Hellwig 	case S_IFDIR:
3245fc4177beSKees Cook 		if (acc_mode & MAY_WRITE)
32461da177e4SLinus Torvalds 			return -EISDIR;
3247fc4177beSKees Cook 		if (acc_mode & MAY_EXEC)
3248fc4177beSKees Cook 			return -EACCES;
3249c8fe8f30SChristoph Hellwig 		break;
3250c8fe8f30SChristoph Hellwig 	case S_IFBLK:
3251c8fe8f30SChristoph Hellwig 	case S_IFCHR:
3252a2982cc9SEric W. Biederman 		if (!may_open_dev(path))
32531da177e4SLinus Torvalds 			return -EACCES;
3254633fb6acSKees Cook 		fallthrough;
3255c8fe8f30SChristoph Hellwig 	case S_IFIFO:
3256c8fe8f30SChristoph Hellwig 	case S_IFSOCK:
3257633fb6acSKees Cook 		if (acc_mode & MAY_EXEC)
3258633fb6acSKees Cook 			return -EACCES;
32591da177e4SLinus Torvalds 		flag &= ~O_TRUNC;
3260c8fe8f30SChristoph Hellwig 		break;
32610fd338b2SKees Cook 	case S_IFREG:
32620fd338b2SKees Cook 		if ((acc_mode & MAY_EXEC) && path_noexec(path))
32630fd338b2SKees Cook 			return -EACCES;
32640fd338b2SKees Cook 		break;
32654a3fd211SDave Hansen 	}
3266b41572e9SDave Hansen 
32674609e1f1SChristian Brauner 	error = inode_permission(idmap, inode, MAY_OPEN | acc_mode);
3268b41572e9SDave Hansen 	if (error)
3269b41572e9SDave Hansen 		return error;
32706146f0d5SMimi Zohar 
32711da177e4SLinus Torvalds 	/*
32721da177e4SLinus Torvalds 	 * An append-only file must be opened in append mode for writing.
32731da177e4SLinus Torvalds 	 */
32741da177e4SLinus Torvalds 	if (IS_APPEND(inode)) {
32758737c930SAl Viro 		if  ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND))
32767715b521SAl Viro 			return -EPERM;
32771da177e4SLinus Torvalds 		if (flag & O_TRUNC)
32787715b521SAl Viro 			return -EPERM;
32791da177e4SLinus Torvalds 	}
32801da177e4SLinus Torvalds 
32811da177e4SLinus Torvalds 	/* O_NOATIME can only be set by the owner or superuser */
328201beba79SChristian Brauner 	if (flag & O_NOATIME && !inode_owner_or_capable(idmap, inode))
32837715b521SAl Viro 		return -EPERM;
32841da177e4SLinus Torvalds 
3285f3c7691eSJ. Bruce Fields 	return 0;
32867715b521SAl Viro }
32877715b521SAl Viro 
3288abf08576SChristian Brauner static int handle_truncate(struct mnt_idmap *idmap, struct file *filp)
32897715b521SAl Viro {
3290f0bb5aafSAl Viro 	const struct path *path = &filp->f_path;
32917715b521SAl Viro 	struct inode *inode = path->dentry->d_inode;
32927715b521SAl Viro 	int error = get_write_access(inode);
32931da177e4SLinus Torvalds 	if (error)
32947715b521SAl Viro 		return error;
3295482e0007SJeff Layton 
32963350607dSGünther Noack 	error = security_file_truncate(filp);
32971da177e4SLinus Torvalds 	if (!error) {
3298abf08576SChristian Brauner 		error = do_truncate(idmap, path->dentry, 0,
3299d139d7ffSMiklos Szeredi 				    ATTR_MTIME|ATTR_CTIME|ATTR_OPEN,
3300e1181ee6SJeff Layton 				    filp);
33011da177e4SLinus Torvalds 	}
33021da177e4SLinus Torvalds 	put_write_access(inode);
3303acd0c935SMimi Zohar 	return error;
33041da177e4SLinus Torvalds }
33051da177e4SLinus Torvalds 
3306d57999e1SDave Hansen static inline int open_to_namei_flags(int flag)
3307d57999e1SDave Hansen {
33088a5e929dSAl Viro 	if ((flag & O_ACCMODE) == 3)
33098a5e929dSAl Viro 		flag--;
3310d57999e1SDave Hansen 	return flag;
3311d57999e1SDave Hansen }
3312d57999e1SDave Hansen 
33134609e1f1SChristian Brauner static int may_o_create(struct mnt_idmap *idmap,
3314ba73d987SChristian Brauner 			const struct path *dir, struct dentry *dentry,
3315ba73d987SChristian Brauner 			umode_t mode)
3316d18e9008SMiklos Szeredi {
3317d18e9008SMiklos Szeredi 	int error = security_path_mknod(dir, dentry, mode, 0);
3318d18e9008SMiklos Szeredi 	if (error)
3319d18e9008SMiklos Szeredi 		return error;
3320d18e9008SMiklos Szeredi 
33214609e1f1SChristian Brauner 	if (!fsuidgid_has_mapping(dir->dentry->d_sb, idmap))
33221328c727SSeth Forshee 		return -EOVERFLOW;
33231328c727SSeth Forshee 
33244609e1f1SChristian Brauner 	error = inode_permission(idmap, dir->dentry->d_inode,
332547291baaSChristian Brauner 				 MAY_WRITE | MAY_EXEC);
3326d18e9008SMiklos Szeredi 	if (error)
3327d18e9008SMiklos Szeredi 		return error;
3328d18e9008SMiklos Szeredi 
3329d18e9008SMiklos Szeredi 	return security_inode_create(dir->dentry->d_inode, dentry, mode);
3330d18e9008SMiklos Szeredi }
3331d18e9008SMiklos Szeredi 
33321acf0af9SDavid Howells /*
33331acf0af9SDavid Howells  * Attempt to atomically look up, create and open a file from a negative
33341acf0af9SDavid Howells  * dentry.
33351acf0af9SDavid Howells  *
33361acf0af9SDavid Howells  * Returns 0 if successful.  The file will have been created and attached to
33371acf0af9SDavid Howells  * @file by the filesystem calling finish_open().
33381acf0af9SDavid Howells  *
333900a07c15SAl Viro  * If the file was looked up only or didn't need creating, FMODE_OPENED won't
334000a07c15SAl Viro  * be set.  The caller will need to perform the open themselves.  @path will
334100a07c15SAl Viro  * have been updated to point to the new dentry.  This may be negative.
33421acf0af9SDavid Howells  *
33431acf0af9SDavid Howells  * Returns an error code otherwise.
33441acf0af9SDavid Howells  */
3345239eb983SAl Viro static struct dentry *atomic_open(struct nameidata *nd, struct dentry *dentry,
3346239eb983SAl Viro 				  struct file *file,
33473ec2eef1SAl Viro 				  int open_flag, umode_t mode)
3348d18e9008SMiklos Szeredi {
3349d18e9008SMiklos Szeredi 	struct dentry *const DENTRY_NOT_SET = (void *) -1UL;
3350d18e9008SMiklos Szeredi 	struct inode *dir =  nd->path.dentry->d_inode;
3351d18e9008SMiklos Szeredi 	int error;
3352d18e9008SMiklos Szeredi 
3353d18e9008SMiklos Szeredi 	if (nd->flags & LOOKUP_DIRECTORY)
3354d18e9008SMiklos Szeredi 		open_flag |= O_DIRECTORY;
3355d18e9008SMiklos Szeredi 
335630d90494SAl Viro 	file->f_path.dentry = DENTRY_NOT_SET;
335730d90494SAl Viro 	file->f_path.mnt = nd->path.mnt;
33580fb1ea09SAl Viro 	error = dir->i_op->atomic_open(dir, dentry, file,
335944907d79SAl Viro 				       open_to_namei_flags(open_flag), mode);
33606fbd0714SAl Viro 	d_lookup_done(dentry);
3361384f26e2SAl Viro 	if (!error) {
336264e1ac4dSAl Viro 		if (file->f_mode & FMODE_OPENED) {
33636fb968cdSAl Viro 			if (unlikely(dentry != file->f_path.dentry)) {
33646fb968cdSAl Viro 				dput(dentry);
33656fb968cdSAl Viro 				dentry = dget(file->f_path.dentry);
33666fb968cdSAl Viro 			}
336764e1ac4dSAl Viro 		} else if (WARN_ON(file->f_path.dentry == DENTRY_NOT_SET)) {
33682675a4ebSAl Viro 			error = -EIO;
3369384f26e2SAl Viro 		} else {
337030d90494SAl Viro 			if (file->f_path.dentry) {
3371d18e9008SMiklos Szeredi 				dput(dentry);
3372d18e9008SMiklos Szeredi 				dentry = file->f_path.dentry;
337310c64ceaSAl Viro 			}
3374239eb983SAl Viro 			if (unlikely(d_is_negative(dentry)))
3375a01e718fSAl Viro 				error = -ENOENT;
3376d18e9008SMiklos Szeredi 		}
3377d18e9008SMiklos Szeredi 	}
3378239eb983SAl Viro 	if (error) {
3379d18e9008SMiklos Szeredi 		dput(dentry);
3380239eb983SAl Viro 		dentry = ERR_PTR(error);
3381239eb983SAl Viro 	}
3382239eb983SAl Viro 	return dentry;
3383d18e9008SMiklos Szeredi }
3384d18e9008SMiklos Szeredi 
338531e6b01fSNick Piggin /*
33861acf0af9SDavid Howells  * Look up and maybe create and open the last component.
3387d58ffd35SMiklos Szeredi  *
338800a07c15SAl Viro  * Must be called with parent locked (exclusive in O_CREAT case).
3389d58ffd35SMiklos Szeredi  *
339000a07c15SAl Viro  * Returns 0 on success, that is, if
339100a07c15SAl Viro  *  the file was successfully atomically created (if necessary) and opened, or
339200a07c15SAl Viro  *  the file was not completely opened at this time, though lookups and
339300a07c15SAl Viro  *  creations were performed.
339400a07c15SAl Viro  * These case are distinguished by presence of FMODE_OPENED on file->f_mode.
339500a07c15SAl Viro  * In the latter case dentry returned in @path might be negative if O_CREAT
339600a07c15SAl Viro  * hadn't been specified.
33971acf0af9SDavid Howells  *
339800a07c15SAl Viro  * An error code is returned on failure.
3399d58ffd35SMiklos Szeredi  */
3400da5ebf5aSAl Viro static struct dentry *lookup_open(struct nameidata *nd, struct file *file,
3401d58ffd35SMiklos Szeredi 				  const struct open_flags *op,
34023ec2eef1SAl Viro 				  bool got_write)
3403d58ffd35SMiklos Szeredi {
34046c960e68SChristian Brauner 	struct mnt_idmap *idmap;
3405d58ffd35SMiklos Szeredi 	struct dentry *dir = nd->path.dentry;
340654ef4872SMiklos Szeredi 	struct inode *dir_inode = dir->d_inode;
34071643b43fSAl Viro 	int open_flag = op->open_flag;
3408d58ffd35SMiklos Szeredi 	struct dentry *dentry;
34091643b43fSAl Viro 	int error, create_error = 0;
34101643b43fSAl Viro 	umode_t mode = op->mode;
34116fbd0714SAl Viro 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
3412d58ffd35SMiklos Szeredi 
3413ce8644fcSAl Viro 	if (unlikely(IS_DEADDIR(dir_inode)))
3414da5ebf5aSAl Viro 		return ERR_PTR(-ENOENT);
3415d58ffd35SMiklos Szeredi 
341673a09dd9SAl Viro 	file->f_mode &= ~FMODE_CREATED;
34176fbd0714SAl Viro 	dentry = d_lookup(dir, &nd->last);
34186fbd0714SAl Viro 	for (;;) {
34196fbd0714SAl Viro 		if (!dentry) {
34206fbd0714SAl Viro 			dentry = d_alloc_parallel(dir, &nd->last, &wq);
3421d58ffd35SMiklos Szeredi 			if (IS_ERR(dentry))
3422da5ebf5aSAl Viro 				return dentry;
34236fbd0714SAl Viro 		}
34246fbd0714SAl Viro 		if (d_in_lookup(dentry))
34256fbd0714SAl Viro 			break;
3426d58ffd35SMiklos Szeredi 
34276fbd0714SAl Viro 		error = d_revalidate(dentry, nd->flags);
34286fbd0714SAl Viro 		if (likely(error > 0))
34296fbd0714SAl Viro 			break;
34306fbd0714SAl Viro 		if (error)
34316fbd0714SAl Viro 			goto out_dput;
34326fbd0714SAl Viro 		d_invalidate(dentry);
34336fbd0714SAl Viro 		dput(dentry);
34346fbd0714SAl Viro 		dentry = NULL;
34356fbd0714SAl Viro 	}
34366fbd0714SAl Viro 	if (dentry->d_inode) {
3437d18e9008SMiklos Szeredi 		/* Cached positive dentry: will open in f_op->open */
3438da5ebf5aSAl Viro 		return dentry;
34396c51e513SAl Viro 	}
3440d18e9008SMiklos Szeredi 
34411643b43fSAl Viro 	/*
34421643b43fSAl Viro 	 * Checking write permission is tricky, bacuse we don't know if we are
34431643b43fSAl Viro 	 * going to actually need it: O_CREAT opens should work as long as the
34441643b43fSAl Viro 	 * file exists.  But checking existence breaks atomicity.  The trick is
34451643b43fSAl Viro 	 * to check access and if not granted clear O_CREAT from the flags.
34461643b43fSAl Viro 	 *
34471643b43fSAl Viro 	 * Another problem is returing the "right" error value (e.g. for an
34481643b43fSAl Viro 	 * O_EXCL open we want to return EEXIST not EROFS).
34491643b43fSAl Viro 	 */
345099a4a90cSAl Viro 	if (unlikely(!got_write))
345199a4a90cSAl Viro 		open_flag &= ~O_TRUNC;
34526c960e68SChristian Brauner 	idmap = mnt_idmap(nd->path.mnt);
34531643b43fSAl Viro 	if (open_flag & O_CREAT) {
345499a4a90cSAl Viro 		if (open_flag & O_EXCL)
345599a4a90cSAl Viro 			open_flag &= ~O_TRUNC;
34569452e93eSChristian Brauner 		mode = vfs_prepare_mode(idmap, dir->d_inode, mode, mode, mode);
345799a4a90cSAl Viro 		if (likely(got_write))
34584609e1f1SChristian Brauner 			create_error = may_o_create(idmap, &nd->path,
3459ba73d987SChristian Brauner 						    dentry, mode);
346099a4a90cSAl Viro 		else
346199a4a90cSAl Viro 			create_error = -EROFS;
346299a4a90cSAl Viro 	}
346399a4a90cSAl Viro 	if (create_error)
34641643b43fSAl Viro 		open_flag &= ~O_CREAT;
34651643b43fSAl Viro 	if (dir_inode->i_op->atomic_open) {
3466d489cf9aSAl Viro 		dentry = atomic_open(nd, dentry, file, open_flag, mode);
3467da5ebf5aSAl Viro 		if (unlikely(create_error) && dentry == ERR_PTR(-ENOENT))
3468da5ebf5aSAl Viro 			dentry = ERR_PTR(create_error);
3469da5ebf5aSAl Viro 		return dentry;
3470239eb983SAl Viro 	}
347154ef4872SMiklos Szeredi 
34726fbd0714SAl Viro 	if (d_in_lookup(dentry)) {
347312fa5e24SAl Viro 		struct dentry *res = dir_inode->i_op->lookup(dir_inode, dentry,
347412fa5e24SAl Viro 							     nd->flags);
34756fbd0714SAl Viro 		d_lookup_done(dentry);
347612fa5e24SAl Viro 		if (unlikely(res)) {
347712fa5e24SAl Viro 			if (IS_ERR(res)) {
347812fa5e24SAl Viro 				error = PTR_ERR(res);
347912fa5e24SAl Viro 				goto out_dput;
348012fa5e24SAl Viro 			}
348112fa5e24SAl Viro 			dput(dentry);
348212fa5e24SAl Viro 			dentry = res;
348312fa5e24SAl Viro 		}
348454ef4872SMiklos Szeredi 	}
348554ef4872SMiklos Szeredi 
3486d58ffd35SMiklos Szeredi 	/* Negative dentry, just create the file */
34871643b43fSAl Viro 	if (!dentry->d_inode && (open_flag & O_CREAT)) {
348873a09dd9SAl Viro 		file->f_mode |= FMODE_CREATED;
3489ce8644fcSAl Viro 		audit_inode_child(dir_inode, dentry, AUDIT_TYPE_CHILD_CREATE);
3490ce8644fcSAl Viro 		if (!dir_inode->i_op->create) {
3491ce8644fcSAl Viro 			error = -EACCES;
3492d58ffd35SMiklos Szeredi 			goto out_dput;
349364894cf8SAl Viro 		}
3494549c7297SChristian Brauner 
34956c960e68SChristian Brauner 		error = dir_inode->i_op->create(idmap, dir_inode, dentry,
3496549c7297SChristian Brauner 						mode, open_flag & O_EXCL);
3497d58ffd35SMiklos Szeredi 		if (error)
3498d58ffd35SMiklos Szeredi 			goto out_dput;
3499d58ffd35SMiklos Szeredi 	}
35001643b43fSAl Viro 	if (unlikely(create_error) && !dentry->d_inode) {
35011643b43fSAl Viro 		error = create_error;
3502d58ffd35SMiklos Szeredi 		goto out_dput;
3503d58ffd35SMiklos Szeredi 	}
3504da5ebf5aSAl Viro 	return dentry;
3505d58ffd35SMiklos Szeredi 
3506d58ffd35SMiklos Szeredi out_dput:
3507d58ffd35SMiklos Szeredi 	dput(dentry);
3508da5ebf5aSAl Viro 	return ERR_PTR(error);
3509d58ffd35SMiklos Szeredi }
3510d58ffd35SMiklos Szeredi 
3511c981a482SAl Viro static const char *open_last_lookups(struct nameidata *nd,
35123ec2eef1SAl Viro 		   struct file *file, const struct open_flags *op)
3513fb1cc555SAl Viro {
3514a1e28038SAl Viro 	struct dentry *dir = nd->path.dentry;
3515ca344a89SAl Viro 	int open_flag = op->open_flag;
351664894cf8SAl Viro 	bool got_write = false;
3517da5ebf5aSAl Viro 	struct dentry *dentry;
3518b0417d2cSAl Viro 	const char *res;
3519fb1cc555SAl Viro 
3520c3e380b0SAl Viro 	nd->flags |= op->intent;
3521c3e380b0SAl Viro 
3522bc77daa7SAl Viro 	if (nd->last_type != LAST_NORM) {
352356676ec3SAl Viro 		if (nd->depth)
352456676ec3SAl Viro 			put_link(nd);
3525ff326a32SAl Viro 		return handle_dots(nd, nd->last_type);
35261f36f774SAl Viro 	}
3527a2c36b45SAl Viro 
3528ca344a89SAl Viro 	if (!(open_flag & O_CREAT)) {
3529fe2d35ffSAl Viro 		if (nd->last.name[nd->last.len])
3530fe2d35ffSAl Viro 			nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
3531fe2d35ffSAl Viro 		/* we _can_ be in RCU mode here */
35324cb64024SAl Viro 		dentry = lookup_fast(nd);
353320e34357SAl Viro 		if (IS_ERR(dentry))
35341ccac622SAl Viro 			return ERR_CAST(dentry);
353520e34357SAl Viro 		if (likely(dentry))
353671574865SMiklos Szeredi 			goto finish_lookup;
353771574865SMiklos Szeredi 
35386583fe22SAl Viro 		BUG_ON(nd->flags & LOOKUP_RCU);
3539b6183df7SMiklos Szeredi 	} else {
3540fe2d35ffSAl Viro 		/* create side of things */
354172287417SAl Viro 		if (nd->flags & LOOKUP_RCU) {
3542e36cffedSJens Axboe 			if (!try_to_unlazy(nd))
3543e36cffedSJens Axboe 				return ERR_PTR(-ECHILD);
354472287417SAl Viro 		}
3545c9b07eabSAl Viro 		audit_inode(nd->name, dir, AUDIT_INODE_PARENT);
35461f36f774SAl Viro 		/* trailing slashes? */
3547deb106c6SAl Viro 		if (unlikely(nd->last.name[nd->last.len]))
35481ccac622SAl Viro 			return ERR_PTR(-EISDIR);
3549b6183df7SMiklos Szeredi 	}
35501f36f774SAl Viro 
35519cf843e3SAl Viro 	if (open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) {
3552e36cffedSJens Axboe 		got_write = !mnt_want_write(nd->path.mnt);
355364894cf8SAl Viro 		/*
355464894cf8SAl Viro 		 * do _not_ fail yet - we might not need that or fail with
355564894cf8SAl Viro 		 * a different error; let lookup_open() decide; we'll be
355664894cf8SAl Viro 		 * dropping this one anyway.
355764894cf8SAl Viro 		 */
355864894cf8SAl Viro 	}
35599cf843e3SAl Viro 	if (open_flag & O_CREAT)
35605955102cSAl Viro 		inode_lock(dir->d_inode);
35619cf843e3SAl Viro 	else
35629cf843e3SAl Viro 		inode_lock_shared(dir->d_inode);
3563da5ebf5aSAl Viro 	dentry = lookup_open(nd, file, op, got_write);
3564f7bb959dSAl Viro 	if (!IS_ERR(dentry) && (file->f_mode & FMODE_CREATED))
3565f7bb959dSAl Viro 		fsnotify_create(dir->d_inode, dentry);
35669cf843e3SAl Viro 	if (open_flag & O_CREAT)
35675955102cSAl Viro 		inode_unlock(dir->d_inode);
35689cf843e3SAl Viro 	else
35699cf843e3SAl Viro 		inode_unlock_shared(dir->d_inode);
3570fb1cc555SAl Viro 
3571c981a482SAl Viro 	if (got_write)
357259e96e65SAl Viro 		mnt_drop_write(nd->path.mnt);
35736c0d46c4SAl Viro 
357459e96e65SAl Viro 	if (IS_ERR(dentry))
357559e96e65SAl Viro 		return ERR_CAST(dentry);
357659e96e65SAl Viro 
3577973d4b73SAl Viro 	if (file->f_mode & (FMODE_OPENED | FMODE_CREATED)) {
3578e73cabffSAl Viro 		dput(nd->path.dentry);
3579e73cabffSAl Viro 		nd->path.dentry = dentry;
3580c981a482SAl Viro 		return NULL;
3581fb1cc555SAl Viro 	}
3582fb1cc555SAl Viro 
358320e34357SAl Viro finish_lookup:
358456676ec3SAl Viro 	if (nd->depth)
358556676ec3SAl Viro 		put_link(nd);
3586a4f5b521SAl Viro 	res = step_into(nd, WALK_TRAILING, dentry);
3587ff326a32SAl Viro 	if (unlikely(res))
35881ccac622SAl Viro 		nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL);
3589b0417d2cSAl Viro 	return res;
35901ccac622SAl Viro }
359131d1726dSAl Viro 
3592c981a482SAl Viro /*
3593c981a482SAl Viro  * Handle the last step of open()
3594c981a482SAl Viro  */
3595c5971b8cSAl Viro static int do_open(struct nameidata *nd,
3596c981a482SAl Viro 		   struct file *file, const struct open_flags *op)
3597c981a482SAl Viro {
3598abf08576SChristian Brauner 	struct mnt_idmap *idmap;
3599c981a482SAl Viro 	int open_flag = op->open_flag;
3600c981a482SAl Viro 	bool do_truncate;
3601c981a482SAl Viro 	int acc_mode;
3602c981a482SAl Viro 	int error;
3603c981a482SAl Viro 
3604ff326a32SAl Viro 	if (!(file->f_mode & (FMODE_OPENED | FMODE_CREATED))) {
3605ff326a32SAl Viro 		error = complete_walk(nd);
3606ff326a32SAl Viro 		if (error)
3607ff326a32SAl Viro 			return error;
3608ff326a32SAl Viro 	}
3609973d4b73SAl Viro 	if (!(file->f_mode & FMODE_CREATED))
361076ae2a5aSAl Viro 		audit_inode(nd->name, nd->path.dentry, 0);
3611abf08576SChristian Brauner 	idmap = mnt_idmap(nd->path.mnt);
361230aba665SSalvatore Mesoraca 	if (open_flag & O_CREAT) {
3613b94e0b32SAl Viro 		if ((open_flag & O_EXCL) && !(file->f_mode & FMODE_CREATED))
3614b94e0b32SAl Viro 			return -EEXIST;
361530aba665SSalvatore Mesoraca 		if (d_is_dir(nd->path.dentry))
3616c5971b8cSAl Viro 			return -EISDIR;
3617e67fe633SChristian Brauner 		error = may_create_in_sticky(idmap, nd,
361830aba665SSalvatore Mesoraca 					     d_backing_inode(nd->path.dentry));
361930aba665SSalvatore Mesoraca 		if (unlikely(error))
3620c5971b8cSAl Viro 			return error;
362130aba665SSalvatore Mesoraca 	}
362244b1d530SMiklos Szeredi 	if ((nd->flags & LOOKUP_DIRECTORY) && !d_can_lookup(nd->path.dentry))
3623c5971b8cSAl Viro 		return -ENOTDIR;
36246c0d46c4SAl Viro 
36258795e7d4SAl Viro 	do_truncate = false;
36268795e7d4SAl Viro 	acc_mode = op->acc_mode;
36275a2d3eddSAl Viro 	if (file->f_mode & FMODE_CREATED) {
36285a2d3eddSAl Viro 		/* Don't check for write permission, don't truncate */
36295a2d3eddSAl Viro 		open_flag &= ~O_TRUNC;
36305a2d3eddSAl Viro 		acc_mode = 0;
36318795e7d4SAl Viro 	} else if (d_is_reg(nd->path.dentry) && open_flag & O_TRUNC) {
36320f9d1a10SAl Viro 		error = mnt_want_write(nd->path.mnt);
36330f9d1a10SAl Viro 		if (error)
3634c5971b8cSAl Viro 			return error;
36358795e7d4SAl Viro 		do_truncate = true;
36360f9d1a10SAl Viro 	}
36374609e1f1SChristian Brauner 	error = may_open(idmap, &nd->path, acc_mode, open_flag);
36388795e7d4SAl Viro 	if (!error && !(file->f_mode & FMODE_OPENED))
3639ae2bb293SAl Viro 		error = vfs_open(&nd->path, file);
36408795e7d4SAl Viro 	if (!error)
36416035a27bSAl Viro 		error = ima_file_check(file, op->acc_mode);
36428795e7d4SAl Viro 	if (!error && do_truncate)
3643abf08576SChristian Brauner 		error = handle_truncate(idmap, file);
3644c80567c8SAl Viro 	if (unlikely(error > 0)) {
3645c80567c8SAl Viro 		WARN_ON(1);
3646c80567c8SAl Viro 		error = -EINVAL;
3647c80567c8SAl Viro 	}
36488795e7d4SAl Viro 	if (do_truncate)
36490f9d1a10SAl Viro 		mnt_drop_write(nd->path.mnt);
3650c5971b8cSAl Viro 	return error;
3651fb1cc555SAl Viro }
3652fb1cc555SAl Viro 
36536521f891SChristian Brauner /**
36546521f891SChristian Brauner  * vfs_tmpfile - create tmpfile
3655abf08576SChristian Brauner  * @idmap:	idmap of the mount the inode was found from
365673bb5a90SRoberto Sassu  * @parentpath:	pointer to the path of the base directory
365773bb5a90SRoberto Sassu  * @file:	file descriptor of the new tmpfile
36586521f891SChristian Brauner  * @mode:	mode of the new tmpfile
36596521f891SChristian Brauner  *
36606521f891SChristian Brauner  * Create a temporary file.
36616521f891SChristian Brauner  *
3662abf08576SChristian Brauner  * If the inode has been found through an idmapped mount the idmap of
3663abf08576SChristian Brauner  * the vfsmount must be passed through @idmap. This function will then take
3664abf08576SChristian Brauner  * care to map the inode according to @idmap before checking permissions.
36656521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
3666abf08576SChristian Brauner  * raw inode simply passs @nop_mnt_idmap.
36676521f891SChristian Brauner  */
3668abf08576SChristian Brauner static int vfs_tmpfile(struct mnt_idmap *idmap,
36699751b338SMiklos Szeredi 		       const struct path *parentpath,
36709751b338SMiklos Szeredi 		       struct file *file, umode_t mode)
3671af7bd4dcSAmir Goldstein {
36729751b338SMiklos Szeredi 	struct dentry *child;
36739751b338SMiklos Szeredi 	struct inode *dir = d_inode(parentpath->dentry);
3674af7bd4dcSAmir Goldstein 	struct inode *inode;
3675af7bd4dcSAmir Goldstein 	int error;
3676406c706cSPeter Griffin 	int open_flag = file->f_flags;
3677af7bd4dcSAmir Goldstein 
3678af7bd4dcSAmir Goldstein 	/* we want directory to be writable */
36794609e1f1SChristian Brauner 	error = inode_permission(idmap, dir, MAY_WRITE | MAY_EXEC);
3680af7bd4dcSAmir Goldstein 	if (error)
36819751b338SMiklos Szeredi 		return error;
3682af7bd4dcSAmir Goldstein 	if (!dir->i_op->tmpfile)
36839751b338SMiklos Szeredi 		return -EOPNOTSUPP;
36849751b338SMiklos Szeredi 	child = d_alloc(parentpath->dentry, &slash_name);
3685af7bd4dcSAmir Goldstein 	if (unlikely(!child))
36869751b338SMiklos Szeredi 		return -ENOMEM;
36879751b338SMiklos Szeredi 	file->f_path.mnt = parentpath->mnt;
36889751b338SMiklos Szeredi 	file->f_path.dentry = child;
36899452e93eSChristian Brauner 	mode = vfs_prepare_mode(idmap, dir, mode, mode, mode);
3690011e2b71SChristian Brauner 	error = dir->i_op->tmpfile(idmap, dir, file, mode);
36919751b338SMiklos Szeredi 	dput(child);
3692af7bd4dcSAmir Goldstein 	if (error)
36939751b338SMiklos Szeredi 		return error;
36949751b338SMiklos Szeredi 	/* Don't check for other permissions, the inode was just created */
36954609e1f1SChristian Brauner 	error = may_open(idmap, &file->f_path, 0, file->f_flags);
36969751b338SMiklos Szeredi 	if (error)
36979751b338SMiklos Szeredi 		return error;
36989751b338SMiklos Szeredi 	inode = file_inode(file);
3699406c706cSPeter Griffin 	if (!(open_flag & O_EXCL)) {
3700af7bd4dcSAmir Goldstein 		spin_lock(&inode->i_lock);
3701af7bd4dcSAmir Goldstein 		inode->i_state |= I_LINKABLE;
3702af7bd4dcSAmir Goldstein 		spin_unlock(&inode->i_lock);
3703af7bd4dcSAmir Goldstein 	}
370439f60c1cSChristian Brauner 	ima_post_create_tmpfile(idmap, inode);
37059751b338SMiklos Szeredi 	return 0;
3706af7bd4dcSAmir Goldstein }
3707af7bd4dcSAmir Goldstein 
370822873deaSMiklos Szeredi /**
3709d56e0ddbSAmir Goldstein  * kernel_tmpfile_open - open a tmpfile for kernel internal use
3710abf08576SChristian Brauner  * @idmap:	idmap of the mount the inode was found from
371122873deaSMiklos Szeredi  * @parentpath:	path of the base directory
371222873deaSMiklos Szeredi  * @mode:	mode of the new tmpfile
371322873deaSMiklos Szeredi  * @open_flag:	flags
371422873deaSMiklos Szeredi  * @cred:	credentials for open
371522873deaSMiklos Szeredi  *
371622873deaSMiklos Szeredi  * Create and open a temporary file.  The file is not accounted in nr_files,
371722873deaSMiklos Szeredi  * hence this is only for kernel internal use, and must not be installed into
371822873deaSMiklos Szeredi  * file tables or such.
371922873deaSMiklos Szeredi  */
3720d56e0ddbSAmir Goldstein struct file *kernel_tmpfile_open(struct mnt_idmap *idmap,
372122873deaSMiklos Szeredi 				 const struct path *parentpath,
3722d56e0ddbSAmir Goldstein 				 umode_t mode, int open_flag,
3723d56e0ddbSAmir Goldstein 				 const struct cred *cred)
372422873deaSMiklos Szeredi {
372522873deaSMiklos Szeredi 	struct file *file;
372622873deaSMiklos Szeredi 	int error;
372722873deaSMiklos Szeredi 
37289751b338SMiklos Szeredi 	file = alloc_empty_file_noaccount(open_flag, cred);
3729d56e0ddbSAmir Goldstein 	if (IS_ERR(file))
3730d56e0ddbSAmir Goldstein 		return file;
3731d56e0ddbSAmir Goldstein 
3732abf08576SChristian Brauner 	error = vfs_tmpfile(idmap, parentpath, file, mode);
37339751b338SMiklos Szeredi 	if (error) {
37349751b338SMiklos Szeredi 		fput(file);
373522873deaSMiklos Szeredi 		file = ERR_PTR(error);
37369751b338SMiklos Szeredi 	}
373722873deaSMiklos Szeredi 	return file;
373822873deaSMiklos Szeredi }
3739d56e0ddbSAmir Goldstein EXPORT_SYMBOL(kernel_tmpfile_open);
3740648fa861SAl Viro 
3741c8a53ee5SAl Viro static int do_tmpfile(struct nameidata *nd, unsigned flags,
374260545d0dSAl Viro 		const struct open_flags *op,
37433ec2eef1SAl Viro 		struct file *file)
374460545d0dSAl Viro {
3745625b6d10SAl Viro 	struct path path;
3746c8a53ee5SAl Viro 	int error = path_lookupat(nd, flags | LOOKUP_DIRECTORY, &path);
37479751b338SMiklos Szeredi 
374860545d0dSAl Viro 	if (unlikely(error))
374960545d0dSAl Viro 		return error;
3750625b6d10SAl Viro 	error = mnt_want_write(path.mnt);
375160545d0dSAl Viro 	if (unlikely(error))
375260545d0dSAl Viro 		goto out;
3753abf08576SChristian Brauner 	error = vfs_tmpfile(mnt_idmap(path.mnt), &path, file, op->mode);
37549751b338SMiklos Szeredi 	if (error)
375560545d0dSAl Viro 		goto out2;
37569751b338SMiklos Szeredi 	audit_inode(nd->name, file->f_path.dentry, 0);
375760545d0dSAl Viro out2:
3758625b6d10SAl Viro 	mnt_drop_write(path.mnt);
375960545d0dSAl Viro out:
3760625b6d10SAl Viro 	path_put(&path);
376160545d0dSAl Viro 	return error;
376260545d0dSAl Viro }
376360545d0dSAl Viro 
37646ac08709SAl Viro static int do_o_path(struct nameidata *nd, unsigned flags, struct file *file)
37656ac08709SAl Viro {
37666ac08709SAl Viro 	struct path path;
37676ac08709SAl Viro 	int error = path_lookupat(nd, flags, &path);
37686ac08709SAl Viro 	if (!error) {
37696ac08709SAl Viro 		audit_inode(nd->name, path.dentry, 0);
3770ae2bb293SAl Viro 		error = vfs_open(&path, file);
37716ac08709SAl Viro 		path_put(&path);
37726ac08709SAl Viro 	}
37736ac08709SAl Viro 	return error;
37746ac08709SAl Viro }
37756ac08709SAl Viro 
3776c8a53ee5SAl Viro static struct file *path_openat(struct nameidata *nd,
3777c8a53ee5SAl Viro 			const struct open_flags *op, unsigned flags)
37781da177e4SLinus Torvalds {
377930d90494SAl Viro 	struct file *file;
378013aab428SAl Viro 	int error;
378131e6b01fSNick Piggin 
3782ea73ea72SAl Viro 	file = alloc_empty_file(op->open_flag, current_cred());
37831afc99beSAl Viro 	if (IS_ERR(file))
37841afc99beSAl Viro 		return file;
378531e6b01fSNick Piggin 
3786bb458c64SAl Viro 	if (unlikely(file->f_flags & __O_TMPFILE)) {
37873ec2eef1SAl Viro 		error = do_tmpfile(nd, flags, op, file);
37885f336e72SAl Viro 	} else if (unlikely(file->f_flags & O_PATH)) {
37896ac08709SAl Viro 		error = do_o_path(nd, flags, file);
37905f336e72SAl Viro 	} else {
37915f336e72SAl Viro 		const char *s = path_init(nd, flags);
37923bdba28bSAl Viro 		while (!(error = link_path_walk(s, nd)) &&
3793c5971b8cSAl Viro 		       (s = open_last_lookups(nd, file, op)) != NULL)
37941ccac622SAl Viro 			;
3795c5971b8cSAl Viro 		if (!error)
3796c5971b8cSAl Viro 			error = do_open(nd, file, op);
3797deb106c6SAl Viro 		terminate_walk(nd);
37985f336e72SAl Viro 	}
37997c1c01ecSAl Viro 	if (likely(!error)) {
3800aad888f8SAl Viro 		if (likely(file->f_mode & FMODE_OPENED))
38017c1c01ecSAl Viro 			return file;
38027c1c01ecSAl Viro 		WARN_ON(1);
38037c1c01ecSAl Viro 		error = -EINVAL;
3804015c3bbcSMiklos Szeredi 	}
38057c1c01ecSAl Viro 	fput(file);
38062675a4ebSAl Viro 	if (error == -EOPENSTALE) {
38072675a4ebSAl Viro 		if (flags & LOOKUP_RCU)
38082675a4ebSAl Viro 			error = -ECHILD;
38092675a4ebSAl Viro 		else
38102675a4ebSAl Viro 			error = -ESTALE;
38112675a4ebSAl Viro 	}
38127c1c01ecSAl Viro 	return ERR_PTR(error);
3813de459215SKirill Korotaev }
38141da177e4SLinus Torvalds 
3815669abf4eSJeff Layton struct file *do_filp_open(int dfd, struct filename *pathname,
3816f9652e10SAl Viro 		const struct open_flags *op)
381713aab428SAl Viro {
38189883d185SAl Viro 	struct nameidata nd;
3819f9652e10SAl Viro 	int flags = op->lookup_flags;
382013aab428SAl Viro 	struct file *filp;
382113aab428SAl Viro 
382206422964SAl Viro 	set_nameidata(&nd, dfd, pathname, NULL);
3823c8a53ee5SAl Viro 	filp = path_openat(&nd, op, flags | LOOKUP_RCU);
382413aab428SAl Viro 	if (unlikely(filp == ERR_PTR(-ECHILD)))
3825c8a53ee5SAl Viro 		filp = path_openat(&nd, op, flags);
382613aab428SAl Viro 	if (unlikely(filp == ERR_PTR(-ESTALE)))
3827c8a53ee5SAl Viro 		filp = path_openat(&nd, op, flags | LOOKUP_REVAL);
38289883d185SAl Viro 	restore_nameidata();
382913aab428SAl Viro 	return filp;
383013aab428SAl Viro }
383113aab428SAl Viro 
3832ffb37ca3SAl Viro struct file *do_file_open_root(const struct path *root,
3833f9652e10SAl Viro 		const char *name, const struct open_flags *op)
383473d049a4SAl Viro {
38359883d185SAl Viro 	struct nameidata nd;
383673d049a4SAl Viro 	struct file *file;
383751689104SPaul Moore 	struct filename *filename;
3838bcba1e7dSAl Viro 	int flags = op->lookup_flags;
383973d049a4SAl Viro 
3840ffb37ca3SAl Viro 	if (d_is_symlink(root->dentry) && op->intent & LOOKUP_OPEN)
384173d049a4SAl Viro 		return ERR_PTR(-ELOOP);
384273d049a4SAl Viro 
384351689104SPaul Moore 	filename = getname_kernel(name);
3844a1c83681SViresh Kumar 	if (IS_ERR(filename))
384551689104SPaul Moore 		return ERR_CAST(filename);
384651689104SPaul Moore 
384706422964SAl Viro 	set_nameidata(&nd, -1, filename, root);
3848c8a53ee5SAl Viro 	file = path_openat(&nd, op, flags | LOOKUP_RCU);
384973d049a4SAl Viro 	if (unlikely(file == ERR_PTR(-ECHILD)))
3850c8a53ee5SAl Viro 		file = path_openat(&nd, op, flags);
385173d049a4SAl Viro 	if (unlikely(file == ERR_PTR(-ESTALE)))
3852c8a53ee5SAl Viro 		file = path_openat(&nd, op, flags | LOOKUP_REVAL);
38539883d185SAl Viro 	restore_nameidata();
385451689104SPaul Moore 	putname(filename);
385573d049a4SAl Viro 	return file;
385673d049a4SAl Viro }
385773d049a4SAl Viro 
3858b4a4f213SStephen Brennan static struct dentry *filename_create(int dfd, struct filename *name,
38591ac12b4bSJeff Layton 				      struct path *path, unsigned int lookup_flags)
38601da177e4SLinus Torvalds {
3861c663e5d8SChristoph Hellwig 	struct dentry *dentry = ERR_PTR(-EEXIST);
3862391172c4SAl Viro 	struct qstr last;
3863b3d4650dSNeilBrown 	bool want_dir = lookup_flags & LOOKUP_DIRECTORY;
3864b3d4650dSNeilBrown 	unsigned int reval_flag = lookup_flags & LOOKUP_REVAL;
3865b3d4650dSNeilBrown 	unsigned int create_flags = LOOKUP_CREATE | LOOKUP_EXCL;
3866391172c4SAl Viro 	int type;
3867c30dabfeSJan Kara 	int err2;
38681ac12b4bSJeff Layton 	int error;
38691ac12b4bSJeff Layton 
3870b3d4650dSNeilBrown 	error = filename_parentat(dfd, name, reval_flag, path, &last, &type);
38710ee50b47SDmitry Kadashev 	if (error)
38720ee50b47SDmitry Kadashev 		return ERR_PTR(error);
38731da177e4SLinus Torvalds 
3874c663e5d8SChristoph Hellwig 	/*
3875c663e5d8SChristoph Hellwig 	 * Yucky last component or no last component at all?
3876c663e5d8SChristoph Hellwig 	 * (foo/., foo/.., /////)
3877c663e5d8SChristoph Hellwig 	 */
38785c31b6ceSAl Viro 	if (unlikely(type != LAST_NORM))
3879ed75e95dSAl Viro 		goto out;
3880c663e5d8SChristoph Hellwig 
3881c30dabfeSJan Kara 	/* don't fail immediately if it's r/o, at least try to report other errors */
3882391172c4SAl Viro 	err2 = mnt_want_write(path->mnt);
3883c663e5d8SChristoph Hellwig 	/*
3884b3d4650dSNeilBrown 	 * Do the final lookup.  Suppress 'create' if there is a trailing
3885b3d4650dSNeilBrown 	 * '/', and a directory wasn't requested.
3886c663e5d8SChristoph Hellwig 	 */
3887b3d4650dSNeilBrown 	if (last.name[last.len] && !want_dir)
3888b3d4650dSNeilBrown 		create_flags = 0;
38895955102cSAl Viro 	inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
389074d7970fSNamjae Jeon 	dentry = lookup_one_qstr_excl(&last, path->dentry,
389174d7970fSNamjae Jeon 				      reval_flag | create_flags);
38921da177e4SLinus Torvalds 	if (IS_ERR(dentry))
3893a8104a9fSAl Viro 		goto unlock;
3894c663e5d8SChristoph Hellwig 
3895a8104a9fSAl Viro 	error = -EEXIST;
3896b18825a7SDavid Howells 	if (d_is_positive(dentry))
3897a8104a9fSAl Viro 		goto fail;
3898b18825a7SDavid Howells 
3899c663e5d8SChristoph Hellwig 	/*
3900c663e5d8SChristoph Hellwig 	 * Special case - lookup gave negative, but... we had foo/bar/
3901c663e5d8SChristoph Hellwig 	 * From the vfs_mknod() POV we just have a negative dentry -
3902c663e5d8SChristoph Hellwig 	 * all is fine. Let's be bastards - you had / on the end, you've
3903c663e5d8SChristoph Hellwig 	 * been asking for (non-existent) directory. -ENOENT for you.
3904c663e5d8SChristoph Hellwig 	 */
3905b3d4650dSNeilBrown 	if (unlikely(!create_flags)) {
3906a8104a9fSAl Viro 		error = -ENOENT;
3907ed75e95dSAl Viro 		goto fail;
3908e9baf6e5SAl Viro 	}
3909c30dabfeSJan Kara 	if (unlikely(err2)) {
3910c30dabfeSJan Kara 		error = err2;
3911a8104a9fSAl Viro 		goto fail;
3912c30dabfeSJan Kara 	}
3913e9baf6e5SAl Viro 	return dentry;
39141da177e4SLinus Torvalds fail:
3915a8104a9fSAl Viro 	dput(dentry);
3916a8104a9fSAl Viro 	dentry = ERR_PTR(error);
3917a8104a9fSAl Viro unlock:
39185955102cSAl Viro 	inode_unlock(path->dentry->d_inode);
3919c30dabfeSJan Kara 	if (!err2)
3920391172c4SAl Viro 		mnt_drop_write(path->mnt);
3921ed75e95dSAl Viro out:
3922391172c4SAl Viro 	path_put(path);
3923ed75e95dSAl Viro 	return dentry;
3924dae6ad8fSAl Viro }
3925fa14a0b8SAl Viro 
3926fa14a0b8SAl Viro struct dentry *kern_path_create(int dfd, const char *pathname,
3927fa14a0b8SAl Viro 				struct path *path, unsigned int lookup_flags)
3928fa14a0b8SAl Viro {
3929b4a4f213SStephen Brennan 	struct filename *filename = getname_kernel(pathname);
3930b4a4f213SStephen Brennan 	struct dentry *res = filename_create(dfd, filename, path, lookup_flags);
3931b4a4f213SStephen Brennan 
3932b4a4f213SStephen Brennan 	putname(filename);
3933b4a4f213SStephen Brennan 	return res;
3934fa14a0b8SAl Viro }
3935dae6ad8fSAl Viro EXPORT_SYMBOL(kern_path_create);
3936dae6ad8fSAl Viro 
3937921a1650SAl Viro void done_path_create(struct path *path, struct dentry *dentry)
3938921a1650SAl Viro {
3939921a1650SAl Viro 	dput(dentry);
39405955102cSAl Viro 	inode_unlock(path->dentry->d_inode);
3941a8104a9fSAl Viro 	mnt_drop_write(path->mnt);
3942921a1650SAl Viro 	path_put(path);
3943921a1650SAl Viro }
3944921a1650SAl Viro EXPORT_SYMBOL(done_path_create);
3945921a1650SAl Viro 
3946520ae687SAl Viro inline struct dentry *user_path_create(int dfd, const char __user *pathname,
39471ac12b4bSJeff Layton 				struct path *path, unsigned int lookup_flags)
3948dae6ad8fSAl Viro {
3949b4a4f213SStephen Brennan 	struct filename *filename = getname(pathname);
3950b4a4f213SStephen Brennan 	struct dentry *res = filename_create(dfd, filename, path, lookup_flags);
3951b4a4f213SStephen Brennan 
3952b4a4f213SStephen Brennan 	putname(filename);
3953b4a4f213SStephen Brennan 	return res;
3954dae6ad8fSAl Viro }
3955dae6ad8fSAl Viro EXPORT_SYMBOL(user_path_create);
3956dae6ad8fSAl Viro 
39576521f891SChristian Brauner /**
39586521f891SChristian Brauner  * vfs_mknod - create device node or file
3959abf08576SChristian Brauner  * @idmap:	idmap of the mount the inode was found from
39606521f891SChristian Brauner  * @dir:	inode of @dentry
39616521f891SChristian Brauner  * @dentry:	pointer to dentry of the base directory
39626521f891SChristian Brauner  * @mode:	mode of the new device node or file
39636521f891SChristian Brauner  * @dev:	device number of device to create
39646521f891SChristian Brauner  *
39656521f891SChristian Brauner  * Create a device node or file.
39666521f891SChristian Brauner  *
3967abf08576SChristian Brauner  * If the inode has been found through an idmapped mount the idmap of
3968abf08576SChristian Brauner  * the vfsmount must be passed through @idmap. This function will then take
3969abf08576SChristian Brauner  * care to map the inode according to @idmap before checking permissions.
39706521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
3971abf08576SChristian Brauner  * raw inode simply passs @nop_mnt_idmap.
39726521f891SChristian Brauner  */
3973abf08576SChristian Brauner int vfs_mknod(struct mnt_idmap *idmap, struct inode *dir,
39746521f891SChristian Brauner 	      struct dentry *dentry, umode_t mode, dev_t dev)
39751da177e4SLinus Torvalds {
3976a3c751a5SMiklos Szeredi 	bool is_whiteout = S_ISCHR(mode) && dev == WHITEOUT_DEV;
39774609e1f1SChristian Brauner 	int error = may_create(idmap, dir, dentry);
39781da177e4SLinus Torvalds 
39791da177e4SLinus Torvalds 	if (error)
39801da177e4SLinus Torvalds 		return error;
39811da177e4SLinus Torvalds 
3982a3c751a5SMiklos Szeredi 	if ((S_ISCHR(mode) || S_ISBLK(mode)) && !is_whiteout &&
3983a3c751a5SMiklos Szeredi 	    !capable(CAP_MKNOD))
39841da177e4SLinus Torvalds 		return -EPERM;
39851da177e4SLinus Torvalds 
3986acfa4380SAl Viro 	if (!dir->i_op->mknod)
39871da177e4SLinus Torvalds 		return -EPERM;
39881da177e4SLinus Torvalds 
39899452e93eSChristian Brauner 	mode = vfs_prepare_mode(idmap, dir, mode, mode, mode);
399008ce5f16SSerge E. Hallyn 	error = devcgroup_inode_mknod(mode, dev);
399108ce5f16SSerge E. Hallyn 	if (error)
399208ce5f16SSerge E. Hallyn 		return error;
399308ce5f16SSerge E. Hallyn 
39941da177e4SLinus Torvalds 	error = security_inode_mknod(dir, dentry, mode, dev);
39951da177e4SLinus Torvalds 	if (error)
39961da177e4SLinus Torvalds 		return error;
39971da177e4SLinus Torvalds 
39985ebb29beSChristian Brauner 	error = dir->i_op->mknod(idmap, dir, dentry, mode, dev);
3999a74574aaSStephen Smalley 	if (!error)
4000f38aa942SAmy Griffis 		fsnotify_create(dir, dentry);
40011da177e4SLinus Torvalds 	return error;
40021da177e4SLinus Torvalds }
40034d359507SAl Viro EXPORT_SYMBOL(vfs_mknod);
40041da177e4SLinus Torvalds 
4005f69aac00SAl Viro static int may_mknod(umode_t mode)
4006463c3197SDave Hansen {
4007463c3197SDave Hansen 	switch (mode & S_IFMT) {
4008463c3197SDave Hansen 	case S_IFREG:
4009463c3197SDave Hansen 	case S_IFCHR:
4010463c3197SDave Hansen 	case S_IFBLK:
4011463c3197SDave Hansen 	case S_IFIFO:
4012463c3197SDave Hansen 	case S_IFSOCK:
4013463c3197SDave Hansen 	case 0: /* zero mode translates to S_IFREG */
4014463c3197SDave Hansen 		return 0;
4015463c3197SDave Hansen 	case S_IFDIR:
4016463c3197SDave Hansen 		return -EPERM;
4017463c3197SDave Hansen 	default:
4018463c3197SDave Hansen 		return -EINVAL;
4019463c3197SDave Hansen 	}
4020463c3197SDave Hansen }
4021463c3197SDave Hansen 
402245f30dabSDmitry Kadashev static int do_mknodat(int dfd, struct filename *name, umode_t mode,
402387c4e192SDominik Brodowski 		unsigned int dev)
40241da177e4SLinus Torvalds {
4025abf08576SChristian Brauner 	struct mnt_idmap *idmap;
40261da177e4SLinus Torvalds 	struct dentry *dentry;
4027dae6ad8fSAl Viro 	struct path path;
4028dae6ad8fSAl Viro 	int error;
4029972567f1SJeff Layton 	unsigned int lookup_flags = 0;
40301da177e4SLinus Torvalds 
40318e4bfca1SAl Viro 	error = may_mknod(mode);
40328e4bfca1SAl Viro 	if (error)
40337797251bSDmitry Kadashev 		goto out1;
4034972567f1SJeff Layton retry:
4035b4a4f213SStephen Brennan 	dentry = filename_create(dfd, name, &path, lookup_flags);
40367797251bSDmitry Kadashev 	error = PTR_ERR(dentry);
4037dae6ad8fSAl Viro 	if (IS_ERR(dentry))
40387797251bSDmitry Kadashev 		goto out1;
40392ad94ae6SAl Viro 
40401639a49cSYang Xu 	error = security_path_mknod(&path, dentry,
40411639a49cSYang Xu 			mode_strip_umask(path.dentry->d_inode, mode), dev);
4042be6d3e56SKentaro Takeda 	if (error)
40437797251bSDmitry Kadashev 		goto out2;
40446521f891SChristian Brauner 
4045abf08576SChristian Brauner 	idmap = mnt_idmap(path.mnt);
40461da177e4SLinus Torvalds 	switch (mode & S_IFMT) {
40471da177e4SLinus Torvalds 		case 0: case S_IFREG:
4048abf08576SChristian Brauner 			error = vfs_create(idmap, path.dentry->d_inode,
40496521f891SChristian Brauner 					   dentry, mode, true);
405005d1a717SMimi Zohar 			if (!error)
405139f60c1cSChristian Brauner 				ima_post_path_mknod(idmap, dentry);
40521da177e4SLinus Torvalds 			break;
40531da177e4SLinus Torvalds 		case S_IFCHR: case S_IFBLK:
4054abf08576SChristian Brauner 			error = vfs_mknod(idmap, path.dentry->d_inode,
40556521f891SChristian Brauner 					  dentry, mode, new_decode_dev(dev));
40561da177e4SLinus Torvalds 			break;
40571da177e4SLinus Torvalds 		case S_IFIFO: case S_IFSOCK:
4058abf08576SChristian Brauner 			error = vfs_mknod(idmap, path.dentry->d_inode,
40596521f891SChristian Brauner 					  dentry, mode, 0);
40601da177e4SLinus Torvalds 			break;
40611da177e4SLinus Torvalds 	}
40627797251bSDmitry Kadashev out2:
4063921a1650SAl Viro 	done_path_create(&path, dentry);
4064972567f1SJeff Layton 	if (retry_estale(error, lookup_flags)) {
4065972567f1SJeff Layton 		lookup_flags |= LOOKUP_REVAL;
4066972567f1SJeff Layton 		goto retry;
4067972567f1SJeff Layton 	}
40687797251bSDmitry Kadashev out1:
40697797251bSDmitry Kadashev 	putname(name);
40701da177e4SLinus Torvalds 	return error;
40711da177e4SLinus Torvalds }
40721da177e4SLinus Torvalds 
407387c4e192SDominik Brodowski SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, umode_t, mode,
407487c4e192SDominik Brodowski 		unsigned int, dev)
407587c4e192SDominik Brodowski {
40767797251bSDmitry Kadashev 	return do_mknodat(dfd, getname(filename), mode, dev);
407787c4e192SDominik Brodowski }
407887c4e192SDominik Brodowski 
40798208a22bSAl Viro SYSCALL_DEFINE3(mknod, const char __user *, filename, umode_t, mode, unsigned, dev)
40805590ff0dSUlrich Drepper {
40817797251bSDmitry Kadashev 	return do_mknodat(AT_FDCWD, getname(filename), mode, dev);
40825590ff0dSUlrich Drepper }
40835590ff0dSUlrich Drepper 
40846521f891SChristian Brauner /**
40856521f891SChristian Brauner  * vfs_mkdir - create directory
4086abf08576SChristian Brauner  * @idmap:	idmap of the mount the inode was found from
40876521f891SChristian Brauner  * @dir:	inode of @dentry
40886521f891SChristian Brauner  * @dentry:	pointer to dentry of the base directory
40896521f891SChristian Brauner  * @mode:	mode of the new directory
40906521f891SChristian Brauner  *
40916521f891SChristian Brauner  * Create a directory.
40926521f891SChristian Brauner  *
4093abf08576SChristian Brauner  * If the inode has been found through an idmapped mount the idmap of
4094abf08576SChristian Brauner  * the vfsmount must be passed through @idmap. This function will then take
4095abf08576SChristian Brauner  * care to map the inode according to @idmap before checking permissions.
40966521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
4097abf08576SChristian Brauner  * raw inode simply passs @nop_mnt_idmap.
40986521f891SChristian Brauner  */
4099abf08576SChristian Brauner int vfs_mkdir(struct mnt_idmap *idmap, struct inode *dir,
41006521f891SChristian Brauner 	      struct dentry *dentry, umode_t mode)
41011da177e4SLinus Torvalds {
4102abf08576SChristian Brauner 	int error;
41038de52778SAl Viro 	unsigned max_links = dir->i_sb->s_max_links;
41041da177e4SLinus Torvalds 
41054609e1f1SChristian Brauner 	error = may_create(idmap, dir, dentry);
41061da177e4SLinus Torvalds 	if (error)
41071da177e4SLinus Torvalds 		return error;
41081da177e4SLinus Torvalds 
4109acfa4380SAl Viro 	if (!dir->i_op->mkdir)
41101da177e4SLinus Torvalds 		return -EPERM;
41111da177e4SLinus Torvalds 
41129452e93eSChristian Brauner 	mode = vfs_prepare_mode(idmap, dir, mode, S_IRWXUGO | S_ISVTX, 0);
41131da177e4SLinus Torvalds 	error = security_inode_mkdir(dir, dentry, mode);
41141da177e4SLinus Torvalds 	if (error)
41151da177e4SLinus Torvalds 		return error;
41161da177e4SLinus Torvalds 
41178de52778SAl Viro 	if (max_links && dir->i_nlink >= max_links)
41188de52778SAl Viro 		return -EMLINK;
41198de52778SAl Viro 
4120c54bd91eSChristian Brauner 	error = dir->i_op->mkdir(idmap, dir, dentry, mode);
4121a74574aaSStephen Smalley 	if (!error)
4122f38aa942SAmy Griffis 		fsnotify_mkdir(dir, dentry);
41231da177e4SLinus Torvalds 	return error;
41241da177e4SLinus Torvalds }
41254d359507SAl Viro EXPORT_SYMBOL(vfs_mkdir);
41261da177e4SLinus Torvalds 
412745f30dabSDmitry Kadashev int do_mkdirat(int dfd, struct filename *name, umode_t mode)
41281da177e4SLinus Torvalds {
41296902d925SDave Hansen 	struct dentry *dentry;
4130dae6ad8fSAl Viro 	struct path path;
4131dae6ad8fSAl Viro 	int error;
4132b76d8b82SJeff Layton 	unsigned int lookup_flags = LOOKUP_DIRECTORY;
41331da177e4SLinus Torvalds 
4134b76d8b82SJeff Layton retry:
4135b4a4f213SStephen Brennan 	dentry = filename_create(dfd, name, &path, lookup_flags);
4136584d3226SDmitry Kadashev 	error = PTR_ERR(dentry);
41376902d925SDave Hansen 	if (IS_ERR(dentry))
4138584d3226SDmitry Kadashev 		goto out_putname;
41396902d925SDave Hansen 
41401639a49cSYang Xu 	error = security_path_mkdir(&path, dentry,
41411639a49cSYang Xu 			mode_strip_umask(path.dentry->d_inode, mode));
41426521f891SChristian Brauner 	if (!error) {
4143abf08576SChristian Brauner 		error = vfs_mkdir(mnt_idmap(path.mnt), path.dentry->d_inode,
4144abf08576SChristian Brauner 				  dentry, mode);
41456521f891SChristian Brauner 	}
4146921a1650SAl Viro 	done_path_create(&path, dentry);
4147b76d8b82SJeff Layton 	if (retry_estale(error, lookup_flags)) {
4148b76d8b82SJeff Layton 		lookup_flags |= LOOKUP_REVAL;
4149b76d8b82SJeff Layton 		goto retry;
4150b76d8b82SJeff Layton 	}
4151584d3226SDmitry Kadashev out_putname:
4152584d3226SDmitry Kadashev 	putname(name);
41531da177e4SLinus Torvalds 	return error;
41541da177e4SLinus Torvalds }
41551da177e4SLinus Torvalds 
41560101db7aSDominik Brodowski SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, umode_t, mode)
41570101db7aSDominik Brodowski {
4158584d3226SDmitry Kadashev 	return do_mkdirat(dfd, getname(pathname), mode);
41590101db7aSDominik Brodowski }
41600101db7aSDominik Brodowski 
4161a218d0fdSAl Viro SYSCALL_DEFINE2(mkdir, const char __user *, pathname, umode_t, mode)
41625590ff0dSUlrich Drepper {
4163584d3226SDmitry Kadashev 	return do_mkdirat(AT_FDCWD, getname(pathname), mode);
41645590ff0dSUlrich Drepper }
41655590ff0dSUlrich Drepper 
41666521f891SChristian Brauner /**
41676521f891SChristian Brauner  * vfs_rmdir - remove directory
4168abf08576SChristian Brauner  * @idmap:	idmap of the mount the inode was found from
41696521f891SChristian Brauner  * @dir:	inode of @dentry
41706521f891SChristian Brauner  * @dentry:	pointer to dentry of the base directory
41716521f891SChristian Brauner  *
41726521f891SChristian Brauner  * Remove a directory.
41736521f891SChristian Brauner  *
4174abf08576SChristian Brauner  * If the inode has been found through an idmapped mount the idmap of
4175abf08576SChristian Brauner  * the vfsmount must be passed through @idmap. This function will then take
4176abf08576SChristian Brauner  * care to map the inode according to @idmap before checking permissions.
41776521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
4178abf08576SChristian Brauner  * raw inode simply passs @nop_mnt_idmap.
41796521f891SChristian Brauner  */
4180abf08576SChristian Brauner int vfs_rmdir(struct mnt_idmap *idmap, struct inode *dir,
41816521f891SChristian Brauner 		     struct dentry *dentry)
41821da177e4SLinus Torvalds {
41834609e1f1SChristian Brauner 	int error = may_delete(idmap, dir, dentry, 1);
41841da177e4SLinus Torvalds 
41851da177e4SLinus Torvalds 	if (error)
41861da177e4SLinus Torvalds 		return error;
41871da177e4SLinus Torvalds 
4188acfa4380SAl Viro 	if (!dir->i_op->rmdir)
41891da177e4SLinus Torvalds 		return -EPERM;
41901da177e4SLinus Torvalds 
41911d2ef590SAl Viro 	dget(dentry);
41925955102cSAl Viro 	inode_lock(dentry->d_inode);
4193912dbc15SSage Weil 
41941da177e4SLinus Torvalds 	error = -EBUSY;
41951bd9c4e4SDavid Howells 	if (is_local_mountpoint(dentry) ||
41961bd9c4e4SDavid Howells 	    (dentry->d_inode->i_flags & S_KERNEL_FILE))
4197912dbc15SSage Weil 		goto out;
4198912dbc15SSage Weil 
41991da177e4SLinus Torvalds 	error = security_inode_rmdir(dir, dentry);
4200912dbc15SSage Weil 	if (error)
4201912dbc15SSage Weil 		goto out;
4202912dbc15SSage Weil 
42031da177e4SLinus Torvalds 	error = dir->i_op->rmdir(dir, dentry);
4204912dbc15SSage Weil 	if (error)
4205912dbc15SSage Weil 		goto out;
4206912dbc15SSage Weil 
42078767712fSAl Viro 	shrink_dcache_parent(dentry);
42081da177e4SLinus Torvalds 	dentry->d_inode->i_flags |= S_DEAD;
4209d83c49f3SAl Viro 	dont_mount(dentry);
42108ed936b5SEric W. Biederman 	detach_mounts(dentry);
42111da177e4SLinus Torvalds 
4212912dbc15SSage Weil out:
42135955102cSAl Viro 	inode_unlock(dentry->d_inode);
42141d2ef590SAl Viro 	dput(dentry);
4215912dbc15SSage Weil 	if (!error)
4216a37d9a17SAmir Goldstein 		d_delete_notify(dir, dentry);
42171da177e4SLinus Torvalds 	return error;
42181da177e4SLinus Torvalds }
42194d359507SAl Viro EXPORT_SYMBOL(vfs_rmdir);
42201da177e4SLinus Torvalds 
422145f30dabSDmitry Kadashev int do_rmdir(int dfd, struct filename *name)
42221da177e4SLinus Torvalds {
42230ee50b47SDmitry Kadashev 	int error;
42241da177e4SLinus Torvalds 	struct dentry *dentry;
4225f5beed75SAl Viro 	struct path path;
4226f5beed75SAl Viro 	struct qstr last;
4227f5beed75SAl Viro 	int type;
4228c6ee9206SJeff Layton 	unsigned int lookup_flags = 0;
4229c6ee9206SJeff Layton retry:
4230c5f563f9SAl Viro 	error = filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
42310ee50b47SDmitry Kadashev 	if (error)
42320ee50b47SDmitry Kadashev 		goto exit1;
42331da177e4SLinus Torvalds 
4234f5beed75SAl Viro 	switch (type) {
42351da177e4SLinus Torvalds 	case LAST_DOTDOT:
42361da177e4SLinus Torvalds 		error = -ENOTEMPTY;
42370ee50b47SDmitry Kadashev 		goto exit2;
42381da177e4SLinus Torvalds 	case LAST_DOT:
42391da177e4SLinus Torvalds 		error = -EINVAL;
42400ee50b47SDmitry Kadashev 		goto exit2;
42411da177e4SLinus Torvalds 	case LAST_ROOT:
42421da177e4SLinus Torvalds 		error = -EBUSY;
42430ee50b47SDmitry Kadashev 		goto exit2;
42441da177e4SLinus Torvalds 	}
42450612d9fbSOGAWA Hirofumi 
4246f5beed75SAl Viro 	error = mnt_want_write(path.mnt);
4247c30dabfeSJan Kara 	if (error)
42480ee50b47SDmitry Kadashev 		goto exit2;
42490612d9fbSOGAWA Hirofumi 
42505955102cSAl Viro 	inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
425174d7970fSNamjae Jeon 	dentry = lookup_one_qstr_excl(&last, path.dentry, lookup_flags);
42521da177e4SLinus Torvalds 	error = PTR_ERR(dentry);
42536902d925SDave Hansen 	if (IS_ERR(dentry))
42540ee50b47SDmitry Kadashev 		goto exit3;
4255e6bc45d6STheodore Ts'o 	if (!dentry->d_inode) {
4256e6bc45d6STheodore Ts'o 		error = -ENOENT;
42570ee50b47SDmitry Kadashev 		goto exit4;
4258e6bc45d6STheodore Ts'o 	}
4259f5beed75SAl Viro 	error = security_path_rmdir(&path, dentry);
4260be6d3e56SKentaro Takeda 	if (error)
42610ee50b47SDmitry Kadashev 		goto exit4;
4262abf08576SChristian Brauner 	error = vfs_rmdir(mnt_idmap(path.mnt), path.dentry->d_inode, dentry);
42630ee50b47SDmitry Kadashev exit4:
42641da177e4SLinus Torvalds 	dput(dentry);
42650ee50b47SDmitry Kadashev exit3:
42665955102cSAl Viro 	inode_unlock(path.dentry->d_inode);
4267f5beed75SAl Viro 	mnt_drop_write(path.mnt);
42680ee50b47SDmitry Kadashev exit2:
4269f5beed75SAl Viro 	path_put(&path);
4270c6ee9206SJeff Layton 	if (retry_estale(error, lookup_flags)) {
4271c6ee9206SJeff Layton 		lookup_flags |= LOOKUP_REVAL;
4272c6ee9206SJeff Layton 		goto retry;
4273c6ee9206SJeff Layton 	}
42740ee50b47SDmitry Kadashev exit1:
427524fb33d4SAl Viro 	putname(name);
42761da177e4SLinus Torvalds 	return error;
42771da177e4SLinus Torvalds }
42781da177e4SLinus Torvalds 
42793cdad428SHeiko Carstens SYSCALL_DEFINE1(rmdir, const char __user *, pathname)
42805590ff0dSUlrich Drepper {
4281e24ab0efSChristoph Hellwig 	return do_rmdir(AT_FDCWD, getname(pathname));
42825590ff0dSUlrich Drepper }
42835590ff0dSUlrich Drepper 
4284b21996e3SJ. Bruce Fields /**
4285b21996e3SJ. Bruce Fields  * vfs_unlink - unlink a filesystem object
4286abf08576SChristian Brauner  * @idmap:	idmap of the mount the inode was found from
4287b21996e3SJ. Bruce Fields  * @dir:	parent directory
4288b21996e3SJ. Bruce Fields  * @dentry:	victim
4289b21996e3SJ. Bruce Fields  * @delegated_inode: returns victim inode, if the inode is delegated.
4290b21996e3SJ. Bruce Fields  *
4291b21996e3SJ. Bruce Fields  * The caller must hold dir->i_mutex.
4292b21996e3SJ. Bruce Fields  *
4293b21996e3SJ. Bruce Fields  * If vfs_unlink discovers a delegation, it will return -EWOULDBLOCK and
4294b21996e3SJ. Bruce Fields  * return a reference to the inode in delegated_inode.  The caller
4295b21996e3SJ. Bruce Fields  * should then break the delegation on that inode and retry.  Because
4296b21996e3SJ. Bruce Fields  * breaking a delegation may take a long time, the caller should drop
4297b21996e3SJ. Bruce Fields  * dir->i_mutex before doing so.
4298b21996e3SJ. Bruce Fields  *
4299b21996e3SJ. Bruce Fields  * Alternatively, a caller may pass NULL for delegated_inode.  This may
4300b21996e3SJ. Bruce Fields  * be appropriate for callers that expect the underlying filesystem not
4301b21996e3SJ. Bruce Fields  * to be NFS exported.
43026521f891SChristian Brauner  *
4303abf08576SChristian Brauner  * If the inode has been found through an idmapped mount the idmap of
4304abf08576SChristian Brauner  * the vfsmount must be passed through @idmap. This function will then take
4305abf08576SChristian Brauner  * care to map the inode according to @idmap before checking permissions.
43066521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
4307abf08576SChristian Brauner  * raw inode simply passs @nop_mnt_idmap.
4308b21996e3SJ. Bruce Fields  */
4309abf08576SChristian Brauner int vfs_unlink(struct mnt_idmap *idmap, struct inode *dir,
43106521f891SChristian Brauner 	       struct dentry *dentry, struct inode **delegated_inode)
43111da177e4SLinus Torvalds {
43129accbb97SJ. Bruce Fields 	struct inode *target = dentry->d_inode;
43134609e1f1SChristian Brauner 	int error = may_delete(idmap, dir, dentry, 0);
43141da177e4SLinus Torvalds 
43151da177e4SLinus Torvalds 	if (error)
43161da177e4SLinus Torvalds 		return error;
43171da177e4SLinus Torvalds 
4318acfa4380SAl Viro 	if (!dir->i_op->unlink)
43191da177e4SLinus Torvalds 		return -EPERM;
43201da177e4SLinus Torvalds 
43215955102cSAl Viro 	inode_lock(target);
432251cc3a66SHugh Dickins 	if (IS_SWAPFILE(target))
432351cc3a66SHugh Dickins 		error = -EPERM;
432451cc3a66SHugh Dickins 	else if (is_local_mountpoint(dentry))
43251da177e4SLinus Torvalds 		error = -EBUSY;
43261da177e4SLinus Torvalds 	else {
43271da177e4SLinus Torvalds 		error = security_inode_unlink(dir, dentry);
4328bec1052eSAl Viro 		if (!error) {
43295a14696cSJ. Bruce Fields 			error = try_break_deleg(target, delegated_inode);
43305a14696cSJ. Bruce Fields 			if (error)
4331b21996e3SJ. Bruce Fields 				goto out;
43321da177e4SLinus Torvalds 			error = dir->i_op->unlink(dir, dentry);
43338ed936b5SEric W. Biederman 			if (!error) {
4334d83c49f3SAl Viro 				dont_mount(dentry);
43358ed936b5SEric W. Biederman 				detach_mounts(dentry);
43368ed936b5SEric W. Biederman 			}
4337bec1052eSAl Viro 		}
43381da177e4SLinus Torvalds 	}
4339b21996e3SJ. Bruce Fields out:
43405955102cSAl Viro 	inode_unlock(target);
43411da177e4SLinus Torvalds 
43421da177e4SLinus Torvalds 	/* We don't d_delete() NFS sillyrenamed files--they still exist. */
4343a37d9a17SAmir Goldstein 	if (!error && dentry->d_flags & DCACHE_NFSFS_RENAMED) {
4344a37d9a17SAmir Goldstein 		fsnotify_unlink(dir, dentry);
4345a37d9a17SAmir Goldstein 	} else if (!error) {
43469accbb97SJ. Bruce Fields 		fsnotify_link_count(target);
4347a37d9a17SAmir Goldstein 		d_delete_notify(dir, dentry);
43481da177e4SLinus Torvalds 	}
43490eeca283SRobert Love 
43501da177e4SLinus Torvalds 	return error;
43511da177e4SLinus Torvalds }
43524d359507SAl Viro EXPORT_SYMBOL(vfs_unlink);
43531da177e4SLinus Torvalds 
43541da177e4SLinus Torvalds /*
43551da177e4SLinus Torvalds  * Make sure that the actual truncation of the file will occur outside its
43561b1dcc1bSJes Sorensen  * directory's i_mutex.  Truncate can take a long time if there is a lot of
43571da177e4SLinus Torvalds  * writeout happening, and we don't want to prevent access to the directory
43581da177e4SLinus Torvalds  * while waiting on the I/O.
43591da177e4SLinus Torvalds  */
436045f30dabSDmitry Kadashev int do_unlinkat(int dfd, struct filename *name)
43611da177e4SLinus Torvalds {
43622ad94ae6SAl Viro 	int error;
43631da177e4SLinus Torvalds 	struct dentry *dentry;
4364f5beed75SAl Viro 	struct path path;
4365f5beed75SAl Viro 	struct qstr last;
4366f5beed75SAl Viro 	int type;
43671da177e4SLinus Torvalds 	struct inode *inode = NULL;
4368b21996e3SJ. Bruce Fields 	struct inode *delegated_inode = NULL;
43695d18f813SJeff Layton 	unsigned int lookup_flags = 0;
43705d18f813SJeff Layton retry:
4371c5f563f9SAl Viro 	error = filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
43720ee50b47SDmitry Kadashev 	if (error)
43730ee50b47SDmitry Kadashev 		goto exit1;
43742ad94ae6SAl Viro 
43751da177e4SLinus Torvalds 	error = -EISDIR;
4376f5beed75SAl Viro 	if (type != LAST_NORM)
43770ee50b47SDmitry Kadashev 		goto exit2;
43780612d9fbSOGAWA Hirofumi 
4379f5beed75SAl Viro 	error = mnt_want_write(path.mnt);
4380c30dabfeSJan Kara 	if (error)
43810ee50b47SDmitry Kadashev 		goto exit2;
4382b21996e3SJ. Bruce Fields retry_deleg:
43835955102cSAl Viro 	inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
438474d7970fSNamjae Jeon 	dentry = lookup_one_qstr_excl(&last, path.dentry, lookup_flags);
43851da177e4SLinus Torvalds 	error = PTR_ERR(dentry);
43861da177e4SLinus Torvalds 	if (!IS_ERR(dentry)) {
43876521f891SChristian Brauner 
43881da177e4SLinus Torvalds 		/* Why not before? Because we want correct error value */
4389f5beed75SAl Viro 		if (last.name[last.len])
439050338b88STörök Edwin 			goto slashes;
43911da177e4SLinus Torvalds 		inode = dentry->d_inode;
4392b18825a7SDavid Howells 		if (d_is_negative(dentry))
4393e6bc45d6STheodore Ts'o 			goto slashes;
43947de9c6eeSAl Viro 		ihold(inode);
4395f5beed75SAl Viro 		error = security_path_unlink(&path, dentry);
4396be6d3e56SKentaro Takeda 		if (error)
43970ee50b47SDmitry Kadashev 			goto exit3;
4398abf08576SChristian Brauner 		error = vfs_unlink(mnt_idmap(path.mnt), path.dentry->d_inode,
4399abf08576SChristian Brauner 				   dentry, &delegated_inode);
44000ee50b47SDmitry Kadashev exit3:
44011da177e4SLinus Torvalds 		dput(dentry);
44021da177e4SLinus Torvalds 	}
44035955102cSAl Viro 	inode_unlock(path.dentry->d_inode);
44041da177e4SLinus Torvalds 	if (inode)
44051da177e4SLinus Torvalds 		iput(inode);	/* truncate the inode here */
4406b21996e3SJ. Bruce Fields 	inode = NULL;
4407b21996e3SJ. Bruce Fields 	if (delegated_inode) {
44085a14696cSJ. Bruce Fields 		error = break_deleg_wait(&delegated_inode);
4409b21996e3SJ. Bruce Fields 		if (!error)
4410b21996e3SJ. Bruce Fields 			goto retry_deleg;
4411b21996e3SJ. Bruce Fields 	}
4412f5beed75SAl Viro 	mnt_drop_write(path.mnt);
44130ee50b47SDmitry Kadashev exit2:
4414f5beed75SAl Viro 	path_put(&path);
44155d18f813SJeff Layton 	if (retry_estale(error, lookup_flags)) {
44165d18f813SJeff Layton 		lookup_flags |= LOOKUP_REVAL;
44175d18f813SJeff Layton 		inode = NULL;
44185d18f813SJeff Layton 		goto retry;
44195d18f813SJeff Layton 	}
44200ee50b47SDmitry Kadashev exit1:
4421da2f1362SChristoph Hellwig 	putname(name);
44221da177e4SLinus Torvalds 	return error;
44231da177e4SLinus Torvalds 
44241da177e4SLinus Torvalds slashes:
4425b18825a7SDavid Howells 	if (d_is_negative(dentry))
4426b18825a7SDavid Howells 		error = -ENOENT;
442744b1d530SMiklos Szeredi 	else if (d_is_dir(dentry))
4428b18825a7SDavid Howells 		error = -EISDIR;
4429b18825a7SDavid Howells 	else
4430b18825a7SDavid Howells 		error = -ENOTDIR;
44310ee50b47SDmitry Kadashev 	goto exit3;
44321da177e4SLinus Torvalds }
44331da177e4SLinus Torvalds 
44342e4d0924SHeiko Carstens SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag)
44355590ff0dSUlrich Drepper {
44365590ff0dSUlrich Drepper 	if ((flag & ~AT_REMOVEDIR) != 0)
44375590ff0dSUlrich Drepper 		return -EINVAL;
44385590ff0dSUlrich Drepper 
44395590ff0dSUlrich Drepper 	if (flag & AT_REMOVEDIR)
4440e24ab0efSChristoph Hellwig 		return do_rmdir(dfd, getname(pathname));
4441da2f1362SChristoph Hellwig 	return do_unlinkat(dfd, getname(pathname));
44425590ff0dSUlrich Drepper }
44435590ff0dSUlrich Drepper 
44443480b257SHeiko Carstens SYSCALL_DEFINE1(unlink, const char __user *, pathname)
44455590ff0dSUlrich Drepper {
4446da2f1362SChristoph Hellwig 	return do_unlinkat(AT_FDCWD, getname(pathname));
44475590ff0dSUlrich Drepper }
44485590ff0dSUlrich Drepper 
44496521f891SChristian Brauner /**
44506521f891SChristian Brauner  * vfs_symlink - create symlink
4451abf08576SChristian Brauner  * @idmap:	idmap of the mount the inode was found from
44526521f891SChristian Brauner  * @dir:	inode of @dentry
44536521f891SChristian Brauner  * @dentry:	pointer to dentry of the base directory
44546521f891SChristian Brauner  * @oldname:	name of the file to link to
44556521f891SChristian Brauner  *
44566521f891SChristian Brauner  * Create a symlink.
44576521f891SChristian Brauner  *
4458abf08576SChristian Brauner  * If the inode has been found through an idmapped mount the idmap of
4459abf08576SChristian Brauner  * the vfsmount must be passed through @idmap. This function will then take
4460abf08576SChristian Brauner  * care to map the inode according to @idmap before checking permissions.
44616521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
4462abf08576SChristian Brauner  * raw inode simply passs @nop_mnt_idmap.
44636521f891SChristian Brauner  */
4464abf08576SChristian Brauner int vfs_symlink(struct mnt_idmap *idmap, struct inode *dir,
44656521f891SChristian Brauner 		struct dentry *dentry, const char *oldname)
44661da177e4SLinus Torvalds {
44677a77db95SChristian Brauner 	int error;
44681da177e4SLinus Torvalds 
44694609e1f1SChristian Brauner 	error = may_create(idmap, dir, dentry);
44701da177e4SLinus Torvalds 	if (error)
44711da177e4SLinus Torvalds 		return error;
44721da177e4SLinus Torvalds 
4473acfa4380SAl Viro 	if (!dir->i_op->symlink)
44741da177e4SLinus Torvalds 		return -EPERM;
44751da177e4SLinus Torvalds 
44761da177e4SLinus Torvalds 	error = security_inode_symlink(dir, dentry, oldname);
44771da177e4SLinus Torvalds 	if (error)
44781da177e4SLinus Torvalds 		return error;
44791da177e4SLinus Torvalds 
44807a77db95SChristian Brauner 	error = dir->i_op->symlink(idmap, dir, dentry, oldname);
4481a74574aaSStephen Smalley 	if (!error)
4482f38aa942SAmy Griffis 		fsnotify_create(dir, dentry);
44831da177e4SLinus Torvalds 	return error;
44841da177e4SLinus Torvalds }
44854d359507SAl Viro EXPORT_SYMBOL(vfs_symlink);
44861da177e4SLinus Torvalds 
44877a8721f8SDmitry Kadashev int do_symlinkat(struct filename *from, int newdfd, struct filename *to)
44881da177e4SLinus Torvalds {
44892ad94ae6SAl Viro 	int error;
44906902d925SDave Hansen 	struct dentry *dentry;
4491dae6ad8fSAl Viro 	struct path path;
4492f46d3567SJeff Layton 	unsigned int lookup_flags = 0;
44931da177e4SLinus Torvalds 
4494da2d0cedSDmitry Kadashev 	if (IS_ERR(from)) {
4495da2d0cedSDmitry Kadashev 		error = PTR_ERR(from);
4496da2d0cedSDmitry Kadashev 		goto out_putnames;
4497da2d0cedSDmitry Kadashev 	}
4498f46d3567SJeff Layton retry:
4499b4a4f213SStephen Brennan 	dentry = filename_create(newdfd, to, &path, lookup_flags);
45001da177e4SLinus Torvalds 	error = PTR_ERR(dentry);
45016902d925SDave Hansen 	if (IS_ERR(dentry))
4502da2d0cedSDmitry Kadashev 		goto out_putnames;
45036902d925SDave Hansen 
450491a27b2aSJeff Layton 	error = security_path_symlink(&path, dentry, from->name);
4505abf08576SChristian Brauner 	if (!error)
4506abf08576SChristian Brauner 		error = vfs_symlink(mnt_idmap(path.mnt), path.dentry->d_inode,
4507abf08576SChristian Brauner 				    dentry, from->name);
4508921a1650SAl Viro 	done_path_create(&path, dentry);
4509f46d3567SJeff Layton 	if (retry_estale(error, lookup_flags)) {
4510f46d3567SJeff Layton 		lookup_flags |= LOOKUP_REVAL;
4511f46d3567SJeff Layton 		goto retry;
4512f46d3567SJeff Layton 	}
4513da2d0cedSDmitry Kadashev out_putnames:
4514da2d0cedSDmitry Kadashev 	putname(to);
45151da177e4SLinus Torvalds 	putname(from);
45161da177e4SLinus Torvalds 	return error;
45171da177e4SLinus Torvalds }
45181da177e4SLinus Torvalds 
4519b724e846SDominik Brodowski SYSCALL_DEFINE3(symlinkat, const char __user *, oldname,
4520b724e846SDominik Brodowski 		int, newdfd, const char __user *, newname)
4521b724e846SDominik Brodowski {
4522da2d0cedSDmitry Kadashev 	return do_symlinkat(getname(oldname), newdfd, getname(newname));
4523b724e846SDominik Brodowski }
4524b724e846SDominik Brodowski 
45253480b257SHeiko Carstens SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname)
45265590ff0dSUlrich Drepper {
4527da2d0cedSDmitry Kadashev 	return do_symlinkat(getname(oldname), AT_FDCWD, getname(newname));
45285590ff0dSUlrich Drepper }
45295590ff0dSUlrich Drepper 
4530146a8595SJ. Bruce Fields /**
4531146a8595SJ. Bruce Fields  * vfs_link - create a new link
4532146a8595SJ. Bruce Fields  * @old_dentry:	object to be linked
4533abf08576SChristian Brauner  * @idmap:	idmap of the mount
4534146a8595SJ. Bruce Fields  * @dir:	new parent
4535146a8595SJ. Bruce Fields  * @new_dentry:	where to create the new link
4536146a8595SJ. Bruce Fields  * @delegated_inode: returns inode needing a delegation break
4537146a8595SJ. Bruce Fields  *
4538146a8595SJ. Bruce Fields  * The caller must hold dir->i_mutex
4539146a8595SJ. Bruce Fields  *
4540146a8595SJ. Bruce Fields  * If vfs_link discovers a delegation on the to-be-linked file in need
4541146a8595SJ. Bruce Fields  * of breaking, it will return -EWOULDBLOCK and return a reference to the
4542146a8595SJ. Bruce Fields  * inode in delegated_inode.  The caller should then break the delegation
4543146a8595SJ. Bruce Fields  * and retry.  Because breaking a delegation may take a long time, the
4544146a8595SJ. Bruce Fields  * caller should drop the i_mutex before doing so.
4545146a8595SJ. Bruce Fields  *
4546146a8595SJ. Bruce Fields  * Alternatively, a caller may pass NULL for delegated_inode.  This may
4547146a8595SJ. Bruce Fields  * be appropriate for callers that expect the underlying filesystem not
4548146a8595SJ. Bruce Fields  * to be NFS exported.
45496521f891SChristian Brauner  *
4550abf08576SChristian Brauner  * If the inode has been found through an idmapped mount the idmap of
4551abf08576SChristian Brauner  * the vfsmount must be passed through @idmap. This function will then take
4552abf08576SChristian Brauner  * care to map the inode according to @idmap before checking permissions.
45536521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
4554abf08576SChristian Brauner  * raw inode simply passs @nop_mnt_idmap.
4555146a8595SJ. Bruce Fields  */
4556abf08576SChristian Brauner int vfs_link(struct dentry *old_dentry, struct mnt_idmap *idmap,
45576521f891SChristian Brauner 	     struct inode *dir, struct dentry *new_dentry,
45586521f891SChristian Brauner 	     struct inode **delegated_inode)
45591da177e4SLinus Torvalds {
45601da177e4SLinus Torvalds 	struct inode *inode = old_dentry->d_inode;
45618de52778SAl Viro 	unsigned max_links = dir->i_sb->s_max_links;
45621da177e4SLinus Torvalds 	int error;
45631da177e4SLinus Torvalds 
45641da177e4SLinus Torvalds 	if (!inode)
45651da177e4SLinus Torvalds 		return -ENOENT;
45661da177e4SLinus Torvalds 
45674609e1f1SChristian Brauner 	error = may_create(idmap, dir, new_dentry);
45681da177e4SLinus Torvalds 	if (error)
45691da177e4SLinus Torvalds 		return error;
45701da177e4SLinus Torvalds 
45711da177e4SLinus Torvalds 	if (dir->i_sb != inode->i_sb)
45721da177e4SLinus Torvalds 		return -EXDEV;
45731da177e4SLinus Torvalds 
45741da177e4SLinus Torvalds 	/*
45751da177e4SLinus Torvalds 	 * A link to an append-only or immutable file cannot be created.
45761da177e4SLinus Torvalds 	 */
45771da177e4SLinus Torvalds 	if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
45781da177e4SLinus Torvalds 		return -EPERM;
45790bd23d09SEric W. Biederman 	/*
45800bd23d09SEric W. Biederman 	 * Updating the link count will likely cause i_uid and i_gid to
45810bd23d09SEric W. Biederman 	 * be writen back improperly if their true value is unknown to
45820bd23d09SEric W. Biederman 	 * the vfs.
45830bd23d09SEric W. Biederman 	 */
45844609e1f1SChristian Brauner 	if (HAS_UNMAPPED_ID(idmap, inode))
45850bd23d09SEric W. Biederman 		return -EPERM;
4586acfa4380SAl Viro 	if (!dir->i_op->link)
45871da177e4SLinus Torvalds 		return -EPERM;
45887e79eedbSTetsuo Handa 	if (S_ISDIR(inode->i_mode))
45891da177e4SLinus Torvalds 		return -EPERM;
45901da177e4SLinus Torvalds 
45911da177e4SLinus Torvalds 	error = security_inode_link(old_dentry, dir, new_dentry);
45921da177e4SLinus Torvalds 	if (error)
45931da177e4SLinus Torvalds 		return error;
45941da177e4SLinus Torvalds 
45955955102cSAl Viro 	inode_lock(inode);
4596aae8a97dSAneesh Kumar K.V 	/* Make sure we don't allow creating hardlink to an unlinked file */
4597f4e0c30cSAl Viro 	if (inode->i_nlink == 0 && !(inode->i_state & I_LINKABLE))
4598aae8a97dSAneesh Kumar K.V 		error =  -ENOENT;
45998de52778SAl Viro 	else if (max_links && inode->i_nlink >= max_links)
46008de52778SAl Viro 		error = -EMLINK;
4601146a8595SJ. Bruce Fields 	else {
4602146a8595SJ. Bruce Fields 		error = try_break_deleg(inode, delegated_inode);
4603146a8595SJ. Bruce Fields 		if (!error)
46041da177e4SLinus Torvalds 			error = dir->i_op->link(old_dentry, dir, new_dentry);
4605146a8595SJ. Bruce Fields 	}
4606f4e0c30cSAl Viro 
4607f4e0c30cSAl Viro 	if (!error && (inode->i_state & I_LINKABLE)) {
4608f4e0c30cSAl Viro 		spin_lock(&inode->i_lock);
4609f4e0c30cSAl Viro 		inode->i_state &= ~I_LINKABLE;
4610f4e0c30cSAl Viro 		spin_unlock(&inode->i_lock);
4611f4e0c30cSAl Viro 	}
46125955102cSAl Viro 	inode_unlock(inode);
4613e31e14ecSStephen Smalley 	if (!error)
46147e79eedbSTetsuo Handa 		fsnotify_link(dir, inode, new_dentry);
46151da177e4SLinus Torvalds 	return error;
46161da177e4SLinus Torvalds }
46174d359507SAl Viro EXPORT_SYMBOL(vfs_link);
46181da177e4SLinus Torvalds 
46191da177e4SLinus Torvalds /*
46201da177e4SLinus Torvalds  * Hardlinks are often used in delicate situations.  We avoid
46211da177e4SLinus Torvalds  * security-related surprises by not following symlinks on the
46221da177e4SLinus Torvalds  * newname.  --KAB
46231da177e4SLinus Torvalds  *
46241da177e4SLinus Torvalds  * We don't follow them on the oldname either to be compatible
46251da177e4SLinus Torvalds  * with linux 2.0, and to avoid hard-linking to directories
46261da177e4SLinus Torvalds  * and other special files.  --ADM
46271da177e4SLinus Torvalds  */
4628cf30da90SDmitry Kadashev int do_linkat(int olddfd, struct filename *old, int newdfd,
4629020250f3SDmitry Kadashev 	      struct filename *new, int flags)
46301da177e4SLinus Torvalds {
4631abf08576SChristian Brauner 	struct mnt_idmap *idmap;
46321da177e4SLinus Torvalds 	struct dentry *new_dentry;
4633dae6ad8fSAl Viro 	struct path old_path, new_path;
4634146a8595SJ. Bruce Fields 	struct inode *delegated_inode = NULL;
463511a7b371SAneesh Kumar K.V 	int how = 0;
46361da177e4SLinus Torvalds 	int error;
46371da177e4SLinus Torvalds 
4638020250f3SDmitry Kadashev 	if ((flags & ~(AT_SYMLINK_FOLLOW | AT_EMPTY_PATH)) != 0) {
4639020250f3SDmitry Kadashev 		error = -EINVAL;
4640020250f3SDmitry Kadashev 		goto out_putnames;
4641020250f3SDmitry Kadashev 	}
464211a7b371SAneesh Kumar K.V 	/*
4643f0cc6ffbSLinus Torvalds 	 * To use null names we require CAP_DAC_READ_SEARCH
4644f0cc6ffbSLinus Torvalds 	 * This ensures that not everyone will be able to create
4645f0cc6ffbSLinus Torvalds 	 * handlink using the passed filedescriptor.
464611a7b371SAneesh Kumar K.V 	 */
4647020250f3SDmitry Kadashev 	if (flags & AT_EMPTY_PATH && !capable(CAP_DAC_READ_SEARCH)) {
4648020250f3SDmitry Kadashev 		error = -ENOENT;
4649020250f3SDmitry Kadashev 		goto out_putnames;
4650f0cc6ffbSLinus Torvalds 	}
4651c04030e1SUlrich Drepper 
465211a7b371SAneesh Kumar K.V 	if (flags & AT_SYMLINK_FOLLOW)
465311a7b371SAneesh Kumar K.V 		how |= LOOKUP_FOLLOW;
4654442e31caSJeff Layton retry:
4655794ebceaSStephen Brennan 	error = filename_lookup(olddfd, old, how, &old_path, NULL);
46561da177e4SLinus Torvalds 	if (error)
4657020250f3SDmitry Kadashev 		goto out_putnames;
46582ad94ae6SAl Viro 
4659b4a4f213SStephen Brennan 	new_dentry = filename_create(newdfd, new, &new_path,
4660442e31caSJeff Layton 					(how & LOOKUP_REVAL));
46611da177e4SLinus Torvalds 	error = PTR_ERR(new_dentry);
46626902d925SDave Hansen 	if (IS_ERR(new_dentry))
4663020250f3SDmitry Kadashev 		goto out_putpath;
4664dae6ad8fSAl Viro 
4665dae6ad8fSAl Viro 	error = -EXDEV;
4666dae6ad8fSAl Viro 	if (old_path.mnt != new_path.mnt)
4667dae6ad8fSAl Viro 		goto out_dput;
4668abf08576SChristian Brauner 	idmap = mnt_idmap(new_path.mnt);
46694609e1f1SChristian Brauner 	error = may_linkat(idmap, &old_path);
4670800179c9SKees Cook 	if (unlikely(error))
4671800179c9SKees Cook 		goto out_dput;
4672dae6ad8fSAl Viro 	error = security_path_link(old_path.dentry, &new_path, new_dentry);
4673be6d3e56SKentaro Takeda 	if (error)
4674a8104a9fSAl Viro 		goto out_dput;
4675abf08576SChristian Brauner 	error = vfs_link(old_path.dentry, idmap, new_path.dentry->d_inode,
46766521f891SChristian Brauner 			 new_dentry, &delegated_inode);
467775c3f29dSDave Hansen out_dput:
4678921a1650SAl Viro 	done_path_create(&new_path, new_dentry);
4679146a8595SJ. Bruce Fields 	if (delegated_inode) {
4680146a8595SJ. Bruce Fields 		error = break_deleg_wait(&delegated_inode);
4681d22e6338SOleg Drokin 		if (!error) {
4682d22e6338SOleg Drokin 			path_put(&old_path);
4683146a8595SJ. Bruce Fields 			goto retry;
4684146a8595SJ. Bruce Fields 		}
4685d22e6338SOleg Drokin 	}
4686442e31caSJeff Layton 	if (retry_estale(error, how)) {
4687d22e6338SOleg Drokin 		path_put(&old_path);
4688442e31caSJeff Layton 		how |= LOOKUP_REVAL;
4689442e31caSJeff Layton 		goto retry;
4690442e31caSJeff Layton 	}
4691020250f3SDmitry Kadashev out_putpath:
46922d8f3038SAl Viro 	path_put(&old_path);
4693020250f3SDmitry Kadashev out_putnames:
4694020250f3SDmitry Kadashev 	putname(old);
4695020250f3SDmitry Kadashev 	putname(new);
46961da177e4SLinus Torvalds 
46971da177e4SLinus Torvalds 	return error;
46981da177e4SLinus Torvalds }
46991da177e4SLinus Torvalds 
470046ea89ebSDominik Brodowski SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname,
470146ea89ebSDominik Brodowski 		int, newdfd, const char __user *, newname, int, flags)
470246ea89ebSDominik Brodowski {
4703020250f3SDmitry Kadashev 	return do_linkat(olddfd, getname_uflags(oldname, flags),
4704020250f3SDmitry Kadashev 		newdfd, getname(newname), flags);
470546ea89ebSDominik Brodowski }
470646ea89ebSDominik Brodowski 
47073480b257SHeiko Carstens SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname)
47085590ff0dSUlrich Drepper {
4709020250f3SDmitry Kadashev 	return do_linkat(AT_FDCWD, getname(oldname), AT_FDCWD, getname(newname), 0);
47105590ff0dSUlrich Drepper }
47115590ff0dSUlrich Drepper 
4712bc27027aSMiklos Szeredi /**
4713bc27027aSMiklos Szeredi  * vfs_rename - rename a filesystem object
47142111c3c0SRandy Dunlap  * @rd:		pointer to &struct renamedata info
4715bc27027aSMiklos Szeredi  *
4716bc27027aSMiklos Szeredi  * The caller must hold multiple mutexes--see lock_rename()).
4717bc27027aSMiklos Szeredi  *
4718bc27027aSMiklos Szeredi  * If vfs_rename discovers a delegation in need of breaking at either
4719bc27027aSMiklos Szeredi  * the source or destination, it will return -EWOULDBLOCK and return a
4720bc27027aSMiklos Szeredi  * reference to the inode in delegated_inode.  The caller should then
4721bc27027aSMiklos Szeredi  * break the delegation and retry.  Because breaking a delegation may
4722bc27027aSMiklos Szeredi  * take a long time, the caller should drop all locks before doing
4723bc27027aSMiklos Szeredi  * so.
4724bc27027aSMiklos Szeredi  *
4725bc27027aSMiklos Szeredi  * Alternatively, a caller may pass NULL for delegated_inode.  This may
4726bc27027aSMiklos Szeredi  * be appropriate for callers that expect the underlying filesystem not
4727bc27027aSMiklos Szeredi  * to be NFS exported.
4728bc27027aSMiklos Szeredi  *
47291da177e4SLinus Torvalds  * The worst of all namespace operations - renaming directory. "Perverted"
47301da177e4SLinus Torvalds  * doesn't even start to describe it. Somebody in UCB had a heck of a trip...
47311da177e4SLinus Torvalds  * Problems:
47320117d427SMauro Carvalho Chehab  *
4733d03b29a2SJ. Bruce Fields  *	a) we can get into loop creation.
47341da177e4SLinus Torvalds  *	b) race potential - two innocent renames can create a loop together.
47351da177e4SLinus Torvalds  *	   That's where 4.4 screws up. Current fix: serialization on
4736a11f3a05SArjan van de Ven  *	   sb->s_vfs_rename_mutex. We might be more accurate, but that's another
47371da177e4SLinus Torvalds  *	   story.
47386cedba89SJ. Bruce Fields  *	c) we have to lock _four_ objects - parents and victim (if it exists),
473928eceedaSJan Kara  *	   and source.
47401b1dcc1bSJes Sorensen  *	   And that - after we got ->i_mutex on parents (until then we don't know
47411da177e4SLinus Torvalds  *	   whether the target exists).  Solution: try to be smart with locking
47421da177e4SLinus Torvalds  *	   order for inodes.  We rely on the fact that tree topology may change
4743a11f3a05SArjan van de Ven  *	   only under ->s_vfs_rename_mutex _and_ that parent of the object we
47441da177e4SLinus Torvalds  *	   move will be locked.  Thus we can rank directories by the tree
47451da177e4SLinus Torvalds  *	   (ancestors first) and rank all non-directories after them.
47461da177e4SLinus Torvalds  *	   That works since everybody except rename does "lock parent, lookup,
4747a11f3a05SArjan van de Ven  *	   lock child" and rename is under ->s_vfs_rename_mutex.
47481da177e4SLinus Torvalds  *	   HOWEVER, it relies on the assumption that any object with ->lookup()
47491da177e4SLinus Torvalds  *	   has no more than 1 dentry.  If "hybrid" objects will ever appear,
47501da177e4SLinus Torvalds  *	   we'd better make sure that there's no link(2) for them.
4751e4eaac06SSage Weil  *	d) conversion from fhandle to dentry may come in the wrong moment - when
47521b1dcc1bSJes Sorensen  *	   we are removing the target. Solution: we will have to grab ->i_mutex
47531da177e4SLinus Torvalds  *	   in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on
4754c41b20e7SAdam Buchbinder  *	   ->i_mutex on parents, which works but leads to some truly excessive
47551da177e4SLinus Torvalds  *	   locking].
47561da177e4SLinus Torvalds  */
47579fe61450SChristian Brauner int vfs_rename(struct renamedata *rd)
47581da177e4SLinus Torvalds {
47591da177e4SLinus Torvalds 	int error;
47609fe61450SChristian Brauner 	struct inode *old_dir = rd->old_dir, *new_dir = rd->new_dir;
47619fe61450SChristian Brauner 	struct dentry *old_dentry = rd->old_dentry;
47629fe61450SChristian Brauner 	struct dentry *new_dentry = rd->new_dentry;
47639fe61450SChristian Brauner 	struct inode **delegated_inode = rd->delegated_inode;
47649fe61450SChristian Brauner 	unsigned int flags = rd->flags;
4765bc27027aSMiklos Szeredi 	bool is_dir = d_is_dir(old_dentry);
4766bc27027aSMiklos Szeredi 	struct inode *source = old_dentry->d_inode;
4767bc27027aSMiklos Szeredi 	struct inode *target = new_dentry->d_inode;
4768da1ce067SMiklos Szeredi 	bool new_is_dir = false;
4769da1ce067SMiklos Szeredi 	unsigned max_links = new_dir->i_sb->s_max_links;
477049d31c2fSAl Viro 	struct name_snapshot old_name;
47711da177e4SLinus Torvalds 
47728d3e2936SMiklos Szeredi 	if (source == target)
47731da177e4SLinus Torvalds 		return 0;
47741da177e4SLinus Torvalds 
47754609e1f1SChristian Brauner 	error = may_delete(rd->old_mnt_idmap, old_dir, old_dentry, is_dir);
47761da177e4SLinus Torvalds 	if (error)
47771da177e4SLinus Torvalds 		return error;
47781da177e4SLinus Torvalds 
4779da1ce067SMiklos Szeredi 	if (!target) {
47804609e1f1SChristian Brauner 		error = may_create(rd->new_mnt_idmap, new_dir, new_dentry);
4781da1ce067SMiklos Szeredi 	} else {
4782da1ce067SMiklos Szeredi 		new_is_dir = d_is_dir(new_dentry);
4783da1ce067SMiklos Szeredi 
4784da1ce067SMiklos Szeredi 		if (!(flags & RENAME_EXCHANGE))
47854609e1f1SChristian Brauner 			error = may_delete(rd->new_mnt_idmap, new_dir,
47866521f891SChristian Brauner 					   new_dentry, is_dir);
4787da1ce067SMiklos Szeredi 		else
47884609e1f1SChristian Brauner 			error = may_delete(rd->new_mnt_idmap, new_dir,
47896521f891SChristian Brauner 					   new_dentry, new_is_dir);
4790da1ce067SMiklos Szeredi 	}
47911da177e4SLinus Torvalds 	if (error)
47921da177e4SLinus Torvalds 		return error;
47931da177e4SLinus Torvalds 
47942773bf00SMiklos Szeredi 	if (!old_dir->i_op->rename)
47951da177e4SLinus Torvalds 		return -EPERM;
47961da177e4SLinus Torvalds 
4797bc27027aSMiklos Szeredi 	/*
4798bc27027aSMiklos Szeredi 	 * If we are going to change the parent - check write permissions,
4799bc27027aSMiklos Szeredi 	 * we'll need to flip '..'.
4800bc27027aSMiklos Szeredi 	 */
4801da1ce067SMiklos Szeredi 	if (new_dir != old_dir) {
4802da1ce067SMiklos Szeredi 		if (is_dir) {
48034609e1f1SChristian Brauner 			error = inode_permission(rd->old_mnt_idmap, source,
480447291baaSChristian Brauner 						 MAY_WRITE);
4805bc27027aSMiklos Szeredi 			if (error)
4806bc27027aSMiklos Szeredi 				return error;
4807bc27027aSMiklos Szeredi 		}
4808da1ce067SMiklos Szeredi 		if ((flags & RENAME_EXCHANGE) && new_is_dir) {
48094609e1f1SChristian Brauner 			error = inode_permission(rd->new_mnt_idmap, target,
481047291baaSChristian Brauner 						 MAY_WRITE);
4811da1ce067SMiklos Szeredi 			if (error)
4812da1ce067SMiklos Szeredi 				return error;
4813da1ce067SMiklos Szeredi 		}
4814da1ce067SMiklos Szeredi 	}
48150eeca283SRobert Love 
48160b3974ebSMiklos Szeredi 	error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,
48170b3974ebSMiklos Szeredi 				      flags);
4818bc27027aSMiklos Szeredi 	if (error)
4819bc27027aSMiklos Szeredi 		return error;
4820bc27027aSMiklos Szeredi 
482149d31c2fSAl Viro 	take_dentry_name_snapshot(&old_name, old_dentry);
4822bc27027aSMiklos Szeredi 	dget(new_dentry);
482328eceedaSJan Kara 	/*
482428eceedaSJan Kara 	 * Lock all moved children. Moved directories may need to change parent
482528eceedaSJan Kara 	 * pointer so they need the lock to prevent against concurrent
482628eceedaSJan Kara 	 * directory changes moving parent pointer. For regular files we've
482728eceedaSJan Kara 	 * historically always done this. The lockdep locking subclasses are
482828eceedaSJan Kara 	 * somewhat arbitrary but RENAME_EXCHANGE in particular can swap
482928eceedaSJan Kara 	 * regular files and directories so it's difficult to tell which
483028eceedaSJan Kara 	 * subclasses to use.
483128eceedaSJan Kara 	 */
483228eceedaSJan Kara 	lock_two_inodes(source, target, I_MUTEX_NORMAL, I_MUTEX_NONDIR2);
4833bc27027aSMiklos Szeredi 
483451cc3a66SHugh Dickins 	error = -EPERM;
483551cc3a66SHugh Dickins 	if (IS_SWAPFILE(source) || (target && IS_SWAPFILE(target)))
483651cc3a66SHugh Dickins 		goto out;
483751cc3a66SHugh Dickins 
4838bc27027aSMiklos Szeredi 	error = -EBUSY;
48397af1364fSEric W. Biederman 	if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
4840bc27027aSMiklos Szeredi 		goto out;
4841bc27027aSMiklos Szeredi 
4842da1ce067SMiklos Szeredi 	if (max_links && new_dir != old_dir) {
4843bc27027aSMiklos Szeredi 		error = -EMLINK;
4844da1ce067SMiklos Szeredi 		if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)
4845bc27027aSMiklos Szeredi 			goto out;
4846da1ce067SMiklos Szeredi 		if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&
4847da1ce067SMiklos Szeredi 		    old_dir->i_nlink >= max_links)
4848da1ce067SMiklos Szeredi 			goto out;
4849da1ce067SMiklos Szeredi 	}
4850da1ce067SMiklos Szeredi 	if (!is_dir) {
4851bc27027aSMiklos Szeredi 		error = try_break_deleg(source, delegated_inode);
4852bc27027aSMiklos Szeredi 		if (error)
4853bc27027aSMiklos Szeredi 			goto out;
4854da1ce067SMiklos Szeredi 	}
4855da1ce067SMiklos Szeredi 	if (target && !new_is_dir) {
4856bc27027aSMiklos Szeredi 		error = try_break_deleg(target, delegated_inode);
4857bc27027aSMiklos Szeredi 		if (error)
4858bc27027aSMiklos Szeredi 			goto out;
4859bc27027aSMiklos Szeredi 	}
4860e18275aeSChristian Brauner 	error = old_dir->i_op->rename(rd->new_mnt_idmap, old_dir, old_dentry,
4861520c8b16SMiklos Szeredi 				      new_dir, new_dentry, flags);
4862bc27027aSMiklos Szeredi 	if (error)
4863bc27027aSMiklos Szeredi 		goto out;
4864bc27027aSMiklos Szeredi 
4865da1ce067SMiklos Szeredi 	if (!(flags & RENAME_EXCHANGE) && target) {
48668767712fSAl Viro 		if (is_dir) {
48678767712fSAl Viro 			shrink_dcache_parent(new_dentry);
4868bc27027aSMiklos Szeredi 			target->i_flags |= S_DEAD;
48698767712fSAl Viro 		}
4870bc27027aSMiklos Szeredi 		dont_mount(new_dentry);
48718ed936b5SEric W. Biederman 		detach_mounts(new_dentry);
4872bc27027aSMiklos Szeredi 	}
4873da1ce067SMiklos Szeredi 	if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {
4874da1ce067SMiklos Szeredi 		if (!(flags & RENAME_EXCHANGE))
4875bc27027aSMiklos Szeredi 			d_move(old_dentry, new_dentry);
4876da1ce067SMiklos Szeredi 		else
4877da1ce067SMiklos Szeredi 			d_exchange(old_dentry, new_dentry);
4878da1ce067SMiklos Szeredi 	}
4879bc27027aSMiklos Szeredi out:
488028eceedaSJan Kara 	inode_unlock(source);
488128eceedaSJan Kara 	if (target)
48825955102cSAl Viro 		inode_unlock(target);
4883bc27027aSMiklos Szeredi 	dput(new_dentry);
4884da1ce067SMiklos Szeredi 	if (!error) {
4885f4ec3a3dSAl Viro 		fsnotify_move(old_dir, new_dir, &old_name.name, is_dir,
4886da1ce067SMiklos Szeredi 			      !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);
4887da1ce067SMiklos Szeredi 		if (flags & RENAME_EXCHANGE) {
4888f4ec3a3dSAl Viro 			fsnotify_move(new_dir, old_dir, &old_dentry->d_name,
4889da1ce067SMiklos Szeredi 				      new_is_dir, NULL, new_dentry);
4890da1ce067SMiklos Szeredi 		}
4891da1ce067SMiklos Szeredi 	}
489249d31c2fSAl Viro 	release_dentry_name_snapshot(&old_name);
48930eeca283SRobert Love 
48941da177e4SLinus Torvalds 	return error;
48951da177e4SLinus Torvalds }
48964d359507SAl Viro EXPORT_SYMBOL(vfs_rename);
48971da177e4SLinus Torvalds 
4898e886663cSJens Axboe int do_renameat2(int olddfd, struct filename *from, int newdfd,
4899e886663cSJens Axboe 		 struct filename *to, unsigned int flags)
49001da177e4SLinus Torvalds {
49019fe61450SChristian Brauner 	struct renamedata rd;
49021da177e4SLinus Torvalds 	struct dentry *old_dentry, *new_dentry;
49031da177e4SLinus Torvalds 	struct dentry *trap;
4904f5beed75SAl Viro 	struct path old_path, new_path;
4905f5beed75SAl Viro 	struct qstr old_last, new_last;
4906f5beed75SAl Viro 	int old_type, new_type;
49078e6d782cSJ. Bruce Fields 	struct inode *delegated_inode = NULL;
4908f5beed75SAl Viro 	unsigned int lookup_flags = 0, target_flags = LOOKUP_RENAME_TARGET;
4909c6a94284SJeff Layton 	bool should_retry = false;
4910e886663cSJens Axboe 	int error = -EINVAL;
4911520c8b16SMiklos Szeredi 
49120d7a8555SMiklos Szeredi 	if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
49130ee50b47SDmitry Kadashev 		goto put_names;
4914da1ce067SMiklos Szeredi 
49150d7a8555SMiklos Szeredi 	if ((flags & (RENAME_NOREPLACE | RENAME_WHITEOUT)) &&
49160d7a8555SMiklos Szeredi 	    (flags & RENAME_EXCHANGE))
49170ee50b47SDmitry Kadashev 		goto put_names;
4918520c8b16SMiklos Szeredi 
4919f5beed75SAl Viro 	if (flags & RENAME_EXCHANGE)
4920f5beed75SAl Viro 		target_flags = 0;
4921f5beed75SAl Viro 
4922c6a94284SJeff Layton retry:
4923c5f563f9SAl Viro 	error = filename_parentat(olddfd, from, lookup_flags, &old_path,
4924e886663cSJens Axboe 				  &old_last, &old_type);
49250ee50b47SDmitry Kadashev 	if (error)
49260ee50b47SDmitry Kadashev 		goto put_names;
49271da177e4SLinus Torvalds 
4928c5f563f9SAl Viro 	error = filename_parentat(newdfd, to, lookup_flags, &new_path, &new_last,
4929e886663cSJens Axboe 				  &new_type);
49300ee50b47SDmitry Kadashev 	if (error)
49311da177e4SLinus Torvalds 		goto exit1;
49321da177e4SLinus Torvalds 
49331da177e4SLinus Torvalds 	error = -EXDEV;
4934f5beed75SAl Viro 	if (old_path.mnt != new_path.mnt)
49351da177e4SLinus Torvalds 		goto exit2;
49361da177e4SLinus Torvalds 
49371da177e4SLinus Torvalds 	error = -EBUSY;
4938f5beed75SAl Viro 	if (old_type != LAST_NORM)
49391da177e4SLinus Torvalds 		goto exit2;
49401da177e4SLinus Torvalds 
49410a7c3937SMiklos Szeredi 	if (flags & RENAME_NOREPLACE)
49420a7c3937SMiklos Szeredi 		error = -EEXIST;
4943f5beed75SAl Viro 	if (new_type != LAST_NORM)
49441da177e4SLinus Torvalds 		goto exit2;
49451da177e4SLinus Torvalds 
4946f5beed75SAl Viro 	error = mnt_want_write(old_path.mnt);
4947c30dabfeSJan Kara 	if (error)
4948c30dabfeSJan Kara 		goto exit2;
4949c30dabfeSJan Kara 
49508e6d782cSJ. Bruce Fields retry_deleg:
4951f5beed75SAl Viro 	trap = lock_rename(new_path.dentry, old_path.dentry);
49521da177e4SLinus Torvalds 
495374d7970fSNamjae Jeon 	old_dentry = lookup_one_qstr_excl(&old_last, old_path.dentry,
495474d7970fSNamjae Jeon 					  lookup_flags);
49551da177e4SLinus Torvalds 	error = PTR_ERR(old_dentry);
49561da177e4SLinus Torvalds 	if (IS_ERR(old_dentry))
49571da177e4SLinus Torvalds 		goto exit3;
49581da177e4SLinus Torvalds 	/* source must exist */
49591da177e4SLinus Torvalds 	error = -ENOENT;
4960b18825a7SDavid Howells 	if (d_is_negative(old_dentry))
49611da177e4SLinus Torvalds 		goto exit4;
496274d7970fSNamjae Jeon 	new_dentry = lookup_one_qstr_excl(&new_last, new_path.dentry,
496374d7970fSNamjae Jeon 					  lookup_flags | target_flags);
49641da177e4SLinus Torvalds 	error = PTR_ERR(new_dentry);
49651da177e4SLinus Torvalds 	if (IS_ERR(new_dentry))
49661da177e4SLinus Torvalds 		goto exit4;
49670a7c3937SMiklos Szeredi 	error = -EEXIST;
49680a7c3937SMiklos Szeredi 	if ((flags & RENAME_NOREPLACE) && d_is_positive(new_dentry))
49690a7c3937SMiklos Szeredi 		goto exit5;
4970da1ce067SMiklos Szeredi 	if (flags & RENAME_EXCHANGE) {
4971da1ce067SMiklos Szeredi 		error = -ENOENT;
4972da1ce067SMiklos Szeredi 		if (d_is_negative(new_dentry))
4973da1ce067SMiklos Szeredi 			goto exit5;
4974da1ce067SMiklos Szeredi 
4975da1ce067SMiklos Szeredi 		if (!d_is_dir(new_dentry)) {
4976da1ce067SMiklos Szeredi 			error = -ENOTDIR;
4977f5beed75SAl Viro 			if (new_last.name[new_last.len])
4978da1ce067SMiklos Szeredi 				goto exit5;
4979da1ce067SMiklos Szeredi 		}
4980da1ce067SMiklos Szeredi 	}
49810a7c3937SMiklos Szeredi 	/* unless the source is a directory trailing slashes give -ENOTDIR */
49820a7c3937SMiklos Szeredi 	if (!d_is_dir(old_dentry)) {
49830a7c3937SMiklos Szeredi 		error = -ENOTDIR;
4984f5beed75SAl Viro 		if (old_last.name[old_last.len])
49850a7c3937SMiklos Szeredi 			goto exit5;
4986f5beed75SAl Viro 		if (!(flags & RENAME_EXCHANGE) && new_last.name[new_last.len])
49870a7c3937SMiklos Szeredi 			goto exit5;
49880a7c3937SMiklos Szeredi 	}
49890a7c3937SMiklos Szeredi 	/* source should not be ancestor of target */
49900a7c3937SMiklos Szeredi 	error = -EINVAL;
49910a7c3937SMiklos Szeredi 	if (old_dentry == trap)
49920a7c3937SMiklos Szeredi 		goto exit5;
49931da177e4SLinus Torvalds 	/* target should not be an ancestor of source */
4994da1ce067SMiklos Szeredi 	if (!(flags & RENAME_EXCHANGE))
49951da177e4SLinus Torvalds 		error = -ENOTEMPTY;
49961da177e4SLinus Torvalds 	if (new_dentry == trap)
49971da177e4SLinus Torvalds 		goto exit5;
49981da177e4SLinus Torvalds 
4999f5beed75SAl Viro 	error = security_path_rename(&old_path, old_dentry,
5000f5beed75SAl Viro 				     &new_path, new_dentry, flags);
5001be6d3e56SKentaro Takeda 	if (error)
5002c30dabfeSJan Kara 		goto exit5;
50039fe61450SChristian Brauner 
50049fe61450SChristian Brauner 	rd.old_dir	   = old_path.dentry->d_inode;
50059fe61450SChristian Brauner 	rd.old_dentry	   = old_dentry;
5006abf08576SChristian Brauner 	rd.old_mnt_idmap   = mnt_idmap(old_path.mnt);
50079fe61450SChristian Brauner 	rd.new_dir	   = new_path.dentry->d_inode;
50089fe61450SChristian Brauner 	rd.new_dentry	   = new_dentry;
5009abf08576SChristian Brauner 	rd.new_mnt_idmap   = mnt_idmap(new_path.mnt);
50109fe61450SChristian Brauner 	rd.delegated_inode = &delegated_inode;
50119fe61450SChristian Brauner 	rd.flags	   = flags;
50129fe61450SChristian Brauner 	error = vfs_rename(&rd);
50131da177e4SLinus Torvalds exit5:
50141da177e4SLinus Torvalds 	dput(new_dentry);
50151da177e4SLinus Torvalds exit4:
50161da177e4SLinus Torvalds 	dput(old_dentry);
50171da177e4SLinus Torvalds exit3:
5018f5beed75SAl Viro 	unlock_rename(new_path.dentry, old_path.dentry);
50198e6d782cSJ. Bruce Fields 	if (delegated_inode) {
50208e6d782cSJ. Bruce Fields 		error = break_deleg_wait(&delegated_inode);
50218e6d782cSJ. Bruce Fields 		if (!error)
50228e6d782cSJ. Bruce Fields 			goto retry_deleg;
50238e6d782cSJ. Bruce Fields 	}
5024f5beed75SAl Viro 	mnt_drop_write(old_path.mnt);
50251da177e4SLinus Torvalds exit2:
5026c6a94284SJeff Layton 	if (retry_estale(error, lookup_flags))
5027c6a94284SJeff Layton 		should_retry = true;
5028f5beed75SAl Viro 	path_put(&new_path);
50291da177e4SLinus Torvalds exit1:
5030f5beed75SAl Viro 	path_put(&old_path);
5031c6a94284SJeff Layton 	if (should_retry) {
5032c6a94284SJeff Layton 		should_retry = false;
5033c6a94284SJeff Layton 		lookup_flags |= LOOKUP_REVAL;
5034c6a94284SJeff Layton 		goto retry;
5035c6a94284SJeff Layton 	}
50360ee50b47SDmitry Kadashev put_names:
5037e886663cSJens Axboe 	putname(from);
5038e886663cSJens Axboe 	putname(to);
50391da177e4SLinus Torvalds 	return error;
50401da177e4SLinus Torvalds }
50411da177e4SLinus Torvalds 
5042ee81feb6SDominik Brodowski SYSCALL_DEFINE5(renameat2, int, olddfd, const char __user *, oldname,
5043ee81feb6SDominik Brodowski 		int, newdfd, const char __user *, newname, unsigned int, flags)
5044ee81feb6SDominik Brodowski {
5045e886663cSJens Axboe 	return do_renameat2(olddfd, getname(oldname), newdfd, getname(newname),
5046e886663cSJens Axboe 				flags);
5047ee81feb6SDominik Brodowski }
5048ee81feb6SDominik Brodowski 
5049520c8b16SMiklos Szeredi SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname,
5050520c8b16SMiklos Szeredi 		int, newdfd, const char __user *, newname)
5051520c8b16SMiklos Szeredi {
5052e886663cSJens Axboe 	return do_renameat2(olddfd, getname(oldname), newdfd, getname(newname),
5053e886663cSJens Axboe 				0);
5054520c8b16SMiklos Szeredi }
5055520c8b16SMiklos Szeredi 
5056a26eab24SHeiko Carstens SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname)
50575590ff0dSUlrich Drepper {
5058e886663cSJens Axboe 	return do_renameat2(AT_FDCWD, getname(oldname), AT_FDCWD,
5059e886663cSJens Axboe 				getname(newname), 0);
50605590ff0dSUlrich Drepper }
50615590ff0dSUlrich Drepper 
50625d826c84SAl Viro int readlink_copy(char __user *buffer, int buflen, const char *link)
50631da177e4SLinus Torvalds {
50645d826c84SAl Viro 	int len = PTR_ERR(link);
50651da177e4SLinus Torvalds 	if (IS_ERR(link))
50661da177e4SLinus Torvalds 		goto out;
50671da177e4SLinus Torvalds 
50681da177e4SLinus Torvalds 	len = strlen(link);
50691da177e4SLinus Torvalds 	if (len > (unsigned) buflen)
50701da177e4SLinus Torvalds 		len = buflen;
50711da177e4SLinus Torvalds 	if (copy_to_user(buffer, link, len))
50721da177e4SLinus Torvalds 		len = -EFAULT;
50731da177e4SLinus Torvalds out:
50741da177e4SLinus Torvalds 	return len;
50751da177e4SLinus Torvalds }
50761da177e4SLinus Torvalds 
5077d60874cdSMiklos Szeredi /**
5078fd4a0edfSMiklos Szeredi  * vfs_readlink - copy symlink body into userspace buffer
5079fd4a0edfSMiklos Szeredi  * @dentry: dentry on which to get symbolic link
5080fd4a0edfSMiklos Szeredi  * @buffer: user memory pointer
5081fd4a0edfSMiklos Szeredi  * @buflen: size of buffer
5082fd4a0edfSMiklos Szeredi  *
5083fd4a0edfSMiklos Szeredi  * Does not touch atime.  That's up to the caller if necessary
5084fd4a0edfSMiklos Szeredi  *
5085fd4a0edfSMiklos Szeredi  * Does not call security hook.
5086fd4a0edfSMiklos Szeredi  */
5087fd4a0edfSMiklos Szeredi int vfs_readlink(struct dentry *dentry, char __user *buffer, int buflen)
5088fd4a0edfSMiklos Szeredi {
5089fd4a0edfSMiklos Szeredi 	struct inode *inode = d_inode(dentry);
5090f2df5da6SAl Viro 	DEFINE_DELAYED_CALL(done);
5091f2df5da6SAl Viro 	const char *link;
5092f2df5da6SAl Viro 	int res;
5093fd4a0edfSMiklos Szeredi 
509476fca90eSMiklos Szeredi 	if (unlikely(!(inode->i_opflags & IOP_DEFAULT_READLINK))) {
509576fca90eSMiklos Szeredi 		if (unlikely(inode->i_op->readlink))
509676fca90eSMiklos Szeredi 			return inode->i_op->readlink(dentry, buffer, buflen);
509776fca90eSMiklos Szeredi 
509876fca90eSMiklos Szeredi 		if (!d_is_symlink(dentry))
5099fd4a0edfSMiklos Szeredi 			return -EINVAL;
5100fd4a0edfSMiklos Szeredi 
510176fca90eSMiklos Szeredi 		spin_lock(&inode->i_lock);
510276fca90eSMiklos Szeredi 		inode->i_opflags |= IOP_DEFAULT_READLINK;
510376fca90eSMiklos Szeredi 		spin_unlock(&inode->i_lock);
510476fca90eSMiklos Szeredi 	}
510576fca90eSMiklos Szeredi 
51064c4f7c19SEric Biggers 	link = READ_ONCE(inode->i_link);
5107f2df5da6SAl Viro 	if (!link) {
5108f2df5da6SAl Viro 		link = inode->i_op->get_link(dentry, inode, &done);
5109f2df5da6SAl Viro 		if (IS_ERR(link))
5110f2df5da6SAl Viro 			return PTR_ERR(link);
5111f2df5da6SAl Viro 	}
5112f2df5da6SAl Viro 	res = readlink_copy(buffer, buflen, link);
5113f2df5da6SAl Viro 	do_delayed_call(&done);
5114f2df5da6SAl Viro 	return res;
5115fd4a0edfSMiklos Szeredi }
5116fd4a0edfSMiklos Szeredi EXPORT_SYMBOL(vfs_readlink);
51171da177e4SLinus Torvalds 
5118d60874cdSMiklos Szeredi /**
5119d60874cdSMiklos Szeredi  * vfs_get_link - get symlink body
5120d60874cdSMiklos Szeredi  * @dentry: dentry on which to get symbolic link
5121d60874cdSMiklos Szeredi  * @done: caller needs to free returned data with this
5122d60874cdSMiklos Szeredi  *
5123d60874cdSMiklos Szeredi  * Calls security hook and i_op->get_link() on the supplied inode.
5124d60874cdSMiklos Szeredi  *
5125d60874cdSMiklos Szeredi  * It does not touch atime.  That's up to the caller if necessary.
5126d60874cdSMiklos Szeredi  *
5127d60874cdSMiklos Szeredi  * Does not work on "special" symlinks like /proc/$$/fd/N
5128d60874cdSMiklos Szeredi  */
5129d60874cdSMiklos Szeredi const char *vfs_get_link(struct dentry *dentry, struct delayed_call *done)
5130d60874cdSMiklos Szeredi {
5131d60874cdSMiklos Szeredi 	const char *res = ERR_PTR(-EINVAL);
5132d60874cdSMiklos Szeredi 	struct inode *inode = d_inode(dentry);
5133d60874cdSMiklos Szeredi 
5134d60874cdSMiklos Szeredi 	if (d_is_symlink(dentry)) {
5135d60874cdSMiklos Szeredi 		res = ERR_PTR(security_inode_readlink(dentry));
5136d60874cdSMiklos Szeredi 		if (!res)
5137d60874cdSMiklos Szeredi 			res = inode->i_op->get_link(dentry, inode, done);
5138d60874cdSMiklos Szeredi 	}
5139d60874cdSMiklos Szeredi 	return res;
5140d60874cdSMiklos Szeredi }
5141d60874cdSMiklos Szeredi EXPORT_SYMBOL(vfs_get_link);
5142d60874cdSMiklos Szeredi 
51431da177e4SLinus Torvalds /* get the link contents into pagecache */
51446b255391SAl Viro const char *page_get_link(struct dentry *dentry, struct inode *inode,
5145fceef393SAl Viro 			  struct delayed_call *callback)
51461da177e4SLinus Torvalds {
5147ebd09abbSDuane Griffin 	char *kaddr;
51481da177e4SLinus Torvalds 	struct page *page;
51496b255391SAl Viro 	struct address_space *mapping = inode->i_mapping;
51506b255391SAl Viro 
5151d3883d4fSAl Viro 	if (!dentry) {
5152d3883d4fSAl Viro 		page = find_get_page(mapping, 0);
5153d3883d4fSAl Viro 		if (!page)
51546b255391SAl Viro 			return ERR_PTR(-ECHILD);
5155d3883d4fSAl Viro 		if (!PageUptodate(page)) {
5156d3883d4fSAl Viro 			put_page(page);
5157d3883d4fSAl Viro 			return ERR_PTR(-ECHILD);
5158d3883d4fSAl Viro 		}
5159d3883d4fSAl Viro 	} else {
5160090d2b18SPekka Enberg 		page = read_mapping_page(mapping, 0, NULL);
51611da177e4SLinus Torvalds 		if (IS_ERR(page))
51626fe6900eSNick Piggin 			return (char*)page;
5163d3883d4fSAl Viro 	}
5164fceef393SAl Viro 	set_delayed_call(callback, page_put_link, page);
516521fc61c7SAl Viro 	BUG_ON(mapping_gfp_mask(mapping) & __GFP_HIGHMEM);
516621fc61c7SAl Viro 	kaddr = page_address(page);
51676b255391SAl Viro 	nd_terminate_link(kaddr, inode->i_size, PAGE_SIZE - 1);
5168ebd09abbSDuane Griffin 	return kaddr;
51691da177e4SLinus Torvalds }
51701da177e4SLinus Torvalds 
51716b255391SAl Viro EXPORT_SYMBOL(page_get_link);
51721da177e4SLinus Torvalds 
5173fceef393SAl Viro void page_put_link(void *arg)
51741da177e4SLinus Torvalds {
5175fceef393SAl Viro 	put_page(arg);
51761da177e4SLinus Torvalds }
51774d359507SAl Viro EXPORT_SYMBOL(page_put_link);
51781da177e4SLinus Torvalds 
5179aa80deabSAl Viro int page_readlink(struct dentry *dentry, char __user *buffer, int buflen)
5180aa80deabSAl Viro {
5181fceef393SAl Viro 	DEFINE_DELAYED_CALL(done);
51826b255391SAl Viro 	int res = readlink_copy(buffer, buflen,
51836b255391SAl Viro 				page_get_link(dentry, d_inode(dentry),
5184fceef393SAl Viro 					      &done));
5185fceef393SAl Viro 	do_delayed_call(&done);
5186aa80deabSAl Viro 	return res;
5187aa80deabSAl Viro }
5188aa80deabSAl Viro EXPORT_SYMBOL(page_readlink);
5189aa80deabSAl Viro 
519056f5746cSMatthew Wilcox (Oracle) int page_symlink(struct inode *inode, const char *symname, int len)
51911da177e4SLinus Torvalds {
51921da177e4SLinus Torvalds 	struct address_space *mapping = inode->i_mapping;
519327a77913SMatthew Wilcox (Oracle) 	const struct address_space_operations *aops = mapping->a_ops;
519456f5746cSMatthew Wilcox (Oracle) 	bool nofs = !mapping_gfp_constraint(mapping, __GFP_FS);
51950adb25d2SKirill Korotaev 	struct page *page;
51961468c6f4SAlexander Potapenko 	void *fsdata = NULL;
5197beb497abSDmitriy Monakhov 	int err;
51982d878178SMatthew Wilcox (Oracle) 	unsigned int flags;
51991da177e4SLinus Torvalds 
52007e53cac4SNeilBrown retry:
52012d878178SMatthew Wilcox (Oracle) 	if (nofs)
52022d878178SMatthew Wilcox (Oracle) 		flags = memalloc_nofs_save();
520327a77913SMatthew Wilcox (Oracle) 	err = aops->write_begin(NULL, mapping, 0, len-1, &page, &fsdata);
52042d878178SMatthew Wilcox (Oracle) 	if (nofs)
52052d878178SMatthew Wilcox (Oracle) 		memalloc_nofs_restore(flags);
52061da177e4SLinus Torvalds 	if (err)
5207afddba49SNick Piggin 		goto fail;
5208afddba49SNick Piggin 
520921fc61c7SAl Viro 	memcpy(page_address(page), symname, len-1);
5210afddba49SNick Piggin 
521127a77913SMatthew Wilcox (Oracle) 	err = aops->write_end(NULL, mapping, 0, len-1, len-1,
5212afddba49SNick Piggin 							page, fsdata);
52131da177e4SLinus Torvalds 	if (err < 0)
52141da177e4SLinus Torvalds 		goto fail;
5215afddba49SNick Piggin 	if (err < len-1)
5216afddba49SNick Piggin 		goto retry;
5217afddba49SNick Piggin 
52181da177e4SLinus Torvalds 	mark_inode_dirty(inode);
52191da177e4SLinus Torvalds 	return 0;
52201da177e4SLinus Torvalds fail:
52211da177e4SLinus Torvalds 	return err;
52221da177e4SLinus Torvalds }
52234d359507SAl Viro EXPORT_SYMBOL(page_symlink);
52240adb25d2SKirill Korotaev 
522592e1d5beSArjan van de Ven const struct inode_operations page_symlink_inode_operations = {
52266b255391SAl Viro 	.get_link	= page_get_link,
52271da177e4SLinus Torvalds };
52281da177e4SLinus Torvalds EXPORT_SYMBOL(page_symlink_inode_operations);
5229