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