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