OSDN Git Service

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