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