xref: /linux/fs/namei.c (revision 26c9342bb761e463774a64fb6210b4f95f5bc035)
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_array(MAXSYMLINKS, sizeof(struct saved),
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 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 EXPORT_SYMBOL(lookup_one_qstr_excl);
1824 
1825 /**
1826  * lookup_fast - do fast lockless (but racy) lookup of a dentry
1827  * @nd: current nameidata
1828  *
1829  * Do a fast, but racy lookup in the dcache for the given dentry, and
1830  * revalidate it. Returns a valid dentry pointer or NULL if one wasn't
1831  * found. On error, an ERR_PTR will be returned.
1832  *
1833  * If this function returns a valid dentry and the walk is no longer
1834  * lazy, the dentry will carry a reference that must later be put. If
1835  * RCU mode is still in force, then this is not the case and the dentry
1836  * must be legitimized before use. If this returns NULL, then the walk
1837  * will no longer be in RCU mode.
1838  */
1839 static struct dentry *lookup_fast(struct nameidata *nd)
1840 {
1841 	struct dentry *dentry, *parent = nd->path.dentry;
1842 	int status = 1;
1843 
1844 	/*
1845 	 * Rename seqlock is not required here because in the off chance
1846 	 * of a false negative due to a concurrent rename, the caller is
1847 	 * going to fall back to non-racy lookup.
1848 	 */
1849 	if (nd->flags & LOOKUP_RCU) {
1850 		dentry = __d_lookup_rcu(parent, &nd->last, &nd->next_seq);
1851 		if (unlikely(!dentry)) {
1852 			if (!try_to_unlazy(nd))
1853 				return ERR_PTR(-ECHILD);
1854 			return NULL;
1855 		}
1856 
1857 		/*
1858 		 * This sequence count validates that the parent had no
1859 		 * changes while we did the lookup of the dentry above.
1860 		 */
1861 		if (read_seqcount_retry(&parent->d_seq, nd->seq))
1862 			return ERR_PTR(-ECHILD);
1863 
1864 		status = d_revalidate(nd->inode, &nd->last, dentry, nd->flags);
1865 		if (likely(status > 0))
1866 			return dentry;
1867 		if (!try_to_unlazy_next(nd, dentry))
1868 			return ERR_PTR(-ECHILD);
1869 		if (status == -ECHILD)
1870 			/* we'd been told to redo it in non-rcu mode */
1871 			status = d_revalidate(nd->inode, &nd->last,
1872 					      dentry, nd->flags);
1873 	} else {
1874 		dentry = __d_lookup(parent, &nd->last);
1875 		if (unlikely(!dentry))
1876 			return NULL;
1877 		status = d_revalidate(nd->inode, &nd->last, dentry, nd->flags);
1878 	}
1879 	if (unlikely(status <= 0)) {
1880 		if (!status)
1881 			d_invalidate(dentry);
1882 		dput(dentry);
1883 		return ERR_PTR(status);
1884 	}
1885 	return dentry;
1886 }
1887 
1888 /* Fast lookup failed, do it the slow way */
1889 static struct dentry *__lookup_slow(const struct qstr *name,
1890 				    struct dentry *dir,
1891 				    unsigned int flags)
1892 {
1893 	struct dentry *dentry, *old;
1894 	struct inode *inode = dir->d_inode;
1895 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
1896 
1897 	/* Don't go there if it's already dead */
1898 	if (unlikely(IS_DEADDIR(inode)))
1899 		return ERR_PTR(-ENOENT);
1900 again:
1901 	dentry = d_alloc_parallel(dir, name, &wq);
1902 	if (IS_ERR(dentry))
1903 		return dentry;
1904 	if (unlikely(!d_in_lookup(dentry))) {
1905 		int error = d_revalidate(inode, name, dentry, flags);
1906 		if (unlikely(error <= 0)) {
1907 			if (!error) {
1908 				d_invalidate(dentry);
1909 				dput(dentry);
1910 				goto again;
1911 			}
1912 			dput(dentry);
1913 			dentry = ERR_PTR(error);
1914 		}
1915 	} else {
1916 		old = inode->i_op->lookup(inode, dentry, flags);
1917 		d_lookup_done(dentry);
1918 		if (unlikely(old)) {
1919 			dput(dentry);
1920 			dentry = old;
1921 		}
1922 	}
1923 	return dentry;
1924 }
1925 
1926 static noinline struct dentry *lookup_slow(const struct qstr *name,
1927 				  struct dentry *dir,
1928 				  unsigned int flags)
1929 {
1930 	struct inode *inode = dir->d_inode;
1931 	struct dentry *res;
1932 	inode_lock_shared(inode);
1933 	res = __lookup_slow(name, dir, flags);
1934 	inode_unlock_shared(inode);
1935 	return res;
1936 }
1937 
1938 static struct dentry *lookup_slow_killable(const struct qstr *name,
1939 					   struct dentry *dir,
1940 					   unsigned int flags)
1941 {
1942 	struct inode *inode = dir->d_inode;
1943 	struct dentry *res;
1944 
1945 	if (inode_lock_shared_killable(inode))
1946 		return ERR_PTR(-EINTR);
1947 	res = __lookup_slow(name, dir, flags);
1948 	inode_unlock_shared(inode);
1949 	return res;
1950 }
1951 
1952 static inline int may_lookup(struct mnt_idmap *idmap,
1953 			     struct nameidata *restrict nd)
1954 {
1955 	int err, mask;
1956 
1957 	mask = nd->flags & LOOKUP_RCU ? MAY_NOT_BLOCK : 0;
1958 	err = lookup_inode_permission_may_exec(idmap, nd->inode, mask);
1959 	if (likely(!err))
1960 		return 0;
1961 
1962 	// If we failed, and we weren't in LOOKUP_RCU, it's final
1963 	if (!(nd->flags & LOOKUP_RCU))
1964 		return err;
1965 
1966 	// Drop out of RCU mode to make sure it wasn't transient
1967 	if (!try_to_unlazy(nd))
1968 		return -ECHILD;	// redo it all non-lazy
1969 
1970 	if (err != -ECHILD)	// hard error
1971 		return err;
1972 
1973 	return lookup_inode_permission_may_exec(idmap, nd->inode, 0);
1974 }
1975 
1976 static int reserve_stack(struct nameidata *nd, struct path *link)
1977 {
1978 	if (unlikely(nd->total_link_count++ >= MAXSYMLINKS))
1979 		return -ELOOP;
1980 
1981 	if (likely(nd->depth != EMBEDDED_LEVELS))
1982 		return 0;
1983 	if (likely(nd->stack != nd->internal))
1984 		return 0;
1985 	if (likely(nd_alloc_stack(nd)))
1986 		return 0;
1987 
1988 	if (nd->flags & LOOKUP_RCU) {
1989 		// we need to grab link before we do unlazy.  And we can't skip
1990 		// unlazy even if we fail to grab the link - cleanup needs it
1991 		bool grabbed_link = legitimize_path(nd, link, nd->next_seq);
1992 
1993 		if (!try_to_unlazy(nd) || !grabbed_link)
1994 			return -ECHILD;
1995 
1996 		if (nd_alloc_stack(nd))
1997 			return 0;
1998 	}
1999 	return -ENOMEM;
2000 }
2001 
2002 enum {WALK_TRAILING = 1, WALK_MORE = 2, WALK_NOFOLLOW = 4};
2003 
2004 static noinline const char *pick_link(struct nameidata *nd, struct path *link,
2005 		     struct inode *inode, int flags)
2006 {
2007 	struct saved *last;
2008 	const char *res;
2009 	int error;
2010 
2011 	if (nd->flags & LOOKUP_RCU) {
2012 		/* make sure that d_is_symlink from step_into_slowpath() matches the inode */
2013 		if (read_seqcount_retry(&link->dentry->d_seq, nd->next_seq))
2014 			return ERR_PTR(-ECHILD);
2015 	} else {
2016 		if (link->mnt == nd->path.mnt)
2017 			mntget(link->mnt);
2018 	}
2019 
2020 	error = reserve_stack(nd, link);
2021 	if (unlikely(error)) {
2022 		if (!(nd->flags & LOOKUP_RCU))
2023 			path_put(link);
2024 		return ERR_PTR(error);
2025 	}
2026 	last = nd->stack + nd->depth++;
2027 	last->link = *link;
2028 	clear_delayed_call(&last->done);
2029 	last->seq = nd->next_seq;
2030 
2031 	if (flags & WALK_TRAILING) {
2032 		error = may_follow_link(nd, inode);
2033 		if (unlikely(error))
2034 			return ERR_PTR(error);
2035 	}
2036 
2037 	if (unlikely(nd->flags & LOOKUP_NO_SYMLINKS) ||
2038 			unlikely(link->mnt->mnt_flags & MNT_NOSYMFOLLOW))
2039 		return ERR_PTR(-ELOOP);
2040 
2041 	if (unlikely(atime_needs_update(&last->link, inode))) {
2042 		if (nd->flags & LOOKUP_RCU) {
2043 			if (!try_to_unlazy(nd))
2044 				return ERR_PTR(-ECHILD);
2045 		}
2046 		touch_atime(&last->link);
2047 		cond_resched();
2048 	}
2049 
2050 	error = security_inode_follow_link(link->dentry, inode,
2051 					   nd->flags & LOOKUP_RCU);
2052 	if (unlikely(error))
2053 		return ERR_PTR(error);
2054 
2055 	res = READ_ONCE(inode->i_link);
2056 	if (!res) {
2057 		const char * (*get)(struct dentry *, struct inode *,
2058 				struct delayed_call *);
2059 		get = inode->i_op->get_link;
2060 		if (nd->flags & LOOKUP_RCU) {
2061 			res = get(NULL, inode, &last->done);
2062 			if (res == ERR_PTR(-ECHILD) && try_to_unlazy(nd))
2063 				res = get(link->dentry, inode, &last->done);
2064 		} else {
2065 			res = get(link->dentry, inode, &last->done);
2066 		}
2067 		if (!res)
2068 			goto all_done;
2069 		if (IS_ERR(res))
2070 			return res;
2071 	}
2072 	if (*res == '/') {
2073 		error = nd_jump_root(nd);
2074 		if (unlikely(error))
2075 			return ERR_PTR(error);
2076 		while (unlikely(*++res == '/'))
2077 			;
2078 	}
2079 	if (*res)
2080 		return res;
2081 all_done: // pure jump
2082 	put_link(nd);
2083 	return NULL;
2084 }
2085 
2086 /*
2087  * Do we need to follow links? We _really_ want to be able
2088  * to do this check without having to look at inode->i_op,
2089  * so we keep a cache of "no, this doesn't need follow_link"
2090  * for the common case.
2091  *
2092  * NOTE: dentry must be what nd->next_seq had been sampled from.
2093  */
2094 static noinline const char *step_into_slowpath(struct nameidata *nd, int flags,
2095 		     struct dentry *dentry)
2096 {
2097 	struct path path;
2098 	struct inode *inode;
2099 	int err;
2100 
2101 	err = handle_mounts(nd, dentry, &path);
2102 	if (unlikely(err < 0))
2103 		return ERR_PTR(err);
2104 	inode = path.dentry->d_inode;
2105 	if (likely(!d_is_symlink(path.dentry)) ||
2106 	   ((flags & WALK_TRAILING) && !(nd->flags & LOOKUP_FOLLOW)) ||
2107 	   (flags & WALK_NOFOLLOW)) {
2108 		/* not a symlink or should not follow */
2109 		if (nd->flags & LOOKUP_RCU) {
2110 			if (read_seqcount_retry(&path.dentry->d_seq, nd->next_seq))
2111 				return ERR_PTR(-ECHILD);
2112 			if (unlikely(!inode))
2113 				return ERR_PTR(-ENOENT);
2114 		} else {
2115 			dput(nd->path.dentry);
2116 			if (nd->path.mnt != path.mnt)
2117 				mntput(nd->path.mnt);
2118 		}
2119 		nd->path = path;
2120 		nd->inode = inode;
2121 		nd->seq = nd->next_seq;
2122 		return NULL;
2123 	}
2124 	return pick_link(nd, &path, inode, flags);
2125 }
2126 
2127 static __always_inline const char *step_into(struct nameidata *nd, int flags,
2128                     struct dentry *dentry)
2129 {
2130 	/*
2131 	 * In the common case we are in rcu-walk and traversing over a non-mounted on
2132 	 * directory (as opposed to e.g., a symlink).
2133 	 *
2134 	 * We can handle that and negative entries with the checks below.
2135 	 */
2136 	if (likely((nd->flags & LOOKUP_RCU) &&
2137 	    !d_managed(dentry) && !d_is_symlink(dentry))) {
2138 		struct inode *inode = dentry->d_inode;
2139 		if (read_seqcount_retry(&dentry->d_seq, nd->next_seq))
2140 			return ERR_PTR(-ECHILD);
2141 		if (unlikely(!inode))
2142 			return ERR_PTR(-ENOENT);
2143 		nd->path.dentry = dentry;
2144 		/* nd->path.mnt is retained on purpose */
2145 		nd->inode = inode;
2146 		nd->seq = nd->next_seq;
2147 		return NULL;
2148 	}
2149 	return step_into_slowpath(nd, flags, dentry);
2150 }
2151 
2152 static struct dentry *follow_dotdot_rcu(struct nameidata *nd)
2153 {
2154 	struct dentry *parent, *old;
2155 
2156 	if (path_equal(&nd->path, &nd->root))
2157 		goto in_root;
2158 	if (unlikely(nd->path.dentry == nd->path.mnt->mnt_root)) {
2159 		struct path path;
2160 		unsigned seq;
2161 		if (!choose_mountpoint_rcu(real_mount(nd->path.mnt),
2162 					   &nd->root, &path, &seq))
2163 			goto in_root;
2164 		if (unlikely(nd->flags & LOOKUP_NO_XDEV))
2165 			return ERR_PTR(-ECHILD);
2166 		nd->path = path;
2167 		nd->inode = path.dentry->d_inode;
2168 		nd->seq = seq;
2169 		// makes sure that non-RCU pathwalk could reach this state
2170 		if (read_seqretry(&mount_lock, nd->m_seq))
2171 			return ERR_PTR(-ECHILD);
2172 		/* we know that mountpoint was pinned */
2173 	}
2174 	old = nd->path.dentry;
2175 	parent = old->d_parent;
2176 	nd->next_seq = read_seqcount_begin(&parent->d_seq);
2177 	// makes sure that non-RCU pathwalk could reach this state
2178 	if (read_seqcount_retry(&old->d_seq, nd->seq))
2179 		return ERR_PTR(-ECHILD);
2180 	if (unlikely(!path_connected(nd->path.mnt, parent)))
2181 		return ERR_PTR(-ECHILD);
2182 	return parent;
2183 in_root:
2184 	if (read_seqretry(&mount_lock, nd->m_seq))
2185 		return ERR_PTR(-ECHILD);
2186 	if (unlikely(nd->flags & LOOKUP_BENEATH))
2187 		return ERR_PTR(-ECHILD);
2188 	nd->next_seq = nd->seq;
2189 	return nd->path.dentry;
2190 }
2191 
2192 static struct dentry *follow_dotdot(struct nameidata *nd)
2193 {
2194 	struct dentry *parent;
2195 
2196 	if (path_equal(&nd->path, &nd->root))
2197 		goto in_root;
2198 	if (unlikely(nd->path.dentry == nd->path.mnt->mnt_root)) {
2199 		struct path path;
2200 
2201 		if (!choose_mountpoint(real_mount(nd->path.mnt),
2202 				       &nd->root, &path))
2203 			goto in_root;
2204 		path_put(&nd->path);
2205 		nd->path = path;
2206 		nd->inode = path.dentry->d_inode;
2207 		if (unlikely(nd->flags & LOOKUP_NO_XDEV))
2208 			return ERR_PTR(-EXDEV);
2209 	}
2210 	/* rare case of legitimate dget_parent()... */
2211 	parent = dget_parent(nd->path.dentry);
2212 	if (unlikely(!path_connected(nd->path.mnt, parent))) {
2213 		dput(parent);
2214 		return ERR_PTR(-ENOENT);
2215 	}
2216 	return parent;
2217 
2218 in_root:
2219 	if (unlikely(nd->flags & LOOKUP_BENEATH))
2220 		return ERR_PTR(-EXDEV);
2221 	return dget(nd->path.dentry);
2222 }
2223 
2224 static const char *handle_dots(struct nameidata *nd, int type)
2225 {
2226 	if (type == LAST_DOTDOT) {
2227 		const char *error = NULL;
2228 		struct dentry *parent;
2229 
2230 		if (!nd->root.mnt) {
2231 			error = ERR_PTR(set_root(nd));
2232 			if (unlikely(error))
2233 				return error;
2234 		}
2235 		if (nd->flags & LOOKUP_RCU)
2236 			parent = follow_dotdot_rcu(nd);
2237 		else
2238 			parent = follow_dotdot(nd);
2239 		if (IS_ERR(parent))
2240 			return ERR_CAST(parent);
2241 		error = step_into(nd, WALK_NOFOLLOW, parent);
2242 		if (unlikely(error))
2243 			return error;
2244 
2245 		if (unlikely(nd->flags & LOOKUP_IS_SCOPED)) {
2246 			/*
2247 			 * If there was a racing rename or mount along our
2248 			 * path, then we can't be sure that ".." hasn't jumped
2249 			 * above nd->root (and so userspace should retry or use
2250 			 * some fallback).
2251 			 */
2252 			smp_rmb();
2253 			if (__read_seqcount_retry(&mount_lock.seqcount, nd->m_seq))
2254 				return ERR_PTR(-EAGAIN);
2255 			if (__read_seqcount_retry(&rename_lock.seqcount, nd->r_seq))
2256 				return ERR_PTR(-EAGAIN);
2257 		}
2258 	}
2259 	return NULL;
2260 }
2261 
2262 static __always_inline const char *walk_component(struct nameidata *nd, int flags)
2263 {
2264 	struct dentry *dentry;
2265 	/*
2266 	 * "." and ".." are special - ".." especially so because it has
2267 	 * to be able to know about the current root directory and
2268 	 * parent relationships.
2269 	 */
2270 	if (unlikely(nd->last_type != LAST_NORM)) {
2271 		if (unlikely(nd->depth) && !(flags & WALK_MORE))
2272 			put_link(nd);
2273 		return handle_dots(nd, nd->last_type);
2274 	}
2275 	dentry = lookup_fast(nd);
2276 	if (IS_ERR(dentry))
2277 		return ERR_CAST(dentry);
2278 	if (unlikely(!dentry)) {
2279 		dentry = lookup_slow(&nd->last, nd->path.dentry, nd->flags);
2280 		if (IS_ERR(dentry))
2281 			return ERR_CAST(dentry);
2282 	}
2283 	if (unlikely(nd->depth) && !(flags & WALK_MORE))
2284 		put_link(nd);
2285 	return step_into(nd, flags, dentry);
2286 }
2287 
2288 /*
2289  * We can do the critical dentry name comparison and hashing
2290  * operations one word at a time, but we are limited to:
2291  *
2292  * - Architectures with fast unaligned word accesses. We could
2293  *   do a "get_unaligned()" if this helps and is sufficiently
2294  *   fast.
2295  *
2296  * - non-CONFIG_DEBUG_PAGEALLOC configurations (so that we
2297  *   do not trap on the (extremely unlikely) case of a page
2298  *   crossing operation.
2299  *
2300  * - Furthermore, we need an efficient 64-bit compile for the
2301  *   64-bit case in order to generate the "number of bytes in
2302  *   the final mask". Again, that could be replaced with a
2303  *   efficient population count instruction or similar.
2304  */
2305 #ifdef CONFIG_DCACHE_WORD_ACCESS
2306 
2307 #include <asm/word-at-a-time.h>
2308 
2309 #ifdef HASH_MIX
2310 
2311 /* Architecture provides HASH_MIX and fold_hash() in <asm/hash.h> */
2312 
2313 #elif defined(CONFIG_64BIT)
2314 /*
2315  * Register pressure in the mixing function is an issue, particularly
2316  * on 32-bit x86, but almost any function requires one state value and
2317  * one temporary.  Instead, use a function designed for two state values
2318  * and no temporaries.
2319  *
2320  * This function cannot create a collision in only two iterations, so
2321  * we have two iterations to achieve avalanche.  In those two iterations,
2322  * we have six layers of mixing, which is enough to spread one bit's
2323  * influence out to 2^6 = 64 state bits.
2324  *
2325  * Rotate constants are scored by considering either 64 one-bit input
2326  * deltas or 64*63/2 = 2016 two-bit input deltas, and finding the
2327  * probability of that delta causing a change to each of the 128 output
2328  * bits, using a sample of random initial states.
2329  *
2330  * The Shannon entropy of the computed probabilities is then summed
2331  * to produce a score.  Ideally, any input change has a 50% chance of
2332  * toggling any given output bit.
2333  *
2334  * Mixing scores (in bits) for (12,45):
2335  * Input delta: 1-bit      2-bit
2336  * 1 round:     713.3    42542.6
2337  * 2 rounds:   2753.7   140389.8
2338  * 3 rounds:   5954.1   233458.2
2339  * 4 rounds:   7862.6   256672.2
2340  * Perfect:    8192     258048
2341  *            (64*128) (64*63/2 * 128)
2342  */
2343 #define HASH_MIX(x, y, a)	\
2344 	(	x ^= (a),	\
2345 	y ^= x,	x = rol64(x,12),\
2346 	x += y,	y = rol64(y,45),\
2347 	y *= 9			)
2348 
2349 /*
2350  * Fold two longs into one 32-bit hash value.  This must be fast, but
2351  * latency isn't quite as critical, as there is a fair bit of additional
2352  * work done before the hash value is used.
2353  */
2354 static inline unsigned int fold_hash(unsigned long x, unsigned long y)
2355 {
2356 	y ^= x * GOLDEN_RATIO_64;
2357 	y *= GOLDEN_RATIO_64;
2358 	return y >> 32;
2359 }
2360 
2361 #else	/* 32-bit case */
2362 
2363 /*
2364  * Mixing scores (in bits) for (7,20):
2365  * Input delta: 1-bit      2-bit
2366  * 1 round:     330.3     9201.6
2367  * 2 rounds:   1246.4    25475.4
2368  * 3 rounds:   1907.1    31295.1
2369  * 4 rounds:   2042.3    31718.6
2370  * Perfect:    2048      31744
2371  *            (32*64)   (32*31/2 * 64)
2372  */
2373 #define HASH_MIX(x, y, a)	\
2374 	(	x ^= (a),	\
2375 	y ^= x,	x = rol32(x, 7),\
2376 	x += y,	y = rol32(y,20),\
2377 	y *= 9			)
2378 
2379 static inline unsigned int fold_hash(unsigned long x, unsigned long y)
2380 {
2381 	/* Use arch-optimized multiply if one exists */
2382 	return __hash_32(y ^ __hash_32(x));
2383 }
2384 
2385 #endif
2386 
2387 /*
2388  * Return the hash of a string of known length.  This is carfully
2389  * designed to match hash_name(), which is the more critical function.
2390  * In particular, we must end by hashing a final word containing 0..7
2391  * payload bytes, to match the way that hash_name() iterates until it
2392  * finds the delimiter after the name.
2393  */
2394 unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
2395 {
2396 	unsigned long a, x = 0, y = (unsigned long)salt;
2397 
2398 	for (;;) {
2399 		if (!len)
2400 			goto done;
2401 		a = load_unaligned_zeropad(name);
2402 		if (len < sizeof(unsigned long))
2403 			break;
2404 		HASH_MIX(x, y, a);
2405 		name += sizeof(unsigned long);
2406 		len -= sizeof(unsigned long);
2407 	}
2408 	x ^= a & bytemask_from_count(len);
2409 done:
2410 	return fold_hash(x, y);
2411 }
2412 EXPORT_SYMBOL(full_name_hash);
2413 
2414 /* Return the "hash_len" (hash and length) of a null-terminated string */
2415 u64 hashlen_string(const void *salt, const char *name)
2416 {
2417 	unsigned long a = 0, x = 0, y = (unsigned long)salt;
2418 	unsigned long adata, mask, len;
2419 	const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2420 
2421 	len = 0;
2422 	goto inside;
2423 
2424 	do {
2425 		HASH_MIX(x, y, a);
2426 		len += sizeof(unsigned long);
2427 inside:
2428 		a = load_unaligned_zeropad(name+len);
2429 	} while (!has_zero(a, &adata, &constants));
2430 
2431 	adata = prep_zero_mask(a, adata, &constants);
2432 	mask = create_zero_mask(adata);
2433 	x ^= a & zero_bytemask(mask);
2434 
2435 	return hashlen_create(fold_hash(x, y), len + find_zero(mask));
2436 }
2437 EXPORT_SYMBOL(hashlen_string);
2438 
2439 /*
2440  * Calculate the length and hash of the path component, and
2441  * return the length as the result.
2442  */
2443 static inline const char *hash_name(struct nameidata *nd,
2444 				    const char *name,
2445 				    unsigned long *lastword)
2446 {
2447 	unsigned long a, b, x, y = (unsigned long)nd->path.dentry;
2448 	unsigned long adata, bdata, mask, len;
2449 	const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2450 
2451 	/*
2452 	 * The first iteration is special, because it can result in
2453 	 * '.' and '..' and has no mixing other than the final fold.
2454 	 */
2455 	a = load_unaligned_zeropad(name);
2456 	b = a ^ REPEAT_BYTE('/');
2457 	if (has_zero(a, &adata, &constants) | has_zero(b, &bdata, &constants)) {
2458 		adata = prep_zero_mask(a, adata, &constants);
2459 		bdata = prep_zero_mask(b, bdata, &constants);
2460 		mask = create_zero_mask(adata | bdata);
2461 		a &= zero_bytemask(mask);
2462 		*lastword = a;
2463 		len = find_zero(mask);
2464 		nd->last.hash = fold_hash(a, y);
2465 		nd->last.len = len;
2466 		return name + len;
2467 	}
2468 
2469 	len = 0;
2470 	x = 0;
2471 	do {
2472 		HASH_MIX(x, y, a);
2473 		len += sizeof(unsigned long);
2474 		a = load_unaligned_zeropad(name+len);
2475 		b = a ^ REPEAT_BYTE('/');
2476 	} while (!(has_zero(a, &adata, &constants) | has_zero(b, &bdata, &constants)));
2477 
2478 	adata = prep_zero_mask(a, adata, &constants);
2479 	bdata = prep_zero_mask(b, bdata, &constants);
2480 	mask = create_zero_mask(adata | bdata);
2481 	a &= zero_bytemask(mask);
2482 	x ^= a;
2483 	len += find_zero(mask);
2484 	*lastword = 0;		// Multi-word components cannot be DOT or DOTDOT
2485 
2486 	nd->last.hash = fold_hash(x, y);
2487 	nd->last.len = len;
2488 	return name + len;
2489 }
2490 
2491 /*
2492  * Note that the 'last' word is always zero-masked, but
2493  * was loaded as a possibly big-endian word.
2494  */
2495 #ifdef __BIG_ENDIAN
2496   #define LAST_WORD_IS_DOT	(0x2eul << (BITS_PER_LONG-8))
2497   #define LAST_WORD_IS_DOTDOT	(0x2e2eul << (BITS_PER_LONG-16))
2498 #endif
2499 
2500 #else	/* !CONFIG_DCACHE_WORD_ACCESS: Slow, byte-at-a-time version */
2501 
2502 /* Return the hash of a string of known length */
2503 unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
2504 {
2505 	unsigned long hash = init_name_hash(salt);
2506 	while (len--)
2507 		hash = partial_name_hash((unsigned char)*name++, hash);
2508 	return end_name_hash(hash);
2509 }
2510 EXPORT_SYMBOL(full_name_hash);
2511 
2512 /* Return the "hash_len" (hash and length) of a null-terminated string */
2513 u64 hashlen_string(const void *salt, const char *name)
2514 {
2515 	unsigned long hash = init_name_hash(salt);
2516 	unsigned long len = 0, c;
2517 
2518 	c = (unsigned char)*name;
2519 	while (c) {
2520 		len++;
2521 		hash = partial_name_hash(c, hash);
2522 		c = (unsigned char)name[len];
2523 	}
2524 	return hashlen_create(end_name_hash(hash), len);
2525 }
2526 EXPORT_SYMBOL(hashlen_string);
2527 
2528 /*
2529  * We know there's a real path component here of at least
2530  * one character.
2531  */
2532 static inline const char *hash_name(struct nameidata *nd, const char *name, unsigned long *lastword)
2533 {
2534 	unsigned long hash = init_name_hash(nd->path.dentry);
2535 	unsigned long len = 0, c, last = 0;
2536 
2537 	c = (unsigned char)*name;
2538 	do {
2539 		last = (last << 8) + c;
2540 		len++;
2541 		hash = partial_name_hash(c, hash);
2542 		c = (unsigned char)name[len];
2543 	} while (c && c != '/');
2544 
2545 	// This is reliable for DOT or DOTDOT, since the component
2546 	// cannot contain NUL characters - top bits being zero means
2547 	// we cannot have had any other pathnames.
2548 	*lastword = last;
2549 	nd->last.hash = end_name_hash(hash);
2550 	nd->last.len = len;
2551 	return name + len;
2552 }
2553 
2554 #endif
2555 
2556 #ifndef LAST_WORD_IS_DOT
2557   #define LAST_WORD_IS_DOT	0x2e
2558   #define LAST_WORD_IS_DOTDOT	0x2e2e
2559 #endif
2560 
2561 /*
2562  * Name resolution.
2563  * This is the basic name resolution function, turning a pathname into
2564  * the final dentry. We expect 'base' to be positive and a directory.
2565  *
2566  * Returns 0 and nd will have valid dentry and mnt on success.
2567  * Returns error and drops reference to input namei data on failure.
2568  */
2569 static int link_path_walk(const char *name, struct nameidata *nd)
2570 {
2571 	int depth = 0; // depth <= nd->depth
2572 	int err;
2573 
2574 	nd->last_type = LAST_ROOT;
2575 	nd->flags |= LOOKUP_PARENT;
2576 	if (IS_ERR(name))
2577 		return PTR_ERR(name);
2578 	if (*name == '/') {
2579 		do {
2580 			name++;
2581 		} while (unlikely(*name == '/'));
2582 	}
2583 	if (unlikely(!*name)) {
2584 		nd->dir_mode = 0; // short-circuit the 'hardening' idiocy
2585 		return 0;
2586 	}
2587 
2588 	/* At this point we know we have a real path component. */
2589 	for(;;) {
2590 		struct mnt_idmap *idmap;
2591 		const char *link;
2592 		unsigned long lastword;
2593 
2594 		idmap = mnt_idmap(nd->path.mnt);
2595 		err = may_lookup(idmap, nd);
2596 		if (unlikely(err))
2597 			return err;
2598 
2599 		nd->last.name = name;
2600 		name = hash_name(nd, name, &lastword);
2601 
2602 		switch(lastword) {
2603 		case LAST_WORD_IS_DOTDOT:
2604 			nd->last_type = LAST_DOTDOT;
2605 			nd->state |= ND_JUMPED;
2606 			break;
2607 
2608 		case LAST_WORD_IS_DOT:
2609 			nd->last_type = LAST_DOT;
2610 			break;
2611 
2612 		default:
2613 			nd->last_type = LAST_NORM;
2614 			nd->state &= ~ND_JUMPED;
2615 
2616 			struct dentry *parent = nd->path.dentry;
2617 			if (unlikely(parent->d_flags & DCACHE_OP_HASH)) {
2618 				err = parent->d_op->d_hash(parent, &nd->last);
2619 				if (err < 0)
2620 					return err;
2621 			}
2622 		}
2623 
2624 		if (!*name)
2625 			goto OK;
2626 		/*
2627 		 * If it wasn't NUL, we know it was '/'. Skip that
2628 		 * slash, and continue until no more slashes.
2629 		 */
2630 		do {
2631 			name++;
2632 		} while (unlikely(*name == '/'));
2633 		if (unlikely(!*name)) {
2634 OK:
2635 			/* pathname or trailing symlink, done */
2636 			if (likely(!depth)) {
2637 				nd->dir_vfsuid = i_uid_into_vfsuid(idmap, nd->inode);
2638 				nd->dir_mode = nd->inode->i_mode;
2639 				nd->flags &= ~LOOKUP_PARENT;
2640 				return 0;
2641 			}
2642 			/* last component of nested symlink */
2643 			name = nd->stack[--depth].name;
2644 			link = walk_component(nd, 0);
2645 		} else {
2646 			/* not the last component */
2647 			link = walk_component(nd, WALK_MORE);
2648 		}
2649 		if (unlikely(link)) {
2650 			if (IS_ERR(link))
2651 				return PTR_ERR(link);
2652 			/* a symlink to follow */
2653 			nd->stack[depth++].name = name;
2654 			name = link;
2655 			continue;
2656 		}
2657 		if (unlikely(!d_can_lookup(nd->path.dentry))) {
2658 			if (nd->flags & LOOKUP_RCU) {
2659 				if (!try_to_unlazy(nd))
2660 					return -ECHILD;
2661 			}
2662 			return -ENOTDIR;
2663 		}
2664 	}
2665 }
2666 
2667 /* must be paired with terminate_walk() */
2668 static const char *path_init(struct nameidata *nd, unsigned flags)
2669 {
2670 	int error;
2671 	const char *s = nd->pathname;
2672 
2673 	/* LOOKUP_CACHED requires RCU, ask caller to retry */
2674 	if (unlikely((flags & (LOOKUP_RCU | LOOKUP_CACHED)) == LOOKUP_CACHED))
2675 		return ERR_PTR(-EAGAIN);
2676 
2677 	if (unlikely(!*s))
2678 		flags &= ~LOOKUP_RCU;
2679 	if (flags & LOOKUP_RCU)
2680 		rcu_read_lock();
2681 	else
2682 		nd->seq = nd->next_seq = 0;
2683 
2684 	nd->flags = flags;
2685 	nd->state |= ND_JUMPED;
2686 
2687 	nd->m_seq = __read_seqcount_begin(&mount_lock.seqcount);
2688 	nd->r_seq = __read_seqcount_begin(&rename_lock.seqcount);
2689 	smp_rmb();
2690 
2691 	if (unlikely(nd->state & ND_ROOT_PRESET)) {
2692 		struct dentry *root = nd->root.dentry;
2693 		struct inode *inode = root->d_inode;
2694 		if (*s && unlikely(!d_can_lookup(root)))
2695 			return ERR_PTR(-ENOTDIR);
2696 		nd->path = nd->root;
2697 		nd->inode = inode;
2698 		if (flags & LOOKUP_RCU) {
2699 			nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
2700 			nd->root_seq = nd->seq;
2701 		} else {
2702 			path_get(&nd->path);
2703 		}
2704 		return s;
2705 	}
2706 
2707 	nd->root.mnt = NULL;
2708 
2709 	/* Absolute pathname -- fetch the root (LOOKUP_IN_ROOT uses nd->dfd). */
2710 	if (*s == '/' && likely(!(flags & LOOKUP_IN_ROOT))) {
2711 		error = nd_jump_root(nd);
2712 		if (unlikely(error))
2713 			return ERR_PTR(error);
2714 		return s;
2715 	}
2716 
2717 	/* Relative pathname -- get the starting-point it is relative to. */
2718 	if (nd->dfd == AT_FDCWD) {
2719 		if (flags & LOOKUP_RCU) {
2720 			struct fs_struct *fs = current->fs;
2721 			unsigned seq;
2722 
2723 			do {
2724 				seq = read_seqbegin(&fs->seq);
2725 				nd->path = fs->pwd;
2726 				nd->inode = nd->path.dentry->d_inode;
2727 				nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
2728 			} while (read_seqretry(&fs->seq, seq));
2729 		} else {
2730 			get_fs_pwd(current->fs, &nd->path);
2731 			nd->inode = nd->path.dentry->d_inode;
2732 		}
2733 	} else {
2734 		/* Caller must check execute permissions on the starting path component */
2735 		CLASS(fd_raw, f)(nd->dfd);
2736 		struct dentry *dentry;
2737 
2738 		if (fd_empty(f))
2739 			return ERR_PTR(-EBADF);
2740 
2741 		if (flags & LOOKUP_LINKAT_EMPTY) {
2742 			if (fd_file(f)->f_cred != current_cred() &&
2743 			    !ns_capable(fd_file(f)->f_cred->user_ns, CAP_DAC_READ_SEARCH))
2744 				return ERR_PTR(-ENOENT);
2745 		}
2746 
2747 		dentry = fd_file(f)->f_path.dentry;
2748 
2749 		if (*s && unlikely(!d_can_lookup(dentry)))
2750 			return ERR_PTR(-ENOTDIR);
2751 
2752 		nd->path = fd_file(f)->f_path;
2753 		if (flags & LOOKUP_RCU) {
2754 			nd->inode = nd->path.dentry->d_inode;
2755 			nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
2756 		} else {
2757 			path_get(&nd->path);
2758 			nd->inode = nd->path.dentry->d_inode;
2759 		}
2760 	}
2761 
2762 	/* For scoped-lookups we need to set the root to the dirfd as well. */
2763 	if (unlikely(flags & LOOKUP_IS_SCOPED)) {
2764 		nd->root = nd->path;
2765 		if (flags & LOOKUP_RCU) {
2766 			nd->root_seq = nd->seq;
2767 		} else {
2768 			path_get(&nd->root);
2769 			nd->state |= ND_ROOT_GRABBED;
2770 		}
2771 	}
2772 	return s;
2773 }
2774 
2775 static inline const char *lookup_last(struct nameidata *nd)
2776 {
2777 	if (nd->last_type == LAST_NORM && nd->last.name[nd->last.len])
2778 		nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
2779 
2780 	return walk_component(nd, WALK_TRAILING);
2781 }
2782 
2783 static int handle_lookup_down(struct nameidata *nd)
2784 {
2785 	if (!(nd->flags & LOOKUP_RCU))
2786 		dget(nd->path.dentry);
2787 	nd->next_seq = nd->seq;
2788 	return PTR_ERR(step_into(nd, WALK_NOFOLLOW, nd->path.dentry));
2789 }
2790 
2791 /* Returns 0 and nd will be valid on success; Returns error, otherwise. */
2792 static int path_lookupat(struct nameidata *nd, unsigned flags, struct path *path)
2793 {
2794 	const char *s = path_init(nd, flags);
2795 	int err;
2796 
2797 	if (unlikely(flags & LOOKUP_DOWN) && !IS_ERR(s)) {
2798 		err = handle_lookup_down(nd);
2799 		if (unlikely(err < 0))
2800 			s = ERR_PTR(err);
2801 	}
2802 
2803 	while (!(err = link_path_walk(s, nd)) &&
2804 	       (s = lookup_last(nd)) != NULL)
2805 		;
2806 	if (!err && unlikely(nd->flags & LOOKUP_MOUNTPOINT)) {
2807 		err = handle_lookup_down(nd);
2808 		nd->state &= ~ND_JUMPED; // no d_weak_revalidate(), please...
2809 	}
2810 	if (!err)
2811 		err = complete_walk(nd);
2812 
2813 	if (!err && nd->flags & LOOKUP_DIRECTORY)
2814 		if (!d_can_lookup(nd->path.dentry))
2815 			err = -ENOTDIR;
2816 	if (!err) {
2817 		*path = nd->path;
2818 		nd->path.mnt = NULL;
2819 		nd->path.dentry = NULL;
2820 	}
2821 	terminate_walk(nd);
2822 	return err;
2823 }
2824 
2825 int filename_lookup(int dfd, struct filename *name, unsigned flags,
2826 		    struct path *path, const struct path *root)
2827 {
2828 	int retval;
2829 	struct nameidata nd;
2830 	if (IS_ERR(name))
2831 		return PTR_ERR(name);
2832 	set_nameidata(&nd, dfd, name, root);
2833 	retval = path_lookupat(&nd, flags | LOOKUP_RCU, path);
2834 	if (unlikely(retval == -ECHILD))
2835 		retval = path_lookupat(&nd, flags, path);
2836 	if (unlikely(retval == -ESTALE))
2837 		retval = path_lookupat(&nd, flags | LOOKUP_REVAL, path);
2838 
2839 	if (likely(!retval))
2840 		audit_inode(name, path->dentry,
2841 			    flags & LOOKUP_MOUNTPOINT ? AUDIT_INODE_NOEVAL : 0);
2842 	restore_nameidata();
2843 	return retval;
2844 }
2845 
2846 /* Returns 0 and nd will be valid on success; Returns error, otherwise. */
2847 static int path_parentat(struct nameidata *nd, unsigned flags,
2848 				struct path *parent)
2849 {
2850 	const char *s = path_init(nd, flags);
2851 	int err = link_path_walk(s, nd);
2852 	if (!err)
2853 		err = complete_walk(nd);
2854 	if (!err) {
2855 		*parent = nd->path;
2856 		nd->path.mnt = NULL;
2857 		nd->path.dentry = NULL;
2858 	}
2859 	terminate_walk(nd);
2860 	return err;
2861 }
2862 
2863 /* Note: this does not consume "name" */
2864 static int __filename_parentat(int dfd, struct filename *name,
2865 			       unsigned int flags, struct path *parent,
2866 			       struct qstr *last, int *type,
2867 			       const struct path *root)
2868 {
2869 	int retval;
2870 	struct nameidata nd;
2871 
2872 	if (IS_ERR(name))
2873 		return PTR_ERR(name);
2874 	set_nameidata(&nd, dfd, name, root);
2875 	retval = path_parentat(&nd, flags | LOOKUP_RCU, parent);
2876 	if (unlikely(retval == -ECHILD))
2877 		retval = path_parentat(&nd, flags, parent);
2878 	if (unlikely(retval == -ESTALE))
2879 		retval = path_parentat(&nd, flags | LOOKUP_REVAL, parent);
2880 	if (likely(!retval)) {
2881 		*last = nd.last;
2882 		*type = nd.last_type;
2883 		audit_inode(name, parent->dentry, AUDIT_INODE_PARENT);
2884 	}
2885 	restore_nameidata();
2886 	return retval;
2887 }
2888 
2889 static int filename_parentat(int dfd, struct filename *name,
2890 			     unsigned int flags, struct path *parent,
2891 			     struct qstr *last, int *type)
2892 {
2893 	return __filename_parentat(dfd, name, flags, parent, last, type, NULL);
2894 }
2895 
2896 /**
2897  * __start_dirop - begin a create or remove dirop, performing locking and lookup
2898  * @parent:       the dentry of the parent in which the operation will occur
2899  * @name:         a qstr holding the name within that parent
2900  * @lookup_flags: intent and other lookup flags.
2901  * @state:        task state bitmask
2902  *
2903  * The lookup is performed and necessary locks are taken so that, on success,
2904  * the returned dentry can be operated on safely.
2905  * The qstr must already have the hash value calculated.
2906  *
2907  * Returns: a locked dentry, or an error.
2908  *
2909  */
2910 static struct dentry *__start_dirop(struct dentry *parent, struct qstr *name,
2911 				    unsigned int lookup_flags,
2912 				    unsigned int state)
2913 {
2914 	struct dentry *dentry;
2915 	struct inode *dir = d_inode(parent);
2916 
2917 	if (state == TASK_KILLABLE) {
2918 		int ret = down_write_killable_nested(&dir->i_rwsem,
2919 						     I_MUTEX_PARENT);
2920 		if (ret)
2921 			return ERR_PTR(ret);
2922 	} else {
2923 		inode_lock_nested(dir, I_MUTEX_PARENT);
2924 	}
2925 	dentry = lookup_one_qstr_excl(name, parent, lookup_flags);
2926 	if (IS_ERR(dentry))
2927 		inode_unlock(dir);
2928 	return dentry;
2929 }
2930 
2931 struct dentry *start_dirop(struct dentry *parent, struct qstr *name,
2932 			   unsigned int lookup_flags)
2933 {
2934 	return __start_dirop(parent, name, lookup_flags, TASK_NORMAL);
2935 }
2936 
2937 /**
2938  * end_dirop - signal completion of a dirop
2939  * @de: the dentry which was returned by start_dirop or similar.
2940  *
2941  * If the de is an error, nothing happens. Otherwise any lock taken to
2942  * protect the dentry is dropped and the dentry itself is release (dput()).
2943  */
2944 void end_dirop(struct dentry *de)
2945 {
2946 	if (!IS_ERR(de)) {
2947 		inode_unlock(de->d_parent->d_inode);
2948 		dput(de);
2949 	}
2950 }
2951 EXPORT_SYMBOL(end_dirop);
2952 
2953 /* does lookup, returns the object with parent locked */
2954 static struct dentry *__start_removing_path(int dfd, struct filename *name,
2955 					   struct path *path)
2956 {
2957 	struct path parent_path __free(path_put) = {};
2958 	struct dentry *d;
2959 	struct qstr last;
2960 	int type, error;
2961 
2962 	error = filename_parentat(dfd, name, 0, &parent_path, &last, &type);
2963 	if (error)
2964 		return ERR_PTR(error);
2965 	if (unlikely(type != LAST_NORM))
2966 		return ERR_PTR(-EINVAL);
2967 	/* don't fail immediately if it's r/o, at least try to report other errors */
2968 	error = mnt_want_write(parent_path.mnt);
2969 	d = start_dirop(parent_path.dentry, &last, 0);
2970 	if (IS_ERR(d))
2971 		goto drop;
2972 	if (error)
2973 		goto fail;
2974 	path->dentry = no_free_ptr(parent_path.dentry);
2975 	path->mnt = no_free_ptr(parent_path.mnt);
2976 	return d;
2977 
2978 fail:
2979 	end_dirop(d);
2980 	d = ERR_PTR(error);
2981 drop:
2982 	if (!error)
2983 		mnt_drop_write(parent_path.mnt);
2984 	return d;
2985 }
2986 
2987 /**
2988  * kern_path_parent: lookup path returning parent and target
2989  * @name: path name
2990  * @path: path to store parent in
2991  *
2992  * The path @name should end with a normal component, not "." or ".." or "/".
2993  * A lookup is performed and if successful the parent information
2994  * is store in @parent and the dentry is returned.
2995  *
2996  * The dentry maybe negative, the parent will be positive.
2997  *
2998  * Returns:  dentry or error.
2999  */
3000 struct dentry *kern_path_parent(const char *name, struct path *path)
3001 {
3002 	struct path parent_path __free(path_put) = {};
3003 	CLASS(filename_kernel, filename)(name);
3004 	struct dentry *d;
3005 	struct qstr last;
3006 	int type, error;
3007 
3008 	error = filename_parentat(AT_FDCWD, filename, 0, &parent_path, &last, &type);
3009 	if (error)
3010 		return ERR_PTR(error);
3011 	if (unlikely(type != LAST_NORM))
3012 		return ERR_PTR(-EINVAL);
3013 
3014 	d = lookup_noperm_unlocked(&last, parent_path.dentry);
3015 	if (IS_ERR(d))
3016 		return d;
3017 	path->dentry = no_free_ptr(parent_path.dentry);
3018 	path->mnt = no_free_ptr(parent_path.mnt);
3019 	return d;
3020 }
3021 
3022 struct dentry *start_removing_path(const char *name, struct path *path)
3023 {
3024 	CLASS(filename_kernel, filename)(name);
3025 	return __start_removing_path(AT_FDCWD, filename, path);
3026 }
3027 
3028 struct dentry *start_removing_user_path_at(int dfd,
3029 					   const char __user *name,
3030 					   struct path *path)
3031 {
3032 	CLASS(filename, filename)(name);
3033 	return __start_removing_path(dfd, filename, path);
3034 }
3035 EXPORT_SYMBOL(start_removing_user_path_at);
3036 
3037 int kern_path(const char *name, unsigned int flags, struct path *path)
3038 {
3039 	CLASS(filename_kernel, filename)(name);
3040 	return filename_lookup(AT_FDCWD, filename, flags, path, NULL);
3041 }
3042 EXPORT_SYMBOL(kern_path);
3043 
3044 /**
3045  * vfs_path_parent_lookup - lookup a parent path relative to a dentry-vfsmount pair
3046  * @filename: filename structure
3047  * @flags: lookup flags
3048  * @parent: pointer to struct path to fill
3049  * @last: last component
3050  * @type: type of the last component
3051  * @root: pointer to struct path of the base directory
3052  */
3053 int vfs_path_parent_lookup(struct filename *filename, unsigned int flags,
3054 			   struct path *parent, struct qstr *last, int *type,
3055 			   const struct path *root)
3056 {
3057 	return  __filename_parentat(AT_FDCWD, filename, flags, parent, last,
3058 				    type, root);
3059 }
3060 EXPORT_SYMBOL(vfs_path_parent_lookup);
3061 
3062 /**
3063  * vfs_path_lookup - lookup a file path relative to a dentry-vfsmount pair
3064  * @dentry:  pointer to dentry of the base directory
3065  * @mnt: pointer to vfs mount of the base directory
3066  * @name: pointer to file name
3067  * @flags: lookup flags
3068  * @path: pointer to struct path to fill
3069  */
3070 int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt,
3071 		    const char *name, unsigned int flags,
3072 		    struct path *path)
3073 {
3074 	CLASS(filename_kernel, filename)(name);
3075 	struct path root = {.mnt = mnt, .dentry = dentry};
3076 
3077 	/* the first argument of filename_lookup() is ignored with root */
3078 	return filename_lookup(AT_FDCWD, filename, flags, path, &root);
3079 }
3080 EXPORT_SYMBOL(vfs_path_lookup);
3081 
3082 int lookup_noperm_common(struct qstr *qname, struct dentry *base)
3083 {
3084 	const char *name = qname->name;
3085 	u32 len = qname->len;
3086 
3087 	qname->hash = full_name_hash(base, name, len);
3088 	if (!len)
3089 		return -EACCES;
3090 
3091 	if (is_dot_dotdot(name, len))
3092 		return -EACCES;
3093 
3094 	while (len--) {
3095 		unsigned int c = *(const unsigned char *)name++;
3096 		if (c == '/' || c == '\0')
3097 			return -EACCES;
3098 	}
3099 	/*
3100 	 * See if the low-level filesystem might want
3101 	 * to use its own hash..
3102 	 */
3103 	if (base->d_flags & DCACHE_OP_HASH) {
3104 		int err = base->d_op->d_hash(base, qname);
3105 		if (err < 0)
3106 			return err;
3107 	}
3108 	return 0;
3109 }
3110 
3111 static int lookup_one_common(struct mnt_idmap *idmap,
3112 			     struct qstr *qname, struct dentry *base)
3113 {
3114 	int err;
3115 	err = lookup_noperm_common(qname, base);
3116 	if (err < 0)
3117 		return err;
3118 	return inode_permission(idmap, base->d_inode, MAY_EXEC);
3119 }
3120 
3121 /**
3122  * try_lookup_noperm - filesystem helper to lookup single pathname component
3123  * @name:	qstr storing pathname component to lookup
3124  * @base:	base directory to lookup from
3125  *
3126  * Look up a dentry by name in the dcache, returning NULL if it does not
3127  * currently exist.  The function does not try to create a dentry and if one
3128  * is found it doesn't try to revalidate it.
3129  *
3130  * Note that this routine is purely a helper for filesystem usage and should
3131  * not be called by generic code.  It does no permission checking.
3132  *
3133  * No locks need be held - only a counted reference to @base is needed.
3134  *
3135  */
3136 struct dentry *try_lookup_noperm(struct qstr *name, struct dentry *base)
3137 {
3138 	int err;
3139 
3140 	err = lookup_noperm_common(name, base);
3141 	if (err)
3142 		return ERR_PTR(err);
3143 
3144 	return d_lookup(base, name);
3145 }
3146 EXPORT_SYMBOL(try_lookup_noperm);
3147 
3148 /**
3149  * lookup_noperm - filesystem helper to lookup single pathname component
3150  * @name:	qstr storing pathname component to lookup
3151  * @base:	base directory to lookup from
3152  *
3153  * Note that this routine is purely a helper for filesystem usage and should
3154  * not be called by generic code.  It does no permission checking.
3155  *
3156  * The caller must hold base->i_rwsem.
3157  */
3158 struct dentry *lookup_noperm(struct qstr *name, struct dentry *base)
3159 {
3160 	struct dentry *dentry;
3161 	int err;
3162 
3163 	WARN_ON_ONCE(!inode_is_locked(base->d_inode));
3164 
3165 	err = lookup_noperm_common(name, base);
3166 	if (err)
3167 		return ERR_PTR(err);
3168 
3169 	dentry = lookup_dcache(name, base, 0);
3170 	return dentry ? dentry : __lookup_slow(name, base, 0);
3171 }
3172 EXPORT_SYMBOL(lookup_noperm);
3173 
3174 /**
3175  * lookup_one - lookup single pathname component
3176  * @idmap:	idmap of the mount the lookup is performed from
3177  * @name:	qstr holding pathname component to lookup
3178  * @base:	base directory to lookup from
3179  *
3180  * This can be used for in-kernel filesystem clients such as file servers.
3181  *
3182  * The caller must hold base->i_rwsem.
3183  */
3184 struct dentry *lookup_one(struct mnt_idmap *idmap, struct qstr *name,
3185 			  struct dentry *base)
3186 {
3187 	struct dentry *dentry;
3188 	int err;
3189 
3190 	WARN_ON_ONCE(!inode_is_locked(base->d_inode));
3191 
3192 	err = lookup_one_common(idmap, name, base);
3193 	if (err)
3194 		return ERR_PTR(err);
3195 
3196 	dentry = lookup_dcache(name, base, 0);
3197 	return dentry ? dentry : __lookup_slow(name, base, 0);
3198 }
3199 EXPORT_SYMBOL(lookup_one);
3200 
3201 /**
3202  * lookup_one_unlocked - lookup single pathname component
3203  * @idmap:	idmap of the mount the lookup is performed from
3204  * @name:	qstr olding pathname component to lookup
3205  * @base:	base directory to lookup from
3206  *
3207  * This can be used for in-kernel filesystem clients such as file servers.
3208  *
3209  * Unlike lookup_one, it should be called without the parent
3210  * i_rwsem held, and will take the i_rwsem itself if necessary.
3211  */
3212 struct dentry *lookup_one_unlocked(struct mnt_idmap *idmap, struct qstr *name,
3213 				   struct dentry *base)
3214 {
3215 	int err;
3216 	struct dentry *ret;
3217 
3218 	err = lookup_one_common(idmap, name, base);
3219 	if (err)
3220 		return ERR_PTR(err);
3221 
3222 	ret = lookup_dcache(name, base, 0);
3223 	if (!ret)
3224 		ret = lookup_slow(name, base, 0);
3225 	return ret;
3226 }
3227 EXPORT_SYMBOL(lookup_one_unlocked);
3228 
3229 /**
3230  * lookup_one_positive_killable - lookup single pathname component
3231  * @idmap:	idmap of the mount the lookup is performed from
3232  * @name:	qstr olding pathname component to lookup
3233  * @base:	base directory to lookup from
3234  *
3235  * This helper will yield ERR_PTR(-ENOENT) on negatives. The helper returns
3236  * known positive or ERR_PTR(). This is what most of the users want.
3237  *
3238  * Note that pinned negative with unlocked parent _can_ become positive at any
3239  * time, so callers of lookup_one_unlocked() need to be very careful; pinned
3240  * positives have >d_inode stable, so this one avoids such problems.
3241  *
3242  * This can be used for in-kernel filesystem clients such as file servers.
3243  *
3244  * It should be called without the parent i_rwsem held, and will take
3245  * the i_rwsem itself if necessary.  If a fatal signal is pending or
3246  * delivered, it will return %-EINTR if the lock is needed.
3247  */
3248 struct dentry *lookup_one_positive_killable(struct mnt_idmap *idmap,
3249 					    struct qstr *name,
3250 					    struct dentry *base)
3251 {
3252 	int err;
3253 	struct dentry *ret;
3254 
3255 	err = lookup_one_common(idmap, name, base);
3256 	if (err)
3257 		return ERR_PTR(err);
3258 
3259 	ret = lookup_dcache(name, base, 0);
3260 	if (!ret)
3261 		ret = lookup_slow_killable(name, base, 0);
3262 	if (!IS_ERR(ret) && d_flags_negative(smp_load_acquire(&ret->d_flags))) {
3263 		dput(ret);
3264 		ret = ERR_PTR(-ENOENT);
3265 	}
3266 	return ret;
3267 }
3268 EXPORT_SYMBOL(lookup_one_positive_killable);
3269 
3270 /**
3271  * lookup_one_positive_unlocked - lookup single pathname component
3272  * @idmap:	idmap of the mount the lookup is performed from
3273  * @name:	qstr holding pathname component to lookup
3274  * @base:	base directory to lookup from
3275  *
3276  * This helper will yield ERR_PTR(-ENOENT) on negatives. The helper returns
3277  * known positive or ERR_PTR(). This is what most of the users want.
3278  *
3279  * Note that pinned negative with unlocked parent _can_ become positive at any
3280  * time, so callers of lookup_one_unlocked() need to be very careful; pinned
3281  * positives have >d_inode stable, so this one avoids such problems.
3282  *
3283  * This can be used for in-kernel filesystem clients such as file servers.
3284  *
3285  * The helper should be called without i_rwsem held.
3286  */
3287 struct dentry *lookup_one_positive_unlocked(struct mnt_idmap *idmap,
3288 					    struct qstr *name,
3289 					    struct dentry *base)
3290 {
3291 	struct dentry *ret = lookup_one_unlocked(idmap, name, base);
3292 
3293 	if (!IS_ERR(ret) && d_flags_negative(smp_load_acquire(&ret->d_flags))) {
3294 		dput(ret);
3295 		ret = ERR_PTR(-ENOENT);
3296 	}
3297 	return ret;
3298 }
3299 EXPORT_SYMBOL(lookup_one_positive_unlocked);
3300 
3301 /**
3302  * lookup_noperm_unlocked - filesystem helper to lookup single pathname component
3303  * @name:	pathname component to lookup
3304  * @base:	base directory to lookup from
3305  *
3306  * Note that this routine is purely a helper for filesystem usage and should
3307  * not be called by generic code. It does no permission checking.
3308  *
3309  * Unlike lookup_noperm(), it should be called without the parent
3310  * i_rwsem held, and will take the i_rwsem itself if necessary.
3311  *
3312  * Unlike try_lookup_noperm() it *does* revalidate the dentry if it already
3313  * existed.
3314  */
3315 struct dentry *lookup_noperm_unlocked(struct qstr *name, struct dentry *base)
3316 {
3317 	struct dentry *ret;
3318 	int err;
3319 
3320 	err = lookup_noperm_common(name, base);
3321 	if (err)
3322 		return ERR_PTR(err);
3323 
3324 	ret = lookup_dcache(name, base, 0);
3325 	if (!ret)
3326 		ret = lookup_slow(name, base, 0);
3327 	return ret;
3328 }
3329 EXPORT_SYMBOL(lookup_noperm_unlocked);
3330 
3331 /*
3332  * Like lookup_noperm_unlocked(), except that it yields ERR_PTR(-ENOENT)
3333  * on negatives.  Returns known positive or ERR_PTR(); that's what
3334  * most of the users want.  Note that pinned negative with unlocked parent
3335  * _can_ become positive at any time, so callers of lookup_noperm_unlocked()
3336  * need to be very careful; pinned positives have ->d_inode stable, so
3337  * this one avoids such problems.
3338  */
3339 struct dentry *lookup_noperm_positive_unlocked(struct qstr *name,
3340 					       struct dentry *base)
3341 {
3342 	struct dentry *ret;
3343 
3344 	ret = lookup_noperm_unlocked(name, base);
3345 	if (!IS_ERR(ret) && d_flags_negative(smp_load_acquire(&ret->d_flags))) {
3346 		dput(ret);
3347 		ret = ERR_PTR(-ENOENT);
3348 	}
3349 	return ret;
3350 }
3351 EXPORT_SYMBOL(lookup_noperm_positive_unlocked);
3352 
3353 /**
3354  * start_creating - prepare to create a given name with permission checking
3355  * @idmap:  idmap of the mount
3356  * @parent: directory in which to prepare to create the name
3357  * @name:   the name to be created
3358  *
3359  * Locks are taken and a lookup is performed prior to creating
3360  * an object in a directory.  Permission checking (MAY_EXEC) is performed
3361  * against @idmap.
3362  *
3363  * If the name already exists, a positive dentry is returned, so
3364  * behaviour is similar to O_CREAT without O_EXCL, which doesn't fail
3365  * with -EEXIST.
3366  *
3367  * Returns: a negative or positive dentry, or an error.
3368  */
3369 struct dentry *start_creating(struct mnt_idmap *idmap, struct dentry *parent,
3370 			      struct qstr *name)
3371 {
3372 	int err = lookup_one_common(idmap, name, parent);
3373 
3374 	if (err)
3375 		return ERR_PTR(err);
3376 	return start_dirop(parent, name, LOOKUP_CREATE);
3377 }
3378 EXPORT_SYMBOL(start_creating);
3379 
3380 /**
3381  * start_removing - prepare to remove a given name with permission checking
3382  * @idmap:  idmap of the mount
3383  * @parent: directory in which to find the name
3384  * @name:   the name to be removed
3385  *
3386  * Locks are taken and a lookup in performed prior to removing
3387  * an object from a directory.  Permission checking (MAY_EXEC) is performed
3388  * against @idmap.
3389  *
3390  * If the name doesn't exist, an error is returned.
3391  *
3392  * end_removing() should be called when removal is complete, or aborted.
3393  *
3394  * Returns: a positive dentry, or an error.
3395  */
3396 struct dentry *start_removing(struct mnt_idmap *idmap, struct dentry *parent,
3397 			      struct qstr *name)
3398 {
3399 	int err = lookup_one_common(idmap, name, parent);
3400 
3401 	if (err)
3402 		return ERR_PTR(err);
3403 	return start_dirop(parent, name, 0);
3404 }
3405 EXPORT_SYMBOL(start_removing);
3406 
3407 /**
3408  * start_creating_killable - prepare to create a given name with permission checking
3409  * @idmap:  idmap of the mount
3410  * @parent: directory in which to prepare to create the name
3411  * @name:   the name to be created
3412  *
3413  * Locks are taken and a lookup in performed prior to creating
3414  * an object in a directory.  Permission checking (MAY_EXEC) is performed
3415  * against @idmap.
3416  *
3417  * If the name already exists, a positive dentry is returned.
3418  *
3419  * If a signal is received or was already pending, the function aborts
3420  * with -EINTR;
3421  *
3422  * Returns: a negative or positive dentry, or an error.
3423  */
3424 struct dentry *start_creating_killable(struct mnt_idmap *idmap,
3425 				       struct dentry *parent,
3426 				       struct qstr *name)
3427 {
3428 	int err = lookup_one_common(idmap, name, parent);
3429 
3430 	if (err)
3431 		return ERR_PTR(err);
3432 	return __start_dirop(parent, name, LOOKUP_CREATE, TASK_KILLABLE);
3433 }
3434 EXPORT_SYMBOL(start_creating_killable);
3435 
3436 /**
3437  * start_removing_killable - prepare to remove a given name with permission checking
3438  * @idmap:  idmap of the mount
3439  * @parent: directory in which to find the name
3440  * @name:   the name to be removed
3441  *
3442  * Locks are taken and a lookup in performed prior to removing
3443  * an object from a directory.  Permission checking (MAY_EXEC) is performed
3444  * against @idmap.
3445  *
3446  * If the name doesn't exist, an error is returned.
3447  *
3448  * end_removing() should be called when removal is complete, or aborted.
3449  *
3450  * If a signal is received or was already pending, the function aborts
3451  * with -EINTR;
3452  *
3453  * Returns: a positive dentry, or an error.
3454  */
3455 struct dentry *start_removing_killable(struct mnt_idmap *idmap,
3456 				       struct dentry *parent,
3457 				       struct qstr *name)
3458 {
3459 	int err = lookup_one_common(idmap, name, parent);
3460 
3461 	if (err)
3462 		return ERR_PTR(err);
3463 	return __start_dirop(parent, name, 0, TASK_KILLABLE);
3464 }
3465 EXPORT_SYMBOL(start_removing_killable);
3466 
3467 /**
3468  * start_creating_noperm - prepare to create a given name without permission checking
3469  * @parent: directory in which to prepare to create the name
3470  * @name:   the name to be created
3471  *
3472  * Locks are taken and a lookup in performed prior to creating
3473  * an object in a directory.
3474  *
3475  * If the name already exists, a positive dentry is returned.
3476  *
3477  * Returns: a negative or positive dentry, or an error.
3478  */
3479 struct dentry *start_creating_noperm(struct dentry *parent,
3480 				     struct qstr *name)
3481 {
3482 	int err = lookup_noperm_common(name, parent);
3483 
3484 	if (err)
3485 		return ERR_PTR(err);
3486 	return start_dirop(parent, name, LOOKUP_CREATE);
3487 }
3488 EXPORT_SYMBOL(start_creating_noperm);
3489 
3490 /**
3491  * start_removing_noperm - prepare to remove a given name without permission checking
3492  * @parent: directory in which to find the name
3493  * @name:   the name to be removed
3494  *
3495  * Locks are taken and a lookup in performed prior to removing
3496  * an object from a directory.
3497  *
3498  * If the name doesn't exist, an error is returned.
3499  *
3500  * end_removing() should be called when removal is complete, or aborted.
3501  *
3502  * Returns: a positive dentry, or an error.
3503  */
3504 struct dentry *start_removing_noperm(struct dentry *parent,
3505 				     struct qstr *name)
3506 {
3507 	int err = lookup_noperm_common(name, parent);
3508 
3509 	if (err)
3510 		return ERR_PTR(err);
3511 	return start_dirop(parent, name, 0);
3512 }
3513 EXPORT_SYMBOL(start_removing_noperm);
3514 
3515 /**
3516  * start_creating_dentry - prepare to create a given dentry
3517  * @parent: directory from which dentry should be removed
3518  * @child:  the dentry to be removed
3519  *
3520  * A lock is taken to protect the dentry again other dirops and
3521  * the validity of the dentry is checked: correct parent and still hashed.
3522  *
3523  * If the dentry is valid and negative a reference is taken and
3524  * returned.  If not an error is returned.
3525  *
3526  * end_creating() should be called when creation is complete, or aborted.
3527  *
3528  * Returns: the valid dentry, or an error.
3529  */
3530 struct dentry *start_creating_dentry(struct dentry *parent,
3531 				     struct dentry *child)
3532 {
3533 	inode_lock_nested(parent->d_inode, I_MUTEX_PARENT);
3534 	if (unlikely(IS_DEADDIR(parent->d_inode) ||
3535 		     child->d_parent != parent ||
3536 		     d_unhashed(child))) {
3537 		inode_unlock(parent->d_inode);
3538 		return ERR_PTR(-EINVAL);
3539 	}
3540 	if (d_is_positive(child)) {
3541 		inode_unlock(parent->d_inode);
3542 		return ERR_PTR(-EEXIST);
3543 	}
3544 	return dget(child);
3545 }
3546 EXPORT_SYMBOL(start_creating_dentry);
3547 
3548 /**
3549  * start_removing_dentry - prepare to remove a given dentry
3550  * @parent: directory from which dentry should be removed
3551  * @child:  the dentry to be removed
3552  *
3553  * A lock is taken to protect the dentry again other dirops and
3554  * the validity of the dentry is checked: correct parent and still hashed.
3555  *
3556  * If the dentry is valid and positive, a reference is taken and
3557  * returned.  If not an error is returned.
3558  *
3559  * end_removing() should be called when removal is complete, or aborted.
3560  *
3561  * Returns: the valid dentry, or an error.
3562  */
3563 struct dentry *start_removing_dentry(struct dentry *parent,
3564 				     struct dentry *child)
3565 {
3566 	inode_lock_nested(parent->d_inode, I_MUTEX_PARENT);
3567 	if (unlikely(IS_DEADDIR(parent->d_inode) ||
3568 		     child->d_parent != parent ||
3569 		     d_unhashed(child))) {
3570 		inode_unlock(parent->d_inode);
3571 		return ERR_PTR(-EINVAL);
3572 	}
3573 	if (d_is_negative(child)) {
3574 		inode_unlock(parent->d_inode);
3575 		return ERR_PTR(-ENOENT);
3576 	}
3577 	return dget(child);
3578 }
3579 EXPORT_SYMBOL(start_removing_dentry);
3580 
3581 #ifdef CONFIG_UNIX98_PTYS
3582 int path_pts(struct path *path)
3583 {
3584 	/* Find something mounted on "pts" in the same directory as
3585 	 * the input path.
3586 	 */
3587 	struct dentry *parent = dget_parent(path->dentry);
3588 	struct dentry *child;
3589 	struct qstr this = QSTR_INIT("pts", 3);
3590 
3591 	if (unlikely(!path_connected(path->mnt, parent))) {
3592 		dput(parent);
3593 		return -ENOENT;
3594 	}
3595 	dput(path->dentry);
3596 	path->dentry = parent;
3597 	child = d_hash_and_lookup(parent, &this);
3598 	if (IS_ERR_OR_NULL(child))
3599 		return -ENOENT;
3600 
3601 	path->dentry = child;
3602 	dput(parent);
3603 	follow_down(path, 0);
3604 	return 0;
3605 }
3606 #endif
3607 
3608 int user_path_at(int dfd, const char __user *name, unsigned flags,
3609 		 struct path *path)
3610 {
3611 	CLASS(filename_flags, filename)(name, flags);
3612 	return filename_lookup(dfd, filename, flags, path, NULL);
3613 }
3614 EXPORT_SYMBOL(user_path_at);
3615 
3616 int __check_sticky(struct mnt_idmap *idmap, struct inode *dir,
3617 		   struct inode *inode)
3618 {
3619 	kuid_t fsuid = current_fsuid();
3620 
3621 	if (vfsuid_eq_kuid(i_uid_into_vfsuid(idmap, inode), fsuid))
3622 		return 0;
3623 	if (vfsuid_eq_kuid(i_uid_into_vfsuid(idmap, dir), fsuid))
3624 		return 0;
3625 	return !capable_wrt_inode_uidgid(idmap, inode, CAP_FOWNER);
3626 }
3627 EXPORT_SYMBOL(__check_sticky);
3628 
3629 /*
3630  *	Check whether we can remove a link victim from directory dir, check
3631  *  whether the type of victim is right.
3632  *  1. We can't do it if dir is read-only (done in permission())
3633  *  2. We should have write and exec permissions on dir
3634  *  3. We can't remove anything from append-only dir
3635  *  4. We can't do anything with immutable dir (done in permission())
3636  *  5. If the sticky bit on dir is set we should either
3637  *	a. be owner of dir, or
3638  *	b. be owner of victim, or
3639  *	c. have CAP_FOWNER capability
3640  *  6. If the victim is append-only or immutable we can't do antyhing with
3641  *     links pointing to it.
3642  *  7. If the victim has an unknown uid or gid we can't change the inode.
3643  *  8. If we were asked to remove a directory and victim isn't one - ENOTDIR.
3644  *  9. If we were asked to remove a non-directory and victim isn't one - EISDIR.
3645  * 10. We can't remove a root or mountpoint.
3646  * 11. We don't allow removal of NFS sillyrenamed files; it's handled by
3647  *     nfs_async_unlink().
3648  */
3649 int may_delete_dentry(struct mnt_idmap *idmap, struct inode *dir,
3650 		      struct dentry *victim, bool isdir)
3651 {
3652 	struct inode *inode = d_backing_inode(victim);
3653 	int error;
3654 
3655 	if (d_is_negative(victim))
3656 		return -ENOENT;
3657 	BUG_ON(!inode);
3658 
3659 	BUG_ON(victim->d_parent->d_inode != dir);
3660 
3661 	/* Inode writeback is not safe when the uid or gid are invalid. */
3662 	if (!vfsuid_valid(i_uid_into_vfsuid(idmap, inode)) ||
3663 	    !vfsgid_valid(i_gid_into_vfsgid(idmap, inode)))
3664 		return -EOVERFLOW;
3665 
3666 	audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
3667 
3668 	error = inode_permission(idmap, dir, MAY_WRITE | MAY_EXEC);
3669 	if (error)
3670 		return error;
3671 	if (IS_APPEND(dir))
3672 		return -EPERM;
3673 
3674 	if (check_sticky(idmap, dir, inode) || IS_APPEND(inode) ||
3675 	    IS_IMMUTABLE(inode) || IS_SWAPFILE(inode) ||
3676 	    HAS_UNMAPPED_ID(idmap, inode))
3677 		return -EPERM;
3678 	if (isdir) {
3679 		if (!d_is_dir(victim))
3680 			return -ENOTDIR;
3681 		if (IS_ROOT(victim))
3682 			return -EBUSY;
3683 	} else if (d_is_dir(victim))
3684 		return -EISDIR;
3685 	if (IS_DEADDIR(dir))
3686 		return -ENOENT;
3687 	if (victim->d_flags & DCACHE_NFSFS_RENAMED)
3688 		return -EBUSY;
3689 	return 0;
3690 }
3691 EXPORT_SYMBOL(may_delete_dentry);
3692 
3693 /*	Check whether we can create an object with dentry child in directory
3694  *  dir.
3695  *  1. We can't do it if child already exists (open has special treatment for
3696  *     this case, but since we are inlined it's OK)
3697  *  2. We can't do it if dir is read-only (done in permission())
3698  *  3. We can't do it if the fs can't represent the fsuid or fsgid.
3699  *  4. We should have write and exec permissions on dir
3700  *  5. We can't do it if dir is immutable (done in permission())
3701  */
3702 int may_create_dentry(struct mnt_idmap *idmap,
3703 		      struct inode *dir, struct dentry *child)
3704 {
3705 	audit_inode_child(dir, child, AUDIT_TYPE_CHILD_CREATE);
3706 	if (child->d_inode)
3707 		return -EEXIST;
3708 	if (IS_DEADDIR(dir))
3709 		return -ENOENT;
3710 	if (!fsuidgid_has_mapping(dir->i_sb, idmap))
3711 		return -EOVERFLOW;
3712 
3713 	return inode_permission(idmap, dir, MAY_WRITE | MAY_EXEC);
3714 }
3715 EXPORT_SYMBOL(may_create_dentry);
3716 
3717 // p1 != p2, both are on the same filesystem, ->s_vfs_rename_mutex is held
3718 static struct dentry *lock_two_directories(struct dentry *p1, struct dentry *p2)
3719 {
3720 	struct dentry *p = p1, *q = p2, *r;
3721 
3722 	while ((r = p->d_parent) != p2 && r != p)
3723 		p = r;
3724 	if (r == p2) {
3725 		// p is a child of p2 and an ancestor of p1 or p1 itself
3726 		inode_lock_nested(p2->d_inode, I_MUTEX_PARENT);
3727 		inode_lock_nested(p1->d_inode, I_MUTEX_PARENT2);
3728 		return p;
3729 	}
3730 	// p is the root of connected component that contains p1
3731 	// p2 does not occur on the path from p to p1
3732 	while ((r = q->d_parent) != p1 && r != p && r != q)
3733 		q = r;
3734 	if (r == p1) {
3735 		// q is a child of p1 and an ancestor of p2 or p2 itself
3736 		inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
3737 		inode_lock_nested(p2->d_inode, I_MUTEX_PARENT2);
3738 		return q;
3739 	} else if (likely(r == p)) {
3740 		// both p2 and p1 are descendents of p
3741 		inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
3742 		inode_lock_nested(p2->d_inode, I_MUTEX_PARENT2);
3743 		return NULL;
3744 	} else { // no common ancestor at the time we'd been called
3745 		mutex_unlock(&p1->d_sb->s_vfs_rename_mutex);
3746 		return ERR_PTR(-EXDEV);
3747 	}
3748 }
3749 
3750 /*
3751  * p1 and p2 should be directories on the same fs.
3752  */
3753 struct dentry *lock_rename(struct dentry *p1, struct dentry *p2)
3754 {
3755 	if (p1 == p2) {
3756 		inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
3757 		return NULL;
3758 	}
3759 
3760 	mutex_lock(&p1->d_sb->s_vfs_rename_mutex);
3761 	return lock_two_directories(p1, p2);
3762 }
3763 EXPORT_SYMBOL(lock_rename);
3764 
3765 /*
3766  * c1 and p2 should be on the same fs.
3767  */
3768 struct dentry *lock_rename_child(struct dentry *c1, struct dentry *p2)
3769 {
3770 	if (READ_ONCE(c1->d_parent) == p2) {
3771 		/*
3772 		 * hopefully won't need to touch ->s_vfs_rename_mutex at all.
3773 		 */
3774 		inode_lock_nested(p2->d_inode, I_MUTEX_PARENT);
3775 		/*
3776 		 * now that p2 is locked, nobody can move in or out of it,
3777 		 * so the test below is safe.
3778 		 */
3779 		if (likely(c1->d_parent == p2))
3780 			return NULL;
3781 
3782 		/*
3783 		 * c1 got moved out of p2 while we'd been taking locks;
3784 		 * unlock and fall back to slow case.
3785 		 */
3786 		inode_unlock(p2->d_inode);
3787 	}
3788 
3789 	mutex_lock(&c1->d_sb->s_vfs_rename_mutex);
3790 	/*
3791 	 * nobody can move out of any directories on this fs.
3792 	 */
3793 	if (likely(c1->d_parent != p2))
3794 		return lock_two_directories(c1->d_parent, p2);
3795 
3796 	/*
3797 	 * c1 got moved into p2 while we were taking locks;
3798 	 * we need p2 locked and ->s_vfs_rename_mutex unlocked,
3799 	 * for consistency with lock_rename().
3800 	 */
3801 	inode_lock_nested(p2->d_inode, I_MUTEX_PARENT);
3802 	mutex_unlock(&c1->d_sb->s_vfs_rename_mutex);
3803 	return NULL;
3804 }
3805 EXPORT_SYMBOL(lock_rename_child);
3806 
3807 void unlock_rename(struct dentry *p1, struct dentry *p2)
3808 {
3809 	inode_unlock(p1->d_inode);
3810 	if (p1 != p2) {
3811 		inode_unlock(p2->d_inode);
3812 		mutex_unlock(&p1->d_sb->s_vfs_rename_mutex);
3813 	}
3814 }
3815 EXPORT_SYMBOL(unlock_rename);
3816 
3817 /**
3818  * __start_renaming - lookup and lock names for rename
3819  * @rd:           rename data containing parents and flags, and
3820  *                for receiving found dentries
3821  * @lookup_flags: extra flags to pass to ->lookup (e.g. LOOKUP_REVAL,
3822  *                LOOKUP_NO_SYMLINKS etc).
3823  * @old_last:     name of object in @rd.old_parent
3824  * @new_last:     name of object in @rd.new_parent
3825  *
3826  * Look up two names and ensure locks are in place for
3827  * rename.
3828  *
3829  * On success the found dentries are stored in @rd.old_dentry,
3830  * @rd.new_dentry and an extra ref is taken on @rd.old_parent.
3831  * These references and the lock are dropped by end_renaming().
3832  *
3833  * The passed in qstrs must have the hash calculated, and no permission
3834  * checking is performed.
3835  *
3836  * Returns: zero or an error.
3837  */
3838 static int
3839 __start_renaming(struct renamedata *rd, int lookup_flags,
3840 		 struct qstr *old_last, struct qstr *new_last)
3841 {
3842 	struct dentry *trap;
3843 	struct dentry *d1, *d2;
3844 	int target_flags = LOOKUP_RENAME_TARGET | LOOKUP_CREATE;
3845 	int err;
3846 
3847 	if (rd->flags & RENAME_EXCHANGE)
3848 		target_flags = 0;
3849 	if (rd->flags & RENAME_NOREPLACE)
3850 		target_flags |= LOOKUP_EXCL;
3851 
3852 	trap = lock_rename(rd->old_parent, rd->new_parent);
3853 	if (IS_ERR(trap))
3854 		return PTR_ERR(trap);
3855 
3856 	d1 = lookup_one_qstr_excl(old_last, rd->old_parent,
3857 				  lookup_flags);
3858 	err = PTR_ERR(d1);
3859 	if (IS_ERR(d1))
3860 		goto out_unlock;
3861 
3862 	d2 = lookup_one_qstr_excl(new_last, rd->new_parent,
3863 				  lookup_flags | target_flags);
3864 	err = PTR_ERR(d2);
3865 	if (IS_ERR(d2))
3866 		goto out_dput_d1;
3867 
3868 	if (d1 == trap) {
3869 		/* source is an ancestor of target */
3870 		err = -EINVAL;
3871 		goto out_dput_d2;
3872 	}
3873 
3874 	if (d2 == trap) {
3875 		/* target is an ancestor of source */
3876 		if (rd->flags & RENAME_EXCHANGE)
3877 			err = -EINVAL;
3878 		else
3879 			err = -ENOTEMPTY;
3880 		goto out_dput_d2;
3881 	}
3882 
3883 	rd->old_dentry = d1;
3884 	rd->new_dentry = d2;
3885 	dget(rd->old_parent);
3886 	return 0;
3887 
3888 out_dput_d2:
3889 	dput(d2);
3890 out_dput_d1:
3891 	dput(d1);
3892 out_unlock:
3893 	unlock_rename(rd->old_parent, rd->new_parent);
3894 	return err;
3895 }
3896 
3897 /**
3898  * start_renaming - lookup and lock names for rename with permission checking
3899  * @rd:           rename data containing parents and flags, and
3900  *                for receiving found dentries
3901  * @lookup_flags: extra flags to pass to ->lookup (e.g. LOOKUP_REVAL,
3902  *                LOOKUP_NO_SYMLINKS etc).
3903  * @old_last:     name of object in @rd.old_parent
3904  * @new_last:     name of object in @rd.new_parent
3905  *
3906  * Look up two names and ensure locks are in place for
3907  * rename.
3908  *
3909  * On success the found dentries are stored in @rd.old_dentry,
3910  * @rd.new_dentry.  Also the refcount on @rd->old_parent is increased.
3911  * These references and the lock are dropped by end_renaming().
3912  *
3913  * The passed in qstrs need not have the hash calculated, and basic
3914  * eXecute permission checking is performed against @rd.mnt_idmap.
3915  *
3916  * Returns: zero or an error.
3917  */
3918 int start_renaming(struct renamedata *rd, int lookup_flags,
3919 		   struct qstr *old_last, struct qstr *new_last)
3920 {
3921 	int err;
3922 
3923 	err = lookup_one_common(rd->mnt_idmap, old_last, rd->old_parent);
3924 	if (err)
3925 		return err;
3926 	err = lookup_one_common(rd->mnt_idmap, new_last, rd->new_parent);
3927 	if (err)
3928 		return err;
3929 	return __start_renaming(rd, lookup_flags, old_last, new_last);
3930 }
3931 EXPORT_SYMBOL(start_renaming);
3932 
3933 static int
3934 __start_renaming_dentry(struct renamedata *rd, int lookup_flags,
3935 			struct dentry *old_dentry, struct qstr *new_last)
3936 {
3937 	struct dentry *trap;
3938 	struct dentry *d2;
3939 	int target_flags = LOOKUP_RENAME_TARGET | LOOKUP_CREATE;
3940 	int err;
3941 
3942 	if (rd->flags & RENAME_EXCHANGE)
3943 		target_flags = 0;
3944 	if (rd->flags & RENAME_NOREPLACE)
3945 		target_flags |= LOOKUP_EXCL;
3946 
3947 	/* Already have the dentry - need to be sure to lock the correct parent */
3948 	trap = lock_rename_child(old_dentry, rd->new_parent);
3949 	if (IS_ERR(trap))
3950 		return PTR_ERR(trap);
3951 	if (d_unhashed(old_dentry) ||
3952 	    (rd->old_parent && rd->old_parent != old_dentry->d_parent)) {
3953 		/* dentry was removed, or moved and explicit parent requested */
3954 		err = -EINVAL;
3955 		goto out_unlock;
3956 	}
3957 
3958 	d2 = lookup_one_qstr_excl(new_last, rd->new_parent,
3959 				  lookup_flags | target_flags);
3960 	err = PTR_ERR(d2);
3961 	if (IS_ERR(d2))
3962 		goto out_unlock;
3963 
3964 	if (old_dentry == trap) {
3965 		/* source is an ancestor of target */
3966 		err = -EINVAL;
3967 		goto out_dput_d2;
3968 	}
3969 
3970 	if (d2 == trap) {
3971 		/* target is an ancestor of source */
3972 		if (rd->flags & RENAME_EXCHANGE)
3973 			err = -EINVAL;
3974 		else
3975 			err = -ENOTEMPTY;
3976 		goto out_dput_d2;
3977 	}
3978 
3979 	rd->old_dentry = dget(old_dentry);
3980 	rd->new_dentry = d2;
3981 	rd->old_parent = dget(old_dentry->d_parent);
3982 	return 0;
3983 
3984 out_dput_d2:
3985 	dput(d2);
3986 out_unlock:
3987 	unlock_rename(old_dentry->d_parent, rd->new_parent);
3988 	return err;
3989 }
3990 
3991 /**
3992  * start_renaming_dentry - lookup and lock name for rename with permission checking
3993  * @rd:           rename data containing parents and flags, and
3994  *                for receiving found dentries
3995  * @lookup_flags: extra flags to pass to ->lookup (e.g. LOOKUP_REVAL,
3996  *                LOOKUP_NO_SYMLINKS etc).
3997  * @old_dentry:   dentry of name to move
3998  * @new_last:     name of target in @rd.new_parent
3999  *
4000  * Look up target name and ensure locks are in place for
4001  * rename.
4002  *
4003  * On success the found dentry is stored in @rd.new_dentry and
4004  * @rd.old_parent is confirmed to be the parent of @old_dentry.  If it
4005  * was originally %NULL, it is set.  In either case a reference is taken
4006  * so that end_renaming() can have a stable reference to unlock.
4007  *
4008  * References and the lock can be dropped with end_renaming()
4009  *
4010  * The passed in qstr need not have the hash calculated, and basic
4011  * eXecute permission checking is performed against @rd.mnt_idmap.
4012  *
4013  * Returns: zero or an error.
4014  */
4015 int start_renaming_dentry(struct renamedata *rd, int lookup_flags,
4016 			  struct dentry *old_dentry, struct qstr *new_last)
4017 {
4018 	int err;
4019 
4020 	err = lookup_one_common(rd->mnt_idmap, new_last, rd->new_parent);
4021 	if (err)
4022 		return err;
4023 	return __start_renaming_dentry(rd, lookup_flags, old_dentry, new_last);
4024 }
4025 EXPORT_SYMBOL(start_renaming_dentry);
4026 
4027 /**
4028  * start_renaming_two_dentries - Lock to dentries in given parents for rename
4029  * @rd:           rename data containing parent
4030  * @old_dentry:   dentry of name to move
4031  * @new_dentry:   dentry to move to
4032  *
4033  * Ensure locks are in place for rename and check parentage is still correct.
4034  *
4035  * On success the two dentries are stored in @rd.old_dentry and
4036  * @rd.new_dentry and @rd.old_parent and @rd.new_parent are confirmed to
4037  * be the parents of the dentries.
4038  *
4039  * References and the lock can be dropped with end_renaming()
4040  *
4041  * Returns: zero or an error.
4042  */
4043 int
4044 start_renaming_two_dentries(struct renamedata *rd,
4045 			    struct dentry *old_dentry, struct dentry *new_dentry)
4046 {
4047 	struct dentry *trap;
4048 	int err;
4049 
4050 	/* Already have the dentry - need to be sure to lock the correct parent */
4051 	trap = lock_rename_child(old_dentry, rd->new_parent);
4052 	if (IS_ERR(trap))
4053 		return PTR_ERR(trap);
4054 	err = -EINVAL;
4055 	if (d_unhashed(old_dentry) ||
4056 	    (rd->old_parent && rd->old_parent != old_dentry->d_parent))
4057 		/* old_dentry was removed, or moved and explicit parent requested */
4058 		goto out_unlock;
4059 	if (d_unhashed(new_dentry) ||
4060 	    rd->new_parent != new_dentry->d_parent)
4061 		/* new_dentry was removed or moved */
4062 		goto out_unlock;
4063 
4064 	if (old_dentry == trap)
4065 		/* source is an ancestor of target */
4066 		goto out_unlock;
4067 
4068 	if (new_dentry == trap) {
4069 		/* target is an ancestor of source */
4070 		if (rd->flags & RENAME_EXCHANGE)
4071 			err = -EINVAL;
4072 		else
4073 			err = -ENOTEMPTY;
4074 		goto out_unlock;
4075 	}
4076 
4077 	err = -EEXIST;
4078 	if (d_is_positive(new_dentry) && (rd->flags & RENAME_NOREPLACE))
4079 		goto out_unlock;
4080 
4081 	rd->old_dentry = dget(old_dentry);
4082 	rd->new_dentry = dget(new_dentry);
4083 	rd->old_parent = dget(old_dentry->d_parent);
4084 	return 0;
4085 
4086 out_unlock:
4087 	unlock_rename(old_dentry->d_parent, rd->new_parent);
4088 	return err;
4089 }
4090 EXPORT_SYMBOL(start_renaming_two_dentries);
4091 
4092 void end_renaming(struct renamedata *rd)
4093 {
4094 	unlock_rename(rd->old_parent, rd->new_parent);
4095 	dput(rd->old_dentry);
4096 	dput(rd->new_dentry);
4097 	dput(rd->old_parent);
4098 }
4099 EXPORT_SYMBOL(end_renaming);
4100 
4101 /**
4102  * vfs_prepare_mode - prepare the mode to be used for a new inode
4103  * @idmap:	idmap of the mount the inode was found from
4104  * @dir:	parent directory of the new inode
4105  * @mode:	mode of the new inode
4106  * @mask_perms:	allowed permission by the vfs
4107  * @type:	type of file to be created
4108  *
4109  * This helper consolidates and enforces vfs restrictions on the @mode of a new
4110  * object to be created.
4111  *
4112  * Umask stripping depends on whether the filesystem supports POSIX ACLs (see
4113  * the kernel documentation for mode_strip_umask()). Moving umask stripping
4114  * after setgid stripping allows the same ordering for both non-POSIX ACL and
4115  * POSIX ACL supporting filesystems.
4116  *
4117  * Note that it's currently valid for @type to be 0 if a directory is created.
4118  * Filesystems raise that flag individually and we need to check whether each
4119  * filesystem can deal with receiving S_IFDIR from the vfs before we enforce a
4120  * non-zero type.
4121  *
4122  * Returns: mode to be passed to the filesystem
4123  */
4124 static inline umode_t vfs_prepare_mode(struct mnt_idmap *idmap,
4125 				       const struct inode *dir, umode_t mode,
4126 				       umode_t mask_perms, umode_t type)
4127 {
4128 	mode = mode_strip_sgid(idmap, dir, mode);
4129 	mode = mode_strip_umask(dir, mode);
4130 
4131 	/*
4132 	 * Apply the vfs mandated allowed permission mask and set the type of
4133 	 * file to be created before we call into the filesystem.
4134 	 */
4135 	mode &= (mask_perms & ~S_IFMT);
4136 	mode |= (type & S_IFMT);
4137 
4138 	return mode;
4139 }
4140 
4141 /**
4142  * vfs_create - create new file
4143  * @idmap:	idmap of the mount the inode was found from
4144  * @dentry:	dentry of the child file
4145  * @mode:	mode of the child file
4146  * @di:		returns parent inode, if the inode is delegated.
4147  *
4148  * Create a new file.
4149  *
4150  * If the inode has been found through an idmapped mount the idmap of
4151  * the vfsmount must be passed through @idmap. This function will then take
4152  * care to map the inode according to @idmap before checking permissions.
4153  * On non-idmapped mounts or if permission checking is to be performed on the
4154  * raw inode simply pass @nop_mnt_idmap.
4155  */
4156 int vfs_create(struct mnt_idmap *idmap, struct dentry *dentry, umode_t mode,
4157 	       struct delegated_inode *di)
4158 {
4159 	struct inode *dir = d_inode(dentry->d_parent);
4160 	int error;
4161 
4162 	error = may_create_dentry(idmap, dir, dentry);
4163 	if (error)
4164 		return error;
4165 
4166 	if (!dir->i_op->create)
4167 		return -EACCES;	/* shouldn't it be ENOSYS? */
4168 
4169 	mode = vfs_prepare_mode(idmap, dir, mode, S_IALLUGO, S_IFREG);
4170 	error = security_inode_create(dir, dentry, mode);
4171 	if (error)
4172 		return error;
4173 	error = try_break_deleg(dir, di);
4174 	if (error)
4175 		return error;
4176 	error = dir->i_op->create(idmap, dir, dentry, mode, true);
4177 	if (!error)
4178 		fsnotify_create(dir, dentry);
4179 	return error;
4180 }
4181 EXPORT_SYMBOL(vfs_create);
4182 
4183 int vfs_mkobj(struct dentry *dentry, umode_t mode,
4184 		int (*f)(struct dentry *, umode_t, void *),
4185 		void *arg)
4186 {
4187 	struct inode *dir = dentry->d_parent->d_inode;
4188 	int error = may_create_dentry(&nop_mnt_idmap, dir, dentry);
4189 	if (error)
4190 		return error;
4191 
4192 	mode &= S_IALLUGO;
4193 	mode |= S_IFREG;
4194 	error = security_inode_create(dir, dentry, mode);
4195 	if (error)
4196 		return error;
4197 	error = f(dentry, mode, arg);
4198 	if (!error)
4199 		fsnotify_create(dir, dentry);
4200 	return error;
4201 }
4202 EXPORT_SYMBOL(vfs_mkobj);
4203 
4204 bool may_open_dev(const struct path *path)
4205 {
4206 	return !(path->mnt->mnt_flags & MNT_NODEV) &&
4207 		!(path->mnt->mnt_sb->s_iflags & SB_I_NODEV);
4208 }
4209 
4210 static int may_open(struct mnt_idmap *idmap, const struct path *path,
4211 		    int acc_mode, int flag)
4212 {
4213 	struct dentry *dentry = path->dentry;
4214 	struct inode *inode = dentry->d_inode;
4215 	int error;
4216 
4217 	if (!inode)
4218 		return -ENOENT;
4219 
4220 	switch (inode->i_mode & S_IFMT) {
4221 	case S_IFLNK:
4222 		return -ELOOP;
4223 	case S_IFDIR:
4224 		if (acc_mode & MAY_WRITE)
4225 			return -EISDIR;
4226 		if (acc_mode & MAY_EXEC)
4227 			return -EACCES;
4228 		break;
4229 	case S_IFBLK:
4230 	case S_IFCHR:
4231 		if (!may_open_dev(path))
4232 			return -EACCES;
4233 		fallthrough;
4234 	case S_IFIFO:
4235 	case S_IFSOCK:
4236 		if (acc_mode & MAY_EXEC)
4237 			return -EACCES;
4238 		flag &= ~O_TRUNC;
4239 		break;
4240 	case S_IFREG:
4241 		if ((acc_mode & MAY_EXEC) && path_noexec(path))
4242 			return -EACCES;
4243 		break;
4244 	default:
4245 		VFS_BUG_ON_INODE(!IS_ANON_FILE(inode), inode);
4246 	}
4247 
4248 	error = inode_permission(idmap, inode, MAY_OPEN | acc_mode);
4249 	if (error)
4250 		return error;
4251 
4252 	/*
4253 	 * An append-only file must be opened in append mode for writing.
4254 	 */
4255 	if (IS_APPEND(inode)) {
4256 		if  ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND))
4257 			return -EPERM;
4258 		if (flag & O_TRUNC)
4259 			return -EPERM;
4260 	}
4261 
4262 	/* O_NOATIME can only be set by the owner or superuser */
4263 	if (flag & O_NOATIME && !inode_owner_or_capable(idmap, inode))
4264 		return -EPERM;
4265 
4266 	return 0;
4267 }
4268 
4269 static int handle_truncate(struct mnt_idmap *idmap, struct file *filp)
4270 {
4271 	const struct path *path = &filp->f_path;
4272 	struct inode *inode = path->dentry->d_inode;
4273 	int error = get_write_access(inode);
4274 	if (error)
4275 		return error;
4276 
4277 	error = security_file_truncate(filp);
4278 	if (!error) {
4279 		error = do_truncate(idmap, path->dentry, 0,
4280 				    ATTR_MTIME|ATTR_CTIME|ATTR_OPEN,
4281 				    filp);
4282 	}
4283 	put_write_access(inode);
4284 	return error;
4285 }
4286 
4287 static inline int open_to_namei_flags(int flag)
4288 {
4289 	if ((flag & O_ACCMODE) == 3)
4290 		flag--;
4291 	return flag;
4292 }
4293 
4294 static int may_o_create(struct mnt_idmap *idmap,
4295 			const struct path *dir, struct dentry *dentry,
4296 			umode_t mode)
4297 {
4298 	int error = security_path_mknod(dir, dentry, mode, 0);
4299 	if (error)
4300 		return error;
4301 
4302 	if (!fsuidgid_has_mapping(dir->dentry->d_sb, idmap))
4303 		return -EOVERFLOW;
4304 
4305 	error = inode_permission(idmap, dir->dentry->d_inode,
4306 				 MAY_WRITE | MAY_EXEC);
4307 	if (error)
4308 		return error;
4309 
4310 	return security_inode_create(dir->dentry->d_inode, dentry, mode);
4311 }
4312 
4313 /*
4314  * Attempt to atomically look up, create and open a file from a negative
4315  * dentry.
4316  *
4317  * Returns 0 if successful.  The file will have been created and attached to
4318  * @file by the filesystem calling finish_open().
4319  *
4320  * If the file was looked up only or didn't need creating, FMODE_OPENED won't
4321  * be set.  The caller will need to perform the open themselves.  @path will
4322  * have been updated to point to the new dentry.  This may be negative.
4323  *
4324  * Returns an error code otherwise.
4325  */
4326 static struct dentry *atomic_open(const struct path *path, struct dentry *dentry,
4327 				  struct file *file,
4328 				  int open_flag, umode_t mode)
4329 {
4330 	struct dentry *const DENTRY_NOT_SET = (void *) -1UL;
4331 	struct inode *dir =  path->dentry->d_inode;
4332 	int error;
4333 
4334 	file->__f_path.dentry = DENTRY_NOT_SET;
4335 	file->__f_path.mnt = path->mnt;
4336 	error = dir->i_op->atomic_open(dir, dentry, file,
4337 				       open_to_namei_flags(open_flag), mode);
4338 	d_lookup_done(dentry);
4339 	if (!error) {
4340 		if (file->f_mode & FMODE_OPENED) {
4341 			if (unlikely(dentry != file->f_path.dentry)) {
4342 				dput(dentry);
4343 				dentry = dget(file->f_path.dentry);
4344 			}
4345 		} else if (WARN_ON(file->f_path.dentry == DENTRY_NOT_SET)) {
4346 			error = -EIO;
4347 		} else {
4348 			if (file->f_path.dentry) {
4349 				dput(dentry);
4350 				dentry = file->f_path.dentry;
4351 			}
4352 			if (unlikely(d_is_negative(dentry)))
4353 				error = -ENOENT;
4354 		}
4355 	}
4356 	if (error) {
4357 		dput(dentry);
4358 		dentry = ERR_PTR(error);
4359 	}
4360 	return dentry;
4361 }
4362 
4363 /*
4364  * Look up and maybe create and open the last component.
4365  *
4366  * Must be called with parent locked (exclusive in O_CREAT case).
4367  *
4368  * Returns 0 on success, that is, if
4369  *  the file was successfully atomically created (if necessary) and opened, or
4370  *  the file was not completely opened at this time, though lookups and
4371  *  creations were performed.
4372  * These case are distinguished by presence of FMODE_OPENED on file->f_mode.
4373  * In the latter case dentry returned in @path might be negative if O_CREAT
4374  * hadn't been specified.
4375  *
4376  * An error code is returned on failure.
4377  */
4378 static struct dentry *lookup_open(struct nameidata *nd, struct file *file,
4379 				  const struct open_flags *op,
4380 				  bool got_write, struct delegated_inode *delegated_inode)
4381 {
4382 	struct mnt_idmap *idmap;
4383 	struct dentry *dir = nd->path.dentry;
4384 	struct inode *dir_inode = dir->d_inode;
4385 	int open_flag = op->open_flag;
4386 	struct dentry *dentry;
4387 	int error, create_error = 0;
4388 	umode_t mode = op->mode;
4389 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
4390 
4391 	if (unlikely(IS_DEADDIR(dir_inode)))
4392 		return ERR_PTR(-ENOENT);
4393 
4394 	file->f_mode &= ~FMODE_CREATED;
4395 	dentry = d_lookup(dir, &nd->last);
4396 	for (;;) {
4397 		if (!dentry) {
4398 			dentry = d_alloc_parallel(dir, &nd->last, &wq);
4399 			if (IS_ERR(dentry))
4400 				return dentry;
4401 		}
4402 		if (d_in_lookup(dentry))
4403 			break;
4404 
4405 		error = d_revalidate(dir_inode, &nd->last, dentry, nd->flags);
4406 		if (likely(error > 0))
4407 			break;
4408 		if (error)
4409 			goto out_dput;
4410 		d_invalidate(dentry);
4411 		dput(dentry);
4412 		dentry = NULL;
4413 	}
4414 	if (dentry->d_inode) {
4415 		/* Cached positive dentry: will open in f_op->open */
4416 		return dentry;
4417 	}
4418 
4419 	if (open_flag & O_CREAT)
4420 		audit_inode(nd->name, dir, AUDIT_INODE_PARENT);
4421 
4422 	/*
4423 	 * Checking write permission is tricky, bacuse we don't know if we are
4424 	 * going to actually need it: O_CREAT opens should work as long as the
4425 	 * file exists.  But checking existence breaks atomicity.  The trick is
4426 	 * to check access and if not granted clear O_CREAT from the flags.
4427 	 *
4428 	 * Another problem is returing the "right" error value (e.g. for an
4429 	 * O_EXCL open we want to return EEXIST not EROFS).
4430 	 */
4431 	if (unlikely(!got_write))
4432 		open_flag &= ~O_TRUNC;
4433 	idmap = mnt_idmap(nd->path.mnt);
4434 	if (open_flag & O_CREAT) {
4435 		if (open_flag & O_EXCL)
4436 			open_flag &= ~O_TRUNC;
4437 		mode = vfs_prepare_mode(idmap, dir->d_inode, mode, mode, mode);
4438 		if (likely(got_write))
4439 			create_error = may_o_create(idmap, &nd->path,
4440 						    dentry, mode);
4441 		else
4442 			create_error = -EROFS;
4443 	}
4444 	if (create_error)
4445 		open_flag &= ~O_CREAT;
4446 	if (dir_inode->i_op->atomic_open) {
4447 		if (nd->flags & LOOKUP_DIRECTORY)
4448 			open_flag |= O_DIRECTORY;
4449 		dentry = atomic_open(&nd->path, dentry, file, open_flag, mode);
4450 		if (unlikely(create_error) && dentry == ERR_PTR(-ENOENT))
4451 			dentry = ERR_PTR(create_error);
4452 		return dentry;
4453 	}
4454 
4455 	if (d_in_lookup(dentry)) {
4456 		struct dentry *res = dir_inode->i_op->lookup(dir_inode, dentry,
4457 							     nd->flags);
4458 		d_lookup_done(dentry);
4459 		if (unlikely(res)) {
4460 			if (IS_ERR(res)) {
4461 				error = PTR_ERR(res);
4462 				goto out_dput;
4463 			}
4464 			dput(dentry);
4465 			dentry = res;
4466 		}
4467 	}
4468 
4469 	/* Negative dentry, just create the file */
4470 	if (!dentry->d_inode && (open_flag & O_CREAT)) {
4471 		/* but break the directory lease first! */
4472 		error = try_break_deleg(dir_inode, delegated_inode);
4473 		if (error)
4474 			goto out_dput;
4475 
4476 		file->f_mode |= FMODE_CREATED;
4477 		audit_inode_child(dir_inode, dentry, AUDIT_TYPE_CHILD_CREATE);
4478 		if (!dir_inode->i_op->create) {
4479 			error = -EACCES;
4480 			goto out_dput;
4481 		}
4482 
4483 		error = dir_inode->i_op->create(idmap, dir_inode, dentry,
4484 						mode, open_flag & O_EXCL);
4485 		if (error)
4486 			goto out_dput;
4487 	}
4488 	if (unlikely(create_error) && !dentry->d_inode) {
4489 		error = create_error;
4490 		goto out_dput;
4491 	}
4492 	return dentry;
4493 
4494 out_dput:
4495 	dput(dentry);
4496 	return ERR_PTR(error);
4497 }
4498 
4499 static inline bool trailing_slashes(struct nameidata *nd)
4500 {
4501 	return (bool)nd->last.name[nd->last.len];
4502 }
4503 
4504 static struct dentry *lookup_fast_for_open(struct nameidata *nd, int open_flag)
4505 {
4506 	struct dentry *dentry;
4507 
4508 	if (open_flag & O_CREAT) {
4509 		if (trailing_slashes(nd))
4510 			return ERR_PTR(-EISDIR);
4511 
4512 		/* Don't bother on an O_EXCL create */
4513 		if (open_flag & O_EXCL)
4514 			return NULL;
4515 	}
4516 
4517 	if (trailing_slashes(nd))
4518 		nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
4519 
4520 	dentry = lookup_fast(nd);
4521 	if (IS_ERR_OR_NULL(dentry))
4522 		return dentry;
4523 
4524 	if (open_flag & O_CREAT) {
4525 		/* Discard negative dentries. Need inode_lock to do the create */
4526 		if (!dentry->d_inode) {
4527 			if (!(nd->flags & LOOKUP_RCU))
4528 				dput(dentry);
4529 			dentry = NULL;
4530 		}
4531 	}
4532 	return dentry;
4533 }
4534 
4535 static const char *open_last_lookups(struct nameidata *nd,
4536 		   struct file *file, const struct open_flags *op)
4537 {
4538 	struct delegated_inode delegated_inode = { };
4539 	struct dentry *dir = nd->path.dentry;
4540 	int open_flag = op->open_flag;
4541 	bool got_write = false;
4542 	struct dentry *dentry;
4543 	const char *res;
4544 
4545 	nd->flags |= op->intent;
4546 
4547 	if (nd->last_type != LAST_NORM) {
4548 		if (nd->depth)
4549 			put_link(nd);
4550 		return handle_dots(nd, nd->last_type);
4551 	}
4552 
4553 	/* We _can_ be in RCU mode here */
4554 	dentry = lookup_fast_for_open(nd, open_flag);
4555 	if (IS_ERR(dentry))
4556 		return ERR_CAST(dentry);
4557 
4558 	if (likely(dentry))
4559 		goto finish_lookup;
4560 
4561 	if (!(open_flag & O_CREAT)) {
4562 		if (WARN_ON_ONCE(nd->flags & LOOKUP_RCU))
4563 			return ERR_PTR(-ECHILD);
4564 	} else {
4565 		if (nd->flags & LOOKUP_RCU) {
4566 			if (!try_to_unlazy(nd))
4567 				return ERR_PTR(-ECHILD);
4568 		}
4569 	}
4570 retry:
4571 	if (open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) {
4572 		got_write = !mnt_want_write(nd->path.mnt);
4573 		/*
4574 		 * do _not_ fail yet - we might not need that or fail with
4575 		 * a different error; let lookup_open() decide; we'll be
4576 		 * dropping this one anyway.
4577 		 */
4578 	}
4579 	if (open_flag & O_CREAT)
4580 		inode_lock(dir->d_inode);
4581 	else
4582 		inode_lock_shared(dir->d_inode);
4583 	dentry = lookup_open(nd, file, op, got_write, &delegated_inode);
4584 	if (!IS_ERR(dentry)) {
4585 		if (file->f_mode & FMODE_CREATED)
4586 			fsnotify_create(dir->d_inode, dentry);
4587 		if (file->f_mode & FMODE_OPENED)
4588 			fsnotify_open(file);
4589 	}
4590 	if (open_flag & O_CREAT)
4591 		inode_unlock(dir->d_inode);
4592 	else
4593 		inode_unlock_shared(dir->d_inode);
4594 
4595 	if (got_write)
4596 		mnt_drop_write(nd->path.mnt);
4597 
4598 	if (IS_ERR(dentry)) {
4599 		if (is_delegated(&delegated_inode)) {
4600 			int error = break_deleg_wait(&delegated_inode);
4601 
4602 			if (!error)
4603 				goto retry;
4604 			return ERR_PTR(error);
4605 		}
4606 		return ERR_CAST(dentry);
4607 	}
4608 
4609 	if (file->f_mode & (FMODE_OPENED | FMODE_CREATED)) {
4610 		dput(nd->path.dentry);
4611 		nd->path.dentry = dentry;
4612 		return NULL;
4613 	}
4614 
4615 finish_lookup:
4616 	if (nd->depth)
4617 		put_link(nd);
4618 	res = step_into(nd, WALK_TRAILING, dentry);
4619 	if (unlikely(res))
4620 		nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL);
4621 	return res;
4622 }
4623 
4624 /*
4625  * Handle the last step of open()
4626  */
4627 static int do_open(struct nameidata *nd,
4628 		   struct file *file, const struct open_flags *op)
4629 {
4630 	struct mnt_idmap *idmap;
4631 	int open_flag = op->open_flag;
4632 	bool do_truncate;
4633 	int acc_mode;
4634 	int error;
4635 
4636 	if (!(file->f_mode & (FMODE_OPENED | FMODE_CREATED))) {
4637 		error = complete_walk(nd);
4638 		if (error)
4639 			return error;
4640 	}
4641 	if (!(file->f_mode & FMODE_CREATED))
4642 		audit_inode(nd->name, nd->path.dentry, 0);
4643 	idmap = mnt_idmap(nd->path.mnt);
4644 	if (open_flag & O_CREAT) {
4645 		if ((open_flag & O_EXCL) && !(file->f_mode & FMODE_CREATED))
4646 			return -EEXIST;
4647 		if (d_is_dir(nd->path.dentry))
4648 			return -EISDIR;
4649 		error = may_create_in_sticky(idmap, nd,
4650 					     d_backing_inode(nd->path.dentry));
4651 		if (unlikely(error))
4652 			return error;
4653 	}
4654 	if ((nd->flags & LOOKUP_DIRECTORY) && !d_can_lookup(nd->path.dentry))
4655 		return -ENOTDIR;
4656 
4657 	do_truncate = false;
4658 	acc_mode = op->acc_mode;
4659 	if (file->f_mode & FMODE_CREATED) {
4660 		/* Don't check for write permission, don't truncate */
4661 		open_flag &= ~O_TRUNC;
4662 		acc_mode = 0;
4663 	} else if (d_is_reg(nd->path.dentry) && open_flag & O_TRUNC) {
4664 		error = mnt_want_write(nd->path.mnt);
4665 		if (error)
4666 			return error;
4667 		do_truncate = true;
4668 	}
4669 	error = may_open(idmap, &nd->path, acc_mode, open_flag);
4670 	if (!error && !(file->f_mode & FMODE_OPENED))
4671 		error = vfs_open(&nd->path, file);
4672 	if (!error)
4673 		error = security_file_post_open(file, op->acc_mode);
4674 	if (!error && do_truncate)
4675 		error = handle_truncate(idmap, file);
4676 	if (unlikely(error > 0)) {
4677 		WARN_ON(1);
4678 		error = -EINVAL;
4679 	}
4680 	if (do_truncate)
4681 		mnt_drop_write(nd->path.mnt);
4682 	return error;
4683 }
4684 
4685 /**
4686  * vfs_tmpfile - create tmpfile
4687  * @idmap:	idmap of the mount the inode was found from
4688  * @parentpath:	pointer to the path of the base directory
4689  * @file:	file descriptor of the new tmpfile
4690  * @mode:	mode of the new tmpfile
4691  *
4692  * Create a temporary file.
4693  *
4694  * If the inode has been found through an idmapped mount the idmap of
4695  * the vfsmount must be passed through @idmap. This function will then take
4696  * care to map the inode according to @idmap before checking permissions.
4697  * On non-idmapped mounts or if permission checking is to be performed on the
4698  * raw inode simply pass @nop_mnt_idmap.
4699  */
4700 int vfs_tmpfile(struct mnt_idmap *idmap,
4701 		const struct path *parentpath,
4702 		struct file *file, umode_t mode)
4703 {
4704 	struct dentry *child;
4705 	struct inode *dir = d_inode(parentpath->dentry);
4706 	struct inode *inode;
4707 	int error;
4708 	int open_flag = file->f_flags;
4709 
4710 	/* we want directory to be writable */
4711 	error = inode_permission(idmap, dir, MAY_WRITE | MAY_EXEC);
4712 	if (error)
4713 		return error;
4714 	if (!dir->i_op->tmpfile)
4715 		return -EOPNOTSUPP;
4716 	child = d_alloc(parentpath->dentry, &slash_name);
4717 	if (unlikely(!child))
4718 		return -ENOMEM;
4719 	file->__f_path.mnt = parentpath->mnt;
4720 	file->__f_path.dentry = child;
4721 	mode = vfs_prepare_mode(idmap, dir, mode, mode, mode);
4722 	error = dir->i_op->tmpfile(idmap, dir, file, mode);
4723 	dput(child);
4724 	if (file->f_mode & FMODE_OPENED)
4725 		fsnotify_open(file);
4726 	if (error)
4727 		return error;
4728 	/* Don't check for other permissions, the inode was just created */
4729 	error = may_open(idmap, &file->f_path, 0, file->f_flags);
4730 	if (error)
4731 		return error;
4732 	inode = file_inode(file);
4733 	if (!(open_flag & O_EXCL)) {
4734 		spin_lock(&inode->i_lock);
4735 		inode_state_set(inode, I_LINKABLE);
4736 		spin_unlock(&inode->i_lock);
4737 	}
4738 	security_inode_post_create_tmpfile(idmap, inode);
4739 	return 0;
4740 }
4741 
4742 /**
4743  * kernel_tmpfile_open - open a tmpfile for kernel internal use
4744  * @idmap:	idmap of the mount the inode was found from
4745  * @parentpath:	path of the base directory
4746  * @mode:	mode of the new tmpfile
4747  * @open_flag:	flags
4748  * @cred:	credentials for open
4749  *
4750  * Create and open a temporary file.  The file is not accounted in nr_files,
4751  * hence this is only for kernel internal use, and must not be installed into
4752  * file tables or such.
4753  */
4754 struct file *kernel_tmpfile_open(struct mnt_idmap *idmap,
4755 				 const struct path *parentpath,
4756 				 umode_t mode, int open_flag,
4757 				 const struct cred *cred)
4758 {
4759 	struct file *file;
4760 	int error;
4761 
4762 	file = alloc_empty_file_noaccount(open_flag, cred);
4763 	if (IS_ERR(file))
4764 		return file;
4765 
4766 	error = vfs_tmpfile(idmap, parentpath, file, mode);
4767 	if (error) {
4768 		fput(file);
4769 		file = ERR_PTR(error);
4770 	}
4771 	return file;
4772 }
4773 EXPORT_SYMBOL(kernel_tmpfile_open);
4774 
4775 static int do_tmpfile(struct nameidata *nd, unsigned flags,
4776 		const struct open_flags *op,
4777 		struct file *file)
4778 {
4779 	struct path path;
4780 	int error = path_lookupat(nd, flags | LOOKUP_DIRECTORY, &path);
4781 
4782 	if (unlikely(error))
4783 		return error;
4784 	error = mnt_want_write(path.mnt);
4785 	if (unlikely(error))
4786 		goto out;
4787 	error = vfs_tmpfile(mnt_idmap(path.mnt), &path, file, op->mode);
4788 	if (error)
4789 		goto out2;
4790 	audit_inode(nd->name, file->f_path.dentry, 0);
4791 out2:
4792 	mnt_drop_write(path.mnt);
4793 out:
4794 	path_put(&path);
4795 	return error;
4796 }
4797 
4798 static int do_o_path(struct nameidata *nd, unsigned flags, struct file *file)
4799 {
4800 	struct path path;
4801 	int error = path_lookupat(nd, flags, &path);
4802 	if (!error) {
4803 		audit_inode(nd->name, path.dentry, 0);
4804 		error = vfs_open(&path, file);
4805 		path_put(&path);
4806 	}
4807 	return error;
4808 }
4809 
4810 static struct file *path_openat(struct nameidata *nd,
4811 			const struct open_flags *op, unsigned flags)
4812 {
4813 	struct file *file;
4814 	int error;
4815 
4816 	file = alloc_empty_file(op->open_flag, current_cred());
4817 	if (IS_ERR(file))
4818 		return file;
4819 
4820 	if (unlikely(file->f_flags & __O_TMPFILE)) {
4821 		error = do_tmpfile(nd, flags, op, file);
4822 	} else if (unlikely(file->f_flags & O_PATH)) {
4823 		error = do_o_path(nd, flags, file);
4824 	} else {
4825 		const char *s = path_init(nd, flags);
4826 		while (!(error = link_path_walk(s, nd)) &&
4827 		       (s = open_last_lookups(nd, file, op)) != NULL)
4828 			;
4829 		if (!error)
4830 			error = do_open(nd, file, op);
4831 		terminate_walk(nd);
4832 	}
4833 	if (likely(!error)) {
4834 		if (likely(file->f_mode & FMODE_OPENED))
4835 			return file;
4836 		WARN_ON(1);
4837 		error = -EINVAL;
4838 	}
4839 	fput_close(file);
4840 	if (error == -EOPENSTALE) {
4841 		if (flags & LOOKUP_RCU)
4842 			error = -ECHILD;
4843 		else
4844 			error = -ESTALE;
4845 	}
4846 	return ERR_PTR(error);
4847 }
4848 
4849 struct file *do_file_open(int dfd, struct filename *pathname,
4850 		const struct open_flags *op)
4851 {
4852 	struct nameidata nd;
4853 	int flags = op->lookup_flags;
4854 	struct file *filp;
4855 
4856 	if (IS_ERR(pathname))
4857 		return ERR_CAST(pathname);
4858 	set_nameidata(&nd, dfd, pathname, NULL);
4859 	filp = path_openat(&nd, op, flags | LOOKUP_RCU);
4860 	if (unlikely(filp == ERR_PTR(-ECHILD)))
4861 		filp = path_openat(&nd, op, flags);
4862 	if (unlikely(filp == ERR_PTR(-ESTALE)))
4863 		filp = path_openat(&nd, op, flags | LOOKUP_REVAL);
4864 	restore_nameidata();
4865 	return filp;
4866 }
4867 
4868 struct file *do_file_open_root(const struct path *root,
4869 		const char *name, const struct open_flags *op)
4870 {
4871 	struct nameidata nd;
4872 	struct file *file;
4873 	int flags = op->lookup_flags;
4874 
4875 	if (d_is_symlink(root->dentry) && op->intent & LOOKUP_OPEN)
4876 		return ERR_PTR(-ELOOP);
4877 
4878 	CLASS(filename_kernel, filename)(name);
4879 	if (IS_ERR(filename))
4880 		return ERR_CAST(filename);
4881 
4882 	set_nameidata(&nd, -1, filename, root);
4883 	file = path_openat(&nd, op, flags | LOOKUP_RCU);
4884 	if (unlikely(file == ERR_PTR(-ECHILD)))
4885 		file = path_openat(&nd, op, flags);
4886 	if (unlikely(file == ERR_PTR(-ESTALE)))
4887 		file = path_openat(&nd, op, flags | LOOKUP_REVAL);
4888 	restore_nameidata();
4889 	return file;
4890 }
4891 
4892 static struct dentry *filename_create(int dfd, struct filename *name,
4893 				      struct path *path, unsigned int lookup_flags)
4894 {
4895 	struct dentry *dentry = ERR_PTR(-EEXIST);
4896 	struct qstr last;
4897 	bool want_dir = lookup_flags & LOOKUP_DIRECTORY;
4898 	unsigned int reval_flag = lookup_flags & LOOKUP_REVAL;
4899 	unsigned int create_flags = LOOKUP_CREATE | LOOKUP_EXCL;
4900 	int type;
4901 	int error;
4902 
4903 	error = filename_parentat(dfd, name, reval_flag, path, &last, &type);
4904 	if (error)
4905 		return ERR_PTR(error);
4906 
4907 	/*
4908 	 * Yucky last component or no last component at all?
4909 	 * (foo/., foo/.., /////)
4910 	 */
4911 	if (unlikely(type != LAST_NORM))
4912 		goto out;
4913 
4914 	/* don't fail immediately if it's r/o, at least try to report other errors */
4915 	error = mnt_want_write(path->mnt);
4916 	/*
4917 	 * Do the final lookup.  Suppress 'create' if there is a trailing
4918 	 * '/', and a directory wasn't requested.
4919 	 */
4920 	if (last.name[last.len] && !want_dir)
4921 		create_flags &= ~LOOKUP_CREATE;
4922 	dentry = start_dirop(path->dentry, &last, reval_flag | create_flags);
4923 	if (IS_ERR(dentry))
4924 		goto out_drop_write;
4925 
4926 	if (unlikely(error))
4927 		goto fail;
4928 
4929 	return dentry;
4930 fail:
4931 	end_dirop(dentry);
4932 	dentry = ERR_PTR(error);
4933 out_drop_write:
4934 	if (!error)
4935 		mnt_drop_write(path->mnt);
4936 out:
4937 	path_put(path);
4938 	return dentry;
4939 }
4940 
4941 struct dentry *start_creating_path(int dfd, const char *pathname,
4942 				   struct path *path, unsigned int lookup_flags)
4943 {
4944 	CLASS(filename_kernel, filename)(pathname);
4945 	return filename_create(dfd, filename, path, lookup_flags);
4946 }
4947 EXPORT_SYMBOL(start_creating_path);
4948 
4949 /**
4950  * end_creating_path - finish a code section started by start_creating_path()
4951  * @path: the path instantiated by start_creating_path()
4952  * @dentry: the dentry returned by start_creating_path()
4953  *
4954  * end_creating_path() will unlock and locks taken by start_creating_path()
4955  * and drop an references that were taken.  It should only be called
4956  * if start_creating_path() returned a non-error.
4957  * If vfs_mkdir() was called and it returned an error, that error *should*
4958  * be passed to end_creating_path() together with the path.
4959  */
4960 void end_creating_path(const struct path *path, struct dentry *dentry)
4961 {
4962 	end_creating(dentry);
4963 	mnt_drop_write(path->mnt);
4964 	path_put(path);
4965 }
4966 EXPORT_SYMBOL(end_creating_path);
4967 
4968 inline struct dentry *start_creating_user_path(
4969 	int dfd, const char __user *pathname,
4970 	struct path *path, unsigned int lookup_flags)
4971 {
4972 	CLASS(filename, filename)(pathname);
4973 	return filename_create(dfd, filename, path, lookup_flags);
4974 }
4975 EXPORT_SYMBOL(start_creating_user_path);
4976 
4977 /**
4978  * dentry_create - Create and open a file
4979  * @path: path to create
4980  * @flags: O\_ flags
4981  * @mode: mode bits for new file
4982  * @cred: credentials to use
4983  *
4984  * Caller must hold the parent directory's lock, and have prepared
4985  * a negative dentry, placed in @path->dentry, for the new file.
4986  *
4987  * Caller sets @path->mnt to the vfsmount of the filesystem where
4988  * the new file is to be created. The parent directory and the
4989  * negative dentry must reside on the same filesystem instance.
4990  *
4991  * On success, returns a ``struct file *``. Otherwise an ERR_PTR
4992  * is returned.
4993  */
4994 struct file *dentry_create(struct path *path, int flags, umode_t mode,
4995 			   const struct cred *cred)
4996 {
4997 	struct file *file __free(fput) = NULL;
4998 	struct dentry *dentry = path->dentry;
4999 	struct dentry *dir = dentry->d_parent;
5000 	struct inode *dir_inode = d_inode(dir);
5001 	struct mnt_idmap *idmap;
5002 	int error, create_error;
5003 
5004 	file = alloc_empty_file(flags, cred);
5005 	if (IS_ERR(file))
5006 		return file;
5007 
5008 	idmap = mnt_idmap(path->mnt);
5009 
5010 	if (dir_inode->i_op->atomic_open) {
5011 		path->dentry = dir;
5012 		mode = vfs_prepare_mode(idmap, dir_inode, mode, S_IALLUGO, S_IFREG);
5013 
5014 		create_error = may_o_create(idmap, path, dentry, mode);
5015 		if (create_error)
5016 			flags &= ~O_CREAT;
5017 
5018 		dentry = atomic_open(path, dentry, file, flags, mode);
5019 		error = PTR_ERR_OR_ZERO(dentry);
5020 
5021 		if (unlikely(create_error) && error == -ENOENT)
5022 			error = create_error;
5023 
5024 		if (!error) {
5025 			if (file->f_mode & FMODE_CREATED)
5026 				fsnotify_create(dir->d_inode, dentry);
5027 			if (file->f_mode & FMODE_OPENED)
5028 				fsnotify_open(file);
5029 		}
5030 
5031 		path->dentry = dentry;
5032 
5033 	} else {
5034 		error = vfs_create(mnt_idmap(path->mnt), path->dentry, mode, NULL);
5035 		if (!error)
5036 			error = vfs_open(path, file);
5037 	}
5038 	if (unlikely(error))
5039 		return ERR_PTR(error);
5040 
5041 	return no_free_ptr(file);
5042 }
5043 EXPORT_SYMBOL(dentry_create);
5044 
5045 /**
5046  * vfs_mknod - create device node or file
5047  * @idmap:		idmap of the mount the inode was found from
5048  * @dir:		inode of the parent directory
5049  * @dentry:		dentry of the child device node
5050  * @mode:		mode of the child device node
5051  * @dev:		device number of device to create
5052  * @delegated_inode:	returns parent inode, if the inode is delegated.
5053  *
5054  * Create a device node or file.
5055  *
5056  * If the inode has been found through an idmapped mount the idmap of
5057  * the vfsmount must be passed through @idmap. This function will then take
5058  * care to map the inode according to @idmap before checking permissions.
5059  * On non-idmapped mounts or if permission checking is to be performed on the
5060  * raw inode simply pass @nop_mnt_idmap.
5061  */
5062 int vfs_mknod(struct mnt_idmap *idmap, struct inode *dir,
5063 	      struct dentry *dentry, umode_t mode, dev_t dev,
5064 	      struct delegated_inode *delegated_inode)
5065 {
5066 	bool is_whiteout = S_ISCHR(mode) && dev == WHITEOUT_DEV;
5067 	int error = may_create_dentry(idmap, dir, dentry);
5068 
5069 	if (error)
5070 		return error;
5071 
5072 	if ((S_ISCHR(mode) || S_ISBLK(mode)) && !is_whiteout &&
5073 	    !capable(CAP_MKNOD))
5074 		return -EPERM;
5075 
5076 	if (!dir->i_op->mknod)
5077 		return -EPERM;
5078 
5079 	mode = vfs_prepare_mode(idmap, dir, mode, mode, mode);
5080 	error = devcgroup_inode_mknod(mode, dev);
5081 	if (error)
5082 		return error;
5083 
5084 	error = security_inode_mknod(dir, dentry, mode, dev);
5085 	if (error)
5086 		return error;
5087 
5088 	error = try_break_deleg(dir, delegated_inode);
5089 	if (error)
5090 		return error;
5091 
5092 	error = dir->i_op->mknod(idmap, dir, dentry, mode, dev);
5093 	if (!error)
5094 		fsnotify_create(dir, dentry);
5095 	return error;
5096 }
5097 EXPORT_SYMBOL(vfs_mknod);
5098 
5099 static int may_mknod(umode_t mode)
5100 {
5101 	switch (mode & S_IFMT) {
5102 	case S_IFREG:
5103 	case S_IFCHR:
5104 	case S_IFBLK:
5105 	case S_IFIFO:
5106 	case S_IFSOCK:
5107 	case 0: /* zero mode translates to S_IFREG */
5108 		return 0;
5109 	case S_IFDIR:
5110 		return -EPERM;
5111 	default:
5112 		return -EINVAL;
5113 	}
5114 }
5115 
5116 int filename_mknodat(int dfd, struct filename *name, umode_t mode,
5117 		     unsigned int dev)
5118 {
5119 	struct delegated_inode di = { };
5120 	struct mnt_idmap *idmap;
5121 	struct dentry *dentry;
5122 	struct path path;
5123 	int error;
5124 	unsigned int lookup_flags = 0;
5125 
5126 	error = may_mknod(mode);
5127 	if (error)
5128 		return error;
5129 retry:
5130 	dentry = filename_create(dfd, name, &path, lookup_flags);
5131 	if (IS_ERR(dentry))
5132 		return PTR_ERR(dentry);
5133 
5134 	error = security_path_mknod(&path, dentry,
5135 			mode_strip_umask(path.dentry->d_inode, mode), dev);
5136 	if (error)
5137 		goto out2;
5138 
5139 	idmap = mnt_idmap(path.mnt);
5140 	switch (mode & S_IFMT) {
5141 		case 0: case S_IFREG:
5142 			error = vfs_create(idmap, dentry, mode, &di);
5143 			if (!error)
5144 				security_path_post_mknod(idmap, dentry);
5145 			break;
5146 		case S_IFCHR: case S_IFBLK:
5147 			error = vfs_mknod(idmap, path.dentry->d_inode,
5148 					  dentry, mode, new_decode_dev(dev), &di);
5149 			break;
5150 		case S_IFIFO: case S_IFSOCK:
5151 			error = vfs_mknod(idmap, path.dentry->d_inode,
5152 					  dentry, mode, 0, &di);
5153 			break;
5154 	}
5155 out2:
5156 	end_creating_path(&path, dentry);
5157 	if (is_delegated(&di)) {
5158 		error = break_deleg_wait(&di);
5159 		if (!error)
5160 			goto retry;
5161 	}
5162 	if (retry_estale(error, lookup_flags)) {
5163 		lookup_flags |= LOOKUP_REVAL;
5164 		goto retry;
5165 	}
5166 	return error;
5167 }
5168 
5169 SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, umode_t, mode,
5170 		unsigned int, dev)
5171 {
5172 	CLASS(filename, name)(filename);
5173 	return filename_mknodat(dfd, name, mode, dev);
5174 }
5175 
5176 SYSCALL_DEFINE3(mknod, const char __user *, filename, umode_t, mode, unsigned, dev)
5177 {
5178 	CLASS(filename, name)(filename);
5179 	return filename_mknodat(AT_FDCWD, name, mode, dev);
5180 }
5181 
5182 /**
5183  * vfs_mkdir - create directory returning correct dentry if possible
5184  * @idmap:		idmap of the mount the inode was found from
5185  * @dir:		inode of the parent directory
5186  * @dentry:		dentry of the child directory
5187  * @mode:		mode of the child directory
5188  * @delegated_inode:	returns parent inode, if the inode is delegated.
5189  *
5190  * Create a directory.
5191  *
5192  * If the inode has been found through an idmapped mount the idmap of
5193  * the vfsmount must be passed through @idmap. This function will then take
5194  * care to map the inode according to @idmap before checking permissions.
5195  * On non-idmapped mounts or if permission checking is to be performed on the
5196  * raw inode simply pass @nop_mnt_idmap.
5197  *
5198  * In the event that the filesystem does not use the *@dentry but leaves it
5199  * negative or unhashes it and possibly splices a different one returning it,
5200  * the original dentry is dput() and the alternate is returned.
5201  *
5202  * In case of an error the dentry is dput() and an ERR_PTR() is returned.
5203  */
5204 struct dentry *vfs_mkdir(struct mnt_idmap *idmap, struct inode *dir,
5205 			 struct dentry *dentry, umode_t mode,
5206 			 struct delegated_inode *delegated_inode)
5207 {
5208 	int error;
5209 	unsigned max_links = dir->i_sb->s_max_links;
5210 	struct dentry *de;
5211 
5212 	error = may_create_dentry(idmap, dir, dentry);
5213 	if (error)
5214 		goto err;
5215 
5216 	error = -EPERM;
5217 	if (!dir->i_op->mkdir)
5218 		goto err;
5219 
5220 	mode = vfs_prepare_mode(idmap, dir, mode, S_IRWXUGO | S_ISVTX, 0);
5221 	error = security_inode_mkdir(dir, dentry, mode);
5222 	if (error)
5223 		goto err;
5224 
5225 	error = -EMLINK;
5226 	if (max_links && dir->i_nlink >= max_links)
5227 		goto err;
5228 
5229 	error = try_break_deleg(dir, delegated_inode);
5230 	if (error)
5231 		goto err;
5232 
5233 	de = dir->i_op->mkdir(idmap, dir, dentry, mode);
5234 	error = PTR_ERR(de);
5235 	if (IS_ERR(de))
5236 		goto err;
5237 	if (de) {
5238 		dput(dentry);
5239 		dentry = de;
5240 	}
5241 	fsnotify_mkdir(dir, dentry);
5242 	return dentry;
5243 
5244 err:
5245 	end_creating(dentry);
5246 	return ERR_PTR(error);
5247 }
5248 EXPORT_SYMBOL(vfs_mkdir);
5249 
5250 int filename_mkdirat(int dfd, struct filename *name, umode_t mode)
5251 {
5252 	struct dentry *dentry;
5253 	struct path path;
5254 	int error;
5255 	unsigned int lookup_flags = LOOKUP_DIRECTORY;
5256 	struct delegated_inode delegated_inode = { };
5257 
5258 retry:
5259 	dentry = filename_create(dfd, name, &path, lookup_flags);
5260 	if (IS_ERR(dentry))
5261 		return PTR_ERR(dentry);
5262 
5263 	error = security_path_mkdir(&path, dentry,
5264 			mode_strip_umask(path.dentry->d_inode, mode));
5265 	if (!error) {
5266 		dentry = vfs_mkdir(mnt_idmap(path.mnt), path.dentry->d_inode,
5267 				   dentry, mode, &delegated_inode);
5268 		if (IS_ERR(dentry))
5269 			error = PTR_ERR(dentry);
5270 	}
5271 	end_creating_path(&path, dentry);
5272 	if (is_delegated(&delegated_inode)) {
5273 		error = break_deleg_wait(&delegated_inode);
5274 		if (!error)
5275 			goto retry;
5276 	}
5277 	if (retry_estale(error, lookup_flags)) {
5278 		lookup_flags |= LOOKUP_REVAL;
5279 		goto retry;
5280 	}
5281 	return error;
5282 }
5283 
5284 SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, umode_t, mode)
5285 {
5286 	CLASS(filename, name)(pathname);
5287 	return filename_mkdirat(dfd, name, mode);
5288 }
5289 
5290 SYSCALL_DEFINE2(mkdir, const char __user *, pathname, umode_t, mode)
5291 {
5292 	CLASS(filename, name)(pathname);
5293 	return filename_mkdirat(AT_FDCWD, name, mode);
5294 }
5295 
5296 /**
5297  * vfs_rmdir - remove directory
5298  * @idmap:		idmap of the mount the inode was found from
5299  * @dir:		inode of the parent directory
5300  * @dentry:		dentry of the child directory
5301  * @delegated_inode:	returns parent inode, if it's delegated.
5302  *
5303  * Remove a directory.
5304  *
5305  * If the inode has been found through an idmapped mount the idmap of
5306  * the vfsmount must be passed through @idmap. This function will then take
5307  * care to map the inode according to @idmap before checking permissions.
5308  * On non-idmapped mounts or if permission checking is to be performed on the
5309  * raw inode simply pass @nop_mnt_idmap.
5310  */
5311 int vfs_rmdir(struct mnt_idmap *idmap, struct inode *dir,
5312 	      struct dentry *dentry, struct delegated_inode *delegated_inode)
5313 {
5314 	int error = may_delete_dentry(idmap, dir, dentry, true);
5315 
5316 	if (error)
5317 		return error;
5318 
5319 	if (!dir->i_op->rmdir)
5320 		return -EPERM;
5321 
5322 	dget(dentry);
5323 	inode_lock(dentry->d_inode);
5324 
5325 	error = -EBUSY;
5326 	if (is_local_mountpoint(dentry) ||
5327 	    (dentry->d_inode->i_flags & S_KERNEL_FILE))
5328 		goto out;
5329 
5330 	error = security_inode_rmdir(dir, dentry);
5331 	if (error)
5332 		goto out;
5333 
5334 	error = try_break_deleg(dir, delegated_inode);
5335 	if (error)
5336 		goto out;
5337 
5338 	error = dir->i_op->rmdir(dir, dentry);
5339 	if (error)
5340 		goto out;
5341 
5342 	shrink_dcache_parent(dentry);
5343 	dentry->d_inode->i_flags |= S_DEAD;
5344 	dont_mount(dentry);
5345 	detach_mounts(dentry);
5346 
5347 out:
5348 	inode_unlock(dentry->d_inode);
5349 	dput(dentry);
5350 	if (!error)
5351 		d_delete_notify(dir, dentry);
5352 	return error;
5353 }
5354 EXPORT_SYMBOL(vfs_rmdir);
5355 
5356 int filename_rmdir(int dfd, struct filename *name)
5357 {
5358 	int error;
5359 	struct dentry *dentry;
5360 	struct path path;
5361 	struct qstr last;
5362 	int type;
5363 	unsigned int lookup_flags = 0;
5364 	struct delegated_inode delegated_inode = { };
5365 retry:
5366 	error = filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
5367 	if (error)
5368 		return error;
5369 
5370 	switch (type) {
5371 	case LAST_DOTDOT:
5372 		error = -ENOTEMPTY;
5373 		goto exit2;
5374 	case LAST_DOT:
5375 		error = -EINVAL;
5376 		goto exit2;
5377 	case LAST_ROOT:
5378 		error = -EBUSY;
5379 		goto exit2;
5380 	}
5381 
5382 	error = mnt_want_write(path.mnt);
5383 	if (error)
5384 		goto exit2;
5385 
5386 	dentry = start_dirop(path.dentry, &last, lookup_flags);
5387 	error = PTR_ERR(dentry);
5388 	if (IS_ERR(dentry))
5389 		goto exit3;
5390 	error = security_path_rmdir(&path, dentry);
5391 	if (error)
5392 		goto exit4;
5393 	error = vfs_rmdir(mnt_idmap(path.mnt), path.dentry->d_inode,
5394 			  dentry, &delegated_inode);
5395 exit4:
5396 	end_dirop(dentry);
5397 exit3:
5398 	mnt_drop_write(path.mnt);
5399 exit2:
5400 	path_put(&path);
5401 	if (is_delegated(&delegated_inode)) {
5402 		error = break_deleg_wait(&delegated_inode);
5403 		if (!error)
5404 			goto retry;
5405 	}
5406 	if (retry_estale(error, lookup_flags)) {
5407 		lookup_flags |= LOOKUP_REVAL;
5408 		goto retry;
5409 	}
5410 	return error;
5411 }
5412 
5413 SYSCALL_DEFINE1(rmdir, const char __user *, pathname)
5414 {
5415 	CLASS(filename, name)(pathname);
5416 	return filename_rmdir(AT_FDCWD, name);
5417 }
5418 
5419 /**
5420  * vfs_unlink - unlink a filesystem object
5421  * @idmap:	idmap of the mount the inode was found from
5422  * @dir:	parent directory
5423  * @dentry:	victim
5424  * @delegated_inode: returns victim inode, if the inode is delegated.
5425  *
5426  * The caller must hold dir->i_rwsem exclusively.
5427  *
5428  * If vfs_unlink discovers a delegation, it will return -EWOULDBLOCK and
5429  * return a reference to the inode in delegated_inode.  The caller
5430  * should then break the delegation on that inode and retry.  Because
5431  * breaking a delegation may take a long time, the caller should drop
5432  * dir->i_rwsem before doing so.
5433  *
5434  * Alternatively, a caller may pass NULL for delegated_inode.  This may
5435  * be appropriate for callers that expect the underlying filesystem not
5436  * to be NFS exported.
5437  *
5438  * If the inode has been found through an idmapped mount the idmap of
5439  * the vfsmount must be passed through @idmap. This function will then take
5440  * care to map the inode according to @idmap before checking permissions.
5441  * On non-idmapped mounts or if permission checking is to be performed on the
5442  * raw inode simply pass @nop_mnt_idmap.
5443  */
5444 int vfs_unlink(struct mnt_idmap *idmap, struct inode *dir,
5445 	       struct dentry *dentry, struct delegated_inode *delegated_inode)
5446 {
5447 	struct inode *target = dentry->d_inode;
5448 	int error = may_delete_dentry(idmap, dir, dentry, false);
5449 
5450 	if (error)
5451 		return error;
5452 
5453 	if (!dir->i_op->unlink)
5454 		return -EPERM;
5455 
5456 	inode_lock(target);
5457 	if (IS_SWAPFILE(target))
5458 		error = -EPERM;
5459 	else if (is_local_mountpoint(dentry))
5460 		error = -EBUSY;
5461 	else {
5462 		error = security_inode_unlink(dir, dentry);
5463 		if (!error) {
5464 			error = try_break_deleg(dir, delegated_inode);
5465 			if (error)
5466 				goto out;
5467 			error = try_break_deleg(target, delegated_inode);
5468 			if (error)
5469 				goto out;
5470 			error = dir->i_op->unlink(dir, dentry);
5471 			if (!error) {
5472 				dont_mount(dentry);
5473 				detach_mounts(dentry);
5474 			}
5475 		}
5476 	}
5477 out:
5478 	inode_unlock(target);
5479 
5480 	/* We don't d_delete() NFS sillyrenamed files--they still exist. */
5481 	if (!error && dentry->d_flags & DCACHE_NFSFS_RENAMED) {
5482 		fsnotify_unlink(dir, dentry);
5483 	} else if (!error) {
5484 		fsnotify_link_count(target);
5485 		d_delete_notify(dir, dentry);
5486 	}
5487 
5488 	return error;
5489 }
5490 EXPORT_SYMBOL(vfs_unlink);
5491 
5492 /*
5493  * Make sure that the actual truncation of the file will occur outside its
5494  * directory's i_rwsem.  Truncate can take a long time if there is a lot of
5495  * writeout happening, and we don't want to prevent access to the directory
5496  * while waiting on the I/O.
5497  */
5498 int filename_unlinkat(int dfd, struct filename *name)
5499 {
5500 	int error;
5501 	struct dentry *dentry;
5502 	struct path path;
5503 	struct qstr last;
5504 	int type;
5505 	struct inode *inode;
5506 	struct delegated_inode delegated_inode = { };
5507 	unsigned int lookup_flags = 0;
5508 retry:
5509 	error = filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
5510 	if (error)
5511 		return error;
5512 
5513 	error = -EISDIR;
5514 	if (type != LAST_NORM)
5515 		goto exit_path_put;
5516 
5517 	error = mnt_want_write(path.mnt);
5518 	if (error)
5519 		goto exit_path_put;
5520 retry_deleg:
5521 	dentry = start_dirop(path.dentry, &last, lookup_flags);
5522 	error = PTR_ERR(dentry);
5523 	if (IS_ERR(dentry))
5524 		goto exit_drop_write;
5525 
5526 	/* Why not before? Because we want correct error value */
5527 	if (unlikely(last.name[last.len])) {
5528 		if (d_is_dir(dentry))
5529 			error = -EISDIR;
5530 		else
5531 			error = -ENOTDIR;
5532 		end_dirop(dentry);
5533 		goto exit_drop_write;
5534 	}
5535 	inode = dentry->d_inode;
5536 	ihold(inode);
5537 	error = security_path_unlink(&path, dentry);
5538 	if (error)
5539 		goto exit_end_dirop;
5540 	error = vfs_unlink(mnt_idmap(path.mnt), path.dentry->d_inode,
5541 			   dentry, &delegated_inode);
5542 exit_end_dirop:
5543 	end_dirop(dentry);
5544 	iput(inode);	/* truncate the inode here */
5545 	if (is_delegated(&delegated_inode)) {
5546 		error = break_deleg_wait(&delegated_inode);
5547 		if (!error)
5548 			goto retry_deleg;
5549 	}
5550 exit_drop_write:
5551 	mnt_drop_write(path.mnt);
5552 exit_path_put:
5553 	path_put(&path);
5554 	if (retry_estale(error, lookup_flags)) {
5555 		lookup_flags |= LOOKUP_REVAL;
5556 		goto retry;
5557 	}
5558 	return error;
5559 }
5560 
5561 SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag)
5562 {
5563 	if ((flag & ~AT_REMOVEDIR) != 0)
5564 		return -EINVAL;
5565 
5566 	CLASS(filename, name)(pathname);
5567 	if (flag & AT_REMOVEDIR)
5568 		return filename_rmdir(dfd, name);
5569 	return filename_unlinkat(dfd, name);
5570 }
5571 
5572 SYSCALL_DEFINE1(unlink, const char __user *, pathname)
5573 {
5574 	CLASS(filename, name)(pathname);
5575 	return filename_unlinkat(AT_FDCWD, name);
5576 }
5577 
5578 /**
5579  * vfs_symlink - create symlink
5580  * @idmap:	idmap of the mount the inode was found from
5581  * @dir:	inode of the parent directory
5582  * @dentry:	dentry of the child symlink file
5583  * @oldname:	name of the file to link to
5584  * @delegated_inode: returns victim inode, if the inode is delegated.
5585  *
5586  * Create a symlink.
5587  *
5588  * If the inode has been found through an idmapped mount the idmap of
5589  * the vfsmount must be passed through @idmap. This function will then take
5590  * care to map the inode according to @idmap before checking permissions.
5591  * On non-idmapped mounts or if permission checking is to be performed on the
5592  * raw inode simply pass @nop_mnt_idmap.
5593  */
5594 int vfs_symlink(struct mnt_idmap *idmap, struct inode *dir,
5595 		struct dentry *dentry, const char *oldname,
5596 		struct delegated_inode *delegated_inode)
5597 {
5598 	int error;
5599 
5600 	error = may_create_dentry(idmap, dir, dentry);
5601 	if (error)
5602 		return error;
5603 
5604 	if (!dir->i_op->symlink)
5605 		return -EPERM;
5606 
5607 	error = security_inode_symlink(dir, dentry, oldname);
5608 	if (error)
5609 		return error;
5610 
5611 	error = try_break_deleg(dir, delegated_inode);
5612 	if (error)
5613 		return error;
5614 
5615 	error = dir->i_op->symlink(idmap, dir, dentry, oldname);
5616 	if (!error)
5617 		fsnotify_create(dir, dentry);
5618 	return error;
5619 }
5620 EXPORT_SYMBOL(vfs_symlink);
5621 
5622 int filename_symlinkat(struct filename *from, int newdfd, struct filename *to)
5623 {
5624 	int error;
5625 	struct dentry *dentry;
5626 	struct path path;
5627 	unsigned int lookup_flags = 0;
5628 	struct delegated_inode delegated_inode = { };
5629 
5630 	if (IS_ERR(from))
5631 		return PTR_ERR(from);
5632 
5633 retry:
5634 	dentry = filename_create(newdfd, to, &path, lookup_flags);
5635 	if (IS_ERR(dentry))
5636 		return PTR_ERR(dentry);
5637 
5638 	error = security_path_symlink(&path, dentry, from->name);
5639 	if (!error)
5640 		error = vfs_symlink(mnt_idmap(path.mnt), path.dentry->d_inode,
5641 				    dentry, from->name, &delegated_inode);
5642 	end_creating_path(&path, dentry);
5643 	if (is_delegated(&delegated_inode)) {
5644 		error = break_deleg_wait(&delegated_inode);
5645 		if (!error)
5646 			goto retry;
5647 	}
5648 	if (retry_estale(error, lookup_flags)) {
5649 		lookup_flags |= LOOKUP_REVAL;
5650 		goto retry;
5651 	}
5652 	return error;
5653 }
5654 
5655 SYSCALL_DEFINE3(symlinkat, const char __user *, oldname,
5656 		int, newdfd, const char __user *, newname)
5657 {
5658 	CLASS(filename, old)(oldname);
5659 	CLASS(filename, new)(newname);
5660 	return filename_symlinkat(old, newdfd, new);
5661 }
5662 
5663 SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname)
5664 {
5665 	CLASS(filename, old)(oldname);
5666 	CLASS(filename, new)(newname);
5667 	return filename_symlinkat(old, AT_FDCWD, new);
5668 }
5669 
5670 /**
5671  * vfs_link - create a new link
5672  * @old_dentry:	object to be linked
5673  * @idmap:	idmap of the mount
5674  * @dir:	new parent
5675  * @new_dentry:	where to create the new link
5676  * @delegated_inode: returns inode needing a delegation break
5677  *
5678  * The caller must hold dir->i_rwsem exclusively.
5679  *
5680  * If vfs_link discovers a delegation on the to-be-linked file in need
5681  * of breaking, it will return -EWOULDBLOCK and return a reference to the
5682  * inode in delegated_inode.  The caller should then break the delegation
5683  * and retry.  Because breaking a delegation may take a long time, the
5684  * caller should drop the i_rwsem before doing so.
5685  *
5686  * Alternatively, a caller may pass NULL for delegated_inode.  This may
5687  * be appropriate for callers that expect the underlying filesystem not
5688  * to be NFS exported.
5689  *
5690  * If the inode has been found through an idmapped mount the idmap of
5691  * the vfsmount must be passed through @idmap. This function will then take
5692  * care to map the inode according to @idmap before checking permissions.
5693  * On non-idmapped mounts or if permission checking is to be performed on the
5694  * raw inode simply pass @nop_mnt_idmap.
5695  */
5696 int vfs_link(struct dentry *old_dentry, struct mnt_idmap *idmap,
5697 	     struct inode *dir, struct dentry *new_dentry,
5698 	     struct delegated_inode *delegated_inode)
5699 {
5700 	struct inode *inode = old_dentry->d_inode;
5701 	unsigned max_links = dir->i_sb->s_max_links;
5702 	int error;
5703 
5704 	if (!inode)
5705 		return -ENOENT;
5706 
5707 	error = may_create_dentry(idmap, dir, new_dentry);
5708 	if (error)
5709 		return error;
5710 
5711 	if (dir->i_sb != inode->i_sb)
5712 		return -EXDEV;
5713 
5714 	/*
5715 	 * A link to an append-only or immutable file cannot be created.
5716 	 */
5717 	if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
5718 		return -EPERM;
5719 	/*
5720 	 * Updating the link count will likely cause i_uid and i_gid to
5721 	 * be written back improperly if their true value is unknown to
5722 	 * the vfs.
5723 	 */
5724 	if (HAS_UNMAPPED_ID(idmap, inode))
5725 		return -EPERM;
5726 	if (!dir->i_op->link)
5727 		return -EPERM;
5728 	if (S_ISDIR(inode->i_mode))
5729 		return -EPERM;
5730 
5731 	error = security_inode_link(old_dentry, dir, new_dentry);
5732 	if (error)
5733 		return error;
5734 
5735 	inode_lock(inode);
5736 	/* Make sure we don't allow creating hardlink to an unlinked file */
5737 	if (inode->i_nlink == 0 && !(inode_state_read_once(inode) & I_LINKABLE))
5738 		error =  -ENOENT;
5739 	else if (max_links && inode->i_nlink >= max_links)
5740 		error = -EMLINK;
5741 	else {
5742 		error = try_break_deleg(dir, delegated_inode);
5743 		if (!error)
5744 			error = try_break_deleg(inode, delegated_inode);
5745 		if (!error)
5746 			error = dir->i_op->link(old_dentry, dir, new_dentry);
5747 	}
5748 
5749 	if (!error && (inode_state_read_once(inode) & I_LINKABLE)) {
5750 		spin_lock(&inode->i_lock);
5751 		inode_state_clear(inode, I_LINKABLE);
5752 		spin_unlock(&inode->i_lock);
5753 	}
5754 	inode_unlock(inode);
5755 	if (!error)
5756 		fsnotify_link(dir, inode, new_dentry);
5757 	return error;
5758 }
5759 EXPORT_SYMBOL(vfs_link);
5760 
5761 /*
5762  * Hardlinks are often used in delicate situations.  We avoid
5763  * security-related surprises by not following symlinks on the
5764  * newname.  --KAB
5765  *
5766  * We don't follow them on the oldname either to be compatible
5767  * with linux 2.0, and to avoid hard-linking to directories
5768  * and other special files.  --ADM
5769 */
5770 int filename_linkat(int olddfd, struct filename *old,
5771 		    int newdfd, struct filename *new, int flags)
5772 {
5773 	struct mnt_idmap *idmap;
5774 	struct dentry *new_dentry;
5775 	struct path old_path, new_path;
5776 	struct delegated_inode delegated_inode = { };
5777 	int how = 0;
5778 	int error;
5779 
5780 	if ((flags & ~(AT_SYMLINK_FOLLOW | AT_EMPTY_PATH)) != 0)
5781 		return -EINVAL;
5782 	/*
5783 	 * To use null names we require CAP_DAC_READ_SEARCH or
5784 	 * that the open-time creds of the dfd matches current.
5785 	 * This ensures that not everyone will be able to create
5786 	 * a hardlink using the passed file descriptor.
5787 	 */
5788 	if (flags & AT_EMPTY_PATH)
5789 		how |= LOOKUP_LINKAT_EMPTY;
5790 
5791 	if (flags & AT_SYMLINK_FOLLOW)
5792 		how |= LOOKUP_FOLLOW;
5793 retry:
5794 	error = filename_lookup(olddfd, old, how, &old_path, NULL);
5795 	if (error)
5796 		return error;
5797 
5798 	new_dentry = filename_create(newdfd, new, &new_path,
5799 					(how & LOOKUP_REVAL));
5800 	error = PTR_ERR(new_dentry);
5801 	if (IS_ERR(new_dentry))
5802 		goto out_putpath;
5803 
5804 	error = -EXDEV;
5805 	if (old_path.mnt != new_path.mnt)
5806 		goto out_dput;
5807 	idmap = mnt_idmap(new_path.mnt);
5808 	error = may_linkat(idmap, &old_path);
5809 	if (unlikely(error))
5810 		goto out_dput;
5811 	error = security_path_link(old_path.dentry, &new_path, new_dentry);
5812 	if (error)
5813 		goto out_dput;
5814 	error = vfs_link(old_path.dentry, idmap, new_path.dentry->d_inode,
5815 			 new_dentry, &delegated_inode);
5816 out_dput:
5817 	end_creating_path(&new_path, new_dentry);
5818 	if (is_delegated(&delegated_inode)) {
5819 		error = break_deleg_wait(&delegated_inode);
5820 		if (!error) {
5821 			path_put(&old_path);
5822 			goto retry;
5823 		}
5824 	}
5825 	if (retry_estale(error, how)) {
5826 		path_put(&old_path);
5827 		how |= LOOKUP_REVAL;
5828 		goto retry;
5829 	}
5830 out_putpath:
5831 	path_put(&old_path);
5832 	return error;
5833 }
5834 
5835 SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname,
5836 		int, newdfd, const char __user *, newname, int, flags)
5837 {
5838 	CLASS(filename_uflags, old)(oldname, flags);
5839 	CLASS(filename, new)(newname);
5840 	return filename_linkat(olddfd, old, newdfd, new, flags);
5841 }
5842 
5843 SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname)
5844 {
5845 	CLASS(filename, old)(oldname);
5846 	CLASS(filename, new)(newname);
5847 	return filename_linkat(AT_FDCWD, old, AT_FDCWD, new, 0);
5848 }
5849 
5850 /**
5851  * vfs_rename - rename a filesystem object
5852  * @rd:		pointer to &struct renamedata info
5853  *
5854  * The caller must hold multiple mutexes--see lock_rename()).
5855  *
5856  * If vfs_rename discovers a delegation in need of breaking at either
5857  * the source or destination, it will return -EWOULDBLOCK and return a
5858  * reference to the inode in delegated_inode.  The caller should then
5859  * break the delegation and retry.  Because breaking a delegation may
5860  * take a long time, the caller should drop all locks before doing
5861  * so.
5862  *
5863  * Alternatively, a caller may pass NULL for delegated_inode.  This may
5864  * be appropriate for callers that expect the underlying filesystem not
5865  * to be NFS exported.
5866  *
5867  * The worst of all namespace operations - renaming directory. "Perverted"
5868  * doesn't even start to describe it. Somebody in UCB had a heck of a trip...
5869  * Problems:
5870  *
5871  *	a) we can get into loop creation.
5872  *	b) race potential - two innocent renames can create a loop together.
5873  *	   That's where 4.4BSD screws up. Current fix: serialization on
5874  *	   sb->s_vfs_rename_mutex. We might be more accurate, but that's another
5875  *	   story.
5876  *	c) we may have to lock up to _four_ objects - parents and victim (if it exists),
5877  *	   and source (if it's a non-directory or a subdirectory that moves to
5878  *	   different parent).
5879  *	   And that - after we got ->i_rwsem on parents (until then we don't know
5880  *	   whether the target exists).  Solution: try to be smart with locking
5881  *	   order for inodes.  We rely on the fact that tree topology may change
5882  *	   only under ->s_vfs_rename_mutex _and_ that parent of the object we
5883  *	   move will be locked.  Thus we can rank directories by the tree
5884  *	   (ancestors first) and rank all non-directories after them.
5885  *	   That works since everybody except rename does "lock parent, lookup,
5886  *	   lock child" and rename is under ->s_vfs_rename_mutex.
5887  *	   HOWEVER, it relies on the assumption that any object with ->lookup()
5888  *	   has no more than 1 dentry.  If "hybrid" objects will ever appear,
5889  *	   we'd better make sure that there's no link(2) for them.
5890  *	d) conversion from fhandle to dentry may come in the wrong moment - when
5891  *	   we are removing the target. Solution: we will have to grab ->i_rwsem
5892  *	   in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on
5893  *	   ->i_rwsem on parents, which works but leads to some truly excessive
5894  *	   locking].
5895  */
5896 int vfs_rename(struct renamedata *rd)
5897 {
5898 	int error;
5899 	struct inode *old_dir = d_inode(rd->old_parent);
5900 	struct inode *new_dir = d_inode(rd->new_parent);
5901 	struct dentry *old_dentry = rd->old_dentry;
5902 	struct dentry *new_dentry = rd->new_dentry;
5903 	struct delegated_inode *delegated_inode = rd->delegated_inode;
5904 	unsigned int flags = rd->flags;
5905 	bool is_dir = d_is_dir(old_dentry);
5906 	struct inode *source = old_dentry->d_inode;
5907 	struct inode *target = new_dentry->d_inode;
5908 	bool new_is_dir = false;
5909 	unsigned max_links = new_dir->i_sb->s_max_links;
5910 	struct name_snapshot old_name;
5911 	bool lock_old_subdir, lock_new_subdir;
5912 
5913 	if (source == target)
5914 		return 0;
5915 
5916 	error = may_delete_dentry(rd->mnt_idmap, old_dir, old_dentry, is_dir);
5917 	if (error)
5918 		return error;
5919 
5920 	if (!target) {
5921 		error = may_create_dentry(rd->mnt_idmap, new_dir, new_dentry);
5922 	} else {
5923 		new_is_dir = d_is_dir(new_dentry);
5924 
5925 		if (!(flags & RENAME_EXCHANGE))
5926 			error = may_delete_dentry(rd->mnt_idmap, new_dir,
5927 						  new_dentry, is_dir);
5928 		else
5929 			error = may_delete_dentry(rd->mnt_idmap, new_dir,
5930 						  new_dentry, new_is_dir);
5931 	}
5932 	if (error)
5933 		return error;
5934 
5935 	if (!old_dir->i_op->rename)
5936 		return -EPERM;
5937 
5938 	/*
5939 	 * If we are going to change the parent - check write permissions,
5940 	 * we'll need to flip '..'.
5941 	 */
5942 	if (new_dir != old_dir) {
5943 		if (is_dir) {
5944 			error = inode_permission(rd->mnt_idmap, source,
5945 						 MAY_WRITE);
5946 			if (error)
5947 				return error;
5948 		}
5949 		if ((flags & RENAME_EXCHANGE) && new_is_dir) {
5950 			error = inode_permission(rd->mnt_idmap, target,
5951 						 MAY_WRITE);
5952 			if (error)
5953 				return error;
5954 		}
5955 	}
5956 
5957 	error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,
5958 				      flags);
5959 	if (error)
5960 		return error;
5961 
5962 	take_dentry_name_snapshot(&old_name, old_dentry);
5963 	dget(new_dentry);
5964 	/*
5965 	 * Lock children.
5966 	 * The source subdirectory needs to be locked on cross-directory
5967 	 * rename or cross-directory exchange since its parent changes.
5968 	 * The target subdirectory needs to be locked on cross-directory
5969 	 * exchange due to parent change and on any rename due to becoming
5970 	 * a victim.
5971 	 * Non-directories need locking in all cases (for NFS reasons);
5972 	 * they get locked after any subdirectories (in inode address order).
5973 	 *
5974 	 * NOTE: WE ONLY LOCK UNRELATED DIRECTORIES IN CROSS-DIRECTORY CASE.
5975 	 * NEVER, EVER DO THAT WITHOUT ->s_vfs_rename_mutex.
5976 	 */
5977 	lock_old_subdir = new_dir != old_dir;
5978 	lock_new_subdir = new_dir != old_dir || !(flags & RENAME_EXCHANGE);
5979 	if (is_dir) {
5980 		if (lock_old_subdir)
5981 			inode_lock_nested(source, I_MUTEX_CHILD);
5982 		if (target && (!new_is_dir || lock_new_subdir))
5983 			inode_lock(target);
5984 	} else if (new_is_dir) {
5985 		if (lock_new_subdir)
5986 			inode_lock_nested(target, I_MUTEX_CHILD);
5987 		inode_lock(source);
5988 	} else {
5989 		lock_two_nondirectories(source, target);
5990 	}
5991 
5992 	error = -EPERM;
5993 	if (IS_SWAPFILE(source) || (target && IS_SWAPFILE(target)))
5994 		goto out;
5995 
5996 	error = -EBUSY;
5997 	if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
5998 		goto out;
5999 
6000 	if (max_links && new_dir != old_dir) {
6001 		error = -EMLINK;
6002 		if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)
6003 			goto out;
6004 		if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&
6005 		    old_dir->i_nlink >= max_links)
6006 			goto out;
6007 	}
6008 	error = try_break_deleg(old_dir, delegated_inode);
6009 	if (error)
6010 		goto out;
6011 	if (new_dir != old_dir) {
6012 		error = try_break_deleg(new_dir, delegated_inode);
6013 		if (error)
6014 			goto out;
6015 	}
6016 	if (!is_dir) {
6017 		error = try_break_deleg(source, delegated_inode);
6018 		if (error)
6019 			goto out;
6020 	}
6021 	if (target && !new_is_dir) {
6022 		error = try_break_deleg(target, delegated_inode);
6023 		if (error)
6024 			goto out;
6025 	}
6026 	error = old_dir->i_op->rename(rd->mnt_idmap, old_dir, old_dentry,
6027 				      new_dir, new_dentry, flags);
6028 	if (error)
6029 		goto out;
6030 
6031 	if (!(flags & RENAME_EXCHANGE) && target) {
6032 		if (is_dir) {
6033 			shrink_dcache_parent(new_dentry);
6034 			target->i_flags |= S_DEAD;
6035 		}
6036 		dont_mount(new_dentry);
6037 		detach_mounts(new_dentry);
6038 	}
6039 	if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {
6040 		if (!(flags & RENAME_EXCHANGE))
6041 			d_move(old_dentry, new_dentry);
6042 		else
6043 			d_exchange(old_dentry, new_dentry);
6044 	}
6045 out:
6046 	if (!is_dir || lock_old_subdir)
6047 		inode_unlock(source);
6048 	if (target && (!new_is_dir || lock_new_subdir))
6049 		inode_unlock(target);
6050 	dput(new_dentry);
6051 	if (!error) {
6052 		fsnotify_move(old_dir, new_dir, &old_name.name, is_dir,
6053 			      !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);
6054 		if (flags & RENAME_EXCHANGE) {
6055 			fsnotify_move(new_dir, old_dir, &old_dentry->d_name,
6056 				      new_is_dir, NULL, new_dentry);
6057 		}
6058 	}
6059 	release_dentry_name_snapshot(&old_name);
6060 
6061 	return error;
6062 }
6063 EXPORT_SYMBOL(vfs_rename);
6064 
6065 int filename_renameat2(int olddfd, struct filename *from,
6066 		       int newdfd, struct filename *to, unsigned int flags)
6067 {
6068 	struct renamedata rd;
6069 	struct path old_path, new_path;
6070 	struct qstr old_last, new_last;
6071 	int old_type, new_type;
6072 	struct delegated_inode delegated_inode = { };
6073 	unsigned int lookup_flags = 0;
6074 	bool should_retry = false;
6075 	int error;
6076 
6077 	if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
6078 		return -EINVAL;
6079 
6080 	if ((flags & (RENAME_NOREPLACE | RENAME_WHITEOUT)) &&
6081 	    (flags & RENAME_EXCHANGE))
6082 		return -EINVAL;
6083 
6084 retry:
6085 	error = filename_parentat(olddfd, from, lookup_flags, &old_path,
6086 				  &old_last, &old_type);
6087 	if (error)
6088 		return error;
6089 
6090 	error = filename_parentat(newdfd, to, lookup_flags, &new_path, &new_last,
6091 				  &new_type);
6092 	if (error)
6093 		goto exit1;
6094 
6095 	error = -EXDEV;
6096 	if (old_path.mnt != new_path.mnt)
6097 		goto exit2;
6098 
6099 	error = -EBUSY;
6100 	if (old_type != LAST_NORM)
6101 		goto exit2;
6102 
6103 	if (flags & RENAME_NOREPLACE)
6104 		error = -EEXIST;
6105 	if (new_type != LAST_NORM)
6106 		goto exit2;
6107 
6108 	error = mnt_want_write(old_path.mnt);
6109 	if (error)
6110 		goto exit2;
6111 
6112 retry_deleg:
6113 	rd.old_parent	   = old_path.dentry;
6114 	rd.mnt_idmap	   = mnt_idmap(old_path.mnt);
6115 	rd.new_parent	   = new_path.dentry;
6116 	rd.delegated_inode = &delegated_inode;
6117 	rd.flags	   = flags;
6118 
6119 	error = __start_renaming(&rd, lookup_flags, &old_last, &new_last);
6120 	if (error)
6121 		goto exit_lock_rename;
6122 
6123 	if (flags & RENAME_EXCHANGE) {
6124 		if (!d_is_dir(rd.new_dentry)) {
6125 			error = -ENOTDIR;
6126 			if (new_last.name[new_last.len])
6127 				goto exit_unlock;
6128 		}
6129 	}
6130 	/* unless the source is a directory trailing slashes give -ENOTDIR */
6131 	if (!d_is_dir(rd.old_dentry)) {
6132 		error = -ENOTDIR;
6133 		if (old_last.name[old_last.len])
6134 			goto exit_unlock;
6135 		if (!(flags & RENAME_EXCHANGE) && new_last.name[new_last.len])
6136 			goto exit_unlock;
6137 	}
6138 
6139 	error = security_path_rename(&old_path, rd.old_dentry,
6140 				     &new_path, rd.new_dentry, flags);
6141 	if (error)
6142 		goto exit_unlock;
6143 
6144 	error = vfs_rename(&rd);
6145 exit_unlock:
6146 	end_renaming(&rd);
6147 exit_lock_rename:
6148 	if (is_delegated(&delegated_inode)) {
6149 		error = break_deleg_wait(&delegated_inode);
6150 		if (!error)
6151 			goto retry_deleg;
6152 	}
6153 	mnt_drop_write(old_path.mnt);
6154 exit2:
6155 	if (retry_estale(error, lookup_flags))
6156 		should_retry = true;
6157 	path_put(&new_path);
6158 exit1:
6159 	path_put(&old_path);
6160 	if (should_retry) {
6161 		should_retry = false;
6162 		lookup_flags |= LOOKUP_REVAL;
6163 		goto retry;
6164 	}
6165 	return error;
6166 }
6167 
6168 SYSCALL_DEFINE5(renameat2, int, olddfd, const char __user *, oldname,
6169 		int, newdfd, const char __user *, newname, unsigned int, flags)
6170 {
6171 	CLASS(filename, old)(oldname);
6172 	CLASS(filename, new)(newname);
6173 	return filename_renameat2(olddfd, old, newdfd, new, flags);
6174 }
6175 
6176 SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname,
6177 		int, newdfd, const char __user *, newname)
6178 {
6179 	CLASS(filename, old)(oldname);
6180 	CLASS(filename, new)(newname);
6181 	return filename_renameat2(olddfd, old, newdfd, new, 0);
6182 }
6183 
6184 SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname)
6185 {
6186 	CLASS(filename, old)(oldname);
6187 	CLASS(filename, new)(newname);
6188 	return filename_renameat2(AT_FDCWD, old, AT_FDCWD, new, 0);
6189 }
6190 
6191 int readlink_copy(char __user *buffer, int buflen, const char *link, int linklen)
6192 {
6193 	int copylen;
6194 
6195 	copylen = linklen;
6196 	if (unlikely(copylen > (unsigned) buflen))
6197 		copylen = buflen;
6198 	if (copy_to_user(buffer, link, copylen))
6199 		copylen = -EFAULT;
6200 	return copylen;
6201 }
6202 
6203 /**
6204  * vfs_readlink - copy symlink body into userspace buffer
6205  * @dentry: dentry on which to get symbolic link
6206  * @buffer: user memory pointer
6207  * @buflen: size of buffer
6208  *
6209  * Does not touch atime.  That's up to the caller if necessary
6210  *
6211  * Does not call security hook.
6212  */
6213 int vfs_readlink(struct dentry *dentry, char __user *buffer, int buflen)
6214 {
6215 	struct inode *inode = d_inode(dentry);
6216 	DEFINE_DELAYED_CALL(done);
6217 	const char *link;
6218 	int res;
6219 
6220 	if (inode->i_opflags & IOP_CACHED_LINK)
6221 		return readlink_copy(buffer, buflen, inode->i_link, inode->i_linklen);
6222 
6223 	if (unlikely(!(inode->i_opflags & IOP_DEFAULT_READLINK))) {
6224 		if (unlikely(inode->i_op->readlink))
6225 			return inode->i_op->readlink(dentry, buffer, buflen);
6226 
6227 		if (!d_is_symlink(dentry))
6228 			return -EINVAL;
6229 
6230 		spin_lock(&inode->i_lock);
6231 		inode->i_opflags |= IOP_DEFAULT_READLINK;
6232 		spin_unlock(&inode->i_lock);
6233 	}
6234 
6235 	link = READ_ONCE(inode->i_link);
6236 	if (!link) {
6237 		link = inode->i_op->get_link(dentry, inode, &done);
6238 		if (IS_ERR(link))
6239 			return PTR_ERR(link);
6240 	}
6241 	res = readlink_copy(buffer, buflen, link, strlen(link));
6242 	do_delayed_call(&done);
6243 	return res;
6244 }
6245 EXPORT_SYMBOL(vfs_readlink);
6246 
6247 /**
6248  * vfs_get_link - get symlink body
6249  * @dentry: dentry on which to get symbolic link
6250  * @done: caller needs to free returned data with this
6251  *
6252  * Calls security hook and i_op->get_link() on the supplied inode.
6253  *
6254  * It does not touch atime.  That's up to the caller if necessary.
6255  *
6256  * Does not work on "special" symlinks like /proc/$$/fd/N
6257  */
6258 const char *vfs_get_link(struct dentry *dentry, struct delayed_call *done)
6259 {
6260 	const char *res = ERR_PTR(-EINVAL);
6261 	struct inode *inode = d_inode(dentry);
6262 
6263 	if (d_is_symlink(dentry)) {
6264 		res = ERR_PTR(security_inode_readlink(dentry));
6265 		if (!res)
6266 			res = inode->i_op->get_link(dentry, inode, done);
6267 	}
6268 	return res;
6269 }
6270 EXPORT_SYMBOL(vfs_get_link);
6271 
6272 /* get the link contents into pagecache */
6273 static char *__page_get_link(struct dentry *dentry, struct inode *inode,
6274 			     struct delayed_call *callback)
6275 {
6276 	struct folio *folio;
6277 	struct address_space *mapping = inode->i_mapping;
6278 
6279 	if (!dentry) {
6280 		folio = filemap_get_folio(mapping, 0);
6281 		if (IS_ERR(folio))
6282 			return ERR_PTR(-ECHILD);
6283 		if (!folio_test_uptodate(folio)) {
6284 			folio_put(folio);
6285 			return ERR_PTR(-ECHILD);
6286 		}
6287 	} else {
6288 		folio = read_mapping_folio(mapping, 0, NULL);
6289 		if (IS_ERR(folio))
6290 			return ERR_CAST(folio);
6291 	}
6292 	set_delayed_call(callback, page_put_link, folio);
6293 	BUG_ON(mapping_gfp_mask(mapping) & __GFP_HIGHMEM);
6294 	return folio_address(folio);
6295 }
6296 
6297 const char *page_get_link_raw(struct dentry *dentry, struct inode *inode,
6298 			      struct delayed_call *callback)
6299 {
6300 	return __page_get_link(dentry, inode, callback);
6301 }
6302 EXPORT_SYMBOL_GPL(page_get_link_raw);
6303 
6304 /**
6305  * page_get_link() - An implementation of the get_link inode_operation.
6306  * @dentry: The directory entry which is the symlink.
6307  * @inode: The inode for the symlink.
6308  * @callback: Used to drop the reference to the symlink.
6309  *
6310  * Filesystems which store their symlinks in the page cache should use
6311  * this to implement the get_link() member of their inode_operations.
6312  *
6313  * Return: A pointer to the NUL-terminated symlink.
6314  */
6315 const char *page_get_link(struct dentry *dentry, struct inode *inode,
6316 					struct delayed_call *callback)
6317 {
6318 	char *kaddr = __page_get_link(dentry, inode, callback);
6319 
6320 	if (!IS_ERR(kaddr))
6321 		nd_terminate_link(kaddr, inode->i_size, PAGE_SIZE - 1);
6322 	return kaddr;
6323 }
6324 EXPORT_SYMBOL(page_get_link);
6325 
6326 /**
6327  * page_put_link() - Drop the reference to the symlink.
6328  * @arg: The folio which contains the symlink.
6329  *
6330  * This is used internally by page_get_link().  It is exported for use
6331  * by filesystems which need to implement a variant of page_get_link()
6332  * themselves.  Despite the apparent symmetry, filesystems which use
6333  * page_get_link() do not need to call page_put_link().
6334  *
6335  * The argument, while it has a void pointer type, must be a pointer to
6336  * the folio which was retrieved from the page cache.  The delayed_call
6337  * infrastructure is used to drop the reference count once the caller
6338  * is done with the symlink.
6339  */
6340 void page_put_link(void *arg)
6341 {
6342 	folio_put(arg);
6343 }
6344 EXPORT_SYMBOL(page_put_link);
6345 
6346 int page_readlink(struct dentry *dentry, char __user *buffer, int buflen)
6347 {
6348 	const char *link;
6349 	int res;
6350 
6351 	DEFINE_DELAYED_CALL(done);
6352 	link = page_get_link(dentry, d_inode(dentry), &done);
6353 	res = PTR_ERR(link);
6354 	if (!IS_ERR(link))
6355 		res = readlink_copy(buffer, buflen, link, strlen(link));
6356 	do_delayed_call(&done);
6357 	return res;
6358 }
6359 EXPORT_SYMBOL(page_readlink);
6360 
6361 int page_symlink(struct inode *inode, const char *symname, int len)
6362 {
6363 	struct address_space *mapping = inode->i_mapping;
6364 	const struct address_space_operations *aops = mapping->a_ops;
6365 	bool nofs = !mapping_gfp_constraint(mapping, __GFP_FS);
6366 	struct folio *folio;
6367 	void *fsdata = NULL;
6368 	int err;
6369 	unsigned int flags;
6370 
6371 retry:
6372 	if (nofs)
6373 		flags = memalloc_nofs_save();
6374 	err = aops->write_begin(NULL, mapping, 0, len-1, &folio, &fsdata);
6375 	if (nofs)
6376 		memalloc_nofs_restore(flags);
6377 	if (err)
6378 		goto fail;
6379 
6380 	memcpy(folio_address(folio), symname, len - 1);
6381 
6382 	err = aops->write_end(NULL, mapping, 0, len - 1, len - 1,
6383 						folio, fsdata);
6384 	if (err < 0)
6385 		goto fail;
6386 	if (err < len-1)
6387 		goto retry;
6388 
6389 	mark_inode_dirty(inode);
6390 	return 0;
6391 fail:
6392 	return err;
6393 }
6394 EXPORT_SYMBOL(page_symlink);
6395 
6396 const struct inode_operations page_symlink_inode_operations = {
6397 	.get_link	= page_get_link,
6398 };
6399 EXPORT_SYMBOL(page_symlink_inode_operations);
6400