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