• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_NS(kern_path, ANDROID_GKI_VFS_EXPORT_ONLY);
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 (IS_ERR_OR_NULL(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_PARENT2);
2859 		return p;
2860 	}
2861 
2862 	p = d_ancestor(p1, p2);
2863 	inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
2864 	inode_lock_nested(p2->d_inode, I_MUTEX_PARENT2);
2865 	return p;
2866 }
2867 EXPORT_SYMBOL(lock_rename);
2868 
unlock_rename(struct dentry * p1,struct dentry * p2)2869 void unlock_rename(struct dentry *p1, struct dentry *p2)
2870 {
2871 	inode_unlock(p1->d_inode);
2872 	if (p1 != p2) {
2873 		inode_unlock(p2->d_inode);
2874 		mutex_unlock(&p1->d_sb->s_vfs_rename_mutex);
2875 	}
2876 }
2877 EXPORT_SYMBOL(unlock_rename);
2878 
2879 /**
2880  * mode_strip_umask - handle vfs umask stripping
2881  * @dir:	parent directory of the new inode
2882  * @mode:	mode of the new inode to be created in @dir
2883  *
2884  * Umask stripping depends on whether or not the filesystem supports POSIX
2885  * ACLs. If the filesystem doesn't support it umask stripping is done directly
2886  * in here. If the filesystem does support POSIX ACLs umask stripping is
2887  * deferred until the filesystem calls posix_acl_create().
2888  *
2889  * Returns: mode
2890  */
mode_strip_umask(const struct inode * dir,umode_t mode)2891 static inline umode_t mode_strip_umask(const struct inode *dir, umode_t mode)
2892 {
2893 	if (!IS_POSIXACL(dir))
2894 		mode &= ~current_umask();
2895 	return mode;
2896 }
2897 
2898 /**
2899  * vfs_prepare_mode - prepare the mode to be used for a new inode
2900  * @dir:	parent directory of the new inode
2901  * @mode:	mode of the new inode
2902  * @mask_perms:	allowed permission by the vfs
2903  * @type:	type of file to be created
2904  *
2905  * This helper consolidates and enforces vfs restrictions on the @mode of a new
2906  * object to be created.
2907  *
2908  * Umask stripping depends on whether the filesystem supports POSIX ACLs (see
2909  * the kernel documentation for mode_strip_umask()). Moving umask stripping
2910  * after setgid stripping allows the same ordering for both non-POSIX ACL and
2911  * POSIX ACL supporting filesystems.
2912  *
2913  * Note that it's currently valid for @type to be 0 if a directory is created.
2914  * Filesystems raise that flag individually and we need to check whether each
2915  * filesystem can deal with receiving S_IFDIR from the vfs before we enforce a
2916  * non-zero type.
2917  *
2918  * Returns: mode to be passed to the filesystem
2919  */
vfs_prepare_mode(const struct inode * dir,umode_t mode,umode_t mask_perms,umode_t type)2920 static inline umode_t vfs_prepare_mode(const struct inode *dir, umode_t mode,
2921 				       umode_t mask_perms, umode_t type)
2922 {
2923 	mode = mode_strip_sgid(dir, mode);
2924 	mode = mode_strip_umask(dir, mode);
2925 
2926 	/*
2927 	 * Apply the vfs mandated allowed permission mask and set the type of
2928 	 * file to be created before we call into the filesystem.
2929 	 */
2930 	mode &= (mask_perms & ~S_IFMT);
2931 	mode |= (type & S_IFMT);
2932 
2933 	return mode;
2934 }
2935 
vfs_create(struct inode * dir,struct dentry * dentry,umode_t mode,bool want_excl)2936 int vfs_create(struct inode *dir, struct dentry *dentry, umode_t mode,
2937 		bool want_excl)
2938 {
2939 	int error = may_create(dir, dentry);
2940 	if (error)
2941 		return error;
2942 
2943 	if (!dir->i_op->create)
2944 		return -EACCES;	/* shouldn't it be ENOSYS? */
2945 
2946 	mode = vfs_prepare_mode(dir, mode, S_IALLUGO, S_IFREG);
2947 	error = security_inode_create(dir, dentry, mode);
2948 	if (error)
2949 		return error;
2950 	error = dir->i_op->create(dir, dentry, mode, want_excl);
2951 	if (!error)
2952 		fsnotify_create(dir, dentry);
2953 	return error;
2954 }
2955 EXPORT_SYMBOL_NS(vfs_create, ANDROID_GKI_VFS_EXPORT_ONLY);
2956 
vfs_mkobj(struct dentry * dentry,umode_t mode,int (* f)(struct dentry *,umode_t,void *),void * arg)2957 int vfs_mkobj(struct dentry *dentry, umode_t mode,
2958 		int (*f)(struct dentry *, umode_t, void *),
2959 		void *arg)
2960 {
2961 	struct inode *dir = dentry->d_parent->d_inode;
2962 	int error = may_create(dir, dentry);
2963 	if (error)
2964 		return error;
2965 
2966 	mode &= S_IALLUGO;
2967 	mode |= S_IFREG;
2968 	error = security_inode_create(dir, dentry, mode);
2969 	if (error)
2970 		return error;
2971 	error = f(dentry, mode, arg);
2972 	if (!error)
2973 		fsnotify_create(dir, dentry);
2974 	return error;
2975 }
2976 EXPORT_SYMBOL(vfs_mkobj);
2977 
may_open_dev(const struct path * path)2978 bool may_open_dev(const struct path *path)
2979 {
2980 	return !(path->mnt->mnt_flags & MNT_NODEV) &&
2981 		!(path->mnt->mnt_sb->s_iflags & SB_I_NODEV);
2982 }
2983 
may_open(const struct path * path,int acc_mode,int flag)2984 static int may_open(const struct path *path, int acc_mode, int flag)
2985 {
2986 	struct dentry *dentry = path->dentry;
2987 	struct inode *inode = dentry->d_inode;
2988 	int error;
2989 
2990 	if (!inode)
2991 		return -ENOENT;
2992 
2993 	switch (inode->i_mode & S_IFMT) {
2994 	case S_IFLNK:
2995 		return -ELOOP;
2996 	case S_IFDIR:
2997 		if (acc_mode & MAY_WRITE)
2998 			return -EISDIR;
2999 		if (acc_mode & MAY_EXEC)
3000 			return -EACCES;
3001 		break;
3002 	case S_IFBLK:
3003 	case S_IFCHR:
3004 		if (!may_open_dev(path))
3005 			return -EACCES;
3006 		fallthrough;
3007 	case S_IFIFO:
3008 	case S_IFSOCK:
3009 		if (acc_mode & MAY_EXEC)
3010 			return -EACCES;
3011 		flag &= ~O_TRUNC;
3012 		break;
3013 	case S_IFREG:
3014 		if ((acc_mode & MAY_EXEC) && path_noexec(path))
3015 			return -EACCES;
3016 		break;
3017 	}
3018 
3019 	error = inode_permission(inode, MAY_OPEN | acc_mode);
3020 	if (error)
3021 		return error;
3022 
3023 	/*
3024 	 * An append-only file must be opened in append mode for writing.
3025 	 */
3026 	if (IS_APPEND(inode)) {
3027 		if  ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND))
3028 			return -EPERM;
3029 		if (flag & O_TRUNC)
3030 			return -EPERM;
3031 	}
3032 
3033 	/* O_NOATIME can only be set by the owner or superuser */
3034 	if (flag & O_NOATIME && !inode_owner_or_capable(inode))
3035 		return -EPERM;
3036 
3037 	return 0;
3038 }
3039 
handle_truncate(struct file * filp)3040 static int handle_truncate(struct file *filp)
3041 {
3042 	const struct path *path = &filp->f_path;
3043 	struct inode *inode = path->dentry->d_inode;
3044 	int error = get_write_access(inode);
3045 	if (error)
3046 		return error;
3047 	/*
3048 	 * Refuse to truncate files with mandatory locks held on them.
3049 	 */
3050 	error = locks_verify_locked(filp);
3051 	if (!error)
3052 		error = security_path_truncate(path);
3053 	if (!error) {
3054 		error = do_truncate(path->dentry, 0,
3055 				    ATTR_MTIME|ATTR_CTIME|ATTR_OPEN,
3056 				    filp);
3057 	}
3058 	put_write_access(inode);
3059 	return error;
3060 }
3061 
open_to_namei_flags(int flag)3062 static inline int open_to_namei_flags(int flag)
3063 {
3064 	if ((flag & O_ACCMODE) == 3)
3065 		flag--;
3066 	return flag;
3067 }
3068 
may_o_create(const struct path * dir,struct dentry * dentry,umode_t mode)3069 static int may_o_create(const struct path *dir, struct dentry *dentry, umode_t mode)
3070 {
3071 	struct user_namespace *s_user_ns;
3072 	int error = security_path_mknod(dir, dentry, mode, 0);
3073 	if (error)
3074 		return error;
3075 
3076 	s_user_ns = dir->dentry->d_sb->s_user_ns;
3077 	if (!kuid_has_mapping(s_user_ns, current_fsuid()) ||
3078 	    !kgid_has_mapping(s_user_ns, current_fsgid()))
3079 		return -EOVERFLOW;
3080 
3081 	error = inode_permission(dir->dentry->d_inode, MAY_WRITE | MAY_EXEC);
3082 	if (error)
3083 		return error;
3084 
3085 	return security_inode_create(dir->dentry->d_inode, dentry, mode);
3086 }
3087 
3088 /*
3089  * Attempt to atomically look up, create and open a file from a negative
3090  * dentry.
3091  *
3092  * Returns 0 if successful.  The file will have been created and attached to
3093  * @file by the filesystem calling finish_open().
3094  *
3095  * If the file was looked up only or didn't need creating, FMODE_OPENED won't
3096  * be set.  The caller will need to perform the open themselves.  @path will
3097  * have been updated to point to the new dentry.  This may be negative.
3098  *
3099  * Returns an error code otherwise.
3100  */
atomic_open(struct nameidata * nd,struct dentry * dentry,struct file * file,int open_flag,umode_t mode)3101 static struct dentry *atomic_open(struct nameidata *nd, struct dentry *dentry,
3102 				  struct file *file,
3103 				  int open_flag, umode_t mode)
3104 {
3105 	struct dentry *const DENTRY_NOT_SET = (void *) -1UL;
3106 	struct inode *dir =  nd->path.dentry->d_inode;
3107 	int error;
3108 
3109 	if (nd->flags & LOOKUP_DIRECTORY)
3110 		open_flag |= O_DIRECTORY;
3111 
3112 	file->f_path.dentry = DENTRY_NOT_SET;
3113 	file->f_path.mnt = nd->path.mnt;
3114 	error = dir->i_op->atomic_open(dir, dentry, file,
3115 				       open_to_namei_flags(open_flag), mode);
3116 	d_lookup_done(dentry);
3117 	if (!error) {
3118 		if (file->f_mode & FMODE_OPENED) {
3119 			if (unlikely(dentry != file->f_path.dentry)) {
3120 				dput(dentry);
3121 				dentry = dget(file->f_path.dentry);
3122 			}
3123 		} else if (WARN_ON(file->f_path.dentry == DENTRY_NOT_SET)) {
3124 			error = -EIO;
3125 		} else {
3126 			if (file->f_path.dentry) {
3127 				dput(dentry);
3128 				dentry = file->f_path.dentry;
3129 			}
3130 			if (unlikely(d_is_negative(dentry)))
3131 				error = -ENOENT;
3132 		}
3133 	}
3134 	if (error) {
3135 		dput(dentry);
3136 		dentry = ERR_PTR(error);
3137 	}
3138 	return dentry;
3139 }
3140 
3141 /*
3142  * Look up and maybe create and open the last component.
3143  *
3144  * Must be called with parent locked (exclusive in O_CREAT case).
3145  *
3146  * Returns 0 on success, that is, if
3147  *  the file was successfully atomically created (if necessary) and opened, or
3148  *  the file was not completely opened at this time, though lookups and
3149  *  creations were performed.
3150  * These case are distinguished by presence of FMODE_OPENED on file->f_mode.
3151  * In the latter case dentry returned in @path might be negative if O_CREAT
3152  * hadn't been specified.
3153  *
3154  * An error code is returned on failure.
3155  */
lookup_open(struct nameidata * nd,struct file * file,const struct open_flags * op,bool got_write)3156 static struct dentry *lookup_open(struct nameidata *nd, struct file *file,
3157 				  const struct open_flags *op,
3158 				  bool got_write)
3159 {
3160 	struct dentry *dir = nd->path.dentry;
3161 	struct inode *dir_inode = dir->d_inode;
3162 	int open_flag = op->open_flag;
3163 	struct dentry *dentry;
3164 	int error, create_error = 0;
3165 	umode_t mode = op->mode;
3166 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
3167 
3168 	if (unlikely(IS_DEADDIR(dir_inode)))
3169 		return ERR_PTR(-ENOENT);
3170 
3171 	file->f_mode &= ~FMODE_CREATED;
3172 	dentry = d_lookup(dir, &nd->last);
3173 	for (;;) {
3174 		if (!dentry) {
3175 			dentry = d_alloc_parallel(dir, &nd->last, &wq);
3176 			if (IS_ERR(dentry))
3177 				return dentry;
3178 		}
3179 		if (d_in_lookup(dentry))
3180 			break;
3181 
3182 		error = d_revalidate(dentry, nd->flags);
3183 		if (likely(error > 0))
3184 			break;
3185 		if (error)
3186 			goto out_dput;
3187 		d_invalidate(dentry);
3188 		dput(dentry);
3189 		dentry = NULL;
3190 	}
3191 	if (dentry->d_inode) {
3192 		/* Cached positive dentry: will open in f_op->open */
3193 		return dentry;
3194 	}
3195 
3196 	/*
3197 	 * Checking write permission is tricky, bacuse we don't know if we are
3198 	 * going to actually need it: O_CREAT opens should work as long as the
3199 	 * file exists.  But checking existence breaks atomicity.  The trick is
3200 	 * to check access and if not granted clear O_CREAT from the flags.
3201 	 *
3202 	 * Another problem is returing the "right" error value (e.g. for an
3203 	 * O_EXCL open we want to return EEXIST not EROFS).
3204 	 */
3205 	if (unlikely(!got_write))
3206 		open_flag &= ~O_TRUNC;
3207 	if (open_flag & O_CREAT) {
3208 		if (open_flag & O_EXCL)
3209 			open_flag &= ~O_TRUNC;
3210 		mode = vfs_prepare_mode(dir->d_inode, mode, mode, mode);
3211 		if (likely(got_write))
3212 			create_error = may_o_create(&nd->path, dentry, mode);
3213 		else
3214 			create_error = -EROFS;
3215 	}
3216 	if (create_error)
3217 		open_flag &= ~O_CREAT;
3218 	if (dir_inode->i_op->atomic_open) {
3219 		dentry = atomic_open(nd, dentry, file, open_flag, mode);
3220 		if (unlikely(create_error) && dentry == ERR_PTR(-ENOENT))
3221 			dentry = ERR_PTR(create_error);
3222 		return dentry;
3223 	}
3224 
3225 	if (d_in_lookup(dentry)) {
3226 		struct dentry *res = dir_inode->i_op->lookup(dir_inode, dentry,
3227 							     nd->flags);
3228 		d_lookup_done(dentry);
3229 		if (unlikely(res)) {
3230 			if (IS_ERR(res)) {
3231 				error = PTR_ERR(res);
3232 				goto out_dput;
3233 			}
3234 			dput(dentry);
3235 			dentry = res;
3236 		}
3237 	}
3238 
3239 	/* Negative dentry, just create the file */
3240 	if (!dentry->d_inode && (open_flag & O_CREAT)) {
3241 		file->f_mode |= FMODE_CREATED;
3242 		audit_inode_child(dir_inode, dentry, AUDIT_TYPE_CHILD_CREATE);
3243 		if (!dir_inode->i_op->create) {
3244 			error = -EACCES;
3245 			goto out_dput;
3246 		}
3247 		error = dir_inode->i_op->create(dir_inode, dentry, mode,
3248 						open_flag & O_EXCL);
3249 		if (error)
3250 			goto out_dput;
3251 	}
3252 	if (unlikely(create_error) && !dentry->d_inode) {
3253 		error = create_error;
3254 		goto out_dput;
3255 	}
3256 	return dentry;
3257 
3258 out_dput:
3259 	dput(dentry);
3260 	return ERR_PTR(error);
3261 }
3262 
open_last_lookups(struct nameidata * nd,struct file * file,const struct open_flags * op)3263 static const char *open_last_lookups(struct nameidata *nd,
3264 		   struct file *file, const struct open_flags *op)
3265 {
3266 	struct dentry *dir = nd->path.dentry;
3267 	int open_flag = op->open_flag;
3268 	bool got_write = false;
3269 	unsigned seq;
3270 	struct inode *inode;
3271 	struct dentry *dentry;
3272 	const char *res;
3273 
3274 	nd->flags |= op->intent;
3275 
3276 	if (nd->last_type != LAST_NORM) {
3277 		if (nd->depth)
3278 			put_link(nd);
3279 		return handle_dots(nd, nd->last_type);
3280 	}
3281 
3282 	if (!(open_flag & O_CREAT)) {
3283 		if (nd->last.name[nd->last.len])
3284 			nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
3285 		/* we _can_ be in RCU mode here */
3286 		dentry = lookup_fast(nd, &inode, &seq);
3287 		if (IS_ERR(dentry))
3288 			return ERR_CAST(dentry);
3289 		if (likely(dentry))
3290 			goto finish_lookup;
3291 
3292 		BUG_ON(nd->flags & LOOKUP_RCU);
3293 	} else {
3294 		/* create side of things */
3295 		if (nd->flags & LOOKUP_RCU) {
3296 			if (!try_to_unlazy(nd))
3297 				return ERR_PTR(-ECHILD);
3298 		}
3299 		audit_inode(nd->name, dir, AUDIT_INODE_PARENT);
3300 		/* trailing slashes? */
3301 		if (unlikely(nd->last.name[nd->last.len]))
3302 			return ERR_PTR(-EISDIR);
3303 	}
3304 
3305 	if (open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) {
3306 		got_write = !mnt_want_write(nd->path.mnt);
3307 		/*
3308 		 * do _not_ fail yet - we might not need that or fail with
3309 		 * a different error; let lookup_open() decide; we'll be
3310 		 * dropping this one anyway.
3311 		 */
3312 	}
3313 	if (open_flag & O_CREAT)
3314 		inode_lock(dir->d_inode);
3315 	else
3316 		inode_lock_shared(dir->d_inode);
3317 	dentry = lookup_open(nd, file, op, got_write);
3318 	if (!IS_ERR(dentry) && (file->f_mode & FMODE_CREATED))
3319 		fsnotify_create(dir->d_inode, dentry);
3320 	if (open_flag & O_CREAT)
3321 		inode_unlock(dir->d_inode);
3322 	else
3323 		inode_unlock_shared(dir->d_inode);
3324 
3325 	if (got_write)
3326 		mnt_drop_write(nd->path.mnt);
3327 
3328 	if (IS_ERR(dentry))
3329 		return ERR_CAST(dentry);
3330 
3331 	if (file->f_mode & (FMODE_OPENED | FMODE_CREATED)) {
3332 		dput(nd->path.dentry);
3333 		nd->path.dentry = dentry;
3334 		return NULL;
3335 	}
3336 
3337 finish_lookup:
3338 	if (nd->depth)
3339 		put_link(nd);
3340 	res = step_into(nd, WALK_TRAILING, dentry, inode, seq);
3341 	if (unlikely(res))
3342 		nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL);
3343 	return res;
3344 }
3345 
3346 /*
3347  * Handle the last step of open()
3348  */
do_open(struct nameidata * nd,struct file * file,const struct open_flags * op)3349 static int do_open(struct nameidata *nd,
3350 		   struct file *file, const struct open_flags *op)
3351 {
3352 	int open_flag = op->open_flag;
3353 	bool do_truncate;
3354 	int acc_mode;
3355 	int error;
3356 
3357 	if (!(file->f_mode & (FMODE_OPENED | FMODE_CREATED))) {
3358 		error = complete_walk(nd);
3359 		if (error)
3360 			return error;
3361 	}
3362 	if (!(file->f_mode & FMODE_CREATED))
3363 		audit_inode(nd->name, nd->path.dentry, 0);
3364 	if (open_flag & O_CREAT) {
3365 		if ((open_flag & O_EXCL) && !(file->f_mode & FMODE_CREATED))
3366 			return -EEXIST;
3367 		if (d_is_dir(nd->path.dentry))
3368 			return -EISDIR;
3369 		error = may_create_in_sticky(nd->dir_mode, nd->dir_uid,
3370 					     d_backing_inode(nd->path.dentry));
3371 		if (unlikely(error))
3372 			return error;
3373 	}
3374 	if ((nd->flags & LOOKUP_DIRECTORY) && !d_can_lookup(nd->path.dentry))
3375 		return -ENOTDIR;
3376 
3377 	do_truncate = false;
3378 	acc_mode = op->acc_mode;
3379 	if (file->f_mode & FMODE_CREATED) {
3380 		/* Don't check for write permission, don't truncate */
3381 		open_flag &= ~O_TRUNC;
3382 		acc_mode = 0;
3383 	} else if (d_is_reg(nd->path.dentry) && open_flag & O_TRUNC) {
3384 		error = mnt_want_write(nd->path.mnt);
3385 		if (error)
3386 			return error;
3387 		do_truncate = true;
3388 	}
3389 	error = may_open(&nd->path, acc_mode, open_flag);
3390 	if (!error && !(file->f_mode & FMODE_OPENED))
3391 		error = vfs_open(&nd->path, file);
3392 	if (!error)
3393 		error = ima_file_check(file, op->acc_mode);
3394 	if (!error && do_truncate)
3395 		error = handle_truncate(file);
3396 	if (unlikely(error > 0)) {
3397 		WARN_ON(1);
3398 		error = -EINVAL;
3399 	}
3400 	if (do_truncate)
3401 		mnt_drop_write(nd->path.mnt);
3402 	return error;
3403 }
3404 
vfs_tmpfile(struct dentry * dentry,umode_t mode,int open_flag)3405 struct dentry *vfs_tmpfile(struct dentry *dentry, umode_t mode, int open_flag)
3406 {
3407 	struct dentry *child = NULL;
3408 	struct inode *dir = dentry->d_inode;
3409 	struct inode *inode;
3410 	int error;
3411 
3412 	/* we want directory to be writable */
3413 	error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
3414 	if (error)
3415 		goto out_err;
3416 	error = -EOPNOTSUPP;
3417 	if (!dir->i_op->tmpfile)
3418 		goto out_err;
3419 	error = -ENOMEM;
3420 	child = d_alloc(dentry, &slash_name);
3421 	if (unlikely(!child))
3422 		goto out_err;
3423 	mode = vfs_prepare_mode(dir, mode, mode, mode);
3424 	error = dir->i_op->tmpfile(dir, child, mode);
3425 	if (error)
3426 		goto out_err;
3427 	error = -ENOENT;
3428 	inode = child->d_inode;
3429 	if (unlikely(!inode))
3430 		goto out_err;
3431 	if (!(open_flag & O_EXCL)) {
3432 		spin_lock(&inode->i_lock);
3433 		inode->i_state |= I_LINKABLE;
3434 		spin_unlock(&inode->i_lock);
3435 	}
3436 	ima_post_create_tmpfile(inode);
3437 	return child;
3438 
3439 out_err:
3440 	dput(child);
3441 	return ERR_PTR(error);
3442 }
3443 EXPORT_SYMBOL(vfs_tmpfile);
3444 
do_tmpfile(struct nameidata * nd,unsigned flags,const struct open_flags * op,struct file * file)3445 static int do_tmpfile(struct nameidata *nd, unsigned flags,
3446 		const struct open_flags *op,
3447 		struct file *file)
3448 {
3449 	struct dentry *child;
3450 	struct path path;
3451 	int error = path_lookupat(nd, flags | LOOKUP_DIRECTORY, &path);
3452 	if (unlikely(error))
3453 		return error;
3454 	error = mnt_want_write(path.mnt);
3455 	if (unlikely(error))
3456 		goto out;
3457 	child = vfs_tmpfile(path.dentry, op->mode, op->open_flag);
3458 	error = PTR_ERR(child);
3459 	if (IS_ERR(child))
3460 		goto out2;
3461 	dput(path.dentry);
3462 	path.dentry = child;
3463 	audit_inode(nd->name, child, 0);
3464 	/* Don't check for other permissions, the inode was just created */
3465 	error = may_open(&path, 0, op->open_flag);
3466 	if (error)
3467 		goto out2;
3468 	file->f_path.mnt = path.mnt;
3469 	error = finish_open(file, child, NULL);
3470 out2:
3471 	mnt_drop_write(path.mnt);
3472 out:
3473 	path_put(&path);
3474 	return error;
3475 }
3476 
do_o_path(struct nameidata * nd,unsigned flags,struct file * file)3477 static int do_o_path(struct nameidata *nd, unsigned flags, struct file *file)
3478 {
3479 	struct path path;
3480 	int error = path_lookupat(nd, flags, &path);
3481 	if (!error) {
3482 		audit_inode(nd->name, path.dentry, 0);
3483 		error = vfs_open(&path, file);
3484 		path_put(&path);
3485 	}
3486 	return error;
3487 }
3488 
path_openat(struct nameidata * nd,const struct open_flags * op,unsigned flags)3489 static struct file *path_openat(struct nameidata *nd,
3490 			const struct open_flags *op, unsigned flags)
3491 {
3492 	struct file *file;
3493 	int error;
3494 
3495 	file = alloc_empty_file(op->open_flag, current_cred());
3496 	if (IS_ERR(file))
3497 		return file;
3498 
3499 	if (unlikely(file->f_flags & __O_TMPFILE)) {
3500 		error = do_tmpfile(nd, flags, op, file);
3501 	} else if (unlikely(file->f_flags & O_PATH)) {
3502 		error = do_o_path(nd, flags, file);
3503 	} else {
3504 		const char *s = path_init(nd, flags);
3505 		while (!(error = link_path_walk(s, nd)) &&
3506 		       (s = open_last_lookups(nd, file, op)) != NULL)
3507 			;
3508 		if (!error)
3509 			error = do_open(nd, file, op);
3510 		terminate_walk(nd);
3511 	}
3512 	if (likely(!error)) {
3513 		if (likely(file->f_mode & FMODE_OPENED))
3514 			return file;
3515 		WARN_ON(1);
3516 		error = -EINVAL;
3517 	}
3518 	fput(file);
3519 	if (error == -EOPENSTALE) {
3520 		if (flags & LOOKUP_RCU)
3521 			error = -ECHILD;
3522 		else
3523 			error = -ESTALE;
3524 	}
3525 	return ERR_PTR(error);
3526 }
3527 
do_filp_open(int dfd,struct filename * pathname,const struct open_flags * op)3528 struct file *do_filp_open(int dfd, struct filename *pathname,
3529 		const struct open_flags *op)
3530 {
3531 	struct nameidata nd;
3532 	int flags = op->lookup_flags;
3533 	struct file *filp;
3534 
3535 	set_nameidata(&nd, dfd, pathname);
3536 	filp = path_openat(&nd, op, flags | LOOKUP_RCU);
3537 	if (unlikely(filp == ERR_PTR(-ECHILD)))
3538 		filp = path_openat(&nd, op, flags);
3539 	if (unlikely(filp == ERR_PTR(-ESTALE)))
3540 		filp = path_openat(&nd, op, flags | LOOKUP_REVAL);
3541 	restore_nameidata();
3542 	return filp;
3543 }
3544 
do_file_open_root(struct dentry * dentry,struct vfsmount * mnt,const char * name,const struct open_flags * op)3545 struct file *do_file_open_root(struct dentry *dentry, struct vfsmount *mnt,
3546 		const char *name, const struct open_flags *op)
3547 {
3548 	struct nameidata nd;
3549 	struct file *file;
3550 	struct filename *filename;
3551 	int flags = op->lookup_flags | LOOKUP_ROOT;
3552 
3553 	nd.root.mnt = mnt;
3554 	nd.root.dentry = dentry;
3555 
3556 	if (d_is_symlink(dentry) && op->intent & LOOKUP_OPEN)
3557 		return ERR_PTR(-ELOOP);
3558 
3559 	filename = getname_kernel(name);
3560 	if (IS_ERR(filename))
3561 		return ERR_CAST(filename);
3562 
3563 	set_nameidata(&nd, -1, filename);
3564 	file = path_openat(&nd, op, flags | LOOKUP_RCU);
3565 	if (unlikely(file == ERR_PTR(-ECHILD)))
3566 		file = path_openat(&nd, op, flags);
3567 	if (unlikely(file == ERR_PTR(-ESTALE)))
3568 		file = path_openat(&nd, op, flags | LOOKUP_REVAL);
3569 	restore_nameidata();
3570 	putname(filename);
3571 	return file;
3572 }
3573 
filename_create(int dfd,struct filename * name,struct path * path,unsigned int lookup_flags)3574 static struct dentry *filename_create(int dfd, struct filename *name,
3575 				struct path *path, unsigned int lookup_flags)
3576 {
3577 	struct dentry *dentry = ERR_PTR(-EEXIST);
3578 	struct qstr last;
3579 	int type;
3580 	int err2;
3581 	int error;
3582 	bool is_dir = (lookup_flags & LOOKUP_DIRECTORY);
3583 
3584 	/*
3585 	 * Note that only LOOKUP_REVAL and LOOKUP_DIRECTORY matter here. Any
3586 	 * other flags passed in are ignored!
3587 	 */
3588 	lookup_flags &= LOOKUP_REVAL;
3589 
3590 	name = filename_parentat(dfd, name, lookup_flags, path, &last, &type);
3591 	if (IS_ERR(name))
3592 		return ERR_CAST(name);
3593 
3594 	/*
3595 	 * Yucky last component or no last component at all?
3596 	 * (foo/., foo/.., /////)
3597 	 */
3598 	if (unlikely(type != LAST_NORM))
3599 		goto out;
3600 
3601 	/* don't fail immediately if it's r/o, at least try to report other errors */
3602 	err2 = mnt_want_write(path->mnt);
3603 	/*
3604 	 * Do the final lookup.
3605 	 */
3606 	lookup_flags |= LOOKUP_CREATE | LOOKUP_EXCL;
3607 	inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
3608 	dentry = __lookup_hash(&last, path->dentry, lookup_flags);
3609 	if (IS_ERR(dentry))
3610 		goto unlock;
3611 
3612 	error = -EEXIST;
3613 	if (d_is_positive(dentry))
3614 		goto fail;
3615 
3616 	/*
3617 	 * Special case - lookup gave negative, but... we had foo/bar/
3618 	 * From the vfs_mknod() POV we just have a negative dentry -
3619 	 * all is fine. Let's be bastards - you had / on the end, you've
3620 	 * been asking for (non-existent) directory. -ENOENT for you.
3621 	 */
3622 	if (unlikely(!is_dir && last.name[last.len])) {
3623 		error = -ENOENT;
3624 		goto fail;
3625 	}
3626 	if (unlikely(err2)) {
3627 		error = err2;
3628 		goto fail;
3629 	}
3630 	putname(name);
3631 	return dentry;
3632 fail:
3633 	dput(dentry);
3634 	dentry = ERR_PTR(error);
3635 unlock:
3636 	inode_unlock(path->dentry->d_inode);
3637 	if (!err2)
3638 		mnt_drop_write(path->mnt);
3639 out:
3640 	path_put(path);
3641 	putname(name);
3642 	return dentry;
3643 }
3644 
kern_path_create(int dfd,const char * pathname,struct path * path,unsigned int lookup_flags)3645 struct dentry *kern_path_create(int dfd, const char *pathname,
3646 				struct path *path, unsigned int lookup_flags)
3647 {
3648 	return filename_create(dfd, getname_kernel(pathname),
3649 				path, lookup_flags);
3650 }
3651 EXPORT_SYMBOL(kern_path_create);
3652 
done_path_create(struct path * path,struct dentry * dentry)3653 void done_path_create(struct path *path, struct dentry *dentry)
3654 {
3655 	dput(dentry);
3656 	inode_unlock(path->dentry->d_inode);
3657 	mnt_drop_write(path->mnt);
3658 	path_put(path);
3659 }
3660 EXPORT_SYMBOL(done_path_create);
3661 
user_path_create(int dfd,const char __user * pathname,struct path * path,unsigned int lookup_flags)3662 inline struct dentry *user_path_create(int dfd, const char __user *pathname,
3663 				struct path *path, unsigned int lookup_flags)
3664 {
3665 	return filename_create(dfd, getname(pathname), path, lookup_flags);
3666 }
3667 EXPORT_SYMBOL(user_path_create);
3668 
vfs_mknod(struct inode * dir,struct dentry * dentry,umode_t mode,dev_t dev)3669 int vfs_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
3670 {
3671 	bool is_whiteout = S_ISCHR(mode) && dev == WHITEOUT_DEV;
3672 	int error = may_create(dir, dentry);
3673 
3674 	if (error)
3675 		return error;
3676 
3677 	if ((S_ISCHR(mode) || S_ISBLK(mode)) && !is_whiteout &&
3678 	    !capable(CAP_MKNOD))
3679 		return -EPERM;
3680 
3681 	if (!dir->i_op->mknod)
3682 		return -EPERM;
3683 
3684 	mode = vfs_prepare_mode(dir, mode, mode, mode);
3685 	error = devcgroup_inode_mknod(mode, dev);
3686 	if (error)
3687 		return error;
3688 
3689 	error = security_inode_mknod(dir, dentry, mode, dev);
3690 	if (error)
3691 		return error;
3692 
3693 	error = dir->i_op->mknod(dir, dentry, mode, dev);
3694 	if (!error)
3695 		fsnotify_create(dir, dentry);
3696 	return error;
3697 }
3698 EXPORT_SYMBOL(vfs_mknod);
3699 
may_mknod(umode_t mode)3700 static int may_mknod(umode_t mode)
3701 {
3702 	switch (mode & S_IFMT) {
3703 	case S_IFREG:
3704 	case S_IFCHR:
3705 	case S_IFBLK:
3706 	case S_IFIFO:
3707 	case S_IFSOCK:
3708 	case 0: /* zero mode translates to S_IFREG */
3709 		return 0;
3710 	case S_IFDIR:
3711 		return -EPERM;
3712 	default:
3713 		return -EINVAL;
3714 	}
3715 }
3716 
do_mknodat(int dfd,const char __user * filename,umode_t mode,unsigned int dev)3717 static long do_mknodat(int dfd, const char __user *filename, umode_t mode,
3718 		unsigned int dev)
3719 {
3720 	struct dentry *dentry;
3721 	struct path path;
3722 	int error;
3723 	unsigned int lookup_flags = 0;
3724 
3725 	error = may_mknod(mode);
3726 	if (error)
3727 		return error;
3728 retry:
3729 	dentry = user_path_create(dfd, filename, &path, lookup_flags);
3730 	if (IS_ERR(dentry))
3731 		return PTR_ERR(dentry);
3732 
3733 	error = security_path_mknod(&path, dentry,
3734 			mode_strip_umask(path.dentry->d_inode, mode), dev);
3735 	if (error)
3736 		goto out;
3737 	switch (mode & S_IFMT) {
3738 		case 0: case S_IFREG:
3739 			error = vfs_create(path.dentry->d_inode,dentry,mode,true);
3740 			if (!error)
3741 				ima_post_path_mknod(dentry);
3742 			break;
3743 		case S_IFCHR: case S_IFBLK:
3744 			error = vfs_mknod(path.dentry->d_inode,dentry,mode,
3745 					new_decode_dev(dev));
3746 			break;
3747 		case S_IFIFO: case S_IFSOCK:
3748 			error = vfs_mknod(path.dentry->d_inode,dentry,mode,0);
3749 			break;
3750 	}
3751 out:
3752 	done_path_create(&path, dentry);
3753 	if (retry_estale(error, lookup_flags)) {
3754 		lookup_flags |= LOOKUP_REVAL;
3755 		goto retry;
3756 	}
3757 	return error;
3758 }
3759 
SYSCALL_DEFINE4(mknodat,int,dfd,const char __user *,filename,umode_t,mode,unsigned int,dev)3760 SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, umode_t, mode,
3761 		unsigned int, dev)
3762 {
3763 	return do_mknodat(dfd, filename, mode, dev);
3764 }
3765 
SYSCALL_DEFINE3(mknod,const char __user *,filename,umode_t,mode,unsigned,dev)3766 SYSCALL_DEFINE3(mknod, const char __user *, filename, umode_t, mode, unsigned, dev)
3767 {
3768 	return do_mknodat(AT_FDCWD, filename, mode, dev);
3769 }
3770 
vfs_mkdir(struct inode * dir,struct dentry * dentry,umode_t mode)3771 int vfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
3772 {
3773 	int error = may_create(dir, dentry);
3774 	unsigned max_links = dir->i_sb->s_max_links;
3775 
3776 	if (error)
3777 		return error;
3778 
3779 	if (!dir->i_op->mkdir)
3780 		return -EPERM;
3781 
3782 	mode = vfs_prepare_mode(dir, mode, S_IRWXUGO | S_ISVTX, 0);
3783 	error = security_inode_mkdir(dir, dentry, mode);
3784 	if (error)
3785 		return error;
3786 
3787 	if (max_links && dir->i_nlink >= max_links)
3788 		return -EMLINK;
3789 
3790 	error = dir->i_op->mkdir(dir, dentry, mode);
3791 	if (!error)
3792 		fsnotify_mkdir(dir, dentry);
3793 	return error;
3794 }
3795 EXPORT_SYMBOL_NS(vfs_mkdir, ANDROID_GKI_VFS_EXPORT_ONLY);
3796 
do_mkdirat(int dfd,const char __user * pathname,umode_t mode)3797 static long do_mkdirat(int dfd, const char __user *pathname, umode_t mode)
3798 {
3799 	struct dentry *dentry;
3800 	struct path path;
3801 	int error;
3802 	unsigned int lookup_flags = LOOKUP_DIRECTORY;
3803 
3804 retry:
3805 	dentry = user_path_create(dfd, pathname, &path, lookup_flags);
3806 	if (IS_ERR(dentry))
3807 		return PTR_ERR(dentry);
3808 
3809 	error = security_path_mkdir(&path, dentry,
3810 			mode_strip_umask(path.dentry->d_inode, mode));
3811 	if (!error)
3812 		error = vfs_mkdir(path.dentry->d_inode, dentry, mode);
3813 	done_path_create(&path, dentry);
3814 	if (retry_estale(error, lookup_flags)) {
3815 		lookup_flags |= LOOKUP_REVAL;
3816 		goto retry;
3817 	}
3818 	return error;
3819 }
3820 
SYSCALL_DEFINE3(mkdirat,int,dfd,const char __user *,pathname,umode_t,mode)3821 SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, umode_t, mode)
3822 {
3823 	return do_mkdirat(dfd, pathname, mode);
3824 }
3825 
SYSCALL_DEFINE2(mkdir,const char __user *,pathname,umode_t,mode)3826 SYSCALL_DEFINE2(mkdir, const char __user *, pathname, umode_t, mode)
3827 {
3828 	return do_mkdirat(AT_FDCWD, pathname, mode);
3829 }
3830 
vfs_rmdir(struct inode * dir,struct dentry * dentry)3831 int vfs_rmdir(struct inode *dir, struct dentry *dentry)
3832 {
3833 	int error = may_delete(dir, dentry, 1);
3834 
3835 	if (error)
3836 		return error;
3837 
3838 	if (!dir->i_op->rmdir)
3839 		return -EPERM;
3840 
3841 	dget(dentry);
3842 	inode_lock(dentry->d_inode);
3843 
3844 	error = -EBUSY;
3845 	if (is_local_mountpoint(dentry))
3846 		goto out;
3847 
3848 	error = security_inode_rmdir(dir, dentry);
3849 	if (error)
3850 		goto out;
3851 
3852 	error = dir->i_op->rmdir(dir, dentry);
3853 	if (error)
3854 		goto out;
3855 
3856 	shrink_dcache_parent(dentry);
3857 	dentry->d_inode->i_flags |= S_DEAD;
3858 	dont_mount(dentry);
3859 	detach_mounts(dentry);
3860 
3861 out:
3862 	inode_unlock(dentry->d_inode);
3863 	dput(dentry);
3864 	if (!error)
3865 		d_delete_notify(dir, dentry);
3866 	return error;
3867 }
3868 EXPORT_SYMBOL_NS(vfs_rmdir, ANDROID_GKI_VFS_EXPORT_ONLY);
3869 
do_rmdir(int dfd,struct filename * name)3870 long do_rmdir(int dfd, struct filename *name)
3871 {
3872 	int error = 0;
3873 	struct dentry *dentry;
3874 	struct path path;
3875 	struct qstr last;
3876 	int type;
3877 	unsigned int lookup_flags = 0;
3878 retry:
3879 	name = filename_parentat(dfd, name, lookup_flags,
3880 				&path, &last, &type);
3881 	if (IS_ERR(name))
3882 		return PTR_ERR(name);
3883 
3884 	switch (type) {
3885 	case LAST_DOTDOT:
3886 		error = -ENOTEMPTY;
3887 		goto exit1;
3888 	case LAST_DOT:
3889 		error = -EINVAL;
3890 		goto exit1;
3891 	case LAST_ROOT:
3892 		error = -EBUSY;
3893 		goto exit1;
3894 	}
3895 
3896 	error = mnt_want_write(path.mnt);
3897 	if (error)
3898 		goto exit1;
3899 
3900 	inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
3901 	dentry = __lookup_hash(&last, path.dentry, lookup_flags);
3902 	error = PTR_ERR(dentry);
3903 	if (IS_ERR(dentry))
3904 		goto exit2;
3905 	if (!dentry->d_inode) {
3906 		error = -ENOENT;
3907 		goto exit3;
3908 	}
3909 	error = security_path_rmdir(&path, dentry);
3910 	if (error)
3911 		goto exit3;
3912 	error = vfs_rmdir(path.dentry->d_inode, dentry);
3913 exit3:
3914 	dput(dentry);
3915 exit2:
3916 	inode_unlock(path.dentry->d_inode);
3917 	mnt_drop_write(path.mnt);
3918 exit1:
3919 	path_put(&path);
3920 	if (retry_estale(error, lookup_flags)) {
3921 		lookup_flags |= LOOKUP_REVAL;
3922 		goto retry;
3923 	}
3924 	putname(name);
3925 	return error;
3926 }
3927 
SYSCALL_DEFINE1(rmdir,const char __user *,pathname)3928 SYSCALL_DEFINE1(rmdir, const char __user *, pathname)
3929 {
3930 	return do_rmdir(AT_FDCWD, getname(pathname));
3931 }
3932 
3933 /**
3934  * vfs_unlink - unlink a filesystem object
3935  * @dir:	parent directory
3936  * @dentry:	victim
3937  * @delegated_inode: returns victim inode, if the inode is delegated.
3938  *
3939  * The caller must hold dir->i_mutex.
3940  *
3941  * If vfs_unlink discovers a delegation, it will return -EWOULDBLOCK and
3942  * return a reference to the inode in delegated_inode.  The caller
3943  * should then break the delegation on that inode and retry.  Because
3944  * breaking a delegation may take a long time, the caller should drop
3945  * dir->i_mutex before doing so.
3946  *
3947  * Alternatively, a caller may pass NULL for delegated_inode.  This may
3948  * be appropriate for callers that expect the underlying filesystem not
3949  * to be NFS exported.
3950  */
vfs_unlink(struct inode * dir,struct dentry * dentry,struct inode ** delegated_inode)3951 int vfs_unlink(struct inode *dir, struct dentry *dentry, struct inode **delegated_inode)
3952 {
3953 	struct inode *target = dentry->d_inode;
3954 	int error = may_delete(dir, dentry, 0);
3955 
3956 	if (error)
3957 		return error;
3958 
3959 	if (!dir->i_op->unlink)
3960 		return -EPERM;
3961 
3962 	inode_lock(target);
3963 	if (is_local_mountpoint(dentry))
3964 		error = -EBUSY;
3965 	else {
3966 		error = security_inode_unlink(dir, dentry);
3967 		if (!error) {
3968 			error = try_break_deleg(target, delegated_inode);
3969 			if (error)
3970 				goto out;
3971 			error = dir->i_op->unlink(dir, dentry);
3972 			if (!error) {
3973 				dont_mount(dentry);
3974 				detach_mounts(dentry);
3975 			}
3976 		}
3977 	}
3978 out:
3979 	inode_unlock(target);
3980 
3981 	/* We don't d_delete() NFS sillyrenamed files--they still exist. */
3982 	if (!error && dentry->d_flags & DCACHE_NFSFS_RENAMED) {
3983 		fsnotify_unlink(dir, dentry);
3984 	} else if (!error) {
3985 		fsnotify_link_count(target);
3986 		d_delete_notify(dir, dentry);
3987 	}
3988 
3989 	return error;
3990 }
3991 EXPORT_SYMBOL_NS(vfs_unlink, ANDROID_GKI_VFS_EXPORT_ONLY);
3992 
3993 /*
3994  * Make sure that the actual truncation of the file will occur outside its
3995  * directory's i_mutex.  Truncate can take a long time if there is a lot of
3996  * writeout happening, and we don't want to prevent access to the directory
3997  * while waiting on the I/O.
3998  */
do_unlinkat(int dfd,struct filename * name)3999 long do_unlinkat(int dfd, struct filename *name)
4000 {
4001 	int error;
4002 	struct dentry *dentry;
4003 	struct path path;
4004 	struct qstr last;
4005 	int type;
4006 	struct inode *inode = NULL;
4007 	struct inode *delegated_inode = NULL;
4008 	unsigned int lookup_flags = 0;
4009 retry:
4010 	name = filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
4011 	if (IS_ERR(name))
4012 		return PTR_ERR(name);
4013 
4014 	error = -EISDIR;
4015 	if (type != LAST_NORM)
4016 		goto exit1;
4017 
4018 	error = mnt_want_write(path.mnt);
4019 	if (error)
4020 		goto exit1;
4021 retry_deleg:
4022 	inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
4023 	dentry = __lookup_hash(&last, path.dentry, lookup_flags);
4024 	error = PTR_ERR(dentry);
4025 	if (!IS_ERR(dentry)) {
4026 		/* Why not before? Because we want correct error value */
4027 		if (last.name[last.len])
4028 			goto slashes;
4029 		inode = dentry->d_inode;
4030 		if (d_is_negative(dentry))
4031 			goto slashes;
4032 		ihold(inode);
4033 		error = security_path_unlink(&path, dentry);
4034 		if (error)
4035 			goto exit2;
4036 		error = vfs_unlink(path.dentry->d_inode, dentry, &delegated_inode);
4037 exit2:
4038 		dput(dentry);
4039 	}
4040 	inode_unlock(path.dentry->d_inode);
4041 	if (inode)
4042 		iput(inode);	/* truncate the inode here */
4043 	inode = NULL;
4044 	if (delegated_inode) {
4045 		error = break_deleg_wait(&delegated_inode);
4046 		if (!error)
4047 			goto retry_deleg;
4048 	}
4049 	mnt_drop_write(path.mnt);
4050 exit1:
4051 	path_put(&path);
4052 	if (retry_estale(error, lookup_flags)) {
4053 		lookup_flags |= LOOKUP_REVAL;
4054 		inode = NULL;
4055 		goto retry;
4056 	}
4057 	putname(name);
4058 	return error;
4059 
4060 slashes:
4061 	if (d_is_negative(dentry))
4062 		error = -ENOENT;
4063 	else if (d_is_dir(dentry))
4064 		error = -EISDIR;
4065 	else
4066 		error = -ENOTDIR;
4067 	goto exit2;
4068 }
4069 
SYSCALL_DEFINE3(unlinkat,int,dfd,const char __user *,pathname,int,flag)4070 SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag)
4071 {
4072 	if ((flag & ~AT_REMOVEDIR) != 0)
4073 		return -EINVAL;
4074 
4075 	if (flag & AT_REMOVEDIR)
4076 		return do_rmdir(dfd, getname(pathname));
4077 	return do_unlinkat(dfd, getname(pathname));
4078 }
4079 
SYSCALL_DEFINE1(unlink,const char __user *,pathname)4080 SYSCALL_DEFINE1(unlink, const char __user *, pathname)
4081 {
4082 	return do_unlinkat(AT_FDCWD, getname(pathname));
4083 }
4084 
vfs_symlink(struct inode * dir,struct dentry * dentry,const char * oldname)4085 int vfs_symlink(struct inode *dir, struct dentry *dentry, const char *oldname)
4086 {
4087 	int error = may_create(dir, dentry);
4088 
4089 	if (error)
4090 		return error;
4091 
4092 	if (!dir->i_op->symlink)
4093 		return -EPERM;
4094 
4095 	error = security_inode_symlink(dir, dentry, oldname);
4096 	if (error)
4097 		return error;
4098 
4099 	error = dir->i_op->symlink(dir, dentry, oldname);
4100 	if (!error)
4101 		fsnotify_create(dir, dentry);
4102 	return error;
4103 }
4104 EXPORT_SYMBOL(vfs_symlink);
4105 
do_symlinkat(const char __user * oldname,int newdfd,const char __user * newname)4106 static long do_symlinkat(const char __user *oldname, int newdfd,
4107 		  const char __user *newname)
4108 {
4109 	int error;
4110 	struct filename *from;
4111 	struct dentry *dentry;
4112 	struct path path;
4113 	unsigned int lookup_flags = 0;
4114 
4115 	from = getname(oldname);
4116 	if (IS_ERR(from))
4117 		return PTR_ERR(from);
4118 retry:
4119 	dentry = user_path_create(newdfd, newname, &path, lookup_flags);
4120 	error = PTR_ERR(dentry);
4121 	if (IS_ERR(dentry))
4122 		goto out_putname;
4123 
4124 	error = security_path_symlink(&path, dentry, from->name);
4125 	if (!error)
4126 		error = vfs_symlink(path.dentry->d_inode, dentry, from->name);
4127 	done_path_create(&path, dentry);
4128 	if (retry_estale(error, lookup_flags)) {
4129 		lookup_flags |= LOOKUP_REVAL;
4130 		goto retry;
4131 	}
4132 out_putname:
4133 	putname(from);
4134 	return error;
4135 }
4136 
SYSCALL_DEFINE3(symlinkat,const char __user *,oldname,int,newdfd,const char __user *,newname)4137 SYSCALL_DEFINE3(symlinkat, const char __user *, oldname,
4138 		int, newdfd, const char __user *, newname)
4139 {
4140 	return do_symlinkat(oldname, newdfd, newname);
4141 }
4142 
SYSCALL_DEFINE2(symlink,const char __user *,oldname,const char __user *,newname)4143 SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname)
4144 {
4145 	return do_symlinkat(oldname, AT_FDCWD, newname);
4146 }
4147 
4148 /**
4149  * vfs_link - create a new link
4150  * @old_dentry:	object to be linked
4151  * @dir:	new parent
4152  * @new_dentry:	where to create the new link
4153  * @delegated_inode: returns inode needing a delegation break
4154  *
4155  * The caller must hold dir->i_mutex
4156  *
4157  * If vfs_link discovers a delegation on the to-be-linked file in need
4158  * of breaking, it will return -EWOULDBLOCK and return a reference to the
4159  * inode in delegated_inode.  The caller should then break the delegation
4160  * and retry.  Because breaking a delegation may take a long time, the
4161  * caller should drop the i_mutex before doing so.
4162  *
4163  * Alternatively, a caller may pass NULL for delegated_inode.  This may
4164  * be appropriate for callers that expect the underlying filesystem not
4165  * to be NFS exported.
4166  */
vfs_link(struct dentry * old_dentry,struct inode * dir,struct dentry * new_dentry,struct inode ** delegated_inode)4167 int vfs_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry, struct inode **delegated_inode)
4168 {
4169 	struct inode *inode = old_dentry->d_inode;
4170 	unsigned max_links = dir->i_sb->s_max_links;
4171 	int error;
4172 
4173 	if (!inode)
4174 		return -ENOENT;
4175 
4176 	error = may_create(dir, new_dentry);
4177 	if (error)
4178 		return error;
4179 
4180 	if (dir->i_sb != inode->i_sb)
4181 		return -EXDEV;
4182 
4183 	/*
4184 	 * A link to an append-only or immutable file cannot be created.
4185 	 */
4186 	if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
4187 		return -EPERM;
4188 	/*
4189 	 * Updating the link count will likely cause i_uid and i_gid to
4190 	 * be writen back improperly if their true value is unknown to
4191 	 * the vfs.
4192 	 */
4193 	if (HAS_UNMAPPED_ID(inode))
4194 		return -EPERM;
4195 	if (!dir->i_op->link)
4196 		return -EPERM;
4197 	if (S_ISDIR(inode->i_mode))
4198 		return -EPERM;
4199 
4200 	error = security_inode_link(old_dentry, dir, new_dentry);
4201 	if (error)
4202 		return error;
4203 
4204 	inode_lock(inode);
4205 	/* Make sure we don't allow creating hardlink to an unlinked file */
4206 	if (inode->i_nlink == 0 && !(inode->i_state & I_LINKABLE))
4207 		error =  -ENOENT;
4208 	else if (max_links && inode->i_nlink >= max_links)
4209 		error = -EMLINK;
4210 	else {
4211 		error = try_break_deleg(inode, delegated_inode);
4212 		if (!error)
4213 			error = dir->i_op->link(old_dentry, dir, new_dentry);
4214 	}
4215 
4216 	if (!error && (inode->i_state & I_LINKABLE)) {
4217 		spin_lock(&inode->i_lock);
4218 		inode->i_state &= ~I_LINKABLE;
4219 		spin_unlock(&inode->i_lock);
4220 	}
4221 	inode_unlock(inode);
4222 	if (!error)
4223 		fsnotify_link(dir, inode, new_dentry);
4224 	return error;
4225 }
4226 EXPORT_SYMBOL_NS(vfs_link, ANDROID_GKI_VFS_EXPORT_ONLY);
4227 
4228 /*
4229  * Hardlinks are often used in delicate situations.  We avoid
4230  * security-related surprises by not following symlinks on the
4231  * newname.  --KAB
4232  *
4233  * We don't follow them on the oldname either to be compatible
4234  * with linux 2.0, and to avoid hard-linking to directories
4235  * and other special files.  --ADM
4236  */
do_linkat(int olddfd,const char __user * oldname,int newdfd,const char __user * newname,int flags)4237 static int do_linkat(int olddfd, const char __user *oldname, int newdfd,
4238 	      const char __user *newname, int flags)
4239 {
4240 	struct dentry *new_dentry;
4241 	struct path old_path, new_path;
4242 	struct inode *delegated_inode = NULL;
4243 	int how = 0;
4244 	int error;
4245 
4246 	if ((flags & ~(AT_SYMLINK_FOLLOW | AT_EMPTY_PATH)) != 0)
4247 		return -EINVAL;
4248 	/*
4249 	 * To use null names we require CAP_DAC_READ_SEARCH
4250 	 * This ensures that not everyone will be able to create
4251 	 * handlink using the passed filedescriptor.
4252 	 */
4253 	if (flags & AT_EMPTY_PATH) {
4254 		if (!capable(CAP_DAC_READ_SEARCH))
4255 			return -ENOENT;
4256 		how = LOOKUP_EMPTY;
4257 	}
4258 
4259 	if (flags & AT_SYMLINK_FOLLOW)
4260 		how |= LOOKUP_FOLLOW;
4261 retry:
4262 	error = user_path_at(olddfd, oldname, how, &old_path);
4263 	if (error)
4264 		return error;
4265 
4266 	new_dentry = user_path_create(newdfd, newname, &new_path,
4267 					(how & LOOKUP_REVAL));
4268 	error = PTR_ERR(new_dentry);
4269 	if (IS_ERR(new_dentry))
4270 		goto out;
4271 
4272 	error = -EXDEV;
4273 	if (old_path.mnt != new_path.mnt)
4274 		goto out_dput;
4275 	error = may_linkat(&old_path);
4276 	if (unlikely(error))
4277 		goto out_dput;
4278 	error = security_path_link(old_path.dentry, &new_path, new_dentry);
4279 	if (error)
4280 		goto out_dput;
4281 	error = vfs_link(old_path.dentry, new_path.dentry->d_inode, new_dentry, &delegated_inode);
4282 out_dput:
4283 	done_path_create(&new_path, new_dentry);
4284 	if (delegated_inode) {
4285 		error = break_deleg_wait(&delegated_inode);
4286 		if (!error) {
4287 			path_put(&old_path);
4288 			goto retry;
4289 		}
4290 	}
4291 	if (retry_estale(error, how)) {
4292 		path_put(&old_path);
4293 		how |= LOOKUP_REVAL;
4294 		goto retry;
4295 	}
4296 out:
4297 	path_put(&old_path);
4298 
4299 	return error;
4300 }
4301 
SYSCALL_DEFINE5(linkat,int,olddfd,const char __user *,oldname,int,newdfd,const char __user *,newname,int,flags)4302 SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname,
4303 		int, newdfd, const char __user *, newname, int, flags)
4304 {
4305 	return do_linkat(olddfd, oldname, newdfd, newname, flags);
4306 }
4307 
SYSCALL_DEFINE2(link,const char __user *,oldname,const char __user *,newname)4308 SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname)
4309 {
4310 	return do_linkat(AT_FDCWD, oldname, AT_FDCWD, newname, 0);
4311 }
4312 
4313 /**
4314  * vfs_rename - rename a filesystem object
4315  * @old_dir:	parent of source
4316  * @old_dentry:	source
4317  * @new_dir:	parent of destination
4318  * @new_dentry:	destination
4319  * @delegated_inode: returns an inode needing a delegation break
4320  * @flags:	rename flags
4321  *
4322  * The caller must hold multiple mutexes--see lock_rename()).
4323  *
4324  * If vfs_rename discovers a delegation in need of breaking at either
4325  * the source or destination, it will return -EWOULDBLOCK and return a
4326  * reference to the inode in delegated_inode.  The caller should then
4327  * break the delegation and retry.  Because breaking a delegation may
4328  * take a long time, the caller should drop all locks before doing
4329  * so.
4330  *
4331  * Alternatively, a caller may pass NULL for delegated_inode.  This may
4332  * be appropriate for callers that expect the underlying filesystem not
4333  * to be NFS exported.
4334  *
4335  * The worst of all namespace operations - renaming directory. "Perverted"
4336  * doesn't even start to describe it. Somebody in UCB had a heck of a trip...
4337  * Problems:
4338  *
4339  *	a) we can get into loop creation.
4340  *	b) race potential - two innocent renames can create a loop together.
4341  *	   That's where 4.4BSD screws up. Current fix: serialization on
4342  *	   sb->s_vfs_rename_mutex. We might be more accurate, but that's another
4343  *	   story.
4344  *	c) we may have to lock up to _four_ objects - parents and victim (if it exists),
4345  *	   and source (if it's a non-directory or a subdirectory that moves to
4346  *	   different parent).
4347  *	   And that - after we got ->i_mutex on parents (until then we don't know
4348  *	   whether the target exists).  Solution: try to be smart with locking
4349  *	   order for inodes.  We rely on the fact that tree topology may change
4350  *	   only under ->s_vfs_rename_mutex _and_ that parent of the object we
4351  *	   move will be locked.  Thus we can rank directories by the tree
4352  *	   (ancestors first) and rank all non-directories after them.
4353  *	   That works since everybody except rename does "lock parent, lookup,
4354  *	   lock child" and rename is under ->s_vfs_rename_mutex.
4355  *	   HOWEVER, it relies on the assumption that any object with ->lookup()
4356  *	   has no more than 1 dentry.  If "hybrid" objects will ever appear,
4357  *	   we'd better make sure that there's no link(2) for them.
4358  *	d) conversion from fhandle to dentry may come in the wrong moment - when
4359  *	   we are removing the target. Solution: we will have to grab ->i_mutex
4360  *	   in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on
4361  *	   ->i_mutex on parents, which works but leads to some truly excessive
4362  *	   locking].
4363  */
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)4364 int vfs_rename(struct inode *old_dir, struct dentry *old_dentry,
4365 	       struct inode *new_dir, struct dentry *new_dentry,
4366 	       struct inode **delegated_inode, unsigned int flags)
4367 {
4368 	int error;
4369 	bool is_dir = d_is_dir(old_dentry);
4370 	struct inode *source = old_dentry->d_inode;
4371 	struct inode *target = new_dentry->d_inode;
4372 	bool new_is_dir = false;
4373 	unsigned max_links = new_dir->i_sb->s_max_links;
4374 	struct name_snapshot old_name;
4375 	bool lock_old_subdir, lock_new_subdir;
4376 
4377 	if (source == target)
4378 		return 0;
4379 
4380 	error = may_delete(old_dir, old_dentry, is_dir);
4381 	if (error)
4382 		return error;
4383 
4384 	if (!target) {
4385 		error = may_create(new_dir, new_dentry);
4386 	} else {
4387 		new_is_dir = d_is_dir(new_dentry);
4388 
4389 		if (!(flags & RENAME_EXCHANGE))
4390 			error = may_delete(new_dir, new_dentry, is_dir);
4391 		else
4392 			error = may_delete(new_dir, new_dentry, new_is_dir);
4393 	}
4394 	if (error)
4395 		return error;
4396 
4397 	if (!old_dir->i_op->rename)
4398 		return -EPERM;
4399 
4400 	/*
4401 	 * If we are going to change the parent - check write permissions,
4402 	 * we'll need to flip '..'.
4403 	 */
4404 	if (new_dir != old_dir) {
4405 		if (is_dir) {
4406 			error = inode_permission(source, MAY_WRITE);
4407 			if (error)
4408 				return error;
4409 		}
4410 		if ((flags & RENAME_EXCHANGE) && new_is_dir) {
4411 			error = inode_permission(target, MAY_WRITE);
4412 			if (error)
4413 				return error;
4414 		}
4415 	}
4416 
4417 	error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,
4418 				      flags);
4419 	if (error)
4420 		return error;
4421 
4422 	take_dentry_name_snapshot(&old_name, old_dentry);
4423 	dget(new_dentry);
4424 	/*
4425 	 * Lock children.
4426 	 * The source subdirectory needs to be locked on cross-directory
4427 	 * rename or cross-directory exchange since its parent changes.
4428 	 * The target subdirectory needs to be locked on cross-directory
4429 	 * exchange due to parent change and on any rename due to becoming
4430 	 * a victim.
4431 	 * Non-directories need locking in all cases (for NFS reasons);
4432 	 * they get locked after any subdirectories (in inode address order).
4433 	 *
4434 	 * NOTE: WE ONLY LOCK UNRELATED DIRECTORIES IN CROSS-DIRECTORY CASE.
4435 	 * NEVER, EVER DO THAT WITHOUT ->s_vfs_rename_mutex.
4436 	 */
4437 	lock_old_subdir = new_dir != old_dir;
4438 	lock_new_subdir = new_dir != old_dir || !(flags & RENAME_EXCHANGE);
4439 	if (is_dir) {
4440 		if (lock_old_subdir)
4441 			inode_lock_nested(source, I_MUTEX_CHILD);
4442 		if (target && (!new_is_dir || lock_new_subdir))
4443 			inode_lock(target);
4444 	} else if (new_is_dir) {
4445 		if (lock_new_subdir)
4446 			inode_lock_nested(target, I_MUTEX_CHILD);
4447 		inode_lock(source);
4448 	} else {
4449 		lock_two_nondirectories(source, target);
4450 	}
4451 
4452 	error = -EBUSY;
4453 	if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
4454 		goto out;
4455 
4456 	if (max_links && new_dir != old_dir) {
4457 		error = -EMLINK;
4458 		if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)
4459 			goto out;
4460 		if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&
4461 		    old_dir->i_nlink >= max_links)
4462 			goto out;
4463 	}
4464 	if (!is_dir) {
4465 		error = try_break_deleg(source, delegated_inode);
4466 		if (error)
4467 			goto out;
4468 	}
4469 	if (target && !new_is_dir) {
4470 		error = try_break_deleg(target, delegated_inode);
4471 		if (error)
4472 			goto out;
4473 	}
4474 	error = old_dir->i_op->rename(old_dir, old_dentry,
4475 				       new_dir, new_dentry, flags);
4476 	if (error)
4477 		goto out;
4478 
4479 	if (!(flags & RENAME_EXCHANGE) && target) {
4480 		if (is_dir) {
4481 			shrink_dcache_parent(new_dentry);
4482 			target->i_flags |= S_DEAD;
4483 		}
4484 		dont_mount(new_dentry);
4485 		detach_mounts(new_dentry);
4486 	}
4487 	if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {
4488 		if (!(flags & RENAME_EXCHANGE))
4489 			d_move(old_dentry, new_dentry);
4490 		else
4491 			d_exchange(old_dentry, new_dentry);
4492 	}
4493 out:
4494 	if (!is_dir || lock_old_subdir)
4495 		inode_unlock(source);
4496 	if (target && (!new_is_dir || lock_new_subdir))
4497 		inode_unlock(target);
4498 	dput(new_dentry);
4499 	if (!error) {
4500 		fsnotify_move(old_dir, new_dir, &old_name.name, is_dir,
4501 			      !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);
4502 		if (flags & RENAME_EXCHANGE) {
4503 			fsnotify_move(new_dir, old_dir, &old_dentry->d_name,
4504 				      new_is_dir, NULL, new_dentry);
4505 		}
4506 	}
4507 	release_dentry_name_snapshot(&old_name);
4508 
4509 	return error;
4510 }
4511 EXPORT_SYMBOL_NS(vfs_rename, ANDROID_GKI_VFS_EXPORT_ONLY);
4512 
do_renameat2(int olddfd,struct filename * from,int newdfd,struct filename * to,unsigned int flags)4513 int do_renameat2(int olddfd, struct filename *from, int newdfd,
4514 		 struct filename *to, unsigned int flags)
4515 {
4516 	struct dentry *old_dentry, *new_dentry;
4517 	struct dentry *trap;
4518 	struct path old_path, new_path;
4519 	struct qstr old_last, new_last;
4520 	int old_type, new_type;
4521 	struct inode *delegated_inode = NULL;
4522 	unsigned int lookup_flags = 0, target_flags = LOOKUP_RENAME_TARGET;
4523 	bool should_retry = false;
4524 	int error = -EINVAL;
4525 
4526 	if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
4527 		goto put_both;
4528 
4529 	if ((flags & (RENAME_NOREPLACE | RENAME_WHITEOUT)) &&
4530 	    (flags & RENAME_EXCHANGE))
4531 		goto put_both;
4532 
4533 	if (flags & RENAME_EXCHANGE)
4534 		target_flags = 0;
4535 
4536 retry:
4537 	from = filename_parentat(olddfd, from, lookup_flags, &old_path,
4538 					&old_last, &old_type);
4539 	if (IS_ERR(from)) {
4540 		error = PTR_ERR(from);
4541 		goto put_new;
4542 	}
4543 
4544 	to = filename_parentat(newdfd, to, lookup_flags, &new_path, &new_last,
4545 				&new_type);
4546 	if (IS_ERR(to)) {
4547 		error = PTR_ERR(to);
4548 		goto exit1;
4549 	}
4550 
4551 	error = -EXDEV;
4552 	if (old_path.mnt != new_path.mnt)
4553 		goto exit2;
4554 
4555 	error = -EBUSY;
4556 	if (old_type != LAST_NORM)
4557 		goto exit2;
4558 
4559 	if (flags & RENAME_NOREPLACE)
4560 		error = -EEXIST;
4561 	if (new_type != LAST_NORM)
4562 		goto exit2;
4563 
4564 	error = mnt_want_write(old_path.mnt);
4565 	if (error)
4566 		goto exit2;
4567 
4568 retry_deleg:
4569 	trap = lock_rename(new_path.dentry, old_path.dentry);
4570 
4571 	old_dentry = __lookup_hash(&old_last, old_path.dentry, lookup_flags);
4572 	error = PTR_ERR(old_dentry);
4573 	if (IS_ERR(old_dentry))
4574 		goto exit3;
4575 	/* source must exist */
4576 	error = -ENOENT;
4577 	if (d_is_negative(old_dentry))
4578 		goto exit4;
4579 	new_dentry = __lookup_hash(&new_last, new_path.dentry, lookup_flags | target_flags);
4580 	error = PTR_ERR(new_dentry);
4581 	if (IS_ERR(new_dentry))
4582 		goto exit4;
4583 	error = -EEXIST;
4584 	if ((flags & RENAME_NOREPLACE) && d_is_positive(new_dentry))
4585 		goto exit5;
4586 	if (flags & RENAME_EXCHANGE) {
4587 		error = -ENOENT;
4588 		if (d_is_negative(new_dentry))
4589 			goto exit5;
4590 
4591 		if (!d_is_dir(new_dentry)) {
4592 			error = -ENOTDIR;
4593 			if (new_last.name[new_last.len])
4594 				goto exit5;
4595 		}
4596 	}
4597 	/* unless the source is a directory trailing slashes give -ENOTDIR */
4598 	if (!d_is_dir(old_dentry)) {
4599 		error = -ENOTDIR;
4600 		if (old_last.name[old_last.len])
4601 			goto exit5;
4602 		if (!(flags & RENAME_EXCHANGE) && new_last.name[new_last.len])
4603 			goto exit5;
4604 	}
4605 	/* source should not be ancestor of target */
4606 	error = -EINVAL;
4607 	if (old_dentry == trap)
4608 		goto exit5;
4609 	/* target should not be an ancestor of source */
4610 	if (!(flags & RENAME_EXCHANGE))
4611 		error = -ENOTEMPTY;
4612 	if (new_dentry == trap)
4613 		goto exit5;
4614 
4615 	error = security_path_rename(&old_path, old_dentry,
4616 				     &new_path, new_dentry, flags);
4617 	if (error)
4618 		goto exit5;
4619 	error = vfs_rename(old_path.dentry->d_inode, old_dentry,
4620 			   new_path.dentry->d_inode, new_dentry,
4621 			   &delegated_inode, flags);
4622 exit5:
4623 	dput(new_dentry);
4624 exit4:
4625 	dput(old_dentry);
4626 exit3:
4627 	unlock_rename(new_path.dentry, old_path.dentry);
4628 	if (delegated_inode) {
4629 		error = break_deleg_wait(&delegated_inode);
4630 		if (!error)
4631 			goto retry_deleg;
4632 	}
4633 	mnt_drop_write(old_path.mnt);
4634 exit2:
4635 	if (retry_estale(error, lookup_flags))
4636 		should_retry = true;
4637 	path_put(&new_path);
4638 exit1:
4639 	path_put(&old_path);
4640 	if (should_retry) {
4641 		should_retry = false;
4642 		lookup_flags |= LOOKUP_REVAL;
4643 		goto retry;
4644 	}
4645 put_both:
4646 	if (!IS_ERR(from))
4647 		putname(from);
4648 put_new:
4649 	if (!IS_ERR(to))
4650 		putname(to);
4651 	return error;
4652 }
4653 
SYSCALL_DEFINE5(renameat2,int,olddfd,const char __user *,oldname,int,newdfd,const char __user *,newname,unsigned int,flags)4654 SYSCALL_DEFINE5(renameat2, int, olddfd, const char __user *, oldname,
4655 		int, newdfd, const char __user *, newname, unsigned int, flags)
4656 {
4657 	return do_renameat2(olddfd, getname(oldname), newdfd, getname(newname),
4658 				flags);
4659 }
4660 
SYSCALL_DEFINE4(renameat,int,olddfd,const char __user *,oldname,int,newdfd,const char __user *,newname)4661 SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname,
4662 		int, newdfd, const char __user *, newname)
4663 {
4664 	return do_renameat2(olddfd, getname(oldname), newdfd, getname(newname),
4665 				0);
4666 }
4667 
SYSCALL_DEFINE2(rename,const char __user *,oldname,const char __user *,newname)4668 SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname)
4669 {
4670 	return do_renameat2(AT_FDCWD, getname(oldname), AT_FDCWD,
4671 				getname(newname), 0);
4672 }
4673 
readlink_copy(char __user * buffer,int buflen,const char * link)4674 int readlink_copy(char __user *buffer, int buflen, const char *link)
4675 {
4676 	int len = PTR_ERR(link);
4677 	if (IS_ERR(link))
4678 		goto out;
4679 
4680 	len = strlen(link);
4681 	if (len > (unsigned) buflen)
4682 		len = buflen;
4683 	if (copy_to_user(buffer, link, len))
4684 		len = -EFAULT;
4685 out:
4686 	return len;
4687 }
4688 
4689 /**
4690  * vfs_readlink - copy symlink body into userspace buffer
4691  * @dentry: dentry on which to get symbolic link
4692  * @buffer: user memory pointer
4693  * @buflen: size of buffer
4694  *
4695  * Does not touch atime.  That's up to the caller if necessary
4696  *
4697  * Does not call security hook.
4698  */
vfs_readlink(struct dentry * dentry,char __user * buffer,int buflen)4699 int vfs_readlink(struct dentry *dentry, char __user *buffer, int buflen)
4700 {
4701 	struct inode *inode = d_inode(dentry);
4702 	DEFINE_DELAYED_CALL(done);
4703 	const char *link;
4704 	int res;
4705 
4706 	if (unlikely(!(inode->i_opflags & IOP_DEFAULT_READLINK))) {
4707 		if (unlikely(inode->i_op->readlink))
4708 			return inode->i_op->readlink(dentry, buffer, buflen);
4709 
4710 		if (!d_is_symlink(dentry))
4711 			return -EINVAL;
4712 
4713 		spin_lock(&inode->i_lock);
4714 		inode->i_opflags |= IOP_DEFAULT_READLINK;
4715 		spin_unlock(&inode->i_lock);
4716 	}
4717 
4718 	link = READ_ONCE(inode->i_link);
4719 	if (!link) {
4720 		link = inode->i_op->get_link(dentry, inode, &done);
4721 		if (IS_ERR(link))
4722 			return PTR_ERR(link);
4723 	}
4724 	res = readlink_copy(buffer, buflen, link);
4725 	do_delayed_call(&done);
4726 	return res;
4727 }
4728 EXPORT_SYMBOL(vfs_readlink);
4729 
4730 /**
4731  * vfs_get_link - get symlink body
4732  * @dentry: dentry on which to get symbolic link
4733  * @done: caller needs to free returned data with this
4734  *
4735  * Calls security hook and i_op->get_link() on the supplied inode.
4736  *
4737  * It does not touch atime.  That's up to the caller if necessary.
4738  *
4739  * Does not work on "special" symlinks like /proc/$$/fd/N
4740  */
vfs_get_link(struct dentry * dentry,struct delayed_call * done)4741 const char *vfs_get_link(struct dentry *dentry, struct delayed_call *done)
4742 {
4743 	const char *res = ERR_PTR(-EINVAL);
4744 	struct inode *inode = d_inode(dentry);
4745 
4746 	if (d_is_symlink(dentry)) {
4747 		res = ERR_PTR(security_inode_readlink(dentry));
4748 		if (!res)
4749 			res = inode->i_op->get_link(dentry, inode, done);
4750 	}
4751 	return res;
4752 }
4753 EXPORT_SYMBOL(vfs_get_link);
4754 
4755 /* get the link contents into pagecache */
page_get_link(struct dentry * dentry,struct inode * inode,struct delayed_call * callback)4756 const char *page_get_link(struct dentry *dentry, struct inode *inode,
4757 			  struct delayed_call *callback)
4758 {
4759 	char *kaddr;
4760 	struct page *page;
4761 	struct address_space *mapping = inode->i_mapping;
4762 
4763 	if (!dentry) {
4764 		page = find_get_page(mapping, 0);
4765 		if (!page)
4766 			return ERR_PTR(-ECHILD);
4767 		if (!PageUptodate(page)) {
4768 			put_page(page);
4769 			return ERR_PTR(-ECHILD);
4770 		}
4771 	} else {
4772 		page = read_mapping_page(mapping, 0, NULL);
4773 		if (IS_ERR(page))
4774 			return (char*)page;
4775 	}
4776 	set_delayed_call(callback, page_put_link, page);
4777 	BUG_ON(mapping_gfp_mask(mapping) & __GFP_HIGHMEM);
4778 	kaddr = page_address(page);
4779 	nd_terminate_link(kaddr, inode->i_size, PAGE_SIZE - 1);
4780 	return kaddr;
4781 }
4782 
4783 EXPORT_SYMBOL(page_get_link);
4784 
page_put_link(void * arg)4785 void page_put_link(void *arg)
4786 {
4787 	put_page(arg);
4788 }
4789 EXPORT_SYMBOL(page_put_link);
4790 
page_readlink(struct dentry * dentry,char __user * buffer,int buflen)4791 int page_readlink(struct dentry *dentry, char __user *buffer, int buflen)
4792 {
4793 	DEFINE_DELAYED_CALL(done);
4794 	int res = readlink_copy(buffer, buflen,
4795 				page_get_link(dentry, d_inode(dentry),
4796 					      &done));
4797 	do_delayed_call(&done);
4798 	return res;
4799 }
4800 EXPORT_SYMBOL(page_readlink);
4801 
4802 /*
4803  * The nofs argument instructs pagecache_write_begin to pass AOP_FLAG_NOFS
4804  */
__page_symlink(struct inode * inode,const char * symname,int len,int nofs)4805 int __page_symlink(struct inode *inode, const char *symname, int len, int nofs)
4806 {
4807 	struct address_space *mapping = inode->i_mapping;
4808 	struct page *page;
4809 	void *fsdata = NULL;
4810 	int err;
4811 	unsigned int flags = 0;
4812 	if (nofs)
4813 		flags |= AOP_FLAG_NOFS;
4814 
4815 retry:
4816 	err = pagecache_write_begin(NULL, mapping, 0, len-1,
4817 				flags, &page, &fsdata);
4818 	if (err)
4819 		goto fail;
4820 
4821 	memcpy(page_address(page), symname, len-1);
4822 
4823 	err = pagecache_write_end(NULL, mapping, 0, len-1, len-1,
4824 							page, fsdata);
4825 	if (err < 0)
4826 		goto fail;
4827 	if (err < len-1)
4828 		goto retry;
4829 
4830 	mark_inode_dirty(inode);
4831 	return 0;
4832 fail:
4833 	return err;
4834 }
4835 EXPORT_SYMBOL(__page_symlink);
4836 
page_symlink(struct inode * inode,const char * symname,int len)4837 int page_symlink(struct inode *inode, const char *symname, int len)
4838 {
4839 	return __page_symlink(inode, symname, len,
4840 			!mapping_gfp_constraint(inode->i_mapping, __GFP_FS));
4841 }
4842 EXPORT_SYMBOL(page_symlink);
4843 
4844 const struct inode_operations page_symlink_inode_operations = {
4845 	.get_link	= page_get_link,
4846 };
4847 EXPORT_SYMBOL(page_symlink_inode_operations);
4848