null_blk: add trace in null_blk_zoned.c
[linux/fpc-iii.git] / fs / namei.c
blobdb6565c998259a12854d2317ce2f8f1d933f0277
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * linux/fs/namei.c
5 * Copyright (C) 1991, 1992 Linus Torvalds
6 */
8 /*
9 * Some corrections by tytso.
12 /* [Feb 1997 T. Schoebel-Theuer] Complete rewrite of the pathname
13 * lookup logic.
15 /* [Feb-Apr 2000, AV] Rewrite to the new namespace architecture.
18 #include <linux/init.h>
19 #include <linux/export.h>
20 #include <linux/kernel.h>
21 #include <linux/slab.h>
22 #include <linux/fs.h>
23 #include <linux/namei.h>
24 #include <linux/pagemap.h>
25 #include <linux/fsnotify.h>
26 #include <linux/personality.h>
27 #include <linux/security.h>
28 #include <linux/ima.h>
29 #include <linux/syscalls.h>
30 #include <linux/mount.h>
31 #include <linux/audit.h>
32 #include <linux/capability.h>
33 #include <linux/file.h>
34 #include <linux/fcntl.h>
35 #include <linux/device_cgroup.h>
36 #include <linux/fs_struct.h>
37 #include <linux/posix_acl.h>
38 #include <linux/hash.h>
39 #include <linux/bitops.h>
40 #include <linux/init_task.h>
41 #include <linux/uaccess.h>
43 #include "internal.h"
44 #include "mount.h"
46 /* [Feb-1997 T. Schoebel-Theuer]
47 * Fundamental changes in the pathname lookup mechanisms (namei)
48 * were necessary because of omirr. The reason is that omirr needs
49 * to know the _real_ pathname, not the user-supplied one, in case
50 * of symlinks (and also when transname replacements occur).
52 * The new code replaces the old recursive symlink resolution with
53 * an iterative one (in case of non-nested symlink chains). It does
54 * this with calls to <fs>_follow_link().
55 * As a side effect, dir_namei(), _namei() and follow_link() are now
56 * replaced with a single function lookup_dentry() that can handle all
57 * the special cases of the former code.
59 * With the new dcache, the pathname is stored at each inode, at least as
60 * long as the refcount of the inode is positive. As a side effect, the
61 * size of the dcache depends on the inode cache and thus is dynamic.
63 * [29-Apr-1998 C. Scott Ananian] Updated above description of symlink
64 * resolution to correspond with current state of the code.
66 * Note that the symlink resolution is not *completely* iterative.
67 * There is still a significant amount of tail- and mid- recursion in
68 * the algorithm. Also, note that <fs>_readlink() is not used in
69 * lookup_dentry(): lookup_dentry() on the result of <fs>_readlink()
70 * may return different results than <fs>_follow_link(). Many virtual
71 * filesystems (including /proc) exhibit this behavior.
74 /* [24-Feb-97 T. Schoebel-Theuer] Side effects caused by new implementation:
75 * New symlink semantics: when open() is called with flags O_CREAT | O_EXCL
76 * and the name already exists in form of a symlink, try to create the new
77 * name indicated by the symlink. The old code always complained that the
78 * name already exists, due to not following the symlink even if its target
79 * is nonexistent. The new semantics affects also mknod() and link() when
80 * the name is a symlink pointing to a non-existent name.
82 * I don't know which semantics is the right one, since I have no access
83 * to standards. But I found by trial that HP-UX 9.0 has the full "new"
84 * semantics implemented, while SunOS 4.1.1 and Solaris (SunOS 5.4) have the
85 * "old" one. Personally, I think the new semantics is much more logical.
86 * Note that "ln old new" where "new" is a symlink pointing to a non-existing
87 * file does succeed in both HP-UX and SunOs, but not in Solaris
88 * and in the old Linux semantics.
91 /* [16-Dec-97 Kevin Buhr] For security reasons, we change some symlink
92 * semantics. See the comments in "open_namei" and "do_link" below.
94 * [10-Sep-98 Alan Modra] Another symlink change.
97 /* [Feb-Apr 2000 AV] Complete rewrite. Rules for symlinks:
98 * inside the path - always follow.
99 * in the last component in creation/removal/renaming - never follow.
100 * if LOOKUP_FOLLOW passed - follow.
101 * if the pathname has trailing slashes - follow.
102 * otherwise - don't follow.
103 * (applied in that order).
105 * [Jun 2000 AV] Inconsistent behaviour of open() in case if flags==O_CREAT
106 * restored for 2.4. This is the last surviving part of old 4.2BSD bug.
107 * During the 2.4 we need to fix the userland stuff depending on it -
108 * hopefully we will be able to get rid of that wart in 2.5. So far only
109 * XEmacs seems to be relying on it...
112 * [Sep 2001 AV] Single-semaphore locking scheme (kudos to David Holland)
113 * implemented. Let's see if raised priority of ->s_vfs_rename_mutex gives
114 * any extra contention...
117 /* In order to reduce some races, while at the same time doing additional
118 * checking and hopefully speeding things up, we copy filenames to the
119 * kernel data space before using them..
121 * POSIX.1 2.4: an empty pathname is invalid (ENOENT).
122 * PATH_MAX includes the nul terminator --RR.
125 #define EMBEDDED_NAME_MAX (PATH_MAX - offsetof(struct filename, iname))
127 struct filename *
128 getname_flags(const char __user *filename, int flags, int *empty)
130 struct filename *result;
131 char *kname;
132 int len;
134 result = audit_reusename(filename);
135 if (result)
136 return result;
138 result = __getname();
139 if (unlikely(!result))
140 return ERR_PTR(-ENOMEM);
143 * First, try to embed the struct filename inside the names_cache
144 * allocation
146 kname = (char *)result->iname;
147 result->name = kname;
149 len = strncpy_from_user(kname, filename, EMBEDDED_NAME_MAX);
150 if (unlikely(len < 0)) {
151 __putname(result);
152 return ERR_PTR(len);
156 * Uh-oh. We have a name that's approaching PATH_MAX. Allocate a
157 * separate struct filename so we can dedicate the entire
158 * names_cache allocation for the pathname, and re-do the copy from
159 * userland.
161 if (unlikely(len == EMBEDDED_NAME_MAX)) {
162 const size_t size = offsetof(struct filename, iname[1]);
163 kname = (char *)result;
166 * size is chosen that way we to guarantee that
167 * result->iname[0] is within the same object and that
168 * kname can't be equal to result->iname, no matter what.
170 result = kzalloc(size, GFP_KERNEL);
171 if (unlikely(!result)) {
172 __putname(kname);
173 return ERR_PTR(-ENOMEM);
175 result->name = kname;
176 len = strncpy_from_user(kname, filename, PATH_MAX);
177 if (unlikely(len < 0)) {
178 __putname(kname);
179 kfree(result);
180 return ERR_PTR(len);
182 if (unlikely(len == PATH_MAX)) {
183 __putname(kname);
184 kfree(result);
185 return ERR_PTR(-ENAMETOOLONG);
189 result->refcnt = 1;
190 /* The empty path is special. */
191 if (unlikely(!len)) {
192 if (empty)
193 *empty = 1;
194 if (!(flags & LOOKUP_EMPTY)) {
195 putname(result);
196 return ERR_PTR(-ENOENT);
200 result->uptr = filename;
201 result->aname = NULL;
202 audit_getname(result);
203 return result;
206 struct filename *
207 getname(const char __user * filename)
209 return getname_flags(filename, 0, NULL);
212 struct filename *
213 getname_kernel(const char * filename)
215 struct filename *result;
216 int len = strlen(filename) + 1;
218 result = __getname();
219 if (unlikely(!result))
220 return ERR_PTR(-ENOMEM);
222 if (len <= EMBEDDED_NAME_MAX) {
223 result->name = (char *)result->iname;
224 } else if (len <= PATH_MAX) {
225 const size_t size = offsetof(struct filename, iname[1]);
226 struct filename *tmp;
228 tmp = kmalloc(size, GFP_KERNEL);
229 if (unlikely(!tmp)) {
230 __putname(result);
231 return ERR_PTR(-ENOMEM);
233 tmp->name = (char *)result;
234 result = tmp;
235 } else {
236 __putname(result);
237 return ERR_PTR(-ENAMETOOLONG);
239 memcpy((char *)result->name, filename, len);
240 result->uptr = NULL;
241 result->aname = NULL;
242 result->refcnt = 1;
243 audit_getname(result);
245 return result;
248 void putname(struct filename *name)
250 BUG_ON(name->refcnt <= 0);
252 if (--name->refcnt > 0)
253 return;
255 if (name->name != name->iname) {
256 __putname(name->name);
257 kfree(name);
258 } else
259 __putname(name);
262 static int check_acl(struct inode *inode, int mask)
264 #ifdef CONFIG_FS_POSIX_ACL
265 struct posix_acl *acl;
267 if (mask & MAY_NOT_BLOCK) {
268 acl = get_cached_acl_rcu(inode, ACL_TYPE_ACCESS);
269 if (!acl)
270 return -EAGAIN;
271 /* no ->get_acl() calls in RCU mode... */
272 if (is_uncached_acl(acl))
273 return -ECHILD;
274 return posix_acl_permission(inode, acl, mask & ~MAY_NOT_BLOCK);
277 acl = get_acl(inode, ACL_TYPE_ACCESS);
278 if (IS_ERR(acl))
279 return PTR_ERR(acl);
280 if (acl) {
281 int error = posix_acl_permission(inode, acl, mask);
282 posix_acl_release(acl);
283 return error;
285 #endif
287 return -EAGAIN;
291 * This does the basic permission checking
293 static int acl_permission_check(struct inode *inode, int mask)
295 unsigned int mode = inode->i_mode;
297 if (likely(uid_eq(current_fsuid(), inode->i_uid)))
298 mode >>= 6;
299 else {
300 if (IS_POSIXACL(inode) && (mode & S_IRWXG)) {
301 int error = check_acl(inode, mask);
302 if (error != -EAGAIN)
303 return error;
306 if (in_group_p(inode->i_gid))
307 mode >>= 3;
311 * If the DACs are ok we don't need any capability check.
313 if ((mask & ~mode & (MAY_READ | MAY_WRITE | MAY_EXEC)) == 0)
314 return 0;
315 return -EACCES;
319 * generic_permission - check for access rights on a Posix-like filesystem
320 * @inode: inode to check access rights for
321 * @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC, ...)
323 * Used to check for read/write/execute permissions on a file.
324 * We use "fsuid" for this, letting us set arbitrary permissions
325 * for filesystem access without changing the "normal" uids which
326 * are used for other things.
328 * generic_permission is rcu-walk aware. It returns -ECHILD in case an rcu-walk
329 * request cannot be satisfied (eg. requires blocking or too much complexity).
330 * It would then be called again in ref-walk mode.
332 int generic_permission(struct inode *inode, int mask)
334 int ret;
337 * Do the basic permission checks.
339 ret = acl_permission_check(inode, mask);
340 if (ret != -EACCES)
341 return ret;
343 if (S_ISDIR(inode->i_mode)) {
344 /* DACs are overridable for directories */
345 if (!(mask & MAY_WRITE))
346 if (capable_wrt_inode_uidgid(inode,
347 CAP_DAC_READ_SEARCH))
348 return 0;
349 if (capable_wrt_inode_uidgid(inode, CAP_DAC_OVERRIDE))
350 return 0;
351 return -EACCES;
355 * Searching includes executable on directories, else just read.
357 mask &= MAY_READ | MAY_WRITE | MAY_EXEC;
358 if (mask == MAY_READ)
359 if (capable_wrt_inode_uidgid(inode, CAP_DAC_READ_SEARCH))
360 return 0;
362 * Read/write DACs are always overridable.
363 * Executable DACs are overridable when there is
364 * at least one exec bit set.
366 if (!(mask & MAY_EXEC) || (inode->i_mode & S_IXUGO))
367 if (capable_wrt_inode_uidgid(inode, CAP_DAC_OVERRIDE))
368 return 0;
370 return -EACCES;
372 EXPORT_SYMBOL(generic_permission);
375 * We _really_ want to just do "generic_permission()" without
376 * even looking at the inode->i_op values. So we keep a cache
377 * flag in inode->i_opflags, that says "this has not special
378 * permission function, use the fast case".
380 static inline int do_inode_permission(struct inode *inode, int mask)
382 if (unlikely(!(inode->i_opflags & IOP_FASTPERM))) {
383 if (likely(inode->i_op->permission))
384 return inode->i_op->permission(inode, mask);
386 /* This gets set once for the inode lifetime */
387 spin_lock(&inode->i_lock);
388 inode->i_opflags |= IOP_FASTPERM;
389 spin_unlock(&inode->i_lock);
391 return generic_permission(inode, mask);
395 * sb_permission - Check superblock-level permissions
396 * @sb: Superblock of inode to check permission on
397 * @inode: Inode to check permission on
398 * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
400 * Separate out file-system wide checks from inode-specific permission checks.
402 static int sb_permission(struct super_block *sb, struct inode *inode, int mask)
404 if (unlikely(mask & MAY_WRITE)) {
405 umode_t mode = inode->i_mode;
407 /* Nobody gets write access to a read-only fs. */
408 if (sb_rdonly(sb) && (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode)))
409 return -EROFS;
411 return 0;
415 * inode_permission - Check for access rights to a given inode
416 * @inode: Inode to check permission on
417 * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
419 * Check for read/write/execute permissions on an inode. We use fs[ug]id for
420 * this, letting us set arbitrary permissions for filesystem access without
421 * changing the "normal" UIDs which are used for other things.
423 * When checking for MAY_APPEND, MAY_WRITE must also be set in @mask.
425 int inode_permission(struct inode *inode, int mask)
427 int retval;
429 retval = sb_permission(inode->i_sb, inode, mask);
430 if (retval)
431 return retval;
433 if (unlikely(mask & MAY_WRITE)) {
435 * Nobody gets write access to an immutable file.
437 if (IS_IMMUTABLE(inode))
438 return -EPERM;
441 * Updating mtime will likely cause i_uid and i_gid to be
442 * written back improperly if their true value is unknown
443 * to the vfs.
445 if (HAS_UNMAPPED_ID(inode))
446 return -EACCES;
449 retval = do_inode_permission(inode, mask);
450 if (retval)
451 return retval;
453 retval = devcgroup_inode_permission(inode, mask);
454 if (retval)
455 return retval;
457 return security_inode_permission(inode, mask);
459 EXPORT_SYMBOL(inode_permission);
462 * path_get - get a reference to a path
463 * @path: path to get the reference to
465 * Given a path increment the reference count to the dentry and the vfsmount.
467 void path_get(const struct path *path)
469 mntget(path->mnt);
470 dget(path->dentry);
472 EXPORT_SYMBOL(path_get);
475 * path_put - put a reference to a path
476 * @path: path to put the reference to
478 * Given a path decrement the reference count to the dentry and the vfsmount.
480 void path_put(const struct path *path)
482 dput(path->dentry);
483 mntput(path->mnt);
485 EXPORT_SYMBOL(path_put);
487 #define EMBEDDED_LEVELS 2
488 struct nameidata {
489 struct path path;
490 struct qstr last;
491 struct path root;
492 struct inode *inode; /* path.dentry.d_inode */
493 unsigned int flags;
494 unsigned seq, m_seq, r_seq;
495 int last_type;
496 unsigned depth;
497 int total_link_count;
498 struct saved {
499 struct path link;
500 struct delayed_call done;
501 const char *name;
502 unsigned seq;
503 } *stack, internal[EMBEDDED_LEVELS];
504 struct filename *name;
505 struct nameidata *saved;
506 struct inode *link_inode;
507 unsigned root_seq;
508 int dfd;
509 } __randomize_layout;
511 static void set_nameidata(struct nameidata *p, int dfd, struct filename *name)
513 struct nameidata *old = current->nameidata;
514 p->stack = p->internal;
515 p->dfd = dfd;
516 p->name = name;
517 p->total_link_count = old ? old->total_link_count : 0;
518 p->saved = old;
519 current->nameidata = p;
522 static void restore_nameidata(void)
524 struct nameidata *now = current->nameidata, *old = now->saved;
526 current->nameidata = old;
527 if (old)
528 old->total_link_count = now->total_link_count;
529 if (now->stack != now->internal)
530 kfree(now->stack);
533 static int __nd_alloc_stack(struct nameidata *nd)
535 struct saved *p;
537 if (nd->flags & LOOKUP_RCU) {
538 p= kmalloc_array(MAXSYMLINKS, sizeof(struct saved),
539 GFP_ATOMIC);
540 if (unlikely(!p))
541 return -ECHILD;
542 } else {
543 p= kmalloc_array(MAXSYMLINKS, sizeof(struct saved),
544 GFP_KERNEL);
545 if (unlikely(!p))
546 return -ENOMEM;
548 memcpy(p, nd->internal, sizeof(nd->internal));
549 nd->stack = p;
550 return 0;
554 * path_connected - Verify that a path->dentry is below path->mnt.mnt_root
555 * @path: nameidate to verify
557 * Rename can sometimes move a file or directory outside of a bind
558 * mount, path_connected allows those cases to be detected.
560 static bool path_connected(const struct path *path)
562 struct vfsmount *mnt = path->mnt;
563 struct super_block *sb = mnt->mnt_sb;
565 /* Bind mounts and multi-root filesystems can have disconnected paths */
566 if (!(sb->s_iflags & SB_I_MULTIROOT) && (mnt->mnt_root == sb->s_root))
567 return true;
569 return is_subdir(path->dentry, mnt->mnt_root);
572 static inline int nd_alloc_stack(struct nameidata *nd)
574 if (likely(nd->depth != EMBEDDED_LEVELS))
575 return 0;
576 if (likely(nd->stack != nd->internal))
577 return 0;
578 return __nd_alloc_stack(nd);
581 static void drop_links(struct nameidata *nd)
583 int i = nd->depth;
584 while (i--) {
585 struct saved *last = nd->stack + i;
586 do_delayed_call(&last->done);
587 clear_delayed_call(&last->done);
591 static void terminate_walk(struct nameidata *nd)
593 drop_links(nd);
594 if (!(nd->flags & LOOKUP_RCU)) {
595 int i;
596 path_put(&nd->path);
597 for (i = 0; i < nd->depth; i++)
598 path_put(&nd->stack[i].link);
599 if (nd->flags & LOOKUP_ROOT_GRABBED) {
600 path_put(&nd->root);
601 nd->flags &= ~LOOKUP_ROOT_GRABBED;
603 } else {
604 nd->flags &= ~LOOKUP_RCU;
605 rcu_read_unlock();
607 nd->depth = 0;
610 /* path_put is needed afterwards regardless of success or failure */
611 static bool legitimize_path(struct nameidata *nd,
612 struct path *path, unsigned seq)
614 int res = __legitimize_mnt(path->mnt, nd->m_seq);
615 if (unlikely(res)) {
616 if (res > 0)
617 path->mnt = NULL;
618 path->dentry = NULL;
619 return false;
621 if (unlikely(!lockref_get_not_dead(&path->dentry->d_lockref))) {
622 path->dentry = NULL;
623 return false;
625 return !read_seqcount_retry(&path->dentry->d_seq, seq);
628 static bool legitimize_links(struct nameidata *nd)
630 int i;
631 for (i = 0; i < nd->depth; i++) {
632 struct saved *last = nd->stack + i;
633 if (unlikely(!legitimize_path(nd, &last->link, last->seq))) {
634 drop_links(nd);
635 nd->depth = i + 1;
636 return false;
639 return true;
642 static bool legitimize_root(struct nameidata *nd)
645 * For scoped-lookups (where nd->root has been zeroed), we need to
646 * restart the whole lookup from scratch -- because set_root() is wrong
647 * for these lookups (nd->dfd is the root, not the filesystem root).
649 if (!nd->root.mnt && (nd->flags & LOOKUP_IS_SCOPED))
650 return false;
651 /* Nothing to do if nd->root is zero or is managed by the VFS user. */
652 if (!nd->root.mnt || (nd->flags & LOOKUP_ROOT))
653 return true;
654 nd->flags |= LOOKUP_ROOT_GRABBED;
655 return legitimize_path(nd, &nd->root, nd->root_seq);
659 * Path walking has 2 modes, rcu-walk and ref-walk (see
660 * Documentation/filesystems/path-lookup.txt). In situations when we can't
661 * continue in RCU mode, we attempt to drop out of rcu-walk mode and grab
662 * normal reference counts on dentries and vfsmounts to transition to ref-walk
663 * mode. Refcounts are grabbed at the last known good point before rcu-walk
664 * got stuck, so ref-walk may continue from there. If this is not successful
665 * (eg. a seqcount has changed), then failure is returned and it's up to caller
666 * to restart the path walk from the beginning in ref-walk mode.
670 * unlazy_walk - try to switch to ref-walk mode.
671 * @nd: nameidata pathwalk data
672 * Returns: 0 on success, -ECHILD on failure
674 * unlazy_walk attempts to legitimize the current nd->path and nd->root
675 * for ref-walk mode.
676 * Must be called from rcu-walk context.
677 * Nothing should touch nameidata between unlazy_walk() failure and
678 * terminate_walk().
680 static int unlazy_walk(struct nameidata *nd)
682 struct dentry *parent = nd->path.dentry;
684 BUG_ON(!(nd->flags & LOOKUP_RCU));
686 nd->flags &= ~LOOKUP_RCU;
687 if (unlikely(!legitimize_links(nd)))
688 goto out1;
689 if (unlikely(!legitimize_path(nd, &nd->path, nd->seq)))
690 goto out;
691 if (unlikely(!legitimize_root(nd)))
692 goto out;
693 rcu_read_unlock();
694 BUG_ON(nd->inode != parent->d_inode);
695 return 0;
697 out1:
698 nd->path.mnt = NULL;
699 nd->path.dentry = NULL;
700 out:
701 rcu_read_unlock();
702 return -ECHILD;
706 * unlazy_child - try to switch to ref-walk mode.
707 * @nd: nameidata pathwalk data
708 * @dentry: child of nd->path.dentry
709 * @seq: seq number to check dentry against
710 * Returns: 0 on success, -ECHILD on failure
712 * unlazy_child attempts to legitimize the current nd->path, nd->root and dentry
713 * for ref-walk mode. @dentry must be a path found by a do_lookup call on
714 * @nd. Must be called from rcu-walk context.
715 * Nothing should touch nameidata between unlazy_child() failure and
716 * terminate_walk().
718 static int unlazy_child(struct nameidata *nd, struct dentry *dentry, unsigned seq)
720 BUG_ON(!(nd->flags & LOOKUP_RCU));
722 nd->flags &= ~LOOKUP_RCU;
723 if (unlikely(!legitimize_links(nd)))
724 goto out2;
725 if (unlikely(!legitimize_mnt(nd->path.mnt, nd->m_seq)))
726 goto out2;
727 if (unlikely(!lockref_get_not_dead(&nd->path.dentry->d_lockref)))
728 goto out1;
731 * We need to move both the parent and the dentry from the RCU domain
732 * to be properly refcounted. And the sequence number in the dentry
733 * validates *both* dentry counters, since we checked the sequence
734 * number of the parent after we got the child sequence number. So we
735 * know the parent must still be valid if the child sequence number is
737 if (unlikely(!lockref_get_not_dead(&dentry->d_lockref)))
738 goto out;
739 if (unlikely(read_seqcount_retry(&dentry->d_seq, seq)))
740 goto out_dput;
742 * Sequence counts matched. Now make sure that the root is
743 * still valid and get it if required.
745 if (unlikely(!legitimize_root(nd)))
746 goto out_dput;
747 rcu_read_unlock();
748 return 0;
750 out2:
751 nd->path.mnt = NULL;
752 out1:
753 nd->path.dentry = NULL;
754 out:
755 rcu_read_unlock();
756 return -ECHILD;
757 out_dput:
758 rcu_read_unlock();
759 dput(dentry);
760 return -ECHILD;
763 static inline int d_revalidate(struct dentry *dentry, unsigned int flags)
765 if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE))
766 return dentry->d_op->d_revalidate(dentry, flags);
767 else
768 return 1;
772 * complete_walk - successful completion of path walk
773 * @nd: pointer nameidata
775 * If we had been in RCU mode, drop out of it and legitimize nd->path.
776 * Revalidate the final result, unless we'd already done that during
777 * the path walk or the filesystem doesn't ask for it. Return 0 on
778 * success, -error on failure. In case of failure caller does not
779 * need to drop nd->path.
781 static int complete_walk(struct nameidata *nd)
783 struct dentry *dentry = nd->path.dentry;
784 int status;
786 if (nd->flags & LOOKUP_RCU) {
788 * We don't want to zero nd->root for scoped-lookups or
789 * externally-managed nd->root.
791 if (!(nd->flags & (LOOKUP_ROOT | LOOKUP_IS_SCOPED)))
792 nd->root.mnt = NULL;
793 if (unlikely(unlazy_walk(nd)))
794 return -ECHILD;
797 if (unlikely(nd->flags & LOOKUP_IS_SCOPED)) {
799 * While the guarantee of LOOKUP_IS_SCOPED is (roughly) "don't
800 * ever step outside the root during lookup" and should already
801 * be guaranteed by the rest of namei, we want to avoid a namei
802 * BUG resulting in userspace being given a path that was not
803 * scoped within the root at some point during the lookup.
805 * So, do a final sanity-check to make sure that in the
806 * worst-case scenario (a complete bypass of LOOKUP_IS_SCOPED)
807 * we won't silently return an fd completely outside of the
808 * requested root to userspace.
810 * Userspace could move the path outside the root after this
811 * check, but as discussed elsewhere this is not a concern (the
812 * resolved file was inside the root at some point).
814 if (!path_is_under(&nd->path, &nd->root))
815 return -EXDEV;
818 if (likely(!(nd->flags & LOOKUP_JUMPED)))
819 return 0;
821 if (likely(!(dentry->d_flags & DCACHE_OP_WEAK_REVALIDATE)))
822 return 0;
824 status = dentry->d_op->d_weak_revalidate(dentry, nd->flags);
825 if (status > 0)
826 return 0;
828 if (!status)
829 status = -ESTALE;
831 return status;
834 static int set_root(struct nameidata *nd)
836 struct fs_struct *fs = current->fs;
839 * Jumping to the real root in a scoped-lookup is a BUG in namei, but we
840 * still have to ensure it doesn't happen because it will cause a breakout
841 * from the dirfd.
843 if (WARN_ON(nd->flags & LOOKUP_IS_SCOPED))
844 return -ENOTRECOVERABLE;
846 if (nd->flags & LOOKUP_RCU) {
847 unsigned seq;
849 do {
850 seq = read_seqcount_begin(&fs->seq);
851 nd->root = fs->root;
852 nd->root_seq = __read_seqcount_begin(&nd->root.dentry->d_seq);
853 } while (read_seqcount_retry(&fs->seq, seq));
854 } else {
855 get_fs_root(fs, &nd->root);
856 nd->flags |= LOOKUP_ROOT_GRABBED;
858 return 0;
861 static void path_put_conditional(struct path *path, struct nameidata *nd)
863 dput(path->dentry);
864 if (path->mnt != nd->path.mnt)
865 mntput(path->mnt);
868 static inline void path_to_nameidata(const struct path *path,
869 struct nameidata *nd)
871 if (!(nd->flags & LOOKUP_RCU)) {
872 dput(nd->path.dentry);
873 if (nd->path.mnt != path->mnt)
874 mntput(nd->path.mnt);
876 nd->path.mnt = path->mnt;
877 nd->path.dentry = path->dentry;
880 static int nd_jump_root(struct nameidata *nd)
882 if (unlikely(nd->flags & LOOKUP_BENEATH))
883 return -EXDEV;
884 if (unlikely(nd->flags & LOOKUP_NO_XDEV)) {
885 /* Absolute path arguments to path_init() are allowed. */
886 if (nd->path.mnt != NULL && nd->path.mnt != nd->root.mnt)
887 return -EXDEV;
889 if (!nd->root.mnt) {
890 int error = set_root(nd);
891 if (error)
892 return error;
894 if (nd->flags & LOOKUP_RCU) {
895 struct dentry *d;
896 nd->path = nd->root;
897 d = nd->path.dentry;
898 nd->inode = d->d_inode;
899 nd->seq = nd->root_seq;
900 if (unlikely(read_seqcount_retry(&d->d_seq, nd->seq)))
901 return -ECHILD;
902 } else {
903 path_put(&nd->path);
904 nd->path = nd->root;
905 path_get(&nd->path);
906 nd->inode = nd->path.dentry->d_inode;
908 nd->flags |= LOOKUP_JUMPED;
909 return 0;
913 * Helper to directly jump to a known parsed path from ->get_link,
914 * caller must have taken a reference to path beforehand.
916 int nd_jump_link(struct path *path)
918 int error = -ELOOP;
919 struct nameidata *nd = current->nameidata;
921 if (unlikely(nd->flags & LOOKUP_NO_MAGICLINKS))
922 goto err;
924 error = -EXDEV;
925 if (unlikely(nd->flags & LOOKUP_NO_XDEV)) {
926 if (nd->path.mnt != path->mnt)
927 goto err;
929 /* Not currently safe for scoped-lookups. */
930 if (unlikely(nd->flags & LOOKUP_IS_SCOPED))
931 goto err;
933 path_put(&nd->path);
934 nd->path = *path;
935 nd->inode = nd->path.dentry->d_inode;
936 nd->flags |= LOOKUP_JUMPED;
937 return 0;
939 err:
940 path_put(path);
941 return error;
944 static inline void put_link(struct nameidata *nd)
946 struct saved *last = nd->stack + --nd->depth;
947 do_delayed_call(&last->done);
948 if (!(nd->flags & LOOKUP_RCU))
949 path_put(&last->link);
952 int sysctl_protected_symlinks __read_mostly = 0;
953 int sysctl_protected_hardlinks __read_mostly = 0;
954 int sysctl_protected_fifos __read_mostly;
955 int sysctl_protected_regular __read_mostly;
958 * may_follow_link - Check symlink following for unsafe situations
959 * @nd: nameidata pathwalk data
961 * In the case of the sysctl_protected_symlinks sysctl being enabled,
962 * CAP_DAC_OVERRIDE needs to be specifically ignored if the symlink is
963 * in a sticky world-writable directory. This is to protect privileged
964 * processes from failing races against path names that may change out
965 * from under them by way of other users creating malicious symlinks.
966 * It will permit symlinks to be followed only when outside a sticky
967 * world-writable directory, or when the uid of the symlink and follower
968 * match, or when the directory owner matches the symlink's owner.
970 * Returns 0 if following the symlink is allowed, -ve on error.
972 static inline int may_follow_link(struct nameidata *nd)
974 const struct inode *inode;
975 const struct inode *parent;
976 kuid_t puid;
978 if (!sysctl_protected_symlinks)
979 return 0;
981 /* Allowed if owner and follower match. */
982 inode = nd->link_inode;
983 if (uid_eq(current_cred()->fsuid, inode->i_uid))
984 return 0;
986 /* Allowed if parent directory not sticky and world-writable. */
987 parent = nd->inode;
988 if ((parent->i_mode & (S_ISVTX|S_IWOTH)) != (S_ISVTX|S_IWOTH))
989 return 0;
991 /* Allowed if parent directory and link owner match. */
992 puid = parent->i_uid;
993 if (uid_valid(puid) && uid_eq(puid, inode->i_uid))
994 return 0;
996 if (nd->flags & LOOKUP_RCU)
997 return -ECHILD;
999 audit_inode(nd->name, nd->stack[0].link.dentry, 0);
1000 audit_log_path_denied(AUDIT_ANOM_LINK, "follow_link");
1001 return -EACCES;
1005 * safe_hardlink_source - Check for safe hardlink conditions
1006 * @inode: the source inode to hardlink from
1008 * Return false if at least one of the following conditions:
1009 * - inode is not a regular file
1010 * - inode is setuid
1011 * - inode is setgid and group-exec
1012 * - access failure for read and write
1014 * Otherwise returns true.
1016 static bool safe_hardlink_source(struct inode *inode)
1018 umode_t mode = inode->i_mode;
1020 /* Special files should not get pinned to the filesystem. */
1021 if (!S_ISREG(mode))
1022 return false;
1024 /* Setuid files should not get pinned to the filesystem. */
1025 if (mode & S_ISUID)
1026 return false;
1028 /* Executable setgid files should not get pinned to the filesystem. */
1029 if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP))
1030 return false;
1032 /* Hardlinking to unreadable or unwritable sources is dangerous. */
1033 if (inode_permission(inode, MAY_READ | MAY_WRITE))
1034 return false;
1036 return true;
1040 * may_linkat - Check permissions for creating a hardlink
1041 * @link: the source to hardlink from
1043 * Block hardlink when all of:
1044 * - sysctl_protected_hardlinks enabled
1045 * - fsuid does not match inode
1046 * - hardlink source is unsafe (see safe_hardlink_source() above)
1047 * - not CAP_FOWNER in a namespace with the inode owner uid mapped
1049 * Returns 0 if successful, -ve on error.
1051 static int may_linkat(struct path *link)
1053 struct inode *inode = link->dentry->d_inode;
1055 /* Inode writeback is not safe when the uid or gid are invalid. */
1056 if (!uid_valid(inode->i_uid) || !gid_valid(inode->i_gid))
1057 return -EOVERFLOW;
1059 if (!sysctl_protected_hardlinks)
1060 return 0;
1062 /* Source inode owner (or CAP_FOWNER) can hardlink all they like,
1063 * otherwise, it must be a safe source.
1065 if (safe_hardlink_source(inode) || inode_owner_or_capable(inode))
1066 return 0;
1068 audit_log_path_denied(AUDIT_ANOM_LINK, "linkat");
1069 return -EPERM;
1073 * may_create_in_sticky - Check whether an O_CREAT open in a sticky directory
1074 * should be allowed, or not, on files that already
1075 * exist.
1076 * @dir_mode: mode bits of directory
1077 * @dir_uid: owner of directory
1078 * @inode: the inode of the file to open
1080 * Block an O_CREAT open of a FIFO (or a regular file) when:
1081 * - sysctl_protected_fifos (or sysctl_protected_regular) is enabled
1082 * - the file already exists
1083 * - we are in a sticky directory
1084 * - we don't own the file
1085 * - the owner of the directory doesn't own the file
1086 * - the directory is world writable
1087 * If the sysctl_protected_fifos (or sysctl_protected_regular) is set to 2
1088 * the directory doesn't have to be world writable: being group writable will
1089 * be enough.
1091 * Returns 0 if the open is allowed, -ve on error.
1093 static int may_create_in_sticky(umode_t dir_mode, kuid_t dir_uid,
1094 struct inode * const inode)
1096 if ((!sysctl_protected_fifos && S_ISFIFO(inode->i_mode)) ||
1097 (!sysctl_protected_regular && S_ISREG(inode->i_mode)) ||
1098 likely(!(dir_mode & S_ISVTX)) ||
1099 uid_eq(inode->i_uid, dir_uid) ||
1100 uid_eq(current_fsuid(), inode->i_uid))
1101 return 0;
1103 if (likely(dir_mode & 0002) ||
1104 (dir_mode & 0020 &&
1105 ((sysctl_protected_fifos >= 2 && S_ISFIFO(inode->i_mode)) ||
1106 (sysctl_protected_regular >= 2 && S_ISREG(inode->i_mode))))) {
1107 const char *operation = S_ISFIFO(inode->i_mode) ?
1108 "sticky_create_fifo" :
1109 "sticky_create_regular";
1110 audit_log_path_denied(AUDIT_ANOM_CREAT, operation);
1111 return -EACCES;
1113 return 0;
1116 static __always_inline
1117 const char *get_link(struct nameidata *nd)
1119 struct saved *last = nd->stack + nd->depth - 1;
1120 struct dentry *dentry = last->link.dentry;
1121 struct inode *inode = nd->link_inode;
1122 int error;
1123 const char *res;
1125 if (unlikely(nd->flags & LOOKUP_NO_SYMLINKS))
1126 return ERR_PTR(-ELOOP);
1128 if (!(nd->flags & LOOKUP_RCU)) {
1129 touch_atime(&last->link);
1130 cond_resched();
1131 } else if (atime_needs_update(&last->link, inode)) {
1132 if (unlikely(unlazy_walk(nd)))
1133 return ERR_PTR(-ECHILD);
1134 touch_atime(&last->link);
1137 error = security_inode_follow_link(dentry, inode,
1138 nd->flags & LOOKUP_RCU);
1139 if (unlikely(error))
1140 return ERR_PTR(error);
1142 nd->last_type = LAST_BIND;
1143 res = READ_ONCE(inode->i_link);
1144 if (!res) {
1145 const char * (*get)(struct dentry *, struct inode *,
1146 struct delayed_call *);
1147 get = inode->i_op->get_link;
1148 if (nd->flags & LOOKUP_RCU) {
1149 res = get(NULL, inode, &last->done);
1150 if (res == ERR_PTR(-ECHILD)) {
1151 if (unlikely(unlazy_walk(nd)))
1152 return ERR_PTR(-ECHILD);
1153 res = get(dentry, inode, &last->done);
1155 } else {
1156 res = get(dentry, inode, &last->done);
1158 if (IS_ERR_OR_NULL(res))
1159 return res;
1161 if (*res == '/') {
1162 error = nd_jump_root(nd);
1163 if (unlikely(error))
1164 return ERR_PTR(error);
1165 while (unlikely(*++res == '/'))
1168 if (!*res)
1169 res = NULL;
1170 return res;
1174 * follow_up - Find the mountpoint of path's vfsmount
1176 * Given a path, find the mountpoint of its source file system.
1177 * Replace @path with the path of the mountpoint in the parent mount.
1178 * Up is towards /.
1180 * Return 1 if we went up a level and 0 if we were already at the
1181 * root.
1183 int follow_up(struct path *path)
1185 struct mount *mnt = real_mount(path->mnt);
1186 struct mount *parent;
1187 struct dentry *mountpoint;
1189 read_seqlock_excl(&mount_lock);
1190 parent = mnt->mnt_parent;
1191 if (parent == mnt) {
1192 read_sequnlock_excl(&mount_lock);
1193 return 0;
1195 mntget(&parent->mnt);
1196 mountpoint = dget(mnt->mnt_mountpoint);
1197 read_sequnlock_excl(&mount_lock);
1198 dput(path->dentry);
1199 path->dentry = mountpoint;
1200 mntput(path->mnt);
1201 path->mnt = &parent->mnt;
1202 return 1;
1204 EXPORT_SYMBOL(follow_up);
1207 * Perform an automount
1208 * - return -EISDIR to tell follow_managed() to stop and return the path we
1209 * were called with.
1211 static int follow_automount(struct path *path, struct nameidata *nd,
1212 bool *need_mntput)
1214 struct vfsmount *mnt;
1215 int err;
1217 if (!path->dentry->d_op || !path->dentry->d_op->d_automount)
1218 return -EREMOTE;
1220 /* We don't want to mount if someone's just doing a stat -
1221 * unless they're stat'ing a directory and appended a '/' to
1222 * the name.
1224 * We do, however, want to mount if someone wants to open or
1225 * create a file of any type under the mountpoint, wants to
1226 * traverse through the mountpoint or wants to open the
1227 * mounted directory. Also, autofs may mark negative dentries
1228 * as being automount points. These will need the attentions
1229 * of the daemon to instantiate them before they can be used.
1231 if (!(nd->flags & (LOOKUP_PARENT | LOOKUP_DIRECTORY |
1232 LOOKUP_OPEN | LOOKUP_CREATE | LOOKUP_AUTOMOUNT)) &&
1233 path->dentry->d_inode)
1234 return -EISDIR;
1236 nd->total_link_count++;
1237 if (nd->total_link_count >= 40)
1238 return -ELOOP;
1240 mnt = path->dentry->d_op->d_automount(path);
1241 if (IS_ERR(mnt)) {
1243 * The filesystem is allowed to return -EISDIR here to indicate
1244 * it doesn't want to automount. For instance, autofs would do
1245 * this so that its userspace daemon can mount on this dentry.
1247 * However, we can only permit this if it's a terminal point in
1248 * the path being looked up; if it wasn't then the remainder of
1249 * the path is inaccessible and we should say so.
1251 if (PTR_ERR(mnt) == -EISDIR && (nd->flags & LOOKUP_PARENT))
1252 return -EREMOTE;
1253 return PTR_ERR(mnt);
1256 if (!mnt) /* mount collision */
1257 return 0;
1259 if (!*need_mntput) {
1260 /* lock_mount() may release path->mnt on error */
1261 mntget(path->mnt);
1262 *need_mntput = true;
1264 err = finish_automount(mnt, path);
1266 switch (err) {
1267 case -EBUSY:
1268 /* Someone else made a mount here whilst we were busy */
1269 return 0;
1270 case 0:
1271 path_put(path);
1272 path->mnt = mnt;
1273 path->dentry = dget(mnt->mnt_root);
1274 return 0;
1275 default:
1276 return err;
1282 * Handle a dentry that is managed in some way.
1283 * - Flagged for transit management (autofs)
1284 * - Flagged as mountpoint
1285 * - Flagged as automount point
1287 * This may only be called in refwalk mode.
1288 * On success path->dentry is known positive.
1290 * Serialization is taken care of in namespace.c
1292 static int follow_managed(struct path *path, struct nameidata *nd)
1294 struct vfsmount *mnt = path->mnt; /* held by caller, must be left alone */
1295 unsigned flags;
1296 bool need_mntput = false;
1297 int ret = 0;
1299 /* Given that we're not holding a lock here, we retain the value in a
1300 * local variable for each dentry as we look at it so that we don't see
1301 * the components of that value change under us */
1302 while (flags = smp_load_acquire(&path->dentry->d_flags),
1303 unlikely(flags & DCACHE_MANAGED_DENTRY)) {
1304 /* Allow the filesystem to manage the transit without i_mutex
1305 * being held. */
1306 if (flags & DCACHE_MANAGE_TRANSIT) {
1307 BUG_ON(!path->dentry->d_op);
1308 BUG_ON(!path->dentry->d_op->d_manage);
1309 ret = path->dentry->d_op->d_manage(path, false);
1310 flags = smp_load_acquire(&path->dentry->d_flags);
1311 if (ret < 0)
1312 break;
1315 /* Transit to a mounted filesystem. */
1316 if (flags & DCACHE_MOUNTED) {
1317 struct vfsmount *mounted = lookup_mnt(path);
1318 if (mounted) {
1319 dput(path->dentry);
1320 if (need_mntput)
1321 mntput(path->mnt);
1322 path->mnt = mounted;
1323 path->dentry = dget(mounted->mnt_root);
1324 need_mntput = true;
1325 continue;
1328 /* Something is mounted on this dentry in another
1329 * namespace and/or whatever was mounted there in this
1330 * namespace got unmounted before lookup_mnt() could
1331 * get it */
1334 /* Handle an automount point */
1335 if (flags & DCACHE_NEED_AUTOMOUNT) {
1336 ret = follow_automount(path, nd, &need_mntput);
1337 if (ret < 0)
1338 break;
1339 continue;
1342 /* We didn't change the current path point */
1343 break;
1346 if (need_mntput) {
1347 if (path->mnt == mnt)
1348 mntput(path->mnt);
1349 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1350 ret = -EXDEV;
1351 else
1352 nd->flags |= LOOKUP_JUMPED;
1354 if (ret == -EISDIR || !ret)
1355 ret = 1;
1356 if (ret > 0 && unlikely(d_flags_negative(flags)))
1357 ret = -ENOENT;
1358 if (unlikely(ret < 0))
1359 path_put_conditional(path, nd);
1360 return ret;
1363 int follow_down_one(struct path *path)
1365 struct vfsmount *mounted;
1367 mounted = lookup_mnt(path);
1368 if (mounted) {
1369 dput(path->dentry);
1370 mntput(path->mnt);
1371 path->mnt = mounted;
1372 path->dentry = dget(mounted->mnt_root);
1373 return 1;
1375 return 0;
1377 EXPORT_SYMBOL(follow_down_one);
1379 static inline int managed_dentry_rcu(const struct path *path)
1381 return (path->dentry->d_flags & DCACHE_MANAGE_TRANSIT) ?
1382 path->dentry->d_op->d_manage(path, true) : 0;
1386 * Try to skip to top of mountpoint pile in rcuwalk mode. Fail if
1387 * we meet a managed dentry that would need blocking.
1389 static bool __follow_mount_rcu(struct nameidata *nd, struct path *path,
1390 struct inode **inode, unsigned *seqp)
1392 for (;;) {
1393 struct mount *mounted;
1395 * Don't forget we might have a non-mountpoint managed dentry
1396 * that wants to block transit.
1398 switch (managed_dentry_rcu(path)) {
1399 case -ECHILD:
1400 default:
1401 return false;
1402 case -EISDIR:
1403 return true;
1404 case 0:
1405 break;
1408 if (!d_mountpoint(path->dentry))
1409 return !(path->dentry->d_flags & DCACHE_NEED_AUTOMOUNT);
1411 mounted = __lookup_mnt(path->mnt, path->dentry);
1412 if (!mounted)
1413 break;
1414 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1415 return false;
1416 path->mnt = &mounted->mnt;
1417 path->dentry = mounted->mnt.mnt_root;
1418 nd->flags |= LOOKUP_JUMPED;
1419 *seqp = read_seqcount_begin(&path->dentry->d_seq);
1421 * Update the inode too. We don't need to re-check the
1422 * dentry sequence number here after this d_inode read,
1423 * because a mount-point is always pinned.
1425 *inode = path->dentry->d_inode;
1427 return !read_seqretry(&mount_lock, nd->m_seq) &&
1428 !(path->dentry->d_flags & DCACHE_NEED_AUTOMOUNT);
1431 static int follow_dotdot_rcu(struct nameidata *nd)
1433 struct inode *inode = nd->inode;
1435 while (1) {
1436 if (path_equal(&nd->path, &nd->root)) {
1437 if (unlikely(nd->flags & LOOKUP_BENEATH))
1438 return -ECHILD;
1439 break;
1441 if (nd->path.dentry != nd->path.mnt->mnt_root) {
1442 struct dentry *old = nd->path.dentry;
1443 struct dentry *parent = old->d_parent;
1444 unsigned seq;
1446 inode = parent->d_inode;
1447 seq = read_seqcount_begin(&parent->d_seq);
1448 if (unlikely(read_seqcount_retry(&old->d_seq, nd->seq)))
1449 return -ECHILD;
1450 nd->path.dentry = parent;
1451 nd->seq = seq;
1452 if (unlikely(!path_connected(&nd->path)))
1453 return -ECHILD;
1454 break;
1455 } else {
1456 struct mount *mnt = real_mount(nd->path.mnt);
1457 struct mount *mparent = mnt->mnt_parent;
1458 struct dentry *mountpoint = mnt->mnt_mountpoint;
1459 struct inode *inode2 = mountpoint->d_inode;
1460 unsigned seq = read_seqcount_begin(&mountpoint->d_seq);
1461 if (unlikely(read_seqretry(&mount_lock, nd->m_seq)))
1462 return -ECHILD;
1463 if (&mparent->mnt == nd->path.mnt)
1464 break;
1465 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1466 return -ECHILD;
1467 /* we know that mountpoint was pinned */
1468 nd->path.dentry = mountpoint;
1469 nd->path.mnt = &mparent->mnt;
1470 inode = inode2;
1471 nd->seq = seq;
1474 while (unlikely(d_mountpoint(nd->path.dentry))) {
1475 struct mount *mounted;
1476 mounted = __lookup_mnt(nd->path.mnt, nd->path.dentry);
1477 if (unlikely(read_seqretry(&mount_lock, nd->m_seq)))
1478 return -ECHILD;
1479 if (!mounted)
1480 break;
1481 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1482 return -ECHILD;
1483 nd->path.mnt = &mounted->mnt;
1484 nd->path.dentry = mounted->mnt.mnt_root;
1485 inode = nd->path.dentry->d_inode;
1486 nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
1488 nd->inode = inode;
1489 return 0;
1493 * Follow down to the covering mount currently visible to userspace. At each
1494 * point, the filesystem owning that dentry may be queried as to whether the
1495 * caller is permitted to proceed or not.
1497 int follow_down(struct path *path)
1499 unsigned managed;
1500 int ret;
1502 while (managed = READ_ONCE(path->dentry->d_flags),
1503 unlikely(managed & DCACHE_MANAGED_DENTRY)) {
1504 /* Allow the filesystem to manage the transit without i_mutex
1505 * being held.
1507 * We indicate to the filesystem if someone is trying to mount
1508 * something here. This gives autofs the chance to deny anyone
1509 * other than its daemon the right to mount on its
1510 * superstructure.
1512 * The filesystem may sleep at this point.
1514 if (managed & DCACHE_MANAGE_TRANSIT) {
1515 BUG_ON(!path->dentry->d_op);
1516 BUG_ON(!path->dentry->d_op->d_manage);
1517 ret = path->dentry->d_op->d_manage(path, false);
1518 if (ret < 0)
1519 return ret == -EISDIR ? 0 : ret;
1522 /* Transit to a mounted filesystem. */
1523 if (managed & DCACHE_MOUNTED) {
1524 struct vfsmount *mounted = lookup_mnt(path);
1525 if (!mounted)
1526 break;
1527 dput(path->dentry);
1528 mntput(path->mnt);
1529 path->mnt = mounted;
1530 path->dentry = dget(mounted->mnt_root);
1531 continue;
1534 /* Don't handle automount points here */
1535 break;
1537 return 0;
1539 EXPORT_SYMBOL(follow_down);
1542 * Skip to top of mountpoint pile in refwalk mode for follow_dotdot()
1544 static void follow_mount(struct path *path)
1546 while (d_mountpoint(path->dentry)) {
1547 struct vfsmount *mounted = lookup_mnt(path);
1548 if (!mounted)
1549 break;
1550 dput(path->dentry);
1551 mntput(path->mnt);
1552 path->mnt = mounted;
1553 path->dentry = dget(mounted->mnt_root);
1557 static int path_parent_directory(struct path *path)
1559 struct dentry *old = path->dentry;
1560 /* rare case of legitimate dget_parent()... */
1561 path->dentry = dget_parent(path->dentry);
1562 dput(old);
1563 if (unlikely(!path_connected(path)))
1564 return -ENOENT;
1565 return 0;
1568 static int follow_dotdot(struct nameidata *nd)
1570 while (1) {
1571 if (path_equal(&nd->path, &nd->root)) {
1572 if (unlikely(nd->flags & LOOKUP_BENEATH))
1573 return -EXDEV;
1574 break;
1576 if (nd->path.dentry != nd->path.mnt->mnt_root) {
1577 int ret = path_parent_directory(&nd->path);
1578 if (ret)
1579 return ret;
1580 break;
1582 if (!follow_up(&nd->path))
1583 break;
1584 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1585 return -EXDEV;
1587 follow_mount(&nd->path);
1588 nd->inode = nd->path.dentry->d_inode;
1589 return 0;
1593 * This looks up the name in dcache and possibly revalidates the found dentry.
1594 * NULL is returned if the dentry does not exist in the cache.
1596 static struct dentry *lookup_dcache(const struct qstr *name,
1597 struct dentry *dir,
1598 unsigned int flags)
1600 struct dentry *dentry = d_lookup(dir, name);
1601 if (dentry) {
1602 int error = d_revalidate(dentry, flags);
1603 if (unlikely(error <= 0)) {
1604 if (!error)
1605 d_invalidate(dentry);
1606 dput(dentry);
1607 return ERR_PTR(error);
1610 return dentry;
1614 * Parent directory has inode locked exclusive. This is one
1615 * and only case when ->lookup() gets called on non in-lookup
1616 * dentries - as the matter of fact, this only gets called
1617 * when directory is guaranteed to have no in-lookup children
1618 * at all.
1620 static struct dentry *__lookup_hash(const struct qstr *name,
1621 struct dentry *base, unsigned int flags)
1623 struct dentry *dentry = lookup_dcache(name, base, flags);
1624 struct dentry *old;
1625 struct inode *dir = base->d_inode;
1627 if (dentry)
1628 return dentry;
1630 /* Don't create child dentry for a dead directory. */
1631 if (unlikely(IS_DEADDIR(dir)))
1632 return ERR_PTR(-ENOENT);
1634 dentry = d_alloc(base, name);
1635 if (unlikely(!dentry))
1636 return ERR_PTR(-ENOMEM);
1638 old = dir->i_op->lookup(dir, dentry, flags);
1639 if (unlikely(old)) {
1640 dput(dentry);
1641 dentry = old;
1643 return dentry;
1646 static int lookup_fast(struct nameidata *nd,
1647 struct path *path, struct inode **inode,
1648 unsigned *seqp)
1650 struct vfsmount *mnt = nd->path.mnt;
1651 struct dentry *dentry, *parent = nd->path.dentry;
1652 int status = 1;
1653 int err;
1656 * Rename seqlock is not required here because in the off chance
1657 * of a false negative due to a concurrent rename, the caller is
1658 * going to fall back to non-racy lookup.
1660 if (nd->flags & LOOKUP_RCU) {
1661 unsigned seq;
1662 bool negative;
1663 dentry = __d_lookup_rcu(parent, &nd->last, &seq);
1664 if (unlikely(!dentry)) {
1665 if (unlazy_walk(nd))
1666 return -ECHILD;
1667 return 0;
1671 * This sequence count validates that the inode matches
1672 * the dentry name information from lookup.
1674 *inode = d_backing_inode(dentry);
1675 negative = d_is_negative(dentry);
1676 if (unlikely(read_seqcount_retry(&dentry->d_seq, seq)))
1677 return -ECHILD;
1680 * This sequence count validates that the parent had no
1681 * changes while we did the lookup of the dentry above.
1683 * The memory barrier in read_seqcount_begin of child is
1684 * enough, we can use __read_seqcount_retry here.
1686 if (unlikely(__read_seqcount_retry(&parent->d_seq, nd->seq)))
1687 return -ECHILD;
1689 *seqp = seq;
1690 status = d_revalidate(dentry, nd->flags);
1691 if (likely(status > 0)) {
1693 * Note: do negative dentry check after revalidation in
1694 * case that drops it.
1696 if (unlikely(negative))
1697 return -ENOENT;
1698 path->mnt = mnt;
1699 path->dentry = dentry;
1700 if (likely(__follow_mount_rcu(nd, path, inode, seqp)))
1701 return 1;
1703 if (unlazy_child(nd, dentry, seq))
1704 return -ECHILD;
1705 if (unlikely(status == -ECHILD))
1706 /* we'd been told to redo it in non-rcu mode */
1707 status = d_revalidate(dentry, nd->flags);
1708 } else {
1709 dentry = __d_lookup(parent, &nd->last);
1710 if (unlikely(!dentry))
1711 return 0;
1712 status = d_revalidate(dentry, nd->flags);
1714 if (unlikely(status <= 0)) {
1715 if (!status)
1716 d_invalidate(dentry);
1717 dput(dentry);
1718 return status;
1721 path->mnt = mnt;
1722 path->dentry = dentry;
1723 err = follow_managed(path, nd);
1724 if (likely(err > 0))
1725 *inode = d_backing_inode(path->dentry);
1726 return err;
1729 /* Fast lookup failed, do it the slow way */
1730 static struct dentry *__lookup_slow(const struct qstr *name,
1731 struct dentry *dir,
1732 unsigned int flags)
1734 struct dentry *dentry, *old;
1735 struct inode *inode = dir->d_inode;
1736 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
1738 /* Don't go there if it's already dead */
1739 if (unlikely(IS_DEADDIR(inode)))
1740 return ERR_PTR(-ENOENT);
1741 again:
1742 dentry = d_alloc_parallel(dir, name, &wq);
1743 if (IS_ERR(dentry))
1744 return dentry;
1745 if (unlikely(!d_in_lookup(dentry))) {
1746 int error = d_revalidate(dentry, flags);
1747 if (unlikely(error <= 0)) {
1748 if (!error) {
1749 d_invalidate(dentry);
1750 dput(dentry);
1751 goto again;
1753 dput(dentry);
1754 dentry = ERR_PTR(error);
1756 } else {
1757 old = inode->i_op->lookup(inode, dentry, flags);
1758 d_lookup_done(dentry);
1759 if (unlikely(old)) {
1760 dput(dentry);
1761 dentry = old;
1764 return dentry;
1767 static struct dentry *lookup_slow(const struct qstr *name,
1768 struct dentry *dir,
1769 unsigned int flags)
1771 struct inode *inode = dir->d_inode;
1772 struct dentry *res;
1773 inode_lock_shared(inode);
1774 res = __lookup_slow(name, dir, flags);
1775 inode_unlock_shared(inode);
1776 return res;
1779 static inline int may_lookup(struct nameidata *nd)
1781 if (nd->flags & LOOKUP_RCU) {
1782 int err = inode_permission(nd->inode, MAY_EXEC|MAY_NOT_BLOCK);
1783 if (err != -ECHILD)
1784 return err;
1785 if (unlazy_walk(nd))
1786 return -ECHILD;
1788 return inode_permission(nd->inode, MAY_EXEC);
1791 static inline int handle_dots(struct nameidata *nd, int type)
1793 if (type == LAST_DOTDOT) {
1794 int error = 0;
1796 if (!nd->root.mnt) {
1797 error = set_root(nd);
1798 if (error)
1799 return error;
1801 if (nd->flags & LOOKUP_RCU)
1802 error = follow_dotdot_rcu(nd);
1803 else
1804 error = follow_dotdot(nd);
1805 if (error)
1806 return error;
1808 if (unlikely(nd->flags & LOOKUP_IS_SCOPED)) {
1810 * If there was a racing rename or mount along our
1811 * path, then we can't be sure that ".." hasn't jumped
1812 * above nd->root (and so userspace should retry or use
1813 * some fallback).
1815 smp_rmb();
1816 if (unlikely(__read_seqcount_retry(&mount_lock.seqcount, nd->m_seq)))
1817 return -EAGAIN;
1818 if (unlikely(__read_seqcount_retry(&rename_lock.seqcount, nd->r_seq)))
1819 return -EAGAIN;
1822 return 0;
1825 static int pick_link(struct nameidata *nd, struct path *link,
1826 struct inode *inode, unsigned seq)
1828 int error;
1829 struct saved *last;
1830 if (unlikely(nd->total_link_count++ >= MAXSYMLINKS)) {
1831 path_to_nameidata(link, nd);
1832 return -ELOOP;
1834 if (!(nd->flags & LOOKUP_RCU)) {
1835 if (link->mnt == nd->path.mnt)
1836 mntget(link->mnt);
1838 error = nd_alloc_stack(nd);
1839 if (unlikely(error)) {
1840 if (error == -ECHILD) {
1841 if (unlikely(!legitimize_path(nd, link, seq))) {
1842 drop_links(nd);
1843 nd->depth = 0;
1844 nd->flags &= ~LOOKUP_RCU;
1845 nd->path.mnt = NULL;
1846 nd->path.dentry = NULL;
1847 rcu_read_unlock();
1848 } else if (likely(unlazy_walk(nd)) == 0)
1849 error = nd_alloc_stack(nd);
1851 if (error) {
1852 path_put(link);
1853 return error;
1857 last = nd->stack + nd->depth++;
1858 last->link = *link;
1859 clear_delayed_call(&last->done);
1860 nd->link_inode = inode;
1861 last->seq = seq;
1862 return 1;
1865 enum {WALK_FOLLOW = 1, WALK_MORE = 2};
1868 * Do we need to follow links? We _really_ want to be able
1869 * to do this check without having to look at inode->i_op,
1870 * so we keep a cache of "no, this doesn't need follow_link"
1871 * for the common case.
1873 static inline int step_into(struct nameidata *nd, struct path *path,
1874 int flags, struct inode *inode, unsigned seq)
1876 if (!(flags & WALK_MORE) && nd->depth)
1877 put_link(nd);
1878 if (likely(!d_is_symlink(path->dentry)) ||
1879 !(flags & WALK_FOLLOW || nd->flags & LOOKUP_FOLLOW)) {
1880 /* not a symlink or should not follow */
1881 path_to_nameidata(path, nd);
1882 nd->inode = inode;
1883 nd->seq = seq;
1884 return 0;
1886 /* make sure that d_is_symlink above matches inode */
1887 if (nd->flags & LOOKUP_RCU) {
1888 if (read_seqcount_retry(&path->dentry->d_seq, seq))
1889 return -ECHILD;
1891 return pick_link(nd, path, inode, seq);
1894 static int walk_component(struct nameidata *nd, int flags)
1896 struct path path;
1897 struct inode *inode;
1898 unsigned seq;
1899 int err;
1901 * "." and ".." are special - ".." especially so because it has
1902 * to be able to know about the current root directory and
1903 * parent relationships.
1905 if (unlikely(nd->last_type != LAST_NORM)) {
1906 err = handle_dots(nd, nd->last_type);
1907 if (!(flags & WALK_MORE) && nd->depth)
1908 put_link(nd);
1909 return err;
1911 err = lookup_fast(nd, &path, &inode, &seq);
1912 if (unlikely(err <= 0)) {
1913 if (err < 0)
1914 return err;
1915 path.dentry = lookup_slow(&nd->last, nd->path.dentry,
1916 nd->flags);
1917 if (IS_ERR(path.dentry))
1918 return PTR_ERR(path.dentry);
1920 path.mnt = nd->path.mnt;
1921 err = follow_managed(&path, nd);
1922 if (unlikely(err < 0))
1923 return err;
1925 seq = 0; /* we are already out of RCU mode */
1926 inode = d_backing_inode(path.dentry);
1929 return step_into(nd, &path, flags, inode, seq);
1933 * We can do the critical dentry name comparison and hashing
1934 * operations one word at a time, but we are limited to:
1936 * - Architectures with fast unaligned word accesses. We could
1937 * do a "get_unaligned()" if this helps and is sufficiently
1938 * fast.
1940 * - non-CONFIG_DEBUG_PAGEALLOC configurations (so that we
1941 * do not trap on the (extremely unlikely) case of a page
1942 * crossing operation.
1944 * - Furthermore, we need an efficient 64-bit compile for the
1945 * 64-bit case in order to generate the "number of bytes in
1946 * the final mask". Again, that could be replaced with a
1947 * efficient population count instruction or similar.
1949 #ifdef CONFIG_DCACHE_WORD_ACCESS
1951 #include <asm/word-at-a-time.h>
1953 #ifdef HASH_MIX
1955 /* Architecture provides HASH_MIX and fold_hash() in <asm/hash.h> */
1957 #elif defined(CONFIG_64BIT)
1959 * Register pressure in the mixing function is an issue, particularly
1960 * on 32-bit x86, but almost any function requires one state value and
1961 * one temporary. Instead, use a function designed for two state values
1962 * and no temporaries.
1964 * This function cannot create a collision in only two iterations, so
1965 * we have two iterations to achieve avalanche. In those two iterations,
1966 * we have six layers of mixing, which is enough to spread one bit's
1967 * influence out to 2^6 = 64 state bits.
1969 * Rotate constants are scored by considering either 64 one-bit input
1970 * deltas or 64*63/2 = 2016 two-bit input deltas, and finding the
1971 * probability of that delta causing a change to each of the 128 output
1972 * bits, using a sample of random initial states.
1974 * The Shannon entropy of the computed probabilities is then summed
1975 * to produce a score. Ideally, any input change has a 50% chance of
1976 * toggling any given output bit.
1978 * Mixing scores (in bits) for (12,45):
1979 * Input delta: 1-bit 2-bit
1980 * 1 round: 713.3 42542.6
1981 * 2 rounds: 2753.7 140389.8
1982 * 3 rounds: 5954.1 233458.2
1983 * 4 rounds: 7862.6 256672.2
1984 * Perfect: 8192 258048
1985 * (64*128) (64*63/2 * 128)
1987 #define HASH_MIX(x, y, a) \
1988 ( x ^= (a), \
1989 y ^= x, x = rol64(x,12),\
1990 x += y, y = rol64(y,45),\
1991 y *= 9 )
1994 * Fold two longs into one 32-bit hash value. This must be fast, but
1995 * latency isn't quite as critical, as there is a fair bit of additional
1996 * work done before the hash value is used.
1998 static inline unsigned int fold_hash(unsigned long x, unsigned long y)
2000 y ^= x * GOLDEN_RATIO_64;
2001 y *= GOLDEN_RATIO_64;
2002 return y >> 32;
2005 #else /* 32-bit case */
2008 * Mixing scores (in bits) for (7,20):
2009 * Input delta: 1-bit 2-bit
2010 * 1 round: 330.3 9201.6
2011 * 2 rounds: 1246.4 25475.4
2012 * 3 rounds: 1907.1 31295.1
2013 * 4 rounds: 2042.3 31718.6
2014 * Perfect: 2048 31744
2015 * (32*64) (32*31/2 * 64)
2017 #define HASH_MIX(x, y, a) \
2018 ( x ^= (a), \
2019 y ^= x, x = rol32(x, 7),\
2020 x += y, y = rol32(y,20),\
2021 y *= 9 )
2023 static inline unsigned int fold_hash(unsigned long x, unsigned long y)
2025 /* Use arch-optimized multiply if one exists */
2026 return __hash_32(y ^ __hash_32(x));
2029 #endif
2032 * Return the hash of a string of known length. This is carfully
2033 * designed to match hash_name(), which is the more critical function.
2034 * In particular, we must end by hashing a final word containing 0..7
2035 * payload bytes, to match the way that hash_name() iterates until it
2036 * finds the delimiter after the name.
2038 unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
2040 unsigned long a, x = 0, y = (unsigned long)salt;
2042 for (;;) {
2043 if (!len)
2044 goto done;
2045 a = load_unaligned_zeropad(name);
2046 if (len < sizeof(unsigned long))
2047 break;
2048 HASH_MIX(x, y, a);
2049 name += sizeof(unsigned long);
2050 len -= sizeof(unsigned long);
2052 x ^= a & bytemask_from_count(len);
2053 done:
2054 return fold_hash(x, y);
2056 EXPORT_SYMBOL(full_name_hash);
2058 /* Return the "hash_len" (hash and length) of a null-terminated string */
2059 u64 hashlen_string(const void *salt, const char *name)
2061 unsigned long a = 0, x = 0, y = (unsigned long)salt;
2062 unsigned long adata, mask, len;
2063 const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2065 len = 0;
2066 goto inside;
2068 do {
2069 HASH_MIX(x, y, a);
2070 len += sizeof(unsigned long);
2071 inside:
2072 a = load_unaligned_zeropad(name+len);
2073 } while (!has_zero(a, &adata, &constants));
2075 adata = prep_zero_mask(a, adata, &constants);
2076 mask = create_zero_mask(adata);
2077 x ^= a & zero_bytemask(mask);
2079 return hashlen_create(fold_hash(x, y), len + find_zero(mask));
2081 EXPORT_SYMBOL(hashlen_string);
2084 * Calculate the length and hash of the path component, and
2085 * return the "hash_len" as the result.
2087 static inline u64 hash_name(const void *salt, const char *name)
2089 unsigned long a = 0, b, x = 0, y = (unsigned long)salt;
2090 unsigned long adata, bdata, mask, len;
2091 const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2093 len = 0;
2094 goto inside;
2096 do {
2097 HASH_MIX(x, y, a);
2098 len += sizeof(unsigned long);
2099 inside:
2100 a = load_unaligned_zeropad(name+len);
2101 b = a ^ REPEAT_BYTE('/');
2102 } while (!(has_zero(a, &adata, &constants) | has_zero(b, &bdata, &constants)));
2104 adata = prep_zero_mask(a, adata, &constants);
2105 bdata = prep_zero_mask(b, bdata, &constants);
2106 mask = create_zero_mask(adata | bdata);
2107 x ^= a & zero_bytemask(mask);
2109 return hashlen_create(fold_hash(x, y), len + find_zero(mask));
2112 #else /* !CONFIG_DCACHE_WORD_ACCESS: Slow, byte-at-a-time version */
2114 /* Return the hash of a string of known length */
2115 unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
2117 unsigned long hash = init_name_hash(salt);
2118 while (len--)
2119 hash = partial_name_hash((unsigned char)*name++, hash);
2120 return end_name_hash(hash);
2122 EXPORT_SYMBOL(full_name_hash);
2124 /* Return the "hash_len" (hash and length) of a null-terminated string */
2125 u64 hashlen_string(const void *salt, const char *name)
2127 unsigned long hash = init_name_hash(salt);
2128 unsigned long len = 0, c;
2130 c = (unsigned char)*name;
2131 while (c) {
2132 len++;
2133 hash = partial_name_hash(c, hash);
2134 c = (unsigned char)name[len];
2136 return hashlen_create(end_name_hash(hash), len);
2138 EXPORT_SYMBOL(hashlen_string);
2141 * We know there's a real path component here of at least
2142 * one character.
2144 static inline u64 hash_name(const void *salt, const char *name)
2146 unsigned long hash = init_name_hash(salt);
2147 unsigned long len = 0, c;
2149 c = (unsigned char)*name;
2150 do {
2151 len++;
2152 hash = partial_name_hash(c, hash);
2153 c = (unsigned char)name[len];
2154 } while (c && c != '/');
2155 return hashlen_create(end_name_hash(hash), len);
2158 #endif
2161 * Name resolution.
2162 * This is the basic name resolution function, turning a pathname into
2163 * the final dentry. We expect 'base' to be positive and a directory.
2165 * Returns 0 and nd will have valid dentry and mnt on success.
2166 * Returns error and drops reference to input namei data on failure.
2168 static int link_path_walk(const char *name, struct nameidata *nd)
2170 int err;
2172 if (IS_ERR(name))
2173 return PTR_ERR(name);
2174 while (*name=='/')
2175 name++;
2176 if (!*name)
2177 return 0;
2179 /* At this point we know we have a real path component. */
2180 for(;;) {
2181 u64 hash_len;
2182 int type;
2184 err = may_lookup(nd);
2185 if (err)
2186 return err;
2188 hash_len = hash_name(nd->path.dentry, name);
2190 type = LAST_NORM;
2191 if (name[0] == '.') switch (hashlen_len(hash_len)) {
2192 case 2:
2193 if (name[1] == '.') {
2194 type = LAST_DOTDOT;
2195 nd->flags |= LOOKUP_JUMPED;
2197 break;
2198 case 1:
2199 type = LAST_DOT;
2201 if (likely(type == LAST_NORM)) {
2202 struct dentry *parent = nd->path.dentry;
2203 nd->flags &= ~LOOKUP_JUMPED;
2204 if (unlikely(parent->d_flags & DCACHE_OP_HASH)) {
2205 struct qstr this = { { .hash_len = hash_len }, .name = name };
2206 err = parent->d_op->d_hash(parent, &this);
2207 if (err < 0)
2208 return err;
2209 hash_len = this.hash_len;
2210 name = this.name;
2214 nd->last.hash_len = hash_len;
2215 nd->last.name = name;
2216 nd->last_type = type;
2218 name += hashlen_len(hash_len);
2219 if (!*name)
2220 goto OK;
2222 * If it wasn't NUL, we know it was '/'. Skip that
2223 * slash, and continue until no more slashes.
2225 do {
2226 name++;
2227 } while (unlikely(*name == '/'));
2228 if (unlikely(!*name)) {
2230 /* pathname body, done */
2231 if (!nd->depth)
2232 return 0;
2233 name = nd->stack[nd->depth - 1].name;
2234 /* trailing symlink, done */
2235 if (!name)
2236 return 0;
2237 /* last component of nested symlink */
2238 err = walk_component(nd, WALK_FOLLOW);
2239 } else {
2240 /* not the last component */
2241 err = walk_component(nd, WALK_FOLLOW | WALK_MORE);
2243 if (err < 0)
2244 return err;
2246 if (err) {
2247 const char *s = get_link(nd);
2249 if (IS_ERR(s))
2250 return PTR_ERR(s);
2251 err = 0;
2252 if (unlikely(!s)) {
2253 /* jumped */
2254 put_link(nd);
2255 } else {
2256 nd->stack[nd->depth - 1].name = name;
2257 name = s;
2258 continue;
2261 if (unlikely(!d_can_lookup(nd->path.dentry))) {
2262 if (nd->flags & LOOKUP_RCU) {
2263 if (unlazy_walk(nd))
2264 return -ECHILD;
2266 return -ENOTDIR;
2271 /* must be paired with terminate_walk() */
2272 static const char *path_init(struct nameidata *nd, unsigned flags)
2274 int error;
2275 const char *s = nd->name->name;
2277 if (!*s)
2278 flags &= ~LOOKUP_RCU;
2279 if (flags & LOOKUP_RCU)
2280 rcu_read_lock();
2282 nd->last_type = LAST_ROOT; /* if there are only slashes... */
2283 nd->flags = flags | LOOKUP_JUMPED | LOOKUP_PARENT;
2284 nd->depth = 0;
2286 nd->m_seq = __read_seqcount_begin(&mount_lock.seqcount);
2287 nd->r_seq = __read_seqcount_begin(&rename_lock.seqcount);
2288 smp_rmb();
2290 if (flags & LOOKUP_ROOT) {
2291 struct dentry *root = nd->root.dentry;
2292 struct inode *inode = root->d_inode;
2293 if (*s && unlikely(!d_can_lookup(root)))
2294 return ERR_PTR(-ENOTDIR);
2295 nd->path = nd->root;
2296 nd->inode = inode;
2297 if (flags & LOOKUP_RCU) {
2298 nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
2299 nd->root_seq = nd->seq;
2300 } else {
2301 path_get(&nd->path);
2303 return s;
2306 nd->root.mnt = NULL;
2307 nd->path.mnt = NULL;
2308 nd->path.dentry = NULL;
2310 /* Absolute pathname -- fetch the root (LOOKUP_IN_ROOT uses nd->dfd). */
2311 if (*s == '/' && !(flags & LOOKUP_IN_ROOT)) {
2312 error = nd_jump_root(nd);
2313 if (unlikely(error))
2314 return ERR_PTR(error);
2315 return s;
2318 /* Relative pathname -- get the starting-point it is relative to. */
2319 if (nd->dfd == AT_FDCWD) {
2320 if (flags & LOOKUP_RCU) {
2321 struct fs_struct *fs = current->fs;
2322 unsigned seq;
2324 do {
2325 seq = read_seqcount_begin(&fs->seq);
2326 nd->path = fs->pwd;
2327 nd->inode = nd->path.dentry->d_inode;
2328 nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
2329 } while (read_seqcount_retry(&fs->seq, seq));
2330 } else {
2331 get_fs_pwd(current->fs, &nd->path);
2332 nd->inode = nd->path.dentry->d_inode;
2334 } else {
2335 /* Caller must check execute permissions on the starting path component */
2336 struct fd f = fdget_raw(nd->dfd);
2337 struct dentry *dentry;
2339 if (!f.file)
2340 return ERR_PTR(-EBADF);
2342 dentry = f.file->f_path.dentry;
2344 if (*s && unlikely(!d_can_lookup(dentry))) {
2345 fdput(f);
2346 return ERR_PTR(-ENOTDIR);
2349 nd->path = f.file->f_path;
2350 if (flags & LOOKUP_RCU) {
2351 nd->inode = nd->path.dentry->d_inode;
2352 nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
2353 } else {
2354 path_get(&nd->path);
2355 nd->inode = nd->path.dentry->d_inode;
2357 fdput(f);
2360 /* For scoped-lookups we need to set the root to the dirfd as well. */
2361 if (flags & LOOKUP_IS_SCOPED) {
2362 nd->root = nd->path;
2363 if (flags & LOOKUP_RCU) {
2364 nd->root_seq = nd->seq;
2365 } else {
2366 path_get(&nd->root);
2367 nd->flags |= LOOKUP_ROOT_GRABBED;
2370 return s;
2373 static const char *trailing_symlink(struct nameidata *nd)
2375 const char *s;
2376 int error = may_follow_link(nd);
2377 if (unlikely(error))
2378 return ERR_PTR(error);
2379 nd->flags |= LOOKUP_PARENT;
2380 nd->stack[0].name = NULL;
2381 s = get_link(nd);
2382 return s ? s : "";
2385 static inline int lookup_last(struct nameidata *nd)
2387 if (nd->last_type == LAST_NORM && nd->last.name[nd->last.len])
2388 nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
2390 nd->flags &= ~LOOKUP_PARENT;
2391 return walk_component(nd, 0);
2394 static int handle_lookup_down(struct nameidata *nd)
2396 struct path path = nd->path;
2397 struct inode *inode = nd->inode;
2398 unsigned seq = nd->seq;
2399 int err;
2401 if (nd->flags & LOOKUP_RCU) {
2403 * don't bother with unlazy_walk on failure - we are
2404 * at the very beginning of walk, so we lose nothing
2405 * if we simply redo everything in non-RCU mode
2407 if (unlikely(!__follow_mount_rcu(nd, &path, &inode, &seq)))
2408 return -ECHILD;
2409 } else {
2410 dget(path.dentry);
2411 err = follow_managed(&path, nd);
2412 if (unlikely(err < 0))
2413 return err;
2414 inode = d_backing_inode(path.dentry);
2415 seq = 0;
2417 path_to_nameidata(&path, nd);
2418 nd->inode = inode;
2419 nd->seq = seq;
2420 return 0;
2423 /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
2424 static int path_lookupat(struct nameidata *nd, unsigned flags, struct path *path)
2426 const char *s = path_init(nd, flags);
2427 int err;
2429 if (unlikely(flags & LOOKUP_DOWN) && !IS_ERR(s)) {
2430 err = handle_lookup_down(nd);
2431 if (unlikely(err < 0))
2432 s = ERR_PTR(err);
2435 while (!(err = link_path_walk(s, nd))
2436 && ((err = lookup_last(nd)) > 0)) {
2437 s = trailing_symlink(nd);
2439 if (!err)
2440 err = complete_walk(nd);
2442 if (!err && nd->flags & LOOKUP_DIRECTORY)
2443 if (!d_can_lookup(nd->path.dentry))
2444 err = -ENOTDIR;
2445 if (!err) {
2446 *path = nd->path;
2447 nd->path.mnt = NULL;
2448 nd->path.dentry = NULL;
2450 terminate_walk(nd);
2451 return err;
2454 int filename_lookup(int dfd, struct filename *name, unsigned flags,
2455 struct path *path, struct path *root)
2457 int retval;
2458 struct nameidata nd;
2459 if (IS_ERR(name))
2460 return PTR_ERR(name);
2461 if (unlikely(root)) {
2462 nd.root = *root;
2463 flags |= LOOKUP_ROOT;
2465 set_nameidata(&nd, dfd, name);
2466 retval = path_lookupat(&nd, flags | LOOKUP_RCU, path);
2467 if (unlikely(retval == -ECHILD))
2468 retval = path_lookupat(&nd, flags, path);
2469 if (unlikely(retval == -ESTALE))
2470 retval = path_lookupat(&nd, flags | LOOKUP_REVAL, path);
2472 if (likely(!retval))
2473 audit_inode(name, path->dentry, 0);
2474 restore_nameidata();
2475 putname(name);
2476 return retval;
2479 /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
2480 static int path_parentat(struct nameidata *nd, unsigned flags,
2481 struct path *parent)
2483 const char *s = path_init(nd, flags);
2484 int err = link_path_walk(s, nd);
2485 if (!err)
2486 err = complete_walk(nd);
2487 if (!err) {
2488 *parent = nd->path;
2489 nd->path.mnt = NULL;
2490 nd->path.dentry = NULL;
2492 terminate_walk(nd);
2493 return err;
2496 static struct filename *filename_parentat(int dfd, struct filename *name,
2497 unsigned int flags, struct path *parent,
2498 struct qstr *last, int *type)
2500 int retval;
2501 struct nameidata nd;
2503 if (IS_ERR(name))
2504 return name;
2505 set_nameidata(&nd, dfd, name);
2506 retval = path_parentat(&nd, flags | LOOKUP_RCU, parent);
2507 if (unlikely(retval == -ECHILD))
2508 retval = path_parentat(&nd, flags, parent);
2509 if (unlikely(retval == -ESTALE))
2510 retval = path_parentat(&nd, flags | LOOKUP_REVAL, parent);
2511 if (likely(!retval)) {
2512 *last = nd.last;
2513 *type = nd.last_type;
2514 audit_inode(name, parent->dentry, AUDIT_INODE_PARENT);
2515 } else {
2516 putname(name);
2517 name = ERR_PTR(retval);
2519 restore_nameidata();
2520 return name;
2523 /* does lookup, returns the object with parent locked */
2524 struct dentry *kern_path_locked(const char *name, struct path *path)
2526 struct filename *filename;
2527 struct dentry *d;
2528 struct qstr last;
2529 int type;
2531 filename = filename_parentat(AT_FDCWD, getname_kernel(name), 0, path,
2532 &last, &type);
2533 if (IS_ERR(filename))
2534 return ERR_CAST(filename);
2535 if (unlikely(type != LAST_NORM)) {
2536 path_put(path);
2537 putname(filename);
2538 return ERR_PTR(-EINVAL);
2540 inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
2541 d = __lookup_hash(&last, path->dentry, 0);
2542 if (IS_ERR(d)) {
2543 inode_unlock(path->dentry->d_inode);
2544 path_put(path);
2546 putname(filename);
2547 return d;
2550 int kern_path(const char *name, unsigned int flags, struct path *path)
2552 return filename_lookup(AT_FDCWD, getname_kernel(name),
2553 flags, path, NULL);
2555 EXPORT_SYMBOL(kern_path);
2558 * vfs_path_lookup - lookup a file path relative to a dentry-vfsmount pair
2559 * @dentry: pointer to dentry of the base directory
2560 * @mnt: pointer to vfs mount of the base directory
2561 * @name: pointer to file name
2562 * @flags: lookup flags
2563 * @path: pointer to struct path to fill
2565 int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt,
2566 const char *name, unsigned int flags,
2567 struct path *path)
2569 struct path root = {.mnt = mnt, .dentry = dentry};
2570 /* the first argument of filename_lookup() is ignored with root */
2571 return filename_lookup(AT_FDCWD, getname_kernel(name),
2572 flags , path, &root);
2574 EXPORT_SYMBOL(vfs_path_lookup);
2576 static int lookup_one_len_common(const char *name, struct dentry *base,
2577 int len, struct qstr *this)
2579 this->name = name;
2580 this->len = len;
2581 this->hash = full_name_hash(base, name, len);
2582 if (!len)
2583 return -EACCES;
2585 if (unlikely(name[0] == '.')) {
2586 if (len < 2 || (len == 2 && name[1] == '.'))
2587 return -EACCES;
2590 while (len--) {
2591 unsigned int c = *(const unsigned char *)name++;
2592 if (c == '/' || c == '\0')
2593 return -EACCES;
2596 * See if the low-level filesystem might want
2597 * to use its own hash..
2599 if (base->d_flags & DCACHE_OP_HASH) {
2600 int err = base->d_op->d_hash(base, this);
2601 if (err < 0)
2602 return err;
2605 return inode_permission(base->d_inode, MAY_EXEC);
2609 * try_lookup_one_len - filesystem helper to lookup single pathname component
2610 * @name: pathname component to lookup
2611 * @base: base directory to lookup from
2612 * @len: maximum length @len should be interpreted to
2614 * Look up a dentry by name in the dcache, returning NULL if it does not
2615 * currently exist. The function does not try to create a dentry.
2617 * Note that this routine is purely a helper for filesystem usage and should
2618 * not be called by generic code.
2620 * The caller must hold base->i_mutex.
2622 struct dentry *try_lookup_one_len(const char *name, struct dentry *base, int len)
2624 struct qstr this;
2625 int err;
2627 WARN_ON_ONCE(!inode_is_locked(base->d_inode));
2629 err = lookup_one_len_common(name, base, len, &this);
2630 if (err)
2631 return ERR_PTR(err);
2633 return lookup_dcache(&this, base, 0);
2635 EXPORT_SYMBOL(try_lookup_one_len);
2638 * lookup_one_len - filesystem helper to lookup single pathname component
2639 * @name: pathname component to lookup
2640 * @base: base directory to lookup from
2641 * @len: maximum length @len should be interpreted to
2643 * Note that this routine is purely a helper for filesystem usage and should
2644 * not be called by generic code.
2646 * The caller must hold base->i_mutex.
2648 struct dentry *lookup_one_len(const char *name, struct dentry *base, int len)
2650 struct dentry *dentry;
2651 struct qstr this;
2652 int err;
2654 WARN_ON_ONCE(!inode_is_locked(base->d_inode));
2656 err = lookup_one_len_common(name, base, len, &this);
2657 if (err)
2658 return ERR_PTR(err);
2660 dentry = lookup_dcache(&this, base, 0);
2661 return dentry ? dentry : __lookup_slow(&this, base, 0);
2663 EXPORT_SYMBOL(lookup_one_len);
2666 * lookup_one_len_unlocked - filesystem helper to lookup single pathname component
2667 * @name: pathname component to lookup
2668 * @base: base directory to lookup from
2669 * @len: maximum length @len should be interpreted to
2671 * Note that this routine is purely a helper for filesystem usage and should
2672 * not be called by generic code.
2674 * Unlike lookup_one_len, it should be called without the parent
2675 * i_mutex held, and will take the i_mutex itself if necessary.
2677 struct dentry *lookup_one_len_unlocked(const char *name,
2678 struct dentry *base, int len)
2680 struct qstr this;
2681 int err;
2682 struct dentry *ret;
2684 err = lookup_one_len_common(name, base, len, &this);
2685 if (err)
2686 return ERR_PTR(err);
2688 ret = lookup_dcache(&this, base, 0);
2689 if (!ret)
2690 ret = lookup_slow(&this, base, 0);
2691 return ret;
2693 EXPORT_SYMBOL(lookup_one_len_unlocked);
2696 * Like lookup_one_len_unlocked(), except that it yields ERR_PTR(-ENOENT)
2697 * on negatives. Returns known positive or ERR_PTR(); that's what
2698 * most of the users want. Note that pinned negative with unlocked parent
2699 * _can_ become positive at any time, so callers of lookup_one_len_unlocked()
2700 * need to be very careful; pinned positives have ->d_inode stable, so
2701 * this one avoids such problems.
2703 struct dentry *lookup_positive_unlocked(const char *name,
2704 struct dentry *base, int len)
2706 struct dentry *ret = lookup_one_len_unlocked(name, base, len);
2707 if (!IS_ERR(ret) && d_flags_negative(smp_load_acquire(&ret->d_flags))) {
2708 dput(ret);
2709 ret = ERR_PTR(-ENOENT);
2711 return ret;
2713 EXPORT_SYMBOL(lookup_positive_unlocked);
2715 #ifdef CONFIG_UNIX98_PTYS
2716 int path_pts(struct path *path)
2718 /* Find something mounted on "pts" in the same directory as
2719 * the input path.
2721 struct dentry *child, *parent;
2722 struct qstr this;
2723 int ret;
2725 ret = path_parent_directory(path);
2726 if (ret)
2727 return ret;
2729 parent = path->dentry;
2730 this.name = "pts";
2731 this.len = 3;
2732 child = d_hash_and_lookup(parent, &this);
2733 if (!child)
2734 return -ENOENT;
2736 path->dentry = child;
2737 dput(parent);
2738 follow_mount(path);
2739 return 0;
2741 #endif
2743 int user_path_at_empty(int dfd, const char __user *name, unsigned flags,
2744 struct path *path, int *empty)
2746 return filename_lookup(dfd, getname_flags(name, flags, empty),
2747 flags, path, NULL);
2749 EXPORT_SYMBOL(user_path_at_empty);
2752 * path_mountpoint - look up a path to be umounted
2753 * @nd: lookup context
2754 * @flags: lookup flags
2755 * @path: pointer to container for result
2757 * Look up the given name, but don't attempt to revalidate the last component.
2758 * Returns 0 and "path" will be valid on success; Returns error otherwise.
2760 static int
2761 path_mountpoint(struct nameidata *nd, unsigned flags, struct path *path)
2763 const char *s = path_init(nd, flags);
2764 int err;
2766 while (!(err = link_path_walk(s, nd)) &&
2767 (err = lookup_last(nd)) > 0) {
2768 s = trailing_symlink(nd);
2770 if (!err && (nd->flags & LOOKUP_RCU))
2771 err = unlazy_walk(nd);
2772 if (!err)
2773 err = handle_lookup_down(nd);
2774 if (!err) {
2775 *path = nd->path;
2776 nd->path.mnt = NULL;
2777 nd->path.dentry = NULL;
2779 terminate_walk(nd);
2780 return err;
2783 static int
2784 filename_mountpoint(int dfd, struct filename *name, struct path *path,
2785 unsigned int flags)
2787 struct nameidata nd;
2788 int error;
2789 if (IS_ERR(name))
2790 return PTR_ERR(name);
2791 set_nameidata(&nd, dfd, name);
2792 error = path_mountpoint(&nd, flags | LOOKUP_RCU, path);
2793 if (unlikely(error == -ECHILD))
2794 error = path_mountpoint(&nd, flags, path);
2795 if (unlikely(error == -ESTALE))
2796 error = path_mountpoint(&nd, flags | LOOKUP_REVAL, path);
2797 if (likely(!error))
2798 audit_inode(name, path->dentry, AUDIT_INODE_NOEVAL);
2799 restore_nameidata();
2800 putname(name);
2801 return error;
2805 * user_path_mountpoint_at - lookup a path from userland in order to umount it
2806 * @dfd: directory file descriptor
2807 * @name: pathname from userland
2808 * @flags: lookup flags
2809 * @path: pointer to container to hold result
2811 * A umount is a special case for path walking. We're not actually interested
2812 * in the inode in this situation, and ESTALE errors can be a problem. We
2813 * simply want track down the dentry and vfsmount attached at the mountpoint
2814 * and avoid revalidating the last component.
2816 * Returns 0 and populates "path" on success.
2819 user_path_mountpoint_at(int dfd, const char __user *name, unsigned int flags,
2820 struct path *path)
2822 return filename_mountpoint(dfd, getname(name), path, flags);
2826 kern_path_mountpoint(int dfd, const char *name, struct path *path,
2827 unsigned int flags)
2829 return filename_mountpoint(dfd, getname_kernel(name), path, flags);
2831 EXPORT_SYMBOL(kern_path_mountpoint);
2833 int __check_sticky(struct inode *dir, struct inode *inode)
2835 kuid_t fsuid = current_fsuid();
2837 if (uid_eq(inode->i_uid, fsuid))
2838 return 0;
2839 if (uid_eq(dir->i_uid, fsuid))
2840 return 0;
2841 return !capable_wrt_inode_uidgid(inode, CAP_FOWNER);
2843 EXPORT_SYMBOL(__check_sticky);
2846 * Check whether we can remove a link victim from directory dir, check
2847 * whether the type of victim is right.
2848 * 1. We can't do it if dir is read-only (done in permission())
2849 * 2. We should have write and exec permissions on dir
2850 * 3. We can't remove anything from append-only dir
2851 * 4. We can't do anything with immutable dir (done in permission())
2852 * 5. If the sticky bit on dir is set we should either
2853 * a. be owner of dir, or
2854 * b. be owner of victim, or
2855 * c. have CAP_FOWNER capability
2856 * 6. If the victim is append-only or immutable we can't do antyhing with
2857 * links pointing to it.
2858 * 7. If the victim has an unknown uid or gid we can't change the inode.
2859 * 8. If we were asked to remove a directory and victim isn't one - ENOTDIR.
2860 * 9. If we were asked to remove a non-directory and victim isn't one - EISDIR.
2861 * 10. We can't remove a root or mountpoint.
2862 * 11. We don't allow removal of NFS sillyrenamed files; it's handled by
2863 * nfs_async_unlink().
2865 static int may_delete(struct inode *dir, struct dentry *victim, bool isdir)
2867 struct inode *inode = d_backing_inode(victim);
2868 int error;
2870 if (d_is_negative(victim))
2871 return -ENOENT;
2872 BUG_ON(!inode);
2874 BUG_ON(victim->d_parent->d_inode != dir);
2876 /* Inode writeback is not safe when the uid or gid are invalid. */
2877 if (!uid_valid(inode->i_uid) || !gid_valid(inode->i_gid))
2878 return -EOVERFLOW;
2880 audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
2882 error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
2883 if (error)
2884 return error;
2885 if (IS_APPEND(dir))
2886 return -EPERM;
2888 if (check_sticky(dir, inode) || IS_APPEND(inode) ||
2889 IS_IMMUTABLE(inode) || IS_SWAPFILE(inode) || HAS_UNMAPPED_ID(inode))
2890 return -EPERM;
2891 if (isdir) {
2892 if (!d_is_dir(victim))
2893 return -ENOTDIR;
2894 if (IS_ROOT(victim))
2895 return -EBUSY;
2896 } else if (d_is_dir(victim))
2897 return -EISDIR;
2898 if (IS_DEADDIR(dir))
2899 return -ENOENT;
2900 if (victim->d_flags & DCACHE_NFSFS_RENAMED)
2901 return -EBUSY;
2902 return 0;
2905 /* Check whether we can create an object with dentry child in directory
2906 * dir.
2907 * 1. We can't do it if child already exists (open has special treatment for
2908 * this case, but since we are inlined it's OK)
2909 * 2. We can't do it if dir is read-only (done in permission())
2910 * 3. We can't do it if the fs can't represent the fsuid or fsgid.
2911 * 4. We should have write and exec permissions on dir
2912 * 5. We can't do it if dir is immutable (done in permission())
2914 static inline int may_create(struct inode *dir, struct dentry *child)
2916 struct user_namespace *s_user_ns;
2917 audit_inode_child(dir, child, AUDIT_TYPE_CHILD_CREATE);
2918 if (child->d_inode)
2919 return -EEXIST;
2920 if (IS_DEADDIR(dir))
2921 return -ENOENT;
2922 s_user_ns = dir->i_sb->s_user_ns;
2923 if (!kuid_has_mapping(s_user_ns, current_fsuid()) ||
2924 !kgid_has_mapping(s_user_ns, current_fsgid()))
2925 return -EOVERFLOW;
2926 return inode_permission(dir, MAY_WRITE | MAY_EXEC);
2930 * p1 and p2 should be directories on the same fs.
2932 struct dentry *lock_rename(struct dentry *p1, struct dentry *p2)
2934 struct dentry *p;
2936 if (p1 == p2) {
2937 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
2938 return NULL;
2941 mutex_lock(&p1->d_sb->s_vfs_rename_mutex);
2943 p = d_ancestor(p2, p1);
2944 if (p) {
2945 inode_lock_nested(p2->d_inode, I_MUTEX_PARENT);
2946 inode_lock_nested(p1->d_inode, I_MUTEX_CHILD);
2947 return p;
2950 p = d_ancestor(p1, p2);
2951 if (p) {
2952 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
2953 inode_lock_nested(p2->d_inode, I_MUTEX_CHILD);
2954 return p;
2957 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
2958 inode_lock_nested(p2->d_inode, I_MUTEX_PARENT2);
2959 return NULL;
2961 EXPORT_SYMBOL(lock_rename);
2963 void unlock_rename(struct dentry *p1, struct dentry *p2)
2965 inode_unlock(p1->d_inode);
2966 if (p1 != p2) {
2967 inode_unlock(p2->d_inode);
2968 mutex_unlock(&p1->d_sb->s_vfs_rename_mutex);
2971 EXPORT_SYMBOL(unlock_rename);
2973 int vfs_create(struct inode *dir, struct dentry *dentry, umode_t mode,
2974 bool want_excl)
2976 int error = may_create(dir, dentry);
2977 if (error)
2978 return error;
2980 if (!dir->i_op->create)
2981 return -EACCES; /* shouldn't it be ENOSYS? */
2982 mode &= S_IALLUGO;
2983 mode |= S_IFREG;
2984 error = security_inode_create(dir, dentry, mode);
2985 if (error)
2986 return error;
2987 error = dir->i_op->create(dir, dentry, mode, want_excl);
2988 if (!error)
2989 fsnotify_create(dir, dentry);
2990 return error;
2992 EXPORT_SYMBOL(vfs_create);
2994 int vfs_mkobj(struct dentry *dentry, umode_t mode,
2995 int (*f)(struct dentry *, umode_t, void *),
2996 void *arg)
2998 struct inode *dir = dentry->d_parent->d_inode;
2999 int error = may_create(dir, dentry);
3000 if (error)
3001 return error;
3003 mode &= S_IALLUGO;
3004 mode |= S_IFREG;
3005 error = security_inode_create(dir, dentry, mode);
3006 if (error)
3007 return error;
3008 error = f(dentry, mode, arg);
3009 if (!error)
3010 fsnotify_create(dir, dentry);
3011 return error;
3013 EXPORT_SYMBOL(vfs_mkobj);
3015 bool may_open_dev(const struct path *path)
3017 return !(path->mnt->mnt_flags & MNT_NODEV) &&
3018 !(path->mnt->mnt_sb->s_iflags & SB_I_NODEV);
3021 static int may_open(const struct path *path, int acc_mode, int flag)
3023 struct dentry *dentry = path->dentry;
3024 struct inode *inode = dentry->d_inode;
3025 int error;
3027 if (!inode)
3028 return -ENOENT;
3030 switch (inode->i_mode & S_IFMT) {
3031 case S_IFLNK:
3032 return -ELOOP;
3033 case S_IFDIR:
3034 if (acc_mode & MAY_WRITE)
3035 return -EISDIR;
3036 break;
3037 case S_IFBLK:
3038 case S_IFCHR:
3039 if (!may_open_dev(path))
3040 return -EACCES;
3041 /*FALLTHRU*/
3042 case S_IFIFO:
3043 case S_IFSOCK:
3044 flag &= ~O_TRUNC;
3045 break;
3048 error = inode_permission(inode, MAY_OPEN | acc_mode);
3049 if (error)
3050 return error;
3053 * An append-only file must be opened in append mode for writing.
3055 if (IS_APPEND(inode)) {
3056 if ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND))
3057 return -EPERM;
3058 if (flag & O_TRUNC)
3059 return -EPERM;
3062 /* O_NOATIME can only be set by the owner or superuser */
3063 if (flag & O_NOATIME && !inode_owner_or_capable(inode))
3064 return -EPERM;
3066 return 0;
3069 static int handle_truncate(struct file *filp)
3071 const struct path *path = &filp->f_path;
3072 struct inode *inode = path->dentry->d_inode;
3073 int error = get_write_access(inode);
3074 if (error)
3075 return error;
3077 * Refuse to truncate files with mandatory locks held on them.
3079 error = locks_verify_locked(filp);
3080 if (!error)
3081 error = security_path_truncate(path);
3082 if (!error) {
3083 error = do_truncate(path->dentry, 0,
3084 ATTR_MTIME|ATTR_CTIME|ATTR_OPEN,
3085 filp);
3087 put_write_access(inode);
3088 return error;
3091 static inline int open_to_namei_flags(int flag)
3093 if ((flag & O_ACCMODE) == 3)
3094 flag--;
3095 return flag;
3098 static int may_o_create(const struct path *dir, struct dentry *dentry, umode_t mode)
3100 struct user_namespace *s_user_ns;
3101 int error = security_path_mknod(dir, dentry, mode, 0);
3102 if (error)
3103 return error;
3105 s_user_ns = dir->dentry->d_sb->s_user_ns;
3106 if (!kuid_has_mapping(s_user_ns, current_fsuid()) ||
3107 !kgid_has_mapping(s_user_ns, current_fsgid()))
3108 return -EOVERFLOW;
3110 error = inode_permission(dir->dentry->d_inode, MAY_WRITE | MAY_EXEC);
3111 if (error)
3112 return error;
3114 return security_inode_create(dir->dentry->d_inode, dentry, mode);
3118 * Attempt to atomically look up, create and open a file from a negative
3119 * dentry.
3121 * Returns 0 if successful. The file will have been created and attached to
3122 * @file by the filesystem calling finish_open().
3124 * If the file was looked up only or didn't need creating, FMODE_OPENED won't
3125 * be set. The caller will need to perform the open themselves. @path will
3126 * have been updated to point to the new dentry. This may be negative.
3128 * Returns an error code otherwise.
3130 static int atomic_open(struct nameidata *nd, struct dentry *dentry,
3131 struct path *path, struct file *file,
3132 const struct open_flags *op,
3133 int open_flag, umode_t mode)
3135 struct dentry *const DENTRY_NOT_SET = (void *) -1UL;
3136 struct inode *dir = nd->path.dentry->d_inode;
3137 int error;
3139 if (!(~open_flag & (O_EXCL | O_CREAT))) /* both O_EXCL and O_CREAT */
3140 open_flag &= ~O_TRUNC;
3142 if (nd->flags & LOOKUP_DIRECTORY)
3143 open_flag |= O_DIRECTORY;
3145 file->f_path.dentry = DENTRY_NOT_SET;
3146 file->f_path.mnt = nd->path.mnt;
3147 error = dir->i_op->atomic_open(dir, dentry, file,
3148 open_to_namei_flags(open_flag), mode);
3149 d_lookup_done(dentry);
3150 if (!error) {
3151 if (file->f_mode & FMODE_OPENED) {
3153 * We didn't have the inode before the open, so check open
3154 * permission here.
3156 int acc_mode = op->acc_mode;
3157 if (file->f_mode & FMODE_CREATED) {
3158 WARN_ON(!(open_flag & O_CREAT));
3159 fsnotify_create(dir, dentry);
3160 acc_mode = 0;
3162 error = may_open(&file->f_path, acc_mode, open_flag);
3163 if (WARN_ON(error > 0))
3164 error = -EINVAL;
3165 } else if (WARN_ON(file->f_path.dentry == DENTRY_NOT_SET)) {
3166 error = -EIO;
3167 } else {
3168 if (file->f_path.dentry) {
3169 dput(dentry);
3170 dentry = file->f_path.dentry;
3172 if (file->f_mode & FMODE_CREATED)
3173 fsnotify_create(dir, dentry);
3174 if (unlikely(d_is_negative(dentry))) {
3175 error = -ENOENT;
3176 } else {
3177 path->dentry = dentry;
3178 path->mnt = nd->path.mnt;
3179 return 0;
3183 dput(dentry);
3184 return error;
3188 * Look up and maybe create and open the last component.
3190 * Must be called with parent locked (exclusive in O_CREAT case).
3192 * Returns 0 on success, that is, if
3193 * the file was successfully atomically created (if necessary) and opened, or
3194 * the file was not completely opened at this time, though lookups and
3195 * creations were performed.
3196 * These case are distinguished by presence of FMODE_OPENED on file->f_mode.
3197 * In the latter case dentry returned in @path might be negative if O_CREAT
3198 * hadn't been specified.
3200 * An error code is returned on failure.
3202 static int lookup_open(struct nameidata *nd, struct path *path,
3203 struct file *file,
3204 const struct open_flags *op,
3205 bool got_write)
3207 struct dentry *dir = nd->path.dentry;
3208 struct inode *dir_inode = dir->d_inode;
3209 int open_flag = op->open_flag;
3210 struct dentry *dentry;
3211 int error, create_error = 0;
3212 umode_t mode = op->mode;
3213 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
3215 if (unlikely(IS_DEADDIR(dir_inode)))
3216 return -ENOENT;
3218 file->f_mode &= ~FMODE_CREATED;
3219 dentry = d_lookup(dir, &nd->last);
3220 for (;;) {
3221 if (!dentry) {
3222 dentry = d_alloc_parallel(dir, &nd->last, &wq);
3223 if (IS_ERR(dentry))
3224 return PTR_ERR(dentry);
3226 if (d_in_lookup(dentry))
3227 break;
3229 error = d_revalidate(dentry, nd->flags);
3230 if (likely(error > 0))
3231 break;
3232 if (error)
3233 goto out_dput;
3234 d_invalidate(dentry);
3235 dput(dentry);
3236 dentry = NULL;
3238 if (dentry->d_inode) {
3239 /* Cached positive dentry: will open in f_op->open */
3240 goto out_no_open;
3244 * Checking write permission is tricky, bacuse we don't know if we are
3245 * going to actually need it: O_CREAT opens should work as long as the
3246 * file exists. But checking existence breaks atomicity. The trick is
3247 * to check access and if not granted clear O_CREAT from the flags.
3249 * Another problem is returing the "right" error value (e.g. for an
3250 * O_EXCL open we want to return EEXIST not EROFS).
3252 if (open_flag & O_CREAT) {
3253 if (!IS_POSIXACL(dir->d_inode))
3254 mode &= ~current_umask();
3255 if (unlikely(!got_write)) {
3256 create_error = -EROFS;
3257 open_flag &= ~O_CREAT;
3258 if (open_flag & (O_EXCL | O_TRUNC))
3259 goto no_open;
3260 /* No side effects, safe to clear O_CREAT */
3261 } else {
3262 create_error = may_o_create(&nd->path, dentry, mode);
3263 if (create_error) {
3264 open_flag &= ~O_CREAT;
3265 if (open_flag & O_EXCL)
3266 goto no_open;
3269 } else if ((open_flag & (O_TRUNC|O_WRONLY|O_RDWR)) &&
3270 unlikely(!got_write)) {
3272 * No O_CREATE -> atomicity not a requirement -> fall
3273 * back to lookup + open
3275 goto no_open;
3278 if (dir_inode->i_op->atomic_open) {
3279 error = atomic_open(nd, dentry, path, file, op, open_flag,
3280 mode);
3281 if (unlikely(error == -ENOENT) && create_error)
3282 error = create_error;
3283 return error;
3286 no_open:
3287 if (d_in_lookup(dentry)) {
3288 struct dentry *res = dir_inode->i_op->lookup(dir_inode, dentry,
3289 nd->flags);
3290 d_lookup_done(dentry);
3291 if (unlikely(res)) {
3292 if (IS_ERR(res)) {
3293 error = PTR_ERR(res);
3294 goto out_dput;
3296 dput(dentry);
3297 dentry = res;
3301 /* Negative dentry, just create the file */
3302 if (!dentry->d_inode && (open_flag & O_CREAT)) {
3303 file->f_mode |= FMODE_CREATED;
3304 audit_inode_child(dir_inode, dentry, AUDIT_TYPE_CHILD_CREATE);
3305 if (!dir_inode->i_op->create) {
3306 error = -EACCES;
3307 goto out_dput;
3309 error = dir_inode->i_op->create(dir_inode, dentry, mode,
3310 open_flag & O_EXCL);
3311 if (error)
3312 goto out_dput;
3313 fsnotify_create(dir_inode, dentry);
3315 if (unlikely(create_error) && !dentry->d_inode) {
3316 error = create_error;
3317 goto out_dput;
3319 out_no_open:
3320 path->dentry = dentry;
3321 path->mnt = nd->path.mnt;
3322 return 0;
3324 out_dput:
3325 dput(dentry);
3326 return error;
3330 * Handle the last step of open()
3332 static int do_last(struct nameidata *nd,
3333 struct file *file, const struct open_flags *op)
3335 struct dentry *dir = nd->path.dentry;
3336 kuid_t dir_uid = nd->inode->i_uid;
3337 umode_t dir_mode = nd->inode->i_mode;
3338 int open_flag = op->open_flag;
3339 bool will_truncate = (open_flag & O_TRUNC) != 0;
3340 bool got_write = false;
3341 int acc_mode = op->acc_mode;
3342 unsigned seq;
3343 struct inode *inode;
3344 struct path path;
3345 int error;
3347 nd->flags &= ~LOOKUP_PARENT;
3348 nd->flags |= op->intent;
3350 if (nd->last_type != LAST_NORM) {
3351 error = handle_dots(nd, nd->last_type);
3352 if (unlikely(error))
3353 return error;
3354 goto finish_open;
3357 if (!(open_flag & O_CREAT)) {
3358 if (nd->last.name[nd->last.len])
3359 nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
3360 /* we _can_ be in RCU mode here */
3361 error = lookup_fast(nd, &path, &inode, &seq);
3362 if (likely(error > 0))
3363 goto finish_lookup;
3365 if (error < 0)
3366 return error;
3368 BUG_ON(nd->inode != dir->d_inode);
3369 BUG_ON(nd->flags & LOOKUP_RCU);
3370 } else {
3371 /* create side of things */
3373 * This will *only* deal with leaving RCU mode - LOOKUP_JUMPED
3374 * has been cleared when we got to the last component we are
3375 * about to look up
3377 error = complete_walk(nd);
3378 if (error)
3379 return error;
3381 audit_inode(nd->name, dir, AUDIT_INODE_PARENT);
3382 /* trailing slashes? */
3383 if (unlikely(nd->last.name[nd->last.len]))
3384 return -EISDIR;
3387 if (open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) {
3388 error = mnt_want_write(nd->path.mnt);
3389 if (!error)
3390 got_write = true;
3392 * do _not_ fail yet - we might not need that or fail with
3393 * a different error; let lookup_open() decide; we'll be
3394 * dropping this one anyway.
3397 if (open_flag & O_CREAT)
3398 inode_lock(dir->d_inode);
3399 else
3400 inode_lock_shared(dir->d_inode);
3401 error = lookup_open(nd, &path, file, op, got_write);
3402 if (open_flag & O_CREAT)
3403 inode_unlock(dir->d_inode);
3404 else
3405 inode_unlock_shared(dir->d_inode);
3407 if (error)
3408 goto out;
3410 if (file->f_mode & FMODE_OPENED) {
3411 if ((file->f_mode & FMODE_CREATED) ||
3412 !S_ISREG(file_inode(file)->i_mode))
3413 will_truncate = false;
3415 audit_inode(nd->name, file->f_path.dentry, 0);
3416 goto opened;
3419 if (file->f_mode & FMODE_CREATED) {
3420 /* Don't check for write permission, don't truncate */
3421 open_flag &= ~O_TRUNC;
3422 will_truncate = false;
3423 acc_mode = 0;
3424 path_to_nameidata(&path, nd);
3425 goto finish_open_created;
3429 * If atomic_open() acquired write access it is dropped now due to
3430 * possible mount and symlink following (this might be optimized away if
3431 * necessary...)
3433 if (got_write) {
3434 mnt_drop_write(nd->path.mnt);
3435 got_write = false;
3438 error = follow_managed(&path, nd);
3439 if (unlikely(error < 0))
3440 return error;
3443 * create/update audit record if it already exists.
3445 audit_inode(nd->name, path.dentry, 0);
3447 if (unlikely((open_flag & (O_EXCL | O_CREAT)) == (O_EXCL | O_CREAT))) {
3448 path_to_nameidata(&path, nd);
3449 return -EEXIST;
3452 seq = 0; /* out of RCU mode, so the value doesn't matter */
3453 inode = d_backing_inode(path.dentry);
3454 finish_lookup:
3455 error = step_into(nd, &path, 0, inode, seq);
3456 if (unlikely(error))
3457 return error;
3458 finish_open:
3459 /* Why this, you ask? _Now_ we might have grown LOOKUP_JUMPED... */
3460 error = complete_walk(nd);
3461 if (error)
3462 return error;
3463 audit_inode(nd->name, nd->path.dentry, 0);
3464 if (open_flag & O_CREAT) {
3465 error = -EISDIR;
3466 if (d_is_dir(nd->path.dentry))
3467 goto out;
3468 error = may_create_in_sticky(dir_mode, dir_uid,
3469 d_backing_inode(nd->path.dentry));
3470 if (unlikely(error))
3471 goto out;
3473 error = -ENOTDIR;
3474 if ((nd->flags & LOOKUP_DIRECTORY) && !d_can_lookup(nd->path.dentry))
3475 goto out;
3476 if (!d_is_reg(nd->path.dentry))
3477 will_truncate = false;
3479 if (will_truncate) {
3480 error = mnt_want_write(nd->path.mnt);
3481 if (error)
3482 goto out;
3483 got_write = true;
3485 finish_open_created:
3486 error = may_open(&nd->path, acc_mode, open_flag);
3487 if (error)
3488 goto out;
3489 BUG_ON(file->f_mode & FMODE_OPENED); /* once it's opened, it's opened */
3490 error = vfs_open(&nd->path, file);
3491 if (error)
3492 goto out;
3493 opened:
3494 error = ima_file_check(file, op->acc_mode);
3495 if (!error && will_truncate)
3496 error = handle_truncate(file);
3497 out:
3498 if (unlikely(error > 0)) {
3499 WARN_ON(1);
3500 error = -EINVAL;
3502 if (got_write)
3503 mnt_drop_write(nd->path.mnt);
3504 return error;
3507 struct dentry *vfs_tmpfile(struct dentry *dentry, umode_t mode, int open_flag)
3509 struct dentry *child = NULL;
3510 struct inode *dir = dentry->d_inode;
3511 struct inode *inode;
3512 int error;
3514 /* we want directory to be writable */
3515 error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
3516 if (error)
3517 goto out_err;
3518 error = -EOPNOTSUPP;
3519 if (!dir->i_op->tmpfile)
3520 goto out_err;
3521 error = -ENOMEM;
3522 child = d_alloc(dentry, &slash_name);
3523 if (unlikely(!child))
3524 goto out_err;
3525 error = dir->i_op->tmpfile(dir, child, mode);
3526 if (error)
3527 goto out_err;
3528 error = -ENOENT;
3529 inode = child->d_inode;
3530 if (unlikely(!inode))
3531 goto out_err;
3532 if (!(open_flag & O_EXCL)) {
3533 spin_lock(&inode->i_lock);
3534 inode->i_state |= I_LINKABLE;
3535 spin_unlock(&inode->i_lock);
3537 ima_post_create_tmpfile(inode);
3538 return child;
3540 out_err:
3541 dput(child);
3542 return ERR_PTR(error);
3544 EXPORT_SYMBOL(vfs_tmpfile);
3546 static int do_tmpfile(struct nameidata *nd, unsigned flags,
3547 const struct open_flags *op,
3548 struct file *file)
3550 struct dentry *child;
3551 struct path path;
3552 int error = path_lookupat(nd, flags | LOOKUP_DIRECTORY, &path);
3553 if (unlikely(error))
3554 return error;
3555 error = mnt_want_write(path.mnt);
3556 if (unlikely(error))
3557 goto out;
3558 child = vfs_tmpfile(path.dentry, op->mode, op->open_flag);
3559 error = PTR_ERR(child);
3560 if (IS_ERR(child))
3561 goto out2;
3562 dput(path.dentry);
3563 path.dentry = child;
3564 audit_inode(nd->name, child, 0);
3565 /* Don't check for other permissions, the inode was just created */
3566 error = may_open(&path, 0, op->open_flag);
3567 if (error)
3568 goto out2;
3569 file->f_path.mnt = path.mnt;
3570 error = finish_open(file, child, NULL);
3571 out2:
3572 mnt_drop_write(path.mnt);
3573 out:
3574 path_put(&path);
3575 return error;
3578 static int do_o_path(struct nameidata *nd, unsigned flags, struct file *file)
3580 struct path path;
3581 int error = path_lookupat(nd, flags, &path);
3582 if (!error) {
3583 audit_inode(nd->name, path.dentry, 0);
3584 error = vfs_open(&path, file);
3585 path_put(&path);
3587 return error;
3590 static struct file *path_openat(struct nameidata *nd,
3591 const struct open_flags *op, unsigned flags)
3593 struct file *file;
3594 int error;
3596 file = alloc_empty_file(op->open_flag, current_cred());
3597 if (IS_ERR(file))
3598 return file;
3600 if (unlikely(file->f_flags & __O_TMPFILE)) {
3601 error = do_tmpfile(nd, flags, op, file);
3602 } else if (unlikely(file->f_flags & O_PATH)) {
3603 error = do_o_path(nd, flags, file);
3604 } else {
3605 const char *s = path_init(nd, flags);
3606 while (!(error = link_path_walk(s, nd)) &&
3607 (error = do_last(nd, file, op)) > 0) {
3608 nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL);
3609 s = trailing_symlink(nd);
3611 terminate_walk(nd);
3613 if (likely(!error)) {
3614 if (likely(file->f_mode & FMODE_OPENED))
3615 return file;
3616 WARN_ON(1);
3617 error = -EINVAL;
3619 fput(file);
3620 if (error == -EOPENSTALE) {
3621 if (flags & LOOKUP_RCU)
3622 error = -ECHILD;
3623 else
3624 error = -ESTALE;
3626 return ERR_PTR(error);
3629 struct file *do_filp_open(int dfd, struct filename *pathname,
3630 const struct open_flags *op)
3632 struct nameidata nd;
3633 int flags = op->lookup_flags;
3634 struct file *filp;
3636 set_nameidata(&nd, dfd, pathname);
3637 filp = path_openat(&nd, op, flags | LOOKUP_RCU);
3638 if (unlikely(filp == ERR_PTR(-ECHILD)))
3639 filp = path_openat(&nd, op, flags);
3640 if (unlikely(filp == ERR_PTR(-ESTALE)))
3641 filp = path_openat(&nd, op, flags | LOOKUP_REVAL);
3642 restore_nameidata();
3643 return filp;
3646 struct file *do_file_open_root(struct dentry *dentry, struct vfsmount *mnt,
3647 const char *name, const struct open_flags *op)
3649 struct nameidata nd;
3650 struct file *file;
3651 struct filename *filename;
3652 int flags = op->lookup_flags | LOOKUP_ROOT;
3654 nd.root.mnt = mnt;
3655 nd.root.dentry = dentry;
3657 if (d_is_symlink(dentry) && op->intent & LOOKUP_OPEN)
3658 return ERR_PTR(-ELOOP);
3660 filename = getname_kernel(name);
3661 if (IS_ERR(filename))
3662 return ERR_CAST(filename);
3664 set_nameidata(&nd, -1, filename);
3665 file = path_openat(&nd, op, flags | LOOKUP_RCU);
3666 if (unlikely(file == ERR_PTR(-ECHILD)))
3667 file = path_openat(&nd, op, flags);
3668 if (unlikely(file == ERR_PTR(-ESTALE)))
3669 file = path_openat(&nd, op, flags | LOOKUP_REVAL);
3670 restore_nameidata();
3671 putname(filename);
3672 return file;
3675 static struct dentry *filename_create(int dfd, struct filename *name,
3676 struct path *path, unsigned int lookup_flags)
3678 struct dentry *dentry = ERR_PTR(-EEXIST);
3679 struct qstr last;
3680 int type;
3681 int err2;
3682 int error;
3683 bool is_dir = (lookup_flags & LOOKUP_DIRECTORY);
3686 * Note that only LOOKUP_REVAL and LOOKUP_DIRECTORY matter here. Any
3687 * other flags passed in are ignored!
3689 lookup_flags &= LOOKUP_REVAL;
3691 name = filename_parentat(dfd, name, lookup_flags, path, &last, &type);
3692 if (IS_ERR(name))
3693 return ERR_CAST(name);
3696 * Yucky last component or no last component at all?
3697 * (foo/., foo/.., /////)
3699 if (unlikely(type != LAST_NORM))
3700 goto out;
3702 /* don't fail immediately if it's r/o, at least try to report other errors */
3703 err2 = mnt_want_write(path->mnt);
3705 * Do the final lookup.
3707 lookup_flags |= LOOKUP_CREATE | LOOKUP_EXCL;
3708 inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
3709 dentry = __lookup_hash(&last, path->dentry, lookup_flags);
3710 if (IS_ERR(dentry))
3711 goto unlock;
3713 error = -EEXIST;
3714 if (d_is_positive(dentry))
3715 goto fail;
3718 * Special case - lookup gave negative, but... we had foo/bar/
3719 * From the vfs_mknod() POV we just have a negative dentry -
3720 * all is fine. Let's be bastards - you had / on the end, you've
3721 * been asking for (non-existent) directory. -ENOENT for you.
3723 if (unlikely(!is_dir && last.name[last.len])) {
3724 error = -ENOENT;
3725 goto fail;
3727 if (unlikely(err2)) {
3728 error = err2;
3729 goto fail;
3731 putname(name);
3732 return dentry;
3733 fail:
3734 dput(dentry);
3735 dentry = ERR_PTR(error);
3736 unlock:
3737 inode_unlock(path->dentry->d_inode);
3738 if (!err2)
3739 mnt_drop_write(path->mnt);
3740 out:
3741 path_put(path);
3742 putname(name);
3743 return dentry;
3746 struct dentry *kern_path_create(int dfd, const char *pathname,
3747 struct path *path, unsigned int lookup_flags)
3749 return filename_create(dfd, getname_kernel(pathname),
3750 path, lookup_flags);
3752 EXPORT_SYMBOL(kern_path_create);
3754 void done_path_create(struct path *path, struct dentry *dentry)
3756 dput(dentry);
3757 inode_unlock(path->dentry->d_inode);
3758 mnt_drop_write(path->mnt);
3759 path_put(path);
3761 EXPORT_SYMBOL(done_path_create);
3763 inline struct dentry *user_path_create(int dfd, const char __user *pathname,
3764 struct path *path, unsigned int lookup_flags)
3766 return filename_create(dfd, getname(pathname), path, lookup_flags);
3768 EXPORT_SYMBOL(user_path_create);
3770 int vfs_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
3772 int error = may_create(dir, dentry);
3774 if (error)
3775 return error;
3777 if ((S_ISCHR(mode) || S_ISBLK(mode)) && !capable(CAP_MKNOD))
3778 return -EPERM;
3780 if (!dir->i_op->mknod)
3781 return -EPERM;
3783 error = devcgroup_inode_mknod(mode, dev);
3784 if (error)
3785 return error;
3787 error = security_inode_mknod(dir, dentry, mode, dev);
3788 if (error)
3789 return error;
3791 error = dir->i_op->mknod(dir, dentry, mode, dev);
3792 if (!error)
3793 fsnotify_create(dir, dentry);
3794 return error;
3796 EXPORT_SYMBOL(vfs_mknod);
3798 static int may_mknod(umode_t mode)
3800 switch (mode & S_IFMT) {
3801 case S_IFREG:
3802 case S_IFCHR:
3803 case S_IFBLK:
3804 case S_IFIFO:
3805 case S_IFSOCK:
3806 case 0: /* zero mode translates to S_IFREG */
3807 return 0;
3808 case S_IFDIR:
3809 return -EPERM;
3810 default:
3811 return -EINVAL;
3815 long do_mknodat(int dfd, const char __user *filename, umode_t mode,
3816 unsigned int dev)
3818 struct dentry *dentry;
3819 struct path path;
3820 int error;
3821 unsigned int lookup_flags = 0;
3823 error = may_mknod(mode);
3824 if (error)
3825 return error;
3826 retry:
3827 dentry = user_path_create(dfd, filename, &path, lookup_flags);
3828 if (IS_ERR(dentry))
3829 return PTR_ERR(dentry);
3831 if (!IS_POSIXACL(path.dentry->d_inode))
3832 mode &= ~current_umask();
3833 error = security_path_mknod(&path, dentry, mode, dev);
3834 if (error)
3835 goto out;
3836 switch (mode & S_IFMT) {
3837 case 0: case S_IFREG:
3838 error = vfs_create(path.dentry->d_inode,dentry,mode,true);
3839 if (!error)
3840 ima_post_path_mknod(dentry);
3841 break;
3842 case S_IFCHR: case S_IFBLK:
3843 error = vfs_mknod(path.dentry->d_inode,dentry,mode,
3844 new_decode_dev(dev));
3845 break;
3846 case S_IFIFO: case S_IFSOCK:
3847 error = vfs_mknod(path.dentry->d_inode,dentry,mode,0);
3848 break;
3850 out:
3851 done_path_create(&path, dentry);
3852 if (retry_estale(error, lookup_flags)) {
3853 lookup_flags |= LOOKUP_REVAL;
3854 goto retry;
3856 return error;
3859 SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, umode_t, mode,
3860 unsigned int, dev)
3862 return do_mknodat(dfd, filename, mode, dev);
3865 SYSCALL_DEFINE3(mknod, const char __user *, filename, umode_t, mode, unsigned, dev)
3867 return do_mknodat(AT_FDCWD, filename, mode, dev);
3870 int vfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
3872 int error = may_create(dir, dentry);
3873 unsigned max_links = dir->i_sb->s_max_links;
3875 if (error)
3876 return error;
3878 if (!dir->i_op->mkdir)
3879 return -EPERM;
3881 mode &= (S_IRWXUGO|S_ISVTX);
3882 error = security_inode_mkdir(dir, dentry, mode);
3883 if (error)
3884 return error;
3886 if (max_links && dir->i_nlink >= max_links)
3887 return -EMLINK;
3889 error = dir->i_op->mkdir(dir, dentry, mode);
3890 if (!error)
3891 fsnotify_mkdir(dir, dentry);
3892 return error;
3894 EXPORT_SYMBOL(vfs_mkdir);
3896 long do_mkdirat(int dfd, const char __user *pathname, umode_t mode)
3898 struct dentry *dentry;
3899 struct path path;
3900 int error;
3901 unsigned int lookup_flags = LOOKUP_DIRECTORY;
3903 retry:
3904 dentry = user_path_create(dfd, pathname, &path, lookup_flags);
3905 if (IS_ERR(dentry))
3906 return PTR_ERR(dentry);
3908 if (!IS_POSIXACL(path.dentry->d_inode))
3909 mode &= ~current_umask();
3910 error = security_path_mkdir(&path, dentry, mode);
3911 if (!error)
3912 error = vfs_mkdir(path.dentry->d_inode, dentry, mode);
3913 done_path_create(&path, dentry);
3914 if (retry_estale(error, lookup_flags)) {
3915 lookup_flags |= LOOKUP_REVAL;
3916 goto retry;
3918 return error;
3921 SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, umode_t, mode)
3923 return do_mkdirat(dfd, pathname, mode);
3926 SYSCALL_DEFINE2(mkdir, const char __user *, pathname, umode_t, mode)
3928 return do_mkdirat(AT_FDCWD, pathname, mode);
3931 int vfs_rmdir(struct inode *dir, struct dentry *dentry)
3933 int error = may_delete(dir, dentry, 1);
3935 if (error)
3936 return error;
3938 if (!dir->i_op->rmdir)
3939 return -EPERM;
3941 dget(dentry);
3942 inode_lock(dentry->d_inode);
3944 error = -EBUSY;
3945 if (is_local_mountpoint(dentry))
3946 goto out;
3948 error = security_inode_rmdir(dir, dentry);
3949 if (error)
3950 goto out;
3952 error = dir->i_op->rmdir(dir, dentry);
3953 if (error)
3954 goto out;
3956 shrink_dcache_parent(dentry);
3957 dentry->d_inode->i_flags |= S_DEAD;
3958 dont_mount(dentry);
3959 detach_mounts(dentry);
3960 fsnotify_rmdir(dir, dentry);
3962 out:
3963 inode_unlock(dentry->d_inode);
3964 dput(dentry);
3965 if (!error)
3966 d_delete(dentry);
3967 return error;
3969 EXPORT_SYMBOL(vfs_rmdir);
3971 long do_rmdir(int dfd, const char __user *pathname)
3973 int error = 0;
3974 struct filename *name;
3975 struct dentry *dentry;
3976 struct path path;
3977 struct qstr last;
3978 int type;
3979 unsigned int lookup_flags = 0;
3980 retry:
3981 name = filename_parentat(dfd, getname(pathname), lookup_flags,
3982 &path, &last, &type);
3983 if (IS_ERR(name))
3984 return PTR_ERR(name);
3986 switch (type) {
3987 case LAST_DOTDOT:
3988 error = -ENOTEMPTY;
3989 goto exit1;
3990 case LAST_DOT:
3991 error = -EINVAL;
3992 goto exit1;
3993 case LAST_ROOT:
3994 error = -EBUSY;
3995 goto exit1;
3998 error = mnt_want_write(path.mnt);
3999 if (error)
4000 goto exit1;
4002 inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
4003 dentry = __lookup_hash(&last, path.dentry, lookup_flags);
4004 error = PTR_ERR(dentry);
4005 if (IS_ERR(dentry))
4006 goto exit2;
4007 if (!dentry->d_inode) {
4008 error = -ENOENT;
4009 goto exit3;
4011 error = security_path_rmdir(&path, dentry);
4012 if (error)
4013 goto exit3;
4014 error = vfs_rmdir(path.dentry->d_inode, dentry);
4015 exit3:
4016 dput(dentry);
4017 exit2:
4018 inode_unlock(path.dentry->d_inode);
4019 mnt_drop_write(path.mnt);
4020 exit1:
4021 path_put(&path);
4022 putname(name);
4023 if (retry_estale(error, lookup_flags)) {
4024 lookup_flags |= LOOKUP_REVAL;
4025 goto retry;
4027 return error;
4030 SYSCALL_DEFINE1(rmdir, const char __user *, pathname)
4032 return do_rmdir(AT_FDCWD, pathname);
4036 * vfs_unlink - unlink a filesystem object
4037 * @dir: parent directory
4038 * @dentry: victim
4039 * @delegated_inode: returns victim inode, if the inode is delegated.
4041 * The caller must hold dir->i_mutex.
4043 * If vfs_unlink discovers a delegation, it will return -EWOULDBLOCK and
4044 * return a reference to the inode in delegated_inode. The caller
4045 * should then break the delegation on that inode and retry. Because
4046 * breaking a delegation may take a long time, the caller should drop
4047 * dir->i_mutex before doing so.
4049 * Alternatively, a caller may pass NULL for delegated_inode. This may
4050 * be appropriate for callers that expect the underlying filesystem not
4051 * to be NFS exported.
4053 int vfs_unlink(struct inode *dir, struct dentry *dentry, struct inode **delegated_inode)
4055 struct inode *target = dentry->d_inode;
4056 int error = may_delete(dir, dentry, 0);
4058 if (error)
4059 return error;
4061 if (!dir->i_op->unlink)
4062 return -EPERM;
4064 inode_lock(target);
4065 if (is_local_mountpoint(dentry))
4066 error = -EBUSY;
4067 else {
4068 error = security_inode_unlink(dir, dentry);
4069 if (!error) {
4070 error = try_break_deleg(target, delegated_inode);
4071 if (error)
4072 goto out;
4073 error = dir->i_op->unlink(dir, dentry);
4074 if (!error) {
4075 dont_mount(dentry);
4076 detach_mounts(dentry);
4077 fsnotify_unlink(dir, dentry);
4081 out:
4082 inode_unlock(target);
4084 /* We don't d_delete() NFS sillyrenamed files--they still exist. */
4085 if (!error && !(dentry->d_flags & DCACHE_NFSFS_RENAMED)) {
4086 fsnotify_link_count(target);
4087 d_delete(dentry);
4090 return error;
4092 EXPORT_SYMBOL(vfs_unlink);
4095 * Make sure that the actual truncation of the file will occur outside its
4096 * directory's i_mutex. Truncate can take a long time if there is a lot of
4097 * writeout happening, and we don't want to prevent access to the directory
4098 * while waiting on the I/O.
4100 long do_unlinkat(int dfd, struct filename *name)
4102 int error;
4103 struct dentry *dentry;
4104 struct path path;
4105 struct qstr last;
4106 int type;
4107 struct inode *inode = NULL;
4108 struct inode *delegated_inode = NULL;
4109 unsigned int lookup_flags = 0;
4110 retry:
4111 name = filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
4112 if (IS_ERR(name))
4113 return PTR_ERR(name);
4115 error = -EISDIR;
4116 if (type != LAST_NORM)
4117 goto exit1;
4119 error = mnt_want_write(path.mnt);
4120 if (error)
4121 goto exit1;
4122 retry_deleg:
4123 inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
4124 dentry = __lookup_hash(&last, path.dentry, lookup_flags);
4125 error = PTR_ERR(dentry);
4126 if (!IS_ERR(dentry)) {
4127 /* Why not before? Because we want correct error value */
4128 if (last.name[last.len])
4129 goto slashes;
4130 inode = dentry->d_inode;
4131 if (d_is_negative(dentry))
4132 goto slashes;
4133 ihold(inode);
4134 error = security_path_unlink(&path, dentry);
4135 if (error)
4136 goto exit2;
4137 error = vfs_unlink(path.dentry->d_inode, dentry, &delegated_inode);
4138 exit2:
4139 dput(dentry);
4141 inode_unlock(path.dentry->d_inode);
4142 if (inode)
4143 iput(inode); /* truncate the inode here */
4144 inode = NULL;
4145 if (delegated_inode) {
4146 error = break_deleg_wait(&delegated_inode);
4147 if (!error)
4148 goto retry_deleg;
4150 mnt_drop_write(path.mnt);
4151 exit1:
4152 path_put(&path);
4153 if (retry_estale(error, lookup_flags)) {
4154 lookup_flags |= LOOKUP_REVAL;
4155 inode = NULL;
4156 goto retry;
4158 putname(name);
4159 return error;
4161 slashes:
4162 if (d_is_negative(dentry))
4163 error = -ENOENT;
4164 else if (d_is_dir(dentry))
4165 error = -EISDIR;
4166 else
4167 error = -ENOTDIR;
4168 goto exit2;
4171 SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag)
4173 if ((flag & ~AT_REMOVEDIR) != 0)
4174 return -EINVAL;
4176 if (flag & AT_REMOVEDIR)
4177 return do_rmdir(dfd, pathname);
4179 return do_unlinkat(dfd, getname(pathname));
4182 SYSCALL_DEFINE1(unlink, const char __user *, pathname)
4184 return do_unlinkat(AT_FDCWD, getname(pathname));
4187 int vfs_symlink(struct inode *dir, struct dentry *dentry, const char *oldname)
4189 int error = may_create(dir, dentry);
4191 if (error)
4192 return error;
4194 if (!dir->i_op->symlink)
4195 return -EPERM;
4197 error = security_inode_symlink(dir, dentry, oldname);
4198 if (error)
4199 return error;
4201 error = dir->i_op->symlink(dir, dentry, oldname);
4202 if (!error)
4203 fsnotify_create(dir, dentry);
4204 return error;
4206 EXPORT_SYMBOL(vfs_symlink);
4208 long do_symlinkat(const char __user *oldname, int newdfd,
4209 const char __user *newname)
4211 int error;
4212 struct filename *from;
4213 struct dentry *dentry;
4214 struct path path;
4215 unsigned int lookup_flags = 0;
4217 from = getname(oldname);
4218 if (IS_ERR(from))
4219 return PTR_ERR(from);
4220 retry:
4221 dentry = user_path_create(newdfd, newname, &path, lookup_flags);
4222 error = PTR_ERR(dentry);
4223 if (IS_ERR(dentry))
4224 goto out_putname;
4226 error = security_path_symlink(&path, dentry, from->name);
4227 if (!error)
4228 error = vfs_symlink(path.dentry->d_inode, dentry, from->name);
4229 done_path_create(&path, dentry);
4230 if (retry_estale(error, lookup_flags)) {
4231 lookup_flags |= LOOKUP_REVAL;
4232 goto retry;
4234 out_putname:
4235 putname(from);
4236 return error;
4239 SYSCALL_DEFINE3(symlinkat, const char __user *, oldname,
4240 int, newdfd, const char __user *, newname)
4242 return do_symlinkat(oldname, newdfd, newname);
4245 SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname)
4247 return do_symlinkat(oldname, AT_FDCWD, newname);
4251 * vfs_link - create a new link
4252 * @old_dentry: object to be linked
4253 * @dir: new parent
4254 * @new_dentry: where to create the new link
4255 * @delegated_inode: returns inode needing a delegation break
4257 * The caller must hold dir->i_mutex
4259 * If vfs_link discovers a delegation on the to-be-linked file in need
4260 * of breaking, it will return -EWOULDBLOCK and return a reference to the
4261 * inode in delegated_inode. The caller should then break the delegation
4262 * and retry. Because breaking a delegation may take a long time, the
4263 * caller should drop the i_mutex before doing so.
4265 * Alternatively, a caller may pass NULL for delegated_inode. This may
4266 * be appropriate for callers that expect the underlying filesystem not
4267 * to be NFS exported.
4269 int vfs_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry, struct inode **delegated_inode)
4271 struct inode *inode = old_dentry->d_inode;
4272 unsigned max_links = dir->i_sb->s_max_links;
4273 int error;
4275 if (!inode)
4276 return -ENOENT;
4278 error = may_create(dir, new_dentry);
4279 if (error)
4280 return error;
4282 if (dir->i_sb != inode->i_sb)
4283 return -EXDEV;
4286 * A link to an append-only or immutable file cannot be created.
4288 if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
4289 return -EPERM;
4291 * Updating the link count will likely cause i_uid and i_gid to
4292 * be writen back improperly if their true value is unknown to
4293 * the vfs.
4295 if (HAS_UNMAPPED_ID(inode))
4296 return -EPERM;
4297 if (!dir->i_op->link)
4298 return -EPERM;
4299 if (S_ISDIR(inode->i_mode))
4300 return -EPERM;
4302 error = security_inode_link(old_dentry, dir, new_dentry);
4303 if (error)
4304 return error;
4306 inode_lock(inode);
4307 /* Make sure we don't allow creating hardlink to an unlinked file */
4308 if (inode->i_nlink == 0 && !(inode->i_state & I_LINKABLE))
4309 error = -ENOENT;
4310 else if (max_links && inode->i_nlink >= max_links)
4311 error = -EMLINK;
4312 else {
4313 error = try_break_deleg(inode, delegated_inode);
4314 if (!error)
4315 error = dir->i_op->link(old_dentry, dir, new_dentry);
4318 if (!error && (inode->i_state & I_LINKABLE)) {
4319 spin_lock(&inode->i_lock);
4320 inode->i_state &= ~I_LINKABLE;
4321 spin_unlock(&inode->i_lock);
4323 inode_unlock(inode);
4324 if (!error)
4325 fsnotify_link(dir, inode, new_dentry);
4326 return error;
4328 EXPORT_SYMBOL(vfs_link);
4331 * Hardlinks are often used in delicate situations. We avoid
4332 * security-related surprises by not following symlinks on the
4333 * newname. --KAB
4335 * We don't follow them on the oldname either to be compatible
4336 * with linux 2.0, and to avoid hard-linking to directories
4337 * and other special files. --ADM
4339 int do_linkat(int olddfd, const char __user *oldname, int newdfd,
4340 const char __user *newname, int flags)
4342 struct dentry *new_dentry;
4343 struct path old_path, new_path;
4344 struct inode *delegated_inode = NULL;
4345 int how = 0;
4346 int error;
4348 if ((flags & ~(AT_SYMLINK_FOLLOW | AT_EMPTY_PATH)) != 0)
4349 return -EINVAL;
4351 * To use null names we require CAP_DAC_READ_SEARCH
4352 * This ensures that not everyone will be able to create
4353 * handlink using the passed filedescriptor.
4355 if (flags & AT_EMPTY_PATH) {
4356 if (!capable(CAP_DAC_READ_SEARCH))
4357 return -ENOENT;
4358 how = LOOKUP_EMPTY;
4361 if (flags & AT_SYMLINK_FOLLOW)
4362 how |= LOOKUP_FOLLOW;
4363 retry:
4364 error = user_path_at(olddfd, oldname, how, &old_path);
4365 if (error)
4366 return error;
4368 new_dentry = user_path_create(newdfd, newname, &new_path,
4369 (how & LOOKUP_REVAL));
4370 error = PTR_ERR(new_dentry);
4371 if (IS_ERR(new_dentry))
4372 goto out;
4374 error = -EXDEV;
4375 if (old_path.mnt != new_path.mnt)
4376 goto out_dput;
4377 error = may_linkat(&old_path);
4378 if (unlikely(error))
4379 goto out_dput;
4380 error = security_path_link(old_path.dentry, &new_path, new_dentry);
4381 if (error)
4382 goto out_dput;
4383 error = vfs_link(old_path.dentry, new_path.dentry->d_inode, new_dentry, &delegated_inode);
4384 out_dput:
4385 done_path_create(&new_path, new_dentry);
4386 if (delegated_inode) {
4387 error = break_deleg_wait(&delegated_inode);
4388 if (!error) {
4389 path_put(&old_path);
4390 goto retry;
4393 if (retry_estale(error, how)) {
4394 path_put(&old_path);
4395 how |= LOOKUP_REVAL;
4396 goto retry;
4398 out:
4399 path_put(&old_path);
4401 return error;
4404 SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname,
4405 int, newdfd, const char __user *, newname, int, flags)
4407 return do_linkat(olddfd, oldname, newdfd, newname, flags);
4410 SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname)
4412 return do_linkat(AT_FDCWD, oldname, AT_FDCWD, newname, 0);
4416 * vfs_rename - rename a filesystem object
4417 * @old_dir: parent of source
4418 * @old_dentry: source
4419 * @new_dir: parent of destination
4420 * @new_dentry: destination
4421 * @delegated_inode: returns an inode needing a delegation break
4422 * @flags: rename flags
4424 * The caller must hold multiple mutexes--see lock_rename()).
4426 * If vfs_rename discovers a delegation in need of breaking at either
4427 * the source or destination, it will return -EWOULDBLOCK and return a
4428 * reference to the inode in delegated_inode. The caller should then
4429 * break the delegation and retry. Because breaking a delegation may
4430 * take a long time, the caller should drop all locks before doing
4431 * so.
4433 * Alternatively, a caller may pass NULL for delegated_inode. This may
4434 * be appropriate for callers that expect the underlying filesystem not
4435 * to be NFS exported.
4437 * The worst of all namespace operations - renaming directory. "Perverted"
4438 * doesn't even start to describe it. Somebody in UCB had a heck of a trip...
4439 * Problems:
4441 * a) we can get into loop creation.
4442 * b) race potential - two innocent renames can create a loop together.
4443 * That's where 4.4 screws up. Current fix: serialization on
4444 * sb->s_vfs_rename_mutex. We might be more accurate, but that's another
4445 * story.
4446 * c) we have to lock _four_ objects - parents and victim (if it exists),
4447 * and source (if it is not a directory).
4448 * And that - after we got ->i_mutex on parents (until then we don't know
4449 * whether the target exists). Solution: try to be smart with locking
4450 * order for inodes. We rely on the fact that tree topology may change
4451 * only under ->s_vfs_rename_mutex _and_ that parent of the object we
4452 * move will be locked. Thus we can rank directories by the tree
4453 * (ancestors first) and rank all non-directories after them.
4454 * That works since everybody except rename does "lock parent, lookup,
4455 * lock child" and rename is under ->s_vfs_rename_mutex.
4456 * HOWEVER, it relies on the assumption that any object with ->lookup()
4457 * has no more than 1 dentry. If "hybrid" objects will ever appear,
4458 * we'd better make sure that there's no link(2) for them.
4459 * d) conversion from fhandle to dentry may come in the wrong moment - when
4460 * we are removing the target. Solution: we will have to grab ->i_mutex
4461 * in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on
4462 * ->i_mutex on parents, which works but leads to some truly excessive
4463 * locking].
4465 int vfs_rename(struct inode *old_dir, struct dentry *old_dentry,
4466 struct inode *new_dir, struct dentry *new_dentry,
4467 struct inode **delegated_inode, unsigned int flags)
4469 int error;
4470 bool is_dir = d_is_dir(old_dentry);
4471 struct inode *source = old_dentry->d_inode;
4472 struct inode *target = new_dentry->d_inode;
4473 bool new_is_dir = false;
4474 unsigned max_links = new_dir->i_sb->s_max_links;
4475 struct name_snapshot old_name;
4477 if (source == target)
4478 return 0;
4480 error = may_delete(old_dir, old_dentry, is_dir);
4481 if (error)
4482 return error;
4484 if (!target) {
4485 error = may_create(new_dir, new_dentry);
4486 } else {
4487 new_is_dir = d_is_dir(new_dentry);
4489 if (!(flags & RENAME_EXCHANGE))
4490 error = may_delete(new_dir, new_dentry, is_dir);
4491 else
4492 error = may_delete(new_dir, new_dentry, new_is_dir);
4494 if (error)
4495 return error;
4497 if (!old_dir->i_op->rename)
4498 return -EPERM;
4501 * If we are going to change the parent - check write permissions,
4502 * we'll need to flip '..'.
4504 if (new_dir != old_dir) {
4505 if (is_dir) {
4506 error = inode_permission(source, MAY_WRITE);
4507 if (error)
4508 return error;
4510 if ((flags & RENAME_EXCHANGE) && new_is_dir) {
4511 error = inode_permission(target, MAY_WRITE);
4512 if (error)
4513 return error;
4517 error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,
4518 flags);
4519 if (error)
4520 return error;
4522 take_dentry_name_snapshot(&old_name, old_dentry);
4523 dget(new_dentry);
4524 if (!is_dir || (flags & RENAME_EXCHANGE))
4525 lock_two_nondirectories(source, target);
4526 else if (target)
4527 inode_lock(target);
4529 error = -EBUSY;
4530 if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
4531 goto out;
4533 if (max_links && new_dir != old_dir) {
4534 error = -EMLINK;
4535 if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)
4536 goto out;
4537 if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&
4538 old_dir->i_nlink >= max_links)
4539 goto out;
4541 if (!is_dir) {
4542 error = try_break_deleg(source, delegated_inode);
4543 if (error)
4544 goto out;
4546 if (target && !new_is_dir) {
4547 error = try_break_deleg(target, delegated_inode);
4548 if (error)
4549 goto out;
4551 error = old_dir->i_op->rename(old_dir, old_dentry,
4552 new_dir, new_dentry, flags);
4553 if (error)
4554 goto out;
4556 if (!(flags & RENAME_EXCHANGE) && target) {
4557 if (is_dir) {
4558 shrink_dcache_parent(new_dentry);
4559 target->i_flags |= S_DEAD;
4561 dont_mount(new_dentry);
4562 detach_mounts(new_dentry);
4564 if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {
4565 if (!(flags & RENAME_EXCHANGE))
4566 d_move(old_dentry, new_dentry);
4567 else
4568 d_exchange(old_dentry, new_dentry);
4570 out:
4571 if (!is_dir || (flags & RENAME_EXCHANGE))
4572 unlock_two_nondirectories(source, target);
4573 else if (target)
4574 inode_unlock(target);
4575 dput(new_dentry);
4576 if (!error) {
4577 fsnotify_move(old_dir, new_dir, &old_name.name, is_dir,
4578 !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);
4579 if (flags & RENAME_EXCHANGE) {
4580 fsnotify_move(new_dir, old_dir, &old_dentry->d_name,
4581 new_is_dir, NULL, new_dentry);
4584 release_dentry_name_snapshot(&old_name);
4586 return error;
4588 EXPORT_SYMBOL(vfs_rename);
4590 static int do_renameat2(int olddfd, const char __user *oldname, int newdfd,
4591 const char __user *newname, unsigned int flags)
4593 struct dentry *old_dentry, *new_dentry;
4594 struct dentry *trap;
4595 struct path old_path, new_path;
4596 struct qstr old_last, new_last;
4597 int old_type, new_type;
4598 struct inode *delegated_inode = NULL;
4599 struct filename *from;
4600 struct filename *to;
4601 unsigned int lookup_flags = 0, target_flags = LOOKUP_RENAME_TARGET;
4602 bool should_retry = false;
4603 int error;
4605 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
4606 return -EINVAL;
4608 if ((flags & (RENAME_NOREPLACE | RENAME_WHITEOUT)) &&
4609 (flags & RENAME_EXCHANGE))
4610 return -EINVAL;
4612 if ((flags & RENAME_WHITEOUT) && !capable(CAP_MKNOD))
4613 return -EPERM;
4615 if (flags & RENAME_EXCHANGE)
4616 target_flags = 0;
4618 retry:
4619 from = filename_parentat(olddfd, getname(oldname), lookup_flags,
4620 &old_path, &old_last, &old_type);
4621 if (IS_ERR(from)) {
4622 error = PTR_ERR(from);
4623 goto exit;
4626 to = filename_parentat(newdfd, getname(newname), lookup_flags,
4627 &new_path, &new_last, &new_type);
4628 if (IS_ERR(to)) {
4629 error = PTR_ERR(to);
4630 goto exit1;
4633 error = -EXDEV;
4634 if (old_path.mnt != new_path.mnt)
4635 goto exit2;
4637 error = -EBUSY;
4638 if (old_type != LAST_NORM)
4639 goto exit2;
4641 if (flags & RENAME_NOREPLACE)
4642 error = -EEXIST;
4643 if (new_type != LAST_NORM)
4644 goto exit2;
4646 error = mnt_want_write(old_path.mnt);
4647 if (error)
4648 goto exit2;
4650 retry_deleg:
4651 trap = lock_rename(new_path.dentry, old_path.dentry);
4653 old_dentry = __lookup_hash(&old_last, old_path.dentry, lookup_flags);
4654 error = PTR_ERR(old_dentry);
4655 if (IS_ERR(old_dentry))
4656 goto exit3;
4657 /* source must exist */
4658 error = -ENOENT;
4659 if (d_is_negative(old_dentry))
4660 goto exit4;
4661 new_dentry = __lookup_hash(&new_last, new_path.dentry, lookup_flags | target_flags);
4662 error = PTR_ERR(new_dentry);
4663 if (IS_ERR(new_dentry))
4664 goto exit4;
4665 error = -EEXIST;
4666 if ((flags & RENAME_NOREPLACE) && d_is_positive(new_dentry))
4667 goto exit5;
4668 if (flags & RENAME_EXCHANGE) {
4669 error = -ENOENT;
4670 if (d_is_negative(new_dentry))
4671 goto exit5;
4673 if (!d_is_dir(new_dentry)) {
4674 error = -ENOTDIR;
4675 if (new_last.name[new_last.len])
4676 goto exit5;
4679 /* unless the source is a directory trailing slashes give -ENOTDIR */
4680 if (!d_is_dir(old_dentry)) {
4681 error = -ENOTDIR;
4682 if (old_last.name[old_last.len])
4683 goto exit5;
4684 if (!(flags & RENAME_EXCHANGE) && new_last.name[new_last.len])
4685 goto exit5;
4687 /* source should not be ancestor of target */
4688 error = -EINVAL;
4689 if (old_dentry == trap)
4690 goto exit5;
4691 /* target should not be an ancestor of source */
4692 if (!(flags & RENAME_EXCHANGE))
4693 error = -ENOTEMPTY;
4694 if (new_dentry == trap)
4695 goto exit5;
4697 error = security_path_rename(&old_path, old_dentry,
4698 &new_path, new_dentry, flags);
4699 if (error)
4700 goto exit5;
4701 error = vfs_rename(old_path.dentry->d_inode, old_dentry,
4702 new_path.dentry->d_inode, new_dentry,
4703 &delegated_inode, flags);
4704 exit5:
4705 dput(new_dentry);
4706 exit4:
4707 dput(old_dentry);
4708 exit3:
4709 unlock_rename(new_path.dentry, old_path.dentry);
4710 if (delegated_inode) {
4711 error = break_deleg_wait(&delegated_inode);
4712 if (!error)
4713 goto retry_deleg;
4715 mnt_drop_write(old_path.mnt);
4716 exit2:
4717 if (retry_estale(error, lookup_flags))
4718 should_retry = true;
4719 path_put(&new_path);
4720 putname(to);
4721 exit1:
4722 path_put(&old_path);
4723 putname(from);
4724 if (should_retry) {
4725 should_retry = false;
4726 lookup_flags |= LOOKUP_REVAL;
4727 goto retry;
4729 exit:
4730 return error;
4733 SYSCALL_DEFINE5(renameat2, int, olddfd, const char __user *, oldname,
4734 int, newdfd, const char __user *, newname, unsigned int, flags)
4736 return do_renameat2(olddfd, oldname, newdfd, newname, flags);
4739 SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname,
4740 int, newdfd, const char __user *, newname)
4742 return do_renameat2(olddfd, oldname, newdfd, newname, 0);
4745 SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname)
4747 return do_renameat2(AT_FDCWD, oldname, AT_FDCWD, newname, 0);
4750 int vfs_whiteout(struct inode *dir, struct dentry *dentry)
4752 int error = may_create(dir, dentry);
4753 if (error)
4754 return error;
4756 if (!dir->i_op->mknod)
4757 return -EPERM;
4759 return dir->i_op->mknod(dir, dentry,
4760 S_IFCHR | WHITEOUT_MODE, WHITEOUT_DEV);
4762 EXPORT_SYMBOL(vfs_whiteout);
4764 int readlink_copy(char __user *buffer, int buflen, const char *link)
4766 int len = PTR_ERR(link);
4767 if (IS_ERR(link))
4768 goto out;
4770 len = strlen(link);
4771 if (len > (unsigned) buflen)
4772 len = buflen;
4773 if (copy_to_user(buffer, link, len))
4774 len = -EFAULT;
4775 out:
4776 return len;
4780 * vfs_readlink - copy symlink body into userspace buffer
4781 * @dentry: dentry on which to get symbolic link
4782 * @buffer: user memory pointer
4783 * @buflen: size of buffer
4785 * Does not touch atime. That's up to the caller if necessary
4787 * Does not call security hook.
4789 int vfs_readlink(struct dentry *dentry, char __user *buffer, int buflen)
4791 struct inode *inode = d_inode(dentry);
4792 DEFINE_DELAYED_CALL(done);
4793 const char *link;
4794 int res;
4796 if (unlikely(!(inode->i_opflags & IOP_DEFAULT_READLINK))) {
4797 if (unlikely(inode->i_op->readlink))
4798 return inode->i_op->readlink(dentry, buffer, buflen);
4800 if (!d_is_symlink(dentry))
4801 return -EINVAL;
4803 spin_lock(&inode->i_lock);
4804 inode->i_opflags |= IOP_DEFAULT_READLINK;
4805 spin_unlock(&inode->i_lock);
4808 link = READ_ONCE(inode->i_link);
4809 if (!link) {
4810 link = inode->i_op->get_link(dentry, inode, &done);
4811 if (IS_ERR(link))
4812 return PTR_ERR(link);
4814 res = readlink_copy(buffer, buflen, link);
4815 do_delayed_call(&done);
4816 return res;
4818 EXPORT_SYMBOL(vfs_readlink);
4821 * vfs_get_link - get symlink body
4822 * @dentry: dentry on which to get symbolic link
4823 * @done: caller needs to free returned data with this
4825 * Calls security hook and i_op->get_link() on the supplied inode.
4827 * It does not touch atime. That's up to the caller if necessary.
4829 * Does not work on "special" symlinks like /proc/$$/fd/N
4831 const char *vfs_get_link(struct dentry *dentry, struct delayed_call *done)
4833 const char *res = ERR_PTR(-EINVAL);
4834 struct inode *inode = d_inode(dentry);
4836 if (d_is_symlink(dentry)) {
4837 res = ERR_PTR(security_inode_readlink(dentry));
4838 if (!res)
4839 res = inode->i_op->get_link(dentry, inode, done);
4841 return res;
4843 EXPORT_SYMBOL(vfs_get_link);
4845 /* get the link contents into pagecache */
4846 const char *page_get_link(struct dentry *dentry, struct inode *inode,
4847 struct delayed_call *callback)
4849 char *kaddr;
4850 struct page *page;
4851 struct address_space *mapping = inode->i_mapping;
4853 if (!dentry) {
4854 page = find_get_page(mapping, 0);
4855 if (!page)
4856 return ERR_PTR(-ECHILD);
4857 if (!PageUptodate(page)) {
4858 put_page(page);
4859 return ERR_PTR(-ECHILD);
4861 } else {
4862 page = read_mapping_page(mapping, 0, NULL);
4863 if (IS_ERR(page))
4864 return (char*)page;
4866 set_delayed_call(callback, page_put_link, page);
4867 BUG_ON(mapping_gfp_mask(mapping) & __GFP_HIGHMEM);
4868 kaddr = page_address(page);
4869 nd_terminate_link(kaddr, inode->i_size, PAGE_SIZE - 1);
4870 return kaddr;
4873 EXPORT_SYMBOL(page_get_link);
4875 void page_put_link(void *arg)
4877 put_page(arg);
4879 EXPORT_SYMBOL(page_put_link);
4881 int page_readlink(struct dentry *dentry, char __user *buffer, int buflen)
4883 DEFINE_DELAYED_CALL(done);
4884 int res = readlink_copy(buffer, buflen,
4885 page_get_link(dentry, d_inode(dentry),
4886 &done));
4887 do_delayed_call(&done);
4888 return res;
4890 EXPORT_SYMBOL(page_readlink);
4893 * The nofs argument instructs pagecache_write_begin to pass AOP_FLAG_NOFS
4895 int __page_symlink(struct inode *inode, const char *symname, int len, int nofs)
4897 struct address_space *mapping = inode->i_mapping;
4898 struct page *page;
4899 void *fsdata;
4900 int err;
4901 unsigned int flags = 0;
4902 if (nofs)
4903 flags |= AOP_FLAG_NOFS;
4905 retry:
4906 err = pagecache_write_begin(NULL, mapping, 0, len-1,
4907 flags, &page, &fsdata);
4908 if (err)
4909 goto fail;
4911 memcpy(page_address(page), symname, len-1);
4913 err = pagecache_write_end(NULL, mapping, 0, len-1, len-1,
4914 page, fsdata);
4915 if (err < 0)
4916 goto fail;
4917 if (err < len-1)
4918 goto retry;
4920 mark_inode_dirty(inode);
4921 return 0;
4922 fail:
4923 return err;
4925 EXPORT_SYMBOL(__page_symlink);
4927 int page_symlink(struct inode *inode, const char *symname, int len)
4929 return __page_symlink(inode, symname, len,
4930 !mapping_gfp_constraint(inode->i_mapping, __GFP_FS));
4932 EXPORT_SYMBOL(page_symlink);
4934 const struct inode_operations page_symlink_inode_operations = {
4935 .get_link = page_get_link,
4937 EXPORT_SYMBOL(page_symlink_inode_operations);