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