OSDN Git Service

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