OSDN Git Service

vfs: fix race in rcu lookup of pruned dentry
[android-x86/kernel.git] / fs / namei.c
1 /*
2  *  linux/fs/namei.c
3  *
4  *  Copyright (C) 1991, 1992  Linus Torvalds
5  */
6
7 /*
8  * Some corrections by tytso.
9  */
10
11 /* [Feb 1997 T. Schoebel-Theuer] Complete rewrite of the pathname
12  * lookup logic.
13  */
14 /* [Feb-Apr 2000, AV] Rewrite to the new namespace architecture.
15  */
16
17 #include <linux/init.h>
18 #include <linux/module.h>
19 #include <linux/slab.h>
20 #include <linux/fs.h>
21 #include <linux/namei.h>
22 #include <linux/pagemap.h>
23 #include <linux/fsnotify.h>
24 #include <linux/personality.h>
25 #include <linux/security.h>
26 #include <linux/ima.h>
27 #include <linux/syscalls.h>
28 #include <linux/mount.h>
29 #include <linux/audit.h>
30 #include <linux/capability.h>
31 #include <linux/file.h>
32 #include <linux/fcntl.h>
33 #include <linux/device_cgroup.h>
34 #include <linux/fs_struct.h>
35 #include <asm/uaccess.h>
36
37 #include "internal.h"
38
39 /* [Feb-1997 T. Schoebel-Theuer]
40  * Fundamental changes in the pathname lookup mechanisms (namei)
41  * were necessary because of omirr.  The reason is that omirr needs
42  * to know the _real_ pathname, not the user-supplied one, in case
43  * of symlinks (and also when transname replacements occur).
44  *
45  * The new code replaces the old recursive symlink resolution with
46  * an iterative one (in case of non-nested symlink chains).  It does
47  * this with calls to <fs>_follow_link().
48  * As a side effect, dir_namei(), _namei() and follow_link() are now 
49  * replaced with a single function lookup_dentry() that can handle all 
50  * the special cases of the former code.
51  *
52  * With the new dcache, the pathname is stored at each inode, at least as
53  * long as the refcount of the inode is positive.  As a side effect, the
54  * size of the dcache depends on the inode cache and thus is dynamic.
55  *
56  * [29-Apr-1998 C. Scott Ananian] Updated above description of symlink
57  * resolution to correspond with current state of the code.
58  *
59  * Note that the symlink resolution is not *completely* iterative.
60  * There is still a significant amount of tail- and mid- recursion in
61  * the algorithm.  Also, note that <fs>_readlink() is not used in
62  * lookup_dentry(): lookup_dentry() on the result of <fs>_readlink()
63  * may return different results than <fs>_follow_link().  Many virtual
64  * filesystems (including /proc) exhibit this behavior.
65  */
66
67 /* [24-Feb-97 T. Schoebel-Theuer] Side effects caused by new implementation:
68  * New symlink semantics: when open() is called with flags O_CREAT | O_EXCL
69  * and the name already exists in form of a symlink, try to create the new
70  * name indicated by the symlink. The old code always complained that the
71  * name already exists, due to not following the symlink even if its target
72  * is nonexistent.  The new semantics affects also mknod() and link() when
73  * the name is a symlink pointing to a non-existent name.
74  *
75  * I don't know which semantics is the right one, since I have no access
76  * to standards. But I found by trial that HP-UX 9.0 has the full "new"
77  * semantics implemented, while SunOS 4.1.1 and Solaris (SunOS 5.4) have the
78  * "old" one. Personally, I think the new semantics is much more logical.
79  * Note that "ln old new" where "new" is a symlink pointing to a non-existing
80  * file does succeed in both HP-UX and SunOs, but not in Solaris
81  * and in the old Linux semantics.
82  */
83
84 /* [16-Dec-97 Kevin Buhr] For security reasons, we change some symlink
85  * semantics.  See the comments in "open_namei" and "do_link" below.
86  *
87  * [10-Sep-98 Alan Modra] Another symlink change.
88  */
89
90 /* [Feb-Apr 2000 AV] Complete rewrite. Rules for symlinks:
91  *      inside the path - always follow.
92  *      in the last component in creation/removal/renaming - never follow.
93  *      if LOOKUP_FOLLOW passed - follow.
94  *      if the pathname has trailing slashes - follow.
95  *      otherwise - don't follow.
96  * (applied in that order).
97  *
98  * [Jun 2000 AV] Inconsistent behaviour of open() in case if flags==O_CREAT
99  * restored for 2.4. This is the last surviving part of old 4.2BSD bug.
100  * During the 2.4 we need to fix the userland stuff depending on it -
101  * hopefully we will be able to get rid of that wart in 2.5. So far only
102  * XEmacs seems to be relying on it...
103  */
104 /*
105  * [Sep 2001 AV] Single-semaphore locking scheme (kudos to David Holland)
106  * implemented.  Let's see if raised priority of ->s_vfs_rename_mutex gives
107  * any extra contention...
108  */
109
110 /* In order to reduce some races, while at the same time doing additional
111  * checking and hopefully speeding things up, we copy filenames to the
112  * kernel data space before using them..
113  *
114  * POSIX.1 2.4: an empty pathname is invalid (ENOENT).
115  * PATH_MAX includes the nul terminator --RR.
116  */
117 static int do_getname(const char __user *filename, char *page)
118 {
119         int retval;
120         unsigned long len = PATH_MAX;
121
122         if (!segment_eq(get_fs(), KERNEL_DS)) {
123                 if ((unsigned long) filename >= TASK_SIZE)
124                         return -EFAULT;
125                 if (TASK_SIZE - (unsigned long) filename < PATH_MAX)
126                         len = TASK_SIZE - (unsigned long) filename;
127         }
128
129         retval = strncpy_from_user(page, filename, len);
130         if (retval > 0) {
131                 if (retval < len)
132                         return 0;
133                 return -ENAMETOOLONG;
134         } else if (!retval)
135                 retval = -ENOENT;
136         return retval;
137 }
138
139 static char *getname_flags(const char __user * filename, int flags)
140 {
141         char *tmp, *result;
142
143         result = ERR_PTR(-ENOMEM);
144         tmp = __getname();
145         if (tmp)  {
146                 int retval = do_getname(filename, tmp);
147
148                 result = tmp;
149                 if (retval < 0) {
150                         if (retval != -ENOENT || !(flags & LOOKUP_EMPTY)) {
151                                 __putname(tmp);
152                                 result = ERR_PTR(retval);
153                         }
154                 }
155         }
156         audit_getname(result);
157         return result;
158 }
159
160 char *getname(const char __user * filename)
161 {
162         return getname_flags(filename, 0);
163 }
164
165 #ifdef CONFIG_AUDITSYSCALL
166 void putname(const char *name)
167 {
168         if (unlikely(!audit_dummy_context()))
169                 audit_putname(name);
170         else
171                 __putname(name);
172 }
173 EXPORT_SYMBOL(putname);
174 #endif
175
176 /*
177  * This does basic POSIX ACL permission checking
178  */
179 static int acl_permission_check(struct inode *inode, int mask, unsigned int flags,
180                 int (*check_acl)(struct inode *inode, int mask, unsigned int flags))
181 {
182         unsigned int mode = inode->i_mode;
183
184         mask &= MAY_READ | MAY_WRITE | MAY_EXEC;
185
186         if (current_user_ns() != inode_userns(inode))
187                 goto other_perms;
188
189         if (current_fsuid() == inode->i_uid)
190                 mode >>= 6;
191         else {
192                 if (IS_POSIXACL(inode) && (mode & S_IRWXG) && check_acl) {
193                         int error = check_acl(inode, mask, flags);
194                         if (error != -EAGAIN)
195                                 return error;
196                 }
197
198                 if (in_group_p(inode->i_gid))
199                         mode >>= 3;
200         }
201
202 other_perms:
203         /*
204          * If the DACs are ok we don't need any capability check.
205          */
206         if ((mask & ~mode) == 0)
207                 return 0;
208         return -EACCES;
209 }
210
211 /**
212  * generic_permission -  check for access rights on a Posix-like filesystem
213  * @inode:      inode to check access rights for
214  * @mask:       right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
215  * @check_acl:  optional callback to check for Posix ACLs
216  * @flags:      IPERM_FLAG_ flags.
217  *
218  * Used to check for read/write/execute permissions on a file.
219  * We use "fsuid" for this, letting us set arbitrary permissions
220  * for filesystem access without changing the "normal" uids which
221  * are used for other things.
222  *
223  * generic_permission is rcu-walk aware. It returns -ECHILD in case an rcu-walk
224  * request cannot be satisfied (eg. requires blocking or too much complexity).
225  * It would then be called again in ref-walk mode.
226  */
227 int generic_permission(struct inode *inode, int mask, unsigned int flags,
228         int (*check_acl)(struct inode *inode, int mask, unsigned int flags))
229 {
230         int ret;
231
232         /*
233          * Do the basic POSIX ACL permission checks.
234          */
235         ret = acl_permission_check(inode, mask, flags, check_acl);
236         if (ret != -EACCES)
237                 return ret;
238
239         /*
240          * Read/write DACs are always overridable.
241          * Executable DACs are overridable if at least one exec bit is set.
242          */
243         if (!(mask & MAY_EXEC) || execute_ok(inode))
244                 if (ns_capable(inode_userns(inode), CAP_DAC_OVERRIDE))
245                         return 0;
246
247         /*
248          * Searching includes executable on directories, else just read.
249          */
250         mask &= MAY_READ | MAY_WRITE | MAY_EXEC;
251         if (mask == MAY_READ || (S_ISDIR(inode->i_mode) && !(mask & MAY_WRITE)))
252                 if (ns_capable(inode_userns(inode), CAP_DAC_READ_SEARCH))
253                         return 0;
254
255         return -EACCES;
256 }
257
258 /**
259  * inode_permission  -  check for access rights to a given inode
260  * @inode:      inode to check permission on
261  * @mask:       right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
262  *
263  * Used to check for read/write/execute permissions on an inode.
264  * We use "fsuid" for this, letting us set arbitrary permissions
265  * for filesystem access without changing the "normal" uids which
266  * are used for other things.
267  */
268 int inode_permission(struct inode *inode, int mask)
269 {
270         int retval;
271
272         if (mask & MAY_WRITE) {
273                 umode_t mode = inode->i_mode;
274
275                 /*
276                  * Nobody gets write access to a read-only fs.
277                  */
278                 if (IS_RDONLY(inode) &&
279                     (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode)))
280                         return -EROFS;
281
282                 /*
283                  * Nobody gets write access to an immutable file.
284                  */
285                 if (IS_IMMUTABLE(inode))
286                         return -EACCES;
287         }
288
289         if (inode->i_op->permission)
290                 retval = inode->i_op->permission(inode, mask, 0);
291         else
292                 retval = generic_permission(inode, mask, 0,
293                                 inode->i_op->check_acl);
294
295         if (retval)
296                 return retval;
297
298         retval = devcgroup_inode_permission(inode, mask);
299         if (retval)
300                 return retval;
301
302         return security_inode_permission(inode, mask);
303 }
304
305 /**
306  * file_permission  -  check for additional access rights to a given file
307  * @file:       file to check access rights for
308  * @mask:       right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
309  *
310  * Used to check for read/write/execute permissions on an already opened
311  * file.
312  *
313  * Note:
314  *      Do not use this function in new code.  All access checks should
315  *      be done using inode_permission().
316  */
317 int file_permission(struct file *file, int mask)
318 {
319         return inode_permission(file->f_path.dentry->d_inode, mask);
320 }
321
322 /*
323  * get_write_access() gets write permission for a file.
324  * put_write_access() releases this write permission.
325  * This is used for regular files.
326  * We cannot support write (and maybe mmap read-write shared) accesses and
327  * MAP_DENYWRITE mmappings simultaneously. The i_writecount field of an inode
328  * can have the following values:
329  * 0: no writers, no VM_DENYWRITE mappings
330  * < 0: (-i_writecount) vm_area_structs with VM_DENYWRITE set exist
331  * > 0: (i_writecount) users are writing to the file.
332  *
333  * Normally we operate on that counter with atomic_{inc,dec} and it's safe
334  * except for the cases where we don't hold i_writecount yet. Then we need to
335  * use {get,deny}_write_access() - these functions check the sign and refuse
336  * to do the change if sign is wrong. Exclusion between them is provided by
337  * the inode->i_lock spinlock.
338  */
339
340 int get_write_access(struct inode * inode)
341 {
342         spin_lock(&inode->i_lock);
343         if (atomic_read(&inode->i_writecount) < 0) {
344                 spin_unlock(&inode->i_lock);
345                 return -ETXTBSY;
346         }
347         atomic_inc(&inode->i_writecount);
348         spin_unlock(&inode->i_lock);
349
350         return 0;
351 }
352
353 int deny_write_access(struct file * file)
354 {
355         struct inode *inode = file->f_path.dentry->d_inode;
356
357         spin_lock(&inode->i_lock);
358         if (atomic_read(&inode->i_writecount) > 0) {
359                 spin_unlock(&inode->i_lock);
360                 return -ETXTBSY;
361         }
362         atomic_dec(&inode->i_writecount);
363         spin_unlock(&inode->i_lock);
364
365         return 0;
366 }
367
368 /**
369  * path_get - get a reference to a path
370  * @path: path to get the reference to
371  *
372  * Given a path increment the reference count to the dentry and the vfsmount.
373  */
374 void path_get(struct path *path)
375 {
376         mntget(path->mnt);
377         dget(path->dentry);
378 }
379 EXPORT_SYMBOL(path_get);
380
381 /**
382  * path_put - put a reference to a path
383  * @path: path to put the reference to
384  *
385  * Given a path decrement the reference count to the dentry and the vfsmount.
386  */
387 void path_put(struct path *path)
388 {
389         dput(path->dentry);
390         mntput(path->mnt);
391 }
392 EXPORT_SYMBOL(path_put);
393
394 /**
395  * nameidata_drop_rcu - drop this nameidata out of rcu-walk
396  * @nd: nameidata pathwalk data to drop
397  * Returns: 0 on success, -ECHILD on failure
398  *
399  * Path walking has 2 modes, rcu-walk and ref-walk (see
400  * Documentation/filesystems/path-lookup.txt). __drop_rcu* functions attempt
401  * to drop out of rcu-walk mode and take normal reference counts on dentries
402  * and vfsmounts to transition to rcu-walk mode. __drop_rcu* functions take
403  * refcounts at the last known good point before rcu-walk got stuck, so
404  * ref-walk may continue from there. If this is not successful (eg. a seqcount
405  * has changed), then failure is returned and path walk restarts from the
406  * beginning in ref-walk mode.
407  *
408  * nameidata_drop_rcu attempts to drop the current nd->path and nd->root into
409  * ref-walk. Must be called from rcu-walk context.
410  */
411 static int nameidata_drop_rcu(struct nameidata *nd)
412 {
413         struct fs_struct *fs = current->fs;
414         struct dentry *dentry = nd->path.dentry;
415         int want_root = 0;
416
417         BUG_ON(!(nd->flags & LOOKUP_RCU));
418         if (nd->root.mnt && !(nd->flags & LOOKUP_ROOT)) {
419                 want_root = 1;
420                 spin_lock(&fs->lock);
421                 if (nd->root.mnt != fs->root.mnt ||
422                                 nd->root.dentry != fs->root.dentry)
423                         goto err_root;
424         }
425         spin_lock(&dentry->d_lock);
426         if (!__d_rcu_to_refcount(dentry, nd->seq))
427                 goto err;
428         BUG_ON(nd->inode != dentry->d_inode);
429         spin_unlock(&dentry->d_lock);
430         if (want_root) {
431                 path_get(&nd->root);
432                 spin_unlock(&fs->lock);
433         }
434         mntget(nd->path.mnt);
435
436         rcu_read_unlock();
437         br_read_unlock(vfsmount_lock);
438         nd->flags &= ~LOOKUP_RCU;
439         return 0;
440 err:
441         spin_unlock(&dentry->d_lock);
442 err_root:
443         if (want_root)
444                 spin_unlock(&fs->lock);
445         return -ECHILD;
446 }
447
448 /* Try to drop out of rcu-walk mode if we were in it, otherwise do nothing.  */
449 static inline int nameidata_drop_rcu_maybe(struct nameidata *nd)
450 {
451         if (nd->flags & LOOKUP_RCU)
452                 return nameidata_drop_rcu(nd);
453         return 0;
454 }
455
456 /**
457  * nameidata_dentry_drop_rcu - drop nameidata and dentry out of rcu-walk
458  * @nd: nameidata pathwalk data to drop
459  * @dentry: dentry to drop
460  * Returns: 0 on success, -ECHILD on failure
461  *
462  * nameidata_dentry_drop_rcu attempts to drop the current nd->path and nd->root,
463  * and dentry into ref-walk. @dentry must be a path found by a do_lookup call on
464  * @nd. Must be called from rcu-walk context.
465  */
466 static int nameidata_dentry_drop_rcu(struct nameidata *nd, struct dentry *dentry)
467 {
468         struct fs_struct *fs = current->fs;
469         struct dentry *parent = nd->path.dentry;
470         int want_root = 0;
471
472         BUG_ON(!(nd->flags & LOOKUP_RCU));
473         if (nd->root.mnt && !(nd->flags & LOOKUP_ROOT)) {
474                 want_root = 1;
475                 spin_lock(&fs->lock);
476                 if (nd->root.mnt != fs->root.mnt ||
477                                 nd->root.dentry != fs->root.dentry)
478                         goto err_root;
479         }
480         spin_lock(&parent->d_lock);
481         spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
482         if (!__d_rcu_to_refcount(dentry, nd->seq))
483                 goto err;
484         /*
485          * If the sequence check on the child dentry passed, then the child has
486          * not been removed from its parent. This means the parent dentry must
487          * be valid and able to take a reference at this point.
488          */
489         BUG_ON(!IS_ROOT(dentry) && dentry->d_parent != parent);
490         BUG_ON(!parent->d_count);
491         parent->d_count++;
492         spin_unlock(&dentry->d_lock);
493         spin_unlock(&parent->d_lock);
494         if (want_root) {
495                 path_get(&nd->root);
496                 spin_unlock(&fs->lock);
497         }
498         mntget(nd->path.mnt);
499
500         rcu_read_unlock();
501         br_read_unlock(vfsmount_lock);
502         nd->flags &= ~LOOKUP_RCU;
503         return 0;
504 err:
505         spin_unlock(&dentry->d_lock);
506         spin_unlock(&parent->d_lock);
507 err_root:
508         if (want_root)
509                 spin_unlock(&fs->lock);
510         return -ECHILD;
511 }
512
513 /* Try to drop out of rcu-walk mode if we were in it, otherwise do nothing.  */
514 static inline int nameidata_dentry_drop_rcu_maybe(struct nameidata *nd, struct dentry *dentry)
515 {
516         if (nd->flags & LOOKUP_RCU) {
517                 if (unlikely(nameidata_dentry_drop_rcu(nd, dentry))) {
518                         nd->flags &= ~LOOKUP_RCU;
519                         if (!(nd->flags & LOOKUP_ROOT))
520                                 nd->root.mnt = NULL;
521                         rcu_read_unlock();
522                         br_read_unlock(vfsmount_lock);
523                         return -ECHILD;
524                 }
525         }
526         return 0;
527 }
528
529 /**
530  * nameidata_drop_rcu_last - drop nameidata ending path walk out of rcu-walk
531  * @nd: nameidata pathwalk data to drop
532  * Returns: 0 on success, -ECHILD on failure
533  *
534  * nameidata_drop_rcu_last attempts to drop the current nd->path into ref-walk.
535  * nd->path should be the final element of the lookup, so nd->root is discarded.
536  * Must be called from rcu-walk context.
537  */
538 static int nameidata_drop_rcu_last(struct nameidata *nd)
539 {
540         struct dentry *dentry = nd->path.dentry;
541
542         BUG_ON(!(nd->flags & LOOKUP_RCU));
543         nd->flags &= ~LOOKUP_RCU;
544         if (!(nd->flags & LOOKUP_ROOT))
545                 nd->root.mnt = NULL;
546         spin_lock(&dentry->d_lock);
547         if (!__d_rcu_to_refcount(dentry, nd->seq))
548                 goto err_unlock;
549         BUG_ON(nd->inode != dentry->d_inode);
550         spin_unlock(&dentry->d_lock);
551
552         mntget(nd->path.mnt);
553
554         rcu_read_unlock();
555         br_read_unlock(vfsmount_lock);
556
557         return 0;
558
559 err_unlock:
560         spin_unlock(&dentry->d_lock);
561         rcu_read_unlock();
562         br_read_unlock(vfsmount_lock);
563         return -ECHILD;
564 }
565
566 /**
567  * release_open_intent - free up open intent resources
568  * @nd: pointer to nameidata
569  */
570 void release_open_intent(struct nameidata *nd)
571 {
572         struct file *file = nd->intent.open.file;
573
574         if (file && !IS_ERR(file)) {
575                 if (file->f_path.dentry == NULL)
576                         put_filp(file);
577                 else
578                         fput(file);
579         }
580 }
581
582 static inline int d_revalidate(struct dentry *dentry, struct nameidata *nd)
583 {
584         return dentry->d_op->d_revalidate(dentry, nd);
585 }
586
587 static struct dentry *
588 do_revalidate(struct dentry *dentry, struct nameidata *nd)
589 {
590         int status = d_revalidate(dentry, nd);
591         if (unlikely(status <= 0)) {
592                 /*
593                  * The dentry failed validation.
594                  * If d_revalidate returned 0 attempt to invalidate
595                  * the dentry otherwise d_revalidate is asking us
596                  * to return a fail status.
597                  */
598                 if (status < 0) {
599                         dput(dentry);
600                         dentry = ERR_PTR(status);
601                 } else if (!d_invalidate(dentry)) {
602                         dput(dentry);
603                         dentry = NULL;
604                 }
605         }
606         return dentry;
607 }
608
609 /*
610  * handle_reval_path - force revalidation of a dentry
611  *
612  * In some situations the path walking code will trust dentries without
613  * revalidating them. This causes problems for filesystems that depend on
614  * d_revalidate to handle file opens (e.g. NFSv4). When FS_REVAL_DOT is set
615  * (which indicates that it's possible for the dentry to go stale), force
616  * a d_revalidate call before proceeding.
617  *
618  * Returns 0 if the revalidation was successful. If the revalidation fails,
619  * either return the error returned by d_revalidate or -ESTALE if the
620  * revalidation it just returned 0. If d_revalidate returns 0, we attempt to
621  * invalidate the dentry. It's up to the caller to handle putting references
622  * to the path if necessary.
623  */
624 static inline int handle_reval_path(struct nameidata *nd)
625 {
626         struct dentry *dentry = nd->path.dentry;
627         int status;
628
629         if (likely(!(nd->flags & LOOKUP_JUMPED)))
630                 return 0;
631
632         if (likely(!(dentry->d_flags & DCACHE_OP_REVALIDATE)))
633                 return 0;
634
635         if (likely(!(dentry->d_sb->s_type->fs_flags & FS_REVAL_DOT)))
636                 return 0;
637
638         /* Note: we do not d_invalidate() */
639         status = d_revalidate(dentry, nd);
640         if (status > 0)
641                 return 0;
642
643         if (!status)
644                 status = -ESTALE;
645
646         return status;
647 }
648
649 /*
650  * Short-cut version of permission(), for calling on directories
651  * during pathname resolution.  Combines parts of permission()
652  * and generic_permission(), and tests ONLY for MAY_EXEC permission.
653  *
654  * If appropriate, check DAC only.  If not appropriate, or
655  * short-cut DAC fails, then call ->permission() to do more
656  * complete permission check.
657  */
658 static inline int exec_permission(struct inode *inode, unsigned int flags)
659 {
660         int ret;
661         struct user_namespace *ns = inode_userns(inode);
662
663         if (inode->i_op->permission) {
664                 ret = inode->i_op->permission(inode, MAY_EXEC, flags);
665         } else {
666                 ret = acl_permission_check(inode, MAY_EXEC, flags,
667                                 inode->i_op->check_acl);
668         }
669         if (likely(!ret))
670                 goto ok;
671         if (ret == -ECHILD)
672                 return ret;
673
674         if (ns_capable(ns, CAP_DAC_OVERRIDE) ||
675                         ns_capable(ns, CAP_DAC_READ_SEARCH))
676                 goto ok;
677
678         return ret;
679 ok:
680         return security_inode_exec_permission(inode, flags);
681 }
682
683 static __always_inline void set_root(struct nameidata *nd)
684 {
685         if (!nd->root.mnt)
686                 get_fs_root(current->fs, &nd->root);
687 }
688
689 static int link_path_walk(const char *, struct nameidata *);
690
691 static __always_inline void set_root_rcu(struct nameidata *nd)
692 {
693         if (!nd->root.mnt) {
694                 struct fs_struct *fs = current->fs;
695                 unsigned seq;
696
697                 do {
698                         seq = read_seqcount_begin(&fs->seq);
699                         nd->root = fs->root;
700                         nd->seq = __read_seqcount_begin(&nd->root.dentry->d_seq);
701                 } while (read_seqcount_retry(&fs->seq, seq));
702         }
703 }
704
705 static __always_inline int __vfs_follow_link(struct nameidata *nd, const char *link)
706 {
707         int ret;
708
709         if (IS_ERR(link))
710                 goto fail;
711
712         if (*link == '/') {
713                 set_root(nd);
714                 path_put(&nd->path);
715                 nd->path = nd->root;
716                 path_get(&nd->root);
717                 nd->flags |= LOOKUP_JUMPED;
718         }
719         nd->inode = nd->path.dentry->d_inode;
720
721         ret = link_path_walk(link, nd);
722         return ret;
723 fail:
724         path_put(&nd->path);
725         return PTR_ERR(link);
726 }
727
728 static void path_put_conditional(struct path *path, struct nameidata *nd)
729 {
730         dput(path->dentry);
731         if (path->mnt != nd->path.mnt)
732                 mntput(path->mnt);
733 }
734
735 static inline void path_to_nameidata(const struct path *path,
736                                         struct nameidata *nd)
737 {
738         if (!(nd->flags & LOOKUP_RCU)) {
739                 dput(nd->path.dentry);
740                 if (nd->path.mnt != path->mnt)
741                         mntput(nd->path.mnt);
742         }
743         nd->path.mnt = path->mnt;
744         nd->path.dentry = path->dentry;
745 }
746
747 static inline void put_link(struct nameidata *nd, struct path *link, void *cookie)
748 {
749         struct inode *inode = link->dentry->d_inode;
750         if (!IS_ERR(cookie) && inode->i_op->put_link)
751                 inode->i_op->put_link(link->dentry, nd, cookie);
752         path_put(link);
753 }
754
755 static __always_inline int
756 follow_link(struct path *link, struct nameidata *nd, void **p)
757 {
758         int error;
759         struct dentry *dentry = link->dentry;
760
761         BUG_ON(nd->flags & LOOKUP_RCU);
762
763         if (link->mnt == nd->path.mnt)
764                 mntget(link->mnt);
765
766         if (unlikely(current->total_link_count >= 40)) {
767                 *p = ERR_PTR(-ELOOP); /* no ->put_link(), please */
768                 path_put(&nd->path);
769                 return -ELOOP;
770         }
771         cond_resched();
772         current->total_link_count++;
773
774         touch_atime(link->mnt, dentry);
775         nd_set_link(nd, NULL);
776
777         error = security_inode_follow_link(link->dentry, nd);
778         if (error) {
779                 *p = ERR_PTR(error); /* no ->put_link(), please */
780                 path_put(&nd->path);
781                 return error;
782         }
783
784         nd->last_type = LAST_BIND;
785         *p = dentry->d_inode->i_op->follow_link(dentry, nd);
786         error = PTR_ERR(*p);
787         if (!IS_ERR(*p)) {
788                 char *s = nd_get_link(nd);
789                 error = 0;
790                 if (s)
791                         error = __vfs_follow_link(nd, s);
792                 else if (nd->last_type == LAST_BIND) {
793                         nd->flags |= LOOKUP_JUMPED;
794                         nd->inode = nd->path.dentry->d_inode;
795                         if (nd->inode->i_op->follow_link) {
796                                 /* stepped on a _really_ weird one */
797                                 path_put(&nd->path);
798                                 error = -ELOOP;
799                         }
800                 }
801         }
802         return error;
803 }
804
805 static int follow_up_rcu(struct path *path)
806 {
807         struct vfsmount *parent;
808         struct dentry *mountpoint;
809
810         parent = path->mnt->mnt_parent;
811         if (parent == path->mnt)
812                 return 0;
813         mountpoint = path->mnt->mnt_mountpoint;
814         path->dentry = mountpoint;
815         path->mnt = parent;
816         return 1;
817 }
818
819 int follow_up(struct path *path)
820 {
821         struct vfsmount *parent;
822         struct dentry *mountpoint;
823
824         br_read_lock(vfsmount_lock);
825         parent = path->mnt->mnt_parent;
826         if (parent == path->mnt) {
827                 br_read_unlock(vfsmount_lock);
828                 return 0;
829         }
830         mntget(parent);
831         mountpoint = dget(path->mnt->mnt_mountpoint);
832         br_read_unlock(vfsmount_lock);
833         dput(path->dentry);
834         path->dentry = mountpoint;
835         mntput(path->mnt);
836         path->mnt = parent;
837         return 1;
838 }
839
840 /*
841  * Perform an automount
842  * - return -EISDIR to tell follow_managed() to stop and return the path we
843  *   were called with.
844  */
845 static int follow_automount(struct path *path, unsigned flags,
846                             bool *need_mntput)
847 {
848         struct vfsmount *mnt;
849         int err;
850
851         if (!path->dentry->d_op || !path->dentry->d_op->d_automount)
852                 return -EREMOTE;
853
854         /* We don't want to mount if someone supplied AT_NO_AUTOMOUNT
855          * and this is the terminal part of the path.
856          */
857         if ((flags & LOOKUP_NO_AUTOMOUNT) && !(flags & LOOKUP_CONTINUE))
858                 return -EISDIR; /* we actually want to stop here */
859
860         /* We want to mount if someone is trying to open/create a file of any
861          * type under the mountpoint, wants to traverse through the mountpoint
862          * or wants to open the mounted directory.
863          *
864          * We don't want to mount if someone's just doing a stat and they've
865          * set AT_SYMLINK_NOFOLLOW - unless they're stat'ing a directory and
866          * appended a '/' to the name.
867          */
868         if (!(flags & LOOKUP_FOLLOW) &&
869             !(flags & (LOOKUP_CONTINUE | LOOKUP_DIRECTORY |
870                        LOOKUP_OPEN | LOOKUP_CREATE)))
871                 return -EISDIR;
872
873         current->total_link_count++;
874         if (current->total_link_count >= 40)
875                 return -ELOOP;
876
877         mnt = path->dentry->d_op->d_automount(path);
878         if (IS_ERR(mnt)) {
879                 /*
880                  * The filesystem is allowed to return -EISDIR here to indicate
881                  * it doesn't want to automount.  For instance, autofs would do
882                  * this so that its userspace daemon can mount on this dentry.
883                  *
884                  * However, we can only permit this if it's a terminal point in
885                  * the path being looked up; if it wasn't then the remainder of
886                  * the path is inaccessible and we should say so.
887                  */
888                 if (PTR_ERR(mnt) == -EISDIR && (flags & LOOKUP_CONTINUE))
889                         return -EREMOTE;
890                 return PTR_ERR(mnt);
891         }
892
893         if (!mnt) /* mount collision */
894                 return 0;
895
896         err = finish_automount(mnt, path);
897
898         switch (err) {
899         case -EBUSY:
900                 /* Someone else made a mount here whilst we were busy */
901                 return 0;
902         case 0:
903                 dput(path->dentry);
904                 if (*need_mntput)
905                         mntput(path->mnt);
906                 path->mnt = mnt;
907                 path->dentry = dget(mnt->mnt_root);
908                 *need_mntput = true;
909                 return 0;
910         default:
911                 return err;
912         }
913
914 }
915
916 /*
917  * Handle a dentry that is managed in some way.
918  * - Flagged for transit management (autofs)
919  * - Flagged as mountpoint
920  * - Flagged as automount point
921  *
922  * This may only be called in refwalk mode.
923  *
924  * Serialization is taken care of in namespace.c
925  */
926 static int follow_managed(struct path *path, unsigned flags)
927 {
928         unsigned managed;
929         bool need_mntput = false;
930         int ret;
931
932         /* Given that we're not holding a lock here, we retain the value in a
933          * local variable for each dentry as we look at it so that we don't see
934          * the components of that value change under us */
935         while (managed = ACCESS_ONCE(path->dentry->d_flags),
936                managed &= DCACHE_MANAGED_DENTRY,
937                unlikely(managed != 0)) {
938                 /* Allow the filesystem to manage the transit without i_mutex
939                  * being held. */
940                 if (managed & DCACHE_MANAGE_TRANSIT) {
941                         BUG_ON(!path->dentry->d_op);
942                         BUG_ON(!path->dentry->d_op->d_manage);
943                         ret = path->dentry->d_op->d_manage(path->dentry, false);
944                         if (ret < 0)
945                                 return ret == -EISDIR ? 0 : ret;
946                 }
947
948                 /* Transit to a mounted filesystem. */
949                 if (managed & DCACHE_MOUNTED) {
950                         struct vfsmount *mounted = lookup_mnt(path);
951                         if (mounted) {
952                                 dput(path->dentry);
953                                 if (need_mntput)
954                                         mntput(path->mnt);
955                                 path->mnt = mounted;
956                                 path->dentry = dget(mounted->mnt_root);
957                                 need_mntput = true;
958                                 continue;
959                         }
960
961                         /* Something is mounted on this dentry in another
962                          * namespace and/or whatever was mounted there in this
963                          * namespace got unmounted before we managed to get the
964                          * vfsmount_lock */
965                 }
966
967                 /* Handle an automount point */
968                 if (managed & DCACHE_NEED_AUTOMOUNT) {
969                         ret = follow_automount(path, flags, &need_mntput);
970                         if (ret < 0)
971                                 return ret == -EISDIR ? 0 : ret;
972                         continue;
973                 }
974
975                 /* We didn't change the current path point */
976                 break;
977         }
978         return 0;
979 }
980
981 int follow_down_one(struct path *path)
982 {
983         struct vfsmount *mounted;
984
985         mounted = lookup_mnt(path);
986         if (mounted) {
987                 dput(path->dentry);
988                 mntput(path->mnt);
989                 path->mnt = mounted;
990                 path->dentry = dget(mounted->mnt_root);
991                 return 1;
992         }
993         return 0;
994 }
995
996 static inline bool managed_dentry_might_block(struct dentry *dentry)
997 {
998         return (dentry->d_flags & DCACHE_MANAGE_TRANSIT &&
999                 dentry->d_op->d_manage(dentry, true) < 0);
1000 }
1001
1002 /*
1003  * Skip to top of mountpoint pile in rcuwalk mode.  We abort the rcu-walk if we
1004  * meet a managed dentry and we're not walking to "..".  True is returned to
1005  * continue, false to abort.
1006  */
1007 static bool __follow_mount_rcu(struct nameidata *nd, struct path *path,
1008                                struct inode **inode, bool reverse_transit)
1009 {
1010         for (;;) {
1011                 struct vfsmount *mounted;
1012                 /*
1013                  * Don't forget we might have a non-mountpoint managed dentry
1014                  * that wants to block transit.
1015                  */
1016                 if (!reverse_transit &&
1017                      unlikely(managed_dentry_might_block(path->dentry)))
1018                         return false;
1019
1020                 if (!d_mountpoint(path->dentry))
1021                         break;
1022
1023                 mounted = __lookup_mnt(path->mnt, path->dentry, 1);
1024                 if (!mounted)
1025                         break;
1026                 path->mnt = mounted;
1027                 path->dentry = mounted->mnt_root;
1028                 nd->seq = read_seqcount_begin(&path->dentry->d_seq);
1029                 /*
1030                  * Update the inode too. We don't need to re-check the
1031                  * dentry sequence number here after this d_inode read,
1032                  * because a mount-point is always pinned.
1033                  */
1034                 *inode = path->dentry->d_inode;
1035         }
1036
1037         if (unlikely(path->dentry->d_flags & DCACHE_NEED_AUTOMOUNT))
1038                 return reverse_transit;
1039         return true;
1040 }
1041
1042 static int follow_dotdot_rcu(struct nameidata *nd)
1043 {
1044         struct inode *inode = nd->inode;
1045
1046         set_root_rcu(nd);
1047
1048         while (1) {
1049                 if (nd->path.dentry == nd->root.dentry &&
1050                     nd->path.mnt == nd->root.mnt) {
1051                         break;
1052                 }
1053                 if (nd->path.dentry != nd->path.mnt->mnt_root) {
1054                         struct dentry *old = nd->path.dentry;
1055                         struct dentry *parent = old->d_parent;
1056                         unsigned seq;
1057
1058                         seq = read_seqcount_begin(&parent->d_seq);
1059                         if (read_seqcount_retry(&old->d_seq, nd->seq))
1060                                 goto failed;
1061                         inode = parent->d_inode;
1062                         nd->path.dentry = parent;
1063                         nd->seq = seq;
1064                         break;
1065                 }
1066                 if (!follow_up_rcu(&nd->path))
1067                         break;
1068                 nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
1069                 inode = nd->path.dentry->d_inode;
1070         }
1071         __follow_mount_rcu(nd, &nd->path, &inode, true);
1072         nd->inode = inode;
1073         return 0;
1074
1075 failed:
1076         nd->flags &= ~LOOKUP_RCU;
1077         if (!(nd->flags & LOOKUP_ROOT))
1078                 nd->root.mnt = NULL;
1079         rcu_read_unlock();
1080         br_read_unlock(vfsmount_lock);
1081         return -ECHILD;
1082 }
1083
1084 /*
1085  * Follow down to the covering mount currently visible to userspace.  At each
1086  * point, the filesystem owning that dentry may be queried as to whether the
1087  * caller is permitted to proceed or not.
1088  *
1089  * Care must be taken as namespace_sem may be held (indicated by mounting_here
1090  * being true).
1091  */
1092 int follow_down(struct path *path)
1093 {
1094         unsigned managed;
1095         int ret;
1096
1097         while (managed = ACCESS_ONCE(path->dentry->d_flags),
1098                unlikely(managed & DCACHE_MANAGED_DENTRY)) {
1099                 /* Allow the filesystem to manage the transit without i_mutex
1100                  * being held.
1101                  *
1102                  * We indicate to the filesystem if someone is trying to mount
1103                  * something here.  This gives autofs the chance to deny anyone
1104                  * other than its daemon the right to mount on its
1105                  * superstructure.
1106                  *
1107                  * The filesystem may sleep at this point.
1108                  */
1109                 if (managed & DCACHE_MANAGE_TRANSIT) {
1110                         BUG_ON(!path->dentry->d_op);
1111                         BUG_ON(!path->dentry->d_op->d_manage);
1112                         ret = path->dentry->d_op->d_manage(
1113                                 path->dentry, false);
1114                         if (ret < 0)
1115                                 return ret == -EISDIR ? 0 : ret;
1116                 }
1117
1118                 /* Transit to a mounted filesystem. */
1119                 if (managed & DCACHE_MOUNTED) {
1120                         struct vfsmount *mounted = lookup_mnt(path);
1121                         if (!mounted)
1122                                 break;
1123                         dput(path->dentry);
1124                         mntput(path->mnt);
1125                         path->mnt = mounted;
1126                         path->dentry = dget(mounted->mnt_root);
1127                         continue;
1128                 }
1129
1130                 /* Don't handle automount points here */
1131                 break;
1132         }
1133         return 0;
1134 }
1135
1136 /*
1137  * Skip to top of mountpoint pile in refwalk mode for follow_dotdot()
1138  */
1139 static void follow_mount(struct path *path)
1140 {
1141         while (d_mountpoint(path->dentry)) {
1142                 struct vfsmount *mounted = lookup_mnt(path);
1143                 if (!mounted)
1144                         break;
1145                 dput(path->dentry);
1146                 mntput(path->mnt);
1147                 path->mnt = mounted;
1148                 path->dentry = dget(mounted->mnt_root);
1149         }
1150 }
1151
1152 static void follow_dotdot(struct nameidata *nd)
1153 {
1154         set_root(nd);
1155
1156         while(1) {
1157                 struct dentry *old = nd->path.dentry;
1158
1159                 if (nd->path.dentry == nd->root.dentry &&
1160                     nd->path.mnt == nd->root.mnt) {
1161                         break;
1162                 }
1163                 if (nd->path.dentry != nd->path.mnt->mnt_root) {
1164                         /* rare case of legitimate dget_parent()... */
1165                         nd->path.dentry = dget_parent(nd->path.dentry);
1166                         dput(old);
1167                         break;
1168                 }
1169                 if (!follow_up(&nd->path))
1170                         break;
1171         }
1172         follow_mount(&nd->path);
1173         nd->inode = nd->path.dentry->d_inode;
1174 }
1175
1176 /*
1177  * Allocate a dentry with name and parent, and perform a parent
1178  * directory ->lookup on it. Returns the new dentry, or ERR_PTR
1179  * on error. parent->d_inode->i_mutex must be held. d_lookup must
1180  * have verified that no child exists while under i_mutex.
1181  */
1182 static struct dentry *d_alloc_and_lookup(struct dentry *parent,
1183                                 struct qstr *name, struct nameidata *nd)
1184 {
1185         struct inode *inode = parent->d_inode;
1186         struct dentry *dentry;
1187         struct dentry *old;
1188
1189         /* Don't create child dentry for a dead directory. */
1190         if (unlikely(IS_DEADDIR(inode)))
1191                 return ERR_PTR(-ENOENT);
1192
1193         dentry = d_alloc(parent, name);
1194         if (unlikely(!dentry))
1195                 return ERR_PTR(-ENOMEM);
1196
1197         old = inode->i_op->lookup(inode, dentry, nd);
1198         if (unlikely(old)) {
1199                 dput(dentry);
1200                 dentry = old;
1201         }
1202         return dentry;
1203 }
1204
1205 /*
1206  *  It's more convoluted than I'd like it to be, but... it's still fairly
1207  *  small and for now I'd prefer to have fast path as straight as possible.
1208  *  It _is_ time-critical.
1209  */
1210 static int do_lookup(struct nameidata *nd, struct qstr *name,
1211                         struct path *path, struct inode **inode)
1212 {
1213         struct vfsmount *mnt = nd->path.mnt;
1214         struct dentry *dentry, *parent = nd->path.dentry;
1215         int need_reval = 1;
1216         int status = 1;
1217         int err;
1218
1219         /*
1220          * Rename seqlock is not required here because in the off chance
1221          * of a false negative due to a concurrent rename, we're going to
1222          * do the non-racy lookup, below.
1223          */
1224         if (nd->flags & LOOKUP_RCU) {
1225                 unsigned seq;
1226                 *inode = nd->inode;
1227                 dentry = __d_lookup_rcu(parent, name, &seq, inode);
1228                 if (!dentry)
1229                         goto unlazy;
1230
1231                 /* Memory barrier in read_seqcount_begin of child is enough */
1232                 if (__read_seqcount_retry(&parent->d_seq, nd->seq))
1233                         return -ECHILD;
1234                 nd->seq = seq;
1235
1236                 if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE)) {
1237                         status = d_revalidate(dentry, nd);
1238                         if (unlikely(status <= 0)) {
1239                                 if (status != -ECHILD)
1240                                         need_reval = 0;
1241                                 goto unlazy;
1242                         }
1243                 }
1244                 path->mnt = mnt;
1245                 path->dentry = dentry;
1246                 if (likely(__follow_mount_rcu(nd, path, inode, false)))
1247                         return 0;
1248 unlazy:
1249                 if (dentry) {
1250                         if (nameidata_dentry_drop_rcu(nd, dentry))
1251                                 return -ECHILD;
1252                 } else {
1253                         if (nameidata_drop_rcu(nd))
1254                                 return -ECHILD;
1255                 }
1256         } else {
1257                 dentry = __d_lookup(parent, name);
1258         }
1259
1260 retry:
1261         if (unlikely(!dentry)) {
1262                 struct inode *dir = parent->d_inode;
1263                 BUG_ON(nd->inode != dir);
1264
1265                 mutex_lock(&dir->i_mutex);
1266                 dentry = d_lookup(parent, name);
1267                 if (likely(!dentry)) {
1268                         dentry = d_alloc_and_lookup(parent, name, nd);
1269                         if (IS_ERR(dentry)) {
1270                                 mutex_unlock(&dir->i_mutex);
1271                                 return PTR_ERR(dentry);
1272                         }
1273                         /* known good */
1274                         need_reval = 0;
1275                         status = 1;
1276                 }
1277                 mutex_unlock(&dir->i_mutex);
1278         }
1279         if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE) && need_reval)
1280                 status = d_revalidate(dentry, nd);
1281         if (unlikely(status <= 0)) {
1282                 if (status < 0) {
1283                         dput(dentry);
1284                         return status;
1285                 }
1286                 if (!d_invalidate(dentry)) {
1287                         dput(dentry);
1288                         dentry = NULL;
1289                         need_reval = 1;
1290                         goto retry;
1291                 }
1292         }
1293
1294         path->mnt = mnt;
1295         path->dentry = dentry;
1296         err = follow_managed(path, nd->flags);
1297         if (unlikely(err < 0)) {
1298                 path_put_conditional(path, nd);
1299                 return err;
1300         }
1301         *inode = path->dentry->d_inode;
1302         return 0;
1303 }
1304
1305 static inline int may_lookup(struct nameidata *nd)
1306 {
1307         if (nd->flags & LOOKUP_RCU) {
1308                 int err = exec_permission(nd->inode, IPERM_FLAG_RCU);
1309                 if (err != -ECHILD)
1310                         return err;
1311                 if (nameidata_drop_rcu(nd))
1312                         return -ECHILD;
1313         }
1314         return exec_permission(nd->inode, 0);
1315 }
1316
1317 static inline int handle_dots(struct nameidata *nd, int type)
1318 {
1319         if (type == LAST_DOTDOT) {
1320                 if (nd->flags & LOOKUP_RCU) {
1321                         if (follow_dotdot_rcu(nd))
1322                                 return -ECHILD;
1323                 } else
1324                         follow_dotdot(nd);
1325         }
1326         return 0;
1327 }
1328
1329 static void terminate_walk(struct nameidata *nd)
1330 {
1331         if (!(nd->flags & LOOKUP_RCU)) {
1332                 path_put(&nd->path);
1333         } else {
1334                 nd->flags &= ~LOOKUP_RCU;
1335                 if (!(nd->flags & LOOKUP_ROOT))
1336                         nd->root.mnt = NULL;
1337                 rcu_read_unlock();
1338                 br_read_unlock(vfsmount_lock);
1339         }
1340 }
1341
1342 static inline int walk_component(struct nameidata *nd, struct path *path,
1343                 struct qstr *name, int type, int follow)
1344 {
1345         struct inode *inode;
1346         int err;
1347         /*
1348          * "." and ".." are special - ".." especially so because it has
1349          * to be able to know about the current root directory and
1350          * parent relationships.
1351          */
1352         if (unlikely(type != LAST_NORM))
1353                 return handle_dots(nd, type);
1354         err = do_lookup(nd, name, path, &inode);
1355         if (unlikely(err)) {
1356                 terminate_walk(nd);
1357                 return err;
1358         }
1359         if (!inode) {
1360                 path_to_nameidata(path, nd);
1361                 terminate_walk(nd);
1362                 return -ENOENT;
1363         }
1364         if (unlikely(inode->i_op->follow_link) && follow) {
1365                 if (nameidata_dentry_drop_rcu_maybe(nd, path->dentry))
1366                         return -ECHILD;
1367                 BUG_ON(inode != path->dentry->d_inode);
1368                 return 1;
1369         }
1370         path_to_nameidata(path, nd);
1371         nd->inode = inode;
1372         return 0;
1373 }
1374
1375 /*
1376  * This limits recursive symlink follows to 8, while
1377  * limiting consecutive symlinks to 40.
1378  *
1379  * Without that kind of total limit, nasty chains of consecutive
1380  * symlinks can cause almost arbitrarily long lookups.
1381  */
1382 static inline int nested_symlink(struct path *path, struct nameidata *nd)
1383 {
1384         int res;
1385
1386         if (unlikely(current->link_count >= MAX_NESTED_LINKS)) {
1387                 path_put_conditional(path, nd);
1388                 path_put(&nd->path);
1389                 return -ELOOP;
1390         }
1391         BUG_ON(nd->depth >= MAX_NESTED_LINKS);
1392
1393         nd->depth++;
1394         current->link_count++;
1395
1396         do {
1397                 struct path link = *path;
1398                 void *cookie;
1399
1400                 res = follow_link(&link, nd, &cookie);
1401                 if (!res)
1402                         res = walk_component(nd, path, &nd->last,
1403                                              nd->last_type, LOOKUP_FOLLOW);
1404                 put_link(nd, &link, cookie);
1405         } while (res > 0);
1406
1407         current->link_count--;
1408         nd->depth--;
1409         return res;
1410 }
1411
1412 /*
1413  * Name resolution.
1414  * This is the basic name resolution function, turning a pathname into
1415  * the final dentry. We expect 'base' to be positive and a directory.
1416  *
1417  * Returns 0 and nd will have valid dentry and mnt on success.
1418  * Returns error and drops reference to input namei data on failure.
1419  */
1420 static int link_path_walk(const char *name, struct nameidata *nd)
1421 {
1422         struct path next;
1423         int err;
1424         unsigned int lookup_flags = nd->flags;
1425         
1426         while (*name=='/')
1427                 name++;
1428         if (!*name)
1429                 return 0;
1430
1431         /* At this point we know we have a real path component. */
1432         for(;;) {
1433                 unsigned long hash;
1434                 struct qstr this;
1435                 unsigned int c;
1436                 int type;
1437
1438                 nd->flags |= LOOKUP_CONTINUE;
1439
1440                 err = may_lookup(nd);
1441                 if (err)
1442                         break;
1443
1444                 this.name = name;
1445                 c = *(const unsigned char *)name;
1446
1447                 hash = init_name_hash();
1448                 do {
1449                         name++;
1450                         hash = partial_name_hash(c, hash);
1451                         c = *(const unsigned char *)name;
1452                 } while (c && (c != '/'));
1453                 this.len = name - (const char *) this.name;
1454                 this.hash = end_name_hash(hash);
1455
1456                 type = LAST_NORM;
1457                 if (this.name[0] == '.') switch (this.len) {
1458                         case 2:
1459                                 if (this.name[1] == '.') {
1460                                         type = LAST_DOTDOT;
1461                                         nd->flags |= LOOKUP_JUMPED;
1462                                 }
1463                                 break;
1464                         case 1:
1465                                 type = LAST_DOT;
1466                 }
1467                 if (likely(type == LAST_NORM)) {
1468                         struct dentry *parent = nd->path.dentry;
1469                         nd->flags &= ~LOOKUP_JUMPED;
1470                         if (unlikely(parent->d_flags & DCACHE_OP_HASH)) {
1471                                 err = parent->d_op->d_hash(parent, nd->inode,
1472                                                            &this);
1473                                 if (err < 0)
1474                                         break;
1475                         }
1476                 }
1477
1478                 /* remove trailing slashes? */
1479                 if (!c)
1480                         goto last_component;
1481                 while (*++name == '/');
1482                 if (!*name)
1483                         goto last_component;
1484
1485                 err = walk_component(nd, &next, &this, type, LOOKUP_FOLLOW);
1486                 if (err < 0)
1487                         return err;
1488
1489                 if (err) {
1490                         err = nested_symlink(&next, nd);
1491                         if (err)
1492                                 return err;
1493                 }
1494                 err = -ENOTDIR; 
1495                 if (!nd->inode->i_op->lookup)
1496                         break;
1497                 continue;
1498                 /* here ends the main loop */
1499
1500 last_component:
1501                 /* Clear LOOKUP_CONTINUE iff it was previously unset */
1502                 nd->flags &= lookup_flags | ~LOOKUP_CONTINUE;
1503                 nd->last = this;
1504                 nd->last_type = type;
1505                 return 0;
1506         }
1507         terminate_walk(nd);
1508         return err;
1509 }
1510
1511 static int path_init(int dfd, const char *name, unsigned int flags,
1512                      struct nameidata *nd, struct file **fp)
1513 {
1514         int retval = 0;
1515         int fput_needed;
1516         struct file *file;
1517
1518         nd->last_type = LAST_ROOT; /* if there are only slashes... */
1519         nd->flags = flags | LOOKUP_JUMPED;
1520         nd->depth = 0;
1521         if (flags & LOOKUP_ROOT) {
1522                 struct inode *inode = nd->root.dentry->d_inode;
1523                 if (*name) {
1524                         if (!inode->i_op->lookup)
1525                                 return -ENOTDIR;
1526                         retval = inode_permission(inode, MAY_EXEC);
1527                         if (retval)
1528                                 return retval;
1529                 }
1530                 nd->path = nd->root;
1531                 nd->inode = inode;
1532                 if (flags & LOOKUP_RCU) {
1533                         br_read_lock(vfsmount_lock);
1534                         rcu_read_lock();
1535                         nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
1536                 } else {
1537                         path_get(&nd->path);
1538                 }
1539                 return 0;
1540         }
1541
1542         nd->root.mnt = NULL;
1543
1544         if (*name=='/') {
1545                 if (flags & LOOKUP_RCU) {
1546                         br_read_lock(vfsmount_lock);
1547                         rcu_read_lock();
1548                         set_root_rcu(nd);
1549                 } else {
1550                         set_root(nd);
1551                         path_get(&nd->root);
1552                 }
1553                 nd->path = nd->root;
1554         } else if (dfd == AT_FDCWD) {
1555                 if (flags & LOOKUP_RCU) {
1556                         struct fs_struct *fs = current->fs;
1557                         unsigned seq;
1558
1559                         br_read_lock(vfsmount_lock);
1560                         rcu_read_lock();
1561
1562                         do {
1563                                 seq = read_seqcount_begin(&fs->seq);
1564                                 nd->path = fs->pwd;
1565                                 nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
1566                         } while (read_seqcount_retry(&fs->seq, seq));
1567                 } else {
1568                         get_fs_pwd(current->fs, &nd->path);
1569                 }
1570         } else {
1571                 struct dentry *dentry;
1572
1573                 file = fget_raw_light(dfd, &fput_needed);
1574                 retval = -EBADF;
1575                 if (!file)
1576                         goto out_fail;
1577
1578                 dentry = file->f_path.dentry;
1579
1580                 if (*name) {
1581                         retval = -ENOTDIR;
1582                         if (!S_ISDIR(dentry->d_inode->i_mode))
1583                                 goto fput_fail;
1584
1585                         retval = file_permission(file, MAY_EXEC);
1586                         if (retval)
1587                                 goto fput_fail;
1588                 }
1589
1590                 nd->path = file->f_path;
1591                 if (flags & LOOKUP_RCU) {
1592                         if (fput_needed)
1593                                 *fp = file;
1594                         nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
1595                         br_read_lock(vfsmount_lock);
1596                         rcu_read_lock();
1597                 } else {
1598                         path_get(&file->f_path);
1599                         fput_light(file, fput_needed);
1600                 }
1601         }
1602
1603         nd->inode = nd->path.dentry->d_inode;
1604         return 0;
1605
1606 fput_fail:
1607         fput_light(file, fput_needed);
1608 out_fail:
1609         return retval;
1610 }
1611
1612 static inline int lookup_last(struct nameidata *nd, struct path *path)
1613 {
1614         if (nd->last_type == LAST_NORM && nd->last.name[nd->last.len])
1615                 nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
1616
1617         nd->flags &= ~LOOKUP_PARENT;
1618         return walk_component(nd, path, &nd->last, nd->last_type,
1619                                         nd->flags & LOOKUP_FOLLOW);
1620 }
1621
1622 /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
1623 static int path_lookupat(int dfd, const char *name,
1624                                 unsigned int flags, struct nameidata *nd)
1625 {
1626         struct file *base = NULL;
1627         struct path path;
1628         int err;
1629
1630         /*
1631          * Path walking is largely split up into 2 different synchronisation
1632          * schemes, rcu-walk and ref-walk (explained in
1633          * Documentation/filesystems/path-lookup.txt). These share much of the
1634          * path walk code, but some things particularly setup, cleanup, and
1635          * following mounts are sufficiently divergent that functions are
1636          * duplicated. Typically there is a function foo(), and its RCU
1637          * analogue, foo_rcu().
1638          *
1639          * -ECHILD is the error number of choice (just to avoid clashes) that
1640          * is returned if some aspect of an rcu-walk fails. Such an error must
1641          * be handled by restarting a traditional ref-walk (which will always
1642          * be able to complete).
1643          */
1644         err = path_init(dfd, name, flags | LOOKUP_PARENT, nd, &base);
1645
1646         if (unlikely(err))
1647                 return err;
1648
1649         current->total_link_count = 0;
1650         err = link_path_walk(name, nd);
1651
1652         if (!err && !(flags & LOOKUP_PARENT)) {
1653                 err = lookup_last(nd, &path);
1654                 while (err > 0) {
1655                         void *cookie;
1656                         struct path link = path;
1657                         nd->flags |= LOOKUP_PARENT;
1658                         err = follow_link(&link, nd, &cookie);
1659                         if (!err)
1660                                 err = lookup_last(nd, &path);
1661                         put_link(nd, &link, cookie);
1662                 }
1663         }
1664
1665         if (nd->flags & LOOKUP_RCU) {
1666                 /* went all way through without dropping RCU */
1667                 BUG_ON(err);
1668                 if (nameidata_drop_rcu_last(nd))
1669                         err = -ECHILD;
1670         }
1671
1672         if (!err) {
1673                 err = handle_reval_path(nd);
1674                 if (err)
1675                         path_put(&nd->path);
1676         }
1677
1678         if (!err && nd->flags & LOOKUP_DIRECTORY) {
1679                 if (!nd->inode->i_op->lookup) {
1680                         path_put(&nd->path);
1681                         err = -ENOTDIR;
1682                 }
1683         }
1684
1685         if (base)
1686                 fput(base);
1687
1688         if (nd->root.mnt && !(nd->flags & LOOKUP_ROOT)) {
1689                 path_put(&nd->root);
1690                 nd->root.mnt = NULL;
1691         }
1692         return err;
1693 }
1694
1695 static int do_path_lookup(int dfd, const char *name,
1696                                 unsigned int flags, struct nameidata *nd)
1697 {
1698         int retval = path_lookupat(dfd, name, flags | LOOKUP_RCU, nd);
1699         if (unlikely(retval == -ECHILD))
1700                 retval = path_lookupat(dfd, name, flags, nd);
1701         if (unlikely(retval == -ESTALE))
1702                 retval = path_lookupat(dfd, name, flags | LOOKUP_REVAL, nd);
1703
1704         if (likely(!retval)) {
1705                 if (unlikely(!audit_dummy_context())) {
1706                         if (nd->path.dentry && nd->inode)
1707                                 audit_inode(name, nd->path.dentry);
1708                 }
1709         }
1710         return retval;
1711 }
1712
1713 int kern_path_parent(const char *name, struct nameidata *nd)
1714 {
1715         return do_path_lookup(AT_FDCWD, name, LOOKUP_PARENT, nd);
1716 }
1717
1718 int kern_path(const char *name, unsigned int flags, struct path *path)
1719 {
1720         struct nameidata nd;
1721         int res = do_path_lookup(AT_FDCWD, name, flags, &nd);
1722         if (!res)
1723                 *path = nd.path;
1724         return res;
1725 }
1726
1727 /**
1728  * vfs_path_lookup - lookup a file path relative to a dentry-vfsmount pair
1729  * @dentry:  pointer to dentry of the base directory
1730  * @mnt: pointer to vfs mount of the base directory
1731  * @name: pointer to file name
1732  * @flags: lookup flags
1733  * @nd: pointer to nameidata
1734  */
1735 int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt,
1736                     const char *name, unsigned int flags,
1737                     struct nameidata *nd)
1738 {
1739         nd->root.dentry = dentry;
1740         nd->root.mnt = mnt;
1741         /* the first argument of do_path_lookup() is ignored with LOOKUP_ROOT */
1742         return do_path_lookup(AT_FDCWD, name, flags | LOOKUP_ROOT, nd);
1743 }
1744
1745 static struct dentry *__lookup_hash(struct qstr *name,
1746                 struct dentry *base, struct nameidata *nd)
1747 {
1748         struct inode *inode = base->d_inode;
1749         struct dentry *dentry;
1750         int err;
1751
1752         err = exec_permission(inode, 0);
1753         if (err)
1754                 return ERR_PTR(err);
1755
1756         /*
1757          * Don't bother with __d_lookup: callers are for creat as
1758          * well as unlink, so a lot of the time it would cost
1759          * a double lookup.
1760          */
1761         dentry = d_lookup(base, name);
1762
1763         if (dentry && (dentry->d_flags & DCACHE_OP_REVALIDATE))
1764                 dentry = do_revalidate(dentry, nd);
1765
1766         if (!dentry)
1767                 dentry = d_alloc_and_lookup(base, name, nd);
1768
1769         return dentry;
1770 }
1771
1772 /*
1773  * Restricted form of lookup. Doesn't follow links, single-component only,
1774  * needs parent already locked. Doesn't follow mounts.
1775  * SMP-safe.
1776  */
1777 static struct dentry *lookup_hash(struct nameidata *nd)
1778 {
1779         return __lookup_hash(&nd->last, nd->path.dentry, nd);
1780 }
1781
1782 /**
1783  * lookup_one_len - filesystem helper to lookup single pathname component
1784  * @name:       pathname component to lookup
1785  * @base:       base directory to lookup from
1786  * @len:        maximum length @len should be interpreted to
1787  *
1788  * Note that this routine is purely a helper for filesystem usage and should
1789  * not be called by generic code.  Also note that by using this function the
1790  * nameidata argument is passed to the filesystem methods and a filesystem
1791  * using this helper needs to be prepared for that.
1792  */
1793 struct dentry *lookup_one_len(const char *name, struct dentry *base, int len)
1794 {
1795         struct qstr this;
1796         unsigned long hash;
1797         unsigned int c;
1798
1799         WARN_ON_ONCE(!mutex_is_locked(&base->d_inode->i_mutex));
1800
1801         this.name = name;
1802         this.len = len;
1803         if (!len)
1804                 return ERR_PTR(-EACCES);
1805
1806         hash = init_name_hash();
1807         while (len--) {
1808                 c = *(const unsigned char *)name++;
1809                 if (c == '/' || c == '\0')
1810                         return ERR_PTR(-EACCES);
1811                 hash = partial_name_hash(c, hash);
1812         }
1813         this.hash = end_name_hash(hash);
1814         /*
1815          * See if the low-level filesystem might want
1816          * to use its own hash..
1817          */
1818         if (base->d_flags & DCACHE_OP_HASH) {
1819                 int err = base->d_op->d_hash(base, base->d_inode, &this);
1820                 if (err < 0)
1821                         return ERR_PTR(err);
1822         }
1823
1824         return __lookup_hash(&this, base, NULL);
1825 }
1826
1827 int user_path_at(int dfd, const char __user *name, unsigned flags,
1828                  struct path *path)
1829 {
1830         struct nameidata nd;
1831         char *tmp = getname_flags(name, flags);
1832         int err = PTR_ERR(tmp);
1833         if (!IS_ERR(tmp)) {
1834
1835                 BUG_ON(flags & LOOKUP_PARENT);
1836
1837                 err = do_path_lookup(dfd, tmp, flags, &nd);
1838                 putname(tmp);
1839                 if (!err)
1840                         *path = nd.path;
1841         }
1842         return err;
1843 }
1844
1845 static int user_path_parent(int dfd, const char __user *path,
1846                         struct nameidata *nd, char **name)
1847 {
1848         char *s = getname(path);
1849         int error;
1850
1851         if (IS_ERR(s))
1852                 return PTR_ERR(s);
1853
1854         error = do_path_lookup(dfd, s, LOOKUP_PARENT, nd);
1855         if (error)
1856                 putname(s);
1857         else
1858                 *name = s;
1859
1860         return error;
1861 }
1862
1863 /*
1864  * It's inline, so penalty for filesystems that don't use sticky bit is
1865  * minimal.
1866  */
1867 static inline int check_sticky(struct inode *dir, struct inode *inode)
1868 {
1869         uid_t fsuid = current_fsuid();
1870
1871         if (!(dir->i_mode & S_ISVTX))
1872                 return 0;
1873         if (current_user_ns() != inode_userns(inode))
1874                 goto other_userns;
1875         if (inode->i_uid == fsuid)
1876                 return 0;
1877         if (dir->i_uid == fsuid)
1878                 return 0;
1879
1880 other_userns:
1881         return !ns_capable(inode_userns(inode), CAP_FOWNER);
1882 }
1883
1884 /*
1885  *      Check whether we can remove a link victim from directory dir, check
1886  *  whether the type of victim is right.
1887  *  1. We can't do it if dir is read-only (done in permission())
1888  *  2. We should have write and exec permissions on dir
1889  *  3. We can't remove anything from append-only dir
1890  *  4. We can't do anything with immutable dir (done in permission())
1891  *  5. If the sticky bit on dir is set we should either
1892  *      a. be owner of dir, or
1893  *      b. be owner of victim, or
1894  *      c. have CAP_FOWNER capability
1895  *  6. If the victim is append-only or immutable we can't do antyhing with
1896  *     links pointing to it.
1897  *  7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
1898  *  8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
1899  *  9. We can't remove a root or mountpoint.
1900  * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
1901  *     nfs_async_unlink().
1902  */
1903 static int may_delete(struct inode *dir,struct dentry *victim,int isdir)
1904 {
1905         int error;
1906
1907         if (!victim->d_inode)
1908                 return -ENOENT;
1909
1910         BUG_ON(victim->d_parent->d_inode != dir);
1911         audit_inode_child(victim, dir);
1912
1913         error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
1914         if (error)
1915                 return error;
1916         if (IS_APPEND(dir))
1917                 return -EPERM;
1918         if (check_sticky(dir, victim->d_inode)||IS_APPEND(victim->d_inode)||
1919             IS_IMMUTABLE(victim->d_inode) || IS_SWAPFILE(victim->d_inode))
1920                 return -EPERM;
1921         if (isdir) {
1922                 if (!S_ISDIR(victim->d_inode->i_mode))
1923                         return -ENOTDIR;
1924                 if (IS_ROOT(victim))
1925                         return -EBUSY;
1926         } else if (S_ISDIR(victim->d_inode->i_mode))
1927                 return -EISDIR;
1928         if (IS_DEADDIR(dir))
1929                 return -ENOENT;
1930         if (victim->d_flags & DCACHE_NFSFS_RENAMED)
1931                 return -EBUSY;
1932         return 0;
1933 }
1934
1935 /*      Check whether we can create an object with dentry child in directory
1936  *  dir.
1937  *  1. We can't do it if child already exists (open has special treatment for
1938  *     this case, but since we are inlined it's OK)
1939  *  2. We can't do it if dir is read-only (done in permission())
1940  *  3. We should have write and exec permissions on dir
1941  *  4. We can't do it if dir is immutable (done in permission())
1942  */
1943 static inline int may_create(struct inode *dir, struct dentry *child)
1944 {
1945         if (child->d_inode)
1946                 return -EEXIST;
1947         if (IS_DEADDIR(dir))
1948                 return -ENOENT;
1949         return inode_permission(dir, MAY_WRITE | MAY_EXEC);
1950 }
1951
1952 /*
1953  * p1 and p2 should be directories on the same fs.
1954  */
1955 struct dentry *lock_rename(struct dentry *p1, struct dentry *p2)
1956 {
1957         struct dentry *p;
1958
1959         if (p1 == p2) {
1960                 mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT);
1961                 return NULL;
1962         }
1963
1964         mutex_lock(&p1->d_inode->i_sb->s_vfs_rename_mutex);
1965
1966         p = d_ancestor(p2, p1);
1967         if (p) {
1968                 mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_PARENT);
1969                 mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_CHILD);
1970                 return p;
1971         }
1972
1973         p = d_ancestor(p1, p2);
1974         if (p) {
1975                 mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT);
1976                 mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_CHILD);
1977                 return p;
1978         }
1979
1980         mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT);
1981         mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_CHILD);
1982         return NULL;
1983 }
1984
1985 void unlock_rename(struct dentry *p1, struct dentry *p2)
1986 {
1987         mutex_unlock(&p1->d_inode->i_mutex);
1988         if (p1 != p2) {
1989                 mutex_unlock(&p2->d_inode->i_mutex);
1990                 mutex_unlock(&p1->d_inode->i_sb->s_vfs_rename_mutex);
1991         }
1992 }
1993
1994 int vfs_create(struct inode *dir, struct dentry *dentry, int mode,
1995                 struct nameidata *nd)
1996 {
1997         int error = may_create(dir, dentry);
1998
1999         if (error)
2000                 return error;
2001
2002         if (!dir->i_op->create)
2003                 return -EACCES; /* shouldn't it be ENOSYS? */
2004         mode &= S_IALLUGO;
2005         mode |= S_IFREG;
2006         error = security_inode_create(dir, dentry, mode);
2007         if (error)
2008                 return error;
2009         error = dir->i_op->create(dir, dentry, mode, nd);
2010         if (!error)
2011                 fsnotify_create(dir, dentry);
2012         return error;
2013 }
2014
2015 static int may_open(struct path *path, int acc_mode, int flag)
2016 {
2017         struct dentry *dentry = path->dentry;
2018         struct inode *inode = dentry->d_inode;
2019         int error;
2020
2021         /* O_PATH? */
2022         if (!acc_mode)
2023                 return 0;
2024
2025         if (!inode)
2026                 return -ENOENT;
2027
2028         switch (inode->i_mode & S_IFMT) {
2029         case S_IFLNK:
2030                 return -ELOOP;
2031         case S_IFDIR:
2032                 if (acc_mode & MAY_WRITE)
2033                         return -EISDIR;
2034                 break;
2035         case S_IFBLK:
2036         case S_IFCHR:
2037                 if (path->mnt->mnt_flags & MNT_NODEV)
2038                         return -EACCES;
2039                 /*FALLTHRU*/
2040         case S_IFIFO:
2041         case S_IFSOCK:
2042                 flag &= ~O_TRUNC;
2043                 break;
2044         }
2045
2046         error = inode_permission(inode, acc_mode);
2047         if (error)
2048                 return error;
2049
2050         /*
2051          * An append-only file must be opened in append mode for writing.
2052          */
2053         if (IS_APPEND(inode)) {
2054                 if  ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND))
2055                         return -EPERM;
2056                 if (flag & O_TRUNC)
2057                         return -EPERM;
2058         }
2059
2060         /* O_NOATIME can only be set by the owner or superuser */
2061         if (flag & O_NOATIME && !inode_owner_or_capable(inode))
2062                 return -EPERM;
2063
2064         /*
2065          * Ensure there are no outstanding leases on the file.
2066          */
2067         return break_lease(inode, flag);
2068 }
2069
2070 static int handle_truncate(struct file *filp)
2071 {
2072         struct path *path = &filp->f_path;
2073         struct inode *inode = path->dentry->d_inode;
2074         int error = get_write_access(inode);
2075         if (error)
2076                 return error;
2077         /*
2078          * Refuse to truncate files with mandatory locks held on them.
2079          */
2080         error = locks_verify_locked(inode);
2081         if (!error)
2082                 error = security_path_truncate(path);
2083         if (!error) {
2084                 error = do_truncate(path->dentry, 0,
2085                                     ATTR_MTIME|ATTR_CTIME|ATTR_OPEN,
2086                                     filp);
2087         }
2088         put_write_access(inode);
2089         return error;
2090 }
2091
2092 /*
2093  * Note that while the flag value (low two bits) for sys_open means:
2094  *      00 - read-only
2095  *      01 - write-only
2096  *      10 - read-write
2097  *      11 - special
2098  * it is changed into
2099  *      00 - no permissions needed
2100  *      01 - read-permission
2101  *      10 - write-permission
2102  *      11 - read-write
2103  * for the internal routines (ie open_namei()/follow_link() etc)
2104  * This is more logical, and also allows the 00 "no perm needed"
2105  * to be used for symlinks (where the permissions are checked
2106  * later).
2107  *
2108 */
2109 static inline int open_to_namei_flags(int flag)
2110 {
2111         if ((flag+1) & O_ACCMODE)
2112                 flag++;
2113         return flag;
2114 }
2115
2116 /*
2117  * Handle the last step of open()
2118  */
2119 static struct file *do_last(struct nameidata *nd, struct path *path,
2120                             const struct open_flags *op, const char *pathname)
2121 {
2122         struct dentry *dir = nd->path.dentry;
2123         struct dentry *dentry;
2124         int open_flag = op->open_flag;
2125         int will_truncate = open_flag & O_TRUNC;
2126         int want_write = 0;
2127         int acc_mode = op->acc_mode;
2128         struct file *filp;
2129         int error;
2130
2131         nd->flags &= ~LOOKUP_PARENT;
2132         nd->flags |= op->intent;
2133
2134         switch (nd->last_type) {
2135         case LAST_DOTDOT:
2136         case LAST_DOT:
2137                 error = handle_dots(nd, nd->last_type);
2138                 if (error)
2139                         return ERR_PTR(error);
2140                 /* fallthrough */
2141         case LAST_ROOT:
2142                 if (nd->flags & LOOKUP_RCU) {
2143                         if (nameidata_drop_rcu_last(nd))
2144                                 return ERR_PTR(-ECHILD);
2145                 }
2146                 error = handle_reval_path(nd);
2147                 if (error)
2148                         goto exit;
2149                 audit_inode(pathname, nd->path.dentry);
2150                 if (open_flag & O_CREAT) {
2151                         error = -EISDIR;
2152                         goto exit;
2153                 }
2154                 goto ok;
2155         case LAST_BIND:
2156                 /* can't be RCU mode here */
2157                 error = handle_reval_path(nd);
2158                 if (error)
2159                         goto exit;
2160                 audit_inode(pathname, dir);
2161                 goto ok;
2162         }
2163
2164         if (!(open_flag & O_CREAT)) {
2165                 int symlink_ok = 0;
2166                 if (nd->last.name[nd->last.len])
2167                         nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
2168                 if (open_flag & O_PATH && !(nd->flags & LOOKUP_FOLLOW))
2169                         symlink_ok = 1;
2170                 /* we _can_ be in RCU mode here */
2171                 error = walk_component(nd, path, &nd->last, LAST_NORM,
2172                                         !symlink_ok);
2173                 if (error < 0)
2174                         return ERR_PTR(error);
2175                 if (error) /* symlink */
2176                         return NULL;
2177                 /* sayonara */
2178                 if (nd->flags & LOOKUP_RCU) {
2179                         if (nameidata_drop_rcu_last(nd))
2180                                 return ERR_PTR(-ECHILD);
2181                 }
2182
2183                 error = -ENOTDIR;
2184                 if (nd->flags & LOOKUP_DIRECTORY) {
2185                         if (!nd->inode->i_op->lookup)
2186                                 goto exit;
2187                 }
2188                 audit_inode(pathname, nd->path.dentry);
2189                 goto ok;
2190         }
2191
2192         /* create side of things */
2193
2194         if (nd->flags & LOOKUP_RCU) {
2195                 if (nameidata_drop_rcu_last(nd))
2196                         return ERR_PTR(-ECHILD);
2197         }
2198
2199         audit_inode(pathname, dir);
2200         error = -EISDIR;
2201         /* trailing slashes? */
2202         if (nd->last.name[nd->last.len])
2203                 goto exit;
2204
2205         mutex_lock(&dir->d_inode->i_mutex);
2206
2207         dentry = lookup_hash(nd);
2208         error = PTR_ERR(dentry);
2209         if (IS_ERR(dentry)) {
2210                 mutex_unlock(&dir->d_inode->i_mutex);
2211                 goto exit;
2212         }
2213
2214         path->dentry = dentry;
2215         path->mnt = nd->path.mnt;
2216
2217         /* Negative dentry, just create the file */
2218         if (!dentry->d_inode) {
2219                 int mode = op->mode;
2220                 if (!IS_POSIXACL(dir->d_inode))
2221                         mode &= ~current_umask();
2222                 /*
2223                  * This write is needed to ensure that a
2224                  * rw->ro transition does not occur between
2225                  * the time when the file is created and when
2226                  * a permanent write count is taken through
2227                  * the 'struct file' in nameidata_to_filp().
2228                  */
2229                 error = mnt_want_write(nd->path.mnt);
2230                 if (error)
2231                         goto exit_mutex_unlock;
2232                 want_write = 1;
2233                 /* Don't check for write permission, don't truncate */
2234                 open_flag &= ~O_TRUNC;
2235                 will_truncate = 0;
2236                 acc_mode = MAY_OPEN;
2237                 error = security_path_mknod(&nd->path, dentry, mode, 0);
2238                 if (error)
2239                         goto exit_mutex_unlock;
2240                 error = vfs_create(dir->d_inode, dentry, mode, nd);
2241                 if (error)
2242                         goto exit_mutex_unlock;
2243                 mutex_unlock(&dir->d_inode->i_mutex);
2244                 dput(nd->path.dentry);
2245                 nd->path.dentry = dentry;
2246                 goto common;
2247         }
2248
2249         /*
2250          * It already exists.
2251          */
2252         mutex_unlock(&dir->d_inode->i_mutex);
2253         audit_inode(pathname, path->dentry);
2254
2255         error = -EEXIST;
2256         if (open_flag & O_EXCL)
2257                 goto exit_dput;
2258
2259         error = follow_managed(path, nd->flags);
2260         if (error < 0)
2261                 goto exit_dput;
2262
2263         error = -ENOENT;
2264         if (!path->dentry->d_inode)
2265                 goto exit_dput;
2266
2267         if (path->dentry->d_inode->i_op->follow_link)
2268                 return NULL;
2269
2270         path_to_nameidata(path, nd);
2271         nd->inode = path->dentry->d_inode;
2272         error = -EISDIR;
2273         if (S_ISDIR(nd->inode->i_mode))
2274                 goto exit;
2275 ok:
2276         if (!S_ISREG(nd->inode->i_mode))
2277                 will_truncate = 0;
2278
2279         if (will_truncate) {
2280                 error = mnt_want_write(nd->path.mnt);
2281                 if (error)
2282                         goto exit;
2283                 want_write = 1;
2284         }
2285 common:
2286         error = may_open(&nd->path, acc_mode, open_flag);
2287         if (error)
2288                 goto exit;
2289         filp = nameidata_to_filp(nd);
2290         if (!IS_ERR(filp)) {
2291                 error = ima_file_check(filp, op->acc_mode);
2292                 if (error) {
2293                         fput(filp);
2294                         filp = ERR_PTR(error);
2295                 }
2296         }
2297         if (!IS_ERR(filp)) {
2298                 if (will_truncate) {
2299                         error = handle_truncate(filp);
2300                         if (error) {
2301                                 fput(filp);
2302                                 filp = ERR_PTR(error);
2303                         }
2304                 }
2305         }
2306 out:
2307         if (want_write)
2308                 mnt_drop_write(nd->path.mnt);
2309         path_put(&nd->path);
2310         return filp;
2311
2312 exit_mutex_unlock:
2313         mutex_unlock(&dir->d_inode->i_mutex);
2314 exit_dput:
2315         path_put_conditional(path, nd);
2316 exit:
2317         filp = ERR_PTR(error);
2318         goto out;
2319 }
2320
2321 static struct file *path_openat(int dfd, const char *pathname,
2322                 struct nameidata *nd, const struct open_flags *op, int flags)
2323 {
2324         struct file *base = NULL;
2325         struct file *filp;
2326         struct path path;
2327         int error;
2328
2329         filp = get_empty_filp();
2330         if (!filp)
2331                 return ERR_PTR(-ENFILE);
2332
2333         filp->f_flags = op->open_flag;
2334         nd->intent.open.file = filp;
2335         nd->intent.open.flags = open_to_namei_flags(op->open_flag);
2336         nd->intent.open.create_mode = op->mode;
2337
2338         error = path_init(dfd, pathname, flags | LOOKUP_PARENT, nd, &base);
2339         if (unlikely(error))
2340                 goto out_filp;
2341
2342         current->total_link_count = 0;
2343         error = link_path_walk(pathname, nd);
2344         if (unlikely(error))
2345                 goto out_filp;
2346
2347         filp = do_last(nd, &path, op, pathname);
2348         while (unlikely(!filp)) { /* trailing symlink */
2349                 struct path link = path;
2350                 void *cookie;
2351                 if (!(nd->flags & LOOKUP_FOLLOW)) {
2352                         path_put_conditional(&path, nd);
2353                         path_put(&nd->path);
2354                         filp = ERR_PTR(-ELOOP);
2355                         break;
2356                 }
2357                 nd->flags |= LOOKUP_PARENT;
2358                 nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL);
2359                 error = follow_link(&link, nd, &cookie);
2360                 if (unlikely(error))
2361                         filp = ERR_PTR(error);
2362                 else
2363                         filp = do_last(nd, &path, op, pathname);
2364                 put_link(nd, &link, cookie);
2365         }
2366 out:
2367         if (nd->root.mnt && !(nd->flags & LOOKUP_ROOT))
2368                 path_put(&nd->root);
2369         if (base)
2370                 fput(base);
2371         release_open_intent(nd);
2372         return filp;
2373
2374 out_filp:
2375         filp = ERR_PTR(error);
2376         goto out;
2377 }
2378
2379 struct file *do_filp_open(int dfd, const char *pathname,
2380                 const struct open_flags *op, int flags)
2381 {
2382         struct nameidata nd;
2383         struct file *filp;
2384
2385         filp = path_openat(dfd, pathname, &nd, op, flags | LOOKUP_RCU);
2386         if (unlikely(filp == ERR_PTR(-ECHILD)))
2387                 filp = path_openat(dfd, pathname, &nd, op, flags);
2388         if (unlikely(filp == ERR_PTR(-ESTALE)))
2389                 filp = path_openat(dfd, pathname, &nd, op, flags | LOOKUP_REVAL);
2390         return filp;
2391 }
2392
2393 struct file *do_file_open_root(struct dentry *dentry, struct vfsmount *mnt,
2394                 const char *name, const struct open_flags *op, int flags)
2395 {
2396         struct nameidata nd;
2397         struct file *file;
2398
2399         nd.root.mnt = mnt;
2400         nd.root.dentry = dentry;
2401
2402         flags |= LOOKUP_ROOT;
2403
2404         if (dentry->d_inode->i_op->follow_link && op->intent & LOOKUP_OPEN)
2405                 return ERR_PTR(-ELOOP);
2406
2407         file = path_openat(-1, name, &nd, op, flags | LOOKUP_RCU);
2408         if (unlikely(file == ERR_PTR(-ECHILD)))
2409                 file = path_openat(-1, name, &nd, op, flags);
2410         if (unlikely(file == ERR_PTR(-ESTALE)))
2411                 file = path_openat(-1, name, &nd, op, flags | LOOKUP_REVAL);
2412         return file;
2413 }
2414
2415 /**
2416  * lookup_create - lookup a dentry, creating it if it doesn't exist
2417  * @nd: nameidata info
2418  * @is_dir: directory flag
2419  *
2420  * Simple function to lookup and return a dentry and create it
2421  * if it doesn't exist.  Is SMP-safe.
2422  *
2423  * Returns with nd->path.dentry->d_inode->i_mutex locked.
2424  */
2425 struct dentry *lookup_create(struct nameidata *nd, int is_dir)
2426 {
2427         struct dentry *dentry = ERR_PTR(-EEXIST);
2428
2429         mutex_lock_nested(&nd->path.dentry->d_inode->i_mutex, I_MUTEX_PARENT);
2430         /*
2431          * Yucky last component or no last component at all?
2432          * (foo/., foo/.., /////)
2433          */
2434         if (nd->last_type != LAST_NORM)
2435                 goto fail;
2436         nd->flags &= ~LOOKUP_PARENT;
2437         nd->flags |= LOOKUP_CREATE | LOOKUP_EXCL;
2438         nd->intent.open.flags = O_EXCL;
2439
2440         /*
2441          * Do the final lookup.
2442          */
2443         dentry = lookup_hash(nd);
2444         if (IS_ERR(dentry))
2445                 goto fail;
2446
2447         if (dentry->d_inode)
2448                 goto eexist;
2449         /*
2450          * Special case - lookup gave negative, but... we had foo/bar/
2451          * From the vfs_mknod() POV we just have a negative dentry -
2452          * all is fine. Let's be bastards - you had / on the end, you've
2453          * been asking for (non-existent) directory. -ENOENT for you.
2454          */
2455         if (unlikely(!is_dir && nd->last.name[nd->last.len])) {
2456                 dput(dentry);
2457                 dentry = ERR_PTR(-ENOENT);
2458         }
2459         return dentry;
2460 eexist:
2461         dput(dentry);
2462         dentry = ERR_PTR(-EEXIST);
2463 fail:
2464         return dentry;
2465 }
2466 EXPORT_SYMBOL_GPL(lookup_create);
2467
2468 int vfs_mknod(struct inode *dir, struct dentry *dentry, int mode, dev_t dev)
2469 {
2470         int error = may_create(dir, dentry);
2471
2472         if (error)
2473                 return error;
2474
2475         if ((S_ISCHR(mode) || S_ISBLK(mode)) &&
2476             !ns_capable(inode_userns(dir), CAP_MKNOD))
2477                 return -EPERM;
2478
2479         if (!dir->i_op->mknod)
2480                 return -EPERM;
2481
2482         error = devcgroup_inode_mknod(mode, dev);
2483         if (error)
2484                 return error;
2485
2486         error = security_inode_mknod(dir, dentry, mode, dev);
2487         if (error)
2488                 return error;
2489
2490         error = dir->i_op->mknod(dir, dentry, mode, dev);
2491         if (!error)
2492                 fsnotify_create(dir, dentry);
2493         return error;
2494 }
2495
2496 static int may_mknod(mode_t mode)
2497 {
2498         switch (mode & S_IFMT) {
2499         case S_IFREG:
2500         case S_IFCHR:
2501         case S_IFBLK:
2502         case S_IFIFO:
2503         case S_IFSOCK:
2504         case 0: /* zero mode translates to S_IFREG */
2505                 return 0;
2506         case S_IFDIR:
2507                 return -EPERM;
2508         default:
2509                 return -EINVAL;
2510         }
2511 }
2512
2513 SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, int, mode,
2514                 unsigned, dev)
2515 {
2516         int error;
2517         char *tmp;
2518         struct dentry *dentry;
2519         struct nameidata nd;
2520
2521         if (S_ISDIR(mode))
2522                 return -EPERM;
2523
2524         error = user_path_parent(dfd, filename, &nd, &tmp);
2525         if (error)
2526                 return error;
2527
2528         dentry = lookup_create(&nd, 0);
2529         if (IS_ERR(dentry)) {
2530                 error = PTR_ERR(dentry);
2531                 goto out_unlock;
2532         }
2533         if (!IS_POSIXACL(nd.path.dentry->d_inode))
2534                 mode &= ~current_umask();
2535         error = may_mknod(mode);
2536         if (error)
2537                 goto out_dput;
2538         error = mnt_want_write(nd.path.mnt);
2539         if (error)
2540                 goto out_dput;
2541         error = security_path_mknod(&nd.path, dentry, mode, dev);
2542         if (error)
2543                 goto out_drop_write;
2544         switch (mode & S_IFMT) {
2545                 case 0: case S_IFREG:
2546                         error = vfs_create(nd.path.dentry->d_inode,dentry,mode,&nd);
2547                         break;
2548                 case S_IFCHR: case S_IFBLK:
2549                         error = vfs_mknod(nd.path.dentry->d_inode,dentry,mode,
2550                                         new_decode_dev(dev));
2551                         break;
2552                 case S_IFIFO: case S_IFSOCK:
2553                         error = vfs_mknod(nd.path.dentry->d_inode,dentry,mode,0);
2554                         break;
2555         }
2556 out_drop_write:
2557         mnt_drop_write(nd.path.mnt);
2558 out_dput:
2559         dput(dentry);
2560 out_unlock:
2561         mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
2562         path_put(&nd.path);
2563         putname(tmp);
2564
2565         return error;
2566 }
2567
2568 SYSCALL_DEFINE3(mknod, const char __user *, filename, int, mode, unsigned, dev)
2569 {
2570         return sys_mknodat(AT_FDCWD, filename, mode, dev);
2571 }
2572
2573 int vfs_mkdir(struct inode *dir, struct dentry *dentry, int mode)
2574 {
2575         int error = may_create(dir, dentry);
2576
2577         if (error)
2578                 return error;
2579
2580         if (!dir->i_op->mkdir)
2581                 return -EPERM;
2582
2583         mode &= (S_IRWXUGO|S_ISVTX);
2584         error = security_inode_mkdir(dir, dentry, mode);
2585         if (error)
2586                 return error;
2587
2588         error = dir->i_op->mkdir(dir, dentry, mode);
2589         if (!error)
2590                 fsnotify_mkdir(dir, dentry);
2591         return error;
2592 }
2593
2594 SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, int, mode)
2595 {
2596         int error = 0;
2597         char * tmp;
2598         struct dentry *dentry;
2599         struct nameidata nd;
2600
2601         error = user_path_parent(dfd, pathname, &nd, &tmp);
2602         if (error)
2603                 goto out_err;
2604
2605         dentry = lookup_create(&nd, 1);
2606         error = PTR_ERR(dentry);
2607         if (IS_ERR(dentry))
2608                 goto out_unlock;
2609
2610         if (!IS_POSIXACL(nd.path.dentry->d_inode))
2611                 mode &= ~current_umask();
2612         error = mnt_want_write(nd.path.mnt);
2613         if (error)
2614                 goto out_dput;
2615         error = security_path_mkdir(&nd.path, dentry, mode);
2616         if (error)
2617                 goto out_drop_write;
2618         error = vfs_mkdir(nd.path.dentry->d_inode, dentry, mode);
2619 out_drop_write:
2620         mnt_drop_write(nd.path.mnt);
2621 out_dput:
2622         dput(dentry);
2623 out_unlock:
2624         mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
2625         path_put(&nd.path);
2626         putname(tmp);
2627 out_err:
2628         return error;
2629 }
2630
2631 SYSCALL_DEFINE2(mkdir, const char __user *, pathname, int, mode)
2632 {
2633         return sys_mkdirat(AT_FDCWD, pathname, mode);
2634 }
2635
2636 /*
2637  * We try to drop the dentry early: we should have
2638  * a usage count of 2 if we're the only user of this
2639  * dentry, and if that is true (possibly after pruning
2640  * the dcache), then we drop the dentry now.
2641  *
2642  * A low-level filesystem can, if it choses, legally
2643  * do a
2644  *
2645  *      if (!d_unhashed(dentry))
2646  *              return -EBUSY;
2647  *
2648  * if it cannot handle the case of removing a directory
2649  * that is still in use by something else..
2650  */
2651 void dentry_unhash(struct dentry *dentry)
2652 {
2653         dget(dentry);
2654         shrink_dcache_parent(dentry);
2655         spin_lock(&dentry->d_lock);
2656         if (dentry->d_count == 2)
2657                 __d_drop(dentry);
2658         spin_unlock(&dentry->d_lock);
2659 }
2660
2661 int vfs_rmdir(struct inode *dir, struct dentry *dentry)
2662 {
2663         int error = may_delete(dir, dentry, 1);
2664
2665         if (error)
2666                 return error;
2667
2668         if (!dir->i_op->rmdir)
2669                 return -EPERM;
2670
2671         mutex_lock(&dentry->d_inode->i_mutex);
2672         dentry_unhash(dentry);
2673         if (d_mountpoint(dentry))
2674                 error = -EBUSY;
2675         else {
2676                 error = security_inode_rmdir(dir, dentry);
2677                 if (!error) {
2678                         error = dir->i_op->rmdir(dir, dentry);
2679                         if (!error) {
2680                                 dentry->d_inode->i_flags |= S_DEAD;
2681                                 dont_mount(dentry);
2682                         }
2683                 }
2684         }
2685         mutex_unlock(&dentry->d_inode->i_mutex);
2686         if (!error) {
2687                 d_delete(dentry);
2688         }
2689         dput(dentry);
2690
2691         return error;
2692 }
2693
2694 static long do_rmdir(int dfd, const char __user *pathname)
2695 {
2696         int error = 0;
2697         char * name;
2698         struct dentry *dentry;
2699         struct nameidata nd;
2700
2701         error = user_path_parent(dfd, pathname, &nd, &name);
2702         if (error)
2703                 return error;
2704
2705         switch(nd.last_type) {
2706         case LAST_DOTDOT:
2707                 error = -ENOTEMPTY;
2708                 goto exit1;
2709         case LAST_DOT:
2710                 error = -EINVAL;
2711                 goto exit1;
2712         case LAST_ROOT:
2713                 error = -EBUSY;
2714                 goto exit1;
2715         }
2716
2717         nd.flags &= ~LOOKUP_PARENT;
2718
2719         mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT);
2720         dentry = lookup_hash(&nd);
2721         error = PTR_ERR(dentry);
2722         if (IS_ERR(dentry))
2723                 goto exit2;
2724         error = mnt_want_write(nd.path.mnt);
2725         if (error)
2726                 goto exit3;
2727         error = security_path_rmdir(&nd.path, dentry);
2728         if (error)
2729                 goto exit4;
2730         error = vfs_rmdir(nd.path.dentry->d_inode, dentry);
2731 exit4:
2732         mnt_drop_write(nd.path.mnt);
2733 exit3:
2734         dput(dentry);
2735 exit2:
2736         mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
2737 exit1:
2738         path_put(&nd.path);
2739         putname(name);
2740         return error;
2741 }
2742
2743 SYSCALL_DEFINE1(rmdir, const char __user *, pathname)
2744 {
2745         return do_rmdir(AT_FDCWD, pathname);
2746 }
2747
2748 int vfs_unlink(struct inode *dir, struct dentry *dentry)
2749 {
2750         int error = may_delete(dir, dentry, 0);
2751
2752         if (error)
2753                 return error;
2754
2755         if (!dir->i_op->unlink)
2756                 return -EPERM;
2757
2758         mutex_lock(&dentry->d_inode->i_mutex);
2759         if (d_mountpoint(dentry))
2760                 error = -EBUSY;
2761         else {
2762                 error = security_inode_unlink(dir, dentry);
2763                 if (!error) {
2764                         error = dir->i_op->unlink(dir, dentry);
2765                         if (!error)
2766                                 dont_mount(dentry);
2767                 }
2768         }
2769         mutex_unlock(&dentry->d_inode->i_mutex);
2770
2771         /* We don't d_delete() NFS sillyrenamed files--they still exist. */
2772         if (!error && !(dentry->d_flags & DCACHE_NFSFS_RENAMED)) {
2773                 fsnotify_link_count(dentry->d_inode);
2774                 d_delete(dentry);
2775         }
2776
2777         return error;
2778 }
2779
2780 /*
2781  * Make sure that the actual truncation of the file will occur outside its
2782  * directory's i_mutex.  Truncate can take a long time if there is a lot of
2783  * writeout happening, and we don't want to prevent access to the directory
2784  * while waiting on the I/O.
2785  */
2786 static long do_unlinkat(int dfd, const char __user *pathname)
2787 {
2788         int error;
2789         char *name;
2790         struct dentry *dentry;
2791         struct nameidata nd;
2792         struct inode *inode = NULL;
2793
2794         error = user_path_parent(dfd, pathname, &nd, &name);
2795         if (error)
2796                 return error;
2797
2798         error = -EISDIR;
2799         if (nd.last_type != LAST_NORM)
2800                 goto exit1;
2801
2802         nd.flags &= ~LOOKUP_PARENT;
2803
2804         mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT);
2805         dentry = lookup_hash(&nd);
2806         error = PTR_ERR(dentry);
2807         if (!IS_ERR(dentry)) {
2808                 /* Why not before? Because we want correct error value */
2809                 if (nd.last.name[nd.last.len])
2810                         goto slashes;
2811                 inode = dentry->d_inode;
2812                 if (inode)
2813                         ihold(inode);
2814                 error = mnt_want_write(nd.path.mnt);
2815                 if (error)
2816                         goto exit2;
2817                 error = security_path_unlink(&nd.path, dentry);
2818                 if (error)
2819                         goto exit3;
2820                 error = vfs_unlink(nd.path.dentry->d_inode, dentry);
2821 exit3:
2822                 mnt_drop_write(nd.path.mnt);
2823         exit2:
2824                 dput(dentry);
2825         }
2826         mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
2827         if (inode)
2828                 iput(inode);    /* truncate the inode here */
2829 exit1:
2830         path_put(&nd.path);
2831         putname(name);
2832         return error;
2833
2834 slashes:
2835         error = !dentry->d_inode ? -ENOENT :
2836                 S_ISDIR(dentry->d_inode->i_mode) ? -EISDIR : -ENOTDIR;
2837         goto exit2;
2838 }
2839
2840 SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag)
2841 {
2842         if ((flag & ~AT_REMOVEDIR) != 0)
2843                 return -EINVAL;
2844
2845         if (flag & AT_REMOVEDIR)
2846                 return do_rmdir(dfd, pathname);
2847
2848         return do_unlinkat(dfd, pathname);
2849 }
2850
2851 SYSCALL_DEFINE1(unlink, const char __user *, pathname)
2852 {
2853         return do_unlinkat(AT_FDCWD, pathname);
2854 }
2855
2856 int vfs_symlink(struct inode *dir, struct dentry *dentry, const char *oldname)
2857 {
2858         int error = may_create(dir, dentry);
2859
2860         if (error)
2861                 return error;
2862
2863         if (!dir->i_op->symlink)
2864                 return -EPERM;
2865
2866         error = security_inode_symlink(dir, dentry, oldname);
2867         if (error)
2868                 return error;
2869
2870         error = dir->i_op->symlink(dir, dentry, oldname);
2871         if (!error)
2872                 fsnotify_create(dir, dentry);
2873         return error;
2874 }
2875
2876 SYSCALL_DEFINE3(symlinkat, const char __user *, oldname,
2877                 int, newdfd, const char __user *, newname)
2878 {
2879         int error;
2880         char *from;
2881         char *to;
2882         struct dentry *dentry;
2883         struct nameidata nd;
2884
2885         from = getname(oldname);
2886         if (IS_ERR(from))
2887                 return PTR_ERR(from);
2888
2889         error = user_path_parent(newdfd, newname, &nd, &to);
2890         if (error)
2891                 goto out_putname;
2892
2893         dentry = lookup_create(&nd, 0);
2894         error = PTR_ERR(dentry);
2895         if (IS_ERR(dentry))
2896                 goto out_unlock;
2897
2898         error = mnt_want_write(nd.path.mnt);
2899         if (error)
2900                 goto out_dput;
2901         error = security_path_symlink(&nd.path, dentry, from);
2902         if (error)
2903                 goto out_drop_write;
2904         error = vfs_symlink(nd.path.dentry->d_inode, dentry, from);
2905 out_drop_write:
2906         mnt_drop_write(nd.path.mnt);
2907 out_dput:
2908         dput(dentry);
2909 out_unlock:
2910         mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
2911         path_put(&nd.path);
2912         putname(to);
2913 out_putname:
2914         putname(from);
2915         return error;
2916 }
2917
2918 SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname)
2919 {
2920         return sys_symlinkat(oldname, AT_FDCWD, newname);
2921 }
2922
2923 int vfs_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry)
2924 {
2925         struct inode *inode = old_dentry->d_inode;
2926         int error;
2927
2928         if (!inode)
2929                 return -ENOENT;
2930
2931         error = may_create(dir, new_dentry);
2932         if (error)
2933                 return error;
2934
2935         if (dir->i_sb != inode->i_sb)
2936                 return -EXDEV;
2937
2938         /*
2939          * A link to an append-only or immutable file cannot be created.
2940          */
2941         if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
2942                 return -EPERM;
2943         if (!dir->i_op->link)
2944                 return -EPERM;
2945         if (S_ISDIR(inode->i_mode))
2946                 return -EPERM;
2947
2948         error = security_inode_link(old_dentry, dir, new_dentry);
2949         if (error)
2950                 return error;
2951
2952         mutex_lock(&inode->i_mutex);
2953         /* Make sure we don't allow creating hardlink to an unlinked file */
2954         if (inode->i_nlink == 0)
2955                 error =  -ENOENT;
2956         else
2957                 error = dir->i_op->link(old_dentry, dir, new_dentry);
2958         mutex_unlock(&inode->i_mutex);
2959         if (!error)
2960                 fsnotify_link(dir, inode, new_dentry);
2961         return error;
2962 }
2963
2964 /*
2965  * Hardlinks are often used in delicate situations.  We avoid
2966  * security-related surprises by not following symlinks on the
2967  * newname.  --KAB
2968  *
2969  * We don't follow them on the oldname either to be compatible
2970  * with linux 2.0, and to avoid hard-linking to directories
2971  * and other special files.  --ADM
2972  */
2973 SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname,
2974                 int, newdfd, const char __user *, newname, int, flags)
2975 {
2976         struct dentry *new_dentry;
2977         struct nameidata nd;
2978         struct path old_path;
2979         int how = 0;
2980         int error;
2981         char *to;
2982
2983         if ((flags & ~(AT_SYMLINK_FOLLOW | AT_EMPTY_PATH)) != 0)
2984                 return -EINVAL;
2985         /*
2986          * To use null names we require CAP_DAC_READ_SEARCH
2987          * This ensures that not everyone will be able to create
2988          * handlink using the passed filedescriptor.
2989          */
2990         if (flags & AT_EMPTY_PATH) {
2991                 if (!capable(CAP_DAC_READ_SEARCH))
2992                         return -ENOENT;
2993                 how = LOOKUP_EMPTY;
2994         }
2995
2996         if (flags & AT_SYMLINK_FOLLOW)
2997                 how |= LOOKUP_FOLLOW;
2998
2999         error = user_path_at(olddfd, oldname, how, &old_path);
3000         if (error)
3001                 return error;
3002
3003         error = user_path_parent(newdfd, newname, &nd, &to);
3004         if (error)
3005                 goto out;
3006         error = -EXDEV;
3007         if (old_path.mnt != nd.path.mnt)
3008                 goto out_release;
3009         new_dentry = lookup_create(&nd, 0);
3010         error = PTR_ERR(new_dentry);
3011         if (IS_ERR(new_dentry))
3012                 goto out_unlock;
3013         error = mnt_want_write(nd.path.mnt);
3014         if (error)
3015                 goto out_dput;
3016         error = security_path_link(old_path.dentry, &nd.path, new_dentry);
3017         if (error)
3018                 goto out_drop_write;
3019         error = vfs_link(old_path.dentry, nd.path.dentry->d_inode, new_dentry);
3020 out_drop_write:
3021         mnt_drop_write(nd.path.mnt);
3022 out_dput:
3023         dput(new_dentry);
3024 out_unlock:
3025         mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
3026 out_release:
3027         path_put(&nd.path);
3028         putname(to);
3029 out:
3030         path_put(&old_path);
3031
3032         return error;
3033 }
3034
3035 SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname)
3036 {
3037         return sys_linkat(AT_FDCWD, oldname, AT_FDCWD, newname, 0);
3038 }
3039
3040 /*
3041  * The worst of all namespace operations - renaming directory. "Perverted"
3042  * doesn't even start to describe it. Somebody in UCB had a heck of a trip...
3043  * Problems:
3044  *      a) we can get into loop creation. Check is done in is_subdir().
3045  *      b) race potential - two innocent renames can create a loop together.
3046  *         That's where 4.4 screws up. Current fix: serialization on
3047  *         sb->s_vfs_rename_mutex. We might be more accurate, but that's another
3048  *         story.
3049  *      c) we have to lock _three_ objects - parents and victim (if it exists).
3050  *         And that - after we got ->i_mutex on parents (until then we don't know
3051  *         whether the target exists).  Solution: try to be smart with locking
3052  *         order for inodes.  We rely on the fact that tree topology may change
3053  *         only under ->s_vfs_rename_mutex _and_ that parent of the object we
3054  *         move will be locked.  Thus we can rank directories by the tree
3055  *         (ancestors first) and rank all non-directories after them.
3056  *         That works since everybody except rename does "lock parent, lookup,
3057  *         lock child" and rename is under ->s_vfs_rename_mutex.
3058  *         HOWEVER, it relies on the assumption that any object with ->lookup()
3059  *         has no more than 1 dentry.  If "hybrid" objects will ever appear,
3060  *         we'd better make sure that there's no link(2) for them.
3061  *      d) some filesystems don't support opened-but-unlinked directories,
3062  *         either because of layout or because they are not ready to deal with
3063  *         all cases correctly. The latter will be fixed (taking this sort of
3064  *         stuff into VFS), but the former is not going away. Solution: the same
3065  *         trick as in rmdir().
3066  *      e) conversion from fhandle to dentry may come in the wrong moment - when
3067  *         we are removing the target. Solution: we will have to grab ->i_mutex
3068  *         in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on
3069  *         ->i_mutex on parents, which works but leads to some truly excessive
3070  *         locking].
3071  */
3072 static int vfs_rename_dir(struct inode *old_dir, struct dentry *old_dentry,
3073                           struct inode *new_dir, struct dentry *new_dentry)
3074 {
3075         int error = 0;
3076         struct inode *target;
3077
3078         /*
3079          * If we are going to change the parent - check write permissions,
3080          * we'll need to flip '..'.
3081          */
3082         if (new_dir != old_dir) {
3083                 error = inode_permission(old_dentry->d_inode, MAY_WRITE);
3084                 if (error)
3085                         return error;
3086         }
3087
3088         error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry);
3089         if (error)
3090                 return error;
3091
3092         target = new_dentry->d_inode;
3093         if (target)
3094                 mutex_lock(&target->i_mutex);
3095         if (d_mountpoint(old_dentry)||d_mountpoint(new_dentry))
3096                 error = -EBUSY;
3097         else {
3098                 if (target)
3099                         dentry_unhash(new_dentry);
3100                 error = old_dir->i_op->rename(old_dir, old_dentry, new_dir, new_dentry);
3101         }
3102         if (target) {
3103                 if (!error) {
3104                         target->i_flags |= S_DEAD;
3105                         dont_mount(new_dentry);
3106                 }
3107                 mutex_unlock(&target->i_mutex);
3108                 if (d_unhashed(new_dentry))
3109                         d_rehash(new_dentry);
3110                 dput(new_dentry);
3111         }
3112         if (!error)
3113                 if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE))
3114                         d_move(old_dentry,new_dentry);
3115         return error;
3116 }
3117
3118 static int vfs_rename_other(struct inode *old_dir, struct dentry *old_dentry,
3119                             struct inode *new_dir, struct dentry *new_dentry)
3120 {
3121         struct inode *target;
3122         int error;
3123
3124         error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry);
3125         if (error)
3126                 return error;
3127
3128         dget(new_dentry);
3129         target = new_dentry->d_inode;
3130         if (target)
3131                 mutex_lock(&target->i_mutex);
3132         if (d_mountpoint(old_dentry)||d_mountpoint(new_dentry))
3133                 error = -EBUSY;
3134         else
3135                 error = old_dir->i_op->rename(old_dir, old_dentry, new_dir, new_dentry);
3136         if (!error) {
3137                 if (target)
3138                         dont_mount(new_dentry);
3139                 if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE))
3140                         d_move(old_dentry, new_dentry);
3141         }
3142         if (target)
3143                 mutex_unlock(&target->i_mutex);
3144         dput(new_dentry);
3145         return error;
3146 }
3147
3148 int vfs_rename(struct inode *old_dir, struct dentry *old_dentry,
3149                struct inode *new_dir, struct dentry *new_dentry)
3150 {
3151         int error;
3152         int is_dir = S_ISDIR(old_dentry->d_inode->i_mode);
3153         const unsigned char *old_name;
3154
3155         if (old_dentry->d_inode == new_dentry->d_inode)
3156                 return 0;
3157  
3158         error = may_delete(old_dir, old_dentry, is_dir);
3159         if (error)
3160                 return error;
3161
3162         if (!new_dentry->d_inode)
3163                 error = may_create(new_dir, new_dentry);
3164         else
3165                 error = may_delete(new_dir, new_dentry, is_dir);
3166         if (error)
3167                 return error;
3168
3169         if (!old_dir->i_op->rename)
3170                 return -EPERM;
3171
3172         old_name = fsnotify_oldname_init(old_dentry->d_name.name);
3173
3174         if (is_dir)
3175                 error = vfs_rename_dir(old_dir,old_dentry,new_dir,new_dentry);
3176         else
3177                 error = vfs_rename_other(old_dir,old_dentry,new_dir,new_dentry);
3178         if (!error)
3179                 fsnotify_move(old_dir, new_dir, old_name, is_dir,
3180                               new_dentry->d_inode, old_dentry);
3181         fsnotify_oldname_free(old_name);
3182
3183         return error;
3184 }
3185
3186 SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname,
3187                 int, newdfd, const char __user *, newname)
3188 {
3189         struct dentry *old_dir, *new_dir;
3190         struct dentry *old_dentry, *new_dentry;
3191         struct dentry *trap;
3192         struct nameidata oldnd, newnd;
3193         char *from;
3194         char *to;
3195         int error;
3196
3197         error = user_path_parent(olddfd, oldname, &oldnd, &from);
3198         if (error)
3199                 goto exit;
3200
3201         error = user_path_parent(newdfd, newname, &newnd, &to);
3202         if (error)
3203                 goto exit1;
3204
3205         error = -EXDEV;
3206         if (oldnd.path.mnt != newnd.path.mnt)
3207                 goto exit2;
3208
3209         old_dir = oldnd.path.dentry;
3210         error = -EBUSY;
3211         if (oldnd.last_type != LAST_NORM)
3212                 goto exit2;
3213
3214         new_dir = newnd.path.dentry;
3215         if (newnd.last_type != LAST_NORM)
3216                 goto exit2;
3217
3218         oldnd.flags &= ~LOOKUP_PARENT;
3219         newnd.flags &= ~LOOKUP_PARENT;
3220         newnd.flags |= LOOKUP_RENAME_TARGET;
3221
3222         trap = lock_rename(new_dir, old_dir);
3223
3224         old_dentry = lookup_hash(&oldnd);
3225         error = PTR_ERR(old_dentry);
3226         if (IS_ERR(old_dentry))
3227                 goto exit3;
3228         /* source must exist */
3229         error = -ENOENT;
3230         if (!old_dentry->d_inode)
3231                 goto exit4;
3232         /* unless the source is a directory trailing slashes give -ENOTDIR */
3233         if (!S_ISDIR(old_dentry->d_inode->i_mode)) {
3234                 error = -ENOTDIR;
3235                 if (oldnd.last.name[oldnd.last.len])
3236                         goto exit4;
3237                 if (newnd.last.name[newnd.last.len])
3238                         goto exit4;
3239         }
3240         /* source should not be ancestor of target */
3241         error = -EINVAL;
3242         if (old_dentry == trap)
3243                 goto exit4;
3244         new_dentry = lookup_hash(&newnd);
3245         error = PTR_ERR(new_dentry);
3246         if (IS_ERR(new_dentry))
3247                 goto exit4;
3248         /* target should not be an ancestor of source */
3249         error = -ENOTEMPTY;
3250         if (new_dentry == trap)
3251                 goto exit5;
3252
3253         error = mnt_want_write(oldnd.path.mnt);
3254         if (error)
3255                 goto exit5;
3256         error = security_path_rename(&oldnd.path, old_dentry,
3257                                      &newnd.path, new_dentry);
3258         if (error)
3259                 goto exit6;
3260         error = vfs_rename(old_dir->d_inode, old_dentry,
3261                                    new_dir->d_inode, new_dentry);
3262 exit6:
3263         mnt_drop_write(oldnd.path.mnt);
3264 exit5:
3265         dput(new_dentry);
3266 exit4:
3267         dput(old_dentry);
3268 exit3:
3269         unlock_rename(new_dir, old_dir);
3270 exit2:
3271         path_put(&newnd.path);
3272         putname(to);
3273 exit1:
3274         path_put(&oldnd.path);
3275         putname(from);
3276 exit:
3277         return error;
3278 }
3279
3280 SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname)
3281 {
3282         return sys_renameat(AT_FDCWD, oldname, AT_FDCWD, newname);
3283 }
3284
3285 int vfs_readlink(struct dentry *dentry, char __user *buffer, int buflen, const char *link)
3286 {
3287         int len;
3288
3289         len = PTR_ERR(link);
3290         if (IS_ERR(link))
3291                 goto out;
3292
3293         len = strlen(link);
3294         if (len > (unsigned) buflen)
3295                 len = buflen;
3296         if (copy_to_user(buffer, link, len))
3297                 len = -EFAULT;
3298 out:
3299         return len;
3300 }
3301
3302 /*
3303  * A helper for ->readlink().  This should be used *ONLY* for symlinks that
3304  * have ->follow_link() touching nd only in nd_set_link().  Using (or not
3305  * using) it for any given inode is up to filesystem.
3306  */
3307 int generic_readlink(struct dentry *dentry, char __user *buffer, int buflen)
3308 {
3309         struct nameidata nd;
3310         void *cookie;
3311         int res;
3312
3313         nd.depth = 0;
3314         cookie = dentry->d_inode->i_op->follow_link(dentry, &nd);
3315         if (IS_ERR(cookie))
3316                 return PTR_ERR(cookie);
3317
3318         res = vfs_readlink(dentry, buffer, buflen, nd_get_link(&nd));
3319         if (dentry->d_inode->i_op->put_link)
3320                 dentry->d_inode->i_op->put_link(dentry, &nd, cookie);
3321         return res;
3322 }
3323
3324 int vfs_follow_link(struct nameidata *nd, const char *link)
3325 {
3326         return __vfs_follow_link(nd, link);
3327 }
3328
3329 /* get the link contents into pagecache */
3330 static char *page_getlink(struct dentry * dentry, struct page **ppage)
3331 {
3332         char *kaddr;
3333         struct page *page;
3334         struct address_space *mapping = dentry->d_inode->i_mapping;
3335         page = read_mapping_page(mapping, 0, NULL);
3336         if (IS_ERR(page))
3337                 return (char*)page;
3338         *ppage = page;
3339         kaddr = kmap(page);
3340         nd_terminate_link(kaddr, dentry->d_inode->i_size, PAGE_SIZE - 1);
3341         return kaddr;
3342 }
3343
3344 int page_readlink(struct dentry *dentry, char __user *buffer, int buflen)
3345 {
3346         struct page *page = NULL;
3347         char *s = page_getlink(dentry, &page);
3348         int res = vfs_readlink(dentry,buffer,buflen,s);
3349         if (page) {
3350                 kunmap(page);
3351                 page_cache_release(page);
3352         }
3353         return res;
3354 }
3355
3356 void *page_follow_link_light(struct dentry *dentry, struct nameidata *nd)
3357 {
3358         struct page *page = NULL;
3359         nd_set_link(nd, page_getlink(dentry, &page));
3360         return page;
3361 }
3362
3363 void page_put_link(struct dentry *dentry, struct nameidata *nd, void *cookie)
3364 {
3365         struct page *page = cookie;
3366
3367         if (page) {
3368                 kunmap(page);
3369                 page_cache_release(page);
3370         }
3371 }
3372
3373 /*
3374  * The nofs argument instructs pagecache_write_begin to pass AOP_FLAG_NOFS
3375  */
3376 int __page_symlink(struct inode *inode, const char *symname, int len, int nofs)
3377 {
3378         struct address_space *mapping = inode->i_mapping;
3379         struct page *page;
3380         void *fsdata;
3381         int err;
3382         char *kaddr;
3383         unsigned int flags = AOP_FLAG_UNINTERRUPTIBLE;
3384         if (nofs)
3385                 flags |= AOP_FLAG_NOFS;
3386
3387 retry:
3388         err = pagecache_write_begin(NULL, mapping, 0, len-1,
3389                                 flags, &page, &fsdata);
3390         if (err)
3391                 goto fail;
3392
3393         kaddr = kmap_atomic(page, KM_USER0);
3394         memcpy(kaddr, symname, len-1);
3395         kunmap_atomic(kaddr, KM_USER0);
3396
3397         err = pagecache_write_end(NULL, mapping, 0, len-1, len-1,
3398                                                         page, fsdata);
3399         if (err < 0)
3400                 goto fail;
3401         if (err < len-1)
3402                 goto retry;
3403
3404         mark_inode_dirty(inode);
3405         return 0;
3406 fail:
3407         return err;
3408 }
3409
3410 int page_symlink(struct inode *inode, const char *symname, int len)
3411 {
3412         return __page_symlink(inode, symname, len,
3413                         !(mapping_gfp_mask(inode->i_mapping) & __GFP_FS));
3414 }
3415
3416 const struct inode_operations page_symlink_inode_operations = {
3417         .readlink       = generic_readlink,
3418         .follow_link    = page_follow_link_light,
3419         .put_link       = page_put_link,
3420 };
3421
3422 EXPORT_SYMBOL(user_path_at);
3423 EXPORT_SYMBOL(follow_down_one);
3424 EXPORT_SYMBOL(follow_down);
3425 EXPORT_SYMBOL(follow_up);
3426 EXPORT_SYMBOL(get_write_access); /* binfmt_aout */
3427 EXPORT_SYMBOL(getname);
3428 EXPORT_SYMBOL(lock_rename);
3429 EXPORT_SYMBOL(lookup_one_len);
3430 EXPORT_SYMBOL(page_follow_link_light);
3431 EXPORT_SYMBOL(page_put_link);
3432 EXPORT_SYMBOL(page_readlink);
3433 EXPORT_SYMBOL(__page_symlink);
3434 EXPORT_SYMBOL(page_symlink);
3435 EXPORT_SYMBOL(page_symlink_inode_operations);
3436 EXPORT_SYMBOL(kern_path_parent);
3437 EXPORT_SYMBOL(kern_path);
3438 EXPORT_SYMBOL(vfs_path_lookup);
3439 EXPORT_SYMBOL(inode_permission);
3440 EXPORT_SYMBOL(file_permission);
3441 EXPORT_SYMBOL(unlock_rename);
3442 EXPORT_SYMBOL(vfs_create);
3443 EXPORT_SYMBOL(vfs_follow_link);
3444 EXPORT_SYMBOL(vfs_link);
3445 EXPORT_SYMBOL(vfs_mkdir);
3446 EXPORT_SYMBOL(vfs_mknod);
3447 EXPORT_SYMBOL(generic_permission);
3448 EXPORT_SYMBOL(vfs_readlink);
3449 EXPORT_SYMBOL(vfs_rename);
3450 EXPORT_SYMBOL(vfs_rmdir);
3451 EXPORT_SYMBOL(vfs_symlink);
3452 EXPORT_SYMBOL(vfs_unlink);
3453 EXPORT_SYMBOL(dentry_unhash);
3454 EXPORT_SYMBOL(generic_readlink);