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