OSDN Git Service

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