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