xref: /openbmc/linux/fs/namei.c (revision 9bc37e04)
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 }
257c4ad8f98SLinus Torvalds 
25891a27b2aSJeff Layton void putname(struct filename *name)
2591da177e4SLinus Torvalds {
260ea47ab11SAl Viro 	if (IS_ERR(name))
26191ef658fSDmitry Kadashev 		return;
26291ef658fSDmitry Kadashev 
26355422d0bSPaul Moore 	BUG_ON(name->refcnt <= 0);
26455422d0bSPaul Moore 
26555422d0bSPaul Moore 	if (--name->refcnt > 0)
26655422d0bSPaul Moore 		return;
26755422d0bSPaul Moore 
268fd2f7cb5SAl Viro 	if (name->name != name->iname) {
26955422d0bSPaul Moore 		__putname(name->name);
27055422d0bSPaul Moore 		kfree(name);
27155422d0bSPaul Moore 	} else
27255422d0bSPaul Moore 		__putname(name);
2731da177e4SLinus Torvalds }
2741da177e4SLinus Torvalds 
27547291baaSChristian Brauner /**
27647291baaSChristian Brauner  * check_acl - perform ACL permission checking
277700b7940SChristian Brauner  * @idmap:	idmap of the mount the inode was found from
27847291baaSChristian Brauner  * @inode:	inode to check permissions on
27947291baaSChristian Brauner  * @mask:	right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
28047291baaSChristian Brauner  *
28147291baaSChristian Brauner  * This function performs the ACL permission checking. Since this function
28247291baaSChristian Brauner  * retrieve POSIX acls it needs to know whether it is called from a blocking or
28347291baaSChristian Brauner  * non-blocking context and thus cares about the MAY_NOT_BLOCK bit.
28447291baaSChristian Brauner  *
285700b7940SChristian Brauner  * If the inode has been found through an idmapped mount the idmap of
286700b7940SChristian Brauner  * the vfsmount must be passed through @idmap. This function will then take
287700b7940SChristian Brauner  * care to map the inode according to @idmap before checking permissions.
28847291baaSChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
289700b7940SChristian Brauner  * raw inode simply passs @nop_mnt_idmap.
29047291baaSChristian Brauner  */
291700b7940SChristian Brauner static int check_acl(struct mnt_idmap *idmap,
29247291baaSChristian Brauner 		     struct inode *inode, int mask)
293e77819e5SLinus Torvalds {
29484635d68SLinus Torvalds #ifdef CONFIG_FS_POSIX_ACL
295e77819e5SLinus Torvalds 	struct posix_acl *acl;
296e77819e5SLinus Torvalds 
297e77819e5SLinus Torvalds 	if (mask & MAY_NOT_BLOCK) {
2983567866bSAl Viro 		acl = get_cached_acl_rcu(inode, ACL_TYPE_ACCESS);
2993567866bSAl Viro 	        if (!acl)
300e77819e5SLinus Torvalds 	                return -EAGAIN;
301cac2f8b8SChristian Brauner 		/* no ->get_inode_acl() calls in RCU mode... */
302b8a7a3a6SAndreas Gruenbacher 		if (is_uncached_acl(acl))
303e77819e5SLinus Torvalds 			return -ECHILD;
304700b7940SChristian Brauner 	        return posix_acl_permission(idmap, inode, acl, mask);
305e77819e5SLinus Torvalds 	}
306e77819e5SLinus Torvalds 
307cac2f8b8SChristian Brauner 	acl = get_inode_acl(inode, ACL_TYPE_ACCESS);
3084e34e719SChristoph Hellwig 	if (IS_ERR(acl))
3094e34e719SChristoph Hellwig 		return PTR_ERR(acl);
310e77819e5SLinus Torvalds 	if (acl) {
311700b7940SChristian Brauner 	        int error = posix_acl_permission(idmap, inode, acl, mask);
312e77819e5SLinus Torvalds 	        posix_acl_release(acl);
313e77819e5SLinus Torvalds 	        return error;
314e77819e5SLinus Torvalds 	}
31584635d68SLinus Torvalds #endif
316e77819e5SLinus Torvalds 
317e77819e5SLinus Torvalds 	return -EAGAIN;
318e77819e5SLinus Torvalds }
319e77819e5SLinus Torvalds 
32047291baaSChristian Brauner /**
32147291baaSChristian Brauner  * acl_permission_check - perform basic UNIX permission checking
322700b7940SChristian Brauner  * @idmap:	idmap of the mount the inode was found from
32347291baaSChristian Brauner  * @inode:	inode to check permissions on
32447291baaSChristian Brauner  * @mask:	right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
3255fc475b7SLinus Torvalds  *
32647291baaSChristian Brauner  * This function performs the basic UNIX permission checking. Since this
32747291baaSChristian Brauner  * function may retrieve POSIX acls it needs to know whether it is called from a
32847291baaSChristian Brauner  * blocking or non-blocking context and thus cares about the MAY_NOT_BLOCK bit.
32947291baaSChristian Brauner  *
330700b7940SChristian Brauner  * If the inode has been found through an idmapped mount the idmap of
331700b7940SChristian Brauner  * the vfsmount must be passed through @idmap. This function will then take
332700b7940SChristian Brauner  * care to map the inode according to @idmap before checking permissions.
33347291baaSChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
334700b7940SChristian Brauner  * raw inode simply passs @nop_mnt_idmap.
3355909ccaaSLinus Torvalds  */
336700b7940SChristian Brauner static int acl_permission_check(struct mnt_idmap *idmap,
33747291baaSChristian Brauner 				struct inode *inode, int mask)
3385909ccaaSLinus Torvalds {
33926cf46beSLinus Torvalds 	unsigned int mode = inode->i_mode;
340a2bd096fSChristian Brauner 	vfsuid_t vfsuid;
3415909ccaaSLinus Torvalds 
3425fc475b7SLinus Torvalds 	/* Are we the owner? If so, ACL's don't matter */
343e67fe633SChristian Brauner 	vfsuid = i_uid_into_vfsuid(idmap, inode);
344a2bd096fSChristian Brauner 	if (likely(vfsuid_eq_kuid(vfsuid, current_fsuid()))) {
3455fc475b7SLinus Torvalds 		mask &= 7;
3465909ccaaSLinus Torvalds 		mode >>= 6;
3475fc475b7SLinus Torvalds 		return (mask & ~mode) ? -EACCES : 0;
3485fc475b7SLinus Torvalds 	}
3495fc475b7SLinus Torvalds 
3505fc475b7SLinus Torvalds 	/* Do we have ACL's? */
351e77819e5SLinus Torvalds 	if (IS_POSIXACL(inode) && (mode & S_IRWXG)) {
352700b7940SChristian Brauner 		int error = check_acl(idmap, inode, mask);
3535909ccaaSLinus Torvalds 		if (error != -EAGAIN)
3545909ccaaSLinus Torvalds 			return error;
3555909ccaaSLinus Torvalds 	}
3565909ccaaSLinus Torvalds 
3575fc475b7SLinus Torvalds 	/* Only RWX matters for group/other mode bits */
3585fc475b7SLinus Torvalds 	mask &= 7;
3595fc475b7SLinus Torvalds 
3605fc475b7SLinus Torvalds 	/*
3615fc475b7SLinus Torvalds 	 * Are the group permissions different from
3625fc475b7SLinus Torvalds 	 * the other permissions in the bits we care
3635fc475b7SLinus Torvalds 	 * about? Need to check group ownership if so.
3645fc475b7SLinus Torvalds 	 */
3655fc475b7SLinus Torvalds 	if (mask & (mode ^ (mode >> 3))) {
366e67fe633SChristian Brauner 		vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
367a2bd096fSChristian Brauner 		if (vfsgid_in_group_p(vfsgid))
3685909ccaaSLinus Torvalds 			mode >>= 3;
3695909ccaaSLinus Torvalds 	}
3705909ccaaSLinus Torvalds 
3715fc475b7SLinus Torvalds 	/* Bits in 'mode' clear that we require? */
3725fc475b7SLinus Torvalds 	return (mask & ~mode) ? -EACCES : 0;
3735909ccaaSLinus Torvalds }
3741da177e4SLinus Torvalds 
3751da177e4SLinus Torvalds /**
3761da177e4SLinus Torvalds  * generic_permission -  check for access rights on a Posix-like filesystem
3774609e1f1SChristian Brauner  * @idmap:	idmap of the mount the inode was found from
3781da177e4SLinus Torvalds  * @inode:	inode to check access rights for
3795fc475b7SLinus Torvalds  * @mask:	right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC,
3805fc475b7SLinus Torvalds  *		%MAY_NOT_BLOCK ...)
3811da177e4SLinus Torvalds  *
3821da177e4SLinus Torvalds  * Used to check for read/write/execute permissions on a file.
3831da177e4SLinus Torvalds  * We use "fsuid" for this, letting us set arbitrary permissions
3841da177e4SLinus Torvalds  * for filesystem access without changing the "normal" uids which
385b74c79e9SNick Piggin  * are used for other things.
386b74c79e9SNick Piggin  *
387b74c79e9SNick Piggin  * generic_permission is rcu-walk aware. It returns -ECHILD in case an rcu-walk
388b74c79e9SNick Piggin  * request cannot be satisfied (eg. requires blocking or too much complexity).
389b74c79e9SNick Piggin  * It would then be called again in ref-walk mode.
39047291baaSChristian Brauner  *
3914609e1f1SChristian Brauner  * If the inode has been found through an idmapped mount the idmap of
3924609e1f1SChristian Brauner  * the vfsmount must be passed through @idmap. This function will then take
3934609e1f1SChristian Brauner  * care to map the inode according to @idmap before checking permissions.
39447291baaSChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
3954609e1f1SChristian Brauner  * raw inode simply passs @nop_mnt_idmap.
3961da177e4SLinus Torvalds  */
3974609e1f1SChristian Brauner int generic_permission(struct mnt_idmap *idmap, struct inode *inode,
39847291baaSChristian Brauner 		       int mask)
3991da177e4SLinus Torvalds {
4005909ccaaSLinus Torvalds 	int ret;
4011da177e4SLinus Torvalds 
4021da177e4SLinus Torvalds 	/*
403948409c7SAndreas Gruenbacher 	 * Do the basic permission checks.
4041da177e4SLinus Torvalds 	 */
405700b7940SChristian Brauner 	ret = acl_permission_check(idmap, inode, mask);
4065909ccaaSLinus Torvalds 	if (ret != -EACCES)
4075909ccaaSLinus Torvalds 		return ret;
4081da177e4SLinus Torvalds 
409d594e7ecSAl Viro 	if (S_ISDIR(inode->i_mode)) {
410d594e7ecSAl Viro 		/* DACs are overridable for directories */
411d594e7ecSAl Viro 		if (!(mask & MAY_WRITE))
4129452e93eSChristian Brauner 			if (capable_wrt_inode_uidgid(idmap, inode,
41323adbe12SAndy Lutomirski 						     CAP_DAC_READ_SEARCH))
414d594e7ecSAl Viro 				return 0;
4159452e93eSChristian Brauner 		if (capable_wrt_inode_uidgid(idmap, inode,
4160558c1bfSChristian Brauner 					     CAP_DAC_OVERRIDE))
4171da177e4SLinus Torvalds 			return 0;
4182a4c2242SStephen Smalley 		return -EACCES;
4192a4c2242SStephen Smalley 	}
4201da177e4SLinus Torvalds 
4211da177e4SLinus Torvalds 	/*
4221da177e4SLinus Torvalds 	 * Searching includes executable on directories, else just read.
4231da177e4SLinus Torvalds 	 */
4247ea66001SSerge E. Hallyn 	mask &= MAY_READ | MAY_WRITE | MAY_EXEC;
425d594e7ecSAl Viro 	if (mask == MAY_READ)
4269452e93eSChristian Brauner 		if (capable_wrt_inode_uidgid(idmap, inode,
4270558c1bfSChristian Brauner 					     CAP_DAC_READ_SEARCH))
4281da177e4SLinus Torvalds 			return 0;
4292a4c2242SStephen Smalley 	/*
4302a4c2242SStephen Smalley 	 * Read/write DACs are always overridable.
4312a4c2242SStephen Smalley 	 * Executable DACs are overridable when there is
4322a4c2242SStephen Smalley 	 * at least one exec bit set.
4332a4c2242SStephen Smalley 	 */
4342a4c2242SStephen Smalley 	if (!(mask & MAY_EXEC) || (inode->i_mode & S_IXUGO))
4359452e93eSChristian Brauner 		if (capable_wrt_inode_uidgid(idmap, inode,
4360558c1bfSChristian Brauner 					     CAP_DAC_OVERRIDE))
4372a4c2242SStephen Smalley 			return 0;
4381da177e4SLinus Torvalds 
4391da177e4SLinus Torvalds 	return -EACCES;
4401da177e4SLinus Torvalds }
4414d359507SAl Viro EXPORT_SYMBOL(generic_permission);
4421da177e4SLinus Torvalds 
44347291baaSChristian Brauner /**
44447291baaSChristian Brauner  * do_inode_permission - UNIX permission checking
4454609e1f1SChristian Brauner  * @idmap:	idmap of the mount the inode was found from
44647291baaSChristian Brauner  * @inode:	inode to check permissions on
44747291baaSChristian Brauner  * @mask:	right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
44847291baaSChristian Brauner  *
4493ddcd056SLinus Torvalds  * We _really_ want to just do "generic_permission()" without
4503ddcd056SLinus Torvalds  * even looking at the inode->i_op values. So we keep a cache
4513ddcd056SLinus Torvalds  * flag in inode->i_opflags, that says "this has not special
4523ddcd056SLinus Torvalds  * permission function, use the fast case".
4533ddcd056SLinus Torvalds  */
4544609e1f1SChristian Brauner static inline int do_inode_permission(struct mnt_idmap *idmap,
45547291baaSChristian Brauner 				      struct inode *inode, int mask)
4563ddcd056SLinus Torvalds {
4573ddcd056SLinus Torvalds 	if (unlikely(!(inode->i_opflags & IOP_FASTPERM))) {
4583ddcd056SLinus Torvalds 		if (likely(inode->i_op->permission))
4594609e1f1SChristian Brauner 			return inode->i_op->permission(idmap, inode, mask);
4603ddcd056SLinus Torvalds 
4613ddcd056SLinus Torvalds 		/* This gets set once for the inode lifetime */
4623ddcd056SLinus Torvalds 		spin_lock(&inode->i_lock);
4633ddcd056SLinus Torvalds 		inode->i_opflags |= IOP_FASTPERM;
4643ddcd056SLinus Torvalds 		spin_unlock(&inode->i_lock);
4653ddcd056SLinus Torvalds 	}
4664609e1f1SChristian Brauner 	return generic_permission(idmap, inode, mask);
4673ddcd056SLinus Torvalds }
4683ddcd056SLinus Torvalds 
469cb23beb5SChristoph Hellwig /**
4700bdaea90SDavid Howells  * sb_permission - Check superblock-level permissions
4710bdaea90SDavid Howells  * @sb: Superblock of inode to check permission on
47255852635SRandy Dunlap  * @inode: Inode to check permission on
4730bdaea90SDavid Howells  * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
4740bdaea90SDavid Howells  *
4750bdaea90SDavid Howells  * Separate out file-system wide checks from inode-specific permission checks.
4760bdaea90SDavid Howells  */
4770bdaea90SDavid Howells static int sb_permission(struct super_block *sb, struct inode *inode, int mask)
4780bdaea90SDavid Howells {
4790bdaea90SDavid Howells 	if (unlikely(mask & MAY_WRITE)) {
4800bdaea90SDavid Howells 		umode_t mode = inode->i_mode;
4810bdaea90SDavid Howells 
4820bdaea90SDavid Howells 		/* Nobody gets write access to a read-only fs. */
483bc98a42cSDavid Howells 		if (sb_rdonly(sb) && (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode)))
4840bdaea90SDavid Howells 			return -EROFS;
4850bdaea90SDavid Howells 	}
4860bdaea90SDavid Howells 	return 0;
4870bdaea90SDavid Howells }
4880bdaea90SDavid Howells 
4890bdaea90SDavid Howells /**
4900bdaea90SDavid Howells  * inode_permission - Check for access rights to a given inode
4914609e1f1SChristian Brauner  * @idmap:	idmap of the mount the inode was found from
4920bdaea90SDavid Howells  * @inode:	Inode to check permission on
4930bdaea90SDavid Howells  * @mask:	Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
4940bdaea90SDavid Howells  *
4950bdaea90SDavid Howells  * Check for read/write/execute permissions on an inode.  We use fs[ug]id for
4960bdaea90SDavid Howells  * this, letting us set arbitrary permissions for filesystem access without
4970bdaea90SDavid Howells  * changing the "normal" UIDs which are used for other things.
4980bdaea90SDavid Howells  *
4990bdaea90SDavid Howells  * When checking for MAY_APPEND, MAY_WRITE must also be set in @mask.
5000bdaea90SDavid Howells  */
5014609e1f1SChristian Brauner int inode_permission(struct mnt_idmap *idmap,
50247291baaSChristian Brauner 		     struct inode *inode, int mask)
5030bdaea90SDavid Howells {
5040bdaea90SDavid Howells 	int retval;
5050bdaea90SDavid Howells 
5060bdaea90SDavid Howells 	retval = sb_permission(inode->i_sb, inode, mask);
5070bdaea90SDavid Howells 	if (retval)
5080bdaea90SDavid Howells 		return retval;
5094bfd054aSEric Biggers 
5104bfd054aSEric Biggers 	if (unlikely(mask & MAY_WRITE)) {
5114bfd054aSEric Biggers 		/*
5124bfd054aSEric Biggers 		 * Nobody gets write access to an immutable file.
5134bfd054aSEric Biggers 		 */
5144bfd054aSEric Biggers 		if (IS_IMMUTABLE(inode))
5154bfd054aSEric Biggers 			return -EPERM;
5164bfd054aSEric Biggers 
5174bfd054aSEric Biggers 		/*
5184bfd054aSEric Biggers 		 * Updating mtime will likely cause i_uid and i_gid to be
5194bfd054aSEric Biggers 		 * written back improperly if their true value is unknown
5204bfd054aSEric Biggers 		 * to the vfs.
5214bfd054aSEric Biggers 		 */
5224609e1f1SChristian Brauner 		if (HAS_UNMAPPED_ID(idmap, inode))
5234bfd054aSEric Biggers 			return -EACCES;
5244bfd054aSEric Biggers 	}
5254bfd054aSEric Biggers 
5264609e1f1SChristian Brauner 	retval = do_inode_permission(idmap, inode, mask);
5274bfd054aSEric Biggers 	if (retval)
5284bfd054aSEric Biggers 		return retval;
5294bfd054aSEric Biggers 
5304bfd054aSEric Biggers 	retval = devcgroup_inode_permission(inode, mask);
5314bfd054aSEric Biggers 	if (retval)
5324bfd054aSEric Biggers 		return retval;
5334bfd054aSEric Biggers 
5344bfd054aSEric Biggers 	return security_inode_permission(inode, mask);
5350bdaea90SDavid Howells }
5364d359507SAl Viro EXPORT_SYMBOL(inode_permission);
5370bdaea90SDavid Howells 
5380bdaea90SDavid Howells /**
5395dd784d0SJan Blunck  * path_get - get a reference to a path
5405dd784d0SJan Blunck  * @path: path to get the reference to
5415dd784d0SJan Blunck  *
5425dd784d0SJan Blunck  * Given a path increment the reference count to the dentry and the vfsmount.
5435dd784d0SJan Blunck  */
544dcf787f3SAl Viro void path_get(const struct path *path)
5455dd784d0SJan Blunck {
5465dd784d0SJan Blunck 	mntget(path->mnt);
5475dd784d0SJan Blunck 	dget(path->dentry);
5485dd784d0SJan Blunck }
5495dd784d0SJan Blunck EXPORT_SYMBOL(path_get);
5505dd784d0SJan Blunck 
5515dd784d0SJan Blunck /**
5521d957f9bSJan Blunck  * path_put - put a reference to a path
5531d957f9bSJan Blunck  * @path: path to put the reference to
5541d957f9bSJan Blunck  *
5551d957f9bSJan Blunck  * Given a path decrement the reference count to the dentry and the vfsmount.
5561d957f9bSJan Blunck  */
557dcf787f3SAl Viro void path_put(const struct path *path)
5581da177e4SLinus Torvalds {
5591d957f9bSJan Blunck 	dput(path->dentry);
5601d957f9bSJan Blunck 	mntput(path->mnt);
5611da177e4SLinus Torvalds }
5621d957f9bSJan Blunck EXPORT_SYMBOL(path_put);
5631da177e4SLinus Torvalds 
564894bc8c4SAl Viro #define EMBEDDED_LEVELS 2
5651f55a6ecSAl Viro struct nameidata {
5661f55a6ecSAl Viro 	struct path	path;
5671f55a6ecSAl Viro 	struct qstr	last;
5681f55a6ecSAl Viro 	struct path	root;
5691f55a6ecSAl Viro 	struct inode	*inode; /* path.dentry.d_inode */
570bcba1e7dSAl Viro 	unsigned int	flags, state;
57103fa86e9SAl Viro 	unsigned	seq, next_seq, m_seq, r_seq;
5721f55a6ecSAl Viro 	int		last_type;
5731f55a6ecSAl Viro 	unsigned	depth;
574756daf26SNeilBrown 	int		total_link_count;
575697fc6caSAl Viro 	struct saved {
576697fc6caSAl Viro 		struct path link;
577fceef393SAl Viro 		struct delayed_call done;
578697fc6caSAl Viro 		const char *name;
5790450b2d1SAl Viro 		unsigned seq;
580894bc8c4SAl Viro 	} *stack, internal[EMBEDDED_LEVELS];
5819883d185SAl Viro 	struct filename	*name;
5829883d185SAl Viro 	struct nameidata *saved;
5839883d185SAl Viro 	unsigned	root_seq;
5849883d185SAl Viro 	int		dfd;
585a2bd096fSChristian Brauner 	vfsuid_t	dir_vfsuid;
5860f705953SAl Viro 	umode_t		dir_mode;
5873859a271SKees Cook } __randomize_layout;
5881f55a6ecSAl Viro 
589bcba1e7dSAl Viro #define ND_ROOT_PRESET 1
590bcba1e7dSAl Viro #define ND_ROOT_GRABBED 2
591bcba1e7dSAl Viro #define ND_JUMPED 4
592bcba1e7dSAl Viro 
59306422964SAl Viro static void __set_nameidata(struct nameidata *p, int dfd, struct filename *name)
594894bc8c4SAl Viro {
595756daf26SNeilBrown 	struct nameidata *old = current->nameidata;
596756daf26SNeilBrown 	p->stack = p->internal;
5977962c7d1SAl Viro 	p->depth = 0;
598c8a53ee5SAl Viro 	p->dfd = dfd;
599c8a53ee5SAl Viro 	p->name = name;
6007d01ef75SAl Viro 	p->path.mnt = NULL;
6017d01ef75SAl Viro 	p->path.dentry = NULL;
602756daf26SNeilBrown 	p->total_link_count = old ? old->total_link_count : 0;
6039883d185SAl Viro 	p->saved = old;
604756daf26SNeilBrown 	current->nameidata = p;
605894bc8c4SAl Viro }
606894bc8c4SAl Viro 
60706422964SAl Viro static inline void set_nameidata(struct nameidata *p, int dfd, struct filename *name,
60806422964SAl Viro 			  const struct path *root)
60906422964SAl Viro {
61006422964SAl Viro 	__set_nameidata(p, dfd, name);
61106422964SAl Viro 	p->state = 0;
61206422964SAl Viro 	if (unlikely(root)) {
61306422964SAl Viro 		p->state = ND_ROOT_PRESET;
61406422964SAl Viro 		p->root = *root;
61506422964SAl Viro 	}
61606422964SAl Viro }
61706422964SAl Viro 
6189883d185SAl Viro static void restore_nameidata(void)
619894bc8c4SAl Viro {
6209883d185SAl Viro 	struct nameidata *now = current->nameidata, *old = now->saved;
621756daf26SNeilBrown 
622756daf26SNeilBrown 	current->nameidata = old;
623756daf26SNeilBrown 	if (old)
624756daf26SNeilBrown 		old->total_link_count = now->total_link_count;
625e1a63bbcSAl Viro 	if (now->stack != now->internal)
626756daf26SNeilBrown 		kfree(now->stack);
627894bc8c4SAl Viro }
628894bc8c4SAl Viro 
62960ef60c7SAl Viro static bool nd_alloc_stack(struct nameidata *nd)
630894bc8c4SAl Viro {
631bc40aee0SAl Viro 	struct saved *p;
632bc40aee0SAl Viro 
6336da2ec56SKees Cook 	p= kmalloc_array(MAXSYMLINKS, sizeof(struct saved),
63460ef60c7SAl Viro 			 nd->flags & LOOKUP_RCU ? GFP_ATOMIC : GFP_KERNEL);
635bc40aee0SAl Viro 	if (unlikely(!p))
63660ef60c7SAl Viro 		return false;
637894bc8c4SAl Viro 	memcpy(p, nd->internal, sizeof(nd->internal));
638894bc8c4SAl Viro 	nd->stack = p;
63960ef60c7SAl Viro 	return true;
640894bc8c4SAl Viro }
641894bc8c4SAl Viro 
642397d425dSEric W. Biederman /**
6436b03f7edSAl Viro  * path_connected - Verify that a dentry is below mnt.mnt_root
644397d425dSEric W. Biederman  *
645397d425dSEric W. Biederman  * Rename can sometimes move a file or directory outside of a bind
646397d425dSEric W. Biederman  * mount, path_connected allows those cases to be detected.
647397d425dSEric W. Biederman  */
6486b03f7edSAl Viro static bool path_connected(struct vfsmount *mnt, struct dentry *dentry)
649397d425dSEric W. Biederman {
65095dd7758SEric W. Biederman 	struct super_block *sb = mnt->mnt_sb;
651397d425dSEric W. Biederman 
652402dd2cfSChristoph Hellwig 	/* Bind mounts can have disconnected paths */
653402dd2cfSChristoph Hellwig 	if (mnt->mnt_root == sb->s_root)
654397d425dSEric W. Biederman 		return true;
655397d425dSEric W. Biederman 
6566b03f7edSAl Viro 	return is_subdir(dentry, mnt->mnt_root);
657397d425dSEric W. Biederman }
658397d425dSEric W. Biederman 
6597973387aSAl Viro static void drop_links(struct nameidata *nd)
6607973387aSAl Viro {
6617973387aSAl Viro 	int i = nd->depth;
6627973387aSAl Viro 	while (i--) {
6637973387aSAl Viro 		struct saved *last = nd->stack + i;
664fceef393SAl Viro 		do_delayed_call(&last->done);
665fceef393SAl Viro 		clear_delayed_call(&last->done);
6667973387aSAl Viro 	}
6677973387aSAl Viro }
6687973387aSAl Viro 
6696e180327SAl Viro static void leave_rcu(struct nameidata *nd)
6706e180327SAl Viro {
6716e180327SAl Viro 	nd->flags &= ~LOOKUP_RCU;
67203fa86e9SAl Viro 	nd->seq = nd->next_seq = 0;
6736e180327SAl Viro 	rcu_read_unlock();
6746e180327SAl Viro }
6756e180327SAl Viro 
6767973387aSAl Viro static void terminate_walk(struct nameidata *nd)
6777973387aSAl Viro {
6787973387aSAl Viro 	drop_links(nd);
6797973387aSAl Viro 	if (!(nd->flags & LOOKUP_RCU)) {
6807973387aSAl Viro 		int i;
6817973387aSAl Viro 		path_put(&nd->path);
6827973387aSAl Viro 		for (i = 0; i < nd->depth; i++)
6837973387aSAl Viro 			path_put(&nd->stack[i].link);
684bcba1e7dSAl Viro 		if (nd->state & ND_ROOT_GRABBED) {
685102b8af2SAl Viro 			path_put(&nd->root);
686bcba1e7dSAl Viro 			nd->state &= ~ND_ROOT_GRABBED;
687102b8af2SAl Viro 		}
6887973387aSAl Viro 	} else {
6896e180327SAl Viro 		leave_rcu(nd);
6907973387aSAl Viro 	}
6917973387aSAl Viro 	nd->depth = 0;
6927d01ef75SAl Viro 	nd->path.mnt = NULL;
6937d01ef75SAl Viro 	nd->path.dentry = NULL;
6947973387aSAl Viro }
6957973387aSAl Viro 
6967973387aSAl Viro /* path_put is needed afterwards regardless of success or failure */
6972aa38470SAl Viro static bool __legitimize_path(struct path *path, unsigned seq, unsigned mseq)
6987973387aSAl Viro {
6992aa38470SAl Viro 	int res = __legitimize_mnt(path->mnt, mseq);
7007973387aSAl Viro 	if (unlikely(res)) {
7017973387aSAl Viro 		if (res > 0)
7027973387aSAl Viro 			path->mnt = NULL;
7037973387aSAl Viro 		path->dentry = NULL;
7047973387aSAl Viro 		return false;
7057973387aSAl Viro 	}
7067973387aSAl Viro 	if (unlikely(!lockref_get_not_dead(&path->dentry->d_lockref))) {
7077973387aSAl Viro 		path->dentry = NULL;
7087973387aSAl Viro 		return false;
7097973387aSAl Viro 	}
7107973387aSAl Viro 	return !read_seqcount_retry(&path->dentry->d_seq, seq);
7117973387aSAl Viro }
7127973387aSAl Viro 
7132aa38470SAl Viro static inline bool legitimize_path(struct nameidata *nd,
7142aa38470SAl Viro 			    struct path *path, unsigned seq)
7152aa38470SAl Viro {
7165bd73286SAl Viro 	return __legitimize_path(path, seq, nd->m_seq);
7172aa38470SAl Viro }
7182aa38470SAl Viro 
7197973387aSAl Viro static bool legitimize_links(struct nameidata *nd)
7207973387aSAl Viro {
7217973387aSAl Viro 	int i;
722eacd9aa8SAl Viro 	if (unlikely(nd->flags & LOOKUP_CACHED)) {
723eacd9aa8SAl Viro 		drop_links(nd);
724eacd9aa8SAl Viro 		nd->depth = 0;
725eacd9aa8SAl Viro 		return false;
726eacd9aa8SAl Viro 	}
7277973387aSAl Viro 	for (i = 0; i < nd->depth; i++) {
7287973387aSAl Viro 		struct saved *last = nd->stack + i;
7297973387aSAl Viro 		if (unlikely(!legitimize_path(nd, &last->link, last->seq))) {
7307973387aSAl Viro 			drop_links(nd);
7317973387aSAl Viro 			nd->depth = i + 1;
7327973387aSAl Viro 			return false;
7337973387aSAl Viro 		}
7347973387aSAl Viro 	}
7357973387aSAl Viro 	return true;
7367973387aSAl Viro }
7377973387aSAl Viro 
738ee594bffSAl Viro static bool legitimize_root(struct nameidata *nd)
739ee594bffSAl Viro {
740adb21d2bSAleksa Sarai 	/* Nothing to do if nd->root is zero or is managed by the VFS user. */
741bcba1e7dSAl Viro 	if (!nd->root.mnt || (nd->state & ND_ROOT_PRESET))
742ee594bffSAl Viro 		return true;
743bcba1e7dSAl Viro 	nd->state |= ND_ROOT_GRABBED;
744ee594bffSAl Viro 	return legitimize_path(nd, &nd->root, nd->root_seq);
745ee594bffSAl Viro }
746ee594bffSAl Viro 
74719660af7SAl Viro /*
74831e6b01fSNick Piggin  * Path walking has 2 modes, rcu-walk and ref-walk (see
74919660af7SAl Viro  * Documentation/filesystems/path-lookup.txt).  In situations when we can't
75019660af7SAl Viro  * continue in RCU mode, we attempt to drop out of rcu-walk mode and grab
75157e3715cSMike Marshall  * normal reference counts on dentries and vfsmounts to transition to ref-walk
75219660af7SAl Viro  * mode.  Refcounts are grabbed at the last known good point before rcu-walk
75319660af7SAl Viro  * got stuck, so ref-walk may continue from there. If this is not successful
75419660af7SAl Viro  * (eg. a seqcount has changed), then failure is returned and it's up to caller
75519660af7SAl Viro  * to restart the path walk from the beginning in ref-walk mode.
75631e6b01fSNick Piggin  */
75731e6b01fSNick Piggin 
75831e6b01fSNick Piggin /**
759e36cffedSJens Axboe  * try_to_unlazy - try to switch to ref-walk mode.
76019660af7SAl Viro  * @nd: nameidata pathwalk data
761e36cffedSJens Axboe  * Returns: true on success, false on failure
76231e6b01fSNick Piggin  *
763e36cffedSJens Axboe  * try_to_unlazy attempts to legitimize the current nd->path and nd->root
7644675ac39SAl Viro  * for ref-walk mode.
7654675ac39SAl Viro  * Must be called from rcu-walk context.
766e36cffedSJens Axboe  * Nothing should touch nameidata between try_to_unlazy() failure and
7677973387aSAl Viro  * terminate_walk().
76831e6b01fSNick Piggin  */
769e36cffedSJens Axboe static bool try_to_unlazy(struct nameidata *nd)
77031e6b01fSNick Piggin {
77131e6b01fSNick Piggin 	struct dentry *parent = nd->path.dentry;
77231e6b01fSNick Piggin 
77331e6b01fSNick Piggin 	BUG_ON(!(nd->flags & LOOKUP_RCU));
774e5c832d5SLinus Torvalds 
7757973387aSAl Viro 	if (unlikely(!legitimize_links(nd)))
7764675ac39SAl Viro 		goto out1;
77784a2bd39SAl Viro 	if (unlikely(!legitimize_path(nd, &nd->path, nd->seq)))
77884a2bd39SAl Viro 		goto out;
779ee594bffSAl Viro 	if (unlikely(!legitimize_root(nd)))
7804675ac39SAl Viro 		goto out;
7816e180327SAl Viro 	leave_rcu(nd);
7824675ac39SAl Viro 	BUG_ON(nd->inode != parent->d_inode);
783e36cffedSJens Axboe 	return true;
7844675ac39SAl Viro 
78584a2bd39SAl Viro out1:
7864675ac39SAl Viro 	nd->path.mnt = NULL;
7874675ac39SAl Viro 	nd->path.dentry = NULL;
7884675ac39SAl Viro out:
7896e180327SAl Viro 	leave_rcu(nd);
790e36cffedSJens Axboe 	return false;
7914675ac39SAl Viro }
7924675ac39SAl Viro 
7934675ac39SAl Viro /**
794ae66db45SAl Viro  * try_to_unlazy_next - try to switch to ref-walk mode.
7954675ac39SAl Viro  * @nd: nameidata pathwalk data
796ae66db45SAl Viro  * @dentry: next dentry to step into
797ae66db45SAl Viro  * Returns: true on success, false on failure
7984675ac39SAl Viro  *
79930476f7eSTom Rix  * Similar to try_to_unlazy(), but here we have the next dentry already
800ae66db45SAl Viro  * picked by rcu-walk and want to legitimize that in addition to the current
801ae66db45SAl Viro  * nd->path and nd->root for ref-walk mode.  Must be called from rcu-walk context.
802ae66db45SAl Viro  * Nothing should touch nameidata between try_to_unlazy_next() failure and
8034675ac39SAl Viro  * terminate_walk().
8044675ac39SAl Viro  */
80503fa86e9SAl Viro static bool try_to_unlazy_next(struct nameidata *nd, struct dentry *dentry)
8064675ac39SAl Viro {
8077e4745a0SAl Viro 	int res;
8084675ac39SAl Viro 	BUG_ON(!(nd->flags & LOOKUP_RCU));
8094675ac39SAl Viro 
8104675ac39SAl Viro 	if (unlikely(!legitimize_links(nd)))
8114675ac39SAl Viro 		goto out2;
8127e4745a0SAl Viro 	res = __legitimize_mnt(nd->path.mnt, nd->m_seq);
8137e4745a0SAl Viro 	if (unlikely(res)) {
8147e4745a0SAl Viro 		if (res > 0)
8157973387aSAl Viro 			goto out2;
8167e4745a0SAl Viro 		goto out1;
8177e4745a0SAl Viro 	}
8184675ac39SAl Viro 	if (unlikely(!lockref_get_not_dead(&nd->path.dentry->d_lockref)))
8197973387aSAl Viro 		goto out1;
82048a066e7SAl Viro 
82115570086SLinus Torvalds 	/*
8224675ac39SAl Viro 	 * We need to move both the parent and the dentry from the RCU domain
8234675ac39SAl Viro 	 * to be properly refcounted. And the sequence number in the dentry
8244675ac39SAl Viro 	 * validates *both* dentry counters, since we checked the sequence
8254675ac39SAl Viro 	 * number of the parent after we got the child sequence number. So we
8264675ac39SAl Viro 	 * know the parent must still be valid if the child sequence number is
82715570086SLinus Torvalds 	 */
8284675ac39SAl Viro 	if (unlikely(!lockref_get_not_dead(&dentry->d_lockref)))
829e5c832d5SLinus Torvalds 		goto out;
83003fa86e9SAl Viro 	if (read_seqcount_retry(&dentry->d_seq, nd->next_seq))
83184a2bd39SAl Viro 		goto out_dput;
832e5c832d5SLinus Torvalds 	/*
833e5c832d5SLinus Torvalds 	 * Sequence counts matched. Now make sure that the root is
834e5c832d5SLinus Torvalds 	 * still valid and get it if required.
835e5c832d5SLinus Torvalds 	 */
83684a2bd39SAl Viro 	if (unlikely(!legitimize_root(nd)))
83784a2bd39SAl Viro 		goto out_dput;
8386e180327SAl Viro 	leave_rcu(nd);
839ae66db45SAl Viro 	return true;
84019660af7SAl Viro 
8417973387aSAl Viro out2:
8427973387aSAl Viro 	nd->path.mnt = NULL;
8437973387aSAl Viro out1:
8447973387aSAl Viro 	nd->path.dentry = NULL;
845e5c832d5SLinus Torvalds out:
8466e180327SAl Viro 	leave_rcu(nd);
847ae66db45SAl Viro 	return false;
84884a2bd39SAl Viro out_dput:
8496e180327SAl Viro 	leave_rcu(nd);
85084a2bd39SAl Viro 	dput(dentry);
851ae66db45SAl Viro 	return false;
85231e6b01fSNick Piggin }
85331e6b01fSNick Piggin 
8544ce16ef3SAl Viro static inline int d_revalidate(struct dentry *dentry, unsigned int flags)
85534286d66SNick Piggin {
856a89f8337SAl Viro 	if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE))
8574ce16ef3SAl Viro 		return dentry->d_op->d_revalidate(dentry, flags);
858a89f8337SAl Viro 	else
859a89f8337SAl Viro 		return 1;
86034286d66SNick Piggin }
86134286d66SNick Piggin 
8629f1fafeeSAl Viro /**
8639f1fafeeSAl Viro  * complete_walk - successful completion of path walk
8649f1fafeeSAl Viro  * @nd:  pointer nameidata
86539159de2SJeff Layton  *
8669f1fafeeSAl Viro  * If we had been in RCU mode, drop out of it and legitimize nd->path.
8679f1fafeeSAl Viro  * Revalidate the final result, unless we'd already done that during
8689f1fafeeSAl Viro  * the path walk or the filesystem doesn't ask for it.  Return 0 on
8699f1fafeeSAl Viro  * success, -error on failure.  In case of failure caller does not
8709f1fafeeSAl Viro  * need to drop nd->path.
87139159de2SJeff Layton  */
8729f1fafeeSAl Viro static int complete_walk(struct nameidata *nd)
87339159de2SJeff Layton {
87416c2cd71SAl Viro 	struct dentry *dentry = nd->path.dentry;
87539159de2SJeff Layton 	int status;
87639159de2SJeff Layton 
8779f1fafeeSAl Viro 	if (nd->flags & LOOKUP_RCU) {
878adb21d2bSAleksa Sarai 		/*
879adb21d2bSAleksa Sarai 		 * We don't want to zero nd->root for scoped-lookups or
880adb21d2bSAleksa Sarai 		 * externally-managed nd->root.
881adb21d2bSAleksa Sarai 		 */
882bcba1e7dSAl Viro 		if (!(nd->state & ND_ROOT_PRESET))
883bcba1e7dSAl Viro 			if (!(nd->flags & LOOKUP_IS_SCOPED))
8849f1fafeeSAl Viro 				nd->root.mnt = NULL;
8856c6ec2b0SJens Axboe 		nd->flags &= ~LOOKUP_CACHED;
886e36cffedSJens Axboe 		if (!try_to_unlazy(nd))
88748a066e7SAl Viro 			return -ECHILD;
88848a066e7SAl Viro 	}
8899f1fafeeSAl Viro 
890adb21d2bSAleksa Sarai 	if (unlikely(nd->flags & LOOKUP_IS_SCOPED)) {
891adb21d2bSAleksa Sarai 		/*
892adb21d2bSAleksa Sarai 		 * While the guarantee of LOOKUP_IS_SCOPED is (roughly) "don't
893adb21d2bSAleksa Sarai 		 * ever step outside the root during lookup" and should already
894adb21d2bSAleksa Sarai 		 * be guaranteed by the rest of namei, we want to avoid a namei
895adb21d2bSAleksa Sarai 		 * BUG resulting in userspace being given a path that was not
896adb21d2bSAleksa Sarai 		 * scoped within the root at some point during the lookup.
897adb21d2bSAleksa Sarai 		 *
898adb21d2bSAleksa Sarai 		 * So, do a final sanity-check to make sure that in the
899adb21d2bSAleksa Sarai 		 * worst-case scenario (a complete bypass of LOOKUP_IS_SCOPED)
900adb21d2bSAleksa Sarai 		 * we won't silently return an fd completely outside of the
901adb21d2bSAleksa Sarai 		 * requested root to userspace.
902adb21d2bSAleksa Sarai 		 *
903adb21d2bSAleksa Sarai 		 * Userspace could move the path outside the root after this
904adb21d2bSAleksa Sarai 		 * check, but as discussed elsewhere this is not a concern (the
905adb21d2bSAleksa Sarai 		 * resolved file was inside the root at some point).
906adb21d2bSAleksa Sarai 		 */
907adb21d2bSAleksa Sarai 		if (!path_is_under(&nd->path, &nd->root))
908adb21d2bSAleksa Sarai 			return -EXDEV;
909adb21d2bSAleksa Sarai 	}
910adb21d2bSAleksa Sarai 
911bcba1e7dSAl Viro 	if (likely(!(nd->state & ND_JUMPED)))
91239159de2SJeff Layton 		return 0;
91339159de2SJeff Layton 
914ecf3d1f1SJeff Layton 	if (likely(!(dentry->d_flags & DCACHE_OP_WEAK_REVALIDATE)))
91516c2cd71SAl Viro 		return 0;
91616c2cd71SAl Viro 
917ecf3d1f1SJeff Layton 	status = dentry->d_op->d_weak_revalidate(dentry, nd->flags);
91839159de2SJeff Layton 	if (status > 0)
91939159de2SJeff Layton 		return 0;
92039159de2SJeff Layton 
92116c2cd71SAl Viro 	if (!status)
92239159de2SJeff Layton 		status = -ESTALE;
92316c2cd71SAl Viro 
92439159de2SJeff Layton 	return status;
92539159de2SJeff Layton }
92639159de2SJeff Layton 
927740a1678SAleksa Sarai static int set_root(struct nameidata *nd)
9282a737871SAl Viro {
92931e6b01fSNick Piggin 	struct fs_struct *fs = current->fs;
9309e6697e2SAl Viro 
931adb21d2bSAleksa Sarai 	/*
932adb21d2bSAleksa Sarai 	 * Jumping to the real root in a scoped-lookup is a BUG in namei, but we
933adb21d2bSAleksa Sarai 	 * still have to ensure it doesn't happen because it will cause a breakout
934adb21d2bSAleksa Sarai 	 * from the dirfd.
935adb21d2bSAleksa Sarai 	 */
936adb21d2bSAleksa Sarai 	if (WARN_ON(nd->flags & LOOKUP_IS_SCOPED))
937adb21d2bSAleksa Sarai 		return -ENOTRECOVERABLE;
938adb21d2bSAleksa Sarai 
9399e6697e2SAl Viro 	if (nd->flags & LOOKUP_RCU) {
9408f47a016SAl Viro 		unsigned seq;
941c28cc364SNick Piggin 
942c28cc364SNick Piggin 		do {
943c28cc364SNick Piggin 			seq = read_seqcount_begin(&fs->seq);
94431e6b01fSNick Piggin 			nd->root = fs->root;
9458f47a016SAl Viro 			nd->root_seq = __read_seqcount_begin(&nd->root.dentry->d_seq);
946c28cc364SNick Piggin 		} while (read_seqcount_retry(&fs->seq, seq));
9479e6697e2SAl Viro 	} else {
9489e6697e2SAl Viro 		get_fs_root(fs, &nd->root);
949bcba1e7dSAl Viro 		nd->state |= ND_ROOT_GRABBED;
9509e6697e2SAl Viro 	}
951740a1678SAleksa Sarai 	return 0;
95231e6b01fSNick Piggin }
95331e6b01fSNick Piggin 
954248fb5b9SAl Viro static int nd_jump_root(struct nameidata *nd)
955248fb5b9SAl Viro {
956adb21d2bSAleksa Sarai 	if (unlikely(nd->flags & LOOKUP_BENEATH))
957adb21d2bSAleksa Sarai 		return -EXDEV;
95872ba2929SAleksa Sarai 	if (unlikely(nd->flags & LOOKUP_NO_XDEV)) {
95972ba2929SAleksa Sarai 		/* Absolute path arguments to path_init() are allowed. */
96072ba2929SAleksa Sarai 		if (nd->path.mnt != NULL && nd->path.mnt != nd->root.mnt)
96172ba2929SAleksa Sarai 			return -EXDEV;
96272ba2929SAleksa Sarai 	}
963740a1678SAleksa Sarai 	if (!nd->root.mnt) {
964740a1678SAleksa Sarai 		int error = set_root(nd);
965740a1678SAleksa Sarai 		if (error)
966740a1678SAleksa Sarai 			return error;
967740a1678SAleksa Sarai 	}
968248fb5b9SAl Viro 	if (nd->flags & LOOKUP_RCU) {
969248fb5b9SAl Viro 		struct dentry *d;
970248fb5b9SAl Viro 		nd->path = nd->root;
971248fb5b9SAl Viro 		d = nd->path.dentry;
972248fb5b9SAl Viro 		nd->inode = d->d_inode;
973248fb5b9SAl Viro 		nd->seq = nd->root_seq;
97482ef0698SAl Viro 		if (read_seqcount_retry(&d->d_seq, nd->seq))
975248fb5b9SAl Viro 			return -ECHILD;
976248fb5b9SAl Viro 	} else {
977248fb5b9SAl Viro 		path_put(&nd->path);
978248fb5b9SAl Viro 		nd->path = nd->root;
979248fb5b9SAl Viro 		path_get(&nd->path);
980248fb5b9SAl Viro 		nd->inode = nd->path.dentry->d_inode;
981248fb5b9SAl Viro 	}
982bcba1e7dSAl Viro 	nd->state |= ND_JUMPED;
983248fb5b9SAl Viro 	return 0;
984248fb5b9SAl Viro }
985248fb5b9SAl Viro 
986b5fb63c1SChristoph Hellwig /*
9876b255391SAl Viro  * Helper to directly jump to a known parsed path from ->get_link,
988b5fb63c1SChristoph Hellwig  * caller must have taken a reference to path beforehand.
989b5fb63c1SChristoph Hellwig  */
990ea4af4aaSAl Viro int nd_jump_link(const struct path *path)
991b5fb63c1SChristoph Hellwig {
9924b99d499SAleksa Sarai 	int error = -ELOOP;
9936e77137bSAl Viro 	struct nameidata *nd = current->nameidata;
994b5fb63c1SChristoph Hellwig 
9954b99d499SAleksa Sarai 	if (unlikely(nd->flags & LOOKUP_NO_MAGICLINKS))
9964b99d499SAleksa Sarai 		goto err;
9974b99d499SAleksa Sarai 
99872ba2929SAleksa Sarai 	error = -EXDEV;
99972ba2929SAleksa Sarai 	if (unlikely(nd->flags & LOOKUP_NO_XDEV)) {
100072ba2929SAleksa Sarai 		if (nd->path.mnt != path->mnt)
100172ba2929SAleksa Sarai 			goto err;
100272ba2929SAleksa Sarai 	}
1003adb21d2bSAleksa Sarai 	/* Not currently safe for scoped-lookups. */
1004adb21d2bSAleksa Sarai 	if (unlikely(nd->flags & LOOKUP_IS_SCOPED))
1005adb21d2bSAleksa Sarai 		goto err;
100672ba2929SAleksa Sarai 
10074b99d499SAleksa Sarai 	path_put(&nd->path);
1008b5fb63c1SChristoph Hellwig 	nd->path = *path;
1009b5fb63c1SChristoph Hellwig 	nd->inode = nd->path.dentry->d_inode;
1010bcba1e7dSAl Viro 	nd->state |= ND_JUMPED;
10111bc82070SAleksa Sarai 	return 0;
10124b99d499SAleksa Sarai 
10134b99d499SAleksa Sarai err:
10144b99d499SAleksa Sarai 	path_put(path);
10154b99d499SAleksa Sarai 	return error;
1016b5fb63c1SChristoph Hellwig }
1017b5fb63c1SChristoph Hellwig 
1018b9ff4429SAl Viro static inline void put_link(struct nameidata *nd)
1019574197e0SAl Viro {
102021c3003dSAl Viro 	struct saved *last = nd->stack + --nd->depth;
1021fceef393SAl Viro 	do_delayed_call(&last->done);
10226548fae2SAl Viro 	if (!(nd->flags & LOOKUP_RCU))
1023b9ff4429SAl Viro 		path_put(&last->link);
1024574197e0SAl Viro }
1025574197e0SAl Viro 
10269c011be1SLuis Chamberlain static int sysctl_protected_symlinks __read_mostly;
10279c011be1SLuis Chamberlain static int sysctl_protected_hardlinks __read_mostly;
10289c011be1SLuis Chamberlain static int sysctl_protected_fifos __read_mostly;
10299c011be1SLuis Chamberlain static int sysctl_protected_regular __read_mostly;
10309c011be1SLuis Chamberlain 
10319c011be1SLuis Chamberlain #ifdef CONFIG_SYSCTL
10329c011be1SLuis Chamberlain static struct ctl_table namei_sysctls[] = {
10339c011be1SLuis Chamberlain 	{
10349c011be1SLuis Chamberlain 		.procname	= "protected_symlinks",
10359c011be1SLuis Chamberlain 		.data		= &sysctl_protected_symlinks,
10369c011be1SLuis Chamberlain 		.maxlen		= sizeof(int),
1037c7031c14SJulius Hemanth Pitti 		.mode		= 0644,
10389c011be1SLuis Chamberlain 		.proc_handler	= proc_dointvec_minmax,
10399c011be1SLuis Chamberlain 		.extra1		= SYSCTL_ZERO,
10409c011be1SLuis Chamberlain 		.extra2		= SYSCTL_ONE,
10419c011be1SLuis Chamberlain 	},
10429c011be1SLuis Chamberlain 	{
10439c011be1SLuis Chamberlain 		.procname	= "protected_hardlinks",
10449c011be1SLuis Chamberlain 		.data		= &sysctl_protected_hardlinks,
10459c011be1SLuis Chamberlain 		.maxlen		= sizeof(int),
1046c7031c14SJulius Hemanth Pitti 		.mode		= 0644,
10479c011be1SLuis Chamberlain 		.proc_handler	= proc_dointvec_minmax,
10489c011be1SLuis Chamberlain 		.extra1		= SYSCTL_ZERO,
10499c011be1SLuis Chamberlain 		.extra2		= SYSCTL_ONE,
10509c011be1SLuis Chamberlain 	},
10519c011be1SLuis Chamberlain 	{
10529c011be1SLuis Chamberlain 		.procname	= "protected_fifos",
10539c011be1SLuis Chamberlain 		.data		= &sysctl_protected_fifos,
10549c011be1SLuis Chamberlain 		.maxlen		= sizeof(int),
1055c7031c14SJulius Hemanth Pitti 		.mode		= 0644,
10569c011be1SLuis Chamberlain 		.proc_handler	= proc_dointvec_minmax,
10579c011be1SLuis Chamberlain 		.extra1		= SYSCTL_ZERO,
10589c011be1SLuis Chamberlain 		.extra2		= SYSCTL_TWO,
10599c011be1SLuis Chamberlain 	},
10609c011be1SLuis Chamberlain 	{
10619c011be1SLuis Chamberlain 		.procname	= "protected_regular",
10629c011be1SLuis Chamberlain 		.data		= &sysctl_protected_regular,
10639c011be1SLuis Chamberlain 		.maxlen		= sizeof(int),
1064c7031c14SJulius Hemanth Pitti 		.mode		= 0644,
10659c011be1SLuis Chamberlain 		.proc_handler	= proc_dointvec_minmax,
10669c011be1SLuis Chamberlain 		.extra1		= SYSCTL_ZERO,
10679c011be1SLuis Chamberlain 		.extra2		= SYSCTL_TWO,
10689c011be1SLuis Chamberlain 	},
10699c011be1SLuis Chamberlain 	{ }
10709c011be1SLuis Chamberlain };
10719c011be1SLuis Chamberlain 
10729c011be1SLuis Chamberlain static int __init init_fs_namei_sysctls(void)
10739c011be1SLuis Chamberlain {
10749c011be1SLuis Chamberlain 	register_sysctl_init("fs", namei_sysctls);
10759c011be1SLuis Chamberlain 	return 0;
10769c011be1SLuis Chamberlain }
10779c011be1SLuis Chamberlain fs_initcall(init_fs_namei_sysctls);
10789c011be1SLuis Chamberlain 
10799c011be1SLuis Chamberlain #endif /* CONFIG_SYSCTL */
1080800179c9SKees Cook 
1081800179c9SKees Cook /**
1082800179c9SKees Cook  * may_follow_link - Check symlink following for unsafe situations
108355852635SRandy Dunlap  * @nd: nameidata pathwalk data
1084800179c9SKees Cook  *
1085800179c9SKees Cook  * In the case of the sysctl_protected_symlinks sysctl being enabled,
1086800179c9SKees Cook  * CAP_DAC_OVERRIDE needs to be specifically ignored if the symlink is
1087800179c9SKees Cook  * in a sticky world-writable directory. This is to protect privileged
1088800179c9SKees Cook  * processes from failing races against path names that may change out
1089800179c9SKees Cook  * from under them by way of other users creating malicious symlinks.
1090800179c9SKees Cook  * It will permit symlinks to be followed only when outside a sticky
1091800179c9SKees Cook  * world-writable directory, or when the uid of the symlink and follower
1092800179c9SKees Cook  * match, or when the directory owner matches the symlink's owner.
1093800179c9SKees Cook  *
1094800179c9SKees Cook  * Returns 0 if following the symlink is allowed, -ve on error.
1095800179c9SKees Cook  */
1096ad6cc4c3SAl Viro static inline int may_follow_link(struct nameidata *nd, const struct inode *inode)
1097800179c9SKees Cook {
1098e67fe633SChristian Brauner 	struct mnt_idmap *idmap;
1099a2bd096fSChristian Brauner 	vfsuid_t vfsuid;
1100ba73d987SChristian Brauner 
1101800179c9SKees Cook 	if (!sysctl_protected_symlinks)
1102800179c9SKees Cook 		return 0;
1103800179c9SKees Cook 
1104e67fe633SChristian Brauner 	idmap = mnt_idmap(nd->path.mnt);
1105e67fe633SChristian Brauner 	vfsuid = i_uid_into_vfsuid(idmap, inode);
1106800179c9SKees Cook 	/* Allowed if owner and follower match. */
1107a2bd096fSChristian Brauner 	if (vfsuid_eq_kuid(vfsuid, current_fsuid()))
1108800179c9SKees Cook 		return 0;
1109800179c9SKees Cook 
1110800179c9SKees Cook 	/* Allowed if parent directory not sticky and world-writable. */
11110f705953SAl Viro 	if ((nd->dir_mode & (S_ISVTX|S_IWOTH)) != (S_ISVTX|S_IWOTH))
1112800179c9SKees Cook 		return 0;
1113800179c9SKees Cook 
1114800179c9SKees Cook 	/* Allowed if parent directory and link owner match. */
1115a2bd096fSChristian Brauner 	if (vfsuid_valid(nd->dir_vfsuid) && vfsuid_eq(nd->dir_vfsuid, vfsuid))
1116800179c9SKees Cook 		return 0;
1117800179c9SKees Cook 
111831956502SAl Viro 	if (nd->flags & LOOKUP_RCU)
111931956502SAl Viro 		return -ECHILD;
112031956502SAl Viro 
1121ea841bafSRichard Guy Briggs 	audit_inode(nd->name, nd->stack[0].link.dentry, 0);
1122245d7369SKees Cook 	audit_log_path_denied(AUDIT_ANOM_LINK, "follow_link");
1123800179c9SKees Cook 	return -EACCES;
1124800179c9SKees Cook }
1125800179c9SKees Cook 
1126800179c9SKees Cook /**
1127800179c9SKees Cook  * safe_hardlink_source - Check for safe hardlink conditions
11284609e1f1SChristian Brauner  * @idmap: idmap of the mount the inode was found from
1129800179c9SKees Cook  * @inode: the source inode to hardlink from
1130800179c9SKees Cook  *
1131800179c9SKees Cook  * Return false if at least one of the following conditions:
1132800179c9SKees Cook  *    - inode is not a regular file
1133800179c9SKees Cook  *    - inode is setuid
1134800179c9SKees Cook  *    - inode is setgid and group-exec
1135800179c9SKees Cook  *    - access failure for read and write
1136800179c9SKees Cook  *
1137800179c9SKees Cook  * Otherwise returns true.
1138800179c9SKees Cook  */
11394609e1f1SChristian Brauner static bool safe_hardlink_source(struct mnt_idmap *idmap,
1140ba73d987SChristian Brauner 				 struct inode *inode)
1141800179c9SKees Cook {
1142800179c9SKees Cook 	umode_t mode = inode->i_mode;
1143800179c9SKees Cook 
1144800179c9SKees Cook 	/* Special files should not get pinned to the filesystem. */
1145800179c9SKees Cook 	if (!S_ISREG(mode))
1146800179c9SKees Cook 		return false;
1147800179c9SKees Cook 
1148800179c9SKees Cook 	/* Setuid files should not get pinned to the filesystem. */
1149800179c9SKees Cook 	if (mode & S_ISUID)
1150800179c9SKees Cook 		return false;
1151800179c9SKees Cook 
1152800179c9SKees Cook 	/* Executable setgid files should not get pinned to the filesystem. */
1153800179c9SKees Cook 	if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP))
1154800179c9SKees Cook 		return false;
1155800179c9SKees Cook 
1156800179c9SKees Cook 	/* Hardlinking to unreadable or unwritable sources is dangerous. */
11574609e1f1SChristian Brauner 	if (inode_permission(idmap, inode, MAY_READ | MAY_WRITE))
1158800179c9SKees Cook 		return false;
1159800179c9SKees Cook 
1160800179c9SKees Cook 	return true;
1161800179c9SKees Cook }
1162800179c9SKees Cook 
1163800179c9SKees Cook /**
1164800179c9SKees Cook  * may_linkat - Check permissions for creating a hardlink
11654609e1f1SChristian Brauner  * @idmap: idmap of the mount the inode was found from
1166800179c9SKees Cook  * @link:  the source to hardlink from
1167800179c9SKees Cook  *
1168800179c9SKees Cook  * Block hardlink when all of:
1169800179c9SKees Cook  *  - sysctl_protected_hardlinks enabled
1170800179c9SKees Cook  *  - fsuid does not match inode
1171800179c9SKees Cook  *  - hardlink source is unsafe (see safe_hardlink_source() above)
1172f2ca3796SDirk Steinmetz  *  - not CAP_FOWNER in a namespace with the inode owner uid mapped
1173800179c9SKees Cook  *
11744609e1f1SChristian Brauner  * If the inode has been found through an idmapped mount the idmap of
11754609e1f1SChristian Brauner  * the vfsmount must be passed through @idmap. This function will then take
11764609e1f1SChristian Brauner  * care to map the inode according to @idmap before checking permissions.
1177ba73d987SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
11784609e1f1SChristian Brauner  * raw inode simply pass @nop_mnt_idmap.
1179ba73d987SChristian Brauner  *
1180800179c9SKees Cook  * Returns 0 if successful, -ve on error.
1181800179c9SKees Cook  */
11824609e1f1SChristian Brauner int may_linkat(struct mnt_idmap *idmap, const struct path *link)
1183800179c9SKees Cook {
1184593d1ce8SEric W. Biederman 	struct inode *inode = link->dentry->d_inode;
1185593d1ce8SEric W. Biederman 
1186593d1ce8SEric W. Biederman 	/* Inode writeback is not safe when the uid or gid are invalid. */
1187e67fe633SChristian Brauner 	if (!vfsuid_valid(i_uid_into_vfsuid(idmap, inode)) ||
1188e67fe633SChristian Brauner 	    !vfsgid_valid(i_gid_into_vfsgid(idmap, inode)))
1189593d1ce8SEric W. Biederman 		return -EOVERFLOW;
1190800179c9SKees Cook 
1191800179c9SKees Cook 	if (!sysctl_protected_hardlinks)
1192800179c9SKees Cook 		return 0;
1193800179c9SKees Cook 
1194800179c9SKees Cook 	/* Source inode owner (or CAP_FOWNER) can hardlink all they like,
1195800179c9SKees Cook 	 * otherwise, it must be a safe source.
1196800179c9SKees Cook 	 */
11974609e1f1SChristian Brauner 	if (safe_hardlink_source(idmap, inode) ||
119801beba79SChristian Brauner 	    inode_owner_or_capable(idmap, inode))
1199800179c9SKees Cook 		return 0;
1200800179c9SKees Cook 
1201245d7369SKees Cook 	audit_log_path_denied(AUDIT_ANOM_LINK, "linkat");
1202800179c9SKees Cook 	return -EPERM;
1203800179c9SKees Cook }
1204800179c9SKees Cook 
120530aba665SSalvatore Mesoraca /**
120630aba665SSalvatore Mesoraca  * may_create_in_sticky - Check whether an O_CREAT open in a sticky directory
120730aba665SSalvatore Mesoraca  *			  should be allowed, or not, on files that already
120830aba665SSalvatore Mesoraca  *			  exist.
1209e67fe633SChristian Brauner  * @idmap: idmap of the mount the inode was found from
12102111c3c0SRandy Dunlap  * @nd: nameidata pathwalk data
121130aba665SSalvatore Mesoraca  * @inode: the inode of the file to open
121230aba665SSalvatore Mesoraca  *
121330aba665SSalvatore Mesoraca  * Block an O_CREAT open of a FIFO (or a regular file) when:
121430aba665SSalvatore Mesoraca  *   - sysctl_protected_fifos (or sysctl_protected_regular) is enabled
121530aba665SSalvatore Mesoraca  *   - the file already exists
121630aba665SSalvatore Mesoraca  *   - we are in a sticky directory
121730aba665SSalvatore Mesoraca  *   - we don't own the file
121830aba665SSalvatore Mesoraca  *   - the owner of the directory doesn't own the file
121930aba665SSalvatore Mesoraca  *   - the directory is world writable
122030aba665SSalvatore Mesoraca  * If the sysctl_protected_fifos (or sysctl_protected_regular) is set to 2
122130aba665SSalvatore Mesoraca  * the directory doesn't have to be world writable: being group writable will
122230aba665SSalvatore Mesoraca  * be enough.
122330aba665SSalvatore Mesoraca  *
1224e67fe633SChristian Brauner  * If the inode has been found through an idmapped mount the idmap of
1225e67fe633SChristian Brauner  * the vfsmount must be passed through @idmap. This function will then take
1226e67fe633SChristian Brauner  * care to map the inode according to @idmap before checking permissions.
1227ba73d987SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
1228e67fe633SChristian Brauner  * raw inode simply pass @nop_mnt_idmap.
1229ba73d987SChristian Brauner  *
123030aba665SSalvatore Mesoraca  * Returns 0 if the open is allowed, -ve on error.
123130aba665SSalvatore Mesoraca  */
1232e67fe633SChristian Brauner static int may_create_in_sticky(struct mnt_idmap *idmap,
1233ba73d987SChristian Brauner 				struct nameidata *nd, struct inode *const inode)
123430aba665SSalvatore Mesoraca {
1235ba73d987SChristian Brauner 	umode_t dir_mode = nd->dir_mode;
1236a2bd096fSChristian Brauner 	vfsuid_t dir_vfsuid = nd->dir_vfsuid;
1237ba73d987SChristian Brauner 
123830aba665SSalvatore Mesoraca 	if ((!sysctl_protected_fifos && S_ISFIFO(inode->i_mode)) ||
123930aba665SSalvatore Mesoraca 	    (!sysctl_protected_regular && S_ISREG(inode->i_mode)) ||
1240d0cb5018SAl Viro 	    likely(!(dir_mode & S_ISVTX)) ||
1241e67fe633SChristian Brauner 	    vfsuid_eq(i_uid_into_vfsuid(idmap, inode), dir_vfsuid) ||
1242e67fe633SChristian Brauner 	    vfsuid_eq_kuid(i_uid_into_vfsuid(idmap, inode), current_fsuid()))
124330aba665SSalvatore Mesoraca 		return 0;
124430aba665SSalvatore Mesoraca 
1245d0cb5018SAl Viro 	if (likely(dir_mode & 0002) ||
1246d0cb5018SAl Viro 	    (dir_mode & 0020 &&
124730aba665SSalvatore Mesoraca 	     ((sysctl_protected_fifos >= 2 && S_ISFIFO(inode->i_mode)) ||
124830aba665SSalvatore Mesoraca 	      (sysctl_protected_regular >= 2 && S_ISREG(inode->i_mode))))) {
1249245d7369SKees Cook 		const char *operation = S_ISFIFO(inode->i_mode) ?
1250245d7369SKees Cook 					"sticky_create_fifo" :
1251245d7369SKees Cook 					"sticky_create_regular";
1252245d7369SKees Cook 		audit_log_path_denied(AUDIT_ANOM_CREAT, operation);
125330aba665SSalvatore Mesoraca 		return -EACCES;
125430aba665SSalvatore Mesoraca 	}
125530aba665SSalvatore Mesoraca 	return 0;
125630aba665SSalvatore Mesoraca }
125730aba665SSalvatore Mesoraca 
1258f015f126SDavid Howells /*
1259f015f126SDavid Howells  * follow_up - Find the mountpoint of path's vfsmount
1260f015f126SDavid Howells  *
1261f015f126SDavid Howells  * Given a path, find the mountpoint of its source file system.
1262f015f126SDavid Howells  * Replace @path with the path of the mountpoint in the parent mount.
1263f015f126SDavid Howells  * Up is towards /.
1264f015f126SDavid Howells  *
1265f015f126SDavid Howells  * Return 1 if we went up a level and 0 if we were already at the
1266f015f126SDavid Howells  * root.
1267f015f126SDavid Howells  */
1268bab77ebfSAl Viro int follow_up(struct path *path)
12691da177e4SLinus Torvalds {
12700714a533SAl Viro 	struct mount *mnt = real_mount(path->mnt);
12710714a533SAl Viro 	struct mount *parent;
12721da177e4SLinus Torvalds 	struct dentry *mountpoint;
127399b7db7bSNick Piggin 
127448a066e7SAl Viro 	read_seqlock_excl(&mount_lock);
12750714a533SAl Viro 	parent = mnt->mnt_parent;
12763c0a6163SAl Viro 	if (parent == mnt) {
127748a066e7SAl Viro 		read_sequnlock_excl(&mount_lock);
12781da177e4SLinus Torvalds 		return 0;
12791da177e4SLinus Torvalds 	}
12800714a533SAl Viro 	mntget(&parent->mnt);
1281a73324daSAl Viro 	mountpoint = dget(mnt->mnt_mountpoint);
128248a066e7SAl Viro 	read_sequnlock_excl(&mount_lock);
1283bab77ebfSAl Viro 	dput(path->dentry);
1284bab77ebfSAl Viro 	path->dentry = mountpoint;
1285bab77ebfSAl Viro 	mntput(path->mnt);
12860714a533SAl Viro 	path->mnt = &parent->mnt;
12871da177e4SLinus Torvalds 	return 1;
12881da177e4SLinus Torvalds }
12894d359507SAl Viro EXPORT_SYMBOL(follow_up);
12901da177e4SLinus Torvalds 
12917ef482faSAl Viro static bool choose_mountpoint_rcu(struct mount *m, const struct path *root,
12927ef482faSAl Viro 				  struct path *path, unsigned *seqp)
12937ef482faSAl Viro {
12947ef482faSAl Viro 	while (mnt_has_parent(m)) {
12957ef482faSAl Viro 		struct dentry *mountpoint = m->mnt_mountpoint;
12967ef482faSAl Viro 
12977ef482faSAl Viro 		m = m->mnt_parent;
12987ef482faSAl Viro 		if (unlikely(root->dentry == mountpoint &&
12997ef482faSAl Viro 			     root->mnt == &m->mnt))
13007ef482faSAl Viro 			break;
13017ef482faSAl Viro 		if (mountpoint != m->mnt.mnt_root) {
13027ef482faSAl Viro 			path->mnt = &m->mnt;
13037ef482faSAl Viro 			path->dentry = mountpoint;
13047ef482faSAl Viro 			*seqp = read_seqcount_begin(&mountpoint->d_seq);
13057ef482faSAl Viro 			return true;
13067ef482faSAl Viro 		}
13077ef482faSAl Viro 	}
13087ef482faSAl Viro 	return false;
13097ef482faSAl Viro }
13107ef482faSAl Viro 
13112aa38470SAl Viro static bool choose_mountpoint(struct mount *m, const struct path *root,
13122aa38470SAl Viro 			      struct path *path)
13132aa38470SAl Viro {
13142aa38470SAl Viro 	bool found;
13152aa38470SAl Viro 
13162aa38470SAl Viro 	rcu_read_lock();
13172aa38470SAl Viro 	while (1) {
13182aa38470SAl Viro 		unsigned seq, mseq = read_seqbegin(&mount_lock);
13192aa38470SAl Viro 
13202aa38470SAl Viro 		found = choose_mountpoint_rcu(m, root, path, &seq);
13212aa38470SAl Viro 		if (unlikely(!found)) {
13222aa38470SAl Viro 			if (!read_seqretry(&mount_lock, mseq))
13232aa38470SAl Viro 				break;
13242aa38470SAl Viro 		} else {
13252aa38470SAl Viro 			if (likely(__legitimize_path(path, seq, mseq)))
13262aa38470SAl Viro 				break;
13272aa38470SAl Viro 			rcu_read_unlock();
13282aa38470SAl Viro 			path_put(path);
13292aa38470SAl Viro 			rcu_read_lock();
13302aa38470SAl Viro 		}
13312aa38470SAl Viro 	}
13322aa38470SAl Viro 	rcu_read_unlock();
13332aa38470SAl Viro 	return found;
13342aa38470SAl Viro }
13352aa38470SAl Viro 
1336b5c84bf6SNick Piggin /*
13379875cf80SDavid Howells  * Perform an automount
13389875cf80SDavid Howells  * - return -EISDIR to tell follow_managed() to stop and return the path we
13399875cf80SDavid Howells  *   were called with.
13401da177e4SLinus Torvalds  */
13411c9f5e06SAl Viro static int follow_automount(struct path *path, int *count, unsigned lookup_flags)
134231e6b01fSNick Piggin {
134325e195aaSAl Viro 	struct dentry *dentry = path->dentry;
13449875cf80SDavid Howells 
13450ec26fd0SMiklos Szeredi 	/* We don't want to mount if someone's just doing a stat -
13460ec26fd0SMiklos Szeredi 	 * unless they're stat'ing a directory and appended a '/' to
13470ec26fd0SMiklos Szeredi 	 * the name.
13480ec26fd0SMiklos Szeredi 	 *
13490ec26fd0SMiklos Szeredi 	 * We do, however, want to mount if someone wants to open or
13505a30d8a2SDavid Howells 	 * create a file of any type under the mountpoint, wants to
13510ec26fd0SMiklos Szeredi 	 * traverse through the mountpoint or wants to open the
13520ec26fd0SMiklos Szeredi 	 * mounted directory.  Also, autofs may mark negative dentries
13530ec26fd0SMiklos Szeredi 	 * as being automount points.  These will need the attentions
13540ec26fd0SMiklos Szeredi 	 * of the daemon to instantiate them before they can be used.
13555a30d8a2SDavid Howells 	 */
13561c9f5e06SAl Viro 	if (!(lookup_flags & (LOOKUP_PARENT | LOOKUP_DIRECTORY |
13575d38f049SIan Kent 			   LOOKUP_OPEN | LOOKUP_CREATE | LOOKUP_AUTOMOUNT)) &&
135825e195aaSAl Viro 	    dentry->d_inode)
13599875cf80SDavid Howells 		return -EISDIR;
13600ec26fd0SMiklos Szeredi 
13611c9f5e06SAl Viro 	if (count && (*count)++ >= MAXSYMLINKS)
13629875cf80SDavid Howells 		return -ELOOP;
13639875cf80SDavid Howells 
136425e195aaSAl Viro 	return finish_automount(dentry->d_op->d_automount(path), path);
1365ea5b778aSDavid Howells }
13669875cf80SDavid Howells 
13679875cf80SDavid Howells /*
13689deed3ebSAl Viro  * mount traversal - out-of-line part.  One note on ->d_flags accesses -
13699deed3ebSAl Viro  * dentries are pinned but not locked here, so negative dentry can go
13709deed3ebSAl Viro  * positive right under us.  Use of smp_load_acquire() provides a barrier
13719deed3ebSAl Viro  * sufficient for ->d_inode and ->d_flags consistency.
13729875cf80SDavid Howells  */
13739deed3ebSAl Viro static int __traverse_mounts(struct path *path, unsigned flags, bool *jumped,
13749deed3ebSAl Viro 			     int *count, unsigned lookup_flags)
13759875cf80SDavid Howells {
13769deed3ebSAl Viro 	struct vfsmount *mnt = path->mnt;
13779875cf80SDavid Howells 	bool need_mntput = false;
13788aef1884SAl Viro 	int ret = 0;
13799875cf80SDavid Howells 
13809deed3ebSAl Viro 	while (flags & DCACHE_MANAGED_DENTRY) {
1381cc53ce53SDavid Howells 		/* Allow the filesystem to manage the transit without i_mutex
1382cc53ce53SDavid Howells 		 * being held. */
1383d41efb52SAl Viro 		if (flags & DCACHE_MANAGE_TRANSIT) {
1384fb5f51c7SIan Kent 			ret = path->dentry->d_op->d_manage(path, false);
1385508c8772SAl Viro 			flags = smp_load_acquire(&path->dentry->d_flags);
1386cc53ce53SDavid Howells 			if (ret < 0)
13878aef1884SAl Viro 				break;
1388cc53ce53SDavid Howells 		}
1389cc53ce53SDavid Howells 
13909deed3ebSAl Viro 		if (flags & DCACHE_MOUNTED) {	// something's mounted on it..
13919875cf80SDavid Howells 			struct vfsmount *mounted = lookup_mnt(path);
13929deed3ebSAl Viro 			if (mounted) {		// ... in our namespace
13939875cf80SDavid Howells 				dput(path->dentry);
13949875cf80SDavid Howells 				if (need_mntput)
1395463ffb2eSAl Viro 					mntput(path->mnt);
1396463ffb2eSAl Viro 				path->mnt = mounted;
1397463ffb2eSAl Viro 				path->dentry = dget(mounted->mnt_root);
13989deed3ebSAl Viro 				// here we know it's positive
13999deed3ebSAl Viro 				flags = path->dentry->d_flags;
14009875cf80SDavid Howells 				need_mntput = true;
14019875cf80SDavid Howells 				continue;
1402463ffb2eSAl Viro 			}
14031da177e4SLinus Torvalds 		}
14049875cf80SDavid Howells 
14059deed3ebSAl Viro 		if (!(flags & DCACHE_NEED_AUTOMOUNT))
14069deed3ebSAl Viro 			break;
14079deed3ebSAl Viro 
14089deed3ebSAl Viro 		// uncovered automount point
14099deed3ebSAl Viro 		ret = follow_automount(path, count, lookup_flags);
14109deed3ebSAl Viro 		flags = smp_load_acquire(&path->dentry->d_flags);
14119875cf80SDavid Howells 		if (ret < 0)
14128aef1884SAl Viro 			break;
14139875cf80SDavid Howells 	}
14149875cf80SDavid Howells 
14159deed3ebSAl Viro 	if (ret == -EISDIR)
14169deed3ebSAl Viro 		ret = 0;
14179deed3ebSAl Viro 	// possible if you race with several mount --move
14189deed3ebSAl Viro 	if (need_mntput && path->mnt == mnt)
14198aef1884SAl Viro 		mntput(path->mnt);
14209deed3ebSAl Viro 	if (!ret && unlikely(d_flags_negative(flags)))
1421d41efb52SAl Viro 		ret = -ENOENT;
14229deed3ebSAl Viro 	*jumped = need_mntput;
14238402752eSAl Viro 	return ret;
14241da177e4SLinus Torvalds }
14251da177e4SLinus Torvalds 
14269deed3ebSAl Viro static inline int traverse_mounts(struct path *path, bool *jumped,
14279deed3ebSAl Viro 				  int *count, unsigned lookup_flags)
14289deed3ebSAl Viro {
14299deed3ebSAl Viro 	unsigned flags = smp_load_acquire(&path->dentry->d_flags);
14309deed3ebSAl Viro 
14319deed3ebSAl Viro 	/* fastpath */
14329deed3ebSAl Viro 	if (likely(!(flags & DCACHE_MANAGED_DENTRY))) {
14339deed3ebSAl Viro 		*jumped = false;
14349deed3ebSAl Viro 		if (unlikely(d_flags_negative(flags)))
14359deed3ebSAl Viro 			return -ENOENT;
14369deed3ebSAl Viro 		return 0;
14379deed3ebSAl Viro 	}
14389deed3ebSAl Viro 	return __traverse_mounts(path, flags, jumped, count, lookup_flags);
14399deed3ebSAl Viro }
14409deed3ebSAl Viro 
1441cc53ce53SDavid Howells int follow_down_one(struct path *path)
14421da177e4SLinus Torvalds {
14431da177e4SLinus Torvalds 	struct vfsmount *mounted;
14441da177e4SLinus Torvalds 
14451c755af4SAl Viro 	mounted = lookup_mnt(path);
14461da177e4SLinus Torvalds 	if (mounted) {
14479393bd07SAl Viro 		dput(path->dentry);
14489393bd07SAl Viro 		mntput(path->mnt);
14499393bd07SAl Viro 		path->mnt = mounted;
14509393bd07SAl Viro 		path->dentry = dget(mounted->mnt_root);
14511da177e4SLinus Torvalds 		return 1;
14521da177e4SLinus Torvalds 	}
14531da177e4SLinus Torvalds 	return 0;
14541da177e4SLinus Torvalds }
14554d359507SAl Viro EXPORT_SYMBOL(follow_down_one);
14561da177e4SLinus Torvalds 
14579875cf80SDavid Howells /*
14589deed3ebSAl Viro  * Follow down to the covering mount currently visible to userspace.  At each
14599deed3ebSAl Viro  * point, the filesystem owning that dentry may be queried as to whether the
14609deed3ebSAl Viro  * caller is permitted to proceed or not.
14619deed3ebSAl Viro  */
1462e1f19857SRichard Weinberger int follow_down(struct path *path, unsigned int flags)
14639deed3ebSAl Viro {
14649deed3ebSAl Viro 	struct vfsmount *mnt = path->mnt;
14659deed3ebSAl Viro 	bool jumped;
1466e1f19857SRichard Weinberger 	int ret = traverse_mounts(path, &jumped, NULL, flags);
14679deed3ebSAl Viro 
14689deed3ebSAl Viro 	if (path->mnt != mnt)
14699deed3ebSAl Viro 		mntput(mnt);
14709deed3ebSAl Viro 	return ret;
14719deed3ebSAl Viro }
14729deed3ebSAl Viro EXPORT_SYMBOL(follow_down);
14739deed3ebSAl Viro 
14749deed3ebSAl Viro /*
1475287548e4SAl Viro  * Try to skip to top of mountpoint pile in rcuwalk mode.  Fail if
1476287548e4SAl Viro  * we meet a managed dentry that would need blocking.
14779875cf80SDavid Howells  */
14783bd8bc89SAl Viro static bool __follow_mount_rcu(struct nameidata *nd, struct path *path)
14799875cf80SDavid Howells {
1480ea936aebSAl Viro 	struct dentry *dentry = path->dentry;
1481ea936aebSAl Viro 	unsigned int flags = dentry->d_flags;
1482ea936aebSAl Viro 
1483ea936aebSAl Viro 	if (likely(!(flags & DCACHE_MANAGED_DENTRY)))
1484ea936aebSAl Viro 		return true;
1485ea936aebSAl Viro 
1486ea936aebSAl Viro 	if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1487ea936aebSAl Viro 		return false;
1488ea936aebSAl Viro 
148962a7375eSIan Kent 	for (;;) {
149062a7375eSIan Kent 		/*
149162a7375eSIan Kent 		 * Don't forget we might have a non-mountpoint managed dentry
149262a7375eSIan Kent 		 * that wants to block transit.
149362a7375eSIan Kent 		 */
1494ea936aebSAl Viro 		if (unlikely(flags & DCACHE_MANAGE_TRANSIT)) {
1495ea936aebSAl Viro 			int res = dentry->d_op->d_manage(path, true);
1496ea936aebSAl Viro 			if (res)
1497ea936aebSAl Viro 				return res == -EISDIR;
1498ea936aebSAl Viro 			flags = dentry->d_flags;
1499b8faf035SNeilBrown 		}
150062a7375eSIan Kent 
1501ea936aebSAl Viro 		if (flags & DCACHE_MOUNTED) {
1502ea936aebSAl Viro 			struct mount *mounted = __lookup_mnt(path->mnt, dentry);
1503ea936aebSAl Viro 			if (mounted) {
1504c7105365SAl Viro 				path->mnt = &mounted->mnt;
1505ea936aebSAl Viro 				dentry = path->dentry = mounted->mnt.mnt_root;
1506bcba1e7dSAl Viro 				nd->state |= ND_JUMPED;
150703fa86e9SAl Viro 				nd->next_seq = read_seqcount_begin(&dentry->d_seq);
1508ea936aebSAl Viro 				flags = dentry->d_flags;
150903fa86e9SAl Viro 				// makes sure that non-RCU pathwalk could reach
151003fa86e9SAl Viro 				// this state.
151120aac6c6SAl Viro 				if (read_seqretry(&mount_lock, nd->m_seq))
151220aac6c6SAl Viro 					return false;
1513ea936aebSAl Viro 				continue;
15149875cf80SDavid Howells 			}
1515ea936aebSAl Viro 			if (read_seqretry(&mount_lock, nd->m_seq))
1516ea936aebSAl Viro 				return false;
1517ea936aebSAl Viro 		}
1518ea936aebSAl Viro 		return !(flags & DCACHE_NEED_AUTOMOUNT);
1519ea936aebSAl Viro 	}
1520287548e4SAl Viro }
1521287548e4SAl Viro 
1522db3c9adeSAl Viro static inline int handle_mounts(struct nameidata *nd, struct dentry *dentry,
15233bd8bc89SAl Viro 			  struct path *path)
1524bd7c4b50SAl Viro {
15259deed3ebSAl Viro 	bool jumped;
1526db3c9adeSAl Viro 	int ret;
1527bd7c4b50SAl Viro 
1528db3c9adeSAl Viro 	path->mnt = nd->path.mnt;
1529db3c9adeSAl Viro 	path->dentry = dentry;
1530c153007bSAl Viro 	if (nd->flags & LOOKUP_RCU) {
153103fa86e9SAl Viro 		unsigned int seq = nd->next_seq;
15323bd8bc89SAl Viro 		if (likely(__follow_mount_rcu(nd, path)))
15339deed3ebSAl Viro 			return 0;
153403fa86e9SAl Viro 		// *path and nd->next_seq might've been clobbered
1535c153007bSAl Viro 		path->mnt = nd->path.mnt;
1536c153007bSAl Viro 		path->dentry = dentry;
153703fa86e9SAl Viro 		nd->next_seq = seq;
153803fa86e9SAl Viro 		if (!try_to_unlazy_next(nd, dentry))
153903fa86e9SAl Viro 			return -ECHILD;
1540c153007bSAl Viro 	}
15419deed3ebSAl Viro 	ret = traverse_mounts(path, &jumped, &nd->total_link_count, nd->flags);
15429deed3ebSAl Viro 	if (jumped) {
15439deed3ebSAl Viro 		if (unlikely(nd->flags & LOOKUP_NO_XDEV))
15449deed3ebSAl Viro 			ret = -EXDEV;
15459deed3ebSAl Viro 		else
1546bcba1e7dSAl Viro 			nd->state |= ND_JUMPED;
15479deed3ebSAl Viro 	}
15489deed3ebSAl Viro 	if (unlikely(ret)) {
15499deed3ebSAl Viro 		dput(path->dentry);
15509deed3ebSAl Viro 		if (path->mnt != nd->path.mnt)
15519deed3ebSAl Viro 			mntput(path->mnt);
1552bd7c4b50SAl Viro 	}
1553bd7c4b50SAl Viro 	return ret;
1554bd7c4b50SAl Viro }
1555bd7c4b50SAl Viro 
15569875cf80SDavid Howells /*
1557f4fdace9SOleg Drokin  * This looks up the name in dcache and possibly revalidates the found dentry.
1558f4fdace9SOleg Drokin  * NULL is returned if the dentry does not exist in the cache.
1559baa03890SNick Piggin  */
1560e3c13928SAl Viro static struct dentry *lookup_dcache(const struct qstr *name,
1561e3c13928SAl Viro 				    struct dentry *dir,
15626c51e513SAl Viro 				    unsigned int flags)
1563baa03890SNick Piggin {
1564a89f8337SAl Viro 	struct dentry *dentry = d_lookup(dir, name);
1565bad61189SMiklos Szeredi 	if (dentry) {
1566a89f8337SAl Viro 		int error = d_revalidate(dentry, flags);
1567bad61189SMiklos Szeredi 		if (unlikely(error <= 0)) {
156874ff0ffcSAl Viro 			if (!error)
15695542aa2fSEric W. Biederman 				d_invalidate(dentry);
1570bad61189SMiklos Szeredi 			dput(dentry);
157174ff0ffcSAl Viro 			return ERR_PTR(error);
1572bad61189SMiklos Szeredi 		}
1573bad61189SMiklos Szeredi 	}
1574baa03890SNick Piggin 	return dentry;
1575baa03890SNick Piggin }
1576baa03890SNick Piggin 
1577baa03890SNick Piggin /*
1578a03ece5fSAl Viro  * Parent directory has inode locked exclusive.  This is one
1579a03ece5fSAl Viro  * and only case when ->lookup() gets called on non in-lookup
1580a03ece5fSAl Viro  * dentries - as the matter of fact, this only gets called
1581a03ece5fSAl Viro  * when directory is guaranteed to have no in-lookup children
1582a03ece5fSAl Viro  * at all.
158344396f4bSJosef Bacik  */
1584a03ece5fSAl Viro static struct dentry *__lookup_hash(const struct qstr *name,
1585a03ece5fSAl Viro 		struct dentry *base, unsigned int flags)
158644396f4bSJosef Bacik {
1587a03ece5fSAl Viro 	struct dentry *dentry = lookup_dcache(name, base, flags);
158844396f4bSJosef Bacik 	struct dentry *old;
1589a03ece5fSAl Viro 	struct inode *dir = base->d_inode;
1590a03ece5fSAl Viro 
1591a03ece5fSAl Viro 	if (dentry)
1592a03ece5fSAl Viro 		return dentry;
159344396f4bSJosef Bacik 
159444396f4bSJosef Bacik 	/* Don't create child dentry for a dead directory. */
1595a03ece5fSAl Viro 	if (unlikely(IS_DEADDIR(dir)))
159644396f4bSJosef Bacik 		return ERR_PTR(-ENOENT);
1597a03ece5fSAl Viro 
1598a03ece5fSAl Viro 	dentry = d_alloc(base, name);
1599a03ece5fSAl Viro 	if (unlikely(!dentry))
1600a03ece5fSAl Viro 		return ERR_PTR(-ENOMEM);
160144396f4bSJosef Bacik 
160272bd866aSAl Viro 	old = dir->i_op->lookup(dir, dentry, flags);
160344396f4bSJosef Bacik 	if (unlikely(old)) {
160444396f4bSJosef Bacik 		dput(dentry);
160544396f4bSJosef Bacik 		dentry = old;
160644396f4bSJosef Bacik 	}
160744396f4bSJosef Bacik 	return dentry;
160844396f4bSJosef Bacik }
160944396f4bSJosef Bacik 
16104cb64024SAl Viro static struct dentry *lookup_fast(struct nameidata *nd)
16111da177e4SLinus Torvalds {
161231e6b01fSNick Piggin 	struct dentry *dentry, *parent = nd->path.dentry;
16135a18fff2SAl Viro 	int status = 1;
16149875cf80SDavid Howells 
16153cac260aSAl Viro 	/*
1616b04f784eSNick Piggin 	 * Rename seqlock is not required here because in the off chance
16175d0f49c1SAl Viro 	 * of a false negative due to a concurrent rename, the caller is
16185d0f49c1SAl Viro 	 * going to fall back to non-racy lookup.
1619b04f784eSNick Piggin 	 */
162031e6b01fSNick Piggin 	if (nd->flags & LOOKUP_RCU) {
162103fa86e9SAl Viro 		dentry = __d_lookup_rcu(parent, &nd->last, &nd->next_seq);
16225d0f49c1SAl Viro 		if (unlikely(!dentry)) {
1623e36cffedSJens Axboe 			if (!try_to_unlazy(nd))
162420e34357SAl Viro 				return ERR_PTR(-ECHILD);
162520e34357SAl Viro 			return NULL;
16265d0f49c1SAl Viro 		}
16275a18fff2SAl Viro 
162812f8ad4bSLinus Torvalds 		/*
162912f8ad4bSLinus Torvalds 		 * This sequence count validates that the parent had no
163012f8ad4bSLinus Torvalds 		 * changes while we did the lookup of the dentry above.
163112f8ad4bSLinus Torvalds 		 */
16324cb64024SAl Viro 		if (read_seqcount_retry(&parent->d_seq, nd->seq))
163320e34357SAl Viro 			return ERR_PTR(-ECHILD);
16345a18fff2SAl Viro 
16354ce16ef3SAl Viro 		status = d_revalidate(dentry, nd->flags);
1636c153007bSAl Viro 		if (likely(status > 0))
163720e34357SAl Viro 			return dentry;
163803fa86e9SAl Viro 		if (!try_to_unlazy_next(nd, dentry))
163920e34357SAl Viro 			return ERR_PTR(-ECHILD);
164026ddb45eSSteven Rostedt (VMware) 		if (status == -ECHILD)
1641209a7fb2SAl Viro 			/* we'd been told to redo it in non-rcu mode */
1642209a7fb2SAl Viro 			status = d_revalidate(dentry, nd->flags);
16435a18fff2SAl Viro 	} else {
1644e97cdc87SAl Viro 		dentry = __d_lookup(parent, &nd->last);
164581e6f520SAl Viro 		if (unlikely(!dentry))
164620e34357SAl Viro 			return NULL;
16474ce16ef3SAl Viro 		status = d_revalidate(dentry, nd->flags);
16485d0f49c1SAl Viro 	}
16495a18fff2SAl Viro 	if (unlikely(status <= 0)) {
1650e9742b53SAl Viro 		if (!status)
16515d0f49c1SAl Viro 			d_invalidate(dentry);
16525a18fff2SAl Viro 		dput(dentry);
165320e34357SAl Viro 		return ERR_PTR(status);
16545a18fff2SAl Viro 	}
165520e34357SAl Viro 	return dentry;
1656697f514dSMiklos Szeredi }
1657697f514dSMiklos Szeredi 
1658697f514dSMiklos Szeredi /* Fast lookup failed, do it the slow way */
165988d8331aSAl Viro static struct dentry *__lookup_slow(const struct qstr *name,
1660e3c13928SAl Viro 				    struct dentry *dir,
1661e3c13928SAl Viro 				    unsigned int flags)
1662697f514dSMiklos Szeredi {
166388d8331aSAl Viro 	struct dentry *dentry, *old;
16641936386eSAl Viro 	struct inode *inode = dir->d_inode;
1665d9171b93SAl Viro 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
16661936386eSAl Viro 
16671936386eSAl Viro 	/* Don't go there if it's already dead */
166894bdd655SAl Viro 	if (unlikely(IS_DEADDIR(inode)))
166988d8331aSAl Viro 		return ERR_PTR(-ENOENT);
167094bdd655SAl Viro again:
1671d9171b93SAl Viro 	dentry = d_alloc_parallel(dir, name, &wq);
167294bdd655SAl Viro 	if (IS_ERR(dentry))
167388d8331aSAl Viro 		return dentry;
167494bdd655SAl Viro 	if (unlikely(!d_in_lookup(dentry))) {
1675949a852eSAl Viro 		int error = d_revalidate(dentry, flags);
1676949a852eSAl Viro 		if (unlikely(error <= 0)) {
167794bdd655SAl Viro 			if (!error) {
1678949a852eSAl Viro 				d_invalidate(dentry);
1679949a852eSAl Viro 				dput(dentry);
168094bdd655SAl Viro 				goto again;
168194bdd655SAl Viro 			}
168294bdd655SAl Viro 			dput(dentry);
1683949a852eSAl Viro 			dentry = ERR_PTR(error);
1684949a852eSAl Viro 		}
168594bdd655SAl Viro 	} else {
16861936386eSAl Viro 		old = inode->i_op->lookup(inode, dentry, flags);
168785c7f810SAl Viro 		d_lookup_done(dentry);
16881936386eSAl Viro 		if (unlikely(old)) {
16891936386eSAl Viro 			dput(dentry);
16901936386eSAl Viro 			dentry = old;
1691949a852eSAl Viro 		}
1692949a852eSAl Viro 	}
1693e3c13928SAl Viro 	return dentry;
16941da177e4SLinus Torvalds }
16951da177e4SLinus Torvalds 
169688d8331aSAl Viro static struct dentry *lookup_slow(const struct qstr *name,
169788d8331aSAl Viro 				  struct dentry *dir,
169888d8331aSAl Viro 				  unsigned int flags)
169988d8331aSAl Viro {
170088d8331aSAl Viro 	struct inode *inode = dir->d_inode;
170188d8331aSAl Viro 	struct dentry *res;
170288d8331aSAl Viro 	inode_lock_shared(inode);
170388d8331aSAl Viro 	res = __lookup_slow(name, dir, flags);
170488d8331aSAl Viro 	inode_unlock_shared(inode);
170588d8331aSAl Viro 	return res;
170688d8331aSAl Viro }
170788d8331aSAl Viro 
17084609e1f1SChristian Brauner static inline int may_lookup(struct mnt_idmap *idmap,
1709ba73d987SChristian Brauner 			     struct nameidata *nd)
171052094c8aSAl Viro {
171152094c8aSAl Viro 	if (nd->flags & LOOKUP_RCU) {
17124609e1f1SChristian Brauner 		int err = inode_permission(idmap, nd->inode, MAY_EXEC|MAY_NOT_BLOCK);
1713e36cffedSJens Axboe 		if (err != -ECHILD || !try_to_unlazy(nd))
171452094c8aSAl Viro 			return err;
171552094c8aSAl Viro 	}
17164609e1f1SChristian Brauner 	return inode_permission(idmap, nd->inode, MAY_EXEC);
171752094c8aSAl Viro }
171852094c8aSAl Viro 
171903fa86e9SAl Viro static int reserve_stack(struct nameidata *nd, struct path *link)
1720d63ff28fSAl Viro {
172149055906SAl Viro 	if (unlikely(nd->total_link_count++ >= MAXSYMLINKS))
172249055906SAl Viro 		return -ELOOP;
17234542576bSAl Viro 
17244542576bSAl Viro 	if (likely(nd->depth != EMBEDDED_LEVELS))
17254542576bSAl Viro 		return 0;
17264542576bSAl Viro 	if (likely(nd->stack != nd->internal))
17274542576bSAl Viro 		return 0;
172860ef60c7SAl Viro 	if (likely(nd_alloc_stack(nd)))
172949055906SAl Viro 		return 0;
173060ef60c7SAl Viro 
173160ef60c7SAl Viro 	if (nd->flags & LOOKUP_RCU) {
173260ef60c7SAl Viro 		// we need to grab link before we do unlazy.  And we can't skip
173360ef60c7SAl Viro 		// unlazy even if we fail to grab the link - cleanup needs it
173403fa86e9SAl Viro 		bool grabbed_link = legitimize_path(nd, link, nd->next_seq);
173560ef60c7SAl Viro 
1736e5ca024eSAl Viro 		if (!try_to_unlazy(nd) || !grabbed_link)
173760ef60c7SAl Viro 			return -ECHILD;
173860ef60c7SAl Viro 
173960ef60c7SAl Viro 		if (nd_alloc_stack(nd))
174060ef60c7SAl Viro 			return 0;
1741bc40aee0SAl Viro 	}
174260ef60c7SAl Viro 	return -ENOMEM;
174349055906SAl Viro }
174449055906SAl Viro 
174549055906SAl Viro enum {WALK_TRAILING = 1, WALK_MORE = 2, WALK_NOFOLLOW = 4};
174649055906SAl Viro 
174749055906SAl Viro static const char *pick_link(struct nameidata *nd, struct path *link,
174803fa86e9SAl Viro 		     struct inode *inode, int flags)
174949055906SAl Viro {
175049055906SAl Viro 	struct saved *last;
175149055906SAl Viro 	const char *res;
175203fa86e9SAl Viro 	int error = reserve_stack(nd, link);
175349055906SAl Viro 
175449055906SAl Viro 	if (unlikely(error)) {
175549055906SAl Viro 		if (!(nd->flags & LOOKUP_RCU))
1756cd179f44SAl Viro 			path_put(link);
175706708adbSAl Viro 		return ERR_PTR(error);
1758626de996SAl Viro 	}
1759ab104923SAl Viro 	last = nd->stack + nd->depth++;
17601cf2665bSAl Viro 	last->link = *link;
1761fceef393SAl Viro 	clear_delayed_call(&last->done);
176203fa86e9SAl Viro 	last->seq = nd->next_seq;
1763ad6cc4c3SAl Viro 
1764b1a81972SAl Viro 	if (flags & WALK_TRAILING) {
1765ad6cc4c3SAl Viro 		error = may_follow_link(nd, inode);
1766ad6cc4c3SAl Viro 		if (unlikely(error))
1767ad6cc4c3SAl Viro 			return ERR_PTR(error);
1768ad6cc4c3SAl Viro 	}
1769ad6cc4c3SAl Viro 
1770dab741e0SMattias Nissler 	if (unlikely(nd->flags & LOOKUP_NO_SYMLINKS) ||
1771dab741e0SMattias Nissler 			unlikely(link->mnt->mnt_flags & MNT_NOSYMFOLLOW))
1772ad6cc4c3SAl Viro 		return ERR_PTR(-ELOOP);
1773ad6cc4c3SAl Viro 
1774ad6cc4c3SAl Viro 	if (!(nd->flags & LOOKUP_RCU)) {
1775ad6cc4c3SAl Viro 		touch_atime(&last->link);
1776ad6cc4c3SAl Viro 		cond_resched();
1777ad6cc4c3SAl Viro 	} else if (atime_needs_update(&last->link, inode)) {
1778e36cffedSJens Axboe 		if (!try_to_unlazy(nd))
1779ad6cc4c3SAl Viro 			return ERR_PTR(-ECHILD);
1780ad6cc4c3SAl Viro 		touch_atime(&last->link);
1781ad6cc4c3SAl Viro 	}
1782ad6cc4c3SAl Viro 
1783ad6cc4c3SAl Viro 	error = security_inode_follow_link(link->dentry, inode,
1784ad6cc4c3SAl Viro 					   nd->flags & LOOKUP_RCU);
1785ad6cc4c3SAl Viro 	if (unlikely(error))
1786ad6cc4c3SAl Viro 		return ERR_PTR(error);
1787ad6cc4c3SAl Viro 
1788ad6cc4c3SAl Viro 	res = READ_ONCE(inode->i_link);
1789ad6cc4c3SAl Viro 	if (!res) {
1790ad6cc4c3SAl Viro 		const char * (*get)(struct dentry *, struct inode *,
1791ad6cc4c3SAl Viro 				struct delayed_call *);
1792ad6cc4c3SAl Viro 		get = inode->i_op->get_link;
1793ad6cc4c3SAl Viro 		if (nd->flags & LOOKUP_RCU) {
1794ad6cc4c3SAl Viro 			res = get(NULL, inode, &last->done);
1795e36cffedSJens Axboe 			if (res == ERR_PTR(-ECHILD) && try_to_unlazy(nd))
1796ad6cc4c3SAl Viro 				res = get(link->dentry, inode, &last->done);
1797ad6cc4c3SAl Viro 		} else {
1798ad6cc4c3SAl Viro 			res = get(link->dentry, inode, &last->done);
1799ad6cc4c3SAl Viro 		}
1800ad6cc4c3SAl Viro 		if (!res)
1801ad6cc4c3SAl Viro 			goto all_done;
1802ad6cc4c3SAl Viro 		if (IS_ERR(res))
1803ad6cc4c3SAl Viro 			return res;
1804ad6cc4c3SAl Viro 	}
1805ad6cc4c3SAl Viro 	if (*res == '/') {
1806ad6cc4c3SAl Viro 		error = nd_jump_root(nd);
1807ad6cc4c3SAl Viro 		if (unlikely(error))
1808ad6cc4c3SAl Viro 			return ERR_PTR(error);
1809ad6cc4c3SAl Viro 		while (unlikely(*++res == '/'))
1810ad6cc4c3SAl Viro 			;
1811ad6cc4c3SAl Viro 	}
1812ad6cc4c3SAl Viro 	if (*res)
1813ad6cc4c3SAl Viro 		return res;
1814ad6cc4c3SAl Viro all_done: // pure jump
1815ad6cc4c3SAl Viro 	put_link(nd);
1816ad6cc4c3SAl Viro 	return NULL;
1817d63ff28fSAl Viro }
1818d63ff28fSAl Viro 
18193ddcd056SLinus Torvalds /*
18203ddcd056SLinus Torvalds  * Do we need to follow links? We _really_ want to be able
18213ddcd056SLinus Torvalds  * to do this check without having to look at inode->i_op,
18223ddcd056SLinus Torvalds  * so we keep a cache of "no, this doesn't need follow_link"
18233ddcd056SLinus Torvalds  * for the common case.
182403fa86e9SAl Viro  *
182503fa86e9SAl Viro  * NOTE: dentry must be what nd->next_seq had been sampled from.
18263ddcd056SLinus Torvalds  */
1827b0417d2cSAl Viro static const char *step_into(struct nameidata *nd, int flags,
1828a4f5b521SAl Viro 		     struct dentry *dentry)
18293ddcd056SLinus Torvalds {
1830cbae4d12SAl Viro 	struct path path;
1831a4f5b521SAl Viro 	struct inode *inode;
18323bd8bc89SAl Viro 	int err = handle_mounts(nd, dentry, &path);
1833cbae4d12SAl Viro 
1834cbae4d12SAl Viro 	if (err < 0)
1835b0417d2cSAl Viro 		return ERR_PTR(err);
18363bd8bc89SAl Viro 	inode = path.dentry->d_inode;
1837cbae4d12SAl Viro 	if (likely(!d_is_symlink(path.dentry)) ||
18388c4efe22SAl Viro 	   ((flags & WALK_TRAILING) && !(nd->flags & LOOKUP_FOLLOW)) ||
1839aca2903eSAl Viro 	   (flags & WALK_NOFOLLOW)) {
18408f64fb1cSAl Viro 		/* not a symlink or should not follow */
18413bd8bc89SAl Viro 		if (nd->flags & LOOKUP_RCU) {
18423bd8bc89SAl Viro 			if (read_seqcount_retry(&path.dentry->d_seq, nd->next_seq))
18433bd8bc89SAl Viro 				return ERR_PTR(-ECHILD);
18443bd8bc89SAl Viro 			if (unlikely(!inode))
18453bd8bc89SAl Viro 				return ERR_PTR(-ENOENT);
18463bd8bc89SAl Viro 		} else {
1847c99687a0SAl Viro 			dput(nd->path.dentry);
1848c99687a0SAl Viro 			if (nd->path.mnt != path.mnt)
1849c99687a0SAl Viro 				mntput(nd->path.mnt);
1850c99687a0SAl Viro 		}
1851c99687a0SAl Viro 		nd->path = path;
18528f64fb1cSAl Viro 		nd->inode = inode;
185303fa86e9SAl Viro 		nd->seq = nd->next_seq;
1854b0417d2cSAl Viro 		return NULL;
18558f64fb1cSAl Viro 	}
1856a7f77542SAl Viro 	if (nd->flags & LOOKUP_RCU) {
185784f0cd9eSAl Viro 		/* make sure that d_is_symlink above matches inode */
185803fa86e9SAl Viro 		if (read_seqcount_retry(&path.dentry->d_seq, nd->next_seq))
1859b0417d2cSAl Viro 			return ERR_PTR(-ECHILD);
186084f0cd9eSAl Viro 	} else {
186184f0cd9eSAl Viro 		if (path.mnt == nd->path.mnt)
186284f0cd9eSAl Viro 			mntget(path.mnt);
1863a7f77542SAl Viro 	}
186403fa86e9SAl Viro 	return pick_link(nd, &path, inode, flags);
18653ddcd056SLinus Torvalds }
18663ddcd056SLinus Torvalds 
1867b16c001dSAl Viro static struct dentry *follow_dotdot_rcu(struct nameidata *nd)
1868957dd41dSAl Viro {
186912487f30SAl Viro 	struct dentry *parent, *old;
1870957dd41dSAl Viro 
187112487f30SAl Viro 	if (path_equal(&nd->path, &nd->root))
187212487f30SAl Viro 		goto in_root;
187312487f30SAl Viro 	if (unlikely(nd->path.dentry == nd->path.mnt->mnt_root)) {
18747ef482faSAl Viro 		struct path path;
1875efe772d6SAl Viro 		unsigned seq;
18767ef482faSAl Viro 		if (!choose_mountpoint_rcu(real_mount(nd->path.mnt),
18777ef482faSAl Viro 					   &nd->root, &path, &seq))
187812487f30SAl Viro 			goto in_root;
1879efe772d6SAl Viro 		if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1880efe772d6SAl Viro 			return ERR_PTR(-ECHILD);
1881efe772d6SAl Viro 		nd->path = path;
1882efe772d6SAl Viro 		nd->inode = path.dentry->d_inode;
1883efe772d6SAl Viro 		nd->seq = seq;
188403fa86e9SAl Viro 		// makes sure that non-RCU pathwalk could reach this state
188582ef0698SAl Viro 		if (read_seqretry(&mount_lock, nd->m_seq))
1886efe772d6SAl Viro 			return ERR_PTR(-ECHILD);
1887efe772d6SAl Viro 		/* we know that mountpoint was pinned */
1888957dd41dSAl Viro 	}
188912487f30SAl Viro 	old = nd->path.dentry;
189012487f30SAl Viro 	parent = old->d_parent;
189103fa86e9SAl Viro 	nd->next_seq = read_seqcount_begin(&parent->d_seq);
189203fa86e9SAl Viro 	// makes sure that non-RCU pathwalk could reach this state
189382ef0698SAl Viro 	if (read_seqcount_retry(&old->d_seq, nd->seq))
189412487f30SAl Viro 		return ERR_PTR(-ECHILD);
189512487f30SAl Viro 	if (unlikely(!path_connected(nd->path.mnt, parent)))
189612487f30SAl Viro 		return ERR_PTR(-ECHILD);
189712487f30SAl Viro 	return parent;
189812487f30SAl Viro in_root:
189982ef0698SAl Viro 	if (read_seqretry(&mount_lock, nd->m_seq))
1900efe772d6SAl Viro 		return ERR_PTR(-ECHILD);
1901957dd41dSAl Viro 	if (unlikely(nd->flags & LOOKUP_BENEATH))
19027521f22bSAl Viro 		return ERR_PTR(-ECHILD);
190303fa86e9SAl Viro 	nd->next_seq = nd->seq;
190451c6546cSAl Viro 	return nd->path.dentry;
1905957dd41dSAl Viro }
1906957dd41dSAl Viro 
1907b16c001dSAl Viro static struct dentry *follow_dotdot(struct nameidata *nd)
1908957dd41dSAl Viro {
190912487f30SAl Viro 	struct dentry *parent;
191012487f30SAl Viro 
1911957dd41dSAl Viro 	if (path_equal(&nd->path, &nd->root))
191212487f30SAl Viro 		goto in_root;
191312487f30SAl Viro 	if (unlikely(nd->path.dentry == nd->path.mnt->mnt_root)) {
19142aa38470SAl Viro 		struct path path;
19152aa38470SAl Viro 
19162aa38470SAl Viro 		if (!choose_mountpoint(real_mount(nd->path.mnt),
19172aa38470SAl Viro 				       &nd->root, &path))
191812487f30SAl Viro 			goto in_root;
1919165200d6SAl Viro 		path_put(&nd->path);
1920165200d6SAl Viro 		nd->path = path;
19212aa38470SAl Viro 		nd->inode = path.dentry->d_inode;
1922165200d6SAl Viro 		if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1923165200d6SAl Viro 			return ERR_PTR(-EXDEV);
192412487f30SAl Viro 	}
1925957dd41dSAl Viro 	/* rare case of legitimate dget_parent()... */
192612487f30SAl Viro 	parent = dget_parent(nd->path.dentry);
1927957dd41dSAl Viro 	if (unlikely(!path_connected(nd->path.mnt, parent))) {
1928957dd41dSAl Viro 		dput(parent);
19297521f22bSAl Viro 		return ERR_PTR(-ENOENT);
1930957dd41dSAl Viro 	}
1931c2df1968SAl Viro 	return parent;
193212487f30SAl Viro 
193312487f30SAl Viro in_root:
1934957dd41dSAl Viro 	if (unlikely(nd->flags & LOOKUP_BENEATH))
19357521f22bSAl Viro 		return ERR_PTR(-EXDEV);
193651c6546cSAl Viro 	return dget(nd->path.dentry);
1937957dd41dSAl Viro }
1938957dd41dSAl Viro 
19397521f22bSAl Viro static const char *handle_dots(struct nameidata *nd, int type)
1940957dd41dSAl Viro {
1941957dd41dSAl Viro 	if (type == LAST_DOTDOT) {
19427521f22bSAl Viro 		const char *error = NULL;
1943c2df1968SAl Viro 		struct dentry *parent;
1944957dd41dSAl Viro 
1945957dd41dSAl Viro 		if (!nd->root.mnt) {
19467521f22bSAl Viro 			error = ERR_PTR(set_root(nd));
1947957dd41dSAl Viro 			if (error)
1948957dd41dSAl Viro 				return error;
1949957dd41dSAl Viro 		}
1950957dd41dSAl Viro 		if (nd->flags & LOOKUP_RCU)
1951b16c001dSAl Viro 			parent = follow_dotdot_rcu(nd);
1952957dd41dSAl Viro 		else
1953b16c001dSAl Viro 			parent = follow_dotdot(nd);
1954c2df1968SAl Viro 		if (IS_ERR(parent))
1955c2df1968SAl Viro 			return ERR_CAST(parent);
1956a4f5b521SAl Viro 		error = step_into(nd, WALK_NOFOLLOW, parent);
1957c2df1968SAl Viro 		if (unlikely(error))
1958957dd41dSAl Viro 			return error;
1959957dd41dSAl Viro 
1960957dd41dSAl Viro 		if (unlikely(nd->flags & LOOKUP_IS_SCOPED)) {
1961957dd41dSAl Viro 			/*
1962957dd41dSAl Viro 			 * If there was a racing rename or mount along our
1963957dd41dSAl Viro 			 * path, then we can't be sure that ".." hasn't jumped
1964957dd41dSAl Viro 			 * above nd->root (and so userspace should retry or use
1965957dd41dSAl Viro 			 * some fallback).
1966957dd41dSAl Viro 			 */
1967957dd41dSAl Viro 			smp_rmb();
196882ef0698SAl Viro 			if (__read_seqcount_retry(&mount_lock.seqcount, nd->m_seq))
19697521f22bSAl Viro 				return ERR_PTR(-EAGAIN);
197082ef0698SAl Viro 			if (__read_seqcount_retry(&rename_lock.seqcount, nd->r_seq))
19717521f22bSAl Viro 				return ERR_PTR(-EAGAIN);
1972957dd41dSAl Viro 		}
1973957dd41dSAl Viro 	}
19747521f22bSAl Viro 	return NULL;
1975957dd41dSAl Viro }
1976957dd41dSAl Viro 
197792d27016SAl Viro static const char *walk_component(struct nameidata *nd, int flags)
1978ce57dfc1SAl Viro {
1979db3c9adeSAl Viro 	struct dentry *dentry;
1980ce57dfc1SAl Viro 	/*
1981ce57dfc1SAl Viro 	 * "." and ".." are special - ".." especially so because it has
1982ce57dfc1SAl Viro 	 * to be able to know about the current root directory and
1983ce57dfc1SAl Viro 	 * parent relationships.
1984ce57dfc1SAl Viro 	 */
19854693a547SAl Viro 	if (unlikely(nd->last_type != LAST_NORM)) {
19861c4ff1a8SAl Viro 		if (!(flags & WALK_MORE) && nd->depth)
19874693a547SAl Viro 			put_link(nd);
19887521f22bSAl Viro 		return handle_dots(nd, nd->last_type);
19894693a547SAl Viro 	}
19904cb64024SAl Viro 	dentry = lookup_fast(nd);
199120e34357SAl Viro 	if (IS_ERR(dentry))
199292d27016SAl Viro 		return ERR_CAST(dentry);
199320e34357SAl Viro 	if (unlikely(!dentry)) {
1994db3c9adeSAl Viro 		dentry = lookup_slow(&nd->last, nd->path.dentry, nd->flags);
1995db3c9adeSAl Viro 		if (IS_ERR(dentry))
199692d27016SAl Viro 			return ERR_CAST(dentry);
199720e34357SAl Viro 	}
199856676ec3SAl Viro 	if (!(flags & WALK_MORE) && nd->depth)
199956676ec3SAl Viro 		put_link(nd);
2000a4f5b521SAl Viro 	return step_into(nd, flags, dentry);
2001ce57dfc1SAl Viro }
2002ce57dfc1SAl Viro 
20031da177e4SLinus Torvalds /*
2004bfcfaa77SLinus Torvalds  * We can do the critical dentry name comparison and hashing
2005bfcfaa77SLinus Torvalds  * operations one word at a time, but we are limited to:
2006bfcfaa77SLinus Torvalds  *
2007bfcfaa77SLinus Torvalds  * - Architectures with fast unaligned word accesses. We could
2008bfcfaa77SLinus Torvalds  *   do a "get_unaligned()" if this helps and is sufficiently
2009bfcfaa77SLinus Torvalds  *   fast.
2010bfcfaa77SLinus Torvalds  *
2011bfcfaa77SLinus Torvalds  * - non-CONFIG_DEBUG_PAGEALLOC configurations (so that we
2012bfcfaa77SLinus Torvalds  *   do not trap on the (extremely unlikely) case of a page
2013bfcfaa77SLinus Torvalds  *   crossing operation.
2014bfcfaa77SLinus Torvalds  *
2015bfcfaa77SLinus Torvalds  * - Furthermore, we need an efficient 64-bit compile for the
2016bfcfaa77SLinus Torvalds  *   64-bit case in order to generate the "number of bytes in
2017bfcfaa77SLinus Torvalds  *   the final mask". Again, that could be replaced with a
2018bfcfaa77SLinus Torvalds  *   efficient population count instruction or similar.
2019bfcfaa77SLinus Torvalds  */
2020bfcfaa77SLinus Torvalds #ifdef CONFIG_DCACHE_WORD_ACCESS
2021bfcfaa77SLinus Torvalds 
2022f68e556eSLinus Torvalds #include <asm/word-at-a-time.h>
2023bfcfaa77SLinus Torvalds 
2024468a9428SGeorge Spelvin #ifdef HASH_MIX
2025bfcfaa77SLinus Torvalds 
2026468a9428SGeorge Spelvin /* Architecture provides HASH_MIX and fold_hash() in <asm/hash.h> */
2027468a9428SGeorge Spelvin 
2028468a9428SGeorge Spelvin #elif defined(CONFIG_64BIT)
20292a18da7aSGeorge Spelvin /*
20302a18da7aSGeorge Spelvin  * Register pressure in the mixing function is an issue, particularly
20312a18da7aSGeorge Spelvin  * on 32-bit x86, but almost any function requires one state value and
20322a18da7aSGeorge Spelvin  * one temporary.  Instead, use a function designed for two state values
20332a18da7aSGeorge Spelvin  * and no temporaries.
20342a18da7aSGeorge Spelvin  *
20352a18da7aSGeorge Spelvin  * This function cannot create a collision in only two iterations, so
20362a18da7aSGeorge Spelvin  * we have two iterations to achieve avalanche.  In those two iterations,
20372a18da7aSGeorge Spelvin  * we have six layers of mixing, which is enough to spread one bit's
20382a18da7aSGeorge Spelvin  * influence out to 2^6 = 64 state bits.
20392a18da7aSGeorge Spelvin  *
20402a18da7aSGeorge Spelvin  * Rotate constants are scored by considering either 64 one-bit input
20412a18da7aSGeorge Spelvin  * deltas or 64*63/2 = 2016 two-bit input deltas, and finding the
20422a18da7aSGeorge Spelvin  * probability of that delta causing a change to each of the 128 output
20432a18da7aSGeorge Spelvin  * bits, using a sample of random initial states.
20442a18da7aSGeorge Spelvin  *
20452a18da7aSGeorge Spelvin  * The Shannon entropy of the computed probabilities is then summed
20462a18da7aSGeorge Spelvin  * to produce a score.  Ideally, any input change has a 50% chance of
20472a18da7aSGeorge Spelvin  * toggling any given output bit.
20482a18da7aSGeorge Spelvin  *
20492a18da7aSGeorge Spelvin  * Mixing scores (in bits) for (12,45):
20502a18da7aSGeorge Spelvin  * Input delta: 1-bit      2-bit
20512a18da7aSGeorge Spelvin  * 1 round:     713.3    42542.6
20522a18da7aSGeorge Spelvin  * 2 rounds:   2753.7   140389.8
20532a18da7aSGeorge Spelvin  * 3 rounds:   5954.1   233458.2
20542a18da7aSGeorge Spelvin  * 4 rounds:   7862.6   256672.2
20552a18da7aSGeorge Spelvin  * Perfect:    8192     258048
20562a18da7aSGeorge Spelvin  *            (64*128) (64*63/2 * 128)
20572a18da7aSGeorge Spelvin  */
20582a18da7aSGeorge Spelvin #define HASH_MIX(x, y, a)	\
20592a18da7aSGeorge Spelvin 	(	x ^= (a),	\
20602a18da7aSGeorge Spelvin 	y ^= x,	x = rol64(x,12),\
20612a18da7aSGeorge Spelvin 	x += y,	y = rol64(y,45),\
20622a18da7aSGeorge Spelvin 	y *= 9			)
2063bfcfaa77SLinus Torvalds 
20640fed3ac8SGeorge Spelvin /*
20652a18da7aSGeorge Spelvin  * Fold two longs into one 32-bit hash value.  This must be fast, but
20662a18da7aSGeorge Spelvin  * latency isn't quite as critical, as there is a fair bit of additional
20672a18da7aSGeorge Spelvin  * work done before the hash value is used.
20680fed3ac8SGeorge Spelvin  */
20692a18da7aSGeorge Spelvin static inline unsigned int fold_hash(unsigned long x, unsigned long y)
20700fed3ac8SGeorge Spelvin {
20712a18da7aSGeorge Spelvin 	y ^= x * GOLDEN_RATIO_64;
20722a18da7aSGeorge Spelvin 	y *= GOLDEN_RATIO_64;
20732a18da7aSGeorge Spelvin 	return y >> 32;
20740fed3ac8SGeorge Spelvin }
20750fed3ac8SGeorge Spelvin 
2076bfcfaa77SLinus Torvalds #else	/* 32-bit case */
2077bfcfaa77SLinus Torvalds 
20782a18da7aSGeorge Spelvin /*
20792a18da7aSGeorge Spelvin  * Mixing scores (in bits) for (7,20):
20802a18da7aSGeorge Spelvin  * Input delta: 1-bit      2-bit
20812a18da7aSGeorge Spelvin  * 1 round:     330.3     9201.6
20822a18da7aSGeorge Spelvin  * 2 rounds:   1246.4    25475.4
20832a18da7aSGeorge Spelvin  * 3 rounds:   1907.1    31295.1
20842a18da7aSGeorge Spelvin  * 4 rounds:   2042.3    31718.6
20852a18da7aSGeorge Spelvin  * Perfect:    2048      31744
20862a18da7aSGeorge Spelvin  *            (32*64)   (32*31/2 * 64)
20872a18da7aSGeorge Spelvin  */
20882a18da7aSGeorge Spelvin #define HASH_MIX(x, y, a)	\
20892a18da7aSGeorge Spelvin 	(	x ^= (a),	\
20902a18da7aSGeorge Spelvin 	y ^= x,	x = rol32(x, 7),\
20912a18da7aSGeorge Spelvin 	x += y,	y = rol32(y,20),\
20922a18da7aSGeorge Spelvin 	y *= 9			)
2093bfcfaa77SLinus Torvalds 
20942a18da7aSGeorge Spelvin static inline unsigned int fold_hash(unsigned long x, unsigned long y)
20950fed3ac8SGeorge Spelvin {
20962a18da7aSGeorge Spelvin 	/* Use arch-optimized multiply if one exists */
20972a18da7aSGeorge Spelvin 	return __hash_32(y ^ __hash_32(x));
20980fed3ac8SGeorge Spelvin }
20990fed3ac8SGeorge Spelvin 
2100bfcfaa77SLinus Torvalds #endif
2101bfcfaa77SLinus Torvalds 
21022a18da7aSGeorge Spelvin /*
21032a18da7aSGeorge Spelvin  * Return the hash of a string of known length.  This is carfully
21042a18da7aSGeorge Spelvin  * designed to match hash_name(), which is the more critical function.
21052a18da7aSGeorge Spelvin  * In particular, we must end by hashing a final word containing 0..7
21062a18da7aSGeorge Spelvin  * payload bytes, to match the way that hash_name() iterates until it
21072a18da7aSGeorge Spelvin  * finds the delimiter after the name.
21082a18da7aSGeorge Spelvin  */
21098387ff25SLinus Torvalds unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
2110bfcfaa77SLinus Torvalds {
21118387ff25SLinus Torvalds 	unsigned long a, x = 0, y = (unsigned long)salt;
2112bfcfaa77SLinus Torvalds 
2113bfcfaa77SLinus Torvalds 	for (;;) {
2114fcfd2fbfSGeorge Spelvin 		if (!len)
2115fcfd2fbfSGeorge Spelvin 			goto done;
2116e419b4ccSLinus Torvalds 		a = load_unaligned_zeropad(name);
2117bfcfaa77SLinus Torvalds 		if (len < sizeof(unsigned long))
2118bfcfaa77SLinus Torvalds 			break;
21192a18da7aSGeorge Spelvin 		HASH_MIX(x, y, a);
2120bfcfaa77SLinus Torvalds 		name += sizeof(unsigned long);
2121bfcfaa77SLinus Torvalds 		len -= sizeof(unsigned long);
2122bfcfaa77SLinus Torvalds 	}
21232a18da7aSGeorge Spelvin 	x ^= a & bytemask_from_count(len);
2124bfcfaa77SLinus Torvalds done:
21252a18da7aSGeorge Spelvin 	return fold_hash(x, y);
2126bfcfaa77SLinus Torvalds }
2127bfcfaa77SLinus Torvalds EXPORT_SYMBOL(full_name_hash);
2128bfcfaa77SLinus Torvalds 
2129fcfd2fbfSGeorge Spelvin /* Return the "hash_len" (hash and length) of a null-terminated string */
21308387ff25SLinus Torvalds u64 hashlen_string(const void *salt, const char *name)
2131fcfd2fbfSGeorge Spelvin {
21328387ff25SLinus Torvalds 	unsigned long a = 0, x = 0, y = (unsigned long)salt;
21338387ff25SLinus Torvalds 	unsigned long adata, mask, len;
2134fcfd2fbfSGeorge Spelvin 	const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2135fcfd2fbfSGeorge Spelvin 
21368387ff25SLinus Torvalds 	len = 0;
21378387ff25SLinus Torvalds 	goto inside;
21388387ff25SLinus Torvalds 
2139fcfd2fbfSGeorge Spelvin 	do {
21402a18da7aSGeorge Spelvin 		HASH_MIX(x, y, a);
2141fcfd2fbfSGeorge Spelvin 		len += sizeof(unsigned long);
21428387ff25SLinus Torvalds inside:
2143fcfd2fbfSGeorge Spelvin 		a = load_unaligned_zeropad(name+len);
2144fcfd2fbfSGeorge Spelvin 	} while (!has_zero(a, &adata, &constants));
2145fcfd2fbfSGeorge Spelvin 
2146fcfd2fbfSGeorge Spelvin 	adata = prep_zero_mask(a, adata, &constants);
2147fcfd2fbfSGeorge Spelvin 	mask = create_zero_mask(adata);
21482a18da7aSGeorge Spelvin 	x ^= a & zero_bytemask(mask);
2149fcfd2fbfSGeorge Spelvin 
21502a18da7aSGeorge Spelvin 	return hashlen_create(fold_hash(x, y), len + find_zero(mask));
2151fcfd2fbfSGeorge Spelvin }
2152fcfd2fbfSGeorge Spelvin EXPORT_SYMBOL(hashlen_string);
2153fcfd2fbfSGeorge Spelvin 
2154bfcfaa77SLinus Torvalds /*
2155bfcfaa77SLinus Torvalds  * Calculate the length and hash of the path component, and
2156d6bb3e90SLinus Torvalds  * return the "hash_len" as the result.
2157bfcfaa77SLinus Torvalds  */
21588387ff25SLinus Torvalds static inline u64 hash_name(const void *salt, const char *name)
2159bfcfaa77SLinus Torvalds {
21608387ff25SLinus Torvalds 	unsigned long a = 0, b, x = 0, y = (unsigned long)salt;
21618387ff25SLinus Torvalds 	unsigned long adata, bdata, mask, len;
216236126f8fSLinus Torvalds 	const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2163bfcfaa77SLinus Torvalds 
21648387ff25SLinus Torvalds 	len = 0;
21658387ff25SLinus Torvalds 	goto inside;
21668387ff25SLinus Torvalds 
2167bfcfaa77SLinus Torvalds 	do {
21682a18da7aSGeorge Spelvin 		HASH_MIX(x, y, a);
2169bfcfaa77SLinus Torvalds 		len += sizeof(unsigned long);
21708387ff25SLinus Torvalds inside:
2171e419b4ccSLinus Torvalds 		a = load_unaligned_zeropad(name+len);
217236126f8fSLinus Torvalds 		b = a ^ REPEAT_BYTE('/');
217336126f8fSLinus Torvalds 	} while (!(has_zero(a, &adata, &constants) | has_zero(b, &bdata, &constants)));
2174bfcfaa77SLinus Torvalds 
217536126f8fSLinus Torvalds 	adata = prep_zero_mask(a, adata, &constants);
217636126f8fSLinus Torvalds 	bdata = prep_zero_mask(b, bdata, &constants);
217736126f8fSLinus Torvalds 	mask = create_zero_mask(adata | bdata);
21782a18da7aSGeorge Spelvin 	x ^= a & zero_bytemask(mask);
217936126f8fSLinus Torvalds 
21802a18da7aSGeorge Spelvin 	return hashlen_create(fold_hash(x, y), len + find_zero(mask));
2181bfcfaa77SLinus Torvalds }
2182bfcfaa77SLinus Torvalds 
21832a18da7aSGeorge Spelvin #else	/* !CONFIG_DCACHE_WORD_ACCESS: Slow, byte-at-a-time version */
2184bfcfaa77SLinus Torvalds 
2185fcfd2fbfSGeorge Spelvin /* Return the hash of a string of known length */
21868387ff25SLinus Torvalds unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
21870145acc2SLinus Torvalds {
21888387ff25SLinus Torvalds 	unsigned long hash = init_name_hash(salt);
21890145acc2SLinus Torvalds 	while (len--)
2190fcfd2fbfSGeorge Spelvin 		hash = partial_name_hash((unsigned char)*name++, hash);
21910145acc2SLinus Torvalds 	return end_name_hash(hash);
21920145acc2SLinus Torvalds }
2193ae942ae7SLinus Torvalds EXPORT_SYMBOL(full_name_hash);
21940145acc2SLinus Torvalds 
2195fcfd2fbfSGeorge Spelvin /* Return the "hash_len" (hash and length) of a null-terminated string */
21968387ff25SLinus Torvalds u64 hashlen_string(const void *salt, const char *name)
2197fcfd2fbfSGeorge Spelvin {
21988387ff25SLinus Torvalds 	unsigned long hash = init_name_hash(salt);
2199fcfd2fbfSGeorge Spelvin 	unsigned long len = 0, c;
2200fcfd2fbfSGeorge Spelvin 
2201fcfd2fbfSGeorge Spelvin 	c = (unsigned char)*name;
2202e0ab7af9SGeorge Spelvin 	while (c) {
2203fcfd2fbfSGeorge Spelvin 		len++;
2204fcfd2fbfSGeorge Spelvin 		hash = partial_name_hash(c, hash);
2205fcfd2fbfSGeorge Spelvin 		c = (unsigned char)name[len];
2206e0ab7af9SGeorge Spelvin 	}
2207fcfd2fbfSGeorge Spelvin 	return hashlen_create(end_name_hash(hash), len);
2208fcfd2fbfSGeorge Spelvin }
2209f2a031b6SGeorge Spelvin EXPORT_SYMBOL(hashlen_string);
2210fcfd2fbfSGeorge Spelvin 
22113ddcd056SLinus Torvalds /*
2212200e9ef7SLinus Torvalds  * We know there's a real path component here of at least
2213200e9ef7SLinus Torvalds  * one character.
2214200e9ef7SLinus Torvalds  */
22158387ff25SLinus Torvalds static inline u64 hash_name(const void *salt, const char *name)
2216200e9ef7SLinus Torvalds {
22178387ff25SLinus Torvalds 	unsigned long hash = init_name_hash(salt);
2218200e9ef7SLinus Torvalds 	unsigned long len = 0, c;
2219200e9ef7SLinus Torvalds 
2220200e9ef7SLinus Torvalds 	c = (unsigned char)*name;
2221200e9ef7SLinus Torvalds 	do {
2222200e9ef7SLinus Torvalds 		len++;
2223200e9ef7SLinus Torvalds 		hash = partial_name_hash(c, hash);
2224200e9ef7SLinus Torvalds 		c = (unsigned char)name[len];
2225200e9ef7SLinus Torvalds 	} while (c && c != '/');
2226d6bb3e90SLinus Torvalds 	return hashlen_create(end_name_hash(hash), len);
2227200e9ef7SLinus Torvalds }
2228200e9ef7SLinus Torvalds 
2229bfcfaa77SLinus Torvalds #endif
2230bfcfaa77SLinus Torvalds 
2231200e9ef7SLinus Torvalds /*
22321da177e4SLinus Torvalds  * Name resolution.
2233ea3834d9SPrasanna Meda  * This is the basic name resolution function, turning a pathname into
2234ea3834d9SPrasanna Meda  * the final dentry. We expect 'base' to be positive and a directory.
22351da177e4SLinus Torvalds  *
2236ea3834d9SPrasanna Meda  * Returns 0 and nd will have valid dentry and mnt on success.
2237ea3834d9SPrasanna Meda  * Returns error and drops reference to input namei data on failure.
22381da177e4SLinus Torvalds  */
22396de88d72SAl Viro static int link_path_walk(const char *name, struct nameidata *nd)
22401da177e4SLinus Torvalds {
2241d8d4611aSAl Viro 	int depth = 0; // depth <= nd->depth
22421da177e4SLinus Torvalds 	int err;
22431da177e4SLinus Torvalds 
2244b4c03536SAl Viro 	nd->last_type = LAST_ROOT;
2245c108837eSAl Viro 	nd->flags |= LOOKUP_PARENT;
22469b5858e9SAl Viro 	if (IS_ERR(name))
22479b5858e9SAl Viro 		return PTR_ERR(name);
22481da177e4SLinus Torvalds 	while (*name=='/')
22491da177e4SLinus Torvalds 		name++;
22501a97d899SAl Viro 	if (!*name) {
22511a97d899SAl Viro 		nd->dir_mode = 0; // short-circuit the 'hardening' idiocy
22529e18f10aSAl Viro 		return 0;
22531a97d899SAl Viro 	}
22541da177e4SLinus Torvalds 
22551da177e4SLinus Torvalds 	/* At this point we know we have a real path component. */
22561da177e4SLinus Torvalds 	for(;;) {
22574609e1f1SChristian Brauner 		struct mnt_idmap *idmap;
225892d27016SAl Viro 		const char *link;
2259d6bb3e90SLinus Torvalds 		u64 hash_len;
2260fe479a58SAl Viro 		int type;
22611da177e4SLinus Torvalds 
22624609e1f1SChristian Brauner 		idmap = mnt_idmap(nd->path.mnt);
22634609e1f1SChristian Brauner 		err = may_lookup(idmap, nd);
22641da177e4SLinus Torvalds 		if (err)
22653595e234SAl Viro 			return err;
22661da177e4SLinus Torvalds 
22678387ff25SLinus Torvalds 		hash_len = hash_name(nd->path.dentry, name);
22681da177e4SLinus Torvalds 
2269fe479a58SAl Viro 		type = LAST_NORM;
2270d6bb3e90SLinus Torvalds 		if (name[0] == '.') switch (hashlen_len(hash_len)) {
2271fe479a58SAl Viro 			case 2:
2272200e9ef7SLinus Torvalds 				if (name[1] == '.') {
2273fe479a58SAl Viro 					type = LAST_DOTDOT;
2274bcba1e7dSAl Viro 					nd->state |= ND_JUMPED;
227516c2cd71SAl Viro 				}
2276fe479a58SAl Viro 				break;
2277fe479a58SAl Viro 			case 1:
2278fe479a58SAl Viro 				type = LAST_DOT;
2279fe479a58SAl Viro 		}
22805a202bcdSAl Viro 		if (likely(type == LAST_NORM)) {
22815a202bcdSAl Viro 			struct dentry *parent = nd->path.dentry;
2282bcba1e7dSAl Viro 			nd->state &= ~ND_JUMPED;
22835a202bcdSAl Viro 			if (unlikely(parent->d_flags & DCACHE_OP_HASH)) {
2284a060dc50SJames Hogan 				struct qstr this = { { .hash_len = hash_len }, .name = name };
2285da53be12SLinus Torvalds 				err = parent->d_op->d_hash(parent, &this);
22865a202bcdSAl Viro 				if (err < 0)
22873595e234SAl Viro 					return err;
2288d6bb3e90SLinus Torvalds 				hash_len = this.hash_len;
2289d6bb3e90SLinus Torvalds 				name = this.name;
22905a202bcdSAl Viro 			}
22915a202bcdSAl Viro 		}
2292fe479a58SAl Viro 
2293d6bb3e90SLinus Torvalds 		nd->last.hash_len = hash_len;
2294d6bb3e90SLinus Torvalds 		nd->last.name = name;
22955f4a6a69SAl Viro 		nd->last_type = type;
22965f4a6a69SAl Viro 
2297d6bb3e90SLinus Torvalds 		name += hashlen_len(hash_len);
2298d6bb3e90SLinus Torvalds 		if (!*name)
2299bdf6cbf1SAl Viro 			goto OK;
2300200e9ef7SLinus Torvalds 		/*
2301200e9ef7SLinus Torvalds 		 * If it wasn't NUL, we know it was '/'. Skip that
2302200e9ef7SLinus Torvalds 		 * slash, and continue until no more slashes.
2303200e9ef7SLinus Torvalds 		 */
2304200e9ef7SLinus Torvalds 		do {
2305d6bb3e90SLinus Torvalds 			name++;
2306d6bb3e90SLinus Torvalds 		} while (unlikely(*name == '/'));
23078620c238SAl Viro 		if (unlikely(!*name)) {
23088620c238SAl Viro OK:
2309d8d4611aSAl Viro 			/* pathname or trailing symlink, done */
2310c108837eSAl Viro 			if (!depth) {
2311e67fe633SChristian Brauner 				nd->dir_vfsuid = i_uid_into_vfsuid(idmap, nd->inode);
23120f705953SAl Viro 				nd->dir_mode = nd->inode->i_mode;
2313c108837eSAl Viro 				nd->flags &= ~LOOKUP_PARENT;
23148620c238SAl Viro 				return 0;
2315c108837eSAl Viro 			}
23168620c238SAl Viro 			/* last component of nested symlink */
2317d8d4611aSAl Viro 			name = nd->stack[--depth].name;
23188c4efe22SAl Viro 			link = walk_component(nd, 0);
23191c4ff1a8SAl Viro 		} else {
23201c4ff1a8SAl Viro 			/* not the last component */
23218c4efe22SAl Viro 			link = walk_component(nd, WALK_MORE);
23228620c238SAl Viro 		}
232392d27016SAl Viro 		if (unlikely(link)) {
232492d27016SAl Viro 			if (IS_ERR(link))
232592d27016SAl Viro 				return PTR_ERR(link);
232692d27016SAl Viro 			/* a symlink to follow */
2327d8d4611aSAl Viro 			nd->stack[depth++].name = name;
232892d27016SAl Viro 			name = link;
23299e18f10aSAl Viro 			continue;
233048c8b0c5SAl Viro 		}
233197242f99SAl Viro 		if (unlikely(!d_can_lookup(nd->path.dentry))) {
233297242f99SAl Viro 			if (nd->flags & LOOKUP_RCU) {
2333e36cffedSJens Axboe 				if (!try_to_unlazy(nd))
233497242f99SAl Viro 					return -ECHILD;
233597242f99SAl Viro 			}
23363595e234SAl Viro 			return -ENOTDIR;
23375f4a6a69SAl Viro 		}
2338ce57dfc1SAl Viro 	}
233997242f99SAl Viro }
23401da177e4SLinus Torvalds 
2341edc2b1daSAl Viro /* must be paired with terminate_walk() */
2342c8a53ee5SAl Viro static const char *path_init(struct nameidata *nd, unsigned flags)
234331e6b01fSNick Piggin {
2344740a1678SAleksa Sarai 	int error;
2345c8a53ee5SAl Viro 	const char *s = nd->name->name;
234631e6b01fSNick Piggin 
23476c6ec2b0SJens Axboe 	/* LOOKUP_CACHED requires RCU, ask caller to retry */
23486c6ec2b0SJens Axboe 	if ((flags & (LOOKUP_RCU | LOOKUP_CACHED)) == LOOKUP_CACHED)
23496c6ec2b0SJens Axboe 		return ERR_PTR(-EAGAIN);
23506c6ec2b0SJens Axboe 
2351c0eb027eSLinus Torvalds 	if (!*s)
2352c0eb027eSLinus Torvalds 		flags &= ~LOOKUP_RCU;
2353edc2b1daSAl Viro 	if (flags & LOOKUP_RCU)
2354edc2b1daSAl Viro 		rcu_read_lock();
235503fa86e9SAl Viro 	else
235603fa86e9SAl Viro 		nd->seq = nd->next_seq = 0;
2357c0eb027eSLinus Torvalds 
2358bcba1e7dSAl Viro 	nd->flags = flags;
2359bcba1e7dSAl Viro 	nd->state |= ND_JUMPED;
2360ab87f9a5SAleksa Sarai 
2361ab87f9a5SAleksa Sarai 	nd->m_seq = __read_seqcount_begin(&mount_lock.seqcount);
2362ab87f9a5SAleksa Sarai 	nd->r_seq = __read_seqcount_begin(&rename_lock.seqcount);
2363ab87f9a5SAleksa Sarai 	smp_rmb();
2364ab87f9a5SAleksa Sarai 
2365bcba1e7dSAl Viro 	if (nd->state & ND_ROOT_PRESET) {
2366b18825a7SDavid Howells 		struct dentry *root = nd->root.dentry;
2367b18825a7SDavid Howells 		struct inode *inode = root->d_inode;
236893893862SAl Viro 		if (*s && unlikely(!d_can_lookup(root)))
2369368ee9baSAl Viro 			return ERR_PTR(-ENOTDIR);
23705b6ca027SAl Viro 		nd->path = nd->root;
23715b6ca027SAl Viro 		nd->inode = inode;
23725b6ca027SAl Viro 		if (flags & LOOKUP_RCU) {
2373ab87f9a5SAleksa Sarai 			nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
23748f47a016SAl Viro 			nd->root_seq = nd->seq;
23755b6ca027SAl Viro 		} else {
23765b6ca027SAl Viro 			path_get(&nd->path);
23775b6ca027SAl Viro 		}
2378368ee9baSAl Viro 		return s;
23795b6ca027SAl Viro 	}
23805b6ca027SAl Viro 
238131e6b01fSNick Piggin 	nd->root.mnt = NULL;
238231e6b01fSNick Piggin 
23838db52c7eSAleksa Sarai 	/* Absolute pathname -- fetch the root (LOOKUP_IN_ROOT uses nd->dfd). */
23848db52c7eSAleksa Sarai 	if (*s == '/' && !(flags & LOOKUP_IN_ROOT)) {
2385740a1678SAleksa Sarai 		error = nd_jump_root(nd);
2386740a1678SAleksa Sarai 		if (unlikely(error))
2387740a1678SAleksa Sarai 			return ERR_PTR(error);
2388ef55d917SAl Viro 		return s;
23898db52c7eSAleksa Sarai 	}
23908db52c7eSAleksa Sarai 
23918db52c7eSAleksa Sarai 	/* Relative pathname -- get the starting-point it is relative to. */
23928db52c7eSAleksa Sarai 	if (nd->dfd == AT_FDCWD) {
2393e41f7d4eSAl Viro 		if (flags & LOOKUP_RCU) {
239431e6b01fSNick Piggin 			struct fs_struct *fs = current->fs;
2395c28cc364SNick Piggin 			unsigned seq;
239631e6b01fSNick Piggin 
2397c28cc364SNick Piggin 			do {
2398c28cc364SNick Piggin 				seq = read_seqcount_begin(&fs->seq);
239931e6b01fSNick Piggin 				nd->path = fs->pwd;
2400ef55d917SAl Viro 				nd->inode = nd->path.dentry->d_inode;
2401c28cc364SNick Piggin 				nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
2402c28cc364SNick Piggin 			} while (read_seqcount_retry(&fs->seq, seq));
2403e41f7d4eSAl Viro 		} else {
2404e41f7d4eSAl Viro 			get_fs_pwd(current->fs, &nd->path);
2405ef55d917SAl Viro 			nd->inode = nd->path.dentry->d_inode;
2406e41f7d4eSAl Viro 		}
240731e6b01fSNick Piggin 	} else {
2408582aa64aSJeff Layton 		/* Caller must check execute permissions on the starting path component */
2409c8a53ee5SAl Viro 		struct fd f = fdget_raw(nd->dfd);
241031e6b01fSNick Piggin 		struct dentry *dentry;
241131e6b01fSNick Piggin 
24122903ff01SAl Viro 		if (!f.file)
2413368ee9baSAl Viro 			return ERR_PTR(-EBADF);
241431e6b01fSNick Piggin 
24152903ff01SAl Viro 		dentry = f.file->f_path.dentry;
241631e6b01fSNick Piggin 
2417edc2b1daSAl Viro 		if (*s && unlikely(!d_can_lookup(dentry))) {
24182903ff01SAl Viro 			fdput(f);
2419368ee9baSAl Viro 			return ERR_PTR(-ENOTDIR);
2420f52e0c11SAl Viro 		}
24212903ff01SAl Viro 
24222903ff01SAl Viro 		nd->path = f.file->f_path;
2423e41f7d4eSAl Viro 		if (flags & LOOKUP_RCU) {
242434a26b99SAl Viro 			nd->inode = nd->path.dentry->d_inode;
242534a26b99SAl Viro 			nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
24265590ff0dSUlrich Drepper 		} else {
24272903ff01SAl Viro 			path_get(&nd->path);
242834a26b99SAl Viro 			nd->inode = nd->path.dentry->d_inode;
24291da177e4SLinus Torvalds 		}
243034a26b99SAl Viro 		fdput(f);
2431e41f7d4eSAl Viro 	}
24328db52c7eSAleksa Sarai 
2433adb21d2bSAleksa Sarai 	/* For scoped-lookups we need to set the root to the dirfd as well. */
2434adb21d2bSAleksa Sarai 	if (flags & LOOKUP_IS_SCOPED) {
2435adb21d2bSAleksa Sarai 		nd->root = nd->path;
2436adb21d2bSAleksa Sarai 		if (flags & LOOKUP_RCU) {
2437adb21d2bSAleksa Sarai 			nd->root_seq = nd->seq;
2438adb21d2bSAleksa Sarai 		} else {
2439adb21d2bSAleksa Sarai 			path_get(&nd->root);
2440bcba1e7dSAl Viro 			nd->state |= ND_ROOT_GRABBED;
2441adb21d2bSAleksa Sarai 		}
2442adb21d2bSAleksa Sarai 	}
2443adb21d2bSAleksa Sarai 	return s;
24449b4a9b14SAl Viro }
24459b4a9b14SAl Viro 
24461ccac622SAl Viro static inline const char *lookup_last(struct nameidata *nd)
244795fa25d9SAl Viro {
2448bd92d7feSAl Viro 	if (nd->last_type == LAST_NORM && nd->last.name[nd->last.len])
2449bd92d7feSAl Viro 		nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
2450bd92d7feSAl Viro 
2451c108837eSAl Viro 	return walk_component(nd, WALK_TRAILING);
2452bd92d7feSAl Viro }
2453bd92d7feSAl Viro 
24544f757f3cSAl Viro static int handle_lookup_down(struct nameidata *nd)
24554f757f3cSAl Viro {
2456c153007bSAl Viro 	if (!(nd->flags & LOOKUP_RCU))
2457db3c9adeSAl Viro 		dget(nd->path.dentry);
245803fa86e9SAl Viro 	nd->next_seq = nd->seq;
2459a4f5b521SAl Viro 	return PTR_ERR(step_into(nd, WALK_NOFOLLOW, nd->path.dentry));
24604f757f3cSAl Viro }
24614f757f3cSAl Viro 
24629b4a9b14SAl Viro /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
2463c8a53ee5SAl Viro static int path_lookupat(struct nameidata *nd, unsigned flags, struct path *path)
24649b4a9b14SAl Viro {
2465c8a53ee5SAl Viro 	const char *s = path_init(nd, flags);
2466bd92d7feSAl Viro 	int err;
246731e6b01fSNick Piggin 
24689b5858e9SAl Viro 	if (unlikely(flags & LOOKUP_DOWN) && !IS_ERR(s)) {
24694f757f3cSAl Viro 		err = handle_lookup_down(nd);
24705f336e72SAl Viro 		if (unlikely(err < 0))
24715f336e72SAl Viro 			s = ERR_PTR(err);
24724f757f3cSAl Viro 	}
24734f757f3cSAl Viro 
24741ccac622SAl Viro 	while (!(err = link_path_walk(s, nd)) &&
24751ccac622SAl Viro 	       (s = lookup_last(nd)) != NULL)
24761ccac622SAl Viro 		;
24774f0ed93fSAl Viro 	if (!err && unlikely(nd->flags & LOOKUP_MOUNTPOINT)) {
24784f0ed93fSAl Viro 		err = handle_lookup_down(nd);
2479bcba1e7dSAl Viro 		nd->state &= ~ND_JUMPED; // no d_weak_revalidate(), please...
24804f0ed93fSAl Viro 	}
24819f1fafeeSAl Viro 	if (!err)
24829f1fafeeSAl Viro 		err = complete_walk(nd);
2483bd92d7feSAl Viro 
2484deb106c6SAl Viro 	if (!err && nd->flags & LOOKUP_DIRECTORY)
2485deb106c6SAl Viro 		if (!d_can_lookup(nd->path.dentry))
2486bd23a539SAl Viro 			err = -ENOTDIR;
2487625b6d10SAl Viro 	if (!err) {
2488625b6d10SAl Viro 		*path = nd->path;
2489625b6d10SAl Viro 		nd->path.mnt = NULL;
2490625b6d10SAl Viro 		nd->path.dentry = NULL;
2491625b6d10SAl Viro 	}
2492deb106c6SAl Viro 	terminate_walk(nd);
2493bd92d7feSAl Viro 	return err;
249431e6b01fSNick Piggin }
249531e6b01fSNick Piggin 
2496794ebceaSStephen Brennan int filename_lookup(int dfd, struct filename *name, unsigned flags,
24979ad1aaa6SAl Viro 		    struct path *path, struct path *root)
2498873f1eedSJeff Layton {
2499894bc8c4SAl Viro 	int retval;
25009883d185SAl Viro 	struct nameidata nd;
2501abc9f5beSAl Viro 	if (IS_ERR(name))
2502abc9f5beSAl Viro 		return PTR_ERR(name);
250306422964SAl Viro 	set_nameidata(&nd, dfd, name, root);
2504c8a53ee5SAl Viro 	retval = path_lookupat(&nd, flags | LOOKUP_RCU, path);
2505873f1eedSJeff Layton 	if (unlikely(retval == -ECHILD))
2506c8a53ee5SAl Viro 		retval = path_lookupat(&nd, flags, path);
2507873f1eedSJeff Layton 	if (unlikely(retval == -ESTALE))
2508c8a53ee5SAl Viro 		retval = path_lookupat(&nd, flags | LOOKUP_REVAL, path);
2509873f1eedSJeff Layton 
2510873f1eedSJeff Layton 	if (likely(!retval))
2511161aff1dSAl Viro 		audit_inode(name, path->dentry,
2512161aff1dSAl Viro 			    flags & LOOKUP_MOUNTPOINT ? AUDIT_INODE_NOEVAL : 0);
25139883d185SAl Viro 	restore_nameidata();
2514020250f3SDmitry Kadashev 	return retval;
2515020250f3SDmitry Kadashev }
2516020250f3SDmitry Kadashev 
25178bcb77faSAl Viro /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
2518c8a53ee5SAl Viro static int path_parentat(struct nameidata *nd, unsigned flags,
2519391172c4SAl Viro 				struct path *parent)
25208bcb77faSAl Viro {
2521c8a53ee5SAl Viro 	const char *s = path_init(nd, flags);
25229b5858e9SAl Viro 	int err = link_path_walk(s, nd);
25238bcb77faSAl Viro 	if (!err)
25248bcb77faSAl Viro 		err = complete_walk(nd);
2525391172c4SAl Viro 	if (!err) {
2526391172c4SAl Viro 		*parent = nd->path;
2527391172c4SAl Viro 		nd->path.mnt = NULL;
2528391172c4SAl Viro 		nd->path.dentry = NULL;
2529391172c4SAl Viro 	}
2530deb106c6SAl Viro 	terminate_walk(nd);
25318bcb77faSAl Viro 	return err;
25328bcb77faSAl Viro }
25338bcb77faSAl Viro 
25340766ec82SStephen Brennan /* Note: this does not consume "name" */
2535c5f563f9SAl Viro static int filename_parentat(int dfd, struct filename *name,
2536391172c4SAl Viro 			     unsigned int flags, struct path *parent,
2537391172c4SAl Viro 			     struct qstr *last, int *type)
25388bcb77faSAl Viro {
25398bcb77faSAl Viro 	int retval;
25409883d185SAl Viro 	struct nameidata nd;
25418bcb77faSAl Viro 
25425c31b6ceSAl Viro 	if (IS_ERR(name))
25430ee50b47SDmitry Kadashev 		return PTR_ERR(name);
254406422964SAl Viro 	set_nameidata(&nd, dfd, name, NULL);
2545c8a53ee5SAl Viro 	retval = path_parentat(&nd, flags | LOOKUP_RCU, parent);
25468bcb77faSAl Viro 	if (unlikely(retval == -ECHILD))
2547c8a53ee5SAl Viro 		retval = path_parentat(&nd, flags, parent);
25488bcb77faSAl Viro 	if (unlikely(retval == -ESTALE))
2549c8a53ee5SAl Viro 		retval = path_parentat(&nd, flags | LOOKUP_REVAL, parent);
2550391172c4SAl Viro 	if (likely(!retval)) {
2551391172c4SAl Viro 		*last = nd.last;
2552391172c4SAl Viro 		*type = nd.last_type;
2553c9b07eabSAl Viro 		audit_inode(name, parent->dentry, AUDIT_INODE_PARENT);
2554391172c4SAl Viro 	}
25559883d185SAl Viro 	restore_nameidata();
25560ee50b47SDmitry Kadashev 	return retval;
25570ee50b47SDmitry Kadashev }
25580ee50b47SDmitry Kadashev 
255979714f72SAl Viro /* does lookup, returns the object with parent locked */
25600766ec82SStephen Brennan static struct dentry *__kern_path_locked(struct filename *name, struct path *path)
25615590ff0dSUlrich Drepper {
25625c31b6ceSAl Viro 	struct dentry *d;
2563391172c4SAl Viro 	struct qstr last;
25640ee50b47SDmitry Kadashev 	int type, error;
256551689104SPaul Moore 
2566c5f563f9SAl Viro 	error = filename_parentat(AT_FDCWD, name, 0, path, &last, &type);
25670ee50b47SDmitry Kadashev 	if (error)
25680ee50b47SDmitry Kadashev 		return ERR_PTR(error);
25695c31b6ceSAl Viro 	if (unlikely(type != LAST_NORM)) {
2570391172c4SAl Viro 		path_put(path);
25715c31b6ceSAl Viro 		return ERR_PTR(-EINVAL);
257279714f72SAl Viro 	}
25735955102cSAl Viro 	inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
2574391172c4SAl Viro 	d = __lookup_hash(&last, path->dentry, 0);
257579714f72SAl Viro 	if (IS_ERR(d)) {
25765955102cSAl Viro 		inode_unlock(path->dentry->d_inode);
2577391172c4SAl Viro 		path_put(path);
257879714f72SAl Viro 	}
257979714f72SAl Viro 	return d;
25805590ff0dSUlrich Drepper }
25815590ff0dSUlrich Drepper 
25820766ec82SStephen Brennan struct dentry *kern_path_locked(const char *name, struct path *path)
25830766ec82SStephen Brennan {
25840766ec82SStephen Brennan 	struct filename *filename = getname_kernel(name);
25850766ec82SStephen Brennan 	struct dentry *res = __kern_path_locked(filename, path);
25860766ec82SStephen Brennan 
25870766ec82SStephen Brennan 	putname(filename);
25880766ec82SStephen Brennan 	return res;
25890766ec82SStephen Brennan }
25900766ec82SStephen Brennan 
2591d1811465SAl Viro int kern_path(const char *name, unsigned int flags, struct path *path)
2592d1811465SAl Viro {
2593794ebceaSStephen Brennan 	struct filename *filename = getname_kernel(name);
2594794ebceaSStephen Brennan 	int ret = filename_lookup(AT_FDCWD, filename, flags, path, NULL);
2595794ebceaSStephen Brennan 
2596794ebceaSStephen Brennan 	putname(filename);
2597794ebceaSStephen Brennan 	return ret;
2598794ebceaSStephen Brennan 
2599d1811465SAl Viro }
26004d359507SAl Viro EXPORT_SYMBOL(kern_path);
2601d1811465SAl Viro 
260216f18200SJosef 'Jeff' Sipek /**
260316f18200SJosef 'Jeff' Sipek  * vfs_path_lookup - lookup a file path relative to a dentry-vfsmount pair
260416f18200SJosef 'Jeff' Sipek  * @dentry:  pointer to dentry of the base directory
260516f18200SJosef 'Jeff' Sipek  * @mnt: pointer to vfs mount of the base directory
260616f18200SJosef 'Jeff' Sipek  * @name: pointer to file name
260716f18200SJosef 'Jeff' Sipek  * @flags: lookup flags
2608e0a01249SAl Viro  * @path: pointer to struct path to fill
260916f18200SJosef 'Jeff' Sipek  */
261016f18200SJosef 'Jeff' Sipek int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt,
261116f18200SJosef 'Jeff' Sipek 		    const char *name, unsigned int flags,
2612e0a01249SAl Viro 		    struct path *path)
261316f18200SJosef 'Jeff' Sipek {
2614794ebceaSStephen Brennan 	struct filename *filename;
26159ad1aaa6SAl Viro 	struct path root = {.mnt = mnt, .dentry = dentry};
2616794ebceaSStephen Brennan 	int ret;
2617794ebceaSStephen Brennan 
2618794ebceaSStephen Brennan 	filename = getname_kernel(name);
26199ad1aaa6SAl Viro 	/* the first argument of filename_lookup() is ignored with root */
2620794ebceaSStephen Brennan 	ret = filename_lookup(AT_FDCWD, filename, flags, path, &root);
2621794ebceaSStephen Brennan 	putname(filename);
2622794ebceaSStephen Brennan 	return ret;
262316f18200SJosef 'Jeff' Sipek }
26244d359507SAl Viro EXPORT_SYMBOL(vfs_path_lookup);
262516f18200SJosef 'Jeff' Sipek 
26264609e1f1SChristian Brauner static int lookup_one_common(struct mnt_idmap *idmap,
2627c2fd68b6SChristian Brauner 			     const char *name, struct dentry *base, int len,
2628c2fd68b6SChristian Brauner 			     struct qstr *this)
26293c95f0dcSAl Viro {
26303c95f0dcSAl Viro 	this->name = name;
26313c95f0dcSAl Viro 	this->len = len;
26323c95f0dcSAl Viro 	this->hash = full_name_hash(base, name, len);
26333c95f0dcSAl Viro 	if (!len)
26343c95f0dcSAl Viro 		return -EACCES;
26353c95f0dcSAl Viro 
26363c95f0dcSAl Viro 	if (unlikely(name[0] == '.')) {
26373c95f0dcSAl Viro 		if (len < 2 || (len == 2 && name[1] == '.'))
26383c95f0dcSAl Viro 			return -EACCES;
26393c95f0dcSAl Viro 	}
26403c95f0dcSAl Viro 
26413c95f0dcSAl Viro 	while (len--) {
26423c95f0dcSAl Viro 		unsigned int c = *(const unsigned char *)name++;
26433c95f0dcSAl Viro 		if (c == '/' || c == '\0')
26443c95f0dcSAl Viro 			return -EACCES;
26453c95f0dcSAl Viro 	}
26463c95f0dcSAl Viro 	/*
26473c95f0dcSAl Viro 	 * See if the low-level filesystem might want
26483c95f0dcSAl Viro 	 * to use its own hash..
26493c95f0dcSAl Viro 	 */
26503c95f0dcSAl Viro 	if (base->d_flags & DCACHE_OP_HASH) {
26513c95f0dcSAl Viro 		int err = base->d_op->d_hash(base, this);
26523c95f0dcSAl Viro 		if (err < 0)
26533c95f0dcSAl Viro 			return err;
26543c95f0dcSAl Viro 	}
26553c95f0dcSAl Viro 
26564609e1f1SChristian Brauner 	return inode_permission(idmap, base->d_inode, MAY_EXEC);
26573c95f0dcSAl Viro }
26583c95f0dcSAl Viro 
2659eead1911SChristoph Hellwig /**
26600da0b7fdSDavid Howells  * try_lookup_one_len - filesystem helper to lookup single pathname component
26610da0b7fdSDavid Howells  * @name:	pathname component to lookup
26620da0b7fdSDavid Howells  * @base:	base directory to lookup from
26630da0b7fdSDavid Howells  * @len:	maximum length @len should be interpreted to
26640da0b7fdSDavid Howells  *
26650da0b7fdSDavid Howells  * Look up a dentry by name in the dcache, returning NULL if it does not
26660da0b7fdSDavid Howells  * currently exist.  The function does not try to create a dentry.
26670da0b7fdSDavid Howells  *
26680da0b7fdSDavid Howells  * Note that this routine is purely a helper for filesystem usage and should
26690da0b7fdSDavid Howells  * not be called by generic code.
26700da0b7fdSDavid Howells  *
26710da0b7fdSDavid Howells  * The caller must hold base->i_mutex.
26720da0b7fdSDavid Howells  */
26730da0b7fdSDavid Howells struct dentry *try_lookup_one_len(const char *name, struct dentry *base, int len)
26740da0b7fdSDavid Howells {
26750da0b7fdSDavid Howells 	struct qstr this;
26760da0b7fdSDavid Howells 	int err;
26770da0b7fdSDavid Howells 
26780da0b7fdSDavid Howells 	WARN_ON_ONCE(!inode_is_locked(base->d_inode));
26790da0b7fdSDavid Howells 
26804609e1f1SChristian Brauner 	err = lookup_one_common(&nop_mnt_idmap, name, base, len, &this);
26810da0b7fdSDavid Howells 	if (err)
26820da0b7fdSDavid Howells 		return ERR_PTR(err);
26830da0b7fdSDavid Howells 
26840da0b7fdSDavid Howells 	return lookup_dcache(&this, base, 0);
26850da0b7fdSDavid Howells }
26860da0b7fdSDavid Howells EXPORT_SYMBOL(try_lookup_one_len);
26870da0b7fdSDavid Howells 
26880da0b7fdSDavid Howells /**
2689a6b91919SRandy Dunlap  * lookup_one_len - filesystem helper to lookup single pathname component
2690eead1911SChristoph Hellwig  * @name:	pathname component to lookup
2691eead1911SChristoph Hellwig  * @base:	base directory to lookup from
2692eead1911SChristoph Hellwig  * @len:	maximum length @len should be interpreted to
2693eead1911SChristoph Hellwig  *
2694a6b91919SRandy Dunlap  * Note that this routine is purely a helper for filesystem usage and should
26959e7543e9SAl Viro  * not be called by generic code.
2696bbddca8eSNeilBrown  *
2697bbddca8eSNeilBrown  * The caller must hold base->i_mutex.
2698eead1911SChristoph Hellwig  */
2699057f6c01SJames Morris struct dentry *lookup_one_len(const char *name, struct dentry *base, int len)
2700057f6c01SJames Morris {
27018613a209SAl Viro 	struct dentry *dentry;
2702057f6c01SJames Morris 	struct qstr this;
2703cda309deSMiklos Szeredi 	int err;
2704057f6c01SJames Morris 
27055955102cSAl Viro 	WARN_ON_ONCE(!inode_is_locked(base->d_inode));
27062f9092e1SDavid Woodhouse 
27074609e1f1SChristian Brauner 	err = lookup_one_common(&nop_mnt_idmap, name, base, len, &this);
2708cda309deSMiklos Szeredi 	if (err)
2709cda309deSMiklos Szeredi 		return ERR_PTR(err);
2710cda309deSMiklos Szeredi 
27118613a209SAl Viro 	dentry = lookup_dcache(&this, base, 0);
27128613a209SAl Viro 	return dentry ? dentry : __lookup_slow(&this, base, 0);
2713057f6c01SJames Morris }
27144d359507SAl Viro EXPORT_SYMBOL(lookup_one_len);
2715057f6c01SJames Morris 
2716bbddca8eSNeilBrown /**
2717c2fd68b6SChristian Brauner  * lookup_one - filesystem helper to lookup single pathname component
27184609e1f1SChristian Brauner  * @idmap:	idmap of the mount the lookup is performed from
2719c2fd68b6SChristian Brauner  * @name:	pathname component to lookup
2720c2fd68b6SChristian Brauner  * @base:	base directory to lookup from
2721c2fd68b6SChristian Brauner  * @len:	maximum length @len should be interpreted to
2722c2fd68b6SChristian Brauner  *
2723c2fd68b6SChristian Brauner  * Note that this routine is purely a helper for filesystem usage and should
2724c2fd68b6SChristian Brauner  * not be called by generic code.
2725c2fd68b6SChristian Brauner  *
2726c2fd68b6SChristian Brauner  * The caller must hold base->i_mutex.
2727c2fd68b6SChristian Brauner  */
27284609e1f1SChristian Brauner struct dentry *lookup_one(struct mnt_idmap *idmap, const char *name,
2729c2fd68b6SChristian Brauner 			  struct dentry *base, int len)
2730c2fd68b6SChristian Brauner {
2731c2fd68b6SChristian Brauner 	struct dentry *dentry;
2732c2fd68b6SChristian Brauner 	struct qstr this;
2733c2fd68b6SChristian Brauner 	int err;
2734c2fd68b6SChristian Brauner 
2735c2fd68b6SChristian Brauner 	WARN_ON_ONCE(!inode_is_locked(base->d_inode));
2736c2fd68b6SChristian Brauner 
27374609e1f1SChristian Brauner 	err = lookup_one_common(idmap, name, base, len, &this);
2738c2fd68b6SChristian Brauner 	if (err)
2739c2fd68b6SChristian Brauner 		return ERR_PTR(err);
2740c2fd68b6SChristian Brauner 
2741c2fd68b6SChristian Brauner 	dentry = lookup_dcache(&this, base, 0);
2742c2fd68b6SChristian Brauner 	return dentry ? dentry : __lookup_slow(&this, base, 0);
2743c2fd68b6SChristian Brauner }
2744c2fd68b6SChristian Brauner EXPORT_SYMBOL(lookup_one);
2745c2fd68b6SChristian Brauner 
2746c2fd68b6SChristian Brauner /**
274700675017SChristian Brauner  * lookup_one_unlocked - filesystem helper to lookup single pathname component
27484609e1f1SChristian Brauner  * @idmap:	idmap of the mount the lookup is performed from
274900675017SChristian Brauner  * @name:	pathname component to lookup
275000675017SChristian Brauner  * @base:	base directory to lookup from
275100675017SChristian Brauner  * @len:	maximum length @len should be interpreted to
275200675017SChristian Brauner  *
275300675017SChristian Brauner  * Note that this routine is purely a helper for filesystem usage and should
275400675017SChristian Brauner  * not be called by generic code.
275500675017SChristian Brauner  *
275600675017SChristian Brauner  * Unlike lookup_one_len, it should be called without the parent
275700675017SChristian Brauner  * i_mutex held, and will take the i_mutex itself if necessary.
275800675017SChristian Brauner  */
27594609e1f1SChristian Brauner struct dentry *lookup_one_unlocked(struct mnt_idmap *idmap,
276000675017SChristian Brauner 				   const char *name, struct dentry *base,
276100675017SChristian Brauner 				   int len)
276200675017SChristian Brauner {
276300675017SChristian Brauner 	struct qstr this;
276400675017SChristian Brauner 	int err;
276500675017SChristian Brauner 	struct dentry *ret;
276600675017SChristian Brauner 
27674609e1f1SChristian Brauner 	err = lookup_one_common(idmap, name, base, len, &this);
276800675017SChristian Brauner 	if (err)
276900675017SChristian Brauner 		return ERR_PTR(err);
277000675017SChristian Brauner 
277100675017SChristian Brauner 	ret = lookup_dcache(&this, base, 0);
277200675017SChristian Brauner 	if (!ret)
277300675017SChristian Brauner 		ret = lookup_slow(&this, base, 0);
277400675017SChristian Brauner 	return ret;
277500675017SChristian Brauner }
277600675017SChristian Brauner EXPORT_SYMBOL(lookup_one_unlocked);
277700675017SChristian Brauner 
277800675017SChristian Brauner /**
277900675017SChristian Brauner  * lookup_one_positive_unlocked - filesystem helper to lookup single
278000675017SChristian Brauner  *				  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  * This helper will yield ERR_PTR(-ENOENT) on negatives. The helper returns
278700675017SChristian Brauner  * known positive or ERR_PTR(). This is what most of the users want.
278800675017SChristian Brauner  *
278900675017SChristian Brauner  * Note that pinned negative with unlocked parent _can_ become positive at any
279000675017SChristian Brauner  * time, so callers of lookup_one_unlocked() need to be very careful; pinned
279100675017SChristian Brauner  * positives have >d_inode stable, so this one avoids such problems.
279200675017SChristian Brauner  *
279300675017SChristian Brauner  * Note that this routine is purely a helper for filesystem usage and should
279400675017SChristian Brauner  * not be called by generic code.
279500675017SChristian Brauner  *
279600675017SChristian Brauner  * The helper should be called without i_mutex held.
279700675017SChristian Brauner  */
27984609e1f1SChristian Brauner struct dentry *lookup_one_positive_unlocked(struct mnt_idmap *idmap,
279900675017SChristian Brauner 					    const char *name,
280000675017SChristian Brauner 					    struct dentry *base, int len)
280100675017SChristian Brauner {
28024609e1f1SChristian Brauner 	struct dentry *ret = lookup_one_unlocked(idmap, name, base, len);
280300675017SChristian Brauner 
280400675017SChristian Brauner 	if (!IS_ERR(ret) && d_flags_negative(smp_load_acquire(&ret->d_flags))) {
280500675017SChristian Brauner 		dput(ret);
280600675017SChristian Brauner 		ret = ERR_PTR(-ENOENT);
280700675017SChristian Brauner 	}
280800675017SChristian Brauner 	return ret;
280900675017SChristian Brauner }
281000675017SChristian Brauner EXPORT_SYMBOL(lookup_one_positive_unlocked);
281100675017SChristian Brauner 
281200675017SChristian Brauner /**
2813bbddca8eSNeilBrown  * lookup_one_len_unlocked - filesystem helper to lookup single pathname component
2814bbddca8eSNeilBrown  * @name:	pathname component to lookup
2815bbddca8eSNeilBrown  * @base:	base directory to lookup from
2816bbddca8eSNeilBrown  * @len:	maximum length @len should be interpreted to
2817bbddca8eSNeilBrown  *
2818bbddca8eSNeilBrown  * Note that this routine is purely a helper for filesystem usage and should
2819bbddca8eSNeilBrown  * not be called by generic code.
2820bbddca8eSNeilBrown  *
2821bbddca8eSNeilBrown  * Unlike lookup_one_len, it should be called without the parent
2822bbddca8eSNeilBrown  * i_mutex held, and will take the i_mutex itself if necessary.
2823bbddca8eSNeilBrown  */
2824bbddca8eSNeilBrown struct dentry *lookup_one_len_unlocked(const char *name,
2825bbddca8eSNeilBrown 				       struct dentry *base, int len)
2826bbddca8eSNeilBrown {
28274609e1f1SChristian Brauner 	return lookup_one_unlocked(&nop_mnt_idmap, name, base, len);
2828bbddca8eSNeilBrown }
2829bbddca8eSNeilBrown EXPORT_SYMBOL(lookup_one_len_unlocked);
2830bbddca8eSNeilBrown 
28316c2d4798SAl Viro /*
28326c2d4798SAl Viro  * Like lookup_one_len_unlocked(), except that it yields ERR_PTR(-ENOENT)
28336c2d4798SAl Viro  * on negatives.  Returns known positive or ERR_PTR(); that's what
28346c2d4798SAl Viro  * most of the users want.  Note that pinned negative with unlocked parent
28356c2d4798SAl Viro  * _can_ become positive at any time, so callers of lookup_one_len_unlocked()
28366c2d4798SAl Viro  * need to be very careful; pinned positives have ->d_inode stable, so
28376c2d4798SAl Viro  * this one avoids such problems.
28386c2d4798SAl Viro  */
28396c2d4798SAl Viro struct dentry *lookup_positive_unlocked(const char *name,
28406c2d4798SAl Viro 				       struct dentry *base, int len)
28416c2d4798SAl Viro {
28424609e1f1SChristian Brauner 	return lookup_one_positive_unlocked(&nop_mnt_idmap, name, base, len);
28436c2d4798SAl Viro }
28446c2d4798SAl Viro EXPORT_SYMBOL(lookup_positive_unlocked);
28456c2d4798SAl Viro 
2846eedf265aSEric W. Biederman #ifdef CONFIG_UNIX98_PTYS
2847eedf265aSEric W. Biederman int path_pts(struct path *path)
2848eedf265aSEric W. Biederman {
2849eedf265aSEric W. Biederman 	/* Find something mounted on "pts" in the same directory as
2850eedf265aSEric W. Biederman 	 * the input path.
2851eedf265aSEric W. Biederman 	 */
2852a6a7eb76SAl Viro 	struct dentry *parent = dget_parent(path->dentry);
2853a6a7eb76SAl Viro 	struct dentry *child;
285419f6028aSAl Viro 	struct qstr this = QSTR_INIT("pts", 3);
2855eedf265aSEric W. Biederman 
2856a6a7eb76SAl Viro 	if (unlikely(!path_connected(path->mnt, parent))) {
2857a6a7eb76SAl Viro 		dput(parent);
285863b27720SAl Viro 		return -ENOENT;
2859a6a7eb76SAl Viro 	}
286063b27720SAl Viro 	dput(path->dentry);
286163b27720SAl Viro 	path->dentry = parent;
2862eedf265aSEric W. Biederman 	child = d_hash_and_lookup(parent, &this);
2863eedf265aSEric W. Biederman 	if (!child)
2864eedf265aSEric W. Biederman 		return -ENOENT;
2865eedf265aSEric W. Biederman 
2866eedf265aSEric W. Biederman 	path->dentry = child;
2867eedf265aSEric W. Biederman 	dput(parent);
2868e1f19857SRichard Weinberger 	follow_down(path, 0);
2869eedf265aSEric W. Biederman 	return 0;
2870eedf265aSEric W. Biederman }
2871eedf265aSEric W. Biederman #endif
2872eedf265aSEric W. Biederman 
28731fa1e7f6SAndy Whitcroft int user_path_at_empty(int dfd, const char __user *name, unsigned flags,
28741fa1e7f6SAndy Whitcroft 		 struct path *path, int *empty)
28751da177e4SLinus Torvalds {
2876794ebceaSStephen Brennan 	struct filename *filename = getname_flags(name, flags, empty);
2877794ebceaSStephen Brennan 	int ret = filename_lookup(dfd, filename, flags, path, NULL);
2878794ebceaSStephen Brennan 
2879794ebceaSStephen Brennan 	putname(filename);
2880794ebceaSStephen Brennan 	return ret;
28811da177e4SLinus Torvalds }
2882b853a161SAl Viro EXPORT_SYMBOL(user_path_at_empty);
28831fa1e7f6SAndy Whitcroft 
28849452e93eSChristian Brauner int __check_sticky(struct mnt_idmap *idmap, struct inode *dir,
2885ba73d987SChristian Brauner 		   struct inode *inode)
28861da177e4SLinus Torvalds {
28878e96e3b7SEric W. Biederman 	kuid_t fsuid = current_fsuid();
2888da9592edSDavid Howells 
2889e67fe633SChristian Brauner 	if (vfsuid_eq_kuid(i_uid_into_vfsuid(idmap, inode), fsuid))
28901da177e4SLinus Torvalds 		return 0;
2891e67fe633SChristian Brauner 	if (vfsuid_eq_kuid(i_uid_into_vfsuid(idmap, dir), fsuid))
28921da177e4SLinus Torvalds 		return 0;
28939452e93eSChristian Brauner 	return !capable_wrt_inode_uidgid(idmap, inode, CAP_FOWNER);
28941da177e4SLinus Torvalds }
2895cbdf35bcSMiklos Szeredi EXPORT_SYMBOL(__check_sticky);
28961da177e4SLinus Torvalds 
28971da177e4SLinus Torvalds /*
28981da177e4SLinus Torvalds  *	Check whether we can remove a link victim from directory dir, check
28991da177e4SLinus Torvalds  *  whether the type of victim is right.
29001da177e4SLinus Torvalds  *  1. We can't do it if dir is read-only (done in permission())
29011da177e4SLinus Torvalds  *  2. We should have write and exec permissions on dir
29021da177e4SLinus Torvalds  *  3. We can't remove anything from append-only dir
29031da177e4SLinus Torvalds  *  4. We can't do anything with immutable dir (done in permission())
29041da177e4SLinus Torvalds  *  5. If the sticky bit on dir is set we should either
29051da177e4SLinus Torvalds  *	a. be owner of dir, or
29061da177e4SLinus Torvalds  *	b. be owner of victim, or
29071da177e4SLinus Torvalds  *	c. have CAP_FOWNER capability
29081da177e4SLinus Torvalds  *  6. If the victim is append-only or immutable we can't do antyhing with
29091da177e4SLinus Torvalds  *     links pointing to it.
29100bd23d09SEric W. Biederman  *  7. If the victim has an unknown uid or gid we can't change the inode.
29110bd23d09SEric W. Biederman  *  8. If we were asked to remove a directory and victim isn't one - ENOTDIR.
29120bd23d09SEric W. Biederman  *  9. If we were asked to remove a non-directory and victim isn't one - EISDIR.
29130bd23d09SEric W. Biederman  * 10. We can't remove a root or mountpoint.
29140bd23d09SEric W. Biederman  * 11. We don't allow removal of NFS sillyrenamed files; it's handled by
29151da177e4SLinus Torvalds  *     nfs_async_unlink().
29161da177e4SLinus Torvalds  */
29174609e1f1SChristian Brauner static int may_delete(struct mnt_idmap *idmap, struct inode *dir,
2918ba73d987SChristian Brauner 		      struct dentry *victim, bool isdir)
29191da177e4SLinus Torvalds {
292063afdfc7SDavid Howells 	struct inode *inode = d_backing_inode(victim);
29211da177e4SLinus Torvalds 	int error;
29221da177e4SLinus Torvalds 
2923b18825a7SDavid Howells 	if (d_is_negative(victim))
29241da177e4SLinus Torvalds 		return -ENOENT;
2925b18825a7SDavid Howells 	BUG_ON(!inode);
29261da177e4SLinus Torvalds 
29271da177e4SLinus Torvalds 	BUG_ON(victim->d_parent->d_inode != dir);
2928593d1ce8SEric W. Biederman 
2929593d1ce8SEric W. Biederman 	/* Inode writeback is not safe when the uid or gid are invalid. */
2930e67fe633SChristian Brauner 	if (!vfsuid_valid(i_uid_into_vfsuid(idmap, inode)) ||
2931e67fe633SChristian Brauner 	    !vfsgid_valid(i_gid_into_vfsgid(idmap, inode)))
2932593d1ce8SEric W. Biederman 		return -EOVERFLOW;
2933593d1ce8SEric W. Biederman 
29344fa6b5ecSJeff Layton 	audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
29351da177e4SLinus Torvalds 
29364609e1f1SChristian Brauner 	error = inode_permission(idmap, dir, MAY_WRITE | MAY_EXEC);
29371da177e4SLinus Torvalds 	if (error)
29381da177e4SLinus Torvalds 		return error;
29391da177e4SLinus Torvalds 	if (IS_APPEND(dir))
29401da177e4SLinus Torvalds 		return -EPERM;
2941b18825a7SDavid Howells 
29429452e93eSChristian Brauner 	if (check_sticky(idmap, dir, inode) || IS_APPEND(inode) ||
2943ba73d987SChristian Brauner 	    IS_IMMUTABLE(inode) || IS_SWAPFILE(inode) ||
29444609e1f1SChristian Brauner 	    HAS_UNMAPPED_ID(idmap, inode))
29451da177e4SLinus Torvalds 		return -EPERM;
29461da177e4SLinus Torvalds 	if (isdir) {
294744b1d530SMiklos Szeredi 		if (!d_is_dir(victim))
29481da177e4SLinus Torvalds 			return -ENOTDIR;
29491da177e4SLinus Torvalds 		if (IS_ROOT(victim))
29501da177e4SLinus Torvalds 			return -EBUSY;
295144b1d530SMiklos Szeredi 	} else if (d_is_dir(victim))
29521da177e4SLinus Torvalds 		return -EISDIR;
29531da177e4SLinus Torvalds 	if (IS_DEADDIR(dir))
29541da177e4SLinus Torvalds 		return -ENOENT;
29551da177e4SLinus Torvalds 	if (victim->d_flags & DCACHE_NFSFS_RENAMED)
29561da177e4SLinus Torvalds 		return -EBUSY;
29571da177e4SLinus Torvalds 	return 0;
29581da177e4SLinus Torvalds }
29591da177e4SLinus Torvalds 
29601da177e4SLinus Torvalds /*	Check whether we can create an object with dentry child in directory
29611da177e4SLinus Torvalds  *  dir.
29621da177e4SLinus Torvalds  *  1. We can't do it if child already exists (open has special treatment for
29631da177e4SLinus Torvalds  *     this case, but since we are inlined it's OK)
29641da177e4SLinus Torvalds  *  2. We can't do it if dir is read-only (done in permission())
2965036d5236SEric W. Biederman  *  3. We can't do it if the fs can't represent the fsuid or fsgid.
2966036d5236SEric W. Biederman  *  4. We should have write and exec permissions on dir
2967036d5236SEric W. Biederman  *  5. We can't do it if dir is immutable (done in permission())
29681da177e4SLinus Torvalds  */
29694609e1f1SChristian Brauner static inline int may_create(struct mnt_idmap *idmap,
2970ba73d987SChristian Brauner 			     struct inode *dir, struct dentry *child)
29711da177e4SLinus Torvalds {
297214e972b4SJeff Layton 	audit_inode_child(dir, child, AUDIT_TYPE_CHILD_CREATE);
29731da177e4SLinus Torvalds 	if (child->d_inode)
29741da177e4SLinus Torvalds 		return -EEXIST;
29751da177e4SLinus Torvalds 	if (IS_DEADDIR(dir))
29761da177e4SLinus Torvalds 		return -ENOENT;
29774609e1f1SChristian Brauner 	if (!fsuidgid_has_mapping(dir->i_sb, idmap))
2978036d5236SEric W. Biederman 		return -EOVERFLOW;
29798e538913SChristian Brauner 
29804609e1f1SChristian Brauner 	return inode_permission(idmap, dir, MAY_WRITE | MAY_EXEC);
29811da177e4SLinus Torvalds }
29821da177e4SLinus Torvalds 
2983*9bc37e04SAl Viro static struct dentry *lock_two_directories(struct dentry *p1, struct dentry *p2)
29841da177e4SLinus Torvalds {
29851da177e4SLinus Torvalds 	struct dentry *p;
29861da177e4SLinus Torvalds 
2987e2761a11SOGAWA Hirofumi 	p = d_ancestor(p2, p1);
2988e2761a11SOGAWA Hirofumi 	if (p) {
29895955102cSAl Viro 		inode_lock_nested(p2->d_inode, I_MUTEX_PARENT);
29905955102cSAl Viro 		inode_lock_nested(p1->d_inode, I_MUTEX_CHILD);
29911da177e4SLinus Torvalds 		return p;
29921da177e4SLinus Torvalds 	}
29931da177e4SLinus Torvalds 
2994e2761a11SOGAWA Hirofumi 	p = d_ancestor(p1, p2);
2995e2761a11SOGAWA Hirofumi 	if (p) {
29965955102cSAl Viro 		inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
29975955102cSAl Viro 		inode_lock_nested(p2->d_inode, I_MUTEX_CHILD);
29981da177e4SLinus Torvalds 		return p;
29991da177e4SLinus Torvalds 	}
30001da177e4SLinus Torvalds 
30015955102cSAl Viro 	inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
30025955102cSAl Viro 	inode_lock_nested(p2->d_inode, I_MUTEX_PARENT2);
30031da177e4SLinus Torvalds 	return NULL;
30041da177e4SLinus Torvalds }
3005*9bc37e04SAl Viro 
3006*9bc37e04SAl Viro /*
3007*9bc37e04SAl Viro  * p1 and p2 should be directories on the same fs.
3008*9bc37e04SAl Viro  */
3009*9bc37e04SAl Viro struct dentry *lock_rename(struct dentry *p1, struct dentry *p2)
3010*9bc37e04SAl Viro {
3011*9bc37e04SAl Viro 	if (p1 == p2) {
3012*9bc37e04SAl Viro 		inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
3013*9bc37e04SAl Viro 		return NULL;
3014*9bc37e04SAl Viro 	}
3015*9bc37e04SAl Viro 
3016*9bc37e04SAl Viro 	mutex_lock(&p1->d_sb->s_vfs_rename_mutex);
3017*9bc37e04SAl Viro 	return lock_two_directories(p1, p2);
3018*9bc37e04SAl Viro }
30194d359507SAl Viro EXPORT_SYMBOL(lock_rename);
30201da177e4SLinus Torvalds 
3021*9bc37e04SAl Viro /*
3022*9bc37e04SAl Viro  * c1 and p2 should be on the same fs.
3023*9bc37e04SAl Viro  */
3024*9bc37e04SAl Viro struct dentry *lock_rename_child(struct dentry *c1, struct dentry *p2)
3025*9bc37e04SAl Viro {
3026*9bc37e04SAl Viro 	if (READ_ONCE(c1->d_parent) == p2) {
3027*9bc37e04SAl Viro 		/*
3028*9bc37e04SAl Viro 		 * hopefully won't need to touch ->s_vfs_rename_mutex at all.
3029*9bc37e04SAl Viro 		 */
3030*9bc37e04SAl Viro 		inode_lock_nested(p2->d_inode, I_MUTEX_PARENT);
3031*9bc37e04SAl Viro 		/*
3032*9bc37e04SAl Viro 		 * now that p2 is locked, nobody can move in or out of it,
3033*9bc37e04SAl Viro 		 * so the test below is safe.
3034*9bc37e04SAl Viro 		 */
3035*9bc37e04SAl Viro 		if (likely(c1->d_parent == p2))
3036*9bc37e04SAl Viro 			return NULL;
3037*9bc37e04SAl Viro 
3038*9bc37e04SAl Viro 		/*
3039*9bc37e04SAl Viro 		 * c1 got moved out of p2 while we'd been taking locks;
3040*9bc37e04SAl Viro 		 * unlock and fall back to slow case.
3041*9bc37e04SAl Viro 		 */
3042*9bc37e04SAl Viro 		inode_unlock(p2->d_inode);
3043*9bc37e04SAl Viro 	}
3044*9bc37e04SAl Viro 
3045*9bc37e04SAl Viro 	mutex_lock(&c1->d_sb->s_vfs_rename_mutex);
3046*9bc37e04SAl Viro 	/*
3047*9bc37e04SAl Viro 	 * nobody can move out of any directories on this fs.
3048*9bc37e04SAl Viro 	 */
3049*9bc37e04SAl Viro 	if (likely(c1->d_parent != p2))
3050*9bc37e04SAl Viro 		return lock_two_directories(c1->d_parent, p2);
3051*9bc37e04SAl Viro 
3052*9bc37e04SAl Viro 	/*
3053*9bc37e04SAl Viro 	 * c1 got moved into p2 while we were taking locks;
3054*9bc37e04SAl Viro 	 * we need p2 locked and ->s_vfs_rename_mutex unlocked,
3055*9bc37e04SAl Viro 	 * for consistency with lock_rename().
3056*9bc37e04SAl Viro 	 */
3057*9bc37e04SAl Viro 	inode_lock_nested(p2->d_inode, I_MUTEX_PARENT);
3058*9bc37e04SAl Viro 	mutex_unlock(&c1->d_sb->s_vfs_rename_mutex);
3059*9bc37e04SAl Viro 	return NULL;
3060*9bc37e04SAl Viro }
3061*9bc37e04SAl Viro EXPORT_SYMBOL(lock_rename_child);
3062*9bc37e04SAl Viro 
30631da177e4SLinus Torvalds void unlock_rename(struct dentry *p1, struct dentry *p2)
30641da177e4SLinus Torvalds {
30655955102cSAl Viro 	inode_unlock(p1->d_inode);
30661da177e4SLinus Torvalds 	if (p1 != p2) {
30675955102cSAl Viro 		inode_unlock(p2->d_inode);
3068fc64005cSAl Viro 		mutex_unlock(&p1->d_sb->s_vfs_rename_mutex);
30691da177e4SLinus Torvalds 	}
30701da177e4SLinus Torvalds }
30714d359507SAl Viro EXPORT_SYMBOL(unlock_rename);
30721da177e4SLinus Torvalds 
30736521f891SChristian Brauner /**
30741639a49cSYang Xu  * mode_strip_umask - handle vfs umask stripping
30751639a49cSYang Xu  * @dir:	parent directory of the new inode
30761639a49cSYang Xu  * @mode:	mode of the new inode to be created in @dir
30771639a49cSYang Xu  *
30781639a49cSYang Xu  * Umask stripping depends on whether or not the filesystem supports POSIX
30791639a49cSYang Xu  * ACLs. If the filesystem doesn't support it umask stripping is done directly
30801639a49cSYang Xu  * in here. If the filesystem does support POSIX ACLs umask stripping is
30811639a49cSYang Xu  * deferred until the filesystem calls posix_acl_create().
30821639a49cSYang Xu  *
30831639a49cSYang Xu  * Returns: mode
30841639a49cSYang Xu  */
30851639a49cSYang Xu static inline umode_t mode_strip_umask(const struct inode *dir, umode_t mode)
30861639a49cSYang Xu {
30871639a49cSYang Xu 	if (!IS_POSIXACL(dir))
30881639a49cSYang Xu 		mode &= ~current_umask();
30891639a49cSYang Xu 	return mode;
30901639a49cSYang Xu }
30911639a49cSYang Xu 
30921639a49cSYang Xu /**
30931639a49cSYang Xu  * vfs_prepare_mode - prepare the mode to be used for a new inode
30949452e93eSChristian Brauner  * @idmap:	idmap of the mount the inode was found from
30951639a49cSYang Xu  * @dir:	parent directory of the new inode
30961639a49cSYang Xu  * @mode:	mode of the new inode
30971639a49cSYang Xu  * @mask_perms:	allowed permission by the vfs
30981639a49cSYang Xu  * @type:	type of file to be created
30991639a49cSYang Xu  *
31001639a49cSYang Xu  * This helper consolidates and enforces vfs restrictions on the @mode of a new
31011639a49cSYang Xu  * object to be created.
31021639a49cSYang Xu  *
31031639a49cSYang Xu  * Umask stripping depends on whether the filesystem supports POSIX ACLs (see
31041639a49cSYang Xu  * the kernel documentation for mode_strip_umask()). Moving umask stripping
31051639a49cSYang Xu  * after setgid stripping allows the same ordering for both non-POSIX ACL and
31061639a49cSYang Xu  * POSIX ACL supporting filesystems.
31071639a49cSYang Xu  *
31081639a49cSYang Xu  * Note that it's currently valid for @type to be 0 if a directory is created.
31091639a49cSYang Xu  * Filesystems raise that flag individually and we need to check whether each
31101639a49cSYang Xu  * filesystem can deal with receiving S_IFDIR from the vfs before we enforce a
31111639a49cSYang Xu  * non-zero type.
31121639a49cSYang Xu  *
31131639a49cSYang Xu  * Returns: mode to be passed to the filesystem
31141639a49cSYang Xu  */
31159452e93eSChristian Brauner static inline umode_t vfs_prepare_mode(struct mnt_idmap *idmap,
31161639a49cSYang Xu 				       const struct inode *dir, umode_t mode,
31171639a49cSYang Xu 				       umode_t mask_perms, umode_t type)
31181639a49cSYang Xu {
31199452e93eSChristian Brauner 	mode = mode_strip_sgid(idmap, dir, mode);
31201639a49cSYang Xu 	mode = mode_strip_umask(dir, mode);
31211639a49cSYang Xu 
31221639a49cSYang Xu 	/*
31231639a49cSYang Xu 	 * Apply the vfs mandated allowed permission mask and set the type of
31241639a49cSYang Xu 	 * file to be created before we call into the filesystem.
31251639a49cSYang Xu 	 */
31261639a49cSYang Xu 	mode &= (mask_perms & ~S_IFMT);
31271639a49cSYang Xu 	mode |= (type & S_IFMT);
31281639a49cSYang Xu 
31291639a49cSYang Xu 	return mode;
31301639a49cSYang Xu }
31311639a49cSYang Xu 
31321639a49cSYang Xu /**
31336521f891SChristian Brauner  * vfs_create - create new file
3134abf08576SChristian Brauner  * @idmap:	idmap of the mount the inode was found from
31356521f891SChristian Brauner  * @dir:	inode of @dentry
31366521f891SChristian Brauner  * @dentry:	pointer to dentry of the base directory
31376521f891SChristian Brauner  * @mode:	mode of the new file
31386521f891SChristian Brauner  * @want_excl:	whether the file must not yet exist
31396521f891SChristian Brauner  *
31406521f891SChristian Brauner  * Create a new file.
31416521f891SChristian Brauner  *
3142abf08576SChristian Brauner  * If the inode has been found through an idmapped mount the idmap of
3143abf08576SChristian Brauner  * the vfsmount must be passed through @idmap. This function will then take
3144abf08576SChristian Brauner  * care to map the inode according to @idmap before checking permissions.
31456521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
3146abf08576SChristian Brauner  * raw inode simply passs @nop_mnt_idmap.
31476521f891SChristian Brauner  */
3148abf08576SChristian Brauner int vfs_create(struct mnt_idmap *idmap, struct inode *dir,
31496521f891SChristian Brauner 	       struct dentry *dentry, umode_t mode, bool want_excl)
31501da177e4SLinus Torvalds {
3151abf08576SChristian Brauner 	int error;
3152abf08576SChristian Brauner 
31534609e1f1SChristian Brauner 	error = may_create(idmap, dir, dentry);
31541da177e4SLinus Torvalds 	if (error)
31551da177e4SLinus Torvalds 		return error;
31561da177e4SLinus Torvalds 
3157acfa4380SAl Viro 	if (!dir->i_op->create)
31581da177e4SLinus Torvalds 		return -EACCES;	/* shouldn't it be ENOSYS? */
31591639a49cSYang Xu 
31609452e93eSChristian Brauner 	mode = vfs_prepare_mode(idmap, dir, mode, S_IALLUGO, S_IFREG);
31611da177e4SLinus Torvalds 	error = security_inode_create(dir, dentry, mode);
31621da177e4SLinus Torvalds 	if (error)
31631da177e4SLinus Torvalds 		return error;
31646c960e68SChristian Brauner 	error = dir->i_op->create(idmap, dir, dentry, mode, want_excl);
3165a74574aaSStephen Smalley 	if (!error)
3166f38aa942SAmy Griffis 		fsnotify_create(dir, dentry);
31671da177e4SLinus Torvalds 	return error;
31681da177e4SLinus Torvalds }
31694d359507SAl Viro EXPORT_SYMBOL(vfs_create);
31701da177e4SLinus Torvalds 
31718e6c848eSAl Viro int vfs_mkobj(struct dentry *dentry, umode_t mode,
31728e6c848eSAl Viro 		int (*f)(struct dentry *, umode_t, void *),
31738e6c848eSAl Viro 		void *arg)
31748e6c848eSAl Viro {
31758e6c848eSAl Viro 	struct inode *dir = dentry->d_parent->d_inode;
31764609e1f1SChristian Brauner 	int error = may_create(&nop_mnt_idmap, dir, dentry);
31778e6c848eSAl Viro 	if (error)
31788e6c848eSAl Viro 		return error;
31798e6c848eSAl Viro 
31808e6c848eSAl Viro 	mode &= S_IALLUGO;
31818e6c848eSAl Viro 	mode |= S_IFREG;
31828e6c848eSAl Viro 	error = security_inode_create(dir, dentry, mode);
31838e6c848eSAl Viro 	if (error)
31848e6c848eSAl Viro 		return error;
31858e6c848eSAl Viro 	error = f(dentry, mode, arg);
31868e6c848eSAl Viro 	if (!error)
31878e6c848eSAl Viro 		fsnotify_create(dir, dentry);
31888e6c848eSAl Viro 	return error;
31898e6c848eSAl Viro }
31908e6c848eSAl Viro EXPORT_SYMBOL(vfs_mkobj);
31918e6c848eSAl Viro 
3192a2982cc9SEric W. Biederman bool may_open_dev(const struct path *path)
3193a2982cc9SEric W. Biederman {
3194a2982cc9SEric W. Biederman 	return !(path->mnt->mnt_flags & MNT_NODEV) &&
3195a2982cc9SEric W. Biederman 		!(path->mnt->mnt_sb->s_iflags & SB_I_NODEV);
3196a2982cc9SEric W. Biederman }
3197a2982cc9SEric W. Biederman 
31984609e1f1SChristian Brauner static int may_open(struct mnt_idmap *idmap, const struct path *path,
3199ba73d987SChristian Brauner 		    int acc_mode, int flag)
32001da177e4SLinus Torvalds {
32013fb64190SChristoph Hellwig 	struct dentry *dentry = path->dentry;
32021da177e4SLinus Torvalds 	struct inode *inode = dentry->d_inode;
32031da177e4SLinus Torvalds 	int error;
32041da177e4SLinus Torvalds 
32051da177e4SLinus Torvalds 	if (!inode)
32061da177e4SLinus Torvalds 		return -ENOENT;
32071da177e4SLinus Torvalds 
3208c8fe8f30SChristoph Hellwig 	switch (inode->i_mode & S_IFMT) {
3209c8fe8f30SChristoph Hellwig 	case S_IFLNK:
32101da177e4SLinus Torvalds 		return -ELOOP;
3211c8fe8f30SChristoph Hellwig 	case S_IFDIR:
3212fc4177beSKees Cook 		if (acc_mode & MAY_WRITE)
32131da177e4SLinus Torvalds 			return -EISDIR;
3214fc4177beSKees Cook 		if (acc_mode & MAY_EXEC)
3215fc4177beSKees Cook 			return -EACCES;
3216c8fe8f30SChristoph Hellwig 		break;
3217c8fe8f30SChristoph Hellwig 	case S_IFBLK:
3218c8fe8f30SChristoph Hellwig 	case S_IFCHR:
3219a2982cc9SEric W. Biederman 		if (!may_open_dev(path))
32201da177e4SLinus Torvalds 			return -EACCES;
3221633fb6acSKees Cook 		fallthrough;
3222c8fe8f30SChristoph Hellwig 	case S_IFIFO:
3223c8fe8f30SChristoph Hellwig 	case S_IFSOCK:
3224633fb6acSKees Cook 		if (acc_mode & MAY_EXEC)
3225633fb6acSKees Cook 			return -EACCES;
32261da177e4SLinus Torvalds 		flag &= ~O_TRUNC;
3227c8fe8f30SChristoph Hellwig 		break;
32280fd338b2SKees Cook 	case S_IFREG:
32290fd338b2SKees Cook 		if ((acc_mode & MAY_EXEC) && path_noexec(path))
32300fd338b2SKees Cook 			return -EACCES;
32310fd338b2SKees Cook 		break;
32324a3fd211SDave Hansen 	}
3233b41572e9SDave Hansen 
32344609e1f1SChristian Brauner 	error = inode_permission(idmap, inode, MAY_OPEN | acc_mode);
3235b41572e9SDave Hansen 	if (error)
3236b41572e9SDave Hansen 		return error;
32376146f0d5SMimi Zohar 
32381da177e4SLinus Torvalds 	/*
32391da177e4SLinus Torvalds 	 * An append-only file must be opened in append mode for writing.
32401da177e4SLinus Torvalds 	 */
32411da177e4SLinus Torvalds 	if (IS_APPEND(inode)) {
32428737c930SAl Viro 		if  ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND))
32437715b521SAl Viro 			return -EPERM;
32441da177e4SLinus Torvalds 		if (flag & O_TRUNC)
32457715b521SAl Viro 			return -EPERM;
32461da177e4SLinus Torvalds 	}
32471da177e4SLinus Torvalds 
32481da177e4SLinus Torvalds 	/* O_NOATIME can only be set by the owner or superuser */
324901beba79SChristian Brauner 	if (flag & O_NOATIME && !inode_owner_or_capable(idmap, inode))
32507715b521SAl Viro 		return -EPERM;
32511da177e4SLinus Torvalds 
3252f3c7691eSJ. Bruce Fields 	return 0;
32537715b521SAl Viro }
32547715b521SAl Viro 
3255abf08576SChristian Brauner static int handle_truncate(struct mnt_idmap *idmap, struct file *filp)
32567715b521SAl Viro {
3257f0bb5aafSAl Viro 	const struct path *path = &filp->f_path;
32587715b521SAl Viro 	struct inode *inode = path->dentry->d_inode;
32597715b521SAl Viro 	int error = get_write_access(inode);
32601da177e4SLinus Torvalds 	if (error)
32617715b521SAl Viro 		return error;
3262482e0007SJeff Layton 
32633350607dSGünther Noack 	error = security_file_truncate(filp);
32641da177e4SLinus Torvalds 	if (!error) {
3265abf08576SChristian Brauner 		error = do_truncate(idmap, path->dentry, 0,
3266d139d7ffSMiklos Szeredi 				    ATTR_MTIME|ATTR_CTIME|ATTR_OPEN,
3267e1181ee6SJeff Layton 				    filp);
32681da177e4SLinus Torvalds 	}
32691da177e4SLinus Torvalds 	put_write_access(inode);
3270acd0c935SMimi Zohar 	return error;
32711da177e4SLinus Torvalds }
32721da177e4SLinus Torvalds 
3273d57999e1SDave Hansen static inline int open_to_namei_flags(int flag)
3274d57999e1SDave Hansen {
32758a5e929dSAl Viro 	if ((flag & O_ACCMODE) == 3)
32768a5e929dSAl Viro 		flag--;
3277d57999e1SDave Hansen 	return flag;
3278d57999e1SDave Hansen }
3279d57999e1SDave Hansen 
32804609e1f1SChristian Brauner static int may_o_create(struct mnt_idmap *idmap,
3281ba73d987SChristian Brauner 			const struct path *dir, struct dentry *dentry,
3282ba73d987SChristian Brauner 			umode_t mode)
3283d18e9008SMiklos Szeredi {
3284d18e9008SMiklos Szeredi 	int error = security_path_mknod(dir, dentry, mode, 0);
3285d18e9008SMiklos Szeredi 	if (error)
3286d18e9008SMiklos Szeredi 		return error;
3287d18e9008SMiklos Szeredi 
32884609e1f1SChristian Brauner 	if (!fsuidgid_has_mapping(dir->dentry->d_sb, idmap))
32891328c727SSeth Forshee 		return -EOVERFLOW;
32901328c727SSeth Forshee 
32914609e1f1SChristian Brauner 	error = inode_permission(idmap, dir->dentry->d_inode,
329247291baaSChristian Brauner 				 MAY_WRITE | MAY_EXEC);
3293d18e9008SMiklos Szeredi 	if (error)
3294d18e9008SMiklos Szeredi 		return error;
3295d18e9008SMiklos Szeredi 
3296d18e9008SMiklos Szeredi 	return security_inode_create(dir->dentry->d_inode, dentry, mode);
3297d18e9008SMiklos Szeredi }
3298d18e9008SMiklos Szeredi 
32991acf0af9SDavid Howells /*
33001acf0af9SDavid Howells  * Attempt to atomically look up, create and open a file from a negative
33011acf0af9SDavid Howells  * dentry.
33021acf0af9SDavid Howells  *
33031acf0af9SDavid Howells  * Returns 0 if successful.  The file will have been created and attached to
33041acf0af9SDavid Howells  * @file by the filesystem calling finish_open().
33051acf0af9SDavid Howells  *
330600a07c15SAl Viro  * If the file was looked up only or didn't need creating, FMODE_OPENED won't
330700a07c15SAl Viro  * be set.  The caller will need to perform the open themselves.  @path will
330800a07c15SAl Viro  * have been updated to point to the new dentry.  This may be negative.
33091acf0af9SDavid Howells  *
33101acf0af9SDavid Howells  * Returns an error code otherwise.
33111acf0af9SDavid Howells  */
3312239eb983SAl Viro static struct dentry *atomic_open(struct nameidata *nd, struct dentry *dentry,
3313239eb983SAl Viro 				  struct file *file,
33143ec2eef1SAl Viro 				  int open_flag, umode_t mode)
3315d18e9008SMiklos Szeredi {
3316d18e9008SMiklos Szeredi 	struct dentry *const DENTRY_NOT_SET = (void *) -1UL;
3317d18e9008SMiklos Szeredi 	struct inode *dir =  nd->path.dentry->d_inode;
3318d18e9008SMiklos Szeredi 	int error;
3319d18e9008SMiklos Szeredi 
3320d18e9008SMiklos Szeredi 	if (nd->flags & LOOKUP_DIRECTORY)
3321d18e9008SMiklos Szeredi 		open_flag |= O_DIRECTORY;
3322d18e9008SMiklos Szeredi 
332330d90494SAl Viro 	file->f_path.dentry = DENTRY_NOT_SET;
332430d90494SAl Viro 	file->f_path.mnt = nd->path.mnt;
33250fb1ea09SAl Viro 	error = dir->i_op->atomic_open(dir, dentry, file,
332644907d79SAl Viro 				       open_to_namei_flags(open_flag), mode);
33276fbd0714SAl Viro 	d_lookup_done(dentry);
3328384f26e2SAl Viro 	if (!error) {
332964e1ac4dSAl Viro 		if (file->f_mode & FMODE_OPENED) {
33306fb968cdSAl Viro 			if (unlikely(dentry != file->f_path.dentry)) {
33316fb968cdSAl Viro 				dput(dentry);
33326fb968cdSAl Viro 				dentry = dget(file->f_path.dentry);
33336fb968cdSAl Viro 			}
333464e1ac4dSAl Viro 		} else if (WARN_ON(file->f_path.dentry == DENTRY_NOT_SET)) {
33352675a4ebSAl Viro 			error = -EIO;
3336384f26e2SAl Viro 		} else {
333730d90494SAl Viro 			if (file->f_path.dentry) {
3338d18e9008SMiklos Szeredi 				dput(dentry);
3339d18e9008SMiklos Szeredi 				dentry = file->f_path.dentry;
334010c64ceaSAl Viro 			}
3341239eb983SAl Viro 			if (unlikely(d_is_negative(dentry)))
3342a01e718fSAl Viro 				error = -ENOENT;
3343d18e9008SMiklos Szeredi 		}
3344d18e9008SMiklos Szeredi 	}
3345239eb983SAl Viro 	if (error) {
3346d18e9008SMiklos Szeredi 		dput(dentry);
3347239eb983SAl Viro 		dentry = ERR_PTR(error);
3348239eb983SAl Viro 	}
3349239eb983SAl Viro 	return dentry;
3350d18e9008SMiklos Szeredi }
3351d18e9008SMiklos Szeredi 
335231e6b01fSNick Piggin /*
33531acf0af9SDavid Howells  * Look up and maybe create and open the last component.
3354d58ffd35SMiklos Szeredi  *
335500a07c15SAl Viro  * Must be called with parent locked (exclusive in O_CREAT case).
3356d58ffd35SMiklos Szeredi  *
335700a07c15SAl Viro  * Returns 0 on success, that is, if
335800a07c15SAl Viro  *  the file was successfully atomically created (if necessary) and opened, or
335900a07c15SAl Viro  *  the file was not completely opened at this time, though lookups and
336000a07c15SAl Viro  *  creations were performed.
336100a07c15SAl Viro  * These case are distinguished by presence of FMODE_OPENED on file->f_mode.
336200a07c15SAl Viro  * In the latter case dentry returned in @path might be negative if O_CREAT
336300a07c15SAl Viro  * hadn't been specified.
33641acf0af9SDavid Howells  *
336500a07c15SAl Viro  * An error code is returned on failure.
3366d58ffd35SMiklos Szeredi  */
3367da5ebf5aSAl Viro static struct dentry *lookup_open(struct nameidata *nd, struct file *file,
3368d58ffd35SMiklos Szeredi 				  const struct open_flags *op,
33693ec2eef1SAl Viro 				  bool got_write)
3370d58ffd35SMiklos Szeredi {
33716c960e68SChristian Brauner 	struct mnt_idmap *idmap;
3372d58ffd35SMiklos Szeredi 	struct dentry *dir = nd->path.dentry;
337354ef4872SMiklos Szeredi 	struct inode *dir_inode = dir->d_inode;
33741643b43fSAl Viro 	int open_flag = op->open_flag;
3375d58ffd35SMiklos Szeredi 	struct dentry *dentry;
33761643b43fSAl Viro 	int error, create_error = 0;
33771643b43fSAl Viro 	umode_t mode = op->mode;
33786fbd0714SAl Viro 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
3379d58ffd35SMiklos Szeredi 
3380ce8644fcSAl Viro 	if (unlikely(IS_DEADDIR(dir_inode)))
3381da5ebf5aSAl Viro 		return ERR_PTR(-ENOENT);
3382d58ffd35SMiklos Szeredi 
338373a09dd9SAl Viro 	file->f_mode &= ~FMODE_CREATED;
33846fbd0714SAl Viro 	dentry = d_lookup(dir, &nd->last);
33856fbd0714SAl Viro 	for (;;) {
33866fbd0714SAl Viro 		if (!dentry) {
33876fbd0714SAl Viro 			dentry = d_alloc_parallel(dir, &nd->last, &wq);
3388d58ffd35SMiklos Szeredi 			if (IS_ERR(dentry))
3389da5ebf5aSAl Viro 				return dentry;
33906fbd0714SAl Viro 		}
33916fbd0714SAl Viro 		if (d_in_lookup(dentry))
33926fbd0714SAl Viro 			break;
3393d58ffd35SMiklos Szeredi 
33946fbd0714SAl Viro 		error = d_revalidate(dentry, nd->flags);
33956fbd0714SAl Viro 		if (likely(error > 0))
33966fbd0714SAl Viro 			break;
33976fbd0714SAl Viro 		if (error)
33986fbd0714SAl Viro 			goto out_dput;
33996fbd0714SAl Viro 		d_invalidate(dentry);
34006fbd0714SAl Viro 		dput(dentry);
34016fbd0714SAl Viro 		dentry = NULL;
34026fbd0714SAl Viro 	}
34036fbd0714SAl Viro 	if (dentry->d_inode) {
3404d18e9008SMiklos Szeredi 		/* Cached positive dentry: will open in f_op->open */
3405da5ebf5aSAl Viro 		return dentry;
34066c51e513SAl Viro 	}
3407d18e9008SMiklos Szeredi 
34081643b43fSAl Viro 	/*
34091643b43fSAl Viro 	 * Checking write permission is tricky, bacuse we don't know if we are
34101643b43fSAl Viro 	 * going to actually need it: O_CREAT opens should work as long as the
34111643b43fSAl Viro 	 * file exists.  But checking existence breaks atomicity.  The trick is
34121643b43fSAl Viro 	 * to check access and if not granted clear O_CREAT from the flags.
34131643b43fSAl Viro 	 *
34141643b43fSAl Viro 	 * Another problem is returing the "right" error value (e.g. for an
34151643b43fSAl Viro 	 * O_EXCL open we want to return EEXIST not EROFS).
34161643b43fSAl Viro 	 */
341799a4a90cSAl Viro 	if (unlikely(!got_write))
341899a4a90cSAl Viro 		open_flag &= ~O_TRUNC;
34196c960e68SChristian Brauner 	idmap = mnt_idmap(nd->path.mnt);
34201643b43fSAl Viro 	if (open_flag & O_CREAT) {
342199a4a90cSAl Viro 		if (open_flag & O_EXCL)
342299a4a90cSAl Viro 			open_flag &= ~O_TRUNC;
34239452e93eSChristian Brauner 		mode = vfs_prepare_mode(idmap, dir->d_inode, mode, mode, mode);
342499a4a90cSAl Viro 		if (likely(got_write))
34254609e1f1SChristian Brauner 			create_error = may_o_create(idmap, &nd->path,
3426ba73d987SChristian Brauner 						    dentry, mode);
342799a4a90cSAl Viro 		else
342899a4a90cSAl Viro 			create_error = -EROFS;
342999a4a90cSAl Viro 	}
343099a4a90cSAl Viro 	if (create_error)
34311643b43fSAl Viro 		open_flag &= ~O_CREAT;
34321643b43fSAl Viro 	if (dir_inode->i_op->atomic_open) {
3433d489cf9aSAl Viro 		dentry = atomic_open(nd, dentry, file, open_flag, mode);
3434da5ebf5aSAl Viro 		if (unlikely(create_error) && dentry == ERR_PTR(-ENOENT))
3435da5ebf5aSAl Viro 			dentry = ERR_PTR(create_error);
3436da5ebf5aSAl Viro 		return dentry;
3437239eb983SAl Viro 	}
343854ef4872SMiklos Szeredi 
34396fbd0714SAl Viro 	if (d_in_lookup(dentry)) {
344012fa5e24SAl Viro 		struct dentry *res = dir_inode->i_op->lookup(dir_inode, dentry,
344112fa5e24SAl Viro 							     nd->flags);
34426fbd0714SAl Viro 		d_lookup_done(dentry);
344312fa5e24SAl Viro 		if (unlikely(res)) {
344412fa5e24SAl Viro 			if (IS_ERR(res)) {
344512fa5e24SAl Viro 				error = PTR_ERR(res);
344612fa5e24SAl Viro 				goto out_dput;
344712fa5e24SAl Viro 			}
344812fa5e24SAl Viro 			dput(dentry);
344912fa5e24SAl Viro 			dentry = res;
345012fa5e24SAl Viro 		}
345154ef4872SMiklos Szeredi 	}
345254ef4872SMiklos Szeredi 
3453d58ffd35SMiklos Szeredi 	/* Negative dentry, just create the file */
34541643b43fSAl Viro 	if (!dentry->d_inode && (open_flag & O_CREAT)) {
345573a09dd9SAl Viro 		file->f_mode |= FMODE_CREATED;
3456ce8644fcSAl Viro 		audit_inode_child(dir_inode, dentry, AUDIT_TYPE_CHILD_CREATE);
3457ce8644fcSAl Viro 		if (!dir_inode->i_op->create) {
3458ce8644fcSAl Viro 			error = -EACCES;
3459d58ffd35SMiklos Szeredi 			goto out_dput;
346064894cf8SAl Viro 		}
3461549c7297SChristian Brauner 
34626c960e68SChristian Brauner 		error = dir_inode->i_op->create(idmap, dir_inode, dentry,
3463549c7297SChristian Brauner 						mode, open_flag & O_EXCL);
3464d58ffd35SMiklos Szeredi 		if (error)
3465d58ffd35SMiklos Szeredi 			goto out_dput;
3466d58ffd35SMiklos Szeredi 	}
34671643b43fSAl Viro 	if (unlikely(create_error) && !dentry->d_inode) {
34681643b43fSAl Viro 		error = create_error;
3469d58ffd35SMiklos Szeredi 		goto out_dput;
3470d58ffd35SMiklos Szeredi 	}
3471da5ebf5aSAl Viro 	return dentry;
3472d58ffd35SMiklos Szeredi 
3473d58ffd35SMiklos Szeredi out_dput:
3474d58ffd35SMiklos Szeredi 	dput(dentry);
3475da5ebf5aSAl Viro 	return ERR_PTR(error);
3476d58ffd35SMiklos Szeredi }
3477d58ffd35SMiklos Szeredi 
3478c981a482SAl Viro static const char *open_last_lookups(struct nameidata *nd,
34793ec2eef1SAl Viro 		   struct file *file, const struct open_flags *op)
3480fb1cc555SAl Viro {
3481a1e28038SAl Viro 	struct dentry *dir = nd->path.dentry;
3482ca344a89SAl Viro 	int open_flag = op->open_flag;
348364894cf8SAl Viro 	bool got_write = false;
3484da5ebf5aSAl Viro 	struct dentry *dentry;
3485b0417d2cSAl Viro 	const char *res;
3486fb1cc555SAl Viro 
3487c3e380b0SAl Viro 	nd->flags |= op->intent;
3488c3e380b0SAl Viro 
3489bc77daa7SAl Viro 	if (nd->last_type != LAST_NORM) {
349056676ec3SAl Viro 		if (nd->depth)
349156676ec3SAl Viro 			put_link(nd);
3492ff326a32SAl Viro 		return handle_dots(nd, nd->last_type);
34931f36f774SAl Viro 	}
3494a2c36b45SAl Viro 
3495ca344a89SAl Viro 	if (!(open_flag & O_CREAT)) {
3496fe2d35ffSAl Viro 		if (nd->last.name[nd->last.len])
3497fe2d35ffSAl Viro 			nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
3498fe2d35ffSAl Viro 		/* we _can_ be in RCU mode here */
34994cb64024SAl Viro 		dentry = lookup_fast(nd);
350020e34357SAl Viro 		if (IS_ERR(dentry))
35011ccac622SAl Viro 			return ERR_CAST(dentry);
350220e34357SAl Viro 		if (likely(dentry))
350371574865SMiklos Szeredi 			goto finish_lookup;
350471574865SMiklos Szeredi 
35056583fe22SAl Viro 		BUG_ON(nd->flags & LOOKUP_RCU);
3506b6183df7SMiklos Szeredi 	} else {
3507fe2d35ffSAl Viro 		/* create side of things */
350872287417SAl Viro 		if (nd->flags & LOOKUP_RCU) {
3509e36cffedSJens Axboe 			if (!try_to_unlazy(nd))
3510e36cffedSJens Axboe 				return ERR_PTR(-ECHILD);
351172287417SAl Viro 		}
3512c9b07eabSAl Viro 		audit_inode(nd->name, dir, AUDIT_INODE_PARENT);
35131f36f774SAl Viro 		/* trailing slashes? */
3514deb106c6SAl Viro 		if (unlikely(nd->last.name[nd->last.len]))
35151ccac622SAl Viro 			return ERR_PTR(-EISDIR);
3516b6183df7SMiklos Szeredi 	}
35171f36f774SAl Viro 
35189cf843e3SAl Viro 	if (open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) {
3519e36cffedSJens Axboe 		got_write = !mnt_want_write(nd->path.mnt);
352064894cf8SAl Viro 		/*
352164894cf8SAl Viro 		 * do _not_ fail yet - we might not need that or fail with
352264894cf8SAl Viro 		 * a different error; let lookup_open() decide; we'll be
352364894cf8SAl Viro 		 * dropping this one anyway.
352464894cf8SAl Viro 		 */
352564894cf8SAl Viro 	}
35269cf843e3SAl Viro 	if (open_flag & O_CREAT)
35275955102cSAl Viro 		inode_lock(dir->d_inode);
35289cf843e3SAl Viro 	else
35299cf843e3SAl Viro 		inode_lock_shared(dir->d_inode);
3530da5ebf5aSAl Viro 	dentry = lookup_open(nd, file, op, got_write);
3531f7bb959dSAl Viro 	if (!IS_ERR(dentry) && (file->f_mode & FMODE_CREATED))
3532f7bb959dSAl Viro 		fsnotify_create(dir->d_inode, dentry);
35339cf843e3SAl Viro 	if (open_flag & O_CREAT)
35345955102cSAl Viro 		inode_unlock(dir->d_inode);
35359cf843e3SAl Viro 	else
35369cf843e3SAl Viro 		inode_unlock_shared(dir->d_inode);
3537fb1cc555SAl Viro 
3538c981a482SAl Viro 	if (got_write)
353959e96e65SAl Viro 		mnt_drop_write(nd->path.mnt);
35406c0d46c4SAl Viro 
354159e96e65SAl Viro 	if (IS_ERR(dentry))
354259e96e65SAl Viro 		return ERR_CAST(dentry);
354359e96e65SAl Viro 
3544973d4b73SAl Viro 	if (file->f_mode & (FMODE_OPENED | FMODE_CREATED)) {
3545e73cabffSAl Viro 		dput(nd->path.dentry);
3546e73cabffSAl Viro 		nd->path.dentry = dentry;
3547c981a482SAl Viro 		return NULL;
3548fb1cc555SAl Viro 	}
3549fb1cc555SAl Viro 
355020e34357SAl Viro finish_lookup:
355156676ec3SAl Viro 	if (nd->depth)
355256676ec3SAl Viro 		put_link(nd);
3553a4f5b521SAl Viro 	res = step_into(nd, WALK_TRAILING, dentry);
3554ff326a32SAl Viro 	if (unlikely(res))
35551ccac622SAl Viro 		nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL);
3556b0417d2cSAl Viro 	return res;
35571ccac622SAl Viro }
355831d1726dSAl Viro 
3559c981a482SAl Viro /*
3560c981a482SAl Viro  * Handle the last step of open()
3561c981a482SAl Viro  */
3562c5971b8cSAl Viro static int do_open(struct nameidata *nd,
3563c981a482SAl Viro 		   struct file *file, const struct open_flags *op)
3564c981a482SAl Viro {
3565abf08576SChristian Brauner 	struct mnt_idmap *idmap;
3566c981a482SAl Viro 	int open_flag = op->open_flag;
3567c981a482SAl Viro 	bool do_truncate;
3568c981a482SAl Viro 	int acc_mode;
3569c981a482SAl Viro 	int error;
3570c981a482SAl Viro 
3571ff326a32SAl Viro 	if (!(file->f_mode & (FMODE_OPENED | FMODE_CREATED))) {
3572ff326a32SAl Viro 		error = complete_walk(nd);
3573ff326a32SAl Viro 		if (error)
3574ff326a32SAl Viro 			return error;
3575ff326a32SAl Viro 	}
3576973d4b73SAl Viro 	if (!(file->f_mode & FMODE_CREATED))
357776ae2a5aSAl Viro 		audit_inode(nd->name, nd->path.dentry, 0);
3578abf08576SChristian Brauner 	idmap = mnt_idmap(nd->path.mnt);
357930aba665SSalvatore Mesoraca 	if (open_flag & O_CREAT) {
3580b94e0b32SAl Viro 		if ((open_flag & O_EXCL) && !(file->f_mode & FMODE_CREATED))
3581b94e0b32SAl Viro 			return -EEXIST;
358230aba665SSalvatore Mesoraca 		if (d_is_dir(nd->path.dentry))
3583c5971b8cSAl Viro 			return -EISDIR;
3584e67fe633SChristian Brauner 		error = may_create_in_sticky(idmap, nd,
358530aba665SSalvatore Mesoraca 					     d_backing_inode(nd->path.dentry));
358630aba665SSalvatore Mesoraca 		if (unlikely(error))
3587c5971b8cSAl Viro 			return error;
358830aba665SSalvatore Mesoraca 	}
358944b1d530SMiklos Szeredi 	if ((nd->flags & LOOKUP_DIRECTORY) && !d_can_lookup(nd->path.dentry))
3590c5971b8cSAl Viro 		return -ENOTDIR;
35916c0d46c4SAl Viro 
35928795e7d4SAl Viro 	do_truncate = false;
35938795e7d4SAl Viro 	acc_mode = op->acc_mode;
35945a2d3eddSAl Viro 	if (file->f_mode & FMODE_CREATED) {
35955a2d3eddSAl Viro 		/* Don't check for write permission, don't truncate */
35965a2d3eddSAl Viro 		open_flag &= ~O_TRUNC;
35975a2d3eddSAl Viro 		acc_mode = 0;
35988795e7d4SAl Viro 	} else if (d_is_reg(nd->path.dentry) && open_flag & O_TRUNC) {
35990f9d1a10SAl Viro 		error = mnt_want_write(nd->path.mnt);
36000f9d1a10SAl Viro 		if (error)
3601c5971b8cSAl Viro 			return error;
36028795e7d4SAl Viro 		do_truncate = true;
36030f9d1a10SAl Viro 	}
36044609e1f1SChristian Brauner 	error = may_open(idmap, &nd->path, acc_mode, open_flag);
36058795e7d4SAl Viro 	if (!error && !(file->f_mode & FMODE_OPENED))
3606ae2bb293SAl Viro 		error = vfs_open(&nd->path, file);
36078795e7d4SAl Viro 	if (!error)
36086035a27bSAl Viro 		error = ima_file_check(file, op->acc_mode);
36098795e7d4SAl Viro 	if (!error && do_truncate)
3610abf08576SChristian Brauner 		error = handle_truncate(idmap, file);
3611c80567c8SAl Viro 	if (unlikely(error > 0)) {
3612c80567c8SAl Viro 		WARN_ON(1);
3613c80567c8SAl Viro 		error = -EINVAL;
3614c80567c8SAl Viro 	}
36158795e7d4SAl Viro 	if (do_truncate)
36160f9d1a10SAl Viro 		mnt_drop_write(nd->path.mnt);
3617c5971b8cSAl Viro 	return error;
3618fb1cc555SAl Viro }
3619fb1cc555SAl Viro 
36206521f891SChristian Brauner /**
36216521f891SChristian Brauner  * vfs_tmpfile - create tmpfile
3622abf08576SChristian Brauner  * @idmap:	idmap of the mount the inode was found from
36236521f891SChristian Brauner  * @dentry:	pointer to dentry of the base directory
36246521f891SChristian Brauner  * @mode:	mode of the new tmpfile
36252111c3c0SRandy Dunlap  * @open_flag:	flags
36266521f891SChristian Brauner  *
36276521f891SChristian Brauner  * Create a temporary file.
36286521f891SChristian Brauner  *
3629abf08576SChristian Brauner  * If the inode has been found through an idmapped mount the idmap of
3630abf08576SChristian Brauner  * the vfsmount must be passed through @idmap. This function will then take
3631abf08576SChristian Brauner  * care to map the inode according to @idmap before checking permissions.
36326521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
3633abf08576SChristian Brauner  * raw inode simply passs @nop_mnt_idmap.
36346521f891SChristian Brauner  */
3635abf08576SChristian Brauner static int vfs_tmpfile(struct mnt_idmap *idmap,
36369751b338SMiklos Szeredi 		       const struct path *parentpath,
36379751b338SMiklos Szeredi 		       struct file *file, umode_t mode)
3638af7bd4dcSAmir Goldstein {
36399751b338SMiklos Szeredi 	struct dentry *child;
36409751b338SMiklos Szeredi 	struct inode *dir = d_inode(parentpath->dentry);
3641af7bd4dcSAmir Goldstein 	struct inode *inode;
3642af7bd4dcSAmir Goldstein 	int error;
3643406c706cSPeter Griffin 	int open_flag = file->f_flags;
3644af7bd4dcSAmir Goldstein 
3645af7bd4dcSAmir Goldstein 	/* we want directory to be writable */
36464609e1f1SChristian Brauner 	error = inode_permission(idmap, dir, MAY_WRITE | MAY_EXEC);
3647af7bd4dcSAmir Goldstein 	if (error)
36489751b338SMiklos Szeredi 		return error;
3649af7bd4dcSAmir Goldstein 	if (!dir->i_op->tmpfile)
36509751b338SMiklos Szeredi 		return -EOPNOTSUPP;
36519751b338SMiklos Szeredi 	child = d_alloc(parentpath->dentry, &slash_name);
3652af7bd4dcSAmir Goldstein 	if (unlikely(!child))
36539751b338SMiklos Szeredi 		return -ENOMEM;
36549751b338SMiklos Szeredi 	file->f_path.mnt = parentpath->mnt;
36559751b338SMiklos Szeredi 	file->f_path.dentry = child;
36569452e93eSChristian Brauner 	mode = vfs_prepare_mode(idmap, dir, mode, mode, mode);
3657011e2b71SChristian Brauner 	error = dir->i_op->tmpfile(idmap, dir, file, mode);
36589751b338SMiklos Szeredi 	dput(child);
3659af7bd4dcSAmir Goldstein 	if (error)
36609751b338SMiklos Szeredi 		return error;
36619751b338SMiklos Szeredi 	/* Don't check for other permissions, the inode was just created */
36624609e1f1SChristian Brauner 	error = may_open(idmap, &file->f_path, 0, file->f_flags);
36639751b338SMiklos Szeredi 	if (error)
36649751b338SMiklos Szeredi 		return error;
36659751b338SMiklos Szeredi 	inode = file_inode(file);
3666406c706cSPeter Griffin 	if (!(open_flag & O_EXCL)) {
3667af7bd4dcSAmir Goldstein 		spin_lock(&inode->i_lock);
3668af7bd4dcSAmir Goldstein 		inode->i_state |= I_LINKABLE;
3669af7bd4dcSAmir Goldstein 		spin_unlock(&inode->i_lock);
3670af7bd4dcSAmir Goldstein 	}
367139f60c1cSChristian Brauner 	ima_post_create_tmpfile(idmap, inode);
36729751b338SMiklos Szeredi 	return 0;
3673af7bd4dcSAmir Goldstein }
3674af7bd4dcSAmir Goldstein 
367522873deaSMiklos Szeredi /**
367622873deaSMiklos Szeredi  * vfs_tmpfile_open - open a tmpfile for kernel internal use
3677abf08576SChristian Brauner  * @idmap:	idmap of the mount the inode was found from
367822873deaSMiklos Szeredi  * @parentpath:	path of the base directory
367922873deaSMiklos Szeredi  * @mode:	mode of the new tmpfile
368022873deaSMiklos Szeredi  * @open_flag:	flags
368122873deaSMiklos Szeredi  * @cred:	credentials for open
368222873deaSMiklos Szeredi  *
368322873deaSMiklos Szeredi  * Create and open a temporary file.  The file is not accounted in nr_files,
368422873deaSMiklos Szeredi  * hence this is only for kernel internal use, and must not be installed into
368522873deaSMiklos Szeredi  * file tables or such.
368622873deaSMiklos Szeredi  */
3687abf08576SChristian Brauner struct file *vfs_tmpfile_open(struct mnt_idmap *idmap,
368822873deaSMiklos Szeredi 			  const struct path *parentpath,
368922873deaSMiklos Szeredi 			  umode_t mode, int open_flag, const struct cred *cred)
369022873deaSMiklos Szeredi {
369122873deaSMiklos Szeredi 	struct file *file;
369222873deaSMiklos Szeredi 	int error;
369322873deaSMiklos Szeredi 
36949751b338SMiklos Szeredi 	file = alloc_empty_file_noaccount(open_flag, cred);
36959751b338SMiklos Szeredi 	if (!IS_ERR(file)) {
3696abf08576SChristian Brauner 		error = vfs_tmpfile(idmap, parentpath, file, mode);
36979751b338SMiklos Szeredi 		if (error) {
36989751b338SMiklos Szeredi 			fput(file);
369922873deaSMiklos Szeredi 			file = ERR_PTR(error);
37009751b338SMiklos Szeredi 		}
37019751b338SMiklos Szeredi 	}
370222873deaSMiklos Szeredi 	return file;
370322873deaSMiklos Szeredi }
370422873deaSMiklos Szeredi EXPORT_SYMBOL(vfs_tmpfile_open);
3705648fa861SAl Viro 
3706c8a53ee5SAl Viro static int do_tmpfile(struct nameidata *nd, unsigned flags,
370760545d0dSAl Viro 		const struct open_flags *op,
37083ec2eef1SAl Viro 		struct file *file)
370960545d0dSAl Viro {
3710625b6d10SAl Viro 	struct path path;
3711c8a53ee5SAl Viro 	int error = path_lookupat(nd, flags | LOOKUP_DIRECTORY, &path);
37129751b338SMiklos Szeredi 
371360545d0dSAl Viro 	if (unlikely(error))
371460545d0dSAl Viro 		return error;
3715625b6d10SAl Viro 	error = mnt_want_write(path.mnt);
371660545d0dSAl Viro 	if (unlikely(error))
371760545d0dSAl Viro 		goto out;
3718abf08576SChristian Brauner 	error = vfs_tmpfile(mnt_idmap(path.mnt), &path, file, op->mode);
37199751b338SMiklos Szeredi 	if (error)
372060545d0dSAl Viro 		goto out2;
37219751b338SMiklos Szeredi 	audit_inode(nd->name, file->f_path.dentry, 0);
372260545d0dSAl Viro out2:
3723625b6d10SAl Viro 	mnt_drop_write(path.mnt);
372460545d0dSAl Viro out:
3725625b6d10SAl Viro 	path_put(&path);
372660545d0dSAl Viro 	return error;
372760545d0dSAl Viro }
372860545d0dSAl Viro 
37296ac08709SAl Viro static int do_o_path(struct nameidata *nd, unsigned flags, struct file *file)
37306ac08709SAl Viro {
37316ac08709SAl Viro 	struct path path;
37326ac08709SAl Viro 	int error = path_lookupat(nd, flags, &path);
37336ac08709SAl Viro 	if (!error) {
37346ac08709SAl Viro 		audit_inode(nd->name, path.dentry, 0);
3735ae2bb293SAl Viro 		error = vfs_open(&path, file);
37366ac08709SAl Viro 		path_put(&path);
37376ac08709SAl Viro 	}
37386ac08709SAl Viro 	return error;
37396ac08709SAl Viro }
37406ac08709SAl Viro 
3741c8a53ee5SAl Viro static struct file *path_openat(struct nameidata *nd,
3742c8a53ee5SAl Viro 			const struct open_flags *op, unsigned flags)
37431da177e4SLinus Torvalds {
374430d90494SAl Viro 	struct file *file;
374513aab428SAl Viro 	int error;
374631e6b01fSNick Piggin 
3747ea73ea72SAl Viro 	file = alloc_empty_file(op->open_flag, current_cred());
37481afc99beSAl Viro 	if (IS_ERR(file))
37491afc99beSAl Viro 		return file;
375031e6b01fSNick Piggin 
3751bb458c64SAl Viro 	if (unlikely(file->f_flags & __O_TMPFILE)) {
37523ec2eef1SAl Viro 		error = do_tmpfile(nd, flags, op, file);
37535f336e72SAl Viro 	} else if (unlikely(file->f_flags & O_PATH)) {
37546ac08709SAl Viro 		error = do_o_path(nd, flags, file);
37555f336e72SAl Viro 	} else {
37565f336e72SAl Viro 		const char *s = path_init(nd, flags);
37573bdba28bSAl Viro 		while (!(error = link_path_walk(s, nd)) &&
3758c5971b8cSAl Viro 		       (s = open_last_lookups(nd, file, op)) != NULL)
37591ccac622SAl Viro 			;
3760c5971b8cSAl Viro 		if (!error)
3761c5971b8cSAl Viro 			error = do_open(nd, file, op);
3762deb106c6SAl Viro 		terminate_walk(nd);
37635f336e72SAl Viro 	}
37647c1c01ecSAl Viro 	if (likely(!error)) {
3765aad888f8SAl Viro 		if (likely(file->f_mode & FMODE_OPENED))
37667c1c01ecSAl Viro 			return file;
37677c1c01ecSAl Viro 		WARN_ON(1);
37687c1c01ecSAl Viro 		error = -EINVAL;
3769015c3bbcSMiklos Szeredi 	}
37707c1c01ecSAl Viro 	fput(file);
37712675a4ebSAl Viro 	if (error == -EOPENSTALE) {
37722675a4ebSAl Viro 		if (flags & LOOKUP_RCU)
37732675a4ebSAl Viro 			error = -ECHILD;
37742675a4ebSAl Viro 		else
37752675a4ebSAl Viro 			error = -ESTALE;
37762675a4ebSAl Viro 	}
37777c1c01ecSAl Viro 	return ERR_PTR(error);
3778de459215SKirill Korotaev }
37791da177e4SLinus Torvalds 
3780669abf4eSJeff Layton struct file *do_filp_open(int dfd, struct filename *pathname,
3781f9652e10SAl Viro 		const struct open_flags *op)
378213aab428SAl Viro {
37839883d185SAl Viro 	struct nameidata nd;
3784f9652e10SAl Viro 	int flags = op->lookup_flags;
378513aab428SAl Viro 	struct file *filp;
378613aab428SAl Viro 
378706422964SAl Viro 	set_nameidata(&nd, dfd, pathname, NULL);
3788c8a53ee5SAl Viro 	filp = path_openat(&nd, op, flags | LOOKUP_RCU);
378913aab428SAl Viro 	if (unlikely(filp == ERR_PTR(-ECHILD)))
3790c8a53ee5SAl Viro 		filp = path_openat(&nd, op, flags);
379113aab428SAl Viro 	if (unlikely(filp == ERR_PTR(-ESTALE)))
3792c8a53ee5SAl Viro 		filp = path_openat(&nd, op, flags | LOOKUP_REVAL);
37939883d185SAl Viro 	restore_nameidata();
379413aab428SAl Viro 	return filp;
379513aab428SAl Viro }
379613aab428SAl Viro 
3797ffb37ca3SAl Viro struct file *do_file_open_root(const struct path *root,
3798f9652e10SAl Viro 		const char *name, const struct open_flags *op)
379973d049a4SAl Viro {
38009883d185SAl Viro 	struct nameidata nd;
380173d049a4SAl Viro 	struct file *file;
380251689104SPaul Moore 	struct filename *filename;
3803bcba1e7dSAl Viro 	int flags = op->lookup_flags;
380473d049a4SAl Viro 
3805ffb37ca3SAl Viro 	if (d_is_symlink(root->dentry) && op->intent & LOOKUP_OPEN)
380673d049a4SAl Viro 		return ERR_PTR(-ELOOP);
380773d049a4SAl Viro 
380851689104SPaul Moore 	filename = getname_kernel(name);
3809a1c83681SViresh Kumar 	if (IS_ERR(filename))
381051689104SPaul Moore 		return ERR_CAST(filename);
381151689104SPaul Moore 
381206422964SAl Viro 	set_nameidata(&nd, -1, filename, root);
3813c8a53ee5SAl Viro 	file = path_openat(&nd, op, flags | LOOKUP_RCU);
381473d049a4SAl Viro 	if (unlikely(file == ERR_PTR(-ECHILD)))
3815c8a53ee5SAl Viro 		file = path_openat(&nd, op, flags);
381673d049a4SAl Viro 	if (unlikely(file == ERR_PTR(-ESTALE)))
3817c8a53ee5SAl Viro 		file = path_openat(&nd, op, flags | LOOKUP_REVAL);
38189883d185SAl Viro 	restore_nameidata();
381951689104SPaul Moore 	putname(filename);
382073d049a4SAl Viro 	return file;
382173d049a4SAl Viro }
382273d049a4SAl Viro 
3823b4a4f213SStephen Brennan static struct dentry *filename_create(int dfd, struct filename *name,
38241ac12b4bSJeff Layton 				      struct path *path, unsigned int lookup_flags)
38251da177e4SLinus Torvalds {
3826c663e5d8SChristoph Hellwig 	struct dentry *dentry = ERR_PTR(-EEXIST);
3827391172c4SAl Viro 	struct qstr last;
3828b3d4650dSNeilBrown 	bool want_dir = lookup_flags & LOOKUP_DIRECTORY;
3829b3d4650dSNeilBrown 	unsigned int reval_flag = lookup_flags & LOOKUP_REVAL;
3830b3d4650dSNeilBrown 	unsigned int create_flags = LOOKUP_CREATE | LOOKUP_EXCL;
3831391172c4SAl Viro 	int type;
3832c30dabfeSJan Kara 	int err2;
38331ac12b4bSJeff Layton 	int error;
38341ac12b4bSJeff Layton 
3835b3d4650dSNeilBrown 	error = filename_parentat(dfd, name, reval_flag, path, &last, &type);
38360ee50b47SDmitry Kadashev 	if (error)
38370ee50b47SDmitry Kadashev 		return ERR_PTR(error);
38381da177e4SLinus Torvalds 
3839c663e5d8SChristoph Hellwig 	/*
3840c663e5d8SChristoph Hellwig 	 * Yucky last component or no last component at all?
3841c663e5d8SChristoph Hellwig 	 * (foo/., foo/.., /////)
3842c663e5d8SChristoph Hellwig 	 */
38435c31b6ceSAl Viro 	if (unlikely(type != LAST_NORM))
3844ed75e95dSAl Viro 		goto out;
3845c663e5d8SChristoph Hellwig 
3846c30dabfeSJan Kara 	/* don't fail immediately if it's r/o, at least try to report other errors */
3847391172c4SAl Viro 	err2 = mnt_want_write(path->mnt);
3848c663e5d8SChristoph Hellwig 	/*
3849b3d4650dSNeilBrown 	 * Do the final lookup.  Suppress 'create' if there is a trailing
3850b3d4650dSNeilBrown 	 * '/', and a directory wasn't requested.
3851c663e5d8SChristoph Hellwig 	 */
3852b3d4650dSNeilBrown 	if (last.name[last.len] && !want_dir)
3853b3d4650dSNeilBrown 		create_flags = 0;
38545955102cSAl Viro 	inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
3855b3d4650dSNeilBrown 	dentry = __lookup_hash(&last, path->dentry, reval_flag | create_flags);
38561da177e4SLinus Torvalds 	if (IS_ERR(dentry))
3857a8104a9fSAl Viro 		goto unlock;
3858c663e5d8SChristoph Hellwig 
3859a8104a9fSAl Viro 	error = -EEXIST;
3860b18825a7SDavid Howells 	if (d_is_positive(dentry))
3861a8104a9fSAl Viro 		goto fail;
3862b18825a7SDavid Howells 
3863c663e5d8SChristoph Hellwig 	/*
3864c663e5d8SChristoph Hellwig 	 * Special case - lookup gave negative, but... we had foo/bar/
3865c663e5d8SChristoph Hellwig 	 * From the vfs_mknod() POV we just have a negative dentry -
3866c663e5d8SChristoph Hellwig 	 * all is fine. Let's be bastards - you had / on the end, you've
3867c663e5d8SChristoph Hellwig 	 * been asking for (non-existent) directory. -ENOENT for you.
3868c663e5d8SChristoph Hellwig 	 */
3869b3d4650dSNeilBrown 	if (unlikely(!create_flags)) {
3870a8104a9fSAl Viro 		error = -ENOENT;
3871ed75e95dSAl Viro 		goto fail;
3872e9baf6e5SAl Viro 	}
3873c30dabfeSJan Kara 	if (unlikely(err2)) {
3874c30dabfeSJan Kara 		error = err2;
3875a8104a9fSAl Viro 		goto fail;
3876c30dabfeSJan Kara 	}
3877e9baf6e5SAl Viro 	return dentry;
38781da177e4SLinus Torvalds fail:
3879a8104a9fSAl Viro 	dput(dentry);
3880a8104a9fSAl Viro 	dentry = ERR_PTR(error);
3881a8104a9fSAl Viro unlock:
38825955102cSAl Viro 	inode_unlock(path->dentry->d_inode);
3883c30dabfeSJan Kara 	if (!err2)
3884391172c4SAl Viro 		mnt_drop_write(path->mnt);
3885ed75e95dSAl Viro out:
3886391172c4SAl Viro 	path_put(path);
3887ed75e95dSAl Viro 	return dentry;
3888dae6ad8fSAl Viro }
3889fa14a0b8SAl Viro 
3890fa14a0b8SAl Viro struct dentry *kern_path_create(int dfd, const char *pathname,
3891fa14a0b8SAl Viro 				struct path *path, unsigned int lookup_flags)
3892fa14a0b8SAl Viro {
3893b4a4f213SStephen Brennan 	struct filename *filename = getname_kernel(pathname);
3894b4a4f213SStephen Brennan 	struct dentry *res = filename_create(dfd, filename, path, lookup_flags);
3895b4a4f213SStephen Brennan 
3896b4a4f213SStephen Brennan 	putname(filename);
3897b4a4f213SStephen Brennan 	return res;
3898fa14a0b8SAl Viro }
3899dae6ad8fSAl Viro EXPORT_SYMBOL(kern_path_create);
3900dae6ad8fSAl Viro 
3901921a1650SAl Viro void done_path_create(struct path *path, struct dentry *dentry)
3902921a1650SAl Viro {
3903921a1650SAl Viro 	dput(dentry);
39045955102cSAl Viro 	inode_unlock(path->dentry->d_inode);
3905a8104a9fSAl Viro 	mnt_drop_write(path->mnt);
3906921a1650SAl Viro 	path_put(path);
3907921a1650SAl Viro }
3908921a1650SAl Viro EXPORT_SYMBOL(done_path_create);
3909921a1650SAl Viro 
3910520ae687SAl Viro inline struct dentry *user_path_create(int dfd, const char __user *pathname,
39111ac12b4bSJeff Layton 				struct path *path, unsigned int lookup_flags)
3912dae6ad8fSAl Viro {
3913b4a4f213SStephen Brennan 	struct filename *filename = getname(pathname);
3914b4a4f213SStephen Brennan 	struct dentry *res = filename_create(dfd, filename, path, lookup_flags);
3915b4a4f213SStephen Brennan 
3916b4a4f213SStephen Brennan 	putname(filename);
3917b4a4f213SStephen Brennan 	return res;
3918dae6ad8fSAl Viro }
3919dae6ad8fSAl Viro EXPORT_SYMBOL(user_path_create);
3920dae6ad8fSAl Viro 
39216521f891SChristian Brauner /**
39226521f891SChristian Brauner  * vfs_mknod - create device node or file
3923abf08576SChristian Brauner  * @idmap:	idmap of the mount the inode was found from
39246521f891SChristian Brauner  * @dir:	inode of @dentry
39256521f891SChristian Brauner  * @dentry:	pointer to dentry of the base directory
39266521f891SChristian Brauner  * @mode:	mode of the new device node or file
39276521f891SChristian Brauner  * @dev:	device number of device to create
39286521f891SChristian Brauner  *
39296521f891SChristian Brauner  * Create a device node or file.
39306521f891SChristian Brauner  *
3931abf08576SChristian Brauner  * If the inode has been found through an idmapped mount the idmap of
3932abf08576SChristian Brauner  * the vfsmount must be passed through @idmap. This function will then take
3933abf08576SChristian Brauner  * care to map the inode according to @idmap before checking permissions.
39346521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
3935abf08576SChristian Brauner  * raw inode simply passs @nop_mnt_idmap.
39366521f891SChristian Brauner  */
3937abf08576SChristian Brauner int vfs_mknod(struct mnt_idmap *idmap, struct inode *dir,
39386521f891SChristian Brauner 	      struct dentry *dentry, umode_t mode, dev_t dev)
39391da177e4SLinus Torvalds {
3940a3c751a5SMiklos Szeredi 	bool is_whiteout = S_ISCHR(mode) && dev == WHITEOUT_DEV;
39414609e1f1SChristian Brauner 	int error = may_create(idmap, dir, dentry);
39421da177e4SLinus Torvalds 
39431da177e4SLinus Torvalds 	if (error)
39441da177e4SLinus Torvalds 		return error;
39451da177e4SLinus Torvalds 
3946a3c751a5SMiklos Szeredi 	if ((S_ISCHR(mode) || S_ISBLK(mode)) && !is_whiteout &&
3947a3c751a5SMiklos Szeredi 	    !capable(CAP_MKNOD))
39481da177e4SLinus Torvalds 		return -EPERM;
39491da177e4SLinus Torvalds 
3950acfa4380SAl Viro 	if (!dir->i_op->mknod)
39511da177e4SLinus Torvalds 		return -EPERM;
39521da177e4SLinus Torvalds 
39539452e93eSChristian Brauner 	mode = vfs_prepare_mode(idmap, dir, mode, mode, mode);
395408ce5f16SSerge E. Hallyn 	error = devcgroup_inode_mknod(mode, dev);
395508ce5f16SSerge E. Hallyn 	if (error)
395608ce5f16SSerge E. Hallyn 		return error;
395708ce5f16SSerge E. Hallyn 
39581da177e4SLinus Torvalds 	error = security_inode_mknod(dir, dentry, mode, dev);
39591da177e4SLinus Torvalds 	if (error)
39601da177e4SLinus Torvalds 		return error;
39611da177e4SLinus Torvalds 
39625ebb29beSChristian Brauner 	error = dir->i_op->mknod(idmap, dir, dentry, mode, dev);
3963a74574aaSStephen Smalley 	if (!error)
3964f38aa942SAmy Griffis 		fsnotify_create(dir, dentry);
39651da177e4SLinus Torvalds 	return error;
39661da177e4SLinus Torvalds }
39674d359507SAl Viro EXPORT_SYMBOL(vfs_mknod);
39681da177e4SLinus Torvalds 
3969f69aac00SAl Viro static int may_mknod(umode_t mode)
3970463c3197SDave Hansen {
3971463c3197SDave Hansen 	switch (mode & S_IFMT) {
3972463c3197SDave Hansen 	case S_IFREG:
3973463c3197SDave Hansen 	case S_IFCHR:
3974463c3197SDave Hansen 	case S_IFBLK:
3975463c3197SDave Hansen 	case S_IFIFO:
3976463c3197SDave Hansen 	case S_IFSOCK:
3977463c3197SDave Hansen 	case 0: /* zero mode translates to S_IFREG */
3978463c3197SDave Hansen 		return 0;
3979463c3197SDave Hansen 	case S_IFDIR:
3980463c3197SDave Hansen 		return -EPERM;
3981463c3197SDave Hansen 	default:
3982463c3197SDave Hansen 		return -EINVAL;
3983463c3197SDave Hansen 	}
3984463c3197SDave Hansen }
3985463c3197SDave Hansen 
398645f30dabSDmitry Kadashev static int do_mknodat(int dfd, struct filename *name, umode_t mode,
398787c4e192SDominik Brodowski 		unsigned int dev)
39881da177e4SLinus Torvalds {
3989abf08576SChristian Brauner 	struct mnt_idmap *idmap;
39901da177e4SLinus Torvalds 	struct dentry *dentry;
3991dae6ad8fSAl Viro 	struct path path;
3992dae6ad8fSAl Viro 	int error;
3993972567f1SJeff Layton 	unsigned int lookup_flags = 0;
39941da177e4SLinus Torvalds 
39958e4bfca1SAl Viro 	error = may_mknod(mode);
39968e4bfca1SAl Viro 	if (error)
39977797251bSDmitry Kadashev 		goto out1;
3998972567f1SJeff Layton retry:
3999b4a4f213SStephen Brennan 	dentry = filename_create(dfd, name, &path, lookup_flags);
40007797251bSDmitry Kadashev 	error = PTR_ERR(dentry);
4001dae6ad8fSAl Viro 	if (IS_ERR(dentry))
40027797251bSDmitry Kadashev 		goto out1;
40032ad94ae6SAl Viro 
40041639a49cSYang Xu 	error = security_path_mknod(&path, dentry,
40051639a49cSYang Xu 			mode_strip_umask(path.dentry->d_inode, mode), dev);
4006be6d3e56SKentaro Takeda 	if (error)
40077797251bSDmitry Kadashev 		goto out2;
40086521f891SChristian Brauner 
4009abf08576SChristian Brauner 	idmap = mnt_idmap(path.mnt);
40101da177e4SLinus Torvalds 	switch (mode & S_IFMT) {
40111da177e4SLinus Torvalds 		case 0: case S_IFREG:
4012abf08576SChristian Brauner 			error = vfs_create(idmap, path.dentry->d_inode,
40136521f891SChristian Brauner 					   dentry, mode, true);
401405d1a717SMimi Zohar 			if (!error)
401539f60c1cSChristian Brauner 				ima_post_path_mknod(idmap, dentry);
40161da177e4SLinus Torvalds 			break;
40171da177e4SLinus Torvalds 		case S_IFCHR: case S_IFBLK:
4018abf08576SChristian Brauner 			error = vfs_mknod(idmap, path.dentry->d_inode,
40196521f891SChristian Brauner 					  dentry, mode, new_decode_dev(dev));
40201da177e4SLinus Torvalds 			break;
40211da177e4SLinus Torvalds 		case S_IFIFO: case S_IFSOCK:
4022abf08576SChristian Brauner 			error = vfs_mknod(idmap, path.dentry->d_inode,
40236521f891SChristian Brauner 					  dentry, mode, 0);
40241da177e4SLinus Torvalds 			break;
40251da177e4SLinus Torvalds 	}
40267797251bSDmitry Kadashev out2:
4027921a1650SAl Viro 	done_path_create(&path, dentry);
4028972567f1SJeff Layton 	if (retry_estale(error, lookup_flags)) {
4029972567f1SJeff Layton 		lookup_flags |= LOOKUP_REVAL;
4030972567f1SJeff Layton 		goto retry;
4031972567f1SJeff Layton 	}
40327797251bSDmitry Kadashev out1:
40337797251bSDmitry Kadashev 	putname(name);
40341da177e4SLinus Torvalds 	return error;
40351da177e4SLinus Torvalds }
40361da177e4SLinus Torvalds 
403787c4e192SDominik Brodowski SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, umode_t, mode,
403887c4e192SDominik Brodowski 		unsigned int, dev)
403987c4e192SDominik Brodowski {
40407797251bSDmitry Kadashev 	return do_mknodat(dfd, getname(filename), mode, dev);
404187c4e192SDominik Brodowski }
404287c4e192SDominik Brodowski 
40438208a22bSAl Viro SYSCALL_DEFINE3(mknod, const char __user *, filename, umode_t, mode, unsigned, dev)
40445590ff0dSUlrich Drepper {
40457797251bSDmitry Kadashev 	return do_mknodat(AT_FDCWD, getname(filename), mode, dev);
40465590ff0dSUlrich Drepper }
40475590ff0dSUlrich Drepper 
40486521f891SChristian Brauner /**
40496521f891SChristian Brauner  * vfs_mkdir - create directory
4050abf08576SChristian Brauner  * @idmap:	idmap of the mount the inode was found from
40516521f891SChristian Brauner  * @dir:	inode of @dentry
40526521f891SChristian Brauner  * @dentry:	pointer to dentry of the base directory
40536521f891SChristian Brauner  * @mode:	mode of the new directory
40546521f891SChristian Brauner  *
40556521f891SChristian Brauner  * Create a directory.
40566521f891SChristian Brauner  *
4057abf08576SChristian Brauner  * If the inode has been found through an idmapped mount the idmap of
4058abf08576SChristian Brauner  * the vfsmount must be passed through @idmap. This function will then take
4059abf08576SChristian Brauner  * care to map the inode according to @idmap before checking permissions.
40606521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
4061abf08576SChristian Brauner  * raw inode simply passs @nop_mnt_idmap.
40626521f891SChristian Brauner  */
4063abf08576SChristian Brauner int vfs_mkdir(struct mnt_idmap *idmap, struct inode *dir,
40646521f891SChristian Brauner 	      struct dentry *dentry, umode_t mode)
40651da177e4SLinus Torvalds {
4066abf08576SChristian Brauner 	int error;
40678de52778SAl Viro 	unsigned max_links = dir->i_sb->s_max_links;
40681da177e4SLinus Torvalds 
40694609e1f1SChristian Brauner 	error = may_create(idmap, dir, dentry);
40701da177e4SLinus Torvalds 	if (error)
40711da177e4SLinus Torvalds 		return error;
40721da177e4SLinus Torvalds 
4073acfa4380SAl Viro 	if (!dir->i_op->mkdir)
40741da177e4SLinus Torvalds 		return -EPERM;
40751da177e4SLinus Torvalds 
40769452e93eSChristian Brauner 	mode = vfs_prepare_mode(idmap, dir, mode, S_IRWXUGO | S_ISVTX, 0);
40771da177e4SLinus Torvalds 	error = security_inode_mkdir(dir, dentry, mode);
40781da177e4SLinus Torvalds 	if (error)
40791da177e4SLinus Torvalds 		return error;
40801da177e4SLinus Torvalds 
40818de52778SAl Viro 	if (max_links && dir->i_nlink >= max_links)
40828de52778SAl Viro 		return -EMLINK;
40838de52778SAl Viro 
4084c54bd91eSChristian Brauner 	error = dir->i_op->mkdir(idmap, dir, dentry, mode);
4085a74574aaSStephen Smalley 	if (!error)
4086f38aa942SAmy Griffis 		fsnotify_mkdir(dir, dentry);
40871da177e4SLinus Torvalds 	return error;
40881da177e4SLinus Torvalds }
40894d359507SAl Viro EXPORT_SYMBOL(vfs_mkdir);
40901da177e4SLinus Torvalds 
409145f30dabSDmitry Kadashev int do_mkdirat(int dfd, struct filename *name, umode_t mode)
40921da177e4SLinus Torvalds {
40936902d925SDave Hansen 	struct dentry *dentry;
4094dae6ad8fSAl Viro 	struct path path;
4095dae6ad8fSAl Viro 	int error;
4096b76d8b82SJeff Layton 	unsigned int lookup_flags = LOOKUP_DIRECTORY;
40971da177e4SLinus Torvalds 
4098b76d8b82SJeff Layton retry:
4099b4a4f213SStephen Brennan 	dentry = filename_create(dfd, name, &path, lookup_flags);
4100584d3226SDmitry Kadashev 	error = PTR_ERR(dentry);
41016902d925SDave Hansen 	if (IS_ERR(dentry))
4102584d3226SDmitry Kadashev 		goto out_putname;
41036902d925SDave Hansen 
41041639a49cSYang Xu 	error = security_path_mkdir(&path, dentry,
41051639a49cSYang Xu 			mode_strip_umask(path.dentry->d_inode, mode));
41066521f891SChristian Brauner 	if (!error) {
4107abf08576SChristian Brauner 		error = vfs_mkdir(mnt_idmap(path.mnt), path.dentry->d_inode,
4108abf08576SChristian Brauner 				  dentry, mode);
41096521f891SChristian Brauner 	}
4110921a1650SAl Viro 	done_path_create(&path, dentry);
4111b76d8b82SJeff Layton 	if (retry_estale(error, lookup_flags)) {
4112b76d8b82SJeff Layton 		lookup_flags |= LOOKUP_REVAL;
4113b76d8b82SJeff Layton 		goto retry;
4114b76d8b82SJeff Layton 	}
4115584d3226SDmitry Kadashev out_putname:
4116584d3226SDmitry Kadashev 	putname(name);
41171da177e4SLinus Torvalds 	return error;
41181da177e4SLinus Torvalds }
41191da177e4SLinus Torvalds 
41200101db7aSDominik Brodowski SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, umode_t, mode)
41210101db7aSDominik Brodowski {
4122584d3226SDmitry Kadashev 	return do_mkdirat(dfd, getname(pathname), mode);
41230101db7aSDominik Brodowski }
41240101db7aSDominik Brodowski 
4125a218d0fdSAl Viro SYSCALL_DEFINE2(mkdir, const char __user *, pathname, umode_t, mode)
41265590ff0dSUlrich Drepper {
4127584d3226SDmitry Kadashev 	return do_mkdirat(AT_FDCWD, getname(pathname), mode);
41285590ff0dSUlrich Drepper }
41295590ff0dSUlrich Drepper 
41306521f891SChristian Brauner /**
41316521f891SChristian Brauner  * vfs_rmdir - remove directory
4132abf08576SChristian Brauner  * @idmap:	idmap of the mount the inode was found from
41336521f891SChristian Brauner  * @dir:	inode of @dentry
41346521f891SChristian Brauner  * @dentry:	pointer to dentry of the base directory
41356521f891SChristian Brauner  *
41366521f891SChristian Brauner  * Remove a directory.
41376521f891SChristian Brauner  *
4138abf08576SChristian Brauner  * If the inode has been found through an idmapped mount the idmap of
4139abf08576SChristian Brauner  * the vfsmount must be passed through @idmap. This function will then take
4140abf08576SChristian Brauner  * care to map the inode according to @idmap before checking permissions.
41416521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
4142abf08576SChristian Brauner  * raw inode simply passs @nop_mnt_idmap.
41436521f891SChristian Brauner  */
4144abf08576SChristian Brauner int vfs_rmdir(struct mnt_idmap *idmap, struct inode *dir,
41456521f891SChristian Brauner 		     struct dentry *dentry)
41461da177e4SLinus Torvalds {
41474609e1f1SChristian Brauner 	int error = may_delete(idmap, dir, dentry, 1);
41481da177e4SLinus Torvalds 
41491da177e4SLinus Torvalds 	if (error)
41501da177e4SLinus Torvalds 		return error;
41511da177e4SLinus Torvalds 
4152acfa4380SAl Viro 	if (!dir->i_op->rmdir)
41531da177e4SLinus Torvalds 		return -EPERM;
41541da177e4SLinus Torvalds 
41551d2ef590SAl Viro 	dget(dentry);
41565955102cSAl Viro 	inode_lock(dentry->d_inode);
4157912dbc15SSage Weil 
41581da177e4SLinus Torvalds 	error = -EBUSY;
41591bd9c4e4SDavid Howells 	if (is_local_mountpoint(dentry) ||
41601bd9c4e4SDavid Howells 	    (dentry->d_inode->i_flags & S_KERNEL_FILE))
4161912dbc15SSage Weil 		goto out;
4162912dbc15SSage Weil 
41631da177e4SLinus Torvalds 	error = security_inode_rmdir(dir, dentry);
4164912dbc15SSage Weil 	if (error)
4165912dbc15SSage Weil 		goto out;
4166912dbc15SSage Weil 
41671da177e4SLinus Torvalds 	error = dir->i_op->rmdir(dir, dentry);
4168912dbc15SSage Weil 	if (error)
4169912dbc15SSage Weil 		goto out;
4170912dbc15SSage Weil 
41718767712fSAl Viro 	shrink_dcache_parent(dentry);
41721da177e4SLinus Torvalds 	dentry->d_inode->i_flags |= S_DEAD;
4173d83c49f3SAl Viro 	dont_mount(dentry);
41748ed936b5SEric W. Biederman 	detach_mounts(dentry);
41751da177e4SLinus Torvalds 
4176912dbc15SSage Weil out:
41775955102cSAl Viro 	inode_unlock(dentry->d_inode);
41781d2ef590SAl Viro 	dput(dentry);
4179912dbc15SSage Weil 	if (!error)
4180a37d9a17SAmir Goldstein 		d_delete_notify(dir, dentry);
41811da177e4SLinus Torvalds 	return error;
41821da177e4SLinus Torvalds }
41834d359507SAl Viro EXPORT_SYMBOL(vfs_rmdir);
41841da177e4SLinus Torvalds 
418545f30dabSDmitry Kadashev int do_rmdir(int dfd, struct filename *name)
41861da177e4SLinus Torvalds {
41870ee50b47SDmitry Kadashev 	int error;
41881da177e4SLinus Torvalds 	struct dentry *dentry;
4189f5beed75SAl Viro 	struct path path;
4190f5beed75SAl Viro 	struct qstr last;
4191f5beed75SAl Viro 	int type;
4192c6ee9206SJeff Layton 	unsigned int lookup_flags = 0;
4193c6ee9206SJeff Layton retry:
4194c5f563f9SAl Viro 	error = filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
41950ee50b47SDmitry Kadashev 	if (error)
41960ee50b47SDmitry Kadashev 		goto exit1;
41971da177e4SLinus Torvalds 
4198f5beed75SAl Viro 	switch (type) {
41991da177e4SLinus Torvalds 	case LAST_DOTDOT:
42001da177e4SLinus Torvalds 		error = -ENOTEMPTY;
42010ee50b47SDmitry Kadashev 		goto exit2;
42021da177e4SLinus Torvalds 	case LAST_DOT:
42031da177e4SLinus Torvalds 		error = -EINVAL;
42040ee50b47SDmitry Kadashev 		goto exit2;
42051da177e4SLinus Torvalds 	case LAST_ROOT:
42061da177e4SLinus Torvalds 		error = -EBUSY;
42070ee50b47SDmitry Kadashev 		goto exit2;
42081da177e4SLinus Torvalds 	}
42090612d9fbSOGAWA Hirofumi 
4210f5beed75SAl Viro 	error = mnt_want_write(path.mnt);
4211c30dabfeSJan Kara 	if (error)
42120ee50b47SDmitry Kadashev 		goto exit2;
42130612d9fbSOGAWA Hirofumi 
42145955102cSAl Viro 	inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
4215f5beed75SAl Viro 	dentry = __lookup_hash(&last, path.dentry, lookup_flags);
42161da177e4SLinus Torvalds 	error = PTR_ERR(dentry);
42176902d925SDave Hansen 	if (IS_ERR(dentry))
42180ee50b47SDmitry Kadashev 		goto exit3;
4219e6bc45d6STheodore Ts'o 	if (!dentry->d_inode) {
4220e6bc45d6STheodore Ts'o 		error = -ENOENT;
42210ee50b47SDmitry Kadashev 		goto exit4;
4222e6bc45d6STheodore Ts'o 	}
4223f5beed75SAl Viro 	error = security_path_rmdir(&path, dentry);
4224be6d3e56SKentaro Takeda 	if (error)
42250ee50b47SDmitry Kadashev 		goto exit4;
4226abf08576SChristian Brauner 	error = vfs_rmdir(mnt_idmap(path.mnt), path.dentry->d_inode, dentry);
42270ee50b47SDmitry Kadashev exit4:
42281da177e4SLinus Torvalds 	dput(dentry);
42290ee50b47SDmitry Kadashev exit3:
42305955102cSAl Viro 	inode_unlock(path.dentry->d_inode);
4231f5beed75SAl Viro 	mnt_drop_write(path.mnt);
42320ee50b47SDmitry Kadashev exit2:
4233f5beed75SAl Viro 	path_put(&path);
4234c6ee9206SJeff Layton 	if (retry_estale(error, lookup_flags)) {
4235c6ee9206SJeff Layton 		lookup_flags |= LOOKUP_REVAL;
4236c6ee9206SJeff Layton 		goto retry;
4237c6ee9206SJeff Layton 	}
42380ee50b47SDmitry Kadashev exit1:
423924fb33d4SAl Viro 	putname(name);
42401da177e4SLinus Torvalds 	return error;
42411da177e4SLinus Torvalds }
42421da177e4SLinus Torvalds 
42433cdad428SHeiko Carstens SYSCALL_DEFINE1(rmdir, const char __user *, pathname)
42445590ff0dSUlrich Drepper {
4245e24ab0efSChristoph Hellwig 	return do_rmdir(AT_FDCWD, getname(pathname));
42465590ff0dSUlrich Drepper }
42475590ff0dSUlrich Drepper 
4248b21996e3SJ. Bruce Fields /**
4249b21996e3SJ. Bruce Fields  * vfs_unlink - unlink a filesystem object
4250abf08576SChristian Brauner  * @idmap:	idmap of the mount the inode was found from
4251b21996e3SJ. Bruce Fields  * @dir:	parent directory
4252b21996e3SJ. Bruce Fields  * @dentry:	victim
4253b21996e3SJ. Bruce Fields  * @delegated_inode: returns victim inode, if the inode is delegated.
4254b21996e3SJ. Bruce Fields  *
4255b21996e3SJ. Bruce Fields  * The caller must hold dir->i_mutex.
4256b21996e3SJ. Bruce Fields  *
4257b21996e3SJ. Bruce Fields  * If vfs_unlink discovers a delegation, it will return -EWOULDBLOCK and
4258b21996e3SJ. Bruce Fields  * return a reference to the inode in delegated_inode.  The caller
4259b21996e3SJ. Bruce Fields  * should then break the delegation on that inode and retry.  Because
4260b21996e3SJ. Bruce Fields  * breaking a delegation may take a long time, the caller should drop
4261b21996e3SJ. Bruce Fields  * dir->i_mutex before doing so.
4262b21996e3SJ. Bruce Fields  *
4263b21996e3SJ. Bruce Fields  * Alternatively, a caller may pass NULL for delegated_inode.  This may
4264b21996e3SJ. Bruce Fields  * be appropriate for callers that expect the underlying filesystem not
4265b21996e3SJ. Bruce Fields  * to be NFS exported.
42666521f891SChristian Brauner  *
4267abf08576SChristian Brauner  * If the inode has been found through an idmapped mount the idmap of
4268abf08576SChristian Brauner  * the vfsmount must be passed through @idmap. This function will then take
4269abf08576SChristian Brauner  * care to map the inode according to @idmap before checking permissions.
42706521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
4271abf08576SChristian Brauner  * raw inode simply passs @nop_mnt_idmap.
4272b21996e3SJ. Bruce Fields  */
4273abf08576SChristian Brauner int vfs_unlink(struct mnt_idmap *idmap, struct inode *dir,
42746521f891SChristian Brauner 	       struct dentry *dentry, struct inode **delegated_inode)
42751da177e4SLinus Torvalds {
42769accbb97SJ. Bruce Fields 	struct inode *target = dentry->d_inode;
42774609e1f1SChristian Brauner 	int error = may_delete(idmap, dir, dentry, 0);
42781da177e4SLinus Torvalds 
42791da177e4SLinus Torvalds 	if (error)
42801da177e4SLinus Torvalds 		return error;
42811da177e4SLinus Torvalds 
4282acfa4380SAl Viro 	if (!dir->i_op->unlink)
42831da177e4SLinus Torvalds 		return -EPERM;
42841da177e4SLinus Torvalds 
42855955102cSAl Viro 	inode_lock(target);
428651cc3a66SHugh Dickins 	if (IS_SWAPFILE(target))
428751cc3a66SHugh Dickins 		error = -EPERM;
428851cc3a66SHugh Dickins 	else if (is_local_mountpoint(dentry))
42891da177e4SLinus Torvalds 		error = -EBUSY;
42901da177e4SLinus Torvalds 	else {
42911da177e4SLinus Torvalds 		error = security_inode_unlink(dir, dentry);
4292bec1052eSAl Viro 		if (!error) {
42935a14696cSJ. Bruce Fields 			error = try_break_deleg(target, delegated_inode);
42945a14696cSJ. Bruce Fields 			if (error)
4295b21996e3SJ. Bruce Fields 				goto out;
42961da177e4SLinus Torvalds 			error = dir->i_op->unlink(dir, dentry);
42978ed936b5SEric W. Biederman 			if (!error) {
4298d83c49f3SAl Viro 				dont_mount(dentry);
42998ed936b5SEric W. Biederman 				detach_mounts(dentry);
43008ed936b5SEric W. Biederman 			}
4301bec1052eSAl Viro 		}
43021da177e4SLinus Torvalds 	}
4303b21996e3SJ. Bruce Fields out:
43045955102cSAl Viro 	inode_unlock(target);
43051da177e4SLinus Torvalds 
43061da177e4SLinus Torvalds 	/* We don't d_delete() NFS sillyrenamed files--they still exist. */
4307a37d9a17SAmir Goldstein 	if (!error && dentry->d_flags & DCACHE_NFSFS_RENAMED) {
4308a37d9a17SAmir Goldstein 		fsnotify_unlink(dir, dentry);
4309a37d9a17SAmir Goldstein 	} else if (!error) {
43109accbb97SJ. Bruce Fields 		fsnotify_link_count(target);
4311a37d9a17SAmir Goldstein 		d_delete_notify(dir, dentry);
43121da177e4SLinus Torvalds 	}
43130eeca283SRobert Love 
43141da177e4SLinus Torvalds 	return error;
43151da177e4SLinus Torvalds }
43164d359507SAl Viro EXPORT_SYMBOL(vfs_unlink);
43171da177e4SLinus Torvalds 
43181da177e4SLinus Torvalds /*
43191da177e4SLinus Torvalds  * Make sure that the actual truncation of the file will occur outside its
43201b1dcc1bSJes Sorensen  * directory's i_mutex.  Truncate can take a long time if there is a lot of
43211da177e4SLinus Torvalds  * writeout happening, and we don't want to prevent access to the directory
43221da177e4SLinus Torvalds  * while waiting on the I/O.
43231da177e4SLinus Torvalds  */
432445f30dabSDmitry Kadashev int do_unlinkat(int dfd, struct filename *name)
43251da177e4SLinus Torvalds {
43262ad94ae6SAl Viro 	int error;
43271da177e4SLinus Torvalds 	struct dentry *dentry;
4328f5beed75SAl Viro 	struct path path;
4329f5beed75SAl Viro 	struct qstr last;
4330f5beed75SAl Viro 	int type;
43311da177e4SLinus Torvalds 	struct inode *inode = NULL;
4332b21996e3SJ. Bruce Fields 	struct inode *delegated_inode = NULL;
43335d18f813SJeff Layton 	unsigned int lookup_flags = 0;
43345d18f813SJeff Layton retry:
4335c5f563f9SAl Viro 	error = filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
43360ee50b47SDmitry Kadashev 	if (error)
43370ee50b47SDmitry Kadashev 		goto exit1;
43382ad94ae6SAl Viro 
43391da177e4SLinus Torvalds 	error = -EISDIR;
4340f5beed75SAl Viro 	if (type != LAST_NORM)
43410ee50b47SDmitry Kadashev 		goto exit2;
43420612d9fbSOGAWA Hirofumi 
4343f5beed75SAl Viro 	error = mnt_want_write(path.mnt);
4344c30dabfeSJan Kara 	if (error)
43450ee50b47SDmitry Kadashev 		goto exit2;
4346b21996e3SJ. Bruce Fields retry_deleg:
43475955102cSAl Viro 	inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
4348f5beed75SAl Viro 	dentry = __lookup_hash(&last, path.dentry, lookup_flags);
43491da177e4SLinus Torvalds 	error = PTR_ERR(dentry);
43501da177e4SLinus Torvalds 	if (!IS_ERR(dentry)) {
43516521f891SChristian Brauner 
43521da177e4SLinus Torvalds 		/* Why not before? Because we want correct error value */
4353f5beed75SAl Viro 		if (last.name[last.len])
435450338b88STörök Edwin 			goto slashes;
43551da177e4SLinus Torvalds 		inode = dentry->d_inode;
4356b18825a7SDavid Howells 		if (d_is_negative(dentry))
4357e6bc45d6STheodore Ts'o 			goto slashes;
43587de9c6eeSAl Viro 		ihold(inode);
4359f5beed75SAl Viro 		error = security_path_unlink(&path, dentry);
4360be6d3e56SKentaro Takeda 		if (error)
43610ee50b47SDmitry Kadashev 			goto exit3;
4362abf08576SChristian Brauner 		error = vfs_unlink(mnt_idmap(path.mnt), path.dentry->d_inode,
4363abf08576SChristian Brauner 				   dentry, &delegated_inode);
43640ee50b47SDmitry Kadashev exit3:
43651da177e4SLinus Torvalds 		dput(dentry);
43661da177e4SLinus Torvalds 	}
43675955102cSAl Viro 	inode_unlock(path.dentry->d_inode);
43681da177e4SLinus Torvalds 	if (inode)
43691da177e4SLinus Torvalds 		iput(inode);	/* truncate the inode here */
4370b21996e3SJ. Bruce Fields 	inode = NULL;
4371b21996e3SJ. Bruce Fields 	if (delegated_inode) {
43725a14696cSJ. Bruce Fields 		error = break_deleg_wait(&delegated_inode);
4373b21996e3SJ. Bruce Fields 		if (!error)
4374b21996e3SJ. Bruce Fields 			goto retry_deleg;
4375b21996e3SJ. Bruce Fields 	}
4376f5beed75SAl Viro 	mnt_drop_write(path.mnt);
43770ee50b47SDmitry Kadashev exit2:
4378f5beed75SAl Viro 	path_put(&path);
43795d18f813SJeff Layton 	if (retry_estale(error, lookup_flags)) {
43805d18f813SJeff Layton 		lookup_flags |= LOOKUP_REVAL;
43815d18f813SJeff Layton 		inode = NULL;
43825d18f813SJeff Layton 		goto retry;
43835d18f813SJeff Layton 	}
43840ee50b47SDmitry Kadashev exit1:
4385da2f1362SChristoph Hellwig 	putname(name);
43861da177e4SLinus Torvalds 	return error;
43871da177e4SLinus Torvalds 
43881da177e4SLinus Torvalds slashes:
4389b18825a7SDavid Howells 	if (d_is_negative(dentry))
4390b18825a7SDavid Howells 		error = -ENOENT;
439144b1d530SMiklos Szeredi 	else if (d_is_dir(dentry))
4392b18825a7SDavid Howells 		error = -EISDIR;
4393b18825a7SDavid Howells 	else
4394b18825a7SDavid Howells 		error = -ENOTDIR;
43950ee50b47SDmitry Kadashev 	goto exit3;
43961da177e4SLinus Torvalds }
43971da177e4SLinus Torvalds 
43982e4d0924SHeiko Carstens SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag)
43995590ff0dSUlrich Drepper {
44005590ff0dSUlrich Drepper 	if ((flag & ~AT_REMOVEDIR) != 0)
44015590ff0dSUlrich Drepper 		return -EINVAL;
44025590ff0dSUlrich Drepper 
44035590ff0dSUlrich Drepper 	if (flag & AT_REMOVEDIR)
4404e24ab0efSChristoph Hellwig 		return do_rmdir(dfd, getname(pathname));
4405da2f1362SChristoph Hellwig 	return do_unlinkat(dfd, getname(pathname));
44065590ff0dSUlrich Drepper }
44075590ff0dSUlrich Drepper 
44083480b257SHeiko Carstens SYSCALL_DEFINE1(unlink, const char __user *, pathname)
44095590ff0dSUlrich Drepper {
4410da2f1362SChristoph Hellwig 	return do_unlinkat(AT_FDCWD, getname(pathname));
44115590ff0dSUlrich Drepper }
44125590ff0dSUlrich Drepper 
44136521f891SChristian Brauner /**
44146521f891SChristian Brauner  * vfs_symlink - create symlink
4415abf08576SChristian Brauner  * @idmap:	idmap of the mount the inode was found from
44166521f891SChristian Brauner  * @dir:	inode of @dentry
44176521f891SChristian Brauner  * @dentry:	pointer to dentry of the base directory
44186521f891SChristian Brauner  * @oldname:	name of the file to link to
44196521f891SChristian Brauner  *
44206521f891SChristian Brauner  * Create a symlink.
44216521f891SChristian Brauner  *
4422abf08576SChristian Brauner  * If the inode has been found through an idmapped mount the idmap of
4423abf08576SChristian Brauner  * the vfsmount must be passed through @idmap. This function will then take
4424abf08576SChristian Brauner  * care to map the inode according to @idmap before checking permissions.
44256521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
4426abf08576SChristian Brauner  * raw inode simply passs @nop_mnt_idmap.
44276521f891SChristian Brauner  */
4428abf08576SChristian Brauner int vfs_symlink(struct mnt_idmap *idmap, struct inode *dir,
44296521f891SChristian Brauner 		struct dentry *dentry, const char *oldname)
44301da177e4SLinus Torvalds {
44317a77db95SChristian Brauner 	int error;
44321da177e4SLinus Torvalds 
44334609e1f1SChristian Brauner 	error = may_create(idmap, dir, dentry);
44341da177e4SLinus Torvalds 	if (error)
44351da177e4SLinus Torvalds 		return error;
44361da177e4SLinus Torvalds 
4437acfa4380SAl Viro 	if (!dir->i_op->symlink)
44381da177e4SLinus Torvalds 		return -EPERM;
44391da177e4SLinus Torvalds 
44401da177e4SLinus Torvalds 	error = security_inode_symlink(dir, dentry, oldname);
44411da177e4SLinus Torvalds 	if (error)
44421da177e4SLinus Torvalds 		return error;
44431da177e4SLinus Torvalds 
44447a77db95SChristian Brauner 	error = dir->i_op->symlink(idmap, dir, dentry, oldname);
4445a74574aaSStephen Smalley 	if (!error)
4446f38aa942SAmy Griffis 		fsnotify_create(dir, dentry);
44471da177e4SLinus Torvalds 	return error;
44481da177e4SLinus Torvalds }
44494d359507SAl Viro EXPORT_SYMBOL(vfs_symlink);
44501da177e4SLinus Torvalds 
44517a8721f8SDmitry Kadashev int do_symlinkat(struct filename *from, int newdfd, struct filename *to)
44521da177e4SLinus Torvalds {
44532ad94ae6SAl Viro 	int error;
44546902d925SDave Hansen 	struct dentry *dentry;
4455dae6ad8fSAl Viro 	struct path path;
4456f46d3567SJeff Layton 	unsigned int lookup_flags = 0;
44571da177e4SLinus Torvalds 
4458da2d0cedSDmitry Kadashev 	if (IS_ERR(from)) {
4459da2d0cedSDmitry Kadashev 		error = PTR_ERR(from);
4460da2d0cedSDmitry Kadashev 		goto out_putnames;
4461da2d0cedSDmitry Kadashev 	}
4462f46d3567SJeff Layton retry:
4463b4a4f213SStephen Brennan 	dentry = filename_create(newdfd, to, &path, lookup_flags);
44641da177e4SLinus Torvalds 	error = PTR_ERR(dentry);
44656902d925SDave Hansen 	if (IS_ERR(dentry))
4466da2d0cedSDmitry Kadashev 		goto out_putnames;
44676902d925SDave Hansen 
446891a27b2aSJeff Layton 	error = security_path_symlink(&path, dentry, from->name);
4469abf08576SChristian Brauner 	if (!error)
4470abf08576SChristian Brauner 		error = vfs_symlink(mnt_idmap(path.mnt), path.dentry->d_inode,
4471abf08576SChristian Brauner 				    dentry, from->name);
4472921a1650SAl Viro 	done_path_create(&path, dentry);
4473f46d3567SJeff Layton 	if (retry_estale(error, lookup_flags)) {
4474f46d3567SJeff Layton 		lookup_flags |= LOOKUP_REVAL;
4475f46d3567SJeff Layton 		goto retry;
4476f46d3567SJeff Layton 	}
4477da2d0cedSDmitry Kadashev out_putnames:
4478da2d0cedSDmitry Kadashev 	putname(to);
44791da177e4SLinus Torvalds 	putname(from);
44801da177e4SLinus Torvalds 	return error;
44811da177e4SLinus Torvalds }
44821da177e4SLinus Torvalds 
4483b724e846SDominik Brodowski SYSCALL_DEFINE3(symlinkat, const char __user *, oldname,
4484b724e846SDominik Brodowski 		int, newdfd, const char __user *, newname)
4485b724e846SDominik Brodowski {
4486da2d0cedSDmitry Kadashev 	return do_symlinkat(getname(oldname), newdfd, getname(newname));
4487b724e846SDominik Brodowski }
4488b724e846SDominik Brodowski 
44893480b257SHeiko Carstens SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname)
44905590ff0dSUlrich Drepper {
4491da2d0cedSDmitry Kadashev 	return do_symlinkat(getname(oldname), AT_FDCWD, getname(newname));
44925590ff0dSUlrich Drepper }
44935590ff0dSUlrich Drepper 
4494146a8595SJ. Bruce Fields /**
4495146a8595SJ. Bruce Fields  * vfs_link - create a new link
4496146a8595SJ. Bruce Fields  * @old_dentry:	object to be linked
4497abf08576SChristian Brauner  * @idmap:	idmap of the mount
4498146a8595SJ. Bruce Fields  * @dir:	new parent
4499146a8595SJ. Bruce Fields  * @new_dentry:	where to create the new link
4500146a8595SJ. Bruce Fields  * @delegated_inode: returns inode needing a delegation break
4501146a8595SJ. Bruce Fields  *
4502146a8595SJ. Bruce Fields  * The caller must hold dir->i_mutex
4503146a8595SJ. Bruce Fields  *
4504146a8595SJ. Bruce Fields  * If vfs_link discovers a delegation on the to-be-linked file in need
4505146a8595SJ. Bruce Fields  * of breaking, it will return -EWOULDBLOCK and return a reference to the
4506146a8595SJ. Bruce Fields  * inode in delegated_inode.  The caller should then break the delegation
4507146a8595SJ. Bruce Fields  * and retry.  Because breaking a delegation may take a long time, the
4508146a8595SJ. Bruce Fields  * caller should drop the i_mutex before doing so.
4509146a8595SJ. Bruce Fields  *
4510146a8595SJ. Bruce Fields  * Alternatively, a caller may pass NULL for delegated_inode.  This may
4511146a8595SJ. Bruce Fields  * be appropriate for callers that expect the underlying filesystem not
4512146a8595SJ. Bruce Fields  * to be NFS exported.
45136521f891SChristian Brauner  *
4514abf08576SChristian Brauner  * If the inode has been found through an idmapped mount the idmap of
4515abf08576SChristian Brauner  * the vfsmount must be passed through @idmap. This function will then take
4516abf08576SChristian Brauner  * care to map the inode according to @idmap before checking permissions.
45176521f891SChristian Brauner  * On non-idmapped mounts or if permission checking is to be performed on the
4518abf08576SChristian Brauner  * raw inode simply passs @nop_mnt_idmap.
4519146a8595SJ. Bruce Fields  */
4520abf08576SChristian Brauner int vfs_link(struct dentry *old_dentry, struct mnt_idmap *idmap,
45216521f891SChristian Brauner 	     struct inode *dir, struct dentry *new_dentry,
45226521f891SChristian Brauner 	     struct inode **delegated_inode)
45231da177e4SLinus Torvalds {
45241da177e4SLinus Torvalds 	struct inode *inode = old_dentry->d_inode;
45258de52778SAl Viro 	unsigned max_links = dir->i_sb->s_max_links;
45261da177e4SLinus Torvalds 	int error;
45271da177e4SLinus Torvalds 
45281da177e4SLinus Torvalds 	if (!inode)
45291da177e4SLinus Torvalds 		return -ENOENT;
45301da177e4SLinus Torvalds 
45314609e1f1SChristian Brauner 	error = may_create(idmap, dir, new_dentry);
45321da177e4SLinus Torvalds 	if (error)
45331da177e4SLinus Torvalds 		return error;
45341da177e4SLinus Torvalds 
45351da177e4SLinus Torvalds 	if (dir->i_sb != inode->i_sb)
45361da177e4SLinus Torvalds 		return -EXDEV;
45371da177e4SLinus Torvalds 
45381da177e4SLinus Torvalds 	/*
45391da177e4SLinus Torvalds 	 * A link to an append-only or immutable file cannot be created.
45401da177e4SLinus Torvalds 	 */
45411da177e4SLinus Torvalds 	if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
45421da177e4SLinus Torvalds 		return -EPERM;
45430bd23d09SEric W. Biederman 	/*
45440bd23d09SEric W. Biederman 	 * Updating the link count will likely cause i_uid and i_gid to
45450bd23d09SEric W. Biederman 	 * be writen back improperly if their true value is unknown to
45460bd23d09SEric W. Biederman 	 * the vfs.
45470bd23d09SEric W. Biederman 	 */
45484609e1f1SChristian Brauner 	if (HAS_UNMAPPED_ID(idmap, inode))
45490bd23d09SEric W. Biederman 		return -EPERM;
4550acfa4380SAl Viro 	if (!dir->i_op->link)
45511da177e4SLinus Torvalds 		return -EPERM;
45527e79eedbSTetsuo Handa 	if (S_ISDIR(inode->i_mode))
45531da177e4SLinus Torvalds 		return -EPERM;
45541da177e4SLinus Torvalds 
45551da177e4SLinus Torvalds 	error = security_inode_link(old_dentry, dir, new_dentry);
45561da177e4SLinus Torvalds 	if (error)
45571da177e4SLinus Torvalds 		return error;
45581da177e4SLinus Torvalds 
45595955102cSAl Viro 	inode_lock(inode);
4560aae8a97dSAneesh Kumar K.V 	/* Make sure we don't allow creating hardlink to an unlinked file */
4561f4e0c30cSAl Viro 	if (inode->i_nlink == 0 && !(inode->i_state & I_LINKABLE))
4562aae8a97dSAneesh Kumar K.V 		error =  -ENOENT;
45638de52778SAl Viro 	else if (max_links && inode->i_nlink >= max_links)
45648de52778SAl Viro 		error = -EMLINK;
4565146a8595SJ. Bruce Fields 	else {
4566146a8595SJ. Bruce Fields 		error = try_break_deleg(inode, delegated_inode);
4567146a8595SJ. Bruce Fields 		if (!error)
45681da177e4SLinus Torvalds 			error = dir->i_op->link(old_dentry, dir, new_dentry);
4569146a8595SJ. Bruce Fields 	}
4570f4e0c30cSAl Viro 
4571f4e0c30cSAl Viro 	if (!error && (inode->i_state & I_LINKABLE)) {
4572f4e0c30cSAl Viro 		spin_lock(&inode->i_lock);
4573f4e0c30cSAl Viro 		inode->i_state &= ~I_LINKABLE;
4574f4e0c30cSAl Viro 		spin_unlock(&inode->i_lock);
4575f4e0c30cSAl Viro 	}
45765955102cSAl Viro 	inode_unlock(inode);
4577e31e14ecSStephen Smalley 	if (!error)
45787e79eedbSTetsuo Handa 		fsnotify_link(dir, inode, new_dentry);
45791da177e4SLinus Torvalds 	return error;
45801da177e4SLinus Torvalds }
45814d359507SAl Viro EXPORT_SYMBOL(vfs_link);
45821da177e4SLinus Torvalds 
45831da177e4SLinus Torvalds /*
45841da177e4SLinus Torvalds  * Hardlinks are often used in delicate situations.  We avoid
45851da177e4SLinus Torvalds  * security-related surprises by not following symlinks on the
45861da177e4SLinus Torvalds  * newname.  --KAB
45871da177e4SLinus Torvalds  *
45881da177e4SLinus Torvalds  * We don't follow them on the oldname either to be compatible
45891da177e4SLinus Torvalds  * with linux 2.0, and to avoid hard-linking to directories
45901da177e4SLinus Torvalds  * and other special files.  --ADM
45911da177e4SLinus Torvalds  */
4592cf30da90SDmitry Kadashev int do_linkat(int olddfd, struct filename *old, int newdfd,
4593020250f3SDmitry Kadashev 	      struct filename *new, int flags)
45941da177e4SLinus Torvalds {
4595abf08576SChristian Brauner 	struct mnt_idmap *idmap;
45961da177e4SLinus Torvalds 	struct dentry *new_dentry;
4597dae6ad8fSAl Viro 	struct path old_path, new_path;
4598146a8595SJ. Bruce Fields 	struct inode *delegated_inode = NULL;
459911a7b371SAneesh Kumar K.V 	int how = 0;
46001da177e4SLinus Torvalds 	int error;
46011da177e4SLinus Torvalds 
4602020250f3SDmitry Kadashev 	if ((flags & ~(AT_SYMLINK_FOLLOW | AT_EMPTY_PATH)) != 0) {
4603020250f3SDmitry Kadashev 		error = -EINVAL;
4604020250f3SDmitry Kadashev 		goto out_putnames;
4605020250f3SDmitry Kadashev 	}
460611a7b371SAneesh Kumar K.V 	/*
4607f0cc6ffbSLinus Torvalds 	 * To use null names we require CAP_DAC_READ_SEARCH
4608f0cc6ffbSLinus Torvalds 	 * This ensures that not everyone will be able to create
4609f0cc6ffbSLinus Torvalds 	 * handlink using the passed filedescriptor.
461011a7b371SAneesh Kumar K.V 	 */
4611020250f3SDmitry Kadashev 	if (flags & AT_EMPTY_PATH && !capable(CAP_DAC_READ_SEARCH)) {
4612020250f3SDmitry Kadashev 		error = -ENOENT;
4613020250f3SDmitry Kadashev 		goto out_putnames;
4614f0cc6ffbSLinus Torvalds 	}
4615c04030e1SUlrich Drepper 
461611a7b371SAneesh Kumar K.V 	if (flags & AT_SYMLINK_FOLLOW)
461711a7b371SAneesh Kumar K.V 		how |= LOOKUP_FOLLOW;
4618442e31caSJeff Layton retry:
4619794ebceaSStephen Brennan 	error = filename_lookup(olddfd, old, how, &old_path, NULL);
46201da177e4SLinus Torvalds 	if (error)
4621020250f3SDmitry Kadashev 		goto out_putnames;
46222ad94ae6SAl Viro 
4623b4a4f213SStephen Brennan 	new_dentry = filename_create(newdfd, new, &new_path,
4624442e31caSJeff Layton 					(how & LOOKUP_REVAL));
46251da177e4SLinus Torvalds 	error = PTR_ERR(new_dentry);
46266902d925SDave Hansen 	if (IS_ERR(new_dentry))
4627020250f3SDmitry Kadashev 		goto out_putpath;
4628dae6ad8fSAl Viro 
4629dae6ad8fSAl Viro 	error = -EXDEV;
4630dae6ad8fSAl Viro 	if (old_path.mnt != new_path.mnt)
4631dae6ad8fSAl Viro 		goto out_dput;
4632abf08576SChristian Brauner 	idmap = mnt_idmap(new_path.mnt);
46334609e1f1SChristian Brauner 	error = may_linkat(idmap, &old_path);
4634800179c9SKees Cook 	if (unlikely(error))
4635800179c9SKees Cook 		goto out_dput;
4636dae6ad8fSAl Viro 	error = security_path_link(old_path.dentry, &new_path, new_dentry);
4637be6d3e56SKentaro Takeda 	if (error)
4638a8104a9fSAl Viro 		goto out_dput;
4639abf08576SChristian Brauner 	error = vfs_link(old_path.dentry, idmap, new_path.dentry->d_inode,
46406521f891SChristian Brauner 			 new_dentry, &delegated_inode);
464175c3f29dSDave Hansen out_dput:
4642921a1650SAl Viro 	done_path_create(&new_path, new_dentry);
4643146a8595SJ. Bruce Fields 	if (delegated_inode) {
4644146a8595SJ. Bruce Fields 		error = break_deleg_wait(&delegated_inode);
4645d22e6338SOleg Drokin 		if (!error) {
4646d22e6338SOleg Drokin 			path_put(&old_path);
4647146a8595SJ. Bruce Fields 			goto retry;
4648146a8595SJ. Bruce Fields 		}
4649d22e6338SOleg Drokin 	}
4650442e31caSJeff Layton 	if (retry_estale(error, how)) {
4651d22e6338SOleg Drokin 		path_put(&old_path);
4652442e31caSJeff Layton 		how |= LOOKUP_REVAL;
4653442e31caSJeff Layton 		goto retry;
4654442e31caSJeff Layton 	}
4655020250f3SDmitry Kadashev out_putpath:
46562d8f3038SAl Viro 	path_put(&old_path);
4657020250f3SDmitry Kadashev out_putnames:
4658020250f3SDmitry Kadashev 	putname(old);
4659020250f3SDmitry Kadashev 	putname(new);
46601da177e4SLinus Torvalds 
46611da177e4SLinus Torvalds 	return error;
46621da177e4SLinus Torvalds }
46631da177e4SLinus Torvalds 
466446ea89ebSDominik Brodowski SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname,
466546ea89ebSDominik Brodowski 		int, newdfd, const char __user *, newname, int, flags)
466646ea89ebSDominik Brodowski {
4667020250f3SDmitry Kadashev 	return do_linkat(olddfd, getname_uflags(oldname, flags),
4668020250f3SDmitry Kadashev 		newdfd, getname(newname), flags);
466946ea89ebSDominik Brodowski }
467046ea89ebSDominik Brodowski 
46713480b257SHeiko Carstens SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname)
46725590ff0dSUlrich Drepper {
4673020250f3SDmitry Kadashev 	return do_linkat(AT_FDCWD, getname(oldname), AT_FDCWD, getname(newname), 0);
46745590ff0dSUlrich Drepper }
46755590ff0dSUlrich Drepper 
4676bc27027aSMiklos Szeredi /**
4677bc27027aSMiklos Szeredi  * vfs_rename - rename a filesystem object
46782111c3c0SRandy Dunlap  * @rd:		pointer to &struct renamedata info
4679bc27027aSMiklos Szeredi  *
4680bc27027aSMiklos Szeredi  * The caller must hold multiple mutexes--see lock_rename()).
4681bc27027aSMiklos Szeredi  *
4682bc27027aSMiklos Szeredi  * If vfs_rename discovers a delegation in need of breaking at either
4683bc27027aSMiklos Szeredi  * the source or destination, it will return -EWOULDBLOCK and return a
4684bc27027aSMiklos Szeredi  * reference to the inode in delegated_inode.  The caller should then
4685bc27027aSMiklos Szeredi  * break the delegation and retry.  Because breaking a delegation may
4686bc27027aSMiklos Szeredi  * take a long time, the caller should drop all locks before doing
4687bc27027aSMiklos Szeredi  * so.
4688bc27027aSMiklos Szeredi  *
4689bc27027aSMiklos Szeredi  * Alternatively, a caller may pass NULL for delegated_inode.  This may
4690bc27027aSMiklos Szeredi  * be appropriate for callers that expect the underlying filesystem not
4691bc27027aSMiklos Szeredi  * to be NFS exported.
4692bc27027aSMiklos Szeredi  *
46931da177e4SLinus Torvalds  * The worst of all namespace operations - renaming directory. "Perverted"
46941da177e4SLinus Torvalds  * doesn't even start to describe it. Somebody in UCB had a heck of a trip...
46951da177e4SLinus Torvalds  * Problems:
46960117d427SMauro Carvalho Chehab  *
4697d03b29a2SJ. Bruce Fields  *	a) we can get into loop creation.
46981da177e4SLinus Torvalds  *	b) race potential - two innocent renames can create a loop together.
46991da177e4SLinus Torvalds  *	   That's where 4.4 screws up. Current fix: serialization on
4700a11f3a05SArjan van de Ven  *	   sb->s_vfs_rename_mutex. We might be more accurate, but that's another
47011da177e4SLinus Torvalds  *	   story.
47026cedba89SJ. Bruce Fields  *	c) we have to lock _four_ objects - parents and victim (if it exists),
47036cedba89SJ. Bruce Fields  *	   and source (if it is not a directory).
47041b1dcc1bSJes Sorensen  *	   And that - after we got ->i_mutex on parents (until then we don't know
47051da177e4SLinus Torvalds  *	   whether the target exists).  Solution: try to be smart with locking
47061da177e4SLinus Torvalds  *	   order for inodes.  We rely on the fact that tree topology may change
4707a11f3a05SArjan van de Ven  *	   only under ->s_vfs_rename_mutex _and_ that parent of the object we
47081da177e4SLinus Torvalds  *	   move will be locked.  Thus we can rank directories by the tree
47091da177e4SLinus Torvalds  *	   (ancestors first) and rank all non-directories after them.
47101da177e4SLinus Torvalds  *	   That works since everybody except rename does "lock parent, lookup,
4711a11f3a05SArjan van de Ven  *	   lock child" and rename is under ->s_vfs_rename_mutex.
47121da177e4SLinus Torvalds  *	   HOWEVER, it relies on the assumption that any object with ->lookup()
47131da177e4SLinus Torvalds  *	   has no more than 1 dentry.  If "hybrid" objects will ever appear,
47141da177e4SLinus Torvalds  *	   we'd better make sure that there's no link(2) for them.
4715e4eaac06SSage Weil  *	d) conversion from fhandle to dentry may come in the wrong moment - when
47161b1dcc1bSJes Sorensen  *	   we are removing the target. Solution: we will have to grab ->i_mutex
47171da177e4SLinus Torvalds  *	   in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on
4718c41b20e7SAdam Buchbinder  *	   ->i_mutex on parents, which works but leads to some truly excessive
47191da177e4SLinus Torvalds  *	   locking].
47201da177e4SLinus Torvalds  */
47219fe61450SChristian Brauner int vfs_rename(struct renamedata *rd)
47221da177e4SLinus Torvalds {
47231da177e4SLinus Torvalds 	int error;
47249fe61450SChristian Brauner 	struct inode *old_dir = rd->old_dir, *new_dir = rd->new_dir;
47259fe61450SChristian Brauner 	struct dentry *old_dentry = rd->old_dentry;
47269fe61450SChristian Brauner 	struct dentry *new_dentry = rd->new_dentry;
47279fe61450SChristian Brauner 	struct inode **delegated_inode = rd->delegated_inode;
47289fe61450SChristian Brauner 	unsigned int flags = rd->flags;
4729bc27027aSMiklos Szeredi 	bool is_dir = d_is_dir(old_dentry);
4730bc27027aSMiklos Szeredi 	struct inode *source = old_dentry->d_inode;
4731bc27027aSMiklos Szeredi 	struct inode *target = new_dentry->d_inode;
4732da1ce067SMiklos Szeredi 	bool new_is_dir = false;
4733da1ce067SMiklos Szeredi 	unsigned max_links = new_dir->i_sb->s_max_links;
473449d31c2fSAl Viro 	struct name_snapshot old_name;
47351da177e4SLinus Torvalds 
47368d3e2936SMiklos Szeredi 	if (source == target)
47371da177e4SLinus Torvalds 		return 0;
47381da177e4SLinus Torvalds 
47394609e1f1SChristian Brauner 	error = may_delete(rd->old_mnt_idmap, old_dir, old_dentry, is_dir);
47401da177e4SLinus Torvalds 	if (error)
47411da177e4SLinus Torvalds 		return error;
47421da177e4SLinus Torvalds 
4743da1ce067SMiklos Szeredi 	if (!target) {
47444609e1f1SChristian Brauner 		error = may_create(rd->new_mnt_idmap, new_dir, new_dentry);
4745da1ce067SMiklos Szeredi 	} else {
4746da1ce067SMiklos Szeredi 		new_is_dir = d_is_dir(new_dentry);
4747da1ce067SMiklos Szeredi 
4748da1ce067SMiklos Szeredi 		if (!(flags & RENAME_EXCHANGE))
47494609e1f1SChristian Brauner 			error = may_delete(rd->new_mnt_idmap, new_dir,
47506521f891SChristian Brauner 					   new_dentry, is_dir);
4751da1ce067SMiklos Szeredi 		else
47524609e1f1SChristian Brauner 			error = may_delete(rd->new_mnt_idmap, new_dir,
47536521f891SChristian Brauner 					   new_dentry, new_is_dir);
4754da1ce067SMiklos Szeredi 	}
47551da177e4SLinus Torvalds 	if (error)
47561da177e4SLinus Torvalds 		return error;
47571da177e4SLinus Torvalds 
47582773bf00SMiklos Szeredi 	if (!old_dir->i_op->rename)
47591da177e4SLinus Torvalds 		return -EPERM;
47601da177e4SLinus Torvalds 
4761bc27027aSMiklos Szeredi 	/*
4762bc27027aSMiklos Szeredi 	 * If we are going to change the parent - check write permissions,
4763bc27027aSMiklos Szeredi 	 * we'll need to flip '..'.
4764bc27027aSMiklos Szeredi 	 */
4765da1ce067SMiklos Szeredi 	if (new_dir != old_dir) {
4766da1ce067SMiklos Szeredi 		if (is_dir) {
47674609e1f1SChristian Brauner 			error = inode_permission(rd->old_mnt_idmap, source,
476847291baaSChristian Brauner 						 MAY_WRITE);
4769bc27027aSMiklos Szeredi 			if (error)
4770bc27027aSMiklos Szeredi 				return error;
4771bc27027aSMiklos Szeredi 		}
4772da1ce067SMiklos Szeredi 		if ((flags & RENAME_EXCHANGE) && new_is_dir) {
47734609e1f1SChristian Brauner 			error = inode_permission(rd->new_mnt_idmap, target,
477447291baaSChristian Brauner 						 MAY_WRITE);
4775da1ce067SMiklos Szeredi 			if (error)
4776da1ce067SMiklos Szeredi 				return error;
4777da1ce067SMiklos Szeredi 		}
4778da1ce067SMiklos Szeredi 	}
47790eeca283SRobert Love 
47800b3974ebSMiklos Szeredi 	error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,
47810b3974ebSMiklos Szeredi 				      flags);
4782bc27027aSMiklos Szeredi 	if (error)
4783bc27027aSMiklos Szeredi 		return error;
4784bc27027aSMiklos Szeredi 
478549d31c2fSAl Viro 	take_dentry_name_snapshot(&old_name, old_dentry);
4786bc27027aSMiklos Szeredi 	dget(new_dentry);
4787da1ce067SMiklos Szeredi 	if (!is_dir || (flags & RENAME_EXCHANGE))
4788bc27027aSMiklos Szeredi 		lock_two_nondirectories(source, target);
4789bc27027aSMiklos Szeredi 	else if (target)
47905955102cSAl Viro 		inode_lock(target);
4791bc27027aSMiklos Szeredi 
479251cc3a66SHugh Dickins 	error = -EPERM;
479351cc3a66SHugh Dickins 	if (IS_SWAPFILE(source) || (target && IS_SWAPFILE(target)))
479451cc3a66SHugh Dickins 		goto out;
479551cc3a66SHugh Dickins 
4796bc27027aSMiklos Szeredi 	error = -EBUSY;
47977af1364fSEric W. Biederman 	if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
4798bc27027aSMiklos Szeredi 		goto out;
4799bc27027aSMiklos Szeredi 
4800da1ce067SMiklos Szeredi 	if (max_links && new_dir != old_dir) {
4801bc27027aSMiklos Szeredi 		error = -EMLINK;
4802da1ce067SMiklos Szeredi 		if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)
4803bc27027aSMiklos Szeredi 			goto out;
4804da1ce067SMiklos Szeredi 		if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&
4805da1ce067SMiklos Szeredi 		    old_dir->i_nlink >= max_links)
4806da1ce067SMiklos Szeredi 			goto out;
4807da1ce067SMiklos Szeredi 	}
4808da1ce067SMiklos Szeredi 	if (!is_dir) {
4809bc27027aSMiklos Szeredi 		error = try_break_deleg(source, delegated_inode);
4810bc27027aSMiklos Szeredi 		if (error)
4811bc27027aSMiklos Szeredi 			goto out;
4812da1ce067SMiklos Szeredi 	}
4813da1ce067SMiklos Szeredi 	if (target && !new_is_dir) {
4814bc27027aSMiklos Szeredi 		error = try_break_deleg(target, delegated_inode);
4815bc27027aSMiklos Szeredi 		if (error)
4816bc27027aSMiklos Szeredi 			goto out;
4817bc27027aSMiklos Szeredi 	}
4818e18275aeSChristian Brauner 	error = old_dir->i_op->rename(rd->new_mnt_idmap, old_dir, old_dentry,
4819520c8b16SMiklos Szeredi 				      new_dir, new_dentry, flags);
4820bc27027aSMiklos Szeredi 	if (error)
4821bc27027aSMiklos Szeredi 		goto out;
4822bc27027aSMiklos Szeredi 
4823da1ce067SMiklos Szeredi 	if (!(flags & RENAME_EXCHANGE) && target) {
48248767712fSAl Viro 		if (is_dir) {
48258767712fSAl Viro 			shrink_dcache_parent(new_dentry);
4826bc27027aSMiklos Szeredi 			target->i_flags |= S_DEAD;
48278767712fSAl Viro 		}
4828bc27027aSMiklos Szeredi 		dont_mount(new_dentry);
48298ed936b5SEric W. Biederman 		detach_mounts(new_dentry);
4830bc27027aSMiklos Szeredi 	}
4831da1ce067SMiklos Szeredi 	if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {
4832da1ce067SMiklos Szeredi 		if (!(flags & RENAME_EXCHANGE))
4833bc27027aSMiklos Szeredi 			d_move(old_dentry, new_dentry);
4834da1ce067SMiklos Szeredi 		else
4835da1ce067SMiklos Szeredi 			d_exchange(old_dentry, new_dentry);
4836da1ce067SMiklos Szeredi 	}
4837bc27027aSMiklos Szeredi out:
4838da1ce067SMiklos Szeredi 	if (!is_dir || (flags & RENAME_EXCHANGE))
4839bc27027aSMiklos Szeredi 		unlock_two_nondirectories(source, target);
4840bc27027aSMiklos Szeredi 	else if (target)
48415955102cSAl Viro 		inode_unlock(target);
4842bc27027aSMiklos Szeredi 	dput(new_dentry);
4843da1ce067SMiklos Szeredi 	if (!error) {
4844f4ec3a3dSAl Viro 		fsnotify_move(old_dir, new_dir, &old_name.name, is_dir,
4845da1ce067SMiklos Szeredi 			      !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);
4846da1ce067SMiklos Szeredi 		if (flags & RENAME_EXCHANGE) {
4847f4ec3a3dSAl Viro 			fsnotify_move(new_dir, old_dir, &old_dentry->d_name,
4848da1ce067SMiklos Szeredi 				      new_is_dir, NULL, new_dentry);
4849da1ce067SMiklos Szeredi 		}
4850da1ce067SMiklos Szeredi 	}
485149d31c2fSAl Viro 	release_dentry_name_snapshot(&old_name);
48520eeca283SRobert Love 
48531da177e4SLinus Torvalds 	return error;
48541da177e4SLinus Torvalds }
48554d359507SAl Viro EXPORT_SYMBOL(vfs_rename);
48561da177e4SLinus Torvalds 
4857e886663cSJens Axboe int do_renameat2(int olddfd, struct filename *from, int newdfd,
4858e886663cSJens Axboe 		 struct filename *to, unsigned int flags)
48591da177e4SLinus Torvalds {
48609fe61450SChristian Brauner 	struct renamedata rd;
48611da177e4SLinus Torvalds 	struct dentry *old_dentry, *new_dentry;
48621da177e4SLinus Torvalds 	struct dentry *trap;
4863f5beed75SAl Viro 	struct path old_path, new_path;
4864f5beed75SAl Viro 	struct qstr old_last, new_last;
4865f5beed75SAl Viro 	int old_type, new_type;
48668e6d782cSJ. Bruce Fields 	struct inode *delegated_inode = NULL;
4867f5beed75SAl Viro 	unsigned int lookup_flags = 0, target_flags = LOOKUP_RENAME_TARGET;
4868c6a94284SJeff Layton 	bool should_retry = false;
4869e886663cSJens Axboe 	int error = -EINVAL;
4870520c8b16SMiklos Szeredi 
48710d7a8555SMiklos Szeredi 	if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
48720ee50b47SDmitry Kadashev 		goto put_names;
4873da1ce067SMiklos Szeredi 
48740d7a8555SMiklos Szeredi 	if ((flags & (RENAME_NOREPLACE | RENAME_WHITEOUT)) &&
48750d7a8555SMiklos Szeredi 	    (flags & RENAME_EXCHANGE))
48760ee50b47SDmitry Kadashev 		goto put_names;
4877520c8b16SMiklos Szeredi 
4878f5beed75SAl Viro 	if (flags & RENAME_EXCHANGE)
4879f5beed75SAl Viro 		target_flags = 0;
4880f5beed75SAl Viro 
4881c6a94284SJeff Layton retry:
4882c5f563f9SAl Viro 	error = filename_parentat(olddfd, from, lookup_flags, &old_path,
4883e886663cSJens Axboe 				  &old_last, &old_type);
48840ee50b47SDmitry Kadashev 	if (error)
48850ee50b47SDmitry Kadashev 		goto put_names;
48861da177e4SLinus Torvalds 
4887c5f563f9SAl Viro 	error = filename_parentat(newdfd, to, lookup_flags, &new_path, &new_last,
4888e886663cSJens Axboe 				  &new_type);
48890ee50b47SDmitry Kadashev 	if (error)
48901da177e4SLinus Torvalds 		goto exit1;
48911da177e4SLinus Torvalds 
48921da177e4SLinus Torvalds 	error = -EXDEV;
4893f5beed75SAl Viro 	if (old_path.mnt != new_path.mnt)
48941da177e4SLinus Torvalds 		goto exit2;
48951da177e4SLinus Torvalds 
48961da177e4SLinus Torvalds 	error = -EBUSY;
4897f5beed75SAl Viro 	if (old_type != LAST_NORM)
48981da177e4SLinus Torvalds 		goto exit2;
48991da177e4SLinus Torvalds 
49000a7c3937SMiklos Szeredi 	if (flags & RENAME_NOREPLACE)
49010a7c3937SMiklos Szeredi 		error = -EEXIST;
4902f5beed75SAl Viro 	if (new_type != LAST_NORM)
49031da177e4SLinus Torvalds 		goto exit2;
49041da177e4SLinus Torvalds 
4905f5beed75SAl Viro 	error = mnt_want_write(old_path.mnt);
4906c30dabfeSJan Kara 	if (error)
4907c30dabfeSJan Kara 		goto exit2;
4908c30dabfeSJan Kara 
49098e6d782cSJ. Bruce Fields retry_deleg:
4910f5beed75SAl Viro 	trap = lock_rename(new_path.dentry, old_path.dentry);
49111da177e4SLinus Torvalds 
4912f5beed75SAl Viro 	old_dentry = __lookup_hash(&old_last, old_path.dentry, lookup_flags);
49131da177e4SLinus Torvalds 	error = PTR_ERR(old_dentry);
49141da177e4SLinus Torvalds 	if (IS_ERR(old_dentry))
49151da177e4SLinus Torvalds 		goto exit3;
49161da177e4SLinus Torvalds 	/* source must exist */
49171da177e4SLinus Torvalds 	error = -ENOENT;
4918b18825a7SDavid Howells 	if (d_is_negative(old_dentry))
49191da177e4SLinus Torvalds 		goto exit4;
4920f5beed75SAl Viro 	new_dentry = __lookup_hash(&new_last, new_path.dentry, lookup_flags | target_flags);
49211da177e4SLinus Torvalds 	error = PTR_ERR(new_dentry);
49221da177e4SLinus Torvalds 	if (IS_ERR(new_dentry))
49231da177e4SLinus Torvalds 		goto exit4;
49240a7c3937SMiklos Szeredi 	error = -EEXIST;
49250a7c3937SMiklos Szeredi 	if ((flags & RENAME_NOREPLACE) && d_is_positive(new_dentry))
49260a7c3937SMiklos Szeredi 		goto exit5;
4927da1ce067SMiklos Szeredi 	if (flags & RENAME_EXCHANGE) {
4928da1ce067SMiklos Szeredi 		error = -ENOENT;
4929da1ce067SMiklos Szeredi 		if (d_is_negative(new_dentry))
4930da1ce067SMiklos Szeredi 			goto exit5;
4931da1ce067SMiklos Szeredi 
4932da1ce067SMiklos Szeredi 		if (!d_is_dir(new_dentry)) {
4933da1ce067SMiklos Szeredi 			error = -ENOTDIR;
4934f5beed75SAl Viro 			if (new_last.name[new_last.len])
4935da1ce067SMiklos Szeredi 				goto exit5;
4936da1ce067SMiklos Szeredi 		}
4937da1ce067SMiklos Szeredi 	}
49380a7c3937SMiklos Szeredi 	/* unless the source is a directory trailing slashes give -ENOTDIR */
49390a7c3937SMiklos Szeredi 	if (!d_is_dir(old_dentry)) {
49400a7c3937SMiklos Szeredi 		error = -ENOTDIR;
4941f5beed75SAl Viro 		if (old_last.name[old_last.len])
49420a7c3937SMiklos Szeredi 			goto exit5;
4943f5beed75SAl Viro 		if (!(flags & RENAME_EXCHANGE) && new_last.name[new_last.len])
49440a7c3937SMiklos Szeredi 			goto exit5;
49450a7c3937SMiklos Szeredi 	}
49460a7c3937SMiklos Szeredi 	/* source should not be ancestor of target */
49470a7c3937SMiklos Szeredi 	error = -EINVAL;
49480a7c3937SMiklos Szeredi 	if (old_dentry == trap)
49490a7c3937SMiklos Szeredi 		goto exit5;
49501da177e4SLinus Torvalds 	/* target should not be an ancestor of source */
4951da1ce067SMiklos Szeredi 	if (!(flags & RENAME_EXCHANGE))
49521da177e4SLinus Torvalds 		error = -ENOTEMPTY;
49531da177e4SLinus Torvalds 	if (new_dentry == trap)
49541da177e4SLinus Torvalds 		goto exit5;
49551da177e4SLinus Torvalds 
4956f5beed75SAl Viro 	error = security_path_rename(&old_path, old_dentry,
4957f5beed75SAl Viro 				     &new_path, new_dentry, flags);
4958be6d3e56SKentaro Takeda 	if (error)
4959c30dabfeSJan Kara 		goto exit5;
49609fe61450SChristian Brauner 
49619fe61450SChristian Brauner 	rd.old_dir	   = old_path.dentry->d_inode;
49629fe61450SChristian Brauner 	rd.old_dentry	   = old_dentry;
4963abf08576SChristian Brauner 	rd.old_mnt_idmap   = mnt_idmap(old_path.mnt);
49649fe61450SChristian Brauner 	rd.new_dir	   = new_path.dentry->d_inode;
49659fe61450SChristian Brauner 	rd.new_dentry	   = new_dentry;
4966abf08576SChristian Brauner 	rd.new_mnt_idmap   = mnt_idmap(new_path.mnt);
49679fe61450SChristian Brauner 	rd.delegated_inode = &delegated_inode;
49689fe61450SChristian Brauner 	rd.flags	   = flags;
49699fe61450SChristian Brauner 	error = vfs_rename(&rd);
49701da177e4SLinus Torvalds exit5:
49711da177e4SLinus Torvalds 	dput(new_dentry);
49721da177e4SLinus Torvalds exit4:
49731da177e4SLinus Torvalds 	dput(old_dentry);
49741da177e4SLinus Torvalds exit3:
4975f5beed75SAl Viro 	unlock_rename(new_path.dentry, old_path.dentry);
49768e6d782cSJ. Bruce Fields 	if (delegated_inode) {
49778e6d782cSJ. Bruce Fields 		error = break_deleg_wait(&delegated_inode);
49788e6d782cSJ. Bruce Fields 		if (!error)
49798e6d782cSJ. Bruce Fields 			goto retry_deleg;
49808e6d782cSJ. Bruce Fields 	}
4981f5beed75SAl Viro 	mnt_drop_write(old_path.mnt);
49821da177e4SLinus Torvalds exit2:
4983c6a94284SJeff Layton 	if (retry_estale(error, lookup_flags))
4984c6a94284SJeff Layton 		should_retry = true;
4985f5beed75SAl Viro 	path_put(&new_path);
49861da177e4SLinus Torvalds exit1:
4987f5beed75SAl Viro 	path_put(&old_path);
4988c6a94284SJeff Layton 	if (should_retry) {
4989c6a94284SJeff Layton 		should_retry = false;
4990c6a94284SJeff Layton 		lookup_flags |= LOOKUP_REVAL;
4991c6a94284SJeff Layton 		goto retry;
4992c6a94284SJeff Layton 	}
49930ee50b47SDmitry Kadashev put_names:
4994e886663cSJens Axboe 	putname(from);
4995e886663cSJens Axboe 	putname(to);
49961da177e4SLinus Torvalds 	return error;
49971da177e4SLinus Torvalds }
49981da177e4SLinus Torvalds 
4999ee81feb6SDominik Brodowski SYSCALL_DEFINE5(renameat2, int, olddfd, const char __user *, oldname,
5000ee81feb6SDominik Brodowski 		int, newdfd, const char __user *, newname, unsigned int, flags)
5001ee81feb6SDominik Brodowski {
5002e886663cSJens Axboe 	return do_renameat2(olddfd, getname(oldname), newdfd, getname(newname),
5003e886663cSJens Axboe 				flags);
5004ee81feb6SDominik Brodowski }
5005ee81feb6SDominik Brodowski 
5006520c8b16SMiklos Szeredi SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname,
5007520c8b16SMiklos Szeredi 		int, newdfd, const char __user *, newname)
5008520c8b16SMiklos Szeredi {
5009e886663cSJens Axboe 	return do_renameat2(olddfd, getname(oldname), newdfd, getname(newname),
5010e886663cSJens Axboe 				0);
5011520c8b16SMiklos Szeredi }
5012520c8b16SMiklos Szeredi 
5013a26eab24SHeiko Carstens SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname)
50145590ff0dSUlrich Drepper {
5015e886663cSJens Axboe 	return do_renameat2(AT_FDCWD, getname(oldname), AT_FDCWD,
5016e886663cSJens Axboe 				getname(newname), 0);
50175590ff0dSUlrich Drepper }
50185590ff0dSUlrich Drepper 
50195d826c84SAl Viro int readlink_copy(char __user *buffer, int buflen, const char *link)
50201da177e4SLinus Torvalds {
50215d826c84SAl Viro 	int len = PTR_ERR(link);
50221da177e4SLinus Torvalds 	if (IS_ERR(link))
50231da177e4SLinus Torvalds 		goto out;
50241da177e4SLinus Torvalds 
50251da177e4SLinus Torvalds 	len = strlen(link);
50261da177e4SLinus Torvalds 	if (len > (unsigned) buflen)
50271da177e4SLinus Torvalds 		len = buflen;
50281da177e4SLinus Torvalds 	if (copy_to_user(buffer, link, len))
50291da177e4SLinus Torvalds 		len = -EFAULT;
50301da177e4SLinus Torvalds out:
50311da177e4SLinus Torvalds 	return len;
50321da177e4SLinus Torvalds }
50331da177e4SLinus Torvalds 
5034d60874cdSMiklos Szeredi /**
5035fd4a0edfSMiklos Szeredi  * vfs_readlink - copy symlink body into userspace buffer
5036fd4a0edfSMiklos Szeredi  * @dentry: dentry on which to get symbolic link
5037fd4a0edfSMiklos Szeredi  * @buffer: user memory pointer
5038fd4a0edfSMiklos Szeredi  * @buflen: size of buffer
5039fd4a0edfSMiklos Szeredi  *
5040fd4a0edfSMiklos Szeredi  * Does not touch atime.  That's up to the caller if necessary
5041fd4a0edfSMiklos Szeredi  *
5042fd4a0edfSMiklos Szeredi  * Does not call security hook.
5043fd4a0edfSMiklos Szeredi  */
5044fd4a0edfSMiklos Szeredi int vfs_readlink(struct dentry *dentry, char __user *buffer, int buflen)
5045fd4a0edfSMiklos Szeredi {
5046fd4a0edfSMiklos Szeredi 	struct inode *inode = d_inode(dentry);
5047f2df5da6SAl Viro 	DEFINE_DELAYED_CALL(done);
5048f2df5da6SAl Viro 	const char *link;
5049f2df5da6SAl Viro 	int res;
5050fd4a0edfSMiklos Szeredi 
505176fca90eSMiklos Szeredi 	if (unlikely(!(inode->i_opflags & IOP_DEFAULT_READLINK))) {
505276fca90eSMiklos Szeredi 		if (unlikely(inode->i_op->readlink))
505376fca90eSMiklos Szeredi 			return inode->i_op->readlink(dentry, buffer, buflen);
505476fca90eSMiklos Szeredi 
505576fca90eSMiklos Szeredi 		if (!d_is_symlink(dentry))
5056fd4a0edfSMiklos Szeredi 			return -EINVAL;
5057fd4a0edfSMiklos Szeredi 
505876fca90eSMiklos Szeredi 		spin_lock(&inode->i_lock);
505976fca90eSMiklos Szeredi 		inode->i_opflags |= IOP_DEFAULT_READLINK;
506076fca90eSMiklos Szeredi 		spin_unlock(&inode->i_lock);
506176fca90eSMiklos Szeredi 	}
506276fca90eSMiklos Szeredi 
50634c4f7c19SEric Biggers 	link = READ_ONCE(inode->i_link);
5064f2df5da6SAl Viro 	if (!link) {
5065f2df5da6SAl Viro 		link = inode->i_op->get_link(dentry, inode, &done);
5066f2df5da6SAl Viro 		if (IS_ERR(link))
5067f2df5da6SAl Viro 			return PTR_ERR(link);
5068f2df5da6SAl Viro 	}
5069f2df5da6SAl Viro 	res = readlink_copy(buffer, buflen, link);
5070f2df5da6SAl Viro 	do_delayed_call(&done);
5071f2df5da6SAl Viro 	return res;
5072fd4a0edfSMiklos Szeredi }
5073fd4a0edfSMiklos Szeredi EXPORT_SYMBOL(vfs_readlink);
50741da177e4SLinus Torvalds 
5075d60874cdSMiklos Szeredi /**
5076d60874cdSMiklos Szeredi  * vfs_get_link - get symlink body
5077d60874cdSMiklos Szeredi  * @dentry: dentry on which to get symbolic link
5078d60874cdSMiklos Szeredi  * @done: caller needs to free returned data with this
5079d60874cdSMiklos Szeredi  *
5080d60874cdSMiklos Szeredi  * Calls security hook and i_op->get_link() on the supplied inode.
5081d60874cdSMiklos Szeredi  *
5082d60874cdSMiklos Szeredi  * It does not touch atime.  That's up to the caller if necessary.
5083d60874cdSMiklos Szeredi  *
5084d60874cdSMiklos Szeredi  * Does not work on "special" symlinks like /proc/$$/fd/N
5085d60874cdSMiklos Szeredi  */
5086d60874cdSMiklos Szeredi const char *vfs_get_link(struct dentry *dentry, struct delayed_call *done)
5087d60874cdSMiklos Szeredi {
5088d60874cdSMiklos Szeredi 	const char *res = ERR_PTR(-EINVAL);
5089d60874cdSMiklos Szeredi 	struct inode *inode = d_inode(dentry);
5090d60874cdSMiklos Szeredi 
5091d60874cdSMiklos Szeredi 	if (d_is_symlink(dentry)) {
5092d60874cdSMiklos Szeredi 		res = ERR_PTR(security_inode_readlink(dentry));
5093d60874cdSMiklos Szeredi 		if (!res)
5094d60874cdSMiklos Szeredi 			res = inode->i_op->get_link(dentry, inode, done);
5095d60874cdSMiklos Szeredi 	}
5096d60874cdSMiklos Szeredi 	return res;
5097d60874cdSMiklos Szeredi }
5098d60874cdSMiklos Szeredi EXPORT_SYMBOL(vfs_get_link);
5099d60874cdSMiklos Szeredi 
51001da177e4SLinus Torvalds /* get the link contents into pagecache */
51016b255391SAl Viro const char *page_get_link(struct dentry *dentry, struct inode *inode,
5102fceef393SAl Viro 			  struct delayed_call *callback)
51031da177e4SLinus Torvalds {
5104ebd09abbSDuane Griffin 	char *kaddr;
51051da177e4SLinus Torvalds 	struct page *page;
51066b255391SAl Viro 	struct address_space *mapping = inode->i_mapping;
51076b255391SAl Viro 
5108d3883d4fSAl Viro 	if (!dentry) {
5109d3883d4fSAl Viro 		page = find_get_page(mapping, 0);
5110d3883d4fSAl Viro 		if (!page)
51116b255391SAl Viro 			return ERR_PTR(-ECHILD);
5112d3883d4fSAl Viro 		if (!PageUptodate(page)) {
5113d3883d4fSAl Viro 			put_page(page);
5114d3883d4fSAl Viro 			return ERR_PTR(-ECHILD);
5115d3883d4fSAl Viro 		}
5116d3883d4fSAl Viro 	} else {
5117090d2b18SPekka Enberg 		page = read_mapping_page(mapping, 0, NULL);
51181da177e4SLinus Torvalds 		if (IS_ERR(page))
51196fe6900eSNick Piggin 			return (char*)page;
5120d3883d4fSAl Viro 	}
5121fceef393SAl Viro 	set_delayed_call(callback, page_put_link, page);
512221fc61c7SAl Viro 	BUG_ON(mapping_gfp_mask(mapping) & __GFP_HIGHMEM);
512321fc61c7SAl Viro 	kaddr = page_address(page);
51246b255391SAl Viro 	nd_terminate_link(kaddr, inode->i_size, PAGE_SIZE - 1);
5125ebd09abbSDuane Griffin 	return kaddr;
51261da177e4SLinus Torvalds }
51271da177e4SLinus Torvalds 
51286b255391SAl Viro EXPORT_SYMBOL(page_get_link);
51291da177e4SLinus Torvalds 
5130fceef393SAl Viro void page_put_link(void *arg)
51311da177e4SLinus Torvalds {
5132fceef393SAl Viro 	put_page(arg);
51331da177e4SLinus Torvalds }
51344d359507SAl Viro EXPORT_SYMBOL(page_put_link);
51351da177e4SLinus Torvalds 
5136aa80deabSAl Viro int page_readlink(struct dentry *dentry, char __user *buffer, int buflen)
5137aa80deabSAl Viro {
5138fceef393SAl Viro 	DEFINE_DELAYED_CALL(done);
51396b255391SAl Viro 	int res = readlink_copy(buffer, buflen,
51406b255391SAl Viro 				page_get_link(dentry, d_inode(dentry),
5141fceef393SAl Viro 					      &done));
5142fceef393SAl Viro 	do_delayed_call(&done);
5143aa80deabSAl Viro 	return res;
5144aa80deabSAl Viro }
5145aa80deabSAl Viro EXPORT_SYMBOL(page_readlink);
5146aa80deabSAl Viro 
514756f5746cSMatthew Wilcox (Oracle) int page_symlink(struct inode *inode, const char *symname, int len)
51481da177e4SLinus Torvalds {
51491da177e4SLinus Torvalds 	struct address_space *mapping = inode->i_mapping;
515027a77913SMatthew Wilcox (Oracle) 	const struct address_space_operations *aops = mapping->a_ops;
515156f5746cSMatthew Wilcox (Oracle) 	bool nofs = !mapping_gfp_constraint(mapping, __GFP_FS);
51520adb25d2SKirill Korotaev 	struct page *page;
51531468c6f4SAlexander Potapenko 	void *fsdata = NULL;
5154beb497abSDmitriy Monakhov 	int err;
51552d878178SMatthew Wilcox (Oracle) 	unsigned int flags;
51561da177e4SLinus Torvalds 
51577e53cac4SNeilBrown retry:
51582d878178SMatthew Wilcox (Oracle) 	if (nofs)
51592d878178SMatthew Wilcox (Oracle) 		flags = memalloc_nofs_save();
516027a77913SMatthew Wilcox (Oracle) 	err = aops->write_begin(NULL, mapping, 0, len-1, &page, &fsdata);
51612d878178SMatthew Wilcox (Oracle) 	if (nofs)
51622d878178SMatthew Wilcox (Oracle) 		memalloc_nofs_restore(flags);
51631da177e4SLinus Torvalds 	if (err)
5164afddba49SNick Piggin 		goto fail;
5165afddba49SNick Piggin 
516621fc61c7SAl Viro 	memcpy(page_address(page), symname, len-1);
5167afddba49SNick Piggin 
516827a77913SMatthew Wilcox (Oracle) 	err = aops->write_end(NULL, mapping, 0, len-1, len-1,
5169afddba49SNick Piggin 							page, fsdata);
51701da177e4SLinus Torvalds 	if (err < 0)
51711da177e4SLinus Torvalds 		goto fail;
5172afddba49SNick Piggin 	if (err < len-1)
5173afddba49SNick Piggin 		goto retry;
5174afddba49SNick Piggin 
51751da177e4SLinus Torvalds 	mark_inode_dirty(inode);
51761da177e4SLinus Torvalds 	return 0;
51771da177e4SLinus Torvalds fail:
51781da177e4SLinus Torvalds 	return err;
51791da177e4SLinus Torvalds }
51804d359507SAl Viro EXPORT_SYMBOL(page_symlink);
51810adb25d2SKirill Korotaev 
518292e1d5beSArjan van de Ven const struct inode_operations page_symlink_inode_operations = {
51836b255391SAl Viro 	.get_link	= page_get_link,
51841da177e4SLinus Torvalds };
51851da177e4SLinus Torvalds EXPORT_SYMBOL(page_symlink_inode_operations);
5186