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