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