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