xref: /openbmc/linux/fs/namei.c (revision babbdf5b)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  linux/fs/namei.c
4  *
5  *  Copyright (C) 1991, 1992  Linus Torvalds
6  */
7 
8 /*
9  * Some corrections by tytso.
10  */
11 
12 /* [Feb 1997 T. Schoebel-Theuer] Complete rewrite of the pathname
13  * lookup logic.
14  */
15 /* [Feb-Apr 2000, AV] Rewrite to the new namespace architecture.
16  */
17 
18 #include <linux/init.h>
19 #include <linux/export.h>
20 #include <linux/kernel.h>
21 #include <linux/slab.h>
22 #include <linux/fs.h>
23 #include <linux/namei.h>
24 #include <linux/pagemap.h>
25 #include <linux/fsnotify.h>
26 #include <linux/personality.h>
27 #include <linux/security.h>
28 #include <linux/ima.h>
29 #include <linux/syscalls.h>
30 #include <linux/mount.h>
31 #include <linux/audit.h>
32 #include <linux/capability.h>
33 #include <linux/file.h>
34 #include <linux/fcntl.h>
35 #include <linux/device_cgroup.h>
36 #include <linux/fs_struct.h>
37 #include <linux/posix_acl.h>
38 #include <linux/hash.h>
39 #include <linux/bitops.h>
40 #include <linux/init_task.h>
41 #include <linux/uaccess.h>
42 
43 #include "internal.h"
44 #include "mount.h"
45 
46 /* [Feb-1997 T. Schoebel-Theuer]
47  * Fundamental changes in the pathname lookup mechanisms (namei)
48  * were necessary because of omirr.  The reason is that omirr needs
49  * to know the _real_ pathname, not the user-supplied one, in case
50  * of symlinks (and also when transname replacements occur).
51  *
52  * The new code replaces the old recursive symlink resolution with
53  * an iterative one (in case of non-nested symlink chains).  It does
54  * this with calls to <fs>_follow_link().
55  * As a side effect, dir_namei(), _namei() and follow_link() are now
56  * replaced with a single function lookup_dentry() that can handle all
57  * the special cases of the former code.
58  *
59  * With the new dcache, the pathname is stored at each inode, at least as
60  * long as the refcount of the inode is positive.  As a side effect, the
61  * size of the dcache depends on the inode cache and thus is dynamic.
62  *
63  * [29-Apr-1998 C. Scott Ananian] Updated above description of symlink
64  * resolution to correspond with current state of the code.
65  *
66  * Note that the symlink resolution is not *completely* iterative.
67  * There is still a significant amount of tail- and mid- recursion in
68  * the algorithm.  Also, note that <fs>_readlink() is not used in
69  * lookup_dentry(): lookup_dentry() on the result of <fs>_readlink()
70  * may return different results than <fs>_follow_link().  Many virtual
71  * filesystems (including /proc) exhibit this behavior.
72  */
73 
74 /* [24-Feb-97 T. Schoebel-Theuer] Side effects caused by new implementation:
75  * New symlink semantics: when open() is called with flags O_CREAT | O_EXCL
76  * and the name already exists in form of a symlink, try to create the new
77  * name indicated by the symlink. The old code always complained that the
78  * name already exists, due to not following the symlink even if its target
79  * is nonexistent.  The new semantics affects also mknod() and link() when
80  * the name is a symlink pointing to a non-existent name.
81  *
82  * I don't know which semantics is the right one, since I have no access
83  * to standards. But I found by trial that HP-UX 9.0 has the full "new"
84  * semantics implemented, while SunOS 4.1.1 and Solaris (SunOS 5.4) have the
85  * "old" one. Personally, I think the new semantics is much more logical.
86  * Note that "ln old new" where "new" is a symlink pointing to a non-existing
87  * file does succeed in both HP-UX and SunOs, but not in Solaris
88  * and in the old Linux semantics.
89  */
90 
91 /* [16-Dec-97 Kevin Buhr] For security reasons, we change some symlink
92  * semantics.  See the comments in "open_namei" and "do_link" below.
93  *
94  * [10-Sep-98 Alan Modra] Another symlink change.
95  */
96 
97 /* [Feb-Apr 2000 AV] Complete rewrite. Rules for symlinks:
98  *	inside the path - always follow.
99  *	in the last component in creation/removal/renaming - never follow.
100  *	if LOOKUP_FOLLOW passed - follow.
101  *	if the pathname has trailing slashes - follow.
102  *	otherwise - don't follow.
103  * (applied in that order).
104  *
105  * [Jun 2000 AV] Inconsistent behaviour of open() in case if flags==O_CREAT
106  * restored for 2.4. This is the last surviving part of old 4.2BSD bug.
107  * During the 2.4 we need to fix the userland stuff depending on it -
108  * hopefully we will be able to get rid of that wart in 2.5. So far only
109  * XEmacs seems to be relying on it...
110  */
111 /*
112  * [Sep 2001 AV] Single-semaphore locking scheme (kudos to David Holland)
113  * implemented.  Let's see if raised priority of ->s_vfs_rename_mutex gives
114  * any extra contention...
115  */
116 
117 /* In order to reduce some races, while at the same time doing additional
118  * checking and hopefully speeding things up, we copy filenames to the
119  * kernel data space before using them..
120  *
121  * POSIX.1 2.4: an empty pathname is invalid (ENOENT).
122  * PATH_MAX includes the nul terminator --RR.
123  */
124 
125 #define EMBEDDED_NAME_MAX	(PATH_MAX - offsetof(struct filename, iname))
126 
127 struct filename *
128 getname_flags(const char __user *filename, int flags, int *empty)
129 {
130 	struct filename *result;
131 	char *kname;
132 	int len;
133 
134 	result = audit_reusename(filename);
135 	if (result)
136 		return result;
137 
138 	result = __getname();
139 	if (unlikely(!result))
140 		return ERR_PTR(-ENOMEM);
141 
142 	/*
143 	 * First, try to embed the struct filename inside the names_cache
144 	 * allocation
145 	 */
146 	kname = (char *)result->iname;
147 	result->name = kname;
148 
149 	len = strncpy_from_user(kname, filename, EMBEDDED_NAME_MAX);
150 	if (unlikely(len < 0)) {
151 		__putname(result);
152 		return ERR_PTR(len);
153 	}
154 
155 	/*
156 	 * Uh-oh. We have a name that's approaching PATH_MAX. Allocate a
157 	 * separate struct filename so we can dedicate the entire
158 	 * names_cache allocation for the pathname, and re-do the copy from
159 	 * userland.
160 	 */
161 	if (unlikely(len == EMBEDDED_NAME_MAX)) {
162 		const size_t size = offsetof(struct filename, iname[1]);
163 		kname = (char *)result;
164 
165 		/*
166 		 * size is chosen that way we to guarantee that
167 		 * result->iname[0] is within the same object and that
168 		 * kname can't be equal to result->iname, no matter what.
169 		 */
170 		result = kzalloc(size, GFP_KERNEL);
171 		if (unlikely(!result)) {
172 			__putname(kname);
173 			return ERR_PTR(-ENOMEM);
174 		}
175 		result->name = kname;
176 		len = strncpy_from_user(kname, filename, PATH_MAX);
177 		if (unlikely(len < 0)) {
178 			__putname(kname);
179 			kfree(result);
180 			return ERR_PTR(len);
181 		}
182 		if (unlikely(len == PATH_MAX)) {
183 			__putname(kname);
184 			kfree(result);
185 			return ERR_PTR(-ENAMETOOLONG);
186 		}
187 	}
188 
189 	result->refcnt = 1;
190 	/* The empty path is special. */
191 	if (unlikely(!len)) {
192 		if (empty)
193 			*empty = 1;
194 		if (!(flags & LOOKUP_EMPTY)) {
195 			putname(result);
196 			return ERR_PTR(-ENOENT);
197 		}
198 	}
199 
200 	result->uptr = filename;
201 	result->aname = NULL;
202 	audit_getname(result);
203 	return result;
204 }
205 
206 struct filename *
207 getname(const char __user * filename)
208 {
209 	return getname_flags(filename, 0, NULL);
210 }
211 
212 struct filename *
213 getname_kernel(const char * filename)
214 {
215 	struct filename *result;
216 	int len = strlen(filename) + 1;
217 
218 	result = __getname();
219 	if (unlikely(!result))
220 		return ERR_PTR(-ENOMEM);
221 
222 	if (len <= EMBEDDED_NAME_MAX) {
223 		result->name = (char *)result->iname;
224 	} else if (len <= PATH_MAX) {
225 		const size_t size = offsetof(struct filename, iname[1]);
226 		struct filename *tmp;
227 
228 		tmp = kmalloc(size, GFP_KERNEL);
229 		if (unlikely(!tmp)) {
230 			__putname(result);
231 			return ERR_PTR(-ENOMEM);
232 		}
233 		tmp->name = (char *)result;
234 		result = tmp;
235 	} else {
236 		__putname(result);
237 		return ERR_PTR(-ENAMETOOLONG);
238 	}
239 	memcpy((char *)result->name, filename, len);
240 	result->uptr = NULL;
241 	result->aname = NULL;
242 	result->refcnt = 1;
243 	audit_getname(result);
244 
245 	return result;
246 }
247 
248 void putname(struct filename *name)
249 {
250 	BUG_ON(name->refcnt <= 0);
251 
252 	if (--name->refcnt > 0)
253 		return;
254 
255 	if (name->name != name->iname) {
256 		__putname(name->name);
257 		kfree(name);
258 	} else
259 		__putname(name);
260 }
261 
262 /**
263  * check_acl - perform ACL permission checking
264  * @mnt_userns:	user namespace of the mount the inode was found from
265  * @inode:	inode to check permissions on
266  * @mask:	right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
267  *
268  * This function performs the ACL permission checking. Since this function
269  * retrieve POSIX acls it needs to know whether it is called from a blocking or
270  * non-blocking context and thus cares about the MAY_NOT_BLOCK bit.
271  *
272  * If the inode has been found through an idmapped mount the user namespace of
273  * the vfsmount must be passed through @mnt_userns. This function will then take
274  * care to map the inode according to @mnt_userns before checking permissions.
275  * On non-idmapped mounts or if permission checking is to be performed on the
276  * raw inode simply passs init_user_ns.
277  */
278 static int check_acl(struct user_namespace *mnt_userns,
279 		     struct inode *inode, int mask)
280 {
281 #ifdef CONFIG_FS_POSIX_ACL
282 	struct posix_acl *acl;
283 
284 	if (mask & MAY_NOT_BLOCK) {
285 		acl = get_cached_acl_rcu(inode, ACL_TYPE_ACCESS);
286 	        if (!acl)
287 	                return -EAGAIN;
288 		/* no ->get_acl() calls in RCU mode... */
289 		if (is_uncached_acl(acl))
290 			return -ECHILD;
291 	        return posix_acl_permission(mnt_userns, inode, acl, mask);
292 	}
293 
294 	acl = get_acl(inode, ACL_TYPE_ACCESS);
295 	if (IS_ERR(acl))
296 		return PTR_ERR(acl);
297 	if (acl) {
298 	        int error = posix_acl_permission(mnt_userns, inode, acl, mask);
299 	        posix_acl_release(acl);
300 	        return error;
301 	}
302 #endif
303 
304 	return -EAGAIN;
305 }
306 
307 /**
308  * acl_permission_check - perform basic UNIX permission checking
309  * @mnt_userns:	user namespace of the mount the inode was found from
310  * @inode:	inode to check permissions on
311  * @mask:	right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
312  *
313  * This function performs the basic UNIX permission checking. Since this
314  * function may retrieve POSIX acls it needs to know whether it is called from a
315  * blocking or non-blocking context and thus cares about the MAY_NOT_BLOCK bit.
316  *
317  * If the inode has been found through an idmapped mount the user namespace of
318  * the vfsmount must be passed through @mnt_userns. This function will then take
319  * care to map the inode according to @mnt_userns before checking permissions.
320  * On non-idmapped mounts or if permission checking is to be performed on the
321  * raw inode simply passs init_user_ns.
322  */
323 static int acl_permission_check(struct user_namespace *mnt_userns,
324 				struct inode *inode, int mask)
325 {
326 	unsigned int mode = inode->i_mode;
327 	kuid_t i_uid;
328 
329 	/* Are we the owner? If so, ACL's don't matter */
330 	i_uid = i_uid_into_mnt(mnt_userns, inode);
331 	if (likely(uid_eq(current_fsuid(), i_uid))) {
332 		mask &= 7;
333 		mode >>= 6;
334 		return (mask & ~mode) ? -EACCES : 0;
335 	}
336 
337 	/* Do we have ACL's? */
338 	if (IS_POSIXACL(inode) && (mode & S_IRWXG)) {
339 		int error = check_acl(mnt_userns, inode, mask);
340 		if (error != -EAGAIN)
341 			return error;
342 	}
343 
344 	/* Only RWX matters for group/other mode bits */
345 	mask &= 7;
346 
347 	/*
348 	 * Are the group permissions different from
349 	 * the other permissions in the bits we care
350 	 * about? Need to check group ownership if so.
351 	 */
352 	if (mask & (mode ^ (mode >> 3))) {
353 		kgid_t kgid = i_gid_into_mnt(mnt_userns, inode);
354 		if (in_group_p(kgid))
355 			mode >>= 3;
356 	}
357 
358 	/* Bits in 'mode' clear that we require? */
359 	return (mask & ~mode) ? -EACCES : 0;
360 }
361 
362 /**
363  * generic_permission -  check for access rights on a Posix-like filesystem
364  * @mnt_userns:	user namespace of the mount the inode was found from
365  * @inode:	inode to check access rights for
366  * @mask:	right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC,
367  *		%MAY_NOT_BLOCK ...)
368  *
369  * Used to check for read/write/execute permissions on a file.
370  * We use "fsuid" for this, letting us set arbitrary permissions
371  * for filesystem access without changing the "normal" uids which
372  * are used for other things.
373  *
374  * generic_permission is rcu-walk aware. It returns -ECHILD in case an rcu-walk
375  * request cannot be satisfied (eg. requires blocking or too much complexity).
376  * It would then be called again in ref-walk mode.
377  *
378  * If the inode has been found through an idmapped mount the user namespace of
379  * the vfsmount must be passed through @mnt_userns. This function will then take
380  * care to map the inode according to @mnt_userns before checking permissions.
381  * On non-idmapped mounts or if permission checking is to be performed on the
382  * raw inode simply passs init_user_ns.
383  */
384 int generic_permission(struct user_namespace *mnt_userns, struct inode *inode,
385 		       int mask)
386 {
387 	int ret;
388 
389 	/*
390 	 * Do the basic permission checks.
391 	 */
392 	ret = acl_permission_check(mnt_userns, inode, mask);
393 	if (ret != -EACCES)
394 		return ret;
395 
396 	if (S_ISDIR(inode->i_mode)) {
397 		/* DACs are overridable for directories */
398 		if (!(mask & MAY_WRITE))
399 			if (capable_wrt_inode_uidgid(mnt_userns, inode,
400 						     CAP_DAC_READ_SEARCH))
401 				return 0;
402 		if (capable_wrt_inode_uidgid(mnt_userns, inode,
403 					     CAP_DAC_OVERRIDE))
404 			return 0;
405 		return -EACCES;
406 	}
407 
408 	/*
409 	 * Searching includes executable on directories, else just read.
410 	 */
411 	mask &= MAY_READ | MAY_WRITE | MAY_EXEC;
412 	if (mask == MAY_READ)
413 		if (capable_wrt_inode_uidgid(mnt_userns, inode,
414 					     CAP_DAC_READ_SEARCH))
415 			return 0;
416 	/*
417 	 * Read/write DACs are always overridable.
418 	 * Executable DACs are overridable when there is
419 	 * at least one exec bit set.
420 	 */
421 	if (!(mask & MAY_EXEC) || (inode->i_mode & S_IXUGO))
422 		if (capable_wrt_inode_uidgid(mnt_userns, inode,
423 					     CAP_DAC_OVERRIDE))
424 			return 0;
425 
426 	return -EACCES;
427 }
428 EXPORT_SYMBOL(generic_permission);
429 
430 /**
431  * do_inode_permission - UNIX permission checking
432  * @mnt_userns:	user namespace of the mount the inode was found from
433  * @inode:	inode to check permissions on
434  * @mask:	right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
435  *
436  * We _really_ want to just do "generic_permission()" without
437  * even looking at the inode->i_op values. So we keep a cache
438  * flag in inode->i_opflags, that says "this has not special
439  * permission function, use the fast case".
440  */
441 static inline int do_inode_permission(struct user_namespace *mnt_userns,
442 				      struct inode *inode, int mask)
443 {
444 	if (unlikely(!(inode->i_opflags & IOP_FASTPERM))) {
445 		if (likely(inode->i_op->permission))
446 			return inode->i_op->permission(mnt_userns, inode, mask);
447 
448 		/* This gets set once for the inode lifetime */
449 		spin_lock(&inode->i_lock);
450 		inode->i_opflags |= IOP_FASTPERM;
451 		spin_unlock(&inode->i_lock);
452 	}
453 	return generic_permission(mnt_userns, inode, mask);
454 }
455 
456 /**
457  * sb_permission - Check superblock-level permissions
458  * @sb: Superblock of inode to check permission on
459  * @inode: Inode to check permission on
460  * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
461  *
462  * Separate out file-system wide checks from inode-specific permission checks.
463  */
464 static int sb_permission(struct super_block *sb, struct inode *inode, int mask)
465 {
466 	if (unlikely(mask & MAY_WRITE)) {
467 		umode_t mode = inode->i_mode;
468 
469 		/* Nobody gets write access to a read-only fs. */
470 		if (sb_rdonly(sb) && (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode)))
471 			return -EROFS;
472 	}
473 	return 0;
474 }
475 
476 /**
477  * inode_permission - Check for access rights to a given inode
478  * @mnt_userns:	User namespace of the mount the inode was found from
479  * @inode:	Inode to check permission on
480  * @mask:	Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
481  *
482  * Check for read/write/execute permissions on an inode.  We use fs[ug]id for
483  * this, letting us set arbitrary permissions for filesystem access without
484  * changing the "normal" UIDs which are used for other things.
485  *
486  * When checking for MAY_APPEND, MAY_WRITE must also be set in @mask.
487  */
488 int inode_permission(struct user_namespace *mnt_userns,
489 		     struct inode *inode, int mask)
490 {
491 	int retval;
492 
493 	retval = sb_permission(inode->i_sb, inode, mask);
494 	if (retval)
495 		return retval;
496 
497 	if (unlikely(mask & MAY_WRITE)) {
498 		/*
499 		 * Nobody gets write access to an immutable file.
500 		 */
501 		if (IS_IMMUTABLE(inode))
502 			return -EPERM;
503 
504 		/*
505 		 * Updating mtime will likely cause i_uid and i_gid to be
506 		 * written back improperly if their true value is unknown
507 		 * to the vfs.
508 		 */
509 		if (HAS_UNMAPPED_ID(mnt_userns, inode))
510 			return -EACCES;
511 	}
512 
513 	retval = do_inode_permission(mnt_userns, inode, mask);
514 	if (retval)
515 		return retval;
516 
517 	retval = devcgroup_inode_permission(inode, mask);
518 	if (retval)
519 		return retval;
520 
521 	return security_inode_permission(inode, mask);
522 }
523 EXPORT_SYMBOL(inode_permission);
524 
525 /**
526  * path_get - get a reference to a path
527  * @path: path to get the reference to
528  *
529  * Given a path increment the reference count to the dentry and the vfsmount.
530  */
531 void path_get(const struct path *path)
532 {
533 	mntget(path->mnt);
534 	dget(path->dentry);
535 }
536 EXPORT_SYMBOL(path_get);
537 
538 /**
539  * path_put - put a reference to a path
540  * @path: path to put the reference to
541  *
542  * Given a path decrement the reference count to the dentry and the vfsmount.
543  */
544 void path_put(const struct path *path)
545 {
546 	dput(path->dentry);
547 	mntput(path->mnt);
548 }
549 EXPORT_SYMBOL(path_put);
550 
551 #define EMBEDDED_LEVELS 2
552 struct nameidata {
553 	struct path	path;
554 	struct qstr	last;
555 	struct path	root;
556 	struct inode	*inode; /* path.dentry.d_inode */
557 	unsigned int	flags;
558 	unsigned	seq, m_seq, r_seq;
559 	int		last_type;
560 	unsigned	depth;
561 	int		total_link_count;
562 	struct saved {
563 		struct path link;
564 		struct delayed_call done;
565 		const char *name;
566 		unsigned seq;
567 	} *stack, internal[EMBEDDED_LEVELS];
568 	struct filename	*name;
569 	struct nameidata *saved;
570 	unsigned	root_seq;
571 	int		dfd;
572 	kuid_t		dir_uid;
573 	umode_t		dir_mode;
574 } __randomize_layout;
575 
576 static void set_nameidata(struct nameidata *p, int dfd, struct filename *name)
577 {
578 	struct nameidata *old = current->nameidata;
579 	p->stack = p->internal;
580 	p->dfd = dfd;
581 	p->name = name;
582 	p->path.mnt = NULL;
583 	p->path.dentry = NULL;
584 	p->total_link_count = old ? old->total_link_count : 0;
585 	p->saved = old;
586 	current->nameidata = p;
587 }
588 
589 static void restore_nameidata(void)
590 {
591 	struct nameidata *now = current->nameidata, *old = now->saved;
592 
593 	current->nameidata = old;
594 	if (old)
595 		old->total_link_count = now->total_link_count;
596 	if (now->stack != now->internal)
597 		kfree(now->stack);
598 }
599 
600 static bool nd_alloc_stack(struct nameidata *nd)
601 {
602 	struct saved *p;
603 
604 	p= kmalloc_array(MAXSYMLINKS, sizeof(struct saved),
605 			 nd->flags & LOOKUP_RCU ? GFP_ATOMIC : GFP_KERNEL);
606 	if (unlikely(!p))
607 		return false;
608 	memcpy(p, nd->internal, sizeof(nd->internal));
609 	nd->stack = p;
610 	return true;
611 }
612 
613 /**
614  * path_connected - Verify that a dentry is below mnt.mnt_root
615  *
616  * Rename can sometimes move a file or directory outside of a bind
617  * mount, path_connected allows those cases to be detected.
618  */
619 static bool path_connected(struct vfsmount *mnt, struct dentry *dentry)
620 {
621 	struct super_block *sb = mnt->mnt_sb;
622 
623 	/* Bind mounts can have disconnected paths */
624 	if (mnt->mnt_root == sb->s_root)
625 		return true;
626 
627 	return is_subdir(dentry, mnt->mnt_root);
628 }
629 
630 static void drop_links(struct nameidata *nd)
631 {
632 	int i = nd->depth;
633 	while (i--) {
634 		struct saved *last = nd->stack + i;
635 		do_delayed_call(&last->done);
636 		clear_delayed_call(&last->done);
637 	}
638 }
639 
640 static void terminate_walk(struct nameidata *nd)
641 {
642 	drop_links(nd);
643 	if (!(nd->flags & LOOKUP_RCU)) {
644 		int i;
645 		path_put(&nd->path);
646 		for (i = 0; i < nd->depth; i++)
647 			path_put(&nd->stack[i].link);
648 		if (nd->flags & LOOKUP_ROOT_GRABBED) {
649 			path_put(&nd->root);
650 			nd->flags &= ~LOOKUP_ROOT_GRABBED;
651 		}
652 	} else {
653 		nd->flags &= ~LOOKUP_RCU;
654 		rcu_read_unlock();
655 	}
656 	nd->depth = 0;
657 	nd->path.mnt = NULL;
658 	nd->path.dentry = NULL;
659 }
660 
661 /* path_put is needed afterwards regardless of success or failure */
662 static bool __legitimize_path(struct path *path, unsigned seq, unsigned mseq)
663 {
664 	int res = __legitimize_mnt(path->mnt, mseq);
665 	if (unlikely(res)) {
666 		if (res > 0)
667 			path->mnt = NULL;
668 		path->dentry = NULL;
669 		return false;
670 	}
671 	if (unlikely(!lockref_get_not_dead(&path->dentry->d_lockref))) {
672 		path->dentry = NULL;
673 		return false;
674 	}
675 	return !read_seqcount_retry(&path->dentry->d_seq, seq);
676 }
677 
678 static inline bool legitimize_path(struct nameidata *nd,
679 			    struct path *path, unsigned seq)
680 {
681 	return __legitimize_path(path, seq, nd->m_seq);
682 }
683 
684 static bool legitimize_links(struct nameidata *nd)
685 {
686 	int i;
687 	if (unlikely(nd->flags & LOOKUP_CACHED)) {
688 		drop_links(nd);
689 		nd->depth = 0;
690 		return false;
691 	}
692 	for (i = 0; i < nd->depth; i++) {
693 		struct saved *last = nd->stack + i;
694 		if (unlikely(!legitimize_path(nd, &last->link, last->seq))) {
695 			drop_links(nd);
696 			nd->depth = i + 1;
697 			return false;
698 		}
699 	}
700 	return true;
701 }
702 
703 static bool legitimize_root(struct nameidata *nd)
704 {
705 	/*
706 	 * For scoped-lookups (where nd->root has been zeroed), we need to
707 	 * restart the whole lookup from scratch -- because set_root() is wrong
708 	 * for these lookups (nd->dfd is the root, not the filesystem root).
709 	 */
710 	if (!nd->root.mnt && (nd->flags & LOOKUP_IS_SCOPED))
711 		return false;
712 	/* Nothing to do if nd->root is zero or is managed by the VFS user. */
713 	if (!nd->root.mnt || (nd->flags & LOOKUP_ROOT))
714 		return true;
715 	nd->flags |= LOOKUP_ROOT_GRABBED;
716 	return legitimize_path(nd, &nd->root, nd->root_seq);
717 }
718 
719 /*
720  * Path walking has 2 modes, rcu-walk and ref-walk (see
721  * Documentation/filesystems/path-lookup.txt).  In situations when we can't
722  * continue in RCU mode, we attempt to drop out of rcu-walk mode and grab
723  * normal reference counts on dentries and vfsmounts to transition to ref-walk
724  * mode.  Refcounts are grabbed at the last known good point before rcu-walk
725  * got stuck, so ref-walk may continue from there. If this is not successful
726  * (eg. a seqcount has changed), then failure is returned and it's up to caller
727  * to restart the path walk from the beginning in ref-walk mode.
728  */
729 
730 /**
731  * try_to_unlazy - try to switch to ref-walk mode.
732  * @nd: nameidata pathwalk data
733  * Returns: true on success, false on failure
734  *
735  * try_to_unlazy attempts to legitimize the current nd->path and nd->root
736  * for ref-walk mode.
737  * Must be called from rcu-walk context.
738  * Nothing should touch nameidata between try_to_unlazy() failure and
739  * terminate_walk().
740  */
741 static bool try_to_unlazy(struct nameidata *nd)
742 {
743 	struct dentry *parent = nd->path.dentry;
744 
745 	BUG_ON(!(nd->flags & LOOKUP_RCU));
746 
747 	nd->flags &= ~LOOKUP_RCU;
748 	if (unlikely(!legitimize_links(nd)))
749 		goto out1;
750 	if (unlikely(!legitimize_path(nd, &nd->path, nd->seq)))
751 		goto out;
752 	if (unlikely(!legitimize_root(nd)))
753 		goto out;
754 	rcu_read_unlock();
755 	BUG_ON(nd->inode != parent->d_inode);
756 	return true;
757 
758 out1:
759 	nd->path.mnt = NULL;
760 	nd->path.dentry = NULL;
761 out:
762 	rcu_read_unlock();
763 	return false;
764 }
765 
766 /**
767  * try_to_unlazy_next - try to switch to ref-walk mode.
768  * @nd: nameidata pathwalk data
769  * @dentry: next dentry to step into
770  * @seq: seq number to check @dentry against
771  * Returns: true on success, false on failure
772  *
773  * Similar to to try_to_unlazy(), but here we have the next dentry already
774  * picked by rcu-walk and want to legitimize that in addition to the current
775  * nd->path and nd->root for ref-walk mode.  Must be called from rcu-walk context.
776  * Nothing should touch nameidata between try_to_unlazy_next() failure and
777  * terminate_walk().
778  */
779 static bool try_to_unlazy_next(struct nameidata *nd, struct dentry *dentry, unsigned seq)
780 {
781 	BUG_ON(!(nd->flags & LOOKUP_RCU));
782 
783 	nd->flags &= ~LOOKUP_RCU;
784 	if (unlikely(!legitimize_links(nd)))
785 		goto out2;
786 	if (unlikely(!legitimize_mnt(nd->path.mnt, nd->m_seq)))
787 		goto out2;
788 	if (unlikely(!lockref_get_not_dead(&nd->path.dentry->d_lockref)))
789 		goto out1;
790 
791 	/*
792 	 * We need to move both the parent and the dentry from the RCU domain
793 	 * to be properly refcounted. And the sequence number in the dentry
794 	 * validates *both* dentry counters, since we checked the sequence
795 	 * number of the parent after we got the child sequence number. So we
796 	 * know the parent must still be valid if the child sequence number is
797 	 */
798 	if (unlikely(!lockref_get_not_dead(&dentry->d_lockref)))
799 		goto out;
800 	if (unlikely(read_seqcount_retry(&dentry->d_seq, seq)))
801 		goto out_dput;
802 	/*
803 	 * Sequence counts matched. Now make sure that the root is
804 	 * still valid and get it if required.
805 	 */
806 	if (unlikely(!legitimize_root(nd)))
807 		goto out_dput;
808 	rcu_read_unlock();
809 	return true;
810 
811 out2:
812 	nd->path.mnt = NULL;
813 out1:
814 	nd->path.dentry = NULL;
815 out:
816 	rcu_read_unlock();
817 	return false;
818 out_dput:
819 	rcu_read_unlock();
820 	dput(dentry);
821 	return false;
822 }
823 
824 static inline int d_revalidate(struct dentry *dentry, unsigned int flags)
825 {
826 	if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE))
827 		return dentry->d_op->d_revalidate(dentry, flags);
828 	else
829 		return 1;
830 }
831 
832 /**
833  * complete_walk - successful completion of path walk
834  * @nd:  pointer nameidata
835  *
836  * If we had been in RCU mode, drop out of it and legitimize nd->path.
837  * Revalidate the final result, unless we'd already done that during
838  * the path walk or the filesystem doesn't ask for it.  Return 0 on
839  * success, -error on failure.  In case of failure caller does not
840  * need to drop nd->path.
841  */
842 static int complete_walk(struct nameidata *nd)
843 {
844 	struct dentry *dentry = nd->path.dentry;
845 	int status;
846 
847 	if (nd->flags & LOOKUP_RCU) {
848 		/*
849 		 * We don't want to zero nd->root for scoped-lookups or
850 		 * externally-managed nd->root.
851 		 */
852 		if (!(nd->flags & (LOOKUP_ROOT | LOOKUP_IS_SCOPED)))
853 			nd->root.mnt = NULL;
854 		nd->flags &= ~LOOKUP_CACHED;
855 		if (!try_to_unlazy(nd))
856 			return -ECHILD;
857 	}
858 
859 	if (unlikely(nd->flags & LOOKUP_IS_SCOPED)) {
860 		/*
861 		 * While the guarantee of LOOKUP_IS_SCOPED is (roughly) "don't
862 		 * ever step outside the root during lookup" and should already
863 		 * be guaranteed by the rest of namei, we want to avoid a namei
864 		 * BUG resulting in userspace being given a path that was not
865 		 * scoped within the root at some point during the lookup.
866 		 *
867 		 * So, do a final sanity-check to make sure that in the
868 		 * worst-case scenario (a complete bypass of LOOKUP_IS_SCOPED)
869 		 * we won't silently return an fd completely outside of the
870 		 * requested root to userspace.
871 		 *
872 		 * Userspace could move the path outside the root after this
873 		 * check, but as discussed elsewhere this is not a concern (the
874 		 * resolved file was inside the root at some point).
875 		 */
876 		if (!path_is_under(&nd->path, &nd->root))
877 			return -EXDEV;
878 	}
879 
880 	if (likely(!(nd->flags & LOOKUP_JUMPED)))
881 		return 0;
882 
883 	if (likely(!(dentry->d_flags & DCACHE_OP_WEAK_REVALIDATE)))
884 		return 0;
885 
886 	status = dentry->d_op->d_weak_revalidate(dentry, nd->flags);
887 	if (status > 0)
888 		return 0;
889 
890 	if (!status)
891 		status = -ESTALE;
892 
893 	return status;
894 }
895 
896 static int set_root(struct nameidata *nd)
897 {
898 	struct fs_struct *fs = current->fs;
899 
900 	/*
901 	 * Jumping to the real root in a scoped-lookup is a BUG in namei, but we
902 	 * still have to ensure it doesn't happen because it will cause a breakout
903 	 * from the dirfd.
904 	 */
905 	if (WARN_ON(nd->flags & LOOKUP_IS_SCOPED))
906 		return -ENOTRECOVERABLE;
907 
908 	if (nd->flags & LOOKUP_RCU) {
909 		unsigned seq;
910 
911 		do {
912 			seq = read_seqcount_begin(&fs->seq);
913 			nd->root = fs->root;
914 			nd->root_seq = __read_seqcount_begin(&nd->root.dentry->d_seq);
915 		} while (read_seqcount_retry(&fs->seq, seq));
916 	} else {
917 		get_fs_root(fs, &nd->root);
918 		nd->flags |= LOOKUP_ROOT_GRABBED;
919 	}
920 	return 0;
921 }
922 
923 static int nd_jump_root(struct nameidata *nd)
924 {
925 	if (unlikely(nd->flags & LOOKUP_BENEATH))
926 		return -EXDEV;
927 	if (unlikely(nd->flags & LOOKUP_NO_XDEV)) {
928 		/* Absolute path arguments to path_init() are allowed. */
929 		if (nd->path.mnt != NULL && nd->path.mnt != nd->root.mnt)
930 			return -EXDEV;
931 	}
932 	if (!nd->root.mnt) {
933 		int error = set_root(nd);
934 		if (error)
935 			return error;
936 	}
937 	if (nd->flags & LOOKUP_RCU) {
938 		struct dentry *d;
939 		nd->path = nd->root;
940 		d = nd->path.dentry;
941 		nd->inode = d->d_inode;
942 		nd->seq = nd->root_seq;
943 		if (unlikely(read_seqcount_retry(&d->d_seq, nd->seq)))
944 			return -ECHILD;
945 	} else {
946 		path_put(&nd->path);
947 		nd->path = nd->root;
948 		path_get(&nd->path);
949 		nd->inode = nd->path.dentry->d_inode;
950 	}
951 	nd->flags |= LOOKUP_JUMPED;
952 	return 0;
953 }
954 
955 /*
956  * Helper to directly jump to a known parsed path from ->get_link,
957  * caller must have taken a reference to path beforehand.
958  */
959 int nd_jump_link(struct path *path)
960 {
961 	int error = -ELOOP;
962 	struct nameidata *nd = current->nameidata;
963 
964 	if (unlikely(nd->flags & LOOKUP_NO_MAGICLINKS))
965 		goto err;
966 
967 	error = -EXDEV;
968 	if (unlikely(nd->flags & LOOKUP_NO_XDEV)) {
969 		if (nd->path.mnt != path->mnt)
970 			goto err;
971 	}
972 	/* Not currently safe for scoped-lookups. */
973 	if (unlikely(nd->flags & LOOKUP_IS_SCOPED))
974 		goto err;
975 
976 	path_put(&nd->path);
977 	nd->path = *path;
978 	nd->inode = nd->path.dentry->d_inode;
979 	nd->flags |= LOOKUP_JUMPED;
980 	return 0;
981 
982 err:
983 	path_put(path);
984 	return error;
985 }
986 
987 static inline void put_link(struct nameidata *nd)
988 {
989 	struct saved *last = nd->stack + --nd->depth;
990 	do_delayed_call(&last->done);
991 	if (!(nd->flags & LOOKUP_RCU))
992 		path_put(&last->link);
993 }
994 
995 int sysctl_protected_symlinks __read_mostly = 0;
996 int sysctl_protected_hardlinks __read_mostly = 0;
997 int sysctl_protected_fifos __read_mostly;
998 int sysctl_protected_regular __read_mostly;
999 
1000 /**
1001  * may_follow_link - Check symlink following for unsafe situations
1002  * @nd: nameidata pathwalk data
1003  *
1004  * In the case of the sysctl_protected_symlinks sysctl being enabled,
1005  * CAP_DAC_OVERRIDE needs to be specifically ignored if the symlink is
1006  * in a sticky world-writable directory. This is to protect privileged
1007  * processes from failing races against path names that may change out
1008  * from under them by way of other users creating malicious symlinks.
1009  * It will permit symlinks to be followed only when outside a sticky
1010  * world-writable directory, or when the uid of the symlink and follower
1011  * match, or when the directory owner matches the symlink's owner.
1012  *
1013  * Returns 0 if following the symlink is allowed, -ve on error.
1014  */
1015 static inline int may_follow_link(struct nameidata *nd, const struct inode *inode)
1016 {
1017 	struct user_namespace *mnt_userns;
1018 	kuid_t i_uid;
1019 
1020 	if (!sysctl_protected_symlinks)
1021 		return 0;
1022 
1023 	mnt_userns = mnt_user_ns(nd->path.mnt);
1024 	i_uid = i_uid_into_mnt(mnt_userns, inode);
1025 	/* Allowed if owner and follower match. */
1026 	if (uid_eq(current_cred()->fsuid, i_uid))
1027 		return 0;
1028 
1029 	/* Allowed if parent directory not sticky and world-writable. */
1030 	if ((nd->dir_mode & (S_ISVTX|S_IWOTH)) != (S_ISVTX|S_IWOTH))
1031 		return 0;
1032 
1033 	/* Allowed if parent directory and link owner match. */
1034 	if (uid_valid(nd->dir_uid) && uid_eq(nd->dir_uid, i_uid))
1035 		return 0;
1036 
1037 	if (nd->flags & LOOKUP_RCU)
1038 		return -ECHILD;
1039 
1040 	audit_inode(nd->name, nd->stack[0].link.dentry, 0);
1041 	audit_log_path_denied(AUDIT_ANOM_LINK, "follow_link");
1042 	return -EACCES;
1043 }
1044 
1045 /**
1046  * safe_hardlink_source - Check for safe hardlink conditions
1047  * @mnt_userns:	user namespace of the mount the inode was found from
1048  * @inode: the source inode to hardlink from
1049  *
1050  * Return false if at least one of the following conditions:
1051  *    - inode is not a regular file
1052  *    - inode is setuid
1053  *    - inode is setgid and group-exec
1054  *    - access failure for read and write
1055  *
1056  * Otherwise returns true.
1057  */
1058 static bool safe_hardlink_source(struct user_namespace *mnt_userns,
1059 				 struct inode *inode)
1060 {
1061 	umode_t mode = inode->i_mode;
1062 
1063 	/* Special files should not get pinned to the filesystem. */
1064 	if (!S_ISREG(mode))
1065 		return false;
1066 
1067 	/* Setuid files should not get pinned to the filesystem. */
1068 	if (mode & S_ISUID)
1069 		return false;
1070 
1071 	/* Executable setgid files should not get pinned to the filesystem. */
1072 	if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP))
1073 		return false;
1074 
1075 	/* Hardlinking to unreadable or unwritable sources is dangerous. */
1076 	if (inode_permission(mnt_userns, inode, MAY_READ | MAY_WRITE))
1077 		return false;
1078 
1079 	return true;
1080 }
1081 
1082 /**
1083  * may_linkat - Check permissions for creating a hardlink
1084  * @mnt_userns:	user namespace of the mount the inode was found from
1085  * @link: the source to hardlink from
1086  *
1087  * Block hardlink when all of:
1088  *  - sysctl_protected_hardlinks enabled
1089  *  - fsuid does not match inode
1090  *  - hardlink source is unsafe (see safe_hardlink_source() above)
1091  *  - not CAP_FOWNER in a namespace with the inode owner uid mapped
1092  *
1093  * If the inode has been found through an idmapped mount the user namespace of
1094  * the vfsmount must be passed through @mnt_userns. This function will then take
1095  * care to map the inode according to @mnt_userns before checking permissions.
1096  * On non-idmapped mounts or if permission checking is to be performed on the
1097  * raw inode simply passs init_user_ns.
1098  *
1099  * Returns 0 if successful, -ve on error.
1100  */
1101 int may_linkat(struct user_namespace *mnt_userns, struct path *link)
1102 {
1103 	struct inode *inode = link->dentry->d_inode;
1104 
1105 	/* Inode writeback is not safe when the uid or gid are invalid. */
1106 	if (!uid_valid(i_uid_into_mnt(mnt_userns, inode)) ||
1107 	    !gid_valid(i_gid_into_mnt(mnt_userns, inode)))
1108 		return -EOVERFLOW;
1109 
1110 	if (!sysctl_protected_hardlinks)
1111 		return 0;
1112 
1113 	/* Source inode owner (or CAP_FOWNER) can hardlink all they like,
1114 	 * otherwise, it must be a safe source.
1115 	 */
1116 	if (safe_hardlink_source(mnt_userns, inode) ||
1117 	    inode_owner_or_capable(mnt_userns, inode))
1118 		return 0;
1119 
1120 	audit_log_path_denied(AUDIT_ANOM_LINK, "linkat");
1121 	return -EPERM;
1122 }
1123 
1124 /**
1125  * may_create_in_sticky - Check whether an O_CREAT open in a sticky directory
1126  *			  should be allowed, or not, on files that already
1127  *			  exist.
1128  * @mnt_userns:	user namespace of the mount the inode was found from
1129  * @nd: nameidata pathwalk data
1130  * @inode: the inode of the file to open
1131  *
1132  * Block an O_CREAT open of a FIFO (or a regular file) when:
1133  *   - sysctl_protected_fifos (or sysctl_protected_regular) is enabled
1134  *   - the file already exists
1135  *   - we are in a sticky directory
1136  *   - we don't own the file
1137  *   - the owner of the directory doesn't own the file
1138  *   - the directory is world writable
1139  * If the sysctl_protected_fifos (or sysctl_protected_regular) is set to 2
1140  * the directory doesn't have to be world writable: being group writable will
1141  * be enough.
1142  *
1143  * If the inode has been found through an idmapped mount the user namespace of
1144  * the vfsmount must be passed through @mnt_userns. This function will then take
1145  * care to map the inode according to @mnt_userns before checking permissions.
1146  * On non-idmapped mounts or if permission checking is to be performed on the
1147  * raw inode simply passs init_user_ns.
1148  *
1149  * Returns 0 if the open is allowed, -ve on error.
1150  */
1151 static int may_create_in_sticky(struct user_namespace *mnt_userns,
1152 				struct nameidata *nd, struct inode *const inode)
1153 {
1154 	umode_t dir_mode = nd->dir_mode;
1155 	kuid_t dir_uid = nd->dir_uid;
1156 
1157 	if ((!sysctl_protected_fifos && S_ISFIFO(inode->i_mode)) ||
1158 	    (!sysctl_protected_regular && S_ISREG(inode->i_mode)) ||
1159 	    likely(!(dir_mode & S_ISVTX)) ||
1160 	    uid_eq(i_uid_into_mnt(mnt_userns, inode), dir_uid) ||
1161 	    uid_eq(current_fsuid(), i_uid_into_mnt(mnt_userns, inode)))
1162 		return 0;
1163 
1164 	if (likely(dir_mode & 0002) ||
1165 	    (dir_mode & 0020 &&
1166 	     ((sysctl_protected_fifos >= 2 && S_ISFIFO(inode->i_mode)) ||
1167 	      (sysctl_protected_regular >= 2 && S_ISREG(inode->i_mode))))) {
1168 		const char *operation = S_ISFIFO(inode->i_mode) ?
1169 					"sticky_create_fifo" :
1170 					"sticky_create_regular";
1171 		audit_log_path_denied(AUDIT_ANOM_CREAT, operation);
1172 		return -EACCES;
1173 	}
1174 	return 0;
1175 }
1176 
1177 /*
1178  * follow_up - Find the mountpoint of path's vfsmount
1179  *
1180  * Given a path, find the mountpoint of its source file system.
1181  * Replace @path with the path of the mountpoint in the parent mount.
1182  * Up is towards /.
1183  *
1184  * Return 1 if we went up a level and 0 if we were already at the
1185  * root.
1186  */
1187 int follow_up(struct path *path)
1188 {
1189 	struct mount *mnt = real_mount(path->mnt);
1190 	struct mount *parent;
1191 	struct dentry *mountpoint;
1192 
1193 	read_seqlock_excl(&mount_lock);
1194 	parent = mnt->mnt_parent;
1195 	if (parent == mnt) {
1196 		read_sequnlock_excl(&mount_lock);
1197 		return 0;
1198 	}
1199 	mntget(&parent->mnt);
1200 	mountpoint = dget(mnt->mnt_mountpoint);
1201 	read_sequnlock_excl(&mount_lock);
1202 	dput(path->dentry);
1203 	path->dentry = mountpoint;
1204 	mntput(path->mnt);
1205 	path->mnt = &parent->mnt;
1206 	return 1;
1207 }
1208 EXPORT_SYMBOL(follow_up);
1209 
1210 static bool choose_mountpoint_rcu(struct mount *m, const struct path *root,
1211 				  struct path *path, unsigned *seqp)
1212 {
1213 	while (mnt_has_parent(m)) {
1214 		struct dentry *mountpoint = m->mnt_mountpoint;
1215 
1216 		m = m->mnt_parent;
1217 		if (unlikely(root->dentry == mountpoint &&
1218 			     root->mnt == &m->mnt))
1219 			break;
1220 		if (mountpoint != m->mnt.mnt_root) {
1221 			path->mnt = &m->mnt;
1222 			path->dentry = mountpoint;
1223 			*seqp = read_seqcount_begin(&mountpoint->d_seq);
1224 			return true;
1225 		}
1226 	}
1227 	return false;
1228 }
1229 
1230 static bool choose_mountpoint(struct mount *m, const struct path *root,
1231 			      struct path *path)
1232 {
1233 	bool found;
1234 
1235 	rcu_read_lock();
1236 	while (1) {
1237 		unsigned seq, mseq = read_seqbegin(&mount_lock);
1238 
1239 		found = choose_mountpoint_rcu(m, root, path, &seq);
1240 		if (unlikely(!found)) {
1241 			if (!read_seqretry(&mount_lock, mseq))
1242 				break;
1243 		} else {
1244 			if (likely(__legitimize_path(path, seq, mseq)))
1245 				break;
1246 			rcu_read_unlock();
1247 			path_put(path);
1248 			rcu_read_lock();
1249 		}
1250 	}
1251 	rcu_read_unlock();
1252 	return found;
1253 }
1254 
1255 /*
1256  * Perform an automount
1257  * - return -EISDIR to tell follow_managed() to stop and return the path we
1258  *   were called with.
1259  */
1260 static int follow_automount(struct path *path, int *count, unsigned lookup_flags)
1261 {
1262 	struct dentry *dentry = path->dentry;
1263 
1264 	/* We don't want to mount if someone's just doing a stat -
1265 	 * unless they're stat'ing a directory and appended a '/' to
1266 	 * the name.
1267 	 *
1268 	 * We do, however, want to mount if someone wants to open or
1269 	 * create a file of any type under the mountpoint, wants to
1270 	 * traverse through the mountpoint or wants to open the
1271 	 * mounted directory.  Also, autofs may mark negative dentries
1272 	 * as being automount points.  These will need the attentions
1273 	 * of the daemon to instantiate them before they can be used.
1274 	 */
1275 	if (!(lookup_flags & (LOOKUP_PARENT | LOOKUP_DIRECTORY |
1276 			   LOOKUP_OPEN | LOOKUP_CREATE | LOOKUP_AUTOMOUNT)) &&
1277 	    dentry->d_inode)
1278 		return -EISDIR;
1279 
1280 	if (count && (*count)++ >= MAXSYMLINKS)
1281 		return -ELOOP;
1282 
1283 	return finish_automount(dentry->d_op->d_automount(path), path);
1284 }
1285 
1286 /*
1287  * mount traversal - out-of-line part.  One note on ->d_flags accesses -
1288  * dentries are pinned but not locked here, so negative dentry can go
1289  * positive right under us.  Use of smp_load_acquire() provides a barrier
1290  * sufficient for ->d_inode and ->d_flags consistency.
1291  */
1292 static int __traverse_mounts(struct path *path, unsigned flags, bool *jumped,
1293 			     int *count, unsigned lookup_flags)
1294 {
1295 	struct vfsmount *mnt = path->mnt;
1296 	bool need_mntput = false;
1297 	int ret = 0;
1298 
1299 	while (flags & DCACHE_MANAGED_DENTRY) {
1300 		/* Allow the filesystem to manage the transit without i_mutex
1301 		 * being held. */
1302 		if (flags & DCACHE_MANAGE_TRANSIT) {
1303 			ret = path->dentry->d_op->d_manage(path, false);
1304 			flags = smp_load_acquire(&path->dentry->d_flags);
1305 			if (ret < 0)
1306 				break;
1307 		}
1308 
1309 		if (flags & DCACHE_MOUNTED) {	// something's mounted on it..
1310 			struct vfsmount *mounted = lookup_mnt(path);
1311 			if (mounted) {		// ... in our namespace
1312 				dput(path->dentry);
1313 				if (need_mntput)
1314 					mntput(path->mnt);
1315 				path->mnt = mounted;
1316 				path->dentry = dget(mounted->mnt_root);
1317 				// here we know it's positive
1318 				flags = path->dentry->d_flags;
1319 				need_mntput = true;
1320 				continue;
1321 			}
1322 		}
1323 
1324 		if (!(flags & DCACHE_NEED_AUTOMOUNT))
1325 			break;
1326 
1327 		// uncovered automount point
1328 		ret = follow_automount(path, count, lookup_flags);
1329 		flags = smp_load_acquire(&path->dentry->d_flags);
1330 		if (ret < 0)
1331 			break;
1332 	}
1333 
1334 	if (ret == -EISDIR)
1335 		ret = 0;
1336 	// possible if you race with several mount --move
1337 	if (need_mntput && path->mnt == mnt)
1338 		mntput(path->mnt);
1339 	if (!ret && unlikely(d_flags_negative(flags)))
1340 		ret = -ENOENT;
1341 	*jumped = need_mntput;
1342 	return ret;
1343 }
1344 
1345 static inline int traverse_mounts(struct path *path, bool *jumped,
1346 				  int *count, unsigned lookup_flags)
1347 {
1348 	unsigned flags = smp_load_acquire(&path->dentry->d_flags);
1349 
1350 	/* fastpath */
1351 	if (likely(!(flags & DCACHE_MANAGED_DENTRY))) {
1352 		*jumped = false;
1353 		if (unlikely(d_flags_negative(flags)))
1354 			return -ENOENT;
1355 		return 0;
1356 	}
1357 	return __traverse_mounts(path, flags, jumped, count, lookup_flags);
1358 }
1359 
1360 int follow_down_one(struct path *path)
1361 {
1362 	struct vfsmount *mounted;
1363 
1364 	mounted = lookup_mnt(path);
1365 	if (mounted) {
1366 		dput(path->dentry);
1367 		mntput(path->mnt);
1368 		path->mnt = mounted;
1369 		path->dentry = dget(mounted->mnt_root);
1370 		return 1;
1371 	}
1372 	return 0;
1373 }
1374 EXPORT_SYMBOL(follow_down_one);
1375 
1376 /*
1377  * Follow down to the covering mount currently visible to userspace.  At each
1378  * point, the filesystem owning that dentry may be queried as to whether the
1379  * caller is permitted to proceed or not.
1380  */
1381 int follow_down(struct path *path)
1382 {
1383 	struct vfsmount *mnt = path->mnt;
1384 	bool jumped;
1385 	int ret = traverse_mounts(path, &jumped, NULL, 0);
1386 
1387 	if (path->mnt != mnt)
1388 		mntput(mnt);
1389 	return ret;
1390 }
1391 EXPORT_SYMBOL(follow_down);
1392 
1393 /*
1394  * Try to skip to top of mountpoint pile in rcuwalk mode.  Fail if
1395  * we meet a managed dentry that would need blocking.
1396  */
1397 static bool __follow_mount_rcu(struct nameidata *nd, struct path *path,
1398 			       struct inode **inode, unsigned *seqp)
1399 {
1400 	struct dentry *dentry = path->dentry;
1401 	unsigned int flags = dentry->d_flags;
1402 
1403 	if (likely(!(flags & DCACHE_MANAGED_DENTRY)))
1404 		return true;
1405 
1406 	if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1407 		return false;
1408 
1409 	for (;;) {
1410 		/*
1411 		 * Don't forget we might have a non-mountpoint managed dentry
1412 		 * that wants to block transit.
1413 		 */
1414 		if (unlikely(flags & DCACHE_MANAGE_TRANSIT)) {
1415 			int res = dentry->d_op->d_manage(path, true);
1416 			if (res)
1417 				return res == -EISDIR;
1418 			flags = dentry->d_flags;
1419 		}
1420 
1421 		if (flags & DCACHE_MOUNTED) {
1422 			struct mount *mounted = __lookup_mnt(path->mnt, dentry);
1423 			if (mounted) {
1424 				path->mnt = &mounted->mnt;
1425 				dentry = path->dentry = mounted->mnt.mnt_root;
1426 				nd->flags |= LOOKUP_JUMPED;
1427 				*seqp = read_seqcount_begin(&dentry->d_seq);
1428 				*inode = dentry->d_inode;
1429 				/*
1430 				 * We don't need to re-check ->d_seq after this
1431 				 * ->d_inode read - there will be an RCU delay
1432 				 * between mount hash removal and ->mnt_root
1433 				 * becoming unpinned.
1434 				 */
1435 				flags = dentry->d_flags;
1436 				continue;
1437 			}
1438 			if (read_seqretry(&mount_lock, nd->m_seq))
1439 				return false;
1440 		}
1441 		return !(flags & DCACHE_NEED_AUTOMOUNT);
1442 	}
1443 }
1444 
1445 static inline int handle_mounts(struct nameidata *nd, struct dentry *dentry,
1446 			  struct path *path, struct inode **inode,
1447 			  unsigned int *seqp)
1448 {
1449 	bool jumped;
1450 	int ret;
1451 
1452 	path->mnt = nd->path.mnt;
1453 	path->dentry = dentry;
1454 	if (nd->flags & LOOKUP_RCU) {
1455 		unsigned int seq = *seqp;
1456 		if (unlikely(!*inode))
1457 			return -ENOENT;
1458 		if (likely(__follow_mount_rcu(nd, path, inode, seqp)))
1459 			return 0;
1460 		if (!try_to_unlazy_next(nd, dentry, seq))
1461 			return -ECHILD;
1462 		// *path might've been clobbered by __follow_mount_rcu()
1463 		path->mnt = nd->path.mnt;
1464 		path->dentry = dentry;
1465 	}
1466 	ret = traverse_mounts(path, &jumped, &nd->total_link_count, nd->flags);
1467 	if (jumped) {
1468 		if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1469 			ret = -EXDEV;
1470 		else
1471 			nd->flags |= LOOKUP_JUMPED;
1472 	}
1473 	if (unlikely(ret)) {
1474 		dput(path->dentry);
1475 		if (path->mnt != nd->path.mnt)
1476 			mntput(path->mnt);
1477 	} else {
1478 		*inode = d_backing_inode(path->dentry);
1479 		*seqp = 0; /* out of RCU mode, so the value doesn't matter */
1480 	}
1481 	return ret;
1482 }
1483 
1484 /*
1485  * This looks up the name in dcache and possibly revalidates the found dentry.
1486  * NULL is returned if the dentry does not exist in the cache.
1487  */
1488 static struct dentry *lookup_dcache(const struct qstr *name,
1489 				    struct dentry *dir,
1490 				    unsigned int flags)
1491 {
1492 	struct dentry *dentry = d_lookup(dir, name);
1493 	if (dentry) {
1494 		int error = d_revalidate(dentry, flags);
1495 		if (unlikely(error <= 0)) {
1496 			if (!error)
1497 				d_invalidate(dentry);
1498 			dput(dentry);
1499 			return ERR_PTR(error);
1500 		}
1501 	}
1502 	return dentry;
1503 }
1504 
1505 /*
1506  * Parent directory has inode locked exclusive.  This is one
1507  * and only case when ->lookup() gets called on non in-lookup
1508  * dentries - as the matter of fact, this only gets called
1509  * when directory is guaranteed to have no in-lookup children
1510  * at all.
1511  */
1512 static struct dentry *__lookup_hash(const struct qstr *name,
1513 		struct dentry *base, unsigned int flags)
1514 {
1515 	struct dentry *dentry = lookup_dcache(name, base, flags);
1516 	struct dentry *old;
1517 	struct inode *dir = base->d_inode;
1518 
1519 	if (dentry)
1520 		return dentry;
1521 
1522 	/* Don't create child dentry for a dead directory. */
1523 	if (unlikely(IS_DEADDIR(dir)))
1524 		return ERR_PTR(-ENOENT);
1525 
1526 	dentry = d_alloc(base, name);
1527 	if (unlikely(!dentry))
1528 		return ERR_PTR(-ENOMEM);
1529 
1530 	old = dir->i_op->lookup(dir, dentry, flags);
1531 	if (unlikely(old)) {
1532 		dput(dentry);
1533 		dentry = old;
1534 	}
1535 	return dentry;
1536 }
1537 
1538 static struct dentry *lookup_fast(struct nameidata *nd,
1539 				  struct inode **inode,
1540 			          unsigned *seqp)
1541 {
1542 	struct dentry *dentry, *parent = nd->path.dentry;
1543 	int status = 1;
1544 
1545 	/*
1546 	 * Rename seqlock is not required here because in the off chance
1547 	 * of a false negative due to a concurrent rename, the caller is
1548 	 * going to fall back to non-racy lookup.
1549 	 */
1550 	if (nd->flags & LOOKUP_RCU) {
1551 		unsigned seq;
1552 		dentry = __d_lookup_rcu(parent, &nd->last, &seq);
1553 		if (unlikely(!dentry)) {
1554 			if (!try_to_unlazy(nd))
1555 				return ERR_PTR(-ECHILD);
1556 			return NULL;
1557 		}
1558 
1559 		/*
1560 		 * This sequence count validates that the inode matches
1561 		 * the dentry name information from lookup.
1562 		 */
1563 		*inode = d_backing_inode(dentry);
1564 		if (unlikely(read_seqcount_retry(&dentry->d_seq, seq)))
1565 			return ERR_PTR(-ECHILD);
1566 
1567 		/*
1568 		 * This sequence count validates that the parent had no
1569 		 * changes while we did the lookup of the dentry above.
1570 		 *
1571 		 * The memory barrier in read_seqcount_begin of child is
1572 		 *  enough, we can use __read_seqcount_retry here.
1573 		 */
1574 		if (unlikely(__read_seqcount_retry(&parent->d_seq, nd->seq)))
1575 			return ERR_PTR(-ECHILD);
1576 
1577 		*seqp = seq;
1578 		status = d_revalidate(dentry, nd->flags);
1579 		if (likely(status > 0))
1580 			return dentry;
1581 		if (!try_to_unlazy_next(nd, dentry, seq))
1582 			return ERR_PTR(-ECHILD);
1583 		if (status == -ECHILD)
1584 			/* we'd been told to redo it in non-rcu mode */
1585 			status = d_revalidate(dentry, nd->flags);
1586 	} else {
1587 		dentry = __d_lookup(parent, &nd->last);
1588 		if (unlikely(!dentry))
1589 			return NULL;
1590 		status = d_revalidate(dentry, nd->flags);
1591 	}
1592 	if (unlikely(status <= 0)) {
1593 		if (!status)
1594 			d_invalidate(dentry);
1595 		dput(dentry);
1596 		return ERR_PTR(status);
1597 	}
1598 	return dentry;
1599 }
1600 
1601 /* Fast lookup failed, do it the slow way */
1602 static struct dentry *__lookup_slow(const struct qstr *name,
1603 				    struct dentry *dir,
1604 				    unsigned int flags)
1605 {
1606 	struct dentry *dentry, *old;
1607 	struct inode *inode = dir->d_inode;
1608 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
1609 
1610 	/* Don't go there if it's already dead */
1611 	if (unlikely(IS_DEADDIR(inode)))
1612 		return ERR_PTR(-ENOENT);
1613 again:
1614 	dentry = d_alloc_parallel(dir, name, &wq);
1615 	if (IS_ERR(dentry))
1616 		return dentry;
1617 	if (unlikely(!d_in_lookup(dentry))) {
1618 		int error = d_revalidate(dentry, flags);
1619 		if (unlikely(error <= 0)) {
1620 			if (!error) {
1621 				d_invalidate(dentry);
1622 				dput(dentry);
1623 				goto again;
1624 			}
1625 			dput(dentry);
1626 			dentry = ERR_PTR(error);
1627 		}
1628 	} else {
1629 		old = inode->i_op->lookup(inode, dentry, flags);
1630 		d_lookup_done(dentry);
1631 		if (unlikely(old)) {
1632 			dput(dentry);
1633 			dentry = old;
1634 		}
1635 	}
1636 	return dentry;
1637 }
1638 
1639 static struct dentry *lookup_slow(const struct qstr *name,
1640 				  struct dentry *dir,
1641 				  unsigned int flags)
1642 {
1643 	struct inode *inode = dir->d_inode;
1644 	struct dentry *res;
1645 	inode_lock_shared(inode);
1646 	res = __lookup_slow(name, dir, flags);
1647 	inode_unlock_shared(inode);
1648 	return res;
1649 }
1650 
1651 static inline int may_lookup(struct user_namespace *mnt_userns,
1652 			     struct nameidata *nd)
1653 {
1654 	if (nd->flags & LOOKUP_RCU) {
1655 		int err = inode_permission(mnt_userns, nd->inode, MAY_EXEC|MAY_NOT_BLOCK);
1656 		if (err != -ECHILD || !try_to_unlazy(nd))
1657 			return err;
1658 	}
1659 	return inode_permission(mnt_userns, nd->inode, MAY_EXEC);
1660 }
1661 
1662 static int reserve_stack(struct nameidata *nd, struct path *link, unsigned seq)
1663 {
1664 	if (unlikely(nd->total_link_count++ >= MAXSYMLINKS))
1665 		return -ELOOP;
1666 
1667 	if (likely(nd->depth != EMBEDDED_LEVELS))
1668 		return 0;
1669 	if (likely(nd->stack != nd->internal))
1670 		return 0;
1671 	if (likely(nd_alloc_stack(nd)))
1672 		return 0;
1673 
1674 	if (nd->flags & LOOKUP_RCU) {
1675 		// we need to grab link before we do unlazy.  And we can't skip
1676 		// unlazy even if we fail to grab the link - cleanup needs it
1677 		bool grabbed_link = legitimize_path(nd, link, seq);
1678 
1679 		if (!try_to_unlazy(nd) != 0 || !grabbed_link)
1680 			return -ECHILD;
1681 
1682 		if (nd_alloc_stack(nd))
1683 			return 0;
1684 	}
1685 	return -ENOMEM;
1686 }
1687 
1688 enum {WALK_TRAILING = 1, WALK_MORE = 2, WALK_NOFOLLOW = 4};
1689 
1690 static const char *pick_link(struct nameidata *nd, struct path *link,
1691 		     struct inode *inode, unsigned seq, int flags)
1692 {
1693 	struct saved *last;
1694 	const char *res;
1695 	int error = reserve_stack(nd, link, seq);
1696 
1697 	if (unlikely(error)) {
1698 		if (!(nd->flags & LOOKUP_RCU))
1699 			path_put(link);
1700 		return ERR_PTR(error);
1701 	}
1702 	last = nd->stack + nd->depth++;
1703 	last->link = *link;
1704 	clear_delayed_call(&last->done);
1705 	last->seq = seq;
1706 
1707 	if (flags & WALK_TRAILING) {
1708 		error = may_follow_link(nd, inode);
1709 		if (unlikely(error))
1710 			return ERR_PTR(error);
1711 	}
1712 
1713 	if (unlikely(nd->flags & LOOKUP_NO_SYMLINKS) ||
1714 			unlikely(link->mnt->mnt_flags & MNT_NOSYMFOLLOW))
1715 		return ERR_PTR(-ELOOP);
1716 
1717 	if (!(nd->flags & LOOKUP_RCU)) {
1718 		touch_atime(&last->link);
1719 		cond_resched();
1720 	} else if (atime_needs_update(&last->link, inode)) {
1721 		if (!try_to_unlazy(nd))
1722 			return ERR_PTR(-ECHILD);
1723 		touch_atime(&last->link);
1724 	}
1725 
1726 	error = security_inode_follow_link(link->dentry, inode,
1727 					   nd->flags & LOOKUP_RCU);
1728 	if (unlikely(error))
1729 		return ERR_PTR(error);
1730 
1731 	res = READ_ONCE(inode->i_link);
1732 	if (!res) {
1733 		const char * (*get)(struct dentry *, struct inode *,
1734 				struct delayed_call *);
1735 		get = inode->i_op->get_link;
1736 		if (nd->flags & LOOKUP_RCU) {
1737 			res = get(NULL, inode, &last->done);
1738 			if (res == ERR_PTR(-ECHILD) && try_to_unlazy(nd))
1739 				res = get(link->dentry, inode, &last->done);
1740 		} else {
1741 			res = get(link->dentry, inode, &last->done);
1742 		}
1743 		if (!res)
1744 			goto all_done;
1745 		if (IS_ERR(res))
1746 			return res;
1747 	}
1748 	if (*res == '/') {
1749 		error = nd_jump_root(nd);
1750 		if (unlikely(error))
1751 			return ERR_PTR(error);
1752 		while (unlikely(*++res == '/'))
1753 			;
1754 	}
1755 	if (*res)
1756 		return res;
1757 all_done: // pure jump
1758 	put_link(nd);
1759 	return NULL;
1760 }
1761 
1762 /*
1763  * Do we need to follow links? We _really_ want to be able
1764  * to do this check without having to look at inode->i_op,
1765  * so we keep a cache of "no, this doesn't need follow_link"
1766  * for the common case.
1767  */
1768 static const char *step_into(struct nameidata *nd, int flags,
1769 		     struct dentry *dentry, struct inode *inode, unsigned seq)
1770 {
1771 	struct path path;
1772 	int err = handle_mounts(nd, dentry, &path, &inode, &seq);
1773 
1774 	if (err < 0)
1775 		return ERR_PTR(err);
1776 	if (likely(!d_is_symlink(path.dentry)) ||
1777 	   ((flags & WALK_TRAILING) && !(nd->flags & LOOKUP_FOLLOW)) ||
1778 	   (flags & WALK_NOFOLLOW)) {
1779 		/* not a symlink or should not follow */
1780 		if (!(nd->flags & LOOKUP_RCU)) {
1781 			dput(nd->path.dentry);
1782 			if (nd->path.mnt != path.mnt)
1783 				mntput(nd->path.mnt);
1784 		}
1785 		nd->path = path;
1786 		nd->inode = inode;
1787 		nd->seq = seq;
1788 		return NULL;
1789 	}
1790 	if (nd->flags & LOOKUP_RCU) {
1791 		/* make sure that d_is_symlink above matches inode */
1792 		if (read_seqcount_retry(&path.dentry->d_seq, seq))
1793 			return ERR_PTR(-ECHILD);
1794 	} else {
1795 		if (path.mnt == nd->path.mnt)
1796 			mntget(path.mnt);
1797 	}
1798 	return pick_link(nd, &path, inode, seq, flags);
1799 }
1800 
1801 static struct dentry *follow_dotdot_rcu(struct nameidata *nd,
1802 					struct inode **inodep,
1803 					unsigned *seqp)
1804 {
1805 	struct dentry *parent, *old;
1806 
1807 	if (path_equal(&nd->path, &nd->root))
1808 		goto in_root;
1809 	if (unlikely(nd->path.dentry == nd->path.mnt->mnt_root)) {
1810 		struct path path;
1811 		unsigned seq;
1812 		if (!choose_mountpoint_rcu(real_mount(nd->path.mnt),
1813 					   &nd->root, &path, &seq))
1814 			goto in_root;
1815 		if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1816 			return ERR_PTR(-ECHILD);
1817 		nd->path = path;
1818 		nd->inode = path.dentry->d_inode;
1819 		nd->seq = seq;
1820 		if (unlikely(read_seqretry(&mount_lock, nd->m_seq)))
1821 			return ERR_PTR(-ECHILD);
1822 		/* we know that mountpoint was pinned */
1823 	}
1824 	old = nd->path.dentry;
1825 	parent = old->d_parent;
1826 	*inodep = parent->d_inode;
1827 	*seqp = read_seqcount_begin(&parent->d_seq);
1828 	if (unlikely(read_seqcount_retry(&old->d_seq, nd->seq)))
1829 		return ERR_PTR(-ECHILD);
1830 	if (unlikely(!path_connected(nd->path.mnt, parent)))
1831 		return ERR_PTR(-ECHILD);
1832 	return parent;
1833 in_root:
1834 	if (unlikely(read_seqretry(&mount_lock, nd->m_seq)))
1835 		return ERR_PTR(-ECHILD);
1836 	if (unlikely(nd->flags & LOOKUP_BENEATH))
1837 		return ERR_PTR(-ECHILD);
1838 	return NULL;
1839 }
1840 
1841 static struct dentry *follow_dotdot(struct nameidata *nd,
1842 				 struct inode **inodep,
1843 				 unsigned *seqp)
1844 {
1845 	struct dentry *parent;
1846 
1847 	if (path_equal(&nd->path, &nd->root))
1848 		goto in_root;
1849 	if (unlikely(nd->path.dentry == nd->path.mnt->mnt_root)) {
1850 		struct path path;
1851 
1852 		if (!choose_mountpoint(real_mount(nd->path.mnt),
1853 				       &nd->root, &path))
1854 			goto in_root;
1855 		path_put(&nd->path);
1856 		nd->path = path;
1857 		nd->inode = path.dentry->d_inode;
1858 		if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1859 			return ERR_PTR(-EXDEV);
1860 	}
1861 	/* rare case of legitimate dget_parent()... */
1862 	parent = dget_parent(nd->path.dentry);
1863 	if (unlikely(!path_connected(nd->path.mnt, parent))) {
1864 		dput(parent);
1865 		return ERR_PTR(-ENOENT);
1866 	}
1867 	*seqp = 0;
1868 	*inodep = parent->d_inode;
1869 	return parent;
1870 
1871 in_root:
1872 	if (unlikely(nd->flags & LOOKUP_BENEATH))
1873 		return ERR_PTR(-EXDEV);
1874 	dget(nd->path.dentry);
1875 	return NULL;
1876 }
1877 
1878 static const char *handle_dots(struct nameidata *nd, int type)
1879 {
1880 	if (type == LAST_DOTDOT) {
1881 		const char *error = NULL;
1882 		struct dentry *parent;
1883 		struct inode *inode;
1884 		unsigned seq;
1885 
1886 		if (!nd->root.mnt) {
1887 			error = ERR_PTR(set_root(nd));
1888 			if (error)
1889 				return error;
1890 		}
1891 		if (nd->flags & LOOKUP_RCU)
1892 			parent = follow_dotdot_rcu(nd, &inode, &seq);
1893 		else
1894 			parent = follow_dotdot(nd, &inode, &seq);
1895 		if (IS_ERR(parent))
1896 			return ERR_CAST(parent);
1897 		if (unlikely(!parent))
1898 			error = step_into(nd, WALK_NOFOLLOW,
1899 					 nd->path.dentry, nd->inode, nd->seq);
1900 		else
1901 			error = step_into(nd, WALK_NOFOLLOW,
1902 					 parent, inode, seq);
1903 		if (unlikely(error))
1904 			return error;
1905 
1906 		if (unlikely(nd->flags & LOOKUP_IS_SCOPED)) {
1907 			/*
1908 			 * If there was a racing rename or mount along our
1909 			 * path, then we can't be sure that ".." hasn't jumped
1910 			 * above nd->root (and so userspace should retry or use
1911 			 * some fallback).
1912 			 */
1913 			smp_rmb();
1914 			if (unlikely(__read_seqcount_retry(&mount_lock.seqcount, nd->m_seq)))
1915 				return ERR_PTR(-EAGAIN);
1916 			if (unlikely(__read_seqcount_retry(&rename_lock.seqcount, nd->r_seq)))
1917 				return ERR_PTR(-EAGAIN);
1918 		}
1919 	}
1920 	return NULL;
1921 }
1922 
1923 static const char *walk_component(struct nameidata *nd, int flags)
1924 {
1925 	struct dentry *dentry;
1926 	struct inode *inode;
1927 	unsigned seq;
1928 	/*
1929 	 * "." and ".." are special - ".." especially so because it has
1930 	 * to be able to know about the current root directory and
1931 	 * parent relationships.
1932 	 */
1933 	if (unlikely(nd->last_type != LAST_NORM)) {
1934 		if (!(flags & WALK_MORE) && nd->depth)
1935 			put_link(nd);
1936 		return handle_dots(nd, nd->last_type);
1937 	}
1938 	dentry = lookup_fast(nd, &inode, &seq);
1939 	if (IS_ERR(dentry))
1940 		return ERR_CAST(dentry);
1941 	if (unlikely(!dentry)) {
1942 		dentry = lookup_slow(&nd->last, nd->path.dentry, nd->flags);
1943 		if (IS_ERR(dentry))
1944 			return ERR_CAST(dentry);
1945 	}
1946 	if (!(flags & WALK_MORE) && nd->depth)
1947 		put_link(nd);
1948 	return step_into(nd, flags, dentry, inode, seq);
1949 }
1950 
1951 /*
1952  * We can do the critical dentry name comparison and hashing
1953  * operations one word at a time, but we are limited to:
1954  *
1955  * - Architectures with fast unaligned word accesses. We could
1956  *   do a "get_unaligned()" if this helps and is sufficiently
1957  *   fast.
1958  *
1959  * - non-CONFIG_DEBUG_PAGEALLOC configurations (so that we
1960  *   do not trap on the (extremely unlikely) case of a page
1961  *   crossing operation.
1962  *
1963  * - Furthermore, we need an efficient 64-bit compile for the
1964  *   64-bit case in order to generate the "number of bytes in
1965  *   the final mask". Again, that could be replaced with a
1966  *   efficient population count instruction or similar.
1967  */
1968 #ifdef CONFIG_DCACHE_WORD_ACCESS
1969 
1970 #include <asm/word-at-a-time.h>
1971 
1972 #ifdef HASH_MIX
1973 
1974 /* Architecture provides HASH_MIX and fold_hash() in <asm/hash.h> */
1975 
1976 #elif defined(CONFIG_64BIT)
1977 /*
1978  * Register pressure in the mixing function is an issue, particularly
1979  * on 32-bit x86, but almost any function requires one state value and
1980  * one temporary.  Instead, use a function designed for two state values
1981  * and no temporaries.
1982  *
1983  * This function cannot create a collision in only two iterations, so
1984  * we have two iterations to achieve avalanche.  In those two iterations,
1985  * we have six layers of mixing, which is enough to spread one bit's
1986  * influence out to 2^6 = 64 state bits.
1987  *
1988  * Rotate constants are scored by considering either 64 one-bit input
1989  * deltas or 64*63/2 = 2016 two-bit input deltas, and finding the
1990  * probability of that delta causing a change to each of the 128 output
1991  * bits, using a sample of random initial states.
1992  *
1993  * The Shannon entropy of the computed probabilities is then summed
1994  * to produce a score.  Ideally, any input change has a 50% chance of
1995  * toggling any given output bit.
1996  *
1997  * Mixing scores (in bits) for (12,45):
1998  * Input delta: 1-bit      2-bit
1999  * 1 round:     713.3    42542.6
2000  * 2 rounds:   2753.7   140389.8
2001  * 3 rounds:   5954.1   233458.2
2002  * 4 rounds:   7862.6   256672.2
2003  * Perfect:    8192     258048
2004  *            (64*128) (64*63/2 * 128)
2005  */
2006 #define HASH_MIX(x, y, a)	\
2007 	(	x ^= (a),	\
2008 	y ^= x,	x = rol64(x,12),\
2009 	x += y,	y = rol64(y,45),\
2010 	y *= 9			)
2011 
2012 /*
2013  * Fold two longs into one 32-bit hash value.  This must be fast, but
2014  * latency isn't quite as critical, as there is a fair bit of additional
2015  * work done before the hash value is used.
2016  */
2017 static inline unsigned int fold_hash(unsigned long x, unsigned long y)
2018 {
2019 	y ^= x * GOLDEN_RATIO_64;
2020 	y *= GOLDEN_RATIO_64;
2021 	return y >> 32;
2022 }
2023 
2024 #else	/* 32-bit case */
2025 
2026 /*
2027  * Mixing scores (in bits) for (7,20):
2028  * Input delta: 1-bit      2-bit
2029  * 1 round:     330.3     9201.6
2030  * 2 rounds:   1246.4    25475.4
2031  * 3 rounds:   1907.1    31295.1
2032  * 4 rounds:   2042.3    31718.6
2033  * Perfect:    2048      31744
2034  *            (32*64)   (32*31/2 * 64)
2035  */
2036 #define HASH_MIX(x, y, a)	\
2037 	(	x ^= (a),	\
2038 	y ^= x,	x = rol32(x, 7),\
2039 	x += y,	y = rol32(y,20),\
2040 	y *= 9			)
2041 
2042 static inline unsigned int fold_hash(unsigned long x, unsigned long y)
2043 {
2044 	/* Use arch-optimized multiply if one exists */
2045 	return __hash_32(y ^ __hash_32(x));
2046 }
2047 
2048 #endif
2049 
2050 /*
2051  * Return the hash of a string of known length.  This is carfully
2052  * designed to match hash_name(), which is the more critical function.
2053  * In particular, we must end by hashing a final word containing 0..7
2054  * payload bytes, to match the way that hash_name() iterates until it
2055  * finds the delimiter after the name.
2056  */
2057 unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
2058 {
2059 	unsigned long a, x = 0, y = (unsigned long)salt;
2060 
2061 	for (;;) {
2062 		if (!len)
2063 			goto done;
2064 		a = load_unaligned_zeropad(name);
2065 		if (len < sizeof(unsigned long))
2066 			break;
2067 		HASH_MIX(x, y, a);
2068 		name += sizeof(unsigned long);
2069 		len -= sizeof(unsigned long);
2070 	}
2071 	x ^= a & bytemask_from_count(len);
2072 done:
2073 	return fold_hash(x, y);
2074 }
2075 EXPORT_SYMBOL(full_name_hash);
2076 
2077 /* Return the "hash_len" (hash and length) of a null-terminated string */
2078 u64 hashlen_string(const void *salt, const char *name)
2079 {
2080 	unsigned long a = 0, x = 0, y = (unsigned long)salt;
2081 	unsigned long adata, mask, len;
2082 	const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2083 
2084 	len = 0;
2085 	goto inside;
2086 
2087 	do {
2088 		HASH_MIX(x, y, a);
2089 		len += sizeof(unsigned long);
2090 inside:
2091 		a = load_unaligned_zeropad(name+len);
2092 	} while (!has_zero(a, &adata, &constants));
2093 
2094 	adata = prep_zero_mask(a, adata, &constants);
2095 	mask = create_zero_mask(adata);
2096 	x ^= a & zero_bytemask(mask);
2097 
2098 	return hashlen_create(fold_hash(x, y), len + find_zero(mask));
2099 }
2100 EXPORT_SYMBOL(hashlen_string);
2101 
2102 /*
2103  * Calculate the length and hash of the path component, and
2104  * return the "hash_len" as the result.
2105  */
2106 static inline u64 hash_name(const void *salt, const char *name)
2107 {
2108 	unsigned long a = 0, b, x = 0, y = (unsigned long)salt;
2109 	unsigned long adata, bdata, mask, len;
2110 	const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2111 
2112 	len = 0;
2113 	goto inside;
2114 
2115 	do {
2116 		HASH_MIX(x, y, a);
2117 		len += sizeof(unsigned long);
2118 inside:
2119 		a = load_unaligned_zeropad(name+len);
2120 		b = a ^ REPEAT_BYTE('/');
2121 	} while (!(has_zero(a, &adata, &constants) | has_zero(b, &bdata, &constants)));
2122 
2123 	adata = prep_zero_mask(a, adata, &constants);
2124 	bdata = prep_zero_mask(b, bdata, &constants);
2125 	mask = create_zero_mask(adata | bdata);
2126 	x ^= a & zero_bytemask(mask);
2127 
2128 	return hashlen_create(fold_hash(x, y), len + find_zero(mask));
2129 }
2130 
2131 #else	/* !CONFIG_DCACHE_WORD_ACCESS: Slow, byte-at-a-time version */
2132 
2133 /* Return the hash of a string of known length */
2134 unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
2135 {
2136 	unsigned long hash = init_name_hash(salt);
2137 	while (len--)
2138 		hash = partial_name_hash((unsigned char)*name++, hash);
2139 	return end_name_hash(hash);
2140 }
2141 EXPORT_SYMBOL(full_name_hash);
2142 
2143 /* Return the "hash_len" (hash and length) of a null-terminated string */
2144 u64 hashlen_string(const void *salt, const char *name)
2145 {
2146 	unsigned long hash = init_name_hash(salt);
2147 	unsigned long len = 0, c;
2148 
2149 	c = (unsigned char)*name;
2150 	while (c) {
2151 		len++;
2152 		hash = partial_name_hash(c, hash);
2153 		c = (unsigned char)name[len];
2154 	}
2155 	return hashlen_create(end_name_hash(hash), len);
2156 }
2157 EXPORT_SYMBOL(hashlen_string);
2158 
2159 /*
2160  * We know there's a real path component here of at least
2161  * one character.
2162  */
2163 static inline u64 hash_name(const void *salt, const char *name)
2164 {
2165 	unsigned long hash = init_name_hash(salt);
2166 	unsigned long len = 0, c;
2167 
2168 	c = (unsigned char)*name;
2169 	do {
2170 		len++;
2171 		hash = partial_name_hash(c, hash);
2172 		c = (unsigned char)name[len];
2173 	} while (c && c != '/');
2174 	return hashlen_create(end_name_hash(hash), len);
2175 }
2176 
2177 #endif
2178 
2179 /*
2180  * Name resolution.
2181  * This is the basic name resolution function, turning a pathname into
2182  * the final dentry. We expect 'base' to be positive and a directory.
2183  *
2184  * Returns 0 and nd will have valid dentry and mnt on success.
2185  * Returns error and drops reference to input namei data on failure.
2186  */
2187 static int link_path_walk(const char *name, struct nameidata *nd)
2188 {
2189 	int depth = 0; // depth <= nd->depth
2190 	int err;
2191 
2192 	nd->last_type = LAST_ROOT;
2193 	nd->flags |= LOOKUP_PARENT;
2194 	if (IS_ERR(name))
2195 		return PTR_ERR(name);
2196 	while (*name=='/')
2197 		name++;
2198 	if (!*name) {
2199 		nd->dir_mode = 0; // short-circuit the 'hardening' idiocy
2200 		return 0;
2201 	}
2202 
2203 	/* At this point we know we have a real path component. */
2204 	for(;;) {
2205 		struct user_namespace *mnt_userns;
2206 		const char *link;
2207 		u64 hash_len;
2208 		int type;
2209 
2210 		mnt_userns = mnt_user_ns(nd->path.mnt);
2211 		err = may_lookup(mnt_userns, nd);
2212 		if (err)
2213 			return err;
2214 
2215 		hash_len = hash_name(nd->path.dentry, name);
2216 
2217 		type = LAST_NORM;
2218 		if (name[0] == '.') switch (hashlen_len(hash_len)) {
2219 			case 2:
2220 				if (name[1] == '.') {
2221 					type = LAST_DOTDOT;
2222 					nd->flags |= LOOKUP_JUMPED;
2223 				}
2224 				break;
2225 			case 1:
2226 				type = LAST_DOT;
2227 		}
2228 		if (likely(type == LAST_NORM)) {
2229 			struct dentry *parent = nd->path.dentry;
2230 			nd->flags &= ~LOOKUP_JUMPED;
2231 			if (unlikely(parent->d_flags & DCACHE_OP_HASH)) {
2232 				struct qstr this = { { .hash_len = hash_len }, .name = name };
2233 				err = parent->d_op->d_hash(parent, &this);
2234 				if (err < 0)
2235 					return err;
2236 				hash_len = this.hash_len;
2237 				name = this.name;
2238 			}
2239 		}
2240 
2241 		nd->last.hash_len = hash_len;
2242 		nd->last.name = name;
2243 		nd->last_type = type;
2244 
2245 		name += hashlen_len(hash_len);
2246 		if (!*name)
2247 			goto OK;
2248 		/*
2249 		 * If it wasn't NUL, we know it was '/'. Skip that
2250 		 * slash, and continue until no more slashes.
2251 		 */
2252 		do {
2253 			name++;
2254 		} while (unlikely(*name == '/'));
2255 		if (unlikely(!*name)) {
2256 OK:
2257 			/* pathname or trailing symlink, done */
2258 			if (!depth) {
2259 				nd->dir_uid = i_uid_into_mnt(mnt_userns, nd->inode);
2260 				nd->dir_mode = nd->inode->i_mode;
2261 				nd->flags &= ~LOOKUP_PARENT;
2262 				return 0;
2263 			}
2264 			/* last component of nested symlink */
2265 			name = nd->stack[--depth].name;
2266 			link = walk_component(nd, 0);
2267 		} else {
2268 			/* not the last component */
2269 			link = walk_component(nd, WALK_MORE);
2270 		}
2271 		if (unlikely(link)) {
2272 			if (IS_ERR(link))
2273 				return PTR_ERR(link);
2274 			/* a symlink to follow */
2275 			nd->stack[depth++].name = name;
2276 			name = link;
2277 			continue;
2278 		}
2279 		if (unlikely(!d_can_lookup(nd->path.dentry))) {
2280 			if (nd->flags & LOOKUP_RCU) {
2281 				if (!try_to_unlazy(nd))
2282 					return -ECHILD;
2283 			}
2284 			return -ENOTDIR;
2285 		}
2286 	}
2287 }
2288 
2289 /* must be paired with terminate_walk() */
2290 static const char *path_init(struct nameidata *nd, unsigned flags)
2291 {
2292 	int error;
2293 	const char *s = nd->name->name;
2294 
2295 	/* LOOKUP_CACHED requires RCU, ask caller to retry */
2296 	if ((flags & (LOOKUP_RCU | LOOKUP_CACHED)) == LOOKUP_CACHED)
2297 		return ERR_PTR(-EAGAIN);
2298 
2299 	if (!*s)
2300 		flags &= ~LOOKUP_RCU;
2301 	if (flags & LOOKUP_RCU)
2302 		rcu_read_lock();
2303 
2304 	nd->flags = flags | LOOKUP_JUMPED;
2305 	nd->depth = 0;
2306 
2307 	nd->m_seq = __read_seqcount_begin(&mount_lock.seqcount);
2308 	nd->r_seq = __read_seqcount_begin(&rename_lock.seqcount);
2309 	smp_rmb();
2310 
2311 	if (flags & LOOKUP_ROOT) {
2312 		struct dentry *root = nd->root.dentry;
2313 		struct inode *inode = root->d_inode;
2314 		if (*s && unlikely(!d_can_lookup(root)))
2315 			return ERR_PTR(-ENOTDIR);
2316 		nd->path = nd->root;
2317 		nd->inode = inode;
2318 		if (flags & LOOKUP_RCU) {
2319 			nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
2320 			nd->root_seq = nd->seq;
2321 		} else {
2322 			path_get(&nd->path);
2323 		}
2324 		return s;
2325 	}
2326 
2327 	nd->root.mnt = NULL;
2328 
2329 	/* Absolute pathname -- fetch the root (LOOKUP_IN_ROOT uses nd->dfd). */
2330 	if (*s == '/' && !(flags & LOOKUP_IN_ROOT)) {
2331 		error = nd_jump_root(nd);
2332 		if (unlikely(error))
2333 			return ERR_PTR(error);
2334 		return s;
2335 	}
2336 
2337 	/* Relative pathname -- get the starting-point it is relative to. */
2338 	if (nd->dfd == AT_FDCWD) {
2339 		if (flags & LOOKUP_RCU) {
2340 			struct fs_struct *fs = current->fs;
2341 			unsigned seq;
2342 
2343 			do {
2344 				seq = read_seqcount_begin(&fs->seq);
2345 				nd->path = fs->pwd;
2346 				nd->inode = nd->path.dentry->d_inode;
2347 				nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
2348 			} while (read_seqcount_retry(&fs->seq, seq));
2349 		} else {
2350 			get_fs_pwd(current->fs, &nd->path);
2351 			nd->inode = nd->path.dentry->d_inode;
2352 		}
2353 	} else {
2354 		/* Caller must check execute permissions on the starting path component */
2355 		struct fd f = fdget_raw(nd->dfd);
2356 		struct dentry *dentry;
2357 
2358 		if (!f.file)
2359 			return ERR_PTR(-EBADF);
2360 
2361 		dentry = f.file->f_path.dentry;
2362 
2363 		if (*s && unlikely(!d_can_lookup(dentry))) {
2364 			fdput(f);
2365 			return ERR_PTR(-ENOTDIR);
2366 		}
2367 
2368 		nd->path = f.file->f_path;
2369 		if (flags & LOOKUP_RCU) {
2370 			nd->inode = nd->path.dentry->d_inode;
2371 			nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
2372 		} else {
2373 			path_get(&nd->path);
2374 			nd->inode = nd->path.dentry->d_inode;
2375 		}
2376 		fdput(f);
2377 	}
2378 
2379 	/* For scoped-lookups we need to set the root to the dirfd as well. */
2380 	if (flags & LOOKUP_IS_SCOPED) {
2381 		nd->root = nd->path;
2382 		if (flags & LOOKUP_RCU) {
2383 			nd->root_seq = nd->seq;
2384 		} else {
2385 			path_get(&nd->root);
2386 			nd->flags |= LOOKUP_ROOT_GRABBED;
2387 		}
2388 	}
2389 	return s;
2390 }
2391 
2392 static inline const char *lookup_last(struct nameidata *nd)
2393 {
2394 	if (nd->last_type == LAST_NORM && nd->last.name[nd->last.len])
2395 		nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
2396 
2397 	return walk_component(nd, WALK_TRAILING);
2398 }
2399 
2400 static int handle_lookup_down(struct nameidata *nd)
2401 {
2402 	if (!(nd->flags & LOOKUP_RCU))
2403 		dget(nd->path.dentry);
2404 	return PTR_ERR(step_into(nd, WALK_NOFOLLOW,
2405 			nd->path.dentry, nd->inode, nd->seq));
2406 }
2407 
2408 /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
2409 static int path_lookupat(struct nameidata *nd, unsigned flags, struct path *path)
2410 {
2411 	const char *s = path_init(nd, flags);
2412 	int err;
2413 
2414 	if (unlikely(flags & LOOKUP_DOWN) && !IS_ERR(s)) {
2415 		err = handle_lookup_down(nd);
2416 		if (unlikely(err < 0))
2417 			s = ERR_PTR(err);
2418 	}
2419 
2420 	while (!(err = link_path_walk(s, nd)) &&
2421 	       (s = lookup_last(nd)) != NULL)
2422 		;
2423 	if (!err && unlikely(nd->flags & LOOKUP_MOUNTPOINT)) {
2424 		err = handle_lookup_down(nd);
2425 		nd->flags &= ~LOOKUP_JUMPED; // no d_weak_revalidate(), please...
2426 	}
2427 	if (!err)
2428 		err = complete_walk(nd);
2429 
2430 	if (!err && nd->flags & LOOKUP_DIRECTORY)
2431 		if (!d_can_lookup(nd->path.dentry))
2432 			err = -ENOTDIR;
2433 	if (!err) {
2434 		*path = nd->path;
2435 		nd->path.mnt = NULL;
2436 		nd->path.dentry = NULL;
2437 	}
2438 	terminate_walk(nd);
2439 	return err;
2440 }
2441 
2442 int filename_lookup(int dfd, struct filename *name, unsigned flags,
2443 		    struct path *path, struct path *root)
2444 {
2445 	int retval;
2446 	struct nameidata nd;
2447 	if (IS_ERR(name))
2448 		return PTR_ERR(name);
2449 	if (unlikely(root)) {
2450 		nd.root = *root;
2451 		flags |= LOOKUP_ROOT;
2452 	}
2453 	set_nameidata(&nd, dfd, name);
2454 	retval = path_lookupat(&nd, flags | LOOKUP_RCU, path);
2455 	if (unlikely(retval == -ECHILD))
2456 		retval = path_lookupat(&nd, flags, path);
2457 	if (unlikely(retval == -ESTALE))
2458 		retval = path_lookupat(&nd, flags | LOOKUP_REVAL, path);
2459 
2460 	if (likely(!retval))
2461 		audit_inode(name, path->dentry,
2462 			    flags & LOOKUP_MOUNTPOINT ? AUDIT_INODE_NOEVAL : 0);
2463 	restore_nameidata();
2464 	putname(name);
2465 	return retval;
2466 }
2467 
2468 /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
2469 static int path_parentat(struct nameidata *nd, unsigned flags,
2470 				struct path *parent)
2471 {
2472 	const char *s = path_init(nd, flags);
2473 	int err = link_path_walk(s, nd);
2474 	if (!err)
2475 		err = complete_walk(nd);
2476 	if (!err) {
2477 		*parent = nd->path;
2478 		nd->path.mnt = NULL;
2479 		nd->path.dentry = NULL;
2480 	}
2481 	terminate_walk(nd);
2482 	return err;
2483 }
2484 
2485 static struct filename *filename_parentat(int dfd, struct filename *name,
2486 				unsigned int flags, struct path *parent,
2487 				struct qstr *last, int *type)
2488 {
2489 	int retval;
2490 	struct nameidata nd;
2491 
2492 	if (IS_ERR(name))
2493 		return name;
2494 	set_nameidata(&nd, dfd, name);
2495 	retval = path_parentat(&nd, flags | LOOKUP_RCU, parent);
2496 	if (unlikely(retval == -ECHILD))
2497 		retval = path_parentat(&nd, flags, parent);
2498 	if (unlikely(retval == -ESTALE))
2499 		retval = path_parentat(&nd, flags | LOOKUP_REVAL, parent);
2500 	if (likely(!retval)) {
2501 		*last = nd.last;
2502 		*type = nd.last_type;
2503 		audit_inode(name, parent->dentry, AUDIT_INODE_PARENT);
2504 	} else {
2505 		putname(name);
2506 		name = ERR_PTR(retval);
2507 	}
2508 	restore_nameidata();
2509 	return name;
2510 }
2511 
2512 /* does lookup, returns the object with parent locked */
2513 struct dentry *kern_path_locked(const char *name, struct path *path)
2514 {
2515 	struct filename *filename;
2516 	struct dentry *d;
2517 	struct qstr last;
2518 	int type;
2519 
2520 	filename = filename_parentat(AT_FDCWD, getname_kernel(name), 0, path,
2521 				    &last, &type);
2522 	if (IS_ERR(filename))
2523 		return ERR_CAST(filename);
2524 	if (unlikely(type != LAST_NORM)) {
2525 		path_put(path);
2526 		putname(filename);
2527 		return ERR_PTR(-EINVAL);
2528 	}
2529 	inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
2530 	d = __lookup_hash(&last, path->dentry, 0);
2531 	if (IS_ERR(d)) {
2532 		inode_unlock(path->dentry->d_inode);
2533 		path_put(path);
2534 	}
2535 	putname(filename);
2536 	return d;
2537 }
2538 
2539 int kern_path(const char *name, unsigned int flags, struct path *path)
2540 {
2541 	return filename_lookup(AT_FDCWD, getname_kernel(name),
2542 			       flags, path, NULL);
2543 }
2544 EXPORT_SYMBOL(kern_path);
2545 
2546 /**
2547  * vfs_path_lookup - lookup a file path relative to a dentry-vfsmount pair
2548  * @dentry:  pointer to dentry of the base directory
2549  * @mnt: pointer to vfs mount of the base directory
2550  * @name: pointer to file name
2551  * @flags: lookup flags
2552  * @path: pointer to struct path to fill
2553  */
2554 int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt,
2555 		    const char *name, unsigned int flags,
2556 		    struct path *path)
2557 {
2558 	struct path root = {.mnt = mnt, .dentry = dentry};
2559 	/* the first argument of filename_lookup() is ignored with root */
2560 	return filename_lookup(AT_FDCWD, getname_kernel(name),
2561 			       flags , path, &root);
2562 }
2563 EXPORT_SYMBOL(vfs_path_lookup);
2564 
2565 static int lookup_one_len_common(const char *name, struct dentry *base,
2566 				 int len, struct qstr *this)
2567 {
2568 	this->name = name;
2569 	this->len = len;
2570 	this->hash = full_name_hash(base, name, len);
2571 	if (!len)
2572 		return -EACCES;
2573 
2574 	if (unlikely(name[0] == '.')) {
2575 		if (len < 2 || (len == 2 && name[1] == '.'))
2576 			return -EACCES;
2577 	}
2578 
2579 	while (len--) {
2580 		unsigned int c = *(const unsigned char *)name++;
2581 		if (c == '/' || c == '\0')
2582 			return -EACCES;
2583 	}
2584 	/*
2585 	 * See if the low-level filesystem might want
2586 	 * to use its own hash..
2587 	 */
2588 	if (base->d_flags & DCACHE_OP_HASH) {
2589 		int err = base->d_op->d_hash(base, this);
2590 		if (err < 0)
2591 			return err;
2592 	}
2593 
2594 	return inode_permission(&init_user_ns, base->d_inode, MAY_EXEC);
2595 }
2596 
2597 /**
2598  * try_lookup_one_len - filesystem helper to lookup single pathname component
2599  * @name:	pathname component to lookup
2600  * @base:	base directory to lookup from
2601  * @len:	maximum length @len should be interpreted to
2602  *
2603  * Look up a dentry by name in the dcache, returning NULL if it does not
2604  * currently exist.  The function does not try to create a dentry.
2605  *
2606  * Note that this routine is purely a helper for filesystem usage and should
2607  * not be called by generic code.
2608  *
2609  * The caller must hold base->i_mutex.
2610  */
2611 struct dentry *try_lookup_one_len(const char *name, struct dentry *base, int len)
2612 {
2613 	struct qstr this;
2614 	int err;
2615 
2616 	WARN_ON_ONCE(!inode_is_locked(base->d_inode));
2617 
2618 	err = lookup_one_len_common(name, base, len, &this);
2619 	if (err)
2620 		return ERR_PTR(err);
2621 
2622 	return lookup_dcache(&this, base, 0);
2623 }
2624 EXPORT_SYMBOL(try_lookup_one_len);
2625 
2626 /**
2627  * lookup_one_len - filesystem helper to lookup single pathname component
2628  * @name:	pathname component to lookup
2629  * @base:	base directory to lookup from
2630  * @len:	maximum length @len should be interpreted to
2631  *
2632  * Note that this routine is purely a helper for filesystem usage and should
2633  * not be called by generic code.
2634  *
2635  * The caller must hold base->i_mutex.
2636  */
2637 struct dentry *lookup_one_len(const char *name, struct dentry *base, int len)
2638 {
2639 	struct dentry *dentry;
2640 	struct qstr this;
2641 	int err;
2642 
2643 	WARN_ON_ONCE(!inode_is_locked(base->d_inode));
2644 
2645 	err = lookup_one_len_common(name, base, len, &this);
2646 	if (err)
2647 		return ERR_PTR(err);
2648 
2649 	dentry = lookup_dcache(&this, base, 0);
2650 	return dentry ? dentry : __lookup_slow(&this, base, 0);
2651 }
2652 EXPORT_SYMBOL(lookup_one_len);
2653 
2654 /**
2655  * lookup_one_len_unlocked - filesystem helper to lookup single pathname component
2656  * @name:	pathname component to lookup
2657  * @base:	base directory to lookup from
2658  * @len:	maximum length @len should be interpreted to
2659  *
2660  * Note that this routine is purely a helper for filesystem usage and should
2661  * not be called by generic code.
2662  *
2663  * Unlike lookup_one_len, it should be called without the parent
2664  * i_mutex held, and will take the i_mutex itself if necessary.
2665  */
2666 struct dentry *lookup_one_len_unlocked(const char *name,
2667 				       struct dentry *base, int len)
2668 {
2669 	struct qstr this;
2670 	int err;
2671 	struct dentry *ret;
2672 
2673 	err = lookup_one_len_common(name, base, len, &this);
2674 	if (err)
2675 		return ERR_PTR(err);
2676 
2677 	ret = lookup_dcache(&this, base, 0);
2678 	if (!ret)
2679 		ret = lookup_slow(&this, base, 0);
2680 	return ret;
2681 }
2682 EXPORT_SYMBOL(lookup_one_len_unlocked);
2683 
2684 /*
2685  * Like lookup_one_len_unlocked(), except that it yields ERR_PTR(-ENOENT)
2686  * on negatives.  Returns known positive or ERR_PTR(); that's what
2687  * most of the users want.  Note that pinned negative with unlocked parent
2688  * _can_ become positive at any time, so callers of lookup_one_len_unlocked()
2689  * need to be very careful; pinned positives have ->d_inode stable, so
2690  * this one avoids such problems.
2691  */
2692 struct dentry *lookup_positive_unlocked(const char *name,
2693 				       struct dentry *base, int len)
2694 {
2695 	struct dentry *ret = lookup_one_len_unlocked(name, base, len);
2696 	if (!IS_ERR(ret) && d_flags_negative(smp_load_acquire(&ret->d_flags))) {
2697 		dput(ret);
2698 		ret = ERR_PTR(-ENOENT);
2699 	}
2700 	return ret;
2701 }
2702 EXPORT_SYMBOL(lookup_positive_unlocked);
2703 
2704 #ifdef CONFIG_UNIX98_PTYS
2705 int path_pts(struct path *path)
2706 {
2707 	/* Find something mounted on "pts" in the same directory as
2708 	 * the input path.
2709 	 */
2710 	struct dentry *parent = dget_parent(path->dentry);
2711 	struct dentry *child;
2712 	struct qstr this = QSTR_INIT("pts", 3);
2713 
2714 	if (unlikely(!path_connected(path->mnt, parent))) {
2715 		dput(parent);
2716 		return -ENOENT;
2717 	}
2718 	dput(path->dentry);
2719 	path->dentry = parent;
2720 	child = d_hash_and_lookup(parent, &this);
2721 	if (!child)
2722 		return -ENOENT;
2723 
2724 	path->dentry = child;
2725 	dput(parent);
2726 	follow_down(path);
2727 	return 0;
2728 }
2729 #endif
2730 
2731 int user_path_at_empty(int dfd, const char __user *name, unsigned flags,
2732 		 struct path *path, int *empty)
2733 {
2734 	return filename_lookup(dfd, getname_flags(name, flags, empty),
2735 			       flags, path, NULL);
2736 }
2737 EXPORT_SYMBOL(user_path_at_empty);
2738 
2739 int __check_sticky(struct user_namespace *mnt_userns, struct inode *dir,
2740 		   struct inode *inode)
2741 {
2742 	kuid_t fsuid = current_fsuid();
2743 
2744 	if (uid_eq(i_uid_into_mnt(mnt_userns, inode), fsuid))
2745 		return 0;
2746 	if (uid_eq(i_uid_into_mnt(mnt_userns, dir), fsuid))
2747 		return 0;
2748 	return !capable_wrt_inode_uidgid(mnt_userns, inode, CAP_FOWNER);
2749 }
2750 EXPORT_SYMBOL(__check_sticky);
2751 
2752 /*
2753  *	Check whether we can remove a link victim from directory dir, check
2754  *  whether the type of victim is right.
2755  *  1. We can't do it if dir is read-only (done in permission())
2756  *  2. We should have write and exec permissions on dir
2757  *  3. We can't remove anything from append-only dir
2758  *  4. We can't do anything with immutable dir (done in permission())
2759  *  5. If the sticky bit on dir is set we should either
2760  *	a. be owner of dir, or
2761  *	b. be owner of victim, or
2762  *	c. have CAP_FOWNER capability
2763  *  6. If the victim is append-only or immutable we can't do antyhing with
2764  *     links pointing to it.
2765  *  7. If the victim has an unknown uid or gid we can't change the inode.
2766  *  8. If we were asked to remove a directory and victim isn't one - ENOTDIR.
2767  *  9. If we were asked to remove a non-directory and victim isn't one - EISDIR.
2768  * 10. We can't remove a root or mountpoint.
2769  * 11. We don't allow removal of NFS sillyrenamed files; it's handled by
2770  *     nfs_async_unlink().
2771  */
2772 static int may_delete(struct user_namespace *mnt_userns, struct inode *dir,
2773 		      struct dentry *victim, bool isdir)
2774 {
2775 	struct inode *inode = d_backing_inode(victim);
2776 	int error;
2777 
2778 	if (d_is_negative(victim))
2779 		return -ENOENT;
2780 	BUG_ON(!inode);
2781 
2782 	BUG_ON(victim->d_parent->d_inode != dir);
2783 
2784 	/* Inode writeback is not safe when the uid or gid are invalid. */
2785 	if (!uid_valid(i_uid_into_mnt(mnt_userns, inode)) ||
2786 	    !gid_valid(i_gid_into_mnt(mnt_userns, inode)))
2787 		return -EOVERFLOW;
2788 
2789 	audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
2790 
2791 	error = inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
2792 	if (error)
2793 		return error;
2794 	if (IS_APPEND(dir))
2795 		return -EPERM;
2796 
2797 	if (check_sticky(mnt_userns, dir, inode) || IS_APPEND(inode) ||
2798 	    IS_IMMUTABLE(inode) || IS_SWAPFILE(inode) ||
2799 	    HAS_UNMAPPED_ID(mnt_userns, inode))
2800 		return -EPERM;
2801 	if (isdir) {
2802 		if (!d_is_dir(victim))
2803 			return -ENOTDIR;
2804 		if (IS_ROOT(victim))
2805 			return -EBUSY;
2806 	} else if (d_is_dir(victim))
2807 		return -EISDIR;
2808 	if (IS_DEADDIR(dir))
2809 		return -ENOENT;
2810 	if (victim->d_flags & DCACHE_NFSFS_RENAMED)
2811 		return -EBUSY;
2812 	return 0;
2813 }
2814 
2815 /*	Check whether we can create an object with dentry child in directory
2816  *  dir.
2817  *  1. We can't do it if child already exists (open has special treatment for
2818  *     this case, but since we are inlined it's OK)
2819  *  2. We can't do it if dir is read-only (done in permission())
2820  *  3. We can't do it if the fs can't represent the fsuid or fsgid.
2821  *  4. We should have write and exec permissions on dir
2822  *  5. We can't do it if dir is immutable (done in permission())
2823  */
2824 static inline int may_create(struct user_namespace *mnt_userns,
2825 			     struct inode *dir, struct dentry *child)
2826 {
2827 	audit_inode_child(dir, child, AUDIT_TYPE_CHILD_CREATE);
2828 	if (child->d_inode)
2829 		return -EEXIST;
2830 	if (IS_DEADDIR(dir))
2831 		return -ENOENT;
2832 	if (!fsuidgid_has_mapping(dir->i_sb, mnt_userns))
2833 		return -EOVERFLOW;
2834 
2835 	return inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
2836 }
2837 
2838 /*
2839  * p1 and p2 should be directories on the same fs.
2840  */
2841 struct dentry *lock_rename(struct dentry *p1, struct dentry *p2)
2842 {
2843 	struct dentry *p;
2844 
2845 	if (p1 == p2) {
2846 		inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
2847 		return NULL;
2848 	}
2849 
2850 	mutex_lock(&p1->d_sb->s_vfs_rename_mutex);
2851 
2852 	p = d_ancestor(p2, p1);
2853 	if (p) {
2854 		inode_lock_nested(p2->d_inode, I_MUTEX_PARENT);
2855 		inode_lock_nested(p1->d_inode, I_MUTEX_CHILD);
2856 		return p;
2857 	}
2858 
2859 	p = d_ancestor(p1, p2);
2860 	if (p) {
2861 		inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
2862 		inode_lock_nested(p2->d_inode, I_MUTEX_CHILD);
2863 		return p;
2864 	}
2865 
2866 	inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
2867 	inode_lock_nested(p2->d_inode, I_MUTEX_PARENT2);
2868 	return NULL;
2869 }
2870 EXPORT_SYMBOL(lock_rename);
2871 
2872 void unlock_rename(struct dentry *p1, struct dentry *p2)
2873 {
2874 	inode_unlock(p1->d_inode);
2875 	if (p1 != p2) {
2876 		inode_unlock(p2->d_inode);
2877 		mutex_unlock(&p1->d_sb->s_vfs_rename_mutex);
2878 	}
2879 }
2880 EXPORT_SYMBOL(unlock_rename);
2881 
2882 /**
2883  * vfs_create - create new file
2884  * @mnt_userns:	user namespace of the mount the inode was found from
2885  * @dir:	inode of @dentry
2886  * @dentry:	pointer to dentry of the base directory
2887  * @mode:	mode of the new file
2888  * @want_excl:	whether the file must not yet exist
2889  *
2890  * Create a new file.
2891  *
2892  * If the inode has been found through an idmapped mount the user namespace of
2893  * the vfsmount must be passed through @mnt_userns. This function will then take
2894  * care to map the inode according to @mnt_userns before checking permissions.
2895  * On non-idmapped mounts or if permission checking is to be performed on the
2896  * raw inode simply passs init_user_ns.
2897  */
2898 int vfs_create(struct user_namespace *mnt_userns, struct inode *dir,
2899 	       struct dentry *dentry, umode_t mode, bool want_excl)
2900 {
2901 	int error = may_create(mnt_userns, dir, dentry);
2902 	if (error)
2903 		return error;
2904 
2905 	if (!dir->i_op->create)
2906 		return -EACCES;	/* shouldn't it be ENOSYS? */
2907 	mode &= S_IALLUGO;
2908 	mode |= S_IFREG;
2909 	error = security_inode_create(dir, dentry, mode);
2910 	if (error)
2911 		return error;
2912 	error = dir->i_op->create(mnt_userns, dir, dentry, mode, want_excl);
2913 	if (!error)
2914 		fsnotify_create(dir, dentry);
2915 	return error;
2916 }
2917 EXPORT_SYMBOL(vfs_create);
2918 
2919 int vfs_mkobj(struct dentry *dentry, umode_t mode,
2920 		int (*f)(struct dentry *, umode_t, void *),
2921 		void *arg)
2922 {
2923 	struct inode *dir = dentry->d_parent->d_inode;
2924 	int error = may_create(&init_user_ns, dir, dentry);
2925 	if (error)
2926 		return error;
2927 
2928 	mode &= S_IALLUGO;
2929 	mode |= S_IFREG;
2930 	error = security_inode_create(dir, dentry, mode);
2931 	if (error)
2932 		return error;
2933 	error = f(dentry, mode, arg);
2934 	if (!error)
2935 		fsnotify_create(dir, dentry);
2936 	return error;
2937 }
2938 EXPORT_SYMBOL(vfs_mkobj);
2939 
2940 bool may_open_dev(const struct path *path)
2941 {
2942 	return !(path->mnt->mnt_flags & MNT_NODEV) &&
2943 		!(path->mnt->mnt_sb->s_iflags & SB_I_NODEV);
2944 }
2945 
2946 static int may_open(struct user_namespace *mnt_userns, const struct path *path,
2947 		    int acc_mode, int flag)
2948 {
2949 	struct dentry *dentry = path->dentry;
2950 	struct inode *inode = dentry->d_inode;
2951 	int error;
2952 
2953 	if (!inode)
2954 		return -ENOENT;
2955 
2956 	switch (inode->i_mode & S_IFMT) {
2957 	case S_IFLNK:
2958 		return -ELOOP;
2959 	case S_IFDIR:
2960 		if (acc_mode & MAY_WRITE)
2961 			return -EISDIR;
2962 		if (acc_mode & MAY_EXEC)
2963 			return -EACCES;
2964 		break;
2965 	case S_IFBLK:
2966 	case S_IFCHR:
2967 		if (!may_open_dev(path))
2968 			return -EACCES;
2969 		fallthrough;
2970 	case S_IFIFO:
2971 	case S_IFSOCK:
2972 		if (acc_mode & MAY_EXEC)
2973 			return -EACCES;
2974 		flag &= ~O_TRUNC;
2975 		break;
2976 	case S_IFREG:
2977 		if ((acc_mode & MAY_EXEC) && path_noexec(path))
2978 			return -EACCES;
2979 		break;
2980 	}
2981 
2982 	error = inode_permission(mnt_userns, inode, MAY_OPEN | acc_mode);
2983 	if (error)
2984 		return error;
2985 
2986 	/*
2987 	 * An append-only file must be opened in append mode for writing.
2988 	 */
2989 	if (IS_APPEND(inode)) {
2990 		if  ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND))
2991 			return -EPERM;
2992 		if (flag & O_TRUNC)
2993 			return -EPERM;
2994 	}
2995 
2996 	/* O_NOATIME can only be set by the owner or superuser */
2997 	if (flag & O_NOATIME && !inode_owner_or_capable(mnt_userns, inode))
2998 		return -EPERM;
2999 
3000 	return 0;
3001 }
3002 
3003 static int handle_truncate(struct user_namespace *mnt_userns, struct file *filp)
3004 {
3005 	const struct path *path = &filp->f_path;
3006 	struct inode *inode = path->dentry->d_inode;
3007 	int error = get_write_access(inode);
3008 	if (error)
3009 		return error;
3010 	/*
3011 	 * Refuse to truncate files with mandatory locks held on them.
3012 	 */
3013 	error = locks_verify_locked(filp);
3014 	if (!error)
3015 		error = security_path_truncate(path);
3016 	if (!error) {
3017 		error = do_truncate(mnt_userns, path->dentry, 0,
3018 				    ATTR_MTIME|ATTR_CTIME|ATTR_OPEN,
3019 				    filp);
3020 	}
3021 	put_write_access(inode);
3022 	return error;
3023 }
3024 
3025 static inline int open_to_namei_flags(int flag)
3026 {
3027 	if ((flag & O_ACCMODE) == 3)
3028 		flag--;
3029 	return flag;
3030 }
3031 
3032 static int may_o_create(struct user_namespace *mnt_userns,
3033 			const struct path *dir, struct dentry *dentry,
3034 			umode_t mode)
3035 {
3036 	int error = security_path_mknod(dir, dentry, mode, 0);
3037 	if (error)
3038 		return error;
3039 
3040 	if (!fsuidgid_has_mapping(dir->dentry->d_sb, mnt_userns))
3041 		return -EOVERFLOW;
3042 
3043 	error = inode_permission(mnt_userns, dir->dentry->d_inode,
3044 				 MAY_WRITE | MAY_EXEC);
3045 	if (error)
3046 		return error;
3047 
3048 	return security_inode_create(dir->dentry->d_inode, dentry, mode);
3049 }
3050 
3051 /*
3052  * Attempt to atomically look up, create and open a file from a negative
3053  * dentry.
3054  *
3055  * Returns 0 if successful.  The file will have been created and attached to
3056  * @file by the filesystem calling finish_open().
3057  *
3058  * If the file was looked up only or didn't need creating, FMODE_OPENED won't
3059  * be set.  The caller will need to perform the open themselves.  @path will
3060  * have been updated to point to the new dentry.  This may be negative.
3061  *
3062  * Returns an error code otherwise.
3063  */
3064 static struct dentry *atomic_open(struct nameidata *nd, struct dentry *dentry,
3065 				  struct file *file,
3066 				  int open_flag, umode_t mode)
3067 {
3068 	struct dentry *const DENTRY_NOT_SET = (void *) -1UL;
3069 	struct inode *dir =  nd->path.dentry->d_inode;
3070 	int error;
3071 
3072 	if (nd->flags & LOOKUP_DIRECTORY)
3073 		open_flag |= O_DIRECTORY;
3074 
3075 	file->f_path.dentry = DENTRY_NOT_SET;
3076 	file->f_path.mnt = nd->path.mnt;
3077 	error = dir->i_op->atomic_open(dir, dentry, file,
3078 				       open_to_namei_flags(open_flag), mode);
3079 	d_lookup_done(dentry);
3080 	if (!error) {
3081 		if (file->f_mode & FMODE_OPENED) {
3082 			if (unlikely(dentry != file->f_path.dentry)) {
3083 				dput(dentry);
3084 				dentry = dget(file->f_path.dentry);
3085 			}
3086 		} else if (WARN_ON(file->f_path.dentry == DENTRY_NOT_SET)) {
3087 			error = -EIO;
3088 		} else {
3089 			if (file->f_path.dentry) {
3090 				dput(dentry);
3091 				dentry = file->f_path.dentry;
3092 			}
3093 			if (unlikely(d_is_negative(dentry)))
3094 				error = -ENOENT;
3095 		}
3096 	}
3097 	if (error) {
3098 		dput(dentry);
3099 		dentry = ERR_PTR(error);
3100 	}
3101 	return dentry;
3102 }
3103 
3104 /*
3105  * Look up and maybe create and open the last component.
3106  *
3107  * Must be called with parent locked (exclusive in O_CREAT case).
3108  *
3109  * Returns 0 on success, that is, if
3110  *  the file was successfully atomically created (if necessary) and opened, or
3111  *  the file was not completely opened at this time, though lookups and
3112  *  creations were performed.
3113  * These case are distinguished by presence of FMODE_OPENED on file->f_mode.
3114  * In the latter case dentry returned in @path might be negative if O_CREAT
3115  * hadn't been specified.
3116  *
3117  * An error code is returned on failure.
3118  */
3119 static struct dentry *lookup_open(struct nameidata *nd, struct file *file,
3120 				  const struct open_flags *op,
3121 				  bool got_write)
3122 {
3123 	struct user_namespace *mnt_userns;
3124 	struct dentry *dir = nd->path.dentry;
3125 	struct inode *dir_inode = dir->d_inode;
3126 	int open_flag = op->open_flag;
3127 	struct dentry *dentry;
3128 	int error, create_error = 0;
3129 	umode_t mode = op->mode;
3130 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
3131 
3132 	if (unlikely(IS_DEADDIR(dir_inode)))
3133 		return ERR_PTR(-ENOENT);
3134 
3135 	file->f_mode &= ~FMODE_CREATED;
3136 	dentry = d_lookup(dir, &nd->last);
3137 	for (;;) {
3138 		if (!dentry) {
3139 			dentry = d_alloc_parallel(dir, &nd->last, &wq);
3140 			if (IS_ERR(dentry))
3141 				return dentry;
3142 		}
3143 		if (d_in_lookup(dentry))
3144 			break;
3145 
3146 		error = d_revalidate(dentry, nd->flags);
3147 		if (likely(error > 0))
3148 			break;
3149 		if (error)
3150 			goto out_dput;
3151 		d_invalidate(dentry);
3152 		dput(dentry);
3153 		dentry = NULL;
3154 	}
3155 	if (dentry->d_inode) {
3156 		/* Cached positive dentry: will open in f_op->open */
3157 		return dentry;
3158 	}
3159 
3160 	/*
3161 	 * Checking write permission is tricky, bacuse we don't know if we are
3162 	 * going to actually need it: O_CREAT opens should work as long as the
3163 	 * file exists.  But checking existence breaks atomicity.  The trick is
3164 	 * to check access and if not granted clear O_CREAT from the flags.
3165 	 *
3166 	 * Another problem is returing the "right" error value (e.g. for an
3167 	 * O_EXCL open we want to return EEXIST not EROFS).
3168 	 */
3169 	if (unlikely(!got_write))
3170 		open_flag &= ~O_TRUNC;
3171 	mnt_userns = mnt_user_ns(nd->path.mnt);
3172 	if (open_flag & O_CREAT) {
3173 		if (open_flag & O_EXCL)
3174 			open_flag &= ~O_TRUNC;
3175 		if (!IS_POSIXACL(dir->d_inode))
3176 			mode &= ~current_umask();
3177 		if (likely(got_write))
3178 			create_error = may_o_create(mnt_userns, &nd->path,
3179 						    dentry, mode);
3180 		else
3181 			create_error = -EROFS;
3182 	}
3183 	if (create_error)
3184 		open_flag &= ~O_CREAT;
3185 	if (dir_inode->i_op->atomic_open) {
3186 		dentry = atomic_open(nd, dentry, file, open_flag, mode);
3187 		if (unlikely(create_error) && dentry == ERR_PTR(-ENOENT))
3188 			dentry = ERR_PTR(create_error);
3189 		return dentry;
3190 	}
3191 
3192 	if (d_in_lookup(dentry)) {
3193 		struct dentry *res = dir_inode->i_op->lookup(dir_inode, dentry,
3194 							     nd->flags);
3195 		d_lookup_done(dentry);
3196 		if (unlikely(res)) {
3197 			if (IS_ERR(res)) {
3198 				error = PTR_ERR(res);
3199 				goto out_dput;
3200 			}
3201 			dput(dentry);
3202 			dentry = res;
3203 		}
3204 	}
3205 
3206 	/* Negative dentry, just create the file */
3207 	if (!dentry->d_inode && (open_flag & O_CREAT)) {
3208 		file->f_mode |= FMODE_CREATED;
3209 		audit_inode_child(dir_inode, dentry, AUDIT_TYPE_CHILD_CREATE);
3210 		if (!dir_inode->i_op->create) {
3211 			error = -EACCES;
3212 			goto out_dput;
3213 		}
3214 
3215 		error = dir_inode->i_op->create(mnt_userns, dir_inode, dentry,
3216 						mode, open_flag & O_EXCL);
3217 		if (error)
3218 			goto out_dput;
3219 	}
3220 	if (unlikely(create_error) && !dentry->d_inode) {
3221 		error = create_error;
3222 		goto out_dput;
3223 	}
3224 	return dentry;
3225 
3226 out_dput:
3227 	dput(dentry);
3228 	return ERR_PTR(error);
3229 }
3230 
3231 static const char *open_last_lookups(struct nameidata *nd,
3232 		   struct file *file, const struct open_flags *op)
3233 {
3234 	struct dentry *dir = nd->path.dentry;
3235 	int open_flag = op->open_flag;
3236 	bool got_write = false;
3237 	unsigned seq;
3238 	struct inode *inode;
3239 	struct dentry *dentry;
3240 	const char *res;
3241 
3242 	nd->flags |= op->intent;
3243 
3244 	if (nd->last_type != LAST_NORM) {
3245 		if (nd->depth)
3246 			put_link(nd);
3247 		return handle_dots(nd, nd->last_type);
3248 	}
3249 
3250 	if (!(open_flag & O_CREAT)) {
3251 		if (nd->last.name[nd->last.len])
3252 			nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
3253 		/* we _can_ be in RCU mode here */
3254 		dentry = lookup_fast(nd, &inode, &seq);
3255 		if (IS_ERR(dentry))
3256 			return ERR_CAST(dentry);
3257 		if (likely(dentry))
3258 			goto finish_lookup;
3259 
3260 		BUG_ON(nd->flags & LOOKUP_RCU);
3261 	} else {
3262 		/* create side of things */
3263 		if (nd->flags & LOOKUP_RCU) {
3264 			if (!try_to_unlazy(nd))
3265 				return ERR_PTR(-ECHILD);
3266 		}
3267 		audit_inode(nd->name, dir, AUDIT_INODE_PARENT);
3268 		/* trailing slashes? */
3269 		if (unlikely(nd->last.name[nd->last.len]))
3270 			return ERR_PTR(-EISDIR);
3271 	}
3272 
3273 	if (open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) {
3274 		got_write = !mnt_want_write(nd->path.mnt);
3275 		/*
3276 		 * do _not_ fail yet - we might not need that or fail with
3277 		 * a different error; let lookup_open() decide; we'll be
3278 		 * dropping this one anyway.
3279 		 */
3280 	}
3281 	if (open_flag & O_CREAT)
3282 		inode_lock(dir->d_inode);
3283 	else
3284 		inode_lock_shared(dir->d_inode);
3285 	dentry = lookup_open(nd, file, op, got_write);
3286 	if (!IS_ERR(dentry) && (file->f_mode & FMODE_CREATED))
3287 		fsnotify_create(dir->d_inode, dentry);
3288 	if (open_flag & O_CREAT)
3289 		inode_unlock(dir->d_inode);
3290 	else
3291 		inode_unlock_shared(dir->d_inode);
3292 
3293 	if (got_write)
3294 		mnt_drop_write(nd->path.mnt);
3295 
3296 	if (IS_ERR(dentry))
3297 		return ERR_CAST(dentry);
3298 
3299 	if (file->f_mode & (FMODE_OPENED | FMODE_CREATED)) {
3300 		dput(nd->path.dentry);
3301 		nd->path.dentry = dentry;
3302 		return NULL;
3303 	}
3304 
3305 finish_lookup:
3306 	if (nd->depth)
3307 		put_link(nd);
3308 	res = step_into(nd, WALK_TRAILING, dentry, inode, seq);
3309 	if (unlikely(res))
3310 		nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL);
3311 	return res;
3312 }
3313 
3314 /*
3315  * Handle the last step of open()
3316  */
3317 static int do_open(struct nameidata *nd,
3318 		   struct file *file, const struct open_flags *op)
3319 {
3320 	struct user_namespace *mnt_userns;
3321 	int open_flag = op->open_flag;
3322 	bool do_truncate;
3323 	int acc_mode;
3324 	int error;
3325 
3326 	if (!(file->f_mode & (FMODE_OPENED | FMODE_CREATED))) {
3327 		error = complete_walk(nd);
3328 		if (error)
3329 			return error;
3330 	}
3331 	if (!(file->f_mode & FMODE_CREATED))
3332 		audit_inode(nd->name, nd->path.dentry, 0);
3333 	mnt_userns = mnt_user_ns(nd->path.mnt);
3334 	if (open_flag & O_CREAT) {
3335 		if ((open_flag & O_EXCL) && !(file->f_mode & FMODE_CREATED))
3336 			return -EEXIST;
3337 		if (d_is_dir(nd->path.dentry))
3338 			return -EISDIR;
3339 		error = may_create_in_sticky(mnt_userns, nd,
3340 					     d_backing_inode(nd->path.dentry));
3341 		if (unlikely(error))
3342 			return error;
3343 	}
3344 	if ((nd->flags & LOOKUP_DIRECTORY) && !d_can_lookup(nd->path.dentry))
3345 		return -ENOTDIR;
3346 
3347 	do_truncate = false;
3348 	acc_mode = op->acc_mode;
3349 	if (file->f_mode & FMODE_CREATED) {
3350 		/* Don't check for write permission, don't truncate */
3351 		open_flag &= ~O_TRUNC;
3352 		acc_mode = 0;
3353 	} else if (d_is_reg(nd->path.dentry) && open_flag & O_TRUNC) {
3354 		error = mnt_want_write(nd->path.mnt);
3355 		if (error)
3356 			return error;
3357 		do_truncate = true;
3358 	}
3359 	error = may_open(mnt_userns, &nd->path, acc_mode, open_flag);
3360 	if (!error && !(file->f_mode & FMODE_OPENED))
3361 		error = vfs_open(&nd->path, file);
3362 	if (!error)
3363 		error = ima_file_check(file, op->acc_mode);
3364 	if (!error && do_truncate)
3365 		error = handle_truncate(mnt_userns, file);
3366 	if (unlikely(error > 0)) {
3367 		WARN_ON(1);
3368 		error = -EINVAL;
3369 	}
3370 	if (do_truncate)
3371 		mnt_drop_write(nd->path.mnt);
3372 	return error;
3373 }
3374 
3375 /**
3376  * vfs_tmpfile - create tmpfile
3377  * @mnt_userns:	user namespace of the mount the inode was found from
3378  * @dentry:	pointer to dentry of the base directory
3379  * @mode:	mode of the new tmpfile
3380  * @open_flag:	flags
3381  *
3382  * Create a temporary file.
3383  *
3384  * If the inode has been found through an idmapped mount the user namespace of
3385  * the vfsmount must be passed through @mnt_userns. This function will then take
3386  * care to map the inode according to @mnt_userns before checking permissions.
3387  * On non-idmapped mounts or if permission checking is to be performed on the
3388  * raw inode simply passs init_user_ns.
3389  */
3390 struct dentry *vfs_tmpfile(struct user_namespace *mnt_userns,
3391 			   struct dentry *dentry, umode_t mode, int open_flag)
3392 {
3393 	struct dentry *child = NULL;
3394 	struct inode *dir = dentry->d_inode;
3395 	struct inode *inode;
3396 	int error;
3397 
3398 	/* we want directory to be writable */
3399 	error = inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
3400 	if (error)
3401 		goto out_err;
3402 	error = -EOPNOTSUPP;
3403 	if (!dir->i_op->tmpfile)
3404 		goto out_err;
3405 	error = -ENOMEM;
3406 	child = d_alloc(dentry, &slash_name);
3407 	if (unlikely(!child))
3408 		goto out_err;
3409 	error = dir->i_op->tmpfile(mnt_userns, dir, child, mode);
3410 	if (error)
3411 		goto out_err;
3412 	error = -ENOENT;
3413 	inode = child->d_inode;
3414 	if (unlikely(!inode))
3415 		goto out_err;
3416 	if (!(open_flag & O_EXCL)) {
3417 		spin_lock(&inode->i_lock);
3418 		inode->i_state |= I_LINKABLE;
3419 		spin_unlock(&inode->i_lock);
3420 	}
3421 	ima_post_create_tmpfile(mnt_userns, inode);
3422 	return child;
3423 
3424 out_err:
3425 	dput(child);
3426 	return ERR_PTR(error);
3427 }
3428 EXPORT_SYMBOL(vfs_tmpfile);
3429 
3430 static int do_tmpfile(struct nameidata *nd, unsigned flags,
3431 		const struct open_flags *op,
3432 		struct file *file)
3433 {
3434 	struct user_namespace *mnt_userns;
3435 	struct dentry *child;
3436 	struct path path;
3437 	int error = path_lookupat(nd, flags | LOOKUP_DIRECTORY, &path);
3438 	if (unlikely(error))
3439 		return error;
3440 	error = mnt_want_write(path.mnt);
3441 	if (unlikely(error))
3442 		goto out;
3443 	mnt_userns = mnt_user_ns(path.mnt);
3444 	child = vfs_tmpfile(mnt_userns, path.dentry, op->mode, op->open_flag);
3445 	error = PTR_ERR(child);
3446 	if (IS_ERR(child))
3447 		goto out2;
3448 	dput(path.dentry);
3449 	path.dentry = child;
3450 	audit_inode(nd->name, child, 0);
3451 	/* Don't check for other permissions, the inode was just created */
3452 	error = may_open(mnt_userns, &path, 0, op->open_flag);
3453 	if (!error)
3454 		error = vfs_open(&path, file);
3455 out2:
3456 	mnt_drop_write(path.mnt);
3457 out:
3458 	path_put(&path);
3459 	return error;
3460 }
3461 
3462 static int do_o_path(struct nameidata *nd, unsigned flags, struct file *file)
3463 {
3464 	struct path path;
3465 	int error = path_lookupat(nd, flags, &path);
3466 	if (!error) {
3467 		audit_inode(nd->name, path.dentry, 0);
3468 		error = vfs_open(&path, file);
3469 		path_put(&path);
3470 	}
3471 	return error;
3472 }
3473 
3474 static struct file *path_openat(struct nameidata *nd,
3475 			const struct open_flags *op, unsigned flags)
3476 {
3477 	struct file *file;
3478 	int error;
3479 
3480 	file = alloc_empty_file(op->open_flag, current_cred());
3481 	if (IS_ERR(file))
3482 		return file;
3483 
3484 	if (unlikely(file->f_flags & __O_TMPFILE)) {
3485 		error = do_tmpfile(nd, flags, op, file);
3486 	} else if (unlikely(file->f_flags & O_PATH)) {
3487 		error = do_o_path(nd, flags, file);
3488 	} else {
3489 		const char *s = path_init(nd, flags);
3490 		while (!(error = link_path_walk(s, nd)) &&
3491 		       (s = open_last_lookups(nd, file, op)) != NULL)
3492 			;
3493 		if (!error)
3494 			error = do_open(nd, file, op);
3495 		terminate_walk(nd);
3496 	}
3497 	if (likely(!error)) {
3498 		if (likely(file->f_mode & FMODE_OPENED))
3499 			return file;
3500 		WARN_ON(1);
3501 		error = -EINVAL;
3502 	}
3503 	fput(file);
3504 	if (error == -EOPENSTALE) {
3505 		if (flags & LOOKUP_RCU)
3506 			error = -ECHILD;
3507 		else
3508 			error = -ESTALE;
3509 	}
3510 	return ERR_PTR(error);
3511 }
3512 
3513 struct file *do_filp_open(int dfd, struct filename *pathname,
3514 		const struct open_flags *op)
3515 {
3516 	struct nameidata nd;
3517 	int flags = op->lookup_flags;
3518 	struct file *filp;
3519 
3520 	set_nameidata(&nd, dfd, pathname);
3521 	filp = path_openat(&nd, op, flags | LOOKUP_RCU);
3522 	if (unlikely(filp == ERR_PTR(-ECHILD)))
3523 		filp = path_openat(&nd, op, flags);
3524 	if (unlikely(filp == ERR_PTR(-ESTALE)))
3525 		filp = path_openat(&nd, op, flags | LOOKUP_REVAL);
3526 	restore_nameidata();
3527 	return filp;
3528 }
3529 
3530 struct file *do_file_open_root(struct dentry *dentry, struct vfsmount *mnt,
3531 		const char *name, const struct open_flags *op)
3532 {
3533 	struct nameidata nd;
3534 	struct file *file;
3535 	struct filename *filename;
3536 	int flags = op->lookup_flags | LOOKUP_ROOT;
3537 
3538 	nd.root.mnt = mnt;
3539 	nd.root.dentry = dentry;
3540 
3541 	if (d_is_symlink(dentry) && op->intent & LOOKUP_OPEN)
3542 		return ERR_PTR(-ELOOP);
3543 
3544 	filename = getname_kernel(name);
3545 	if (IS_ERR(filename))
3546 		return ERR_CAST(filename);
3547 
3548 	set_nameidata(&nd, -1, filename);
3549 	file = path_openat(&nd, op, flags | LOOKUP_RCU);
3550 	if (unlikely(file == ERR_PTR(-ECHILD)))
3551 		file = path_openat(&nd, op, flags);
3552 	if (unlikely(file == ERR_PTR(-ESTALE)))
3553 		file = path_openat(&nd, op, flags | LOOKUP_REVAL);
3554 	restore_nameidata();
3555 	putname(filename);
3556 	return file;
3557 }
3558 
3559 static struct dentry *filename_create(int dfd, struct filename *name,
3560 				struct path *path, unsigned int lookup_flags)
3561 {
3562 	struct dentry *dentry = ERR_PTR(-EEXIST);
3563 	struct qstr last;
3564 	int type;
3565 	int err2;
3566 	int error;
3567 	bool is_dir = (lookup_flags & LOOKUP_DIRECTORY);
3568 
3569 	/*
3570 	 * Note that only LOOKUP_REVAL and LOOKUP_DIRECTORY matter here. Any
3571 	 * other flags passed in are ignored!
3572 	 */
3573 	lookup_flags &= LOOKUP_REVAL;
3574 
3575 	name = filename_parentat(dfd, name, lookup_flags, path, &last, &type);
3576 	if (IS_ERR(name))
3577 		return ERR_CAST(name);
3578 
3579 	/*
3580 	 * Yucky last component or no last component at all?
3581 	 * (foo/., foo/.., /////)
3582 	 */
3583 	if (unlikely(type != LAST_NORM))
3584 		goto out;
3585 
3586 	/* don't fail immediately if it's r/o, at least try to report other errors */
3587 	err2 = mnt_want_write(path->mnt);
3588 	/*
3589 	 * Do the final lookup.
3590 	 */
3591 	lookup_flags |= LOOKUP_CREATE | LOOKUP_EXCL;
3592 	inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
3593 	dentry = __lookup_hash(&last, path->dentry, lookup_flags);
3594 	if (IS_ERR(dentry))
3595 		goto unlock;
3596 
3597 	error = -EEXIST;
3598 	if (d_is_positive(dentry))
3599 		goto fail;
3600 
3601 	/*
3602 	 * Special case - lookup gave negative, but... we had foo/bar/
3603 	 * From the vfs_mknod() POV we just have a negative dentry -
3604 	 * all is fine. Let's be bastards - you had / on the end, you've
3605 	 * been asking for (non-existent) directory. -ENOENT for you.
3606 	 */
3607 	if (unlikely(!is_dir && last.name[last.len])) {
3608 		error = -ENOENT;
3609 		goto fail;
3610 	}
3611 	if (unlikely(err2)) {
3612 		error = err2;
3613 		goto fail;
3614 	}
3615 	putname(name);
3616 	return dentry;
3617 fail:
3618 	dput(dentry);
3619 	dentry = ERR_PTR(error);
3620 unlock:
3621 	inode_unlock(path->dentry->d_inode);
3622 	if (!err2)
3623 		mnt_drop_write(path->mnt);
3624 out:
3625 	path_put(path);
3626 	putname(name);
3627 	return dentry;
3628 }
3629 
3630 struct dentry *kern_path_create(int dfd, const char *pathname,
3631 				struct path *path, unsigned int lookup_flags)
3632 {
3633 	return filename_create(dfd, getname_kernel(pathname),
3634 				path, lookup_flags);
3635 }
3636 EXPORT_SYMBOL(kern_path_create);
3637 
3638 void done_path_create(struct path *path, struct dentry *dentry)
3639 {
3640 	dput(dentry);
3641 	inode_unlock(path->dentry->d_inode);
3642 	mnt_drop_write(path->mnt);
3643 	path_put(path);
3644 }
3645 EXPORT_SYMBOL(done_path_create);
3646 
3647 inline struct dentry *user_path_create(int dfd, const char __user *pathname,
3648 				struct path *path, unsigned int lookup_flags)
3649 {
3650 	return filename_create(dfd, getname(pathname), path, lookup_flags);
3651 }
3652 EXPORT_SYMBOL(user_path_create);
3653 
3654 /**
3655  * vfs_mknod - create device node or file
3656  * @mnt_userns:	user namespace of the mount the inode was found from
3657  * @dir:	inode of @dentry
3658  * @dentry:	pointer to dentry of the base directory
3659  * @mode:	mode of the new device node or file
3660  * @dev:	device number of device to create
3661  *
3662  * Create a device node or file.
3663  *
3664  * If the inode has been found through an idmapped mount the user namespace of
3665  * the vfsmount must be passed through @mnt_userns. This function will then take
3666  * care to map the inode according to @mnt_userns before checking permissions.
3667  * On non-idmapped mounts or if permission checking is to be performed on the
3668  * raw inode simply passs init_user_ns.
3669  */
3670 int vfs_mknod(struct user_namespace *mnt_userns, struct inode *dir,
3671 	      struct dentry *dentry, umode_t mode, dev_t dev)
3672 {
3673 	bool is_whiteout = S_ISCHR(mode) && dev == WHITEOUT_DEV;
3674 	int error = may_create(mnt_userns, dir, dentry);
3675 
3676 	if (error)
3677 		return error;
3678 
3679 	if ((S_ISCHR(mode) || S_ISBLK(mode)) && !is_whiteout &&
3680 	    !capable(CAP_MKNOD))
3681 		return -EPERM;
3682 
3683 	if (!dir->i_op->mknod)
3684 		return -EPERM;
3685 
3686 	error = devcgroup_inode_mknod(mode, dev);
3687 	if (error)
3688 		return error;
3689 
3690 	error = security_inode_mknod(dir, dentry, mode, dev);
3691 	if (error)
3692 		return error;
3693 
3694 	error = dir->i_op->mknod(mnt_userns, dir, dentry, mode, dev);
3695 	if (!error)
3696 		fsnotify_create(dir, dentry);
3697 	return error;
3698 }
3699 EXPORT_SYMBOL(vfs_mknod);
3700 
3701 static int may_mknod(umode_t mode)
3702 {
3703 	switch (mode & S_IFMT) {
3704 	case S_IFREG:
3705 	case S_IFCHR:
3706 	case S_IFBLK:
3707 	case S_IFIFO:
3708 	case S_IFSOCK:
3709 	case 0: /* zero mode translates to S_IFREG */
3710 		return 0;
3711 	case S_IFDIR:
3712 		return -EPERM;
3713 	default:
3714 		return -EINVAL;
3715 	}
3716 }
3717 
3718 static long do_mknodat(int dfd, const char __user *filename, umode_t mode,
3719 		unsigned int dev)
3720 {
3721 	struct user_namespace *mnt_userns;
3722 	struct dentry *dentry;
3723 	struct path path;
3724 	int error;
3725 	unsigned int lookup_flags = 0;
3726 
3727 	error = may_mknod(mode);
3728 	if (error)
3729 		return error;
3730 retry:
3731 	dentry = user_path_create(dfd, filename, &path, lookup_flags);
3732 	if (IS_ERR(dentry))
3733 		return PTR_ERR(dentry);
3734 
3735 	if (!IS_POSIXACL(path.dentry->d_inode))
3736 		mode &= ~current_umask();
3737 	error = security_path_mknod(&path, dentry, mode, dev);
3738 	if (error)
3739 		goto out;
3740 
3741 	mnt_userns = mnt_user_ns(path.mnt);
3742 	switch (mode & S_IFMT) {
3743 		case 0: case S_IFREG:
3744 			error = vfs_create(mnt_userns, path.dentry->d_inode,
3745 					   dentry, mode, true);
3746 			if (!error)
3747 				ima_post_path_mknod(mnt_userns, dentry);
3748 			break;
3749 		case S_IFCHR: case S_IFBLK:
3750 			error = vfs_mknod(mnt_userns, path.dentry->d_inode,
3751 					  dentry, mode, new_decode_dev(dev));
3752 			break;
3753 		case S_IFIFO: case S_IFSOCK:
3754 			error = vfs_mknod(mnt_userns, path.dentry->d_inode,
3755 					  dentry, mode, 0);
3756 			break;
3757 	}
3758 out:
3759 	done_path_create(&path, dentry);
3760 	if (retry_estale(error, lookup_flags)) {
3761 		lookup_flags |= LOOKUP_REVAL;
3762 		goto retry;
3763 	}
3764 	return error;
3765 }
3766 
3767 SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, umode_t, mode,
3768 		unsigned int, dev)
3769 {
3770 	return do_mknodat(dfd, filename, mode, dev);
3771 }
3772 
3773 SYSCALL_DEFINE3(mknod, const char __user *, filename, umode_t, mode, unsigned, dev)
3774 {
3775 	return do_mknodat(AT_FDCWD, filename, mode, dev);
3776 }
3777 
3778 /**
3779  * vfs_mkdir - create directory
3780  * @mnt_userns:	user namespace of the mount the inode was found from
3781  * @dir:	inode of @dentry
3782  * @dentry:	pointer to dentry of the base directory
3783  * @mode:	mode of the new directory
3784  *
3785  * Create a directory.
3786  *
3787  * If the inode has been found through an idmapped mount the user namespace of
3788  * the vfsmount must be passed through @mnt_userns. This function will then take
3789  * care to map the inode according to @mnt_userns before checking permissions.
3790  * On non-idmapped mounts or if permission checking is to be performed on the
3791  * raw inode simply passs init_user_ns.
3792  */
3793 int vfs_mkdir(struct user_namespace *mnt_userns, struct inode *dir,
3794 	      struct dentry *dentry, umode_t mode)
3795 {
3796 	int error = may_create(mnt_userns, dir, dentry);
3797 	unsigned max_links = dir->i_sb->s_max_links;
3798 
3799 	if (error)
3800 		return error;
3801 
3802 	if (!dir->i_op->mkdir)
3803 		return -EPERM;
3804 
3805 	mode &= (S_IRWXUGO|S_ISVTX);
3806 	error = security_inode_mkdir(dir, dentry, mode);
3807 	if (error)
3808 		return error;
3809 
3810 	if (max_links && dir->i_nlink >= max_links)
3811 		return -EMLINK;
3812 
3813 	error = dir->i_op->mkdir(mnt_userns, dir, dentry, mode);
3814 	if (!error)
3815 		fsnotify_mkdir(dir, dentry);
3816 	return error;
3817 }
3818 EXPORT_SYMBOL(vfs_mkdir);
3819 
3820 static long do_mkdirat(int dfd, const char __user *pathname, umode_t mode)
3821 {
3822 	struct dentry *dentry;
3823 	struct path path;
3824 	int error;
3825 	unsigned int lookup_flags = LOOKUP_DIRECTORY;
3826 
3827 retry:
3828 	dentry = user_path_create(dfd, pathname, &path, lookup_flags);
3829 	if (IS_ERR(dentry))
3830 		return PTR_ERR(dentry);
3831 
3832 	if (!IS_POSIXACL(path.dentry->d_inode))
3833 		mode &= ~current_umask();
3834 	error = security_path_mkdir(&path, dentry, mode);
3835 	if (!error) {
3836 		struct user_namespace *mnt_userns;
3837 		mnt_userns = mnt_user_ns(path.mnt);
3838 		error = vfs_mkdir(mnt_userns, path.dentry->d_inode, dentry,
3839 				  mode);
3840 	}
3841 	done_path_create(&path, dentry);
3842 	if (retry_estale(error, lookup_flags)) {
3843 		lookup_flags |= LOOKUP_REVAL;
3844 		goto retry;
3845 	}
3846 	return error;
3847 }
3848 
3849 SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, umode_t, mode)
3850 {
3851 	return do_mkdirat(dfd, pathname, mode);
3852 }
3853 
3854 SYSCALL_DEFINE2(mkdir, const char __user *, pathname, umode_t, mode)
3855 {
3856 	return do_mkdirat(AT_FDCWD, pathname, mode);
3857 }
3858 
3859 /**
3860  * vfs_rmdir - remove directory
3861  * @mnt_userns:	user namespace of the mount the inode was found from
3862  * @dir:	inode of @dentry
3863  * @dentry:	pointer to dentry of the base directory
3864  *
3865  * Remove a directory.
3866  *
3867  * If the inode has been found through an idmapped mount the user namespace of
3868  * the vfsmount must be passed through @mnt_userns. This function will then take
3869  * care to map the inode according to @mnt_userns before checking permissions.
3870  * On non-idmapped mounts or if permission checking is to be performed on the
3871  * raw inode simply passs init_user_ns.
3872  */
3873 int vfs_rmdir(struct user_namespace *mnt_userns, struct inode *dir,
3874 		     struct dentry *dentry)
3875 {
3876 	int error = may_delete(mnt_userns, dir, dentry, 1);
3877 
3878 	if (error)
3879 		return error;
3880 
3881 	if (!dir->i_op->rmdir)
3882 		return -EPERM;
3883 
3884 	dget(dentry);
3885 	inode_lock(dentry->d_inode);
3886 
3887 	error = -EBUSY;
3888 	if (is_local_mountpoint(dentry))
3889 		goto out;
3890 
3891 	error = security_inode_rmdir(dir, dentry);
3892 	if (error)
3893 		goto out;
3894 
3895 	error = dir->i_op->rmdir(dir, dentry);
3896 	if (error)
3897 		goto out;
3898 
3899 	shrink_dcache_parent(dentry);
3900 	dentry->d_inode->i_flags |= S_DEAD;
3901 	dont_mount(dentry);
3902 	detach_mounts(dentry);
3903 	fsnotify_rmdir(dir, dentry);
3904 
3905 out:
3906 	inode_unlock(dentry->d_inode);
3907 	dput(dentry);
3908 	if (!error)
3909 		d_delete(dentry);
3910 	return error;
3911 }
3912 EXPORT_SYMBOL(vfs_rmdir);
3913 
3914 long do_rmdir(int dfd, struct filename *name)
3915 {
3916 	struct user_namespace *mnt_userns;
3917 	int error = 0;
3918 	struct dentry *dentry;
3919 	struct path path;
3920 	struct qstr last;
3921 	int type;
3922 	unsigned int lookup_flags = 0;
3923 retry:
3924 	name = filename_parentat(dfd, name, lookup_flags,
3925 				&path, &last, &type);
3926 	if (IS_ERR(name))
3927 		return PTR_ERR(name);
3928 
3929 	switch (type) {
3930 	case LAST_DOTDOT:
3931 		error = -ENOTEMPTY;
3932 		goto exit1;
3933 	case LAST_DOT:
3934 		error = -EINVAL;
3935 		goto exit1;
3936 	case LAST_ROOT:
3937 		error = -EBUSY;
3938 		goto exit1;
3939 	}
3940 
3941 	error = mnt_want_write(path.mnt);
3942 	if (error)
3943 		goto exit1;
3944 
3945 	inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
3946 	dentry = __lookup_hash(&last, path.dentry, lookup_flags);
3947 	error = PTR_ERR(dentry);
3948 	if (IS_ERR(dentry))
3949 		goto exit2;
3950 	if (!dentry->d_inode) {
3951 		error = -ENOENT;
3952 		goto exit3;
3953 	}
3954 	error = security_path_rmdir(&path, dentry);
3955 	if (error)
3956 		goto exit3;
3957 	mnt_userns = mnt_user_ns(path.mnt);
3958 	error = vfs_rmdir(mnt_userns, path.dentry->d_inode, dentry);
3959 exit3:
3960 	dput(dentry);
3961 exit2:
3962 	inode_unlock(path.dentry->d_inode);
3963 	mnt_drop_write(path.mnt);
3964 exit1:
3965 	path_put(&path);
3966 	if (retry_estale(error, lookup_flags)) {
3967 		lookup_flags |= LOOKUP_REVAL;
3968 		goto retry;
3969 	}
3970 	putname(name);
3971 	return error;
3972 }
3973 
3974 SYSCALL_DEFINE1(rmdir, const char __user *, pathname)
3975 {
3976 	return do_rmdir(AT_FDCWD, getname(pathname));
3977 }
3978 
3979 /**
3980  * vfs_unlink - unlink a filesystem object
3981  * @mnt_userns:	user namespace of the mount the inode was found from
3982  * @dir:	parent directory
3983  * @dentry:	victim
3984  * @delegated_inode: returns victim inode, if the inode is delegated.
3985  *
3986  * The caller must hold dir->i_mutex.
3987  *
3988  * If vfs_unlink discovers a delegation, it will return -EWOULDBLOCK and
3989  * return a reference to the inode in delegated_inode.  The caller
3990  * should then break the delegation on that inode and retry.  Because
3991  * breaking a delegation may take a long time, the caller should drop
3992  * dir->i_mutex before doing so.
3993  *
3994  * Alternatively, a caller may pass NULL for delegated_inode.  This may
3995  * be appropriate for callers that expect the underlying filesystem not
3996  * to be NFS exported.
3997  *
3998  * If the inode has been found through an idmapped mount the user namespace of
3999  * the vfsmount must be passed through @mnt_userns. This function will then take
4000  * care to map the inode according to @mnt_userns before checking permissions.
4001  * On non-idmapped mounts or if permission checking is to be performed on the
4002  * raw inode simply passs init_user_ns.
4003  */
4004 int vfs_unlink(struct user_namespace *mnt_userns, struct inode *dir,
4005 	       struct dentry *dentry, struct inode **delegated_inode)
4006 {
4007 	struct inode *target = dentry->d_inode;
4008 	int error = may_delete(mnt_userns, dir, dentry, 0);
4009 
4010 	if (error)
4011 		return error;
4012 
4013 	if (!dir->i_op->unlink)
4014 		return -EPERM;
4015 
4016 	inode_lock(target);
4017 	if (is_local_mountpoint(dentry))
4018 		error = -EBUSY;
4019 	else {
4020 		error = security_inode_unlink(dir, dentry);
4021 		if (!error) {
4022 			error = try_break_deleg(target, delegated_inode);
4023 			if (error)
4024 				goto out;
4025 			error = dir->i_op->unlink(dir, dentry);
4026 			if (!error) {
4027 				dont_mount(dentry);
4028 				detach_mounts(dentry);
4029 				fsnotify_unlink(dir, dentry);
4030 			}
4031 		}
4032 	}
4033 out:
4034 	inode_unlock(target);
4035 
4036 	/* We don't d_delete() NFS sillyrenamed files--they still exist. */
4037 	if (!error && !(dentry->d_flags & DCACHE_NFSFS_RENAMED)) {
4038 		fsnotify_link_count(target);
4039 		d_delete(dentry);
4040 	}
4041 
4042 	return error;
4043 }
4044 EXPORT_SYMBOL(vfs_unlink);
4045 
4046 /*
4047  * Make sure that the actual truncation of the file will occur outside its
4048  * directory's i_mutex.  Truncate can take a long time if there is a lot of
4049  * writeout happening, and we don't want to prevent access to the directory
4050  * while waiting on the I/O.
4051  */
4052 long do_unlinkat(int dfd, struct filename *name)
4053 {
4054 	int error;
4055 	struct dentry *dentry;
4056 	struct path path;
4057 	struct qstr last;
4058 	int type;
4059 	struct inode *inode = NULL;
4060 	struct inode *delegated_inode = NULL;
4061 	unsigned int lookup_flags = 0;
4062 retry:
4063 	name = filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
4064 	if (IS_ERR(name))
4065 		return PTR_ERR(name);
4066 
4067 	error = -EISDIR;
4068 	if (type != LAST_NORM)
4069 		goto exit1;
4070 
4071 	error = mnt_want_write(path.mnt);
4072 	if (error)
4073 		goto exit1;
4074 retry_deleg:
4075 	inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
4076 	dentry = __lookup_hash(&last, path.dentry, lookup_flags);
4077 	error = PTR_ERR(dentry);
4078 	if (!IS_ERR(dentry)) {
4079 		struct user_namespace *mnt_userns;
4080 
4081 		/* Why not before? Because we want correct error value */
4082 		if (last.name[last.len])
4083 			goto slashes;
4084 		inode = dentry->d_inode;
4085 		if (d_is_negative(dentry))
4086 			goto slashes;
4087 		ihold(inode);
4088 		error = security_path_unlink(&path, dentry);
4089 		if (error)
4090 			goto exit2;
4091 		mnt_userns = mnt_user_ns(path.mnt);
4092 		error = vfs_unlink(mnt_userns, path.dentry->d_inode, dentry,
4093 				   &delegated_inode);
4094 exit2:
4095 		dput(dentry);
4096 	}
4097 	inode_unlock(path.dentry->d_inode);
4098 	if (inode)
4099 		iput(inode);	/* truncate the inode here */
4100 	inode = NULL;
4101 	if (delegated_inode) {
4102 		error = break_deleg_wait(&delegated_inode);
4103 		if (!error)
4104 			goto retry_deleg;
4105 	}
4106 	mnt_drop_write(path.mnt);
4107 exit1:
4108 	path_put(&path);
4109 	if (retry_estale(error, lookup_flags)) {
4110 		lookup_flags |= LOOKUP_REVAL;
4111 		inode = NULL;
4112 		goto retry;
4113 	}
4114 	putname(name);
4115 	return error;
4116 
4117 slashes:
4118 	if (d_is_negative(dentry))
4119 		error = -ENOENT;
4120 	else if (d_is_dir(dentry))
4121 		error = -EISDIR;
4122 	else
4123 		error = -ENOTDIR;
4124 	goto exit2;
4125 }
4126 
4127 SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag)
4128 {
4129 	if ((flag & ~AT_REMOVEDIR) != 0)
4130 		return -EINVAL;
4131 
4132 	if (flag & AT_REMOVEDIR)
4133 		return do_rmdir(dfd, getname(pathname));
4134 	return do_unlinkat(dfd, getname(pathname));
4135 }
4136 
4137 SYSCALL_DEFINE1(unlink, const char __user *, pathname)
4138 {
4139 	return do_unlinkat(AT_FDCWD, getname(pathname));
4140 }
4141 
4142 /**
4143  * vfs_symlink - create symlink
4144  * @mnt_userns:	user namespace of the mount the inode was found from
4145  * @dir:	inode of @dentry
4146  * @dentry:	pointer to dentry of the base directory
4147  * @oldname:	name of the file to link to
4148  *
4149  * Create a symlink.
4150  *
4151  * If the inode has been found through an idmapped mount the user namespace of
4152  * the vfsmount must be passed through @mnt_userns. This function will then take
4153  * care to map the inode according to @mnt_userns before checking permissions.
4154  * On non-idmapped mounts or if permission checking is to be performed on the
4155  * raw inode simply passs init_user_ns.
4156  */
4157 int vfs_symlink(struct user_namespace *mnt_userns, struct inode *dir,
4158 		struct dentry *dentry, const char *oldname)
4159 {
4160 	int error = may_create(mnt_userns, dir, dentry);
4161 
4162 	if (error)
4163 		return error;
4164 
4165 	if (!dir->i_op->symlink)
4166 		return -EPERM;
4167 
4168 	error = security_inode_symlink(dir, dentry, oldname);
4169 	if (error)
4170 		return error;
4171 
4172 	error = dir->i_op->symlink(mnt_userns, dir, dentry, oldname);
4173 	if (!error)
4174 		fsnotify_create(dir, dentry);
4175 	return error;
4176 }
4177 EXPORT_SYMBOL(vfs_symlink);
4178 
4179 static long do_symlinkat(const char __user *oldname, int newdfd,
4180 		  const char __user *newname)
4181 {
4182 	int error;
4183 	struct filename *from;
4184 	struct dentry *dentry;
4185 	struct path path;
4186 	unsigned int lookup_flags = 0;
4187 
4188 	from = getname(oldname);
4189 	if (IS_ERR(from))
4190 		return PTR_ERR(from);
4191 retry:
4192 	dentry = user_path_create(newdfd, newname, &path, lookup_flags);
4193 	error = PTR_ERR(dentry);
4194 	if (IS_ERR(dentry))
4195 		goto out_putname;
4196 
4197 	error = security_path_symlink(&path, dentry, from->name);
4198 	if (!error) {
4199 		struct user_namespace *mnt_userns;
4200 
4201 		mnt_userns = mnt_user_ns(path.mnt);
4202 		error = vfs_symlink(mnt_userns, path.dentry->d_inode, dentry,
4203 				    from->name);
4204 	}
4205 	done_path_create(&path, dentry);
4206 	if (retry_estale(error, lookup_flags)) {
4207 		lookup_flags |= LOOKUP_REVAL;
4208 		goto retry;
4209 	}
4210 out_putname:
4211 	putname(from);
4212 	return error;
4213 }
4214 
4215 SYSCALL_DEFINE3(symlinkat, const char __user *, oldname,
4216 		int, newdfd, const char __user *, newname)
4217 {
4218 	return do_symlinkat(oldname, newdfd, newname);
4219 }
4220 
4221 SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname)
4222 {
4223 	return do_symlinkat(oldname, AT_FDCWD, newname);
4224 }
4225 
4226 /**
4227  * vfs_link - create a new link
4228  * @old_dentry:	object to be linked
4229  * @mnt_userns:	the user namespace of the mount
4230  * @dir:	new parent
4231  * @new_dentry:	where to create the new link
4232  * @delegated_inode: returns inode needing a delegation break
4233  *
4234  * The caller must hold dir->i_mutex
4235  *
4236  * If vfs_link discovers a delegation on the to-be-linked file in need
4237  * of breaking, it will return -EWOULDBLOCK and return a reference to the
4238  * inode in delegated_inode.  The caller should then break the delegation
4239  * and retry.  Because breaking a delegation may take a long time, the
4240  * caller should drop the i_mutex before doing so.
4241  *
4242  * Alternatively, a caller may pass NULL for delegated_inode.  This may
4243  * be appropriate for callers that expect the underlying filesystem not
4244  * to be NFS exported.
4245  *
4246  * If the inode has been found through an idmapped mount the user namespace of
4247  * the vfsmount must be passed through @mnt_userns. This function will then take
4248  * care to map the inode according to @mnt_userns before checking permissions.
4249  * On non-idmapped mounts or if permission checking is to be performed on the
4250  * raw inode simply passs init_user_ns.
4251  */
4252 int vfs_link(struct dentry *old_dentry, struct user_namespace *mnt_userns,
4253 	     struct inode *dir, struct dentry *new_dentry,
4254 	     struct inode **delegated_inode)
4255 {
4256 	struct inode *inode = old_dentry->d_inode;
4257 	unsigned max_links = dir->i_sb->s_max_links;
4258 	int error;
4259 
4260 	if (!inode)
4261 		return -ENOENT;
4262 
4263 	error = may_create(mnt_userns, dir, new_dentry);
4264 	if (error)
4265 		return error;
4266 
4267 	if (dir->i_sb != inode->i_sb)
4268 		return -EXDEV;
4269 
4270 	/*
4271 	 * A link to an append-only or immutable file cannot be created.
4272 	 */
4273 	if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
4274 		return -EPERM;
4275 	/*
4276 	 * Updating the link count will likely cause i_uid and i_gid to
4277 	 * be writen back improperly if their true value is unknown to
4278 	 * the vfs.
4279 	 */
4280 	if (HAS_UNMAPPED_ID(mnt_userns, inode))
4281 		return -EPERM;
4282 	if (!dir->i_op->link)
4283 		return -EPERM;
4284 	if (S_ISDIR(inode->i_mode))
4285 		return -EPERM;
4286 
4287 	error = security_inode_link(old_dentry, dir, new_dentry);
4288 	if (error)
4289 		return error;
4290 
4291 	inode_lock(inode);
4292 	/* Make sure we don't allow creating hardlink to an unlinked file */
4293 	if (inode->i_nlink == 0 && !(inode->i_state & I_LINKABLE))
4294 		error =  -ENOENT;
4295 	else if (max_links && inode->i_nlink >= max_links)
4296 		error = -EMLINK;
4297 	else {
4298 		error = try_break_deleg(inode, delegated_inode);
4299 		if (!error)
4300 			error = dir->i_op->link(old_dentry, dir, new_dentry);
4301 	}
4302 
4303 	if (!error && (inode->i_state & I_LINKABLE)) {
4304 		spin_lock(&inode->i_lock);
4305 		inode->i_state &= ~I_LINKABLE;
4306 		spin_unlock(&inode->i_lock);
4307 	}
4308 	inode_unlock(inode);
4309 	if (!error)
4310 		fsnotify_link(dir, inode, new_dentry);
4311 	return error;
4312 }
4313 EXPORT_SYMBOL(vfs_link);
4314 
4315 /*
4316  * Hardlinks are often used in delicate situations.  We avoid
4317  * security-related surprises by not following symlinks on the
4318  * newname.  --KAB
4319  *
4320  * We don't follow them on the oldname either to be compatible
4321  * with linux 2.0, and to avoid hard-linking to directories
4322  * and other special files.  --ADM
4323  */
4324 static int do_linkat(int olddfd, const char __user *oldname, int newdfd,
4325 	      const char __user *newname, int flags)
4326 {
4327 	struct user_namespace *mnt_userns;
4328 	struct dentry *new_dentry;
4329 	struct path old_path, new_path;
4330 	struct inode *delegated_inode = NULL;
4331 	int how = 0;
4332 	int error;
4333 
4334 	if ((flags & ~(AT_SYMLINK_FOLLOW | AT_EMPTY_PATH)) != 0)
4335 		return -EINVAL;
4336 	/*
4337 	 * To use null names we require CAP_DAC_READ_SEARCH
4338 	 * This ensures that not everyone will be able to create
4339 	 * handlink using the passed filedescriptor.
4340 	 */
4341 	if (flags & AT_EMPTY_PATH) {
4342 		if (!capable(CAP_DAC_READ_SEARCH))
4343 			return -ENOENT;
4344 		how = LOOKUP_EMPTY;
4345 	}
4346 
4347 	if (flags & AT_SYMLINK_FOLLOW)
4348 		how |= LOOKUP_FOLLOW;
4349 retry:
4350 	error = user_path_at(olddfd, oldname, how, &old_path);
4351 	if (error)
4352 		return error;
4353 
4354 	new_dentry = user_path_create(newdfd, newname, &new_path,
4355 					(how & LOOKUP_REVAL));
4356 	error = PTR_ERR(new_dentry);
4357 	if (IS_ERR(new_dentry))
4358 		goto out;
4359 
4360 	error = -EXDEV;
4361 	if (old_path.mnt != new_path.mnt)
4362 		goto out_dput;
4363 	mnt_userns = mnt_user_ns(new_path.mnt);
4364 	error = may_linkat(mnt_userns, &old_path);
4365 	if (unlikely(error))
4366 		goto out_dput;
4367 	error = security_path_link(old_path.dentry, &new_path, new_dentry);
4368 	if (error)
4369 		goto out_dput;
4370 	error = vfs_link(old_path.dentry, mnt_userns, new_path.dentry->d_inode,
4371 			 new_dentry, &delegated_inode);
4372 out_dput:
4373 	done_path_create(&new_path, new_dentry);
4374 	if (delegated_inode) {
4375 		error = break_deleg_wait(&delegated_inode);
4376 		if (!error) {
4377 			path_put(&old_path);
4378 			goto retry;
4379 		}
4380 	}
4381 	if (retry_estale(error, how)) {
4382 		path_put(&old_path);
4383 		how |= LOOKUP_REVAL;
4384 		goto retry;
4385 	}
4386 out:
4387 	path_put(&old_path);
4388 
4389 	return error;
4390 }
4391 
4392 SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname,
4393 		int, newdfd, const char __user *, newname, int, flags)
4394 {
4395 	return do_linkat(olddfd, oldname, newdfd, newname, flags);
4396 }
4397 
4398 SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname)
4399 {
4400 	return do_linkat(AT_FDCWD, oldname, AT_FDCWD, newname, 0);
4401 }
4402 
4403 /**
4404  * vfs_rename - rename a filesystem object
4405  * @rd:		pointer to &struct renamedata info
4406  *
4407  * The caller must hold multiple mutexes--see lock_rename()).
4408  *
4409  * If vfs_rename discovers a delegation in need of breaking at either
4410  * the source or destination, it will return -EWOULDBLOCK and return a
4411  * reference to the inode in delegated_inode.  The caller should then
4412  * break the delegation and retry.  Because breaking a delegation may
4413  * take a long time, the caller should drop all locks before doing
4414  * so.
4415  *
4416  * Alternatively, a caller may pass NULL for delegated_inode.  This may
4417  * be appropriate for callers that expect the underlying filesystem not
4418  * to be NFS exported.
4419  *
4420  * The worst of all namespace operations - renaming directory. "Perverted"
4421  * doesn't even start to describe it. Somebody in UCB had a heck of a trip...
4422  * Problems:
4423  *
4424  *	a) we can get into loop creation.
4425  *	b) race potential - two innocent renames can create a loop together.
4426  *	   That's where 4.4 screws up. Current fix: serialization on
4427  *	   sb->s_vfs_rename_mutex. We might be more accurate, but that's another
4428  *	   story.
4429  *	c) we have to lock _four_ objects - parents and victim (if it exists),
4430  *	   and source (if it is not a directory).
4431  *	   And that - after we got ->i_mutex on parents (until then we don't know
4432  *	   whether the target exists).  Solution: try to be smart with locking
4433  *	   order for inodes.  We rely on the fact that tree topology may change
4434  *	   only under ->s_vfs_rename_mutex _and_ that parent of the object we
4435  *	   move will be locked.  Thus we can rank directories by the tree
4436  *	   (ancestors first) and rank all non-directories after them.
4437  *	   That works since everybody except rename does "lock parent, lookup,
4438  *	   lock child" and rename is under ->s_vfs_rename_mutex.
4439  *	   HOWEVER, it relies on the assumption that any object with ->lookup()
4440  *	   has no more than 1 dentry.  If "hybrid" objects will ever appear,
4441  *	   we'd better make sure that there's no link(2) for them.
4442  *	d) conversion from fhandle to dentry may come in the wrong moment - when
4443  *	   we are removing the target. Solution: we will have to grab ->i_mutex
4444  *	   in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on
4445  *	   ->i_mutex on parents, which works but leads to some truly excessive
4446  *	   locking].
4447  */
4448 int vfs_rename(struct renamedata *rd)
4449 {
4450 	int error;
4451 	struct inode *old_dir = rd->old_dir, *new_dir = rd->new_dir;
4452 	struct dentry *old_dentry = rd->old_dentry;
4453 	struct dentry *new_dentry = rd->new_dentry;
4454 	struct inode **delegated_inode = rd->delegated_inode;
4455 	unsigned int flags = rd->flags;
4456 	bool is_dir = d_is_dir(old_dentry);
4457 	struct inode *source = old_dentry->d_inode;
4458 	struct inode *target = new_dentry->d_inode;
4459 	bool new_is_dir = false;
4460 	unsigned max_links = new_dir->i_sb->s_max_links;
4461 	struct name_snapshot old_name;
4462 
4463 	if (source == target)
4464 		return 0;
4465 
4466 	error = may_delete(rd->old_mnt_userns, old_dir, old_dentry, is_dir);
4467 	if (error)
4468 		return error;
4469 
4470 	if (!target) {
4471 		error = may_create(rd->new_mnt_userns, new_dir, new_dentry);
4472 	} else {
4473 		new_is_dir = d_is_dir(new_dentry);
4474 
4475 		if (!(flags & RENAME_EXCHANGE))
4476 			error = may_delete(rd->new_mnt_userns, new_dir,
4477 					   new_dentry, is_dir);
4478 		else
4479 			error = may_delete(rd->new_mnt_userns, new_dir,
4480 					   new_dentry, new_is_dir);
4481 	}
4482 	if (error)
4483 		return error;
4484 
4485 	if (!old_dir->i_op->rename)
4486 		return -EPERM;
4487 
4488 	/*
4489 	 * If we are going to change the parent - check write permissions,
4490 	 * we'll need to flip '..'.
4491 	 */
4492 	if (new_dir != old_dir) {
4493 		if (is_dir) {
4494 			error = inode_permission(rd->old_mnt_userns, source,
4495 						 MAY_WRITE);
4496 			if (error)
4497 				return error;
4498 		}
4499 		if ((flags & RENAME_EXCHANGE) && new_is_dir) {
4500 			error = inode_permission(rd->new_mnt_userns, target,
4501 						 MAY_WRITE);
4502 			if (error)
4503 				return error;
4504 		}
4505 	}
4506 
4507 	error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,
4508 				      flags);
4509 	if (error)
4510 		return error;
4511 
4512 	take_dentry_name_snapshot(&old_name, old_dentry);
4513 	dget(new_dentry);
4514 	if (!is_dir || (flags & RENAME_EXCHANGE))
4515 		lock_two_nondirectories(source, target);
4516 	else if (target)
4517 		inode_lock(target);
4518 
4519 	error = -EBUSY;
4520 	if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
4521 		goto out;
4522 
4523 	if (max_links && new_dir != old_dir) {
4524 		error = -EMLINK;
4525 		if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)
4526 			goto out;
4527 		if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&
4528 		    old_dir->i_nlink >= max_links)
4529 			goto out;
4530 	}
4531 	if (!is_dir) {
4532 		error = try_break_deleg(source, delegated_inode);
4533 		if (error)
4534 			goto out;
4535 	}
4536 	if (target && !new_is_dir) {
4537 		error = try_break_deleg(target, delegated_inode);
4538 		if (error)
4539 			goto out;
4540 	}
4541 	error = old_dir->i_op->rename(rd->new_mnt_userns, old_dir, old_dentry,
4542 				      new_dir, new_dentry, flags);
4543 	if (error)
4544 		goto out;
4545 
4546 	if (!(flags & RENAME_EXCHANGE) && target) {
4547 		if (is_dir) {
4548 			shrink_dcache_parent(new_dentry);
4549 			target->i_flags |= S_DEAD;
4550 		}
4551 		dont_mount(new_dentry);
4552 		detach_mounts(new_dentry);
4553 	}
4554 	if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {
4555 		if (!(flags & RENAME_EXCHANGE))
4556 			d_move(old_dentry, new_dentry);
4557 		else
4558 			d_exchange(old_dentry, new_dentry);
4559 	}
4560 out:
4561 	if (!is_dir || (flags & RENAME_EXCHANGE))
4562 		unlock_two_nondirectories(source, target);
4563 	else if (target)
4564 		inode_unlock(target);
4565 	dput(new_dentry);
4566 	if (!error) {
4567 		fsnotify_move(old_dir, new_dir, &old_name.name, is_dir,
4568 			      !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);
4569 		if (flags & RENAME_EXCHANGE) {
4570 			fsnotify_move(new_dir, old_dir, &old_dentry->d_name,
4571 				      new_is_dir, NULL, new_dentry);
4572 		}
4573 	}
4574 	release_dentry_name_snapshot(&old_name);
4575 
4576 	return error;
4577 }
4578 EXPORT_SYMBOL(vfs_rename);
4579 
4580 int do_renameat2(int olddfd, struct filename *from, int newdfd,
4581 		 struct filename *to, unsigned int flags)
4582 {
4583 	struct renamedata rd;
4584 	struct dentry *old_dentry, *new_dentry;
4585 	struct dentry *trap;
4586 	struct path old_path, new_path;
4587 	struct qstr old_last, new_last;
4588 	int old_type, new_type;
4589 	struct inode *delegated_inode = NULL;
4590 	unsigned int lookup_flags = 0, target_flags = LOOKUP_RENAME_TARGET;
4591 	bool should_retry = false;
4592 	int error = -EINVAL;
4593 
4594 	if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
4595 		goto put_both;
4596 
4597 	if ((flags & (RENAME_NOREPLACE | RENAME_WHITEOUT)) &&
4598 	    (flags & RENAME_EXCHANGE))
4599 		goto put_both;
4600 
4601 	if (flags & RENAME_EXCHANGE)
4602 		target_flags = 0;
4603 
4604 retry:
4605 	from = filename_parentat(olddfd, from, lookup_flags, &old_path,
4606 					&old_last, &old_type);
4607 	if (IS_ERR(from)) {
4608 		error = PTR_ERR(from);
4609 		goto put_new;
4610 	}
4611 
4612 	to = filename_parentat(newdfd, to, lookup_flags, &new_path, &new_last,
4613 				&new_type);
4614 	if (IS_ERR(to)) {
4615 		error = PTR_ERR(to);
4616 		goto exit1;
4617 	}
4618 
4619 	error = -EXDEV;
4620 	if (old_path.mnt != new_path.mnt)
4621 		goto exit2;
4622 
4623 	error = -EBUSY;
4624 	if (old_type != LAST_NORM)
4625 		goto exit2;
4626 
4627 	if (flags & RENAME_NOREPLACE)
4628 		error = -EEXIST;
4629 	if (new_type != LAST_NORM)
4630 		goto exit2;
4631 
4632 	error = mnt_want_write(old_path.mnt);
4633 	if (error)
4634 		goto exit2;
4635 
4636 retry_deleg:
4637 	trap = lock_rename(new_path.dentry, old_path.dentry);
4638 
4639 	old_dentry = __lookup_hash(&old_last, old_path.dentry, lookup_flags);
4640 	error = PTR_ERR(old_dentry);
4641 	if (IS_ERR(old_dentry))
4642 		goto exit3;
4643 	/* source must exist */
4644 	error = -ENOENT;
4645 	if (d_is_negative(old_dentry))
4646 		goto exit4;
4647 	new_dentry = __lookup_hash(&new_last, new_path.dentry, lookup_flags | target_flags);
4648 	error = PTR_ERR(new_dentry);
4649 	if (IS_ERR(new_dentry))
4650 		goto exit4;
4651 	error = -EEXIST;
4652 	if ((flags & RENAME_NOREPLACE) && d_is_positive(new_dentry))
4653 		goto exit5;
4654 	if (flags & RENAME_EXCHANGE) {
4655 		error = -ENOENT;
4656 		if (d_is_negative(new_dentry))
4657 			goto exit5;
4658 
4659 		if (!d_is_dir(new_dentry)) {
4660 			error = -ENOTDIR;
4661 			if (new_last.name[new_last.len])
4662 				goto exit5;
4663 		}
4664 	}
4665 	/* unless the source is a directory trailing slashes give -ENOTDIR */
4666 	if (!d_is_dir(old_dentry)) {
4667 		error = -ENOTDIR;
4668 		if (old_last.name[old_last.len])
4669 			goto exit5;
4670 		if (!(flags & RENAME_EXCHANGE) && new_last.name[new_last.len])
4671 			goto exit5;
4672 	}
4673 	/* source should not be ancestor of target */
4674 	error = -EINVAL;
4675 	if (old_dentry == trap)
4676 		goto exit5;
4677 	/* target should not be an ancestor of source */
4678 	if (!(flags & RENAME_EXCHANGE))
4679 		error = -ENOTEMPTY;
4680 	if (new_dentry == trap)
4681 		goto exit5;
4682 
4683 	error = security_path_rename(&old_path, old_dentry,
4684 				     &new_path, new_dentry, flags);
4685 	if (error)
4686 		goto exit5;
4687 
4688 	rd.old_dir	   = old_path.dentry->d_inode;
4689 	rd.old_dentry	   = old_dentry;
4690 	rd.old_mnt_userns  = mnt_user_ns(old_path.mnt);
4691 	rd.new_dir	   = new_path.dentry->d_inode;
4692 	rd.new_dentry	   = new_dentry;
4693 	rd.new_mnt_userns  = mnt_user_ns(new_path.mnt);
4694 	rd.delegated_inode = &delegated_inode;
4695 	rd.flags	   = flags;
4696 	error = vfs_rename(&rd);
4697 exit5:
4698 	dput(new_dentry);
4699 exit4:
4700 	dput(old_dentry);
4701 exit3:
4702 	unlock_rename(new_path.dentry, old_path.dentry);
4703 	if (delegated_inode) {
4704 		error = break_deleg_wait(&delegated_inode);
4705 		if (!error)
4706 			goto retry_deleg;
4707 	}
4708 	mnt_drop_write(old_path.mnt);
4709 exit2:
4710 	if (retry_estale(error, lookup_flags))
4711 		should_retry = true;
4712 	path_put(&new_path);
4713 exit1:
4714 	path_put(&old_path);
4715 	if (should_retry) {
4716 		should_retry = false;
4717 		lookup_flags |= LOOKUP_REVAL;
4718 		goto retry;
4719 	}
4720 put_both:
4721 	if (!IS_ERR(from))
4722 		putname(from);
4723 put_new:
4724 	if (!IS_ERR(to))
4725 		putname(to);
4726 	return error;
4727 }
4728 
4729 SYSCALL_DEFINE5(renameat2, int, olddfd, const char __user *, oldname,
4730 		int, newdfd, const char __user *, newname, unsigned int, flags)
4731 {
4732 	return do_renameat2(olddfd, getname(oldname), newdfd, getname(newname),
4733 				flags);
4734 }
4735 
4736 SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname,
4737 		int, newdfd, const char __user *, newname)
4738 {
4739 	return do_renameat2(olddfd, getname(oldname), newdfd, getname(newname),
4740 				0);
4741 }
4742 
4743 SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname)
4744 {
4745 	return do_renameat2(AT_FDCWD, getname(oldname), AT_FDCWD,
4746 				getname(newname), 0);
4747 }
4748 
4749 int readlink_copy(char __user *buffer, int buflen, const char *link)
4750 {
4751 	int len = PTR_ERR(link);
4752 	if (IS_ERR(link))
4753 		goto out;
4754 
4755 	len = strlen(link);
4756 	if (len > (unsigned) buflen)
4757 		len = buflen;
4758 	if (copy_to_user(buffer, link, len))
4759 		len = -EFAULT;
4760 out:
4761 	return len;
4762 }
4763 
4764 /**
4765  * vfs_readlink - copy symlink body into userspace buffer
4766  * @dentry: dentry on which to get symbolic link
4767  * @buffer: user memory pointer
4768  * @buflen: size of buffer
4769  *
4770  * Does not touch atime.  That's up to the caller if necessary
4771  *
4772  * Does not call security hook.
4773  */
4774 int vfs_readlink(struct dentry *dentry, char __user *buffer, int buflen)
4775 {
4776 	struct inode *inode = d_inode(dentry);
4777 	DEFINE_DELAYED_CALL(done);
4778 	const char *link;
4779 	int res;
4780 
4781 	if (unlikely(!(inode->i_opflags & IOP_DEFAULT_READLINK))) {
4782 		if (unlikely(inode->i_op->readlink))
4783 			return inode->i_op->readlink(dentry, buffer, buflen);
4784 
4785 		if (!d_is_symlink(dentry))
4786 			return -EINVAL;
4787 
4788 		spin_lock(&inode->i_lock);
4789 		inode->i_opflags |= IOP_DEFAULT_READLINK;
4790 		spin_unlock(&inode->i_lock);
4791 	}
4792 
4793 	link = READ_ONCE(inode->i_link);
4794 	if (!link) {
4795 		link = inode->i_op->get_link(dentry, inode, &done);
4796 		if (IS_ERR(link))
4797 			return PTR_ERR(link);
4798 	}
4799 	res = readlink_copy(buffer, buflen, link);
4800 	do_delayed_call(&done);
4801 	return res;
4802 }
4803 EXPORT_SYMBOL(vfs_readlink);
4804 
4805 /**
4806  * vfs_get_link - get symlink body
4807  * @dentry: dentry on which to get symbolic link
4808  * @done: caller needs to free returned data with this
4809  *
4810  * Calls security hook and i_op->get_link() on the supplied inode.
4811  *
4812  * It does not touch atime.  That's up to the caller if necessary.
4813  *
4814  * Does not work on "special" symlinks like /proc/$$/fd/N
4815  */
4816 const char *vfs_get_link(struct dentry *dentry, struct delayed_call *done)
4817 {
4818 	const char *res = ERR_PTR(-EINVAL);
4819 	struct inode *inode = d_inode(dentry);
4820 
4821 	if (d_is_symlink(dentry)) {
4822 		res = ERR_PTR(security_inode_readlink(dentry));
4823 		if (!res)
4824 			res = inode->i_op->get_link(dentry, inode, done);
4825 	}
4826 	return res;
4827 }
4828 EXPORT_SYMBOL(vfs_get_link);
4829 
4830 /* get the link contents into pagecache */
4831 const char *page_get_link(struct dentry *dentry, struct inode *inode,
4832 			  struct delayed_call *callback)
4833 {
4834 	char *kaddr;
4835 	struct page *page;
4836 	struct address_space *mapping = inode->i_mapping;
4837 
4838 	if (!dentry) {
4839 		page = find_get_page(mapping, 0);
4840 		if (!page)
4841 			return ERR_PTR(-ECHILD);
4842 		if (!PageUptodate(page)) {
4843 			put_page(page);
4844 			return ERR_PTR(-ECHILD);
4845 		}
4846 	} else {
4847 		page = read_mapping_page(mapping, 0, NULL);
4848 		if (IS_ERR(page))
4849 			return (char*)page;
4850 	}
4851 	set_delayed_call(callback, page_put_link, page);
4852 	BUG_ON(mapping_gfp_mask(mapping) & __GFP_HIGHMEM);
4853 	kaddr = page_address(page);
4854 	nd_terminate_link(kaddr, inode->i_size, PAGE_SIZE - 1);
4855 	return kaddr;
4856 }
4857 
4858 EXPORT_SYMBOL(page_get_link);
4859 
4860 void page_put_link(void *arg)
4861 {
4862 	put_page(arg);
4863 }
4864 EXPORT_SYMBOL(page_put_link);
4865 
4866 int page_readlink(struct dentry *dentry, char __user *buffer, int buflen)
4867 {
4868 	DEFINE_DELAYED_CALL(done);
4869 	int res = readlink_copy(buffer, buflen,
4870 				page_get_link(dentry, d_inode(dentry),
4871 					      &done));
4872 	do_delayed_call(&done);
4873 	return res;
4874 }
4875 EXPORT_SYMBOL(page_readlink);
4876 
4877 /*
4878  * The nofs argument instructs pagecache_write_begin to pass AOP_FLAG_NOFS
4879  */
4880 int __page_symlink(struct inode *inode, const char *symname, int len, int nofs)
4881 {
4882 	struct address_space *mapping = inode->i_mapping;
4883 	struct page *page;
4884 	void *fsdata;
4885 	int err;
4886 	unsigned int flags = 0;
4887 	if (nofs)
4888 		flags |= AOP_FLAG_NOFS;
4889 
4890 retry:
4891 	err = pagecache_write_begin(NULL, mapping, 0, len-1,
4892 				flags, &page, &fsdata);
4893 	if (err)
4894 		goto fail;
4895 
4896 	memcpy(page_address(page), symname, len-1);
4897 
4898 	err = pagecache_write_end(NULL, mapping, 0, len-1, len-1,
4899 							page, fsdata);
4900 	if (err < 0)
4901 		goto fail;
4902 	if (err < len-1)
4903 		goto retry;
4904 
4905 	mark_inode_dirty(inode);
4906 	return 0;
4907 fail:
4908 	return err;
4909 }
4910 EXPORT_SYMBOL(__page_symlink);
4911 
4912 int page_symlink(struct inode *inode, const char *symname, int len)
4913 {
4914 	return __page_symlink(inode, symname, len,
4915 			!mapping_gfp_constraint(inode->i_mapping, __GFP_FS));
4916 }
4917 EXPORT_SYMBOL(page_symlink);
4918 
4919 const struct inode_operations page_symlink_inode_operations = {
4920 	.get_link	= page_get_link,
4921 };
4922 EXPORT_SYMBOL(page_symlink_inode_operations);
4923