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