OSDN Git Service

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