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