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