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