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