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