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