OSDN Git Service

Merge tag 'v4.4.214' into 10
[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_mode: mode bits of directory
1091  * @dir_uid: owner of directory
1092  * @inode: the inode of the file to open
1093  *
1094  * Block an O_CREAT open of a FIFO (or a regular file) when:
1095  *   - sysctl_protected_fifos (or sysctl_protected_regular) is enabled
1096  *   - the file already exists
1097  *   - we are in a sticky directory
1098  *   - we don't own the file
1099  *   - the owner of the directory doesn't own the file
1100  *   - the directory is world writable
1101  * If the sysctl_protected_fifos (or sysctl_protected_regular) is set to 2
1102  * the directory doesn't have to be world writable: being group writable will
1103  * be enough.
1104  *
1105  * Returns 0 if the open is allowed, -ve on error.
1106  */
1107 static int may_create_in_sticky(umode_t dir_mode, kuid_t dir_uid,
1108                                 struct inode * const inode)
1109 {
1110         if ((!sysctl_protected_fifos && S_ISFIFO(inode->i_mode)) ||
1111             (!sysctl_protected_regular && S_ISREG(inode->i_mode)) ||
1112             likely(!(dir_mode & S_ISVTX)) ||
1113             uid_eq(inode->i_uid, dir_uid) ||
1114             uid_eq(current_fsuid(), inode->i_uid))
1115                 return 0;
1116
1117         if (likely(dir_mode & 0002) ||
1118             (dir_mode & 0020 &&
1119              ((sysctl_protected_fifos >= 2 && S_ISFIFO(inode->i_mode)) ||
1120               (sysctl_protected_regular >= 2 && S_ISREG(inode->i_mode))))) {
1121                 return -EACCES;
1122         }
1123         return 0;
1124 }
1125
1126 static __always_inline
1127 const char *get_link(struct nameidata *nd)
1128 {
1129         struct saved *last = nd->stack + nd->depth - 1;
1130         struct dentry *dentry = last->link.dentry;
1131         struct inode *inode = last->inode;
1132         int error;
1133         const char *res;
1134
1135         if (!(nd->flags & LOOKUP_RCU)) {
1136                 touch_atime(&last->link);
1137                 cond_resched();
1138         } else if (atime_needs_update(&last->link, inode)) {
1139                 if (unlikely(unlazy_walk(nd, NULL, 0)))
1140                         return ERR_PTR(-ECHILD);
1141                 touch_atime(&last->link);
1142         }
1143
1144         error = security_inode_follow_link(dentry, inode,
1145                                            nd->flags & LOOKUP_RCU);
1146         if (unlikely(error))
1147                 return ERR_PTR(error);
1148
1149         nd->last_type = LAST_BIND;
1150         res = inode->i_link;
1151         if (!res) {
1152                 if (nd->flags & LOOKUP_RCU) {
1153                         if (unlikely(unlazy_walk(nd, NULL, 0)))
1154                                 return ERR_PTR(-ECHILD);
1155                 }
1156                 res = inode->i_op->follow_link(dentry, &last->cookie);
1157                 if (IS_ERR_OR_NULL(res)) {
1158                         last->cookie = NULL;
1159                         return res;
1160                 }
1161         }
1162         if (*res == '/') {
1163                 if (nd->flags & LOOKUP_RCU) {
1164                         struct dentry *d;
1165                         if (!nd->root.mnt)
1166                                 set_root_rcu(nd);
1167                         nd->path = nd->root;
1168                         d = nd->path.dentry;
1169                         nd->inode = d->d_inode;
1170                         nd->seq = nd->root_seq;
1171                         if (unlikely(read_seqcount_retry(&d->d_seq, nd->seq)))
1172                                 return ERR_PTR(-ECHILD);
1173                 } else {
1174                         if (!nd->root.mnt)
1175                                 set_root(nd);
1176                         path_put(&nd->path);
1177                         nd->path = nd->root;
1178                         path_get(&nd->root);
1179                         nd->inode = nd->path.dentry->d_inode;
1180                 }
1181                 nd->flags |= LOOKUP_JUMPED;
1182                 while (unlikely(*++res == '/'))
1183                         ;
1184         }
1185         if (!*res)
1186                 res = NULL;
1187         return res;
1188 }
1189
1190 /*
1191  * follow_up - Find the mountpoint of path's vfsmount
1192  *
1193  * Given a path, find the mountpoint of its source file system.
1194  * Replace @path with the path of the mountpoint in the parent mount.
1195  * Up is towards /.
1196  *
1197  * Return 1 if we went up a level and 0 if we were already at the
1198  * root.
1199  */
1200 int follow_up(struct path *path)
1201 {
1202         struct mount *mnt = real_mount(path->mnt);
1203         struct mount *parent;
1204         struct dentry *mountpoint;
1205
1206         read_seqlock_excl(&mount_lock);
1207         parent = mnt->mnt_parent;
1208         if (parent == mnt) {
1209                 read_sequnlock_excl(&mount_lock);
1210                 return 0;
1211         }
1212         mntget(&parent->mnt);
1213         mountpoint = dget(mnt->mnt_mountpoint);
1214         read_sequnlock_excl(&mount_lock);
1215         dput(path->dentry);
1216         path->dentry = mountpoint;
1217         mntput(path->mnt);
1218         path->mnt = &parent->mnt;
1219         return 1;
1220 }
1221 EXPORT_SYMBOL(follow_up);
1222
1223 /*
1224  * Perform an automount
1225  * - return -EISDIR to tell follow_managed() to stop and return the path we
1226  *   were called with.
1227  */
1228 static int follow_automount(struct path *path, struct nameidata *nd,
1229                             bool *need_mntput)
1230 {
1231         struct vfsmount *mnt;
1232         int err;
1233
1234         if (!path->dentry->d_op || !path->dentry->d_op->d_automount)
1235                 return -EREMOTE;
1236
1237         /* We don't want to mount if someone's just doing a stat -
1238          * unless they're stat'ing a directory and appended a '/' to
1239          * the name.
1240          *
1241          * We do, however, want to mount if someone wants to open or
1242          * create a file of any type under the mountpoint, wants to
1243          * traverse through the mountpoint or wants to open the
1244          * mounted directory.  Also, autofs may mark negative dentries
1245          * as being automount points.  These will need the attentions
1246          * of the daemon to instantiate them before they can be used.
1247          */
1248         if (!(nd->flags & (LOOKUP_PARENT | LOOKUP_DIRECTORY |
1249                            LOOKUP_OPEN | LOOKUP_CREATE | LOOKUP_AUTOMOUNT)) &&
1250             path->dentry->d_inode)
1251                 return -EISDIR;
1252
1253         nd->total_link_count++;
1254         if (nd->total_link_count >= 40)
1255                 return -ELOOP;
1256
1257         mnt = path->dentry->d_op->d_automount(path);
1258         if (IS_ERR(mnt)) {
1259                 /*
1260                  * The filesystem is allowed to return -EISDIR here to indicate
1261                  * it doesn't want to automount.  For instance, autofs would do
1262                  * this so that its userspace daemon can mount on this dentry.
1263                  *
1264                  * However, we can only permit this if it's a terminal point in
1265                  * the path being looked up; if it wasn't then the remainder of
1266                  * the path is inaccessible and we should say so.
1267                  */
1268                 if (PTR_ERR(mnt) == -EISDIR && (nd->flags & LOOKUP_PARENT))
1269                         return -EREMOTE;
1270                 return PTR_ERR(mnt);
1271         }
1272
1273         if (!mnt) /* mount collision */
1274                 return 0;
1275
1276         if (!*need_mntput) {
1277                 /* lock_mount() may release path->mnt on error */
1278                 mntget(path->mnt);
1279                 *need_mntput = true;
1280         }
1281         err = finish_automount(mnt, path);
1282
1283         switch (err) {
1284         case -EBUSY:
1285                 /* Someone else made a mount here whilst we were busy */
1286                 return 0;
1287         case 0:
1288                 path_put(path);
1289                 path->mnt = mnt;
1290                 path->dentry = dget(mnt->mnt_root);
1291                 return 0;
1292         default:
1293                 return err;
1294         }
1295
1296 }
1297
1298 /*
1299  * Handle a dentry that is managed in some way.
1300  * - Flagged for transit management (autofs)
1301  * - Flagged as mountpoint
1302  * - Flagged as automount point
1303  *
1304  * This may only be called in refwalk mode.
1305  *
1306  * Serialization is taken care of in namespace.c
1307  */
1308 static int follow_managed(struct path *path, struct nameidata *nd)
1309 {
1310         struct vfsmount *mnt = path->mnt; /* held by caller, must be left alone */
1311         unsigned managed;
1312         bool need_mntput = false;
1313         int ret = 0;
1314
1315         /* Given that we're not holding a lock here, we retain the value in a
1316          * local variable for each dentry as we look at it so that we don't see
1317          * the components of that value change under us */
1318         while (managed = ACCESS_ONCE(path->dentry->d_flags),
1319                managed &= DCACHE_MANAGED_DENTRY,
1320                unlikely(managed != 0)) {
1321                 /* Allow the filesystem to manage the transit without i_mutex
1322                  * being held. */
1323                 if (managed & DCACHE_MANAGE_TRANSIT) {
1324                         BUG_ON(!path->dentry->d_op);
1325                         BUG_ON(!path->dentry->d_op->d_manage);
1326                         ret = path->dentry->d_op->d_manage(path->dentry, false);
1327                         if (ret < 0)
1328                                 break;
1329                 }
1330
1331                 /* Transit to a mounted filesystem. */
1332                 if (managed & DCACHE_MOUNTED) {
1333                         struct vfsmount *mounted = lookup_mnt(path);
1334                         if (mounted) {
1335                                 dput(path->dentry);
1336                                 if (need_mntput)
1337                                         mntput(path->mnt);
1338                                 path->mnt = mounted;
1339                                 path->dentry = dget(mounted->mnt_root);
1340                                 need_mntput = true;
1341                                 continue;
1342                         }
1343
1344                         /* Something is mounted on this dentry in another
1345                          * namespace and/or whatever was mounted there in this
1346                          * namespace got unmounted before lookup_mnt() could
1347                          * get it */
1348                 }
1349
1350                 /* Handle an automount point */
1351                 if (managed & DCACHE_NEED_AUTOMOUNT) {
1352                         ret = follow_automount(path, nd, &need_mntput);
1353                         if (ret < 0)
1354                                 break;
1355                         continue;
1356                 }
1357
1358                 /* We didn't change the current path point */
1359                 break;
1360         }
1361
1362         if (need_mntput && path->mnt == mnt)
1363                 mntput(path->mnt);
1364         if (ret == -EISDIR)
1365                 ret = 0;
1366         if (need_mntput)
1367                 nd->flags |= LOOKUP_JUMPED;
1368         if (unlikely(ret < 0))
1369                 path_put_conditional(path, nd);
1370         return ret;
1371 }
1372
1373 int follow_down_one(struct path *path)
1374 {
1375         struct vfsmount *mounted;
1376
1377         mounted = lookup_mnt(path);
1378         if (mounted) {
1379                 dput(path->dentry);
1380                 mntput(path->mnt);
1381                 path->mnt = mounted;
1382                 path->dentry = dget(mounted->mnt_root);
1383                 return 1;
1384         }
1385         return 0;
1386 }
1387 EXPORT_SYMBOL(follow_down_one);
1388
1389 static inline int managed_dentry_rcu(struct dentry *dentry)
1390 {
1391         return (dentry->d_flags & DCACHE_MANAGE_TRANSIT) ?
1392                 dentry->d_op->d_manage(dentry, true) : 0;
1393 }
1394
1395 /*
1396  * Try to skip to top of mountpoint pile in rcuwalk mode.  Fail if
1397  * we meet a managed dentry that would need blocking.
1398  */
1399 static bool __follow_mount_rcu(struct nameidata *nd, struct path *path,
1400                                struct inode **inode, unsigned *seqp)
1401 {
1402         for (;;) {
1403                 struct mount *mounted;
1404                 /*
1405                  * Don't forget we might have a non-mountpoint managed dentry
1406                  * that wants to block transit.
1407                  */
1408                 switch (managed_dentry_rcu(path->dentry)) {
1409                 case -ECHILD:
1410                 default:
1411                         return false;
1412                 case -EISDIR:
1413                         return true;
1414                 case 0:
1415                         break;
1416                 }
1417
1418                 if (!d_mountpoint(path->dentry))
1419                         return !(path->dentry->d_flags & DCACHE_NEED_AUTOMOUNT);
1420
1421                 mounted = __lookup_mnt(path->mnt, path->dentry);
1422                 if (!mounted)
1423                         break;
1424                 path->mnt = &mounted->mnt;
1425                 path->dentry = mounted->mnt.mnt_root;
1426                 nd->flags |= LOOKUP_JUMPED;
1427                 *seqp = read_seqcount_begin(&path->dentry->d_seq);
1428                 /*
1429                  * Update the inode too. We don't need to re-check the
1430                  * dentry sequence number here after this d_inode read,
1431                  * because a mount-point is always pinned.
1432                  */
1433                 *inode = path->dentry->d_inode;
1434         }
1435         return !read_seqretry(&mount_lock, nd->m_seq) &&
1436                 !(path->dentry->d_flags & DCACHE_NEED_AUTOMOUNT);
1437 }
1438
1439 static int follow_dotdot_rcu(struct nameidata *nd)
1440 {
1441         struct inode *inode = nd->inode;
1442         if (!nd->root.mnt)
1443                 set_root_rcu(nd);
1444
1445         while (1) {
1446                 if (path_equal(&nd->path, &nd->root))
1447                         break;
1448                 if (nd->path.dentry != nd->path.mnt->mnt_root) {
1449                         struct dentry *old = nd->path.dentry;
1450                         struct dentry *parent = old->d_parent;
1451                         unsigned seq;
1452
1453                         inode = parent->d_inode;
1454                         seq = read_seqcount_begin(&parent->d_seq);
1455                         if (unlikely(read_seqcount_retry(&old->d_seq, nd->seq)))
1456                                 return -ECHILD;
1457                         nd->path.dentry = parent;
1458                         nd->seq = seq;
1459                         if (unlikely(!path_connected(&nd->path)))
1460                                 return -ENOENT;
1461                         break;
1462                 } else {
1463                         struct mount *mnt = real_mount(nd->path.mnt);
1464                         struct mount *mparent = mnt->mnt_parent;
1465                         struct dentry *mountpoint = mnt->mnt_mountpoint;
1466                         struct inode *inode2 = mountpoint->d_inode;
1467                         unsigned seq = read_seqcount_begin(&mountpoint->d_seq);
1468                         if (unlikely(read_seqretry(&mount_lock, nd->m_seq)))
1469                                 return -ECHILD;
1470                         if (&mparent->mnt == nd->path.mnt)
1471                                 break;
1472                         /* we know that mountpoint was pinned */
1473                         nd->path.dentry = mountpoint;
1474                         nd->path.mnt = &mparent->mnt;
1475                         inode = inode2;
1476                         nd->seq = seq;
1477                 }
1478         }
1479         while (unlikely(d_mountpoint(nd->path.dentry))) {
1480                 struct mount *mounted;
1481                 mounted = __lookup_mnt(nd->path.mnt, nd->path.dentry);
1482                 if (unlikely(read_seqretry(&mount_lock, nd->m_seq)))
1483                         return -ECHILD;
1484                 if (!mounted)
1485                         break;
1486                 nd->path.mnt = &mounted->mnt;
1487                 nd->path.dentry = mounted->mnt.mnt_root;
1488                 inode = nd->path.dentry->d_inode;
1489                 nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
1490         }
1491         nd->inode = inode;
1492         return 0;
1493 }
1494
1495 /*
1496  * Follow down to the covering mount currently visible to userspace.  At each
1497  * point, the filesystem owning that dentry may be queried as to whether the
1498  * caller is permitted to proceed or not.
1499  */
1500 int follow_down(struct path *path)
1501 {
1502         unsigned managed;
1503         int ret;
1504
1505         while (managed = ACCESS_ONCE(path->dentry->d_flags),
1506                unlikely(managed & DCACHE_MANAGED_DENTRY)) {
1507                 /* Allow the filesystem to manage the transit without i_mutex
1508                  * being held.
1509                  *
1510                  * We indicate to the filesystem if someone is trying to mount
1511                  * something here.  This gives autofs the chance to deny anyone
1512                  * other than its daemon the right to mount on its
1513                  * superstructure.
1514                  *
1515                  * The filesystem may sleep at this point.
1516                  */
1517                 if (managed & DCACHE_MANAGE_TRANSIT) {
1518                         BUG_ON(!path->dentry->d_op);
1519                         BUG_ON(!path->dentry->d_op->d_manage);
1520                         ret = path->dentry->d_op->d_manage(
1521                                 path->dentry, false);
1522                         if (ret < 0)
1523                                 return ret == -EISDIR ? 0 : ret;
1524                 }
1525
1526                 /* Transit to a mounted filesystem. */
1527                 if (managed & DCACHE_MOUNTED) {
1528                         struct vfsmount *mounted = lookup_mnt(path);
1529                         if (!mounted)
1530                                 break;
1531                         dput(path->dentry);
1532                         mntput(path->mnt);
1533                         path->mnt = mounted;
1534                         path->dentry = dget(mounted->mnt_root);
1535                         continue;
1536                 }
1537
1538                 /* Don't handle automount points here */
1539                 break;
1540         }
1541         return 0;
1542 }
1543 EXPORT_SYMBOL(follow_down);
1544
1545 /*
1546  * Skip to top of mountpoint pile in refwalk mode for follow_dotdot()
1547  */
1548 static void follow_mount(struct path *path)
1549 {
1550         while (d_mountpoint(path->dentry)) {
1551                 struct vfsmount *mounted = lookup_mnt(path);
1552                 if (!mounted)
1553                         break;
1554                 dput(path->dentry);
1555                 mntput(path->mnt);
1556                 path->mnt = mounted;
1557                 path->dentry = dget(mounted->mnt_root);
1558         }
1559 }
1560
1561 static int follow_dotdot(struct nameidata *nd)
1562 {
1563         if (!nd->root.mnt)
1564                 set_root(nd);
1565
1566         while(1) {
1567                 struct dentry *old = nd->path.dentry;
1568
1569                 if (nd->path.dentry == nd->root.dentry &&
1570                     nd->path.mnt == nd->root.mnt) {
1571                         break;
1572                 }
1573                 if (nd->path.dentry != nd->path.mnt->mnt_root) {
1574                         /* rare case of legitimate dget_parent()... */
1575                         nd->path.dentry = dget_parent(nd->path.dentry);
1576                         dput(old);
1577                         if (unlikely(!path_connected(&nd->path)))
1578                                 return -ENOENT;
1579                         break;
1580                 }
1581                 if (!follow_up(&nd->path))
1582                         break;
1583         }
1584         follow_mount(&nd->path);
1585         nd->inode = nd->path.dentry->d_inode;
1586         return 0;
1587 }
1588
1589 /*
1590  * This looks up the name in dcache, possibly revalidates the old dentry and
1591  * allocates a new one if not found or not valid.  In the need_lookup argument
1592  * returns whether i_op->lookup is necessary.
1593  *
1594  * dir->d_inode->i_mutex must be held
1595  */
1596 static struct dentry *lookup_dcache(struct qstr *name, struct dentry *dir,
1597                                     unsigned int flags, bool *need_lookup)
1598 {
1599         struct dentry *dentry;
1600         int error;
1601
1602         *need_lookup = false;
1603         dentry = d_lookup(dir, name);
1604         if (dentry) {
1605                 if (dentry->d_flags & DCACHE_OP_REVALIDATE) {
1606                         error = d_revalidate(dentry, flags);
1607                         if (unlikely(error <= 0)) {
1608                                 if (error < 0) {
1609                                         dput(dentry);
1610                                         return ERR_PTR(error);
1611                                 } else {
1612                                         d_invalidate(dentry);
1613                                         dput(dentry);
1614                                         dentry = NULL;
1615                                 }
1616                         }
1617                 }
1618         }
1619
1620         if (!dentry) {
1621                 dentry = d_alloc(dir, name);
1622                 if (unlikely(!dentry))
1623                         return ERR_PTR(-ENOMEM);
1624
1625                 *need_lookup = true;
1626         }
1627         return dentry;
1628 }
1629
1630 /*
1631  * Call i_op->lookup on the dentry.  The dentry must be negative and
1632  * unhashed.
1633  *
1634  * dir->d_inode->i_mutex must be held
1635  */
1636 static struct dentry *lookup_real(struct inode *dir, struct dentry *dentry,
1637                                   unsigned int flags)
1638 {
1639         struct dentry *old;
1640
1641         /* Don't create child dentry for a dead directory. */
1642         if (unlikely(IS_DEADDIR(dir))) {
1643                 dput(dentry);
1644                 return ERR_PTR(-ENOENT);
1645         }
1646
1647         old = dir->i_op->lookup(dir, dentry, flags);
1648         if (unlikely(old)) {
1649                 dput(dentry);
1650                 dentry = old;
1651         }
1652         return dentry;
1653 }
1654
1655 static struct dentry *__lookup_hash(struct qstr *name,
1656                 struct dentry *base, unsigned int flags)
1657 {
1658         bool need_lookup;
1659         struct dentry *dentry;
1660
1661         dentry = lookup_dcache(name, base, flags, &need_lookup);
1662         if (!need_lookup)
1663                 return dentry;
1664
1665         return lookup_real(base->d_inode, dentry, flags);
1666 }
1667
1668 /*
1669  *  It's more convoluted than I'd like it to be, but... it's still fairly
1670  *  small and for now I'd prefer to have fast path as straight as possible.
1671  *  It _is_ time-critical.
1672  */
1673 static int lookup_fast(struct nameidata *nd,
1674                        struct path *path, struct inode **inode,
1675                        unsigned *seqp)
1676 {
1677         struct vfsmount *mnt = nd->path.mnt;
1678         struct dentry *dentry, *parent = nd->path.dentry;
1679         int need_reval = 1;
1680         int status = 1;
1681         int err;
1682
1683         /*
1684          * Rename seqlock is not required here because in the off chance
1685          * of a false negative due to a concurrent rename, we're going to
1686          * do the non-racy lookup, below.
1687          */
1688         if (nd->flags & LOOKUP_RCU) {
1689                 unsigned seq;
1690                 bool negative;
1691                 dentry = __d_lookup_rcu(parent, &nd->last, &seq);
1692                 if (!dentry)
1693                         goto unlazy;
1694
1695                 /*
1696                  * This sequence count validates that the inode matches
1697                  * the dentry name information from lookup.
1698                  */
1699                 *inode = d_backing_inode(dentry);
1700                 negative = d_is_negative(dentry);
1701                 if (read_seqcount_retry(&dentry->d_seq, seq))
1702                         return -ECHILD;
1703
1704                 /*
1705                  * This sequence count validates that the parent had no
1706                  * changes while we did the lookup of the dentry above.
1707                  *
1708                  * The memory barrier in read_seqcount_begin of child is
1709                  *  enough, we can use __read_seqcount_retry here.
1710                  */
1711                 if (__read_seqcount_retry(&parent->d_seq, nd->seq))
1712                         return -ECHILD;
1713
1714                 *seqp = seq;
1715                 if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE)) {
1716                         status = d_revalidate(dentry, nd->flags);
1717                         if (unlikely(status <= 0)) {
1718                                 if (status != -ECHILD)
1719                                         need_reval = 0;
1720                                 goto unlazy;
1721                         }
1722                 }
1723                 /*
1724                  * Note: do negative dentry check after revalidation in
1725                  * case that drops it.
1726                  */
1727                 if (negative)
1728                         return -ENOENT;
1729                 path->mnt = mnt;
1730                 path->dentry = dentry;
1731                 if (likely(__follow_mount_rcu(nd, path, inode, seqp)))
1732                         return 0;
1733 unlazy:
1734                 if (unlazy_walk(nd, dentry, seq))
1735                         return -ECHILD;
1736         } else {
1737                 dentry = __d_lookup(parent, &nd->last);
1738         }
1739
1740         if (unlikely(!dentry))
1741                 goto need_lookup;
1742
1743         if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE) && need_reval)
1744                 status = d_revalidate(dentry, nd->flags);
1745         if (unlikely(status <= 0)) {
1746                 if (status < 0) {
1747                         dput(dentry);
1748                         return status;
1749                 }
1750                 d_invalidate(dentry);
1751                 dput(dentry);
1752                 goto need_lookup;
1753         }
1754
1755         if (unlikely(d_is_negative(dentry))) {
1756                 dput(dentry);
1757                 return -ENOENT;
1758         }
1759         path->mnt = mnt;
1760         path->dentry = dentry;
1761         err = follow_managed(path, nd);
1762         if (likely(!err))
1763                 *inode = d_backing_inode(path->dentry);
1764         return err;
1765
1766 need_lookup:
1767         return 1;
1768 }
1769
1770 /* Fast lookup failed, do it the slow way */
1771 static int lookup_slow(struct nameidata *nd, struct path *path)
1772 {
1773         struct dentry *dentry, *parent;
1774
1775         parent = nd->path.dentry;
1776         BUG_ON(nd->inode != parent->d_inode);
1777
1778         mutex_lock(&parent->d_inode->i_mutex);
1779         dentry = __lookup_hash(&nd->last, parent, nd->flags);
1780         mutex_unlock(&parent->d_inode->i_mutex);
1781         if (IS_ERR(dentry))
1782                 return PTR_ERR(dentry);
1783         path->mnt = nd->path.mnt;
1784         path->dentry = dentry;
1785         return follow_managed(path, nd);
1786 }
1787
1788 static inline int may_lookup(struct nameidata *nd)
1789 {
1790         if (nd->flags & LOOKUP_RCU) {
1791                 int err = inode_permission2(nd->path.mnt, nd->inode, MAY_EXEC|MAY_NOT_BLOCK);
1792                 if (err != -ECHILD)
1793                         return err;
1794                 if (unlazy_walk(nd, NULL, 0))
1795                         return -ECHILD;
1796         }
1797         return inode_permission2(nd->path.mnt, nd->inode, MAY_EXEC);
1798 }
1799
1800 static inline int handle_dots(struct nameidata *nd, int type)
1801 {
1802         if (type == LAST_DOTDOT) {
1803                 if (nd->flags & LOOKUP_RCU) {
1804                         return follow_dotdot_rcu(nd);
1805                 } else
1806                         return follow_dotdot(nd);
1807         }
1808         return 0;
1809 }
1810
1811 static int pick_link(struct nameidata *nd, struct path *link,
1812                      struct inode *inode, unsigned seq)
1813 {
1814         int error;
1815         struct saved *last;
1816         if (unlikely(nd->total_link_count++ >= MAXSYMLINKS)) {
1817                 path_to_nameidata(link, nd);
1818                 return -ELOOP;
1819         }
1820         if (!(nd->flags & LOOKUP_RCU)) {
1821                 if (link->mnt == nd->path.mnt)
1822                         mntget(link->mnt);
1823         }
1824         error = nd_alloc_stack(nd);
1825         if (unlikely(error)) {
1826                 if (error == -ECHILD) {
1827                         if (unlikely(unlazy_link(nd, link, seq)))
1828                                 return -ECHILD;
1829                         error = nd_alloc_stack(nd);
1830                 }
1831                 if (error) {
1832                         path_put(link);
1833                         return error;
1834                 }
1835         }
1836
1837         last = nd->stack + nd->depth++;
1838         last->link = *link;
1839         last->cookie = NULL;
1840         last->inode = inode;
1841         last->seq = seq;
1842         return 1;
1843 }
1844
1845 /*
1846  * Do we need to follow links? We _really_ want to be able
1847  * to do this check without having to look at inode->i_op,
1848  * so we keep a cache of "no, this doesn't need follow_link"
1849  * for the common case.
1850  */
1851 static inline int should_follow_link(struct nameidata *nd, struct path *link,
1852                                      int follow,
1853                                      struct inode *inode, unsigned seq)
1854 {
1855         if (likely(!d_is_symlink(link->dentry)))
1856                 return 0;
1857         if (!follow)
1858                 return 0;
1859         /* make sure that d_is_symlink above matches inode */
1860         if (nd->flags & LOOKUP_RCU) {
1861                 if (read_seqcount_retry(&link->dentry->d_seq, seq))
1862                         return -ECHILD;
1863         }
1864         return pick_link(nd, link, inode, seq);
1865 }
1866
1867 enum {WALK_GET = 1, WALK_PUT = 2};
1868
1869 static int walk_component(struct nameidata *nd, int flags)
1870 {
1871         struct path path;
1872         struct inode *inode;
1873         unsigned seq;
1874         int err;
1875         /*
1876          * "." and ".." are special - ".." especially so because it has
1877          * to be able to know about the current root directory and
1878          * parent relationships.
1879          */
1880         if (unlikely(nd->last_type != LAST_NORM)) {
1881                 err = handle_dots(nd, nd->last_type);
1882                 if (flags & WALK_PUT)
1883                         put_link(nd);
1884                 return err;
1885         }
1886         err = lookup_fast(nd, &path, &inode, &seq);
1887         if (unlikely(err)) {
1888                 if (err < 0)
1889                         return err;
1890
1891                 err = lookup_slow(nd, &path);
1892                 if (err < 0)
1893                         return err;
1894
1895                 seq = 0;        /* we are already out of RCU mode */
1896                 err = -ENOENT;
1897                 if (d_is_negative(path.dentry))
1898                         goto out_path_put;
1899                 inode = d_backing_inode(path.dentry);
1900         }
1901
1902         if (flags & WALK_PUT)
1903                 put_link(nd);
1904         err = should_follow_link(nd, &path, flags & WALK_GET, inode, seq);
1905         if (unlikely(err))
1906                 return err;
1907         path_to_nameidata(&path, nd);
1908         nd->inode = inode;
1909         nd->seq = seq;
1910         return 0;
1911
1912 out_path_put:
1913         path_to_nameidata(&path, nd);
1914         return err;
1915 }
1916
1917 /*
1918  * We can do the critical dentry name comparison and hashing
1919  * operations one word at a time, but we are limited to:
1920  *
1921  * - Architectures with fast unaligned word accesses. We could
1922  *   do a "get_unaligned()" if this helps and is sufficiently
1923  *   fast.
1924  *
1925  * - non-CONFIG_DEBUG_PAGEALLOC configurations (so that we
1926  *   do not trap on the (extremely unlikely) case of a page
1927  *   crossing operation.
1928  *
1929  * - Furthermore, we need an efficient 64-bit compile for the
1930  *   64-bit case in order to generate the "number of bytes in
1931  *   the final mask". Again, that could be replaced with a
1932  *   efficient population count instruction or similar.
1933  */
1934 #ifdef CONFIG_DCACHE_WORD_ACCESS
1935
1936 #include <asm/word-at-a-time.h>
1937
1938 #ifdef CONFIG_64BIT
1939
1940 static inline unsigned int fold_hash(unsigned long hash)
1941 {
1942         return hash_64(hash, 32);
1943 }
1944
1945 #else   /* 32-bit case */
1946
1947 #define fold_hash(x) (x)
1948
1949 #endif
1950
1951 unsigned int full_name_hash(const unsigned char *name, unsigned int len)
1952 {
1953         unsigned long a, mask;
1954         unsigned long hash = 0;
1955
1956         for (;;) {
1957                 a = load_unaligned_zeropad(name);
1958                 if (len < sizeof(unsigned long))
1959                         break;
1960                 hash += a;
1961                 hash *= 9;
1962                 name += sizeof(unsigned long);
1963                 len -= sizeof(unsigned long);
1964                 if (!len)
1965                         goto done;
1966         }
1967         mask = bytemask_from_count(len);
1968         hash += mask & a;
1969 done:
1970         return fold_hash(hash);
1971 }
1972 EXPORT_SYMBOL(full_name_hash);
1973
1974 /*
1975  * Calculate the length and hash of the path component, and
1976  * return the "hash_len" as the result.
1977  */
1978 static inline u64 hash_name(const char *name)
1979 {
1980         unsigned long a, b, adata, bdata, mask, hash, len;
1981         const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
1982
1983         hash = a = 0;
1984         len = -sizeof(unsigned long);
1985         do {
1986                 hash = (hash + a) * 9;
1987                 len += sizeof(unsigned long);
1988                 a = load_unaligned_zeropad(name+len);
1989                 b = a ^ REPEAT_BYTE('/');
1990         } while (!(has_zero(a, &adata, &constants) | has_zero(b, &bdata, &constants)));
1991
1992         adata = prep_zero_mask(a, adata, &constants);
1993         bdata = prep_zero_mask(b, bdata, &constants);
1994
1995         mask = create_zero_mask(adata | bdata);
1996
1997         hash += a & zero_bytemask(mask);
1998         len += find_zero(mask);
1999         return hashlen_create(fold_hash(hash), len);
2000 }
2001
2002 #else
2003
2004 unsigned int full_name_hash(const unsigned char *name, unsigned int len)
2005 {
2006         unsigned long hash = init_name_hash();
2007         while (len--)
2008                 hash = partial_name_hash(*name++, hash);
2009         return end_name_hash(hash);
2010 }
2011 EXPORT_SYMBOL(full_name_hash);
2012
2013 /*
2014  * We know there's a real path component here of at least
2015  * one character.
2016  */
2017 static inline u64 hash_name(const char *name)
2018 {
2019         unsigned long hash = init_name_hash();
2020         unsigned long len = 0, c;
2021
2022         c = (unsigned char)*name;
2023         do {
2024                 len++;
2025                 hash = partial_name_hash(c, hash);
2026                 c = (unsigned char)name[len];
2027         } while (c && c != '/');
2028         return hashlen_create(end_name_hash(hash), len);
2029 }
2030
2031 #endif
2032
2033 /*
2034  * Name resolution.
2035  * This is the basic name resolution function, turning a pathname into
2036  * the final dentry. We expect 'base' to be positive and a directory.
2037  *
2038  * Returns 0 and nd will have valid dentry and mnt on success.
2039  * Returns error and drops reference to input namei data on failure.
2040  */
2041 static int link_path_walk(const char *name, struct nameidata *nd)
2042 {
2043         int err;
2044
2045         while (*name=='/')
2046                 name++;
2047         if (!*name)
2048                 return 0;
2049
2050         /* At this point we know we have a real path component. */
2051         for(;;) {
2052                 u64 hash_len;
2053                 int type;
2054
2055                 err = may_lookup(nd);
2056                 if (err)
2057                         return err;
2058
2059                 hash_len = hash_name(name);
2060
2061                 type = LAST_NORM;
2062                 if (name[0] == '.') switch (hashlen_len(hash_len)) {
2063                         case 2:
2064                                 if (name[1] == '.') {
2065                                         type = LAST_DOTDOT;
2066                                         nd->flags |= LOOKUP_JUMPED;
2067                                 }
2068                                 break;
2069                         case 1:
2070                                 type = LAST_DOT;
2071                 }
2072                 if (likely(type == LAST_NORM)) {
2073                         struct dentry *parent = nd->path.dentry;
2074                         nd->flags &= ~LOOKUP_JUMPED;
2075                         if (unlikely(parent->d_flags & DCACHE_OP_HASH)) {
2076                                 struct qstr this = { { .hash_len = hash_len }, .name = name };
2077                                 err = parent->d_op->d_hash(parent, &this);
2078                                 if (err < 0)
2079                                         return err;
2080                                 hash_len = this.hash_len;
2081                                 name = this.name;
2082                         }
2083                 }
2084
2085                 nd->last.hash_len = hash_len;
2086                 nd->last.name = name;
2087                 nd->last_type = type;
2088
2089                 name += hashlen_len(hash_len);
2090                 if (!*name)
2091                         goto OK;
2092                 /*
2093                  * If it wasn't NUL, we know it was '/'. Skip that
2094                  * slash, and continue until no more slashes.
2095                  */
2096                 do {
2097                         name++;
2098                 } while (unlikely(*name == '/'));
2099                 if (unlikely(!*name)) {
2100 OK:
2101                         /* pathname body, done */
2102                         if (!nd->depth)
2103                                 return 0;
2104                         name = nd->stack[nd->depth - 1].name;
2105                         /* trailing symlink, done */
2106                         if (!name)
2107                                 return 0;
2108                         /* last component of nested symlink */
2109                         err = walk_component(nd, WALK_GET | WALK_PUT);
2110                 } else {
2111                         err = walk_component(nd, WALK_GET);
2112                 }
2113                 if (err < 0)
2114                         return err;
2115
2116                 if (err) {
2117                         const char *s = get_link(nd);
2118
2119                         if (IS_ERR(s))
2120                                 return PTR_ERR(s);
2121                         err = 0;
2122                         if (unlikely(!s)) {
2123                                 /* jumped */
2124                                 put_link(nd);
2125                         } else {
2126                                 nd->stack[nd->depth - 1].name = name;
2127                                 name = s;
2128                                 continue;
2129                         }
2130                 }
2131                 if (unlikely(!d_can_lookup(nd->path.dentry))) {
2132                         if (nd->flags & LOOKUP_RCU) {
2133                                 if (unlazy_walk(nd, NULL, 0))
2134                                         return -ECHILD;
2135                         }
2136                         return -ENOTDIR;
2137                 }
2138         }
2139 }
2140
2141 static const char *path_init(struct nameidata *nd, unsigned flags)
2142 {
2143         int retval = 0;
2144         const char *s = nd->name->name;
2145
2146         if (!*s)
2147                 flags &= ~LOOKUP_RCU;
2148
2149         nd->last_type = LAST_ROOT; /* if there are only slashes... */
2150         nd->flags = flags | LOOKUP_JUMPED | LOOKUP_PARENT;
2151         nd->depth = 0;
2152         if (flags & LOOKUP_ROOT) {
2153                 struct dentry *root = nd->root.dentry;
2154                 struct vfsmount *mnt = nd->root.mnt;
2155                 struct inode *inode = root->d_inode;
2156                 if (*s) {
2157                         if (!d_can_lookup(root))
2158                                 return ERR_PTR(-ENOTDIR);
2159                         retval = inode_permission2(mnt, inode, MAY_EXEC);
2160                         if (retval)
2161                                 return ERR_PTR(retval);
2162                 }
2163                 nd->path = nd->root;
2164                 nd->inode = inode;
2165                 if (flags & LOOKUP_RCU) {
2166                         rcu_read_lock();
2167                         nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
2168                         nd->root_seq = nd->seq;
2169                         nd->m_seq = read_seqbegin(&mount_lock);
2170                 } else {
2171                         path_get(&nd->path);
2172                 }
2173                 return s;
2174         }
2175
2176         nd->root.mnt = NULL;
2177
2178         nd->m_seq = read_seqbegin(&mount_lock);
2179         if (*s == '/') {
2180                 if (flags & LOOKUP_RCU) {
2181                         rcu_read_lock();
2182                         set_root_rcu(nd);
2183                         nd->seq = nd->root_seq;
2184                 } else {
2185                         set_root(nd);
2186                         path_get(&nd->root);
2187                 }
2188                 nd->path = nd->root;
2189         } else if (nd->dfd == AT_FDCWD) {
2190                 if (flags & LOOKUP_RCU) {
2191                         struct fs_struct *fs = current->fs;
2192                         unsigned seq;
2193
2194                         rcu_read_lock();
2195
2196                         do {
2197                                 seq = read_seqcount_begin(&fs->seq);
2198                                 nd->path = fs->pwd;
2199                                 nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
2200                         } while (read_seqcount_retry(&fs->seq, seq));
2201                 } else {
2202                         get_fs_pwd(current->fs, &nd->path);
2203                 }
2204         } else {
2205                 /* Caller must check execute permissions on the starting path component */
2206                 struct fd f = fdget_raw(nd->dfd);
2207                 struct dentry *dentry;
2208
2209                 if (!f.file)
2210                         return ERR_PTR(-EBADF);
2211
2212                 dentry = f.file->f_path.dentry;
2213
2214                 if (*s) {
2215                         if (!d_can_lookup(dentry)) {
2216                                 fdput(f);
2217                                 return ERR_PTR(-ENOTDIR);
2218                         }
2219                 }
2220
2221                 nd->path = f.file->f_path;
2222                 if (flags & LOOKUP_RCU) {
2223                         rcu_read_lock();
2224                         nd->inode = nd->path.dentry->d_inode;
2225                         nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
2226                 } else {
2227                         path_get(&nd->path);
2228                         nd->inode = nd->path.dentry->d_inode;
2229                 }
2230                 fdput(f);
2231                 return s;
2232         }
2233
2234         nd->inode = nd->path.dentry->d_inode;
2235         if (!(flags & LOOKUP_RCU))
2236                 return s;
2237         if (likely(!read_seqcount_retry(&nd->path.dentry->d_seq, nd->seq)))
2238                 return s;
2239         if (!(nd->flags & LOOKUP_ROOT))
2240                 nd->root.mnt = NULL;
2241         rcu_read_unlock();
2242         return ERR_PTR(-ECHILD);
2243 }
2244
2245 static const char *trailing_symlink(struct nameidata *nd)
2246 {
2247         const char *s;
2248         int error = may_follow_link(nd);
2249         if (unlikely(error))
2250                 return ERR_PTR(error);
2251         nd->flags |= LOOKUP_PARENT;
2252         nd->stack[0].name = NULL;
2253         s = get_link(nd);
2254         return s ? s : "";
2255 }
2256
2257 static inline int lookup_last(struct nameidata *nd)
2258 {
2259         if (nd->last_type == LAST_NORM && nd->last.name[nd->last.len])
2260                 nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
2261
2262         nd->flags &= ~LOOKUP_PARENT;
2263         return walk_component(nd,
2264                         nd->flags & LOOKUP_FOLLOW
2265                                 ? nd->depth
2266                                         ? WALK_PUT | WALK_GET
2267                                         : WALK_GET
2268                                 : 0);
2269 }
2270
2271 /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
2272 static int path_lookupat(struct nameidata *nd, unsigned flags, struct path *path)
2273 {
2274         const char *s = path_init(nd, flags);
2275         int err;
2276
2277         if (IS_ERR(s))
2278                 return PTR_ERR(s);
2279         while (!(err = link_path_walk(s, nd))
2280                 && ((err = lookup_last(nd)) > 0)) {
2281                 s = trailing_symlink(nd);
2282                 if (IS_ERR(s)) {
2283                         err = PTR_ERR(s);
2284                         break;
2285                 }
2286         }
2287         if (!err)
2288                 err = complete_walk(nd);
2289
2290         if (!err && nd->flags & LOOKUP_DIRECTORY)
2291                 if (!d_can_lookup(nd->path.dentry))
2292                         err = -ENOTDIR;
2293
2294         if (!err) {
2295                 *path = nd->path;
2296                 nd->path.mnt = NULL;
2297                 nd->path.dentry = NULL;
2298         }
2299         terminate_walk(nd);
2300         return err;
2301 }
2302
2303 static int filename_lookup(int dfd, struct filename *name, unsigned flags,
2304                            struct path *path, struct path *root)
2305 {
2306         int retval;
2307         struct nameidata nd;
2308         if (IS_ERR(name))
2309                 return PTR_ERR(name);
2310         if (unlikely(root)) {
2311                 nd.root = *root;
2312                 flags |= LOOKUP_ROOT;
2313         }
2314         set_nameidata(&nd, dfd, name);
2315         retval = path_lookupat(&nd, flags | LOOKUP_RCU, path);
2316         if (unlikely(retval == -ECHILD))
2317                 retval = path_lookupat(&nd, flags, path);
2318         if (unlikely(retval == -ESTALE))
2319                 retval = path_lookupat(&nd, flags | LOOKUP_REVAL, path);
2320
2321         if (likely(!retval))
2322                 audit_inode(name, path->dentry, flags & LOOKUP_PARENT);
2323         restore_nameidata();
2324         putname(name);
2325         return retval;
2326 }
2327
2328 /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
2329 static int path_parentat(struct nameidata *nd, unsigned flags,
2330                                 struct path *parent)
2331 {
2332         const char *s = path_init(nd, flags);
2333         int err;
2334         if (IS_ERR(s))
2335                 return PTR_ERR(s);
2336         err = link_path_walk(s, nd);
2337         if (!err)
2338                 err = complete_walk(nd);
2339         if (!err) {
2340                 *parent = nd->path;
2341                 nd->path.mnt = NULL;
2342                 nd->path.dentry = NULL;
2343         }
2344         terminate_walk(nd);
2345         return err;
2346 }
2347
2348 static struct filename *filename_parentat(int dfd, struct filename *name,
2349                                 unsigned int flags, struct path *parent,
2350                                 struct qstr *last, int *type)
2351 {
2352         int retval;
2353         struct nameidata nd;
2354
2355         if (IS_ERR(name))
2356                 return name;
2357         set_nameidata(&nd, dfd, name);
2358         retval = path_parentat(&nd, flags | LOOKUP_RCU, parent);
2359         if (unlikely(retval == -ECHILD))
2360                 retval = path_parentat(&nd, flags, parent);
2361         if (unlikely(retval == -ESTALE))
2362                 retval = path_parentat(&nd, flags | LOOKUP_REVAL, parent);
2363         if (likely(!retval)) {
2364                 *last = nd.last;
2365                 *type = nd.last_type;
2366                 audit_inode(name, parent->dentry, LOOKUP_PARENT);
2367         } else {
2368                 putname(name);
2369                 name = ERR_PTR(retval);
2370         }
2371         restore_nameidata();
2372         return name;
2373 }
2374
2375 /* does lookup, returns the object with parent locked */
2376 struct dentry *kern_path_locked(const char *name, struct path *path)
2377 {
2378         struct filename *filename;
2379         struct dentry *d;
2380         struct qstr last;
2381         int type;
2382
2383         filename = filename_parentat(AT_FDCWD, getname_kernel(name), 0, path,
2384                                     &last, &type);
2385         if (IS_ERR(filename))
2386                 return ERR_CAST(filename);
2387         if (unlikely(type != LAST_NORM)) {
2388                 path_put(path);
2389                 putname(filename);
2390                 return ERR_PTR(-EINVAL);
2391         }
2392         mutex_lock_nested(&path->dentry->d_inode->i_mutex, I_MUTEX_PARENT);
2393         d = __lookup_hash(&last, path->dentry, 0);
2394         if (IS_ERR(d)) {
2395                 mutex_unlock(&path->dentry->d_inode->i_mutex);
2396                 path_put(path);
2397         }
2398         putname(filename);
2399         return d;
2400 }
2401
2402 int kern_path(const char *name, unsigned int flags, struct path *path)
2403 {
2404         return filename_lookup(AT_FDCWD, getname_kernel(name),
2405                                flags, path, NULL);
2406 }
2407 EXPORT_SYMBOL(kern_path);
2408
2409 /**
2410  * vfs_path_lookup - lookup a file path relative to a dentry-vfsmount pair
2411  * @dentry:  pointer to dentry of the base directory
2412  * @mnt: pointer to vfs mount of the base directory
2413  * @name: pointer to file name
2414  * @flags: lookup flags
2415  * @path: pointer to struct path to fill
2416  */
2417 int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt,
2418                     const char *name, unsigned int flags,
2419                     struct path *path)
2420 {
2421         struct path root = {.mnt = mnt, .dentry = dentry};
2422         /* the first argument of filename_lookup() is ignored with root */
2423         return filename_lookup(AT_FDCWD, getname_kernel(name),
2424                                flags , path, &root);
2425 }
2426 EXPORT_SYMBOL(vfs_path_lookup);
2427
2428 /**
2429  * lookup_one_len - filesystem helper to lookup single pathname component
2430  * @name:       pathname component to lookup
2431  * @mnt:        mount we are looking up on
2432  * @base:       base directory to lookup from
2433  * @len:        maximum length @len should be interpreted to
2434  *
2435  * Note that this routine is purely a helper for filesystem usage and should
2436  * not be called by generic code.
2437  */
2438 struct dentry *lookup_one_len2(const char *name, struct vfsmount *mnt, struct dentry *base, int len)
2439 {
2440         struct qstr this;
2441         unsigned int c;
2442         int err;
2443
2444         WARN_ON_ONCE(!mutex_is_locked(&base->d_inode->i_mutex));
2445
2446         this.name = name;
2447         this.len = len;
2448         this.hash = full_name_hash(name, len);
2449         if (!len)
2450                 return ERR_PTR(-EACCES);
2451
2452         if (unlikely(name[0] == '.')) {
2453                 if (len < 2 || (len == 2 && name[1] == '.'))
2454                         return ERR_PTR(-EACCES);
2455         }
2456
2457         while (len--) {
2458                 c = *(const unsigned char *)name++;
2459                 if (c == '/' || c == '\0')
2460                         return ERR_PTR(-EACCES);
2461         }
2462         /*
2463          * See if the low-level filesystem might want
2464          * to use its own hash..
2465          */
2466         if (base->d_flags & DCACHE_OP_HASH) {
2467                 int err = base->d_op->d_hash(base, &this);
2468                 if (err < 0)
2469                         return ERR_PTR(err);
2470         }
2471
2472         err = inode_permission2(mnt, base->d_inode, MAY_EXEC);
2473         if (err)
2474                 return ERR_PTR(err);
2475
2476         return __lookup_hash(&this, base, 0);
2477 }
2478 EXPORT_SYMBOL(lookup_one_len2);
2479
2480 struct dentry *lookup_one_len(const char *name, struct dentry *base, int len)
2481 {
2482         return lookup_one_len2(name, NULL, base, len);
2483 }
2484 EXPORT_SYMBOL(lookup_one_len);
2485
2486 int user_path_at_empty(int dfd, const char __user *name, unsigned flags,
2487                  struct path *path, int *empty)
2488 {
2489         return filename_lookup(dfd, getname_flags(name, flags, empty),
2490                                flags, path, NULL);
2491 }
2492 EXPORT_SYMBOL(user_path_at_empty);
2493
2494 /*
2495  * NB: most callers don't do anything directly with the reference to the
2496  *     to struct filename, but the nd->last pointer points into the name string
2497  *     allocated by getname. So we must hold the reference to it until all
2498  *     path-walking is complete.
2499  */
2500 static inline struct filename *
2501 user_path_parent(int dfd, const char __user *path,
2502                  struct path *parent,
2503                  struct qstr *last,
2504                  int *type,
2505                  unsigned int flags)
2506 {
2507         /* only LOOKUP_REVAL is allowed in extra flags */
2508         return filename_parentat(dfd, getname(path), flags & LOOKUP_REVAL,
2509                                  parent, last, type);
2510 }
2511
2512 /**
2513  * mountpoint_last - look up last component for umount
2514  * @nd:   pathwalk nameidata - currently pointing at parent directory of "last"
2515  * @path: pointer to container for result
2516  *
2517  * This is a special lookup_last function just for umount. In this case, we
2518  * need to resolve the path without doing any revalidation.
2519  *
2520  * The nameidata should be the result of doing a LOOKUP_PARENT pathwalk. Since
2521  * mountpoints are always pinned in the dcache, their ancestors are too. Thus,
2522  * in almost all cases, this lookup will be served out of the dcache. The only
2523  * cases where it won't are if nd->last refers to a symlink or the path is
2524  * bogus and it doesn't exist.
2525  *
2526  * Returns:
2527  * -error: if there was an error during lookup. This includes -ENOENT if the
2528  *         lookup found a negative dentry. The nd->path reference will also be
2529  *         put in this case.
2530  *
2531  * 0:      if we successfully resolved nd->path and found it to not to be a
2532  *         symlink that needs to be followed. "path" will also be populated.
2533  *         The nd->path reference will also be put.
2534  *
2535  * 1:      if we successfully resolved nd->last and found it to be a symlink
2536  *         that needs to be followed. "path" will be populated with the path
2537  *         to the link, and nd->path will *not* be put.
2538  */
2539 static int
2540 mountpoint_last(struct nameidata *nd, struct path *path)
2541 {
2542         int error = 0;
2543         struct dentry *dentry;
2544         struct dentry *dir = nd->path.dentry;
2545
2546         /* If we're in rcuwalk, drop out of it to handle last component */
2547         if (nd->flags & LOOKUP_RCU) {
2548                 if (unlazy_walk(nd, NULL, 0))
2549                         return -ECHILD;
2550         }
2551
2552         nd->flags &= ~LOOKUP_PARENT;
2553
2554         if (unlikely(nd->last_type != LAST_NORM)) {
2555                 error = handle_dots(nd, nd->last_type);
2556                 if (error)
2557                         return error;
2558                 dentry = dget(nd->path.dentry);
2559                 goto done;
2560         }
2561
2562         mutex_lock(&dir->d_inode->i_mutex);
2563         dentry = d_lookup(dir, &nd->last);
2564         if (!dentry) {
2565                 /*
2566                  * No cached dentry. Mounted dentries are pinned in the cache,
2567                  * so that means that this dentry is probably a symlink or the
2568                  * path doesn't actually point to a mounted dentry.
2569                  */
2570                 dentry = d_alloc(dir, &nd->last);
2571                 if (!dentry) {
2572                         mutex_unlock(&dir->d_inode->i_mutex);
2573                         return -ENOMEM;
2574                 }
2575                 dentry = lookup_real(dir->d_inode, dentry, nd->flags);
2576                 if (IS_ERR(dentry)) {
2577                         mutex_unlock(&dir->d_inode->i_mutex);
2578                         return PTR_ERR(dentry);
2579                 }
2580         }
2581         mutex_unlock(&dir->d_inode->i_mutex);
2582
2583 done:
2584         if (d_is_negative(dentry)) {
2585                 dput(dentry);
2586                 return -ENOENT;
2587         }
2588         if (nd->depth)
2589                 put_link(nd);
2590         path->dentry = dentry;
2591         path->mnt = nd->path.mnt;
2592         error = should_follow_link(nd, path, nd->flags & LOOKUP_FOLLOW,
2593                                    d_backing_inode(dentry), 0);
2594         if (unlikely(error))
2595                 return error;
2596         mntget(path->mnt);
2597         follow_mount(path);
2598         return 0;
2599 }
2600
2601 /**
2602  * path_mountpoint - look up a path to be umounted
2603  * @nd:         lookup context
2604  * @flags:      lookup flags
2605  * @path:       pointer to container for result
2606  *
2607  * Look up the given name, but don't attempt to revalidate the last component.
2608  * Returns 0 and "path" will be valid on success; Returns error otherwise.
2609  */
2610 static int
2611 path_mountpoint(struct nameidata *nd, unsigned flags, struct path *path)
2612 {
2613         const char *s = path_init(nd, flags);
2614         int err;
2615         if (IS_ERR(s))
2616                 return PTR_ERR(s);
2617         while (!(err = link_path_walk(s, nd)) &&
2618                 (err = mountpoint_last(nd, path)) > 0) {
2619                 s = trailing_symlink(nd);
2620                 if (IS_ERR(s)) {
2621                         err = PTR_ERR(s);
2622                         break;
2623                 }
2624         }
2625         terminate_walk(nd);
2626         return err;
2627 }
2628
2629 static int
2630 filename_mountpoint(int dfd, struct filename *name, struct path *path,
2631                         unsigned int flags)
2632 {
2633         struct nameidata nd;
2634         int error;
2635         if (IS_ERR(name))
2636                 return PTR_ERR(name);
2637         set_nameidata(&nd, dfd, name);
2638         error = path_mountpoint(&nd, flags | LOOKUP_RCU, path);
2639         if (unlikely(error == -ECHILD))
2640                 error = path_mountpoint(&nd, flags, path);
2641         if (unlikely(error == -ESTALE))
2642                 error = path_mountpoint(&nd, flags | LOOKUP_REVAL, path);
2643         if (likely(!error))
2644                 audit_inode(name, path->dentry, 0);
2645         restore_nameidata();
2646         putname(name);
2647         return error;
2648 }
2649
2650 /**
2651  * user_path_mountpoint_at - lookup a path from userland in order to umount it
2652  * @dfd:        directory file descriptor
2653  * @name:       pathname from userland
2654  * @flags:      lookup flags
2655  * @path:       pointer to container to hold result
2656  *
2657  * A umount is a special case for path walking. We're not actually interested
2658  * in the inode in this situation, and ESTALE errors can be a problem. We
2659  * simply want track down the dentry and vfsmount attached at the mountpoint
2660  * and avoid revalidating the last component.
2661  *
2662  * Returns 0 and populates "path" on success.
2663  */
2664 int
2665 user_path_mountpoint_at(int dfd, const char __user *name, unsigned int flags,
2666                         struct path *path)
2667 {
2668         return filename_mountpoint(dfd, getname(name), path, flags);
2669 }
2670
2671 int
2672 kern_path_mountpoint(int dfd, const char *name, struct path *path,
2673                         unsigned int flags)
2674 {
2675         return filename_mountpoint(dfd, getname_kernel(name), path, flags);
2676 }
2677 EXPORT_SYMBOL(kern_path_mountpoint);
2678
2679 int __check_sticky(struct inode *dir, struct inode *inode)
2680 {
2681         kuid_t fsuid = current_fsuid();
2682
2683         if (uid_eq(inode->i_uid, fsuid))
2684                 return 0;
2685         if (uid_eq(dir->i_uid, fsuid))
2686                 return 0;
2687         return !capable_wrt_inode_uidgid(inode, CAP_FOWNER);
2688 }
2689 EXPORT_SYMBOL(__check_sticky);
2690
2691 /*
2692  *      Check whether we can remove a link victim from directory dir, check
2693  *  whether the type of victim is right.
2694  *  1. We can't do it if dir is read-only (done in permission())
2695  *  2. We should have write and exec permissions on dir
2696  *  3. We can't remove anything from append-only dir
2697  *  4. We can't do anything with immutable dir (done in permission())
2698  *  5. If the sticky bit on dir is set we should either
2699  *      a. be owner of dir, or
2700  *      b. be owner of victim, or
2701  *      c. have CAP_FOWNER capability
2702  *  6. If the victim is append-only or immutable we can't do antyhing with
2703  *     links pointing to it.
2704  *  7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
2705  *  8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
2706  *  9. We can't remove a root or mountpoint.
2707  * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
2708  *     nfs_async_unlink().
2709  */
2710 static int may_delete(struct vfsmount *mnt, struct inode *dir, struct dentry *victim, bool isdir)
2711 {
2712         struct inode *inode = d_backing_inode(victim);
2713         int error;
2714
2715         if (d_is_negative(victim))
2716                 return -ENOENT;
2717         BUG_ON(!inode);
2718
2719         BUG_ON(victim->d_parent->d_inode != dir);
2720         audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
2721
2722         error = inode_permission2(mnt, dir, MAY_WRITE | MAY_EXEC);
2723         if (error)
2724                 return error;
2725         if (IS_APPEND(dir))
2726                 return -EPERM;
2727
2728         if (check_sticky(dir, inode) || IS_APPEND(inode) ||
2729             IS_IMMUTABLE(inode) || IS_SWAPFILE(inode))
2730                 return -EPERM;
2731         if (isdir) {
2732                 if (!d_is_dir(victim))
2733                         return -ENOTDIR;
2734                 if (IS_ROOT(victim))
2735                         return -EBUSY;
2736         } else if (d_is_dir(victim))
2737                 return -EISDIR;
2738         if (IS_DEADDIR(dir))
2739                 return -ENOENT;
2740         if (victim->d_flags & DCACHE_NFSFS_RENAMED)
2741                 return -EBUSY;
2742         return 0;
2743 }
2744
2745 /*      Check whether we can create an object with dentry child in directory
2746  *  dir.
2747  *  1. We can't do it if child already exists (open has special treatment for
2748  *     this case, but since we are inlined it's OK)
2749  *  2. We can't do it if dir is read-only (done in permission())
2750  *  3. We should have write and exec permissions on dir
2751  *  4. We can't do it if dir is immutable (done in permission())
2752  */
2753 static inline int may_create(struct vfsmount *mnt, struct inode *dir, struct dentry *child)
2754 {
2755         audit_inode_child(dir, child, AUDIT_TYPE_CHILD_CREATE);
2756         if (child->d_inode)
2757                 return -EEXIST;
2758         if (IS_DEADDIR(dir))
2759                 return -ENOENT;
2760         return inode_permission2(mnt, dir, MAY_WRITE | MAY_EXEC);
2761 }
2762
2763 /*
2764  * p1 and p2 should be directories on the same fs.
2765  */
2766 struct dentry *lock_rename(struct dentry *p1, struct dentry *p2)
2767 {
2768         struct dentry *p;
2769
2770         if (p1 == p2) {
2771                 mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT);
2772                 return NULL;
2773         }
2774
2775         mutex_lock(&p1->d_inode->i_sb->s_vfs_rename_mutex);
2776
2777         p = d_ancestor(p2, p1);
2778         if (p) {
2779                 mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_PARENT);
2780                 mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_CHILD);
2781                 return p;
2782         }
2783
2784         p = d_ancestor(p1, p2);
2785         if (p) {
2786                 mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT);
2787                 mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_CHILD);
2788                 return p;
2789         }
2790
2791         mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT);
2792         mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_PARENT2);
2793         return NULL;
2794 }
2795 EXPORT_SYMBOL(lock_rename);
2796
2797 void unlock_rename(struct dentry *p1, struct dentry *p2)
2798 {
2799         mutex_unlock(&p1->d_inode->i_mutex);
2800         if (p1 != p2) {
2801                 mutex_unlock(&p2->d_inode->i_mutex);
2802                 mutex_unlock(&p1->d_inode->i_sb->s_vfs_rename_mutex);
2803         }
2804 }
2805 EXPORT_SYMBOL(unlock_rename);
2806
2807 int vfs_create2(struct vfsmount *mnt, struct inode *dir, struct dentry *dentry,
2808                 umode_t mode, bool want_excl)
2809 {
2810         int error = may_create(mnt, dir, dentry);
2811         if (error)
2812                 return error;
2813
2814         if (!dir->i_op->create)
2815                 return -EACCES; /* shouldn't it be ENOSYS? */
2816         mode &= S_IALLUGO;
2817         mode |= S_IFREG;
2818         error = security_inode_create(dir, dentry, mode);
2819         if (error)
2820                 return error;
2821         error = dir->i_op->create(dir, dentry, mode, want_excl);
2822         if (error)
2823                 return error;
2824         error = security_inode_post_create(dir, dentry, mode);
2825         if (error)
2826                 return error;
2827         if (!error)
2828                 fsnotify_create(dir, dentry);
2829
2830         return error;
2831 }
2832 EXPORT_SYMBOL(vfs_create2);
2833
2834 int vfs_create(struct inode *dir, struct dentry *dentry, umode_t mode,
2835                 bool want_excl)
2836 {
2837         return vfs_create2(NULL, dir, dentry, mode, want_excl);
2838 }
2839 EXPORT_SYMBOL(vfs_create);
2840
2841 static int may_open(struct path *path, int acc_mode, int flag)
2842 {
2843         struct dentry *dentry = path->dentry;
2844         struct vfsmount *mnt = path->mnt;
2845         struct inode *inode = dentry->d_inode;
2846         int error;
2847
2848         /* O_PATH? */
2849         if (!acc_mode)
2850                 return 0;
2851
2852         if (!inode)
2853                 return -ENOENT;
2854
2855         switch (inode->i_mode & S_IFMT) {
2856         case S_IFLNK:
2857                 return -ELOOP;
2858         case S_IFDIR:
2859                 if (acc_mode & MAY_WRITE)
2860                         return -EISDIR;
2861                 break;
2862         case S_IFBLK:
2863         case S_IFCHR:
2864                 if (path->mnt->mnt_flags & MNT_NODEV)
2865                         return -EACCES;
2866                 /*FALLTHRU*/
2867         case S_IFIFO:
2868         case S_IFSOCK:
2869                 flag &= ~O_TRUNC;
2870                 break;
2871         }
2872
2873         error = inode_permission2(mnt, inode, acc_mode);
2874         if (error)
2875                 return error;
2876
2877         /*
2878          * An append-only file must be opened in append mode for writing.
2879          */
2880         if (IS_APPEND(inode)) {
2881                 if  ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND))
2882                         return -EPERM;
2883                 if (flag & O_TRUNC)
2884                         return -EPERM;
2885         }
2886
2887         /* O_NOATIME can only be set by the owner or superuser */
2888         if (flag & O_NOATIME && !inode_owner_or_capable(inode))
2889                 return -EPERM;
2890
2891         return 0;
2892 }
2893
2894 static int handle_truncate(struct file *filp)
2895 {
2896         struct path *path = &filp->f_path;
2897         struct inode *inode = path->dentry->d_inode;
2898         int error = get_write_access(inode);
2899         if (error)
2900                 return error;
2901         /*
2902          * Refuse to truncate files with mandatory locks held on them.
2903          */
2904         error = locks_verify_locked(filp);
2905         if (!error)
2906                 error = security_path_truncate(path);
2907         if (!error) {
2908                 error = do_truncate2(path->mnt, path->dentry, 0,
2909                                     ATTR_MTIME|ATTR_CTIME|ATTR_OPEN,
2910                                     filp);
2911         }
2912         put_write_access(inode);
2913         return error;
2914 }
2915
2916 static inline int open_to_namei_flags(int flag)
2917 {
2918         if ((flag & O_ACCMODE) == 3)
2919                 flag--;
2920         return flag;
2921 }
2922
2923 static int may_o_create(struct path *dir, struct dentry *dentry, umode_t mode)
2924 {
2925         int error = security_path_mknod(dir, dentry, mode, 0);
2926         if (error)
2927                 return error;
2928
2929         error = inode_permission2(dir->mnt, dir->dentry->d_inode, MAY_WRITE | MAY_EXEC);
2930         if (error)
2931                 return error;
2932
2933         return security_inode_create(dir->dentry->d_inode, dentry, mode);
2934 }
2935
2936 /*
2937  * Attempt to atomically look up, create and open a file from a negative
2938  * dentry.
2939  *
2940  * Returns 0 if successful.  The file will have been created and attached to
2941  * @file by the filesystem calling finish_open().
2942  *
2943  * Returns 1 if the file was looked up only or didn't need creating.  The
2944  * caller will need to perform the open themselves.  @path will have been
2945  * updated to point to the new dentry.  This may be negative.
2946  *
2947  * Returns an error code otherwise.
2948  */
2949 static int atomic_open(struct nameidata *nd, struct dentry *dentry,
2950                         struct path *path, struct file *file,
2951                         const struct open_flags *op,
2952                         bool got_write, bool need_lookup,
2953                         int *opened)
2954 {
2955         struct inode *dir =  nd->path.dentry->d_inode;
2956         unsigned open_flag = open_to_namei_flags(op->open_flag);
2957         umode_t mode;
2958         int error;
2959         int acc_mode;
2960         int create_error = 0;
2961         struct dentry *const DENTRY_NOT_SET = (void *) -1UL;
2962         bool excl;
2963
2964         BUG_ON(dentry->d_inode);
2965
2966         /* Don't create child dentry for a dead directory. */
2967         if (unlikely(IS_DEADDIR(dir))) {
2968                 error = -ENOENT;
2969                 goto out;
2970         }
2971
2972         mode = op->mode;
2973         if ((open_flag & O_CREAT) && !IS_POSIXACL(dir))
2974                 mode &= ~current_umask();
2975
2976         excl = (open_flag & (O_EXCL | O_CREAT)) == (O_EXCL | O_CREAT);
2977         if (excl)
2978                 open_flag &= ~O_TRUNC;
2979
2980         /*
2981          * Checking write permission is tricky, bacuse we don't know if we are
2982          * going to actually need it: O_CREAT opens should work as long as the
2983          * file exists.  But checking existence breaks atomicity.  The trick is
2984          * to check access and if not granted clear O_CREAT from the flags.
2985          *
2986          * Another problem is returing the "right" error value (e.g. for an
2987          * O_EXCL open we want to return EEXIST not EROFS).
2988          */
2989         if (((open_flag & (O_CREAT | O_TRUNC)) ||
2990             (open_flag & O_ACCMODE) != O_RDONLY) && unlikely(!got_write)) {
2991                 if (!(open_flag & O_CREAT)) {
2992                         /*
2993                          * No O_CREATE -> atomicity not a requirement -> fall
2994                          * back to lookup + open
2995                          */
2996                         goto no_open;
2997                 } else if (open_flag & (O_EXCL | O_TRUNC)) {
2998                         /* Fall back and fail with the right error */
2999                         create_error = -EROFS;
3000                         goto no_open;
3001                 } else {
3002                         /* No side effects, safe to clear O_CREAT */
3003                         create_error = -EROFS;
3004                         open_flag &= ~O_CREAT;
3005                 }
3006         }
3007
3008         if (open_flag & O_CREAT) {
3009                 error = may_o_create(&nd->path, dentry, mode);
3010                 if (error) {
3011                         create_error = error;
3012                         if (open_flag & O_EXCL)
3013                                 goto no_open;
3014                         open_flag &= ~O_CREAT;
3015                 }
3016         }
3017
3018         if (nd->flags & LOOKUP_DIRECTORY)
3019                 open_flag |= O_DIRECTORY;
3020
3021         file->f_path.dentry = DENTRY_NOT_SET;
3022         file->f_path.mnt = nd->path.mnt;
3023         error = dir->i_op->atomic_open(dir, dentry, file, open_flag, mode,
3024                                       opened);
3025         if (error < 0) {
3026                 if (create_error && error == -ENOENT)
3027                         error = create_error;
3028                 goto out;
3029         }
3030
3031         if (error) {    /* returned 1, that is */
3032                 if (WARN_ON(file->f_path.dentry == DENTRY_NOT_SET)) {
3033                         error = -EIO;
3034                         goto out;
3035                 }
3036                 if (file->f_path.dentry) {
3037                         dput(dentry);
3038                         dentry = file->f_path.dentry;
3039                 }
3040                 if (*opened & FILE_CREATED)
3041                         fsnotify_create(dir, dentry);
3042                 if (!dentry->d_inode) {
3043                         WARN_ON(*opened & FILE_CREATED);
3044                         if (create_error) {
3045                                 error = create_error;
3046                                 goto out;
3047                         }
3048                 } else {
3049                         if (excl && !(*opened & FILE_CREATED)) {
3050                                 error = -EEXIST;
3051                                 goto out;
3052                         }
3053                 }
3054                 goto looked_up;
3055         }
3056
3057         /*
3058          * We didn't have the inode before the open, so check open permission
3059          * here.
3060          */
3061         acc_mode = op->acc_mode;
3062         if (*opened & FILE_CREATED) {
3063                 WARN_ON(!(open_flag & O_CREAT));
3064                 fsnotify_create(dir, dentry);
3065                 acc_mode = MAY_OPEN;
3066         }
3067         error = may_open(&file->f_path, acc_mode, open_flag);
3068         if (error)
3069                 fput(file);
3070
3071 out:
3072         dput(dentry);
3073         return error;
3074
3075 no_open:
3076         if (need_lookup) {
3077                 dentry = lookup_real(dir, dentry, nd->flags);
3078                 if (IS_ERR(dentry))
3079                         return PTR_ERR(dentry);
3080         }
3081         if (create_error && !dentry->d_inode) {
3082                 error = create_error;
3083                 goto out;
3084         }
3085 looked_up:
3086         path->dentry = dentry;
3087         path->mnt = nd->path.mnt;
3088         return 1;
3089 }
3090
3091 /*
3092  * Look up and maybe create and open the last component.
3093  *
3094  * Must be called with i_mutex held on parent.
3095  *
3096  * Returns 0 if the file was successfully atomically created (if necessary) and
3097  * opened.  In this case the file will be returned attached to @file.
3098  *
3099  * Returns 1 if the file was not completely opened at this time, though lookups
3100  * and creations will have been performed and the dentry returned in @path will
3101  * be positive upon return if O_CREAT was specified.  If O_CREAT wasn't
3102  * specified then a negative dentry may be returned.
3103  *
3104  * An error code is returned otherwise.
3105  *
3106  * FILE_CREATE will be set in @*opened if the dentry was created and will be
3107  * cleared otherwise prior to returning.
3108  */
3109 static int lookup_open(struct nameidata *nd, struct path *path,
3110                         struct file *file,
3111                         const struct open_flags *op,
3112                         bool got_write, int *opened)
3113 {
3114         struct dentry *dir = nd->path.dentry;
3115         struct vfsmount *mnt = nd->path.mnt;
3116         struct inode *dir_inode = dir->d_inode;
3117         struct dentry *dentry;
3118         int error;
3119         bool need_lookup;
3120
3121         *opened &= ~FILE_CREATED;
3122         dentry = lookup_dcache(&nd->last, dir, nd->flags, &need_lookup);
3123         if (IS_ERR(dentry))
3124                 return PTR_ERR(dentry);
3125
3126         /* Cached positive dentry: will open in f_op->open */
3127         if (!need_lookup && dentry->d_inode)
3128                 goto out_no_open;
3129
3130         if ((nd->flags & LOOKUP_OPEN) && dir_inode->i_op->atomic_open) {
3131                 return atomic_open(nd, dentry, path, file, op, got_write,
3132                                    need_lookup, opened);
3133         }
3134
3135         if (need_lookup) {
3136                 BUG_ON(dentry->d_inode);
3137
3138                 dentry = lookup_real(dir_inode, dentry, nd->flags);
3139                 if (IS_ERR(dentry))
3140                         return PTR_ERR(dentry);
3141         }
3142
3143         /* Negative dentry, just create the file */
3144         if (!dentry->d_inode && (op->open_flag & O_CREAT)) {
3145                 umode_t mode = op->mode;
3146                 if (!IS_POSIXACL(dir->d_inode))
3147                         mode &= ~current_umask();
3148                 /*
3149                  * This write is needed to ensure that a
3150                  * rw->ro transition does not occur between
3151                  * the time when the file is created and when
3152                  * a permanent write count is taken through
3153                  * the 'struct file' in finish_open().
3154                  */
3155                 if (!got_write) {
3156                         error = -EROFS;
3157                         goto out_dput;
3158                 }
3159                 *opened |= FILE_CREATED;
3160                 error = security_path_mknod(&nd->path, dentry, mode, 0);
3161                 if (error)
3162                         goto out_dput;
3163                 error = vfs_create2(mnt, dir->d_inode, dentry, mode,
3164                                    nd->flags & LOOKUP_EXCL);
3165                 if (error)
3166                         goto out_dput;
3167         }
3168 out_no_open:
3169         path->dentry = dentry;
3170         path->mnt = nd->path.mnt;
3171         return 1;
3172
3173 out_dput:
3174         dput(dentry);
3175         return error;
3176 }
3177
3178 /*
3179  * Handle the last step of open()
3180  */
3181 static int do_last(struct nameidata *nd,
3182                    struct file *file, const struct open_flags *op,
3183                    int *opened)
3184 {
3185         struct dentry *dir = nd->path.dentry;
3186         kuid_t dir_uid = nd->inode->i_uid;
3187         umode_t dir_mode = nd->inode->i_mode;
3188         int open_flag = op->open_flag;
3189         bool will_truncate = (open_flag & O_TRUNC) != 0;
3190         bool got_write = false;
3191         int acc_mode = op->acc_mode;
3192         unsigned seq;
3193         struct inode *inode;
3194         struct path save_parent = { .dentry = NULL, .mnt = NULL };
3195         struct path path;
3196         bool retried = false;
3197         int error;
3198
3199         nd->flags &= ~LOOKUP_PARENT;
3200         nd->flags |= op->intent;
3201
3202         if (nd->last_type != LAST_NORM) {
3203                 error = handle_dots(nd, nd->last_type);
3204                 if (unlikely(error))
3205                         return error;
3206                 goto finish_open;
3207         }
3208
3209         if (!(open_flag & O_CREAT)) {
3210                 if (nd->last.name[nd->last.len])
3211                         nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
3212                 /* we _can_ be in RCU mode here */
3213                 error = lookup_fast(nd, &path, &inode, &seq);
3214                 if (likely(!error))
3215                         goto finish_lookup;
3216
3217                 if (error < 0)
3218                         return error;
3219
3220                 BUG_ON(nd->inode != dir->d_inode);
3221         } else {
3222                 /* create side of things */
3223                 /*
3224                  * This will *only* deal with leaving RCU mode - LOOKUP_JUMPED
3225                  * has been cleared when we got to the last component we are
3226                  * about to look up
3227                  */
3228                 error = complete_walk(nd);
3229                 if (error)
3230                         return error;
3231
3232                 audit_inode(nd->name, dir, LOOKUP_PARENT);
3233                 /* trailing slashes? */
3234                 if (unlikely(nd->last.name[nd->last.len]))
3235                         return -EISDIR;
3236         }
3237
3238 retry_lookup:
3239         if (op->open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) {
3240                 error = mnt_want_write(nd->path.mnt);
3241                 if (!error)
3242                         got_write = true;
3243                 /*
3244                  * do _not_ fail yet - we might not need that or fail with
3245                  * a different error; let lookup_open() decide; we'll be
3246                  * dropping this one anyway.
3247                  */
3248         }
3249         mutex_lock(&dir->d_inode->i_mutex);
3250         error = lookup_open(nd, &path, file, op, got_write, opened);
3251         mutex_unlock(&dir->d_inode->i_mutex);
3252
3253         if (error <= 0) {
3254                 if (error)
3255                         goto out;
3256
3257                 if ((*opened & FILE_CREATED) ||
3258                     !S_ISREG(file_inode(file)->i_mode))
3259                         will_truncate = false;
3260
3261                 audit_inode(nd->name, file->f_path.dentry, 0);
3262                 goto opened;
3263         }
3264
3265         if (*opened & FILE_CREATED) {
3266                 /* Don't check for write permission, don't truncate */
3267                 open_flag &= ~O_TRUNC;
3268                 will_truncate = false;
3269                 acc_mode = MAY_OPEN;
3270                 path_to_nameidata(&path, nd);
3271                 goto finish_open_created;
3272         }
3273
3274         /*
3275          * create/update audit record if it already exists.
3276          */
3277         if (d_is_positive(path.dentry))
3278                 audit_inode(nd->name, path.dentry, 0);
3279
3280         /*
3281          * If atomic_open() acquired write access it is dropped now due to
3282          * possible mount and symlink following (this might be optimized away if
3283          * necessary...)
3284          */
3285         if (got_write) {
3286                 mnt_drop_write(nd->path.mnt);
3287                 got_write = false;
3288         }
3289
3290         if (unlikely((open_flag & (O_EXCL | O_CREAT)) == (O_EXCL | O_CREAT))) {
3291                 path_to_nameidata(&path, nd);
3292                 return -EEXIST;
3293         }
3294
3295         error = follow_managed(&path, nd);
3296         if (unlikely(error < 0))
3297                 return error;
3298
3299         BUG_ON(nd->flags & LOOKUP_RCU);
3300         seq = 0;        /* out of RCU mode, so the value doesn't matter */
3301         if (unlikely(d_is_negative(path.dentry))) {
3302                 path_to_nameidata(&path, nd);
3303                 return -ENOENT;
3304         }
3305         inode = d_backing_inode(path.dentry);
3306 finish_lookup:
3307         if (nd->depth)
3308                 put_link(nd);
3309         error = should_follow_link(nd, &path, nd->flags & LOOKUP_FOLLOW,
3310                                    inode, seq);
3311         if (unlikely(error))
3312                 return error;
3313
3314         if ((nd->flags & LOOKUP_RCU) || nd->path.mnt != path.mnt) {
3315                 path_to_nameidata(&path, nd);
3316         } else {
3317                 save_parent.dentry = nd->path.dentry;
3318                 save_parent.mnt = mntget(path.mnt);
3319                 nd->path.dentry = path.dentry;
3320
3321         }
3322         nd->inode = inode;
3323         nd->seq = seq;
3324         /* Why this, you ask?  _Now_ we might have grown LOOKUP_JUMPED... */
3325 finish_open:
3326         error = complete_walk(nd);
3327         if (error) {
3328                 path_put(&save_parent);
3329                 return error;
3330         }
3331         audit_inode(nd->name, nd->path.dentry, 0);
3332         if (unlikely(d_is_symlink(nd->path.dentry)) && !(open_flag & O_PATH)) {
3333                 error = -ELOOP;
3334                 goto out;
3335         }
3336         if (open_flag & O_CREAT) {
3337                 error = -EISDIR;
3338                 if (d_is_dir(nd->path.dentry))
3339                         goto out;
3340                 error = may_create_in_sticky(dir_mode, dir_uid,
3341                                              d_backing_inode(nd->path.dentry));
3342                 if (unlikely(error))
3343                         goto out;
3344         }
3345         error = -ENOTDIR;
3346         if ((nd->flags & LOOKUP_DIRECTORY) && !d_can_lookup(nd->path.dentry))
3347                 goto out;
3348         if (!d_is_reg(nd->path.dentry))
3349                 will_truncate = false;
3350
3351         if (will_truncate) {
3352                 error = mnt_want_write(nd->path.mnt);
3353                 if (error)
3354                         goto out;
3355                 got_write = true;
3356         }
3357 finish_open_created:
3358         error = may_open(&nd->path, acc_mode, open_flag);
3359         if (error)
3360                 goto out;
3361
3362         BUG_ON(*opened & FILE_OPENED); /* once it's opened, it's opened */
3363         error = vfs_open(&nd->path, file, current_cred());
3364         if (!error) {
3365                 *opened |= FILE_OPENED;
3366         } else {
3367                 if (error == -EOPENSTALE)
3368                         goto stale_open;
3369                 goto out;
3370         }
3371 opened:
3372         error = open_check_o_direct(file);
3373         if (error)
3374                 goto exit_fput;
3375         error = ima_file_check(file, op->acc_mode, *opened);
3376         if (error)
3377                 goto exit_fput;
3378
3379         if (will_truncate) {
3380                 error = handle_truncate(file);
3381                 if (error)
3382                         goto exit_fput;
3383         }
3384 out:
3385         if (unlikely(error > 0)) {
3386                 WARN_ON(1);
3387                 error = -EINVAL;
3388         }
3389         if (got_write)
3390                 mnt_drop_write(nd->path.mnt);
3391         path_put(&save_parent);
3392         return error;
3393
3394 exit_fput:
3395         fput(file);
3396         goto out;
3397
3398 stale_open:
3399         /* If no saved parent or already retried then can't retry */
3400         if (!save_parent.dentry || retried)
3401                 goto out;
3402
3403         BUG_ON(save_parent.dentry != dir);
3404         path_put(&nd->path);
3405         nd->path = save_parent;
3406         nd->inode = dir->d_inode;
3407         save_parent.mnt = NULL;
3408         save_parent.dentry = NULL;
3409         if (got_write) {
3410                 mnt_drop_write(nd->path.mnt);
3411                 got_write = false;
3412         }
3413         retried = true;
3414         goto retry_lookup;
3415 }
3416
3417 static int do_tmpfile(struct nameidata *nd, unsigned flags,
3418                 const struct open_flags *op,
3419                 struct file *file, int *opened)
3420 {
3421         static const struct qstr name = QSTR_INIT("/", 1);
3422         struct dentry *child;
3423         struct inode *dir;
3424         struct path path;
3425         int error = path_lookupat(nd, flags | LOOKUP_DIRECTORY, &path);
3426         if (unlikely(error))
3427                 return error;
3428         error = mnt_want_write(path.mnt);
3429         if (unlikely(error))
3430                 goto out;
3431         dir = path.dentry->d_inode;
3432         /* we want directory to be writable */
3433         error = inode_permission2(path.mnt, dir, MAY_WRITE | MAY_EXEC);
3434         if (error)
3435                 goto out2;
3436         if (!dir->i_op->tmpfile) {
3437                 error = -EOPNOTSUPP;
3438                 goto out2;
3439         }
3440         child = d_alloc(path.dentry, &name);
3441         if (unlikely(!child)) {
3442                 error = -ENOMEM;
3443                 goto out2;
3444         }
3445         dput(path.dentry);
3446         path.dentry = child;
3447         error = dir->i_op->tmpfile(dir, child, op->mode);
3448         if (error)
3449                 goto out2;
3450         audit_inode(nd->name, child, 0);
3451         /* Don't check for other permissions, the inode was just created */
3452         error = may_open(&path, MAY_OPEN, op->open_flag);
3453         if (error)
3454                 goto out2;
3455         file->f_path.mnt = path.mnt;
3456         error = finish_open(file, child, NULL, opened);
3457         if (error)
3458                 goto out2;
3459         error = open_check_o_direct(file);
3460         if (error) {
3461                 fput(file);
3462         } else if (!(op->open_flag & O_EXCL)) {
3463                 struct inode *inode = file_inode(file);
3464                 spin_lock(&inode->i_lock);
3465                 inode->i_state |= I_LINKABLE;
3466                 spin_unlock(&inode->i_lock);
3467         }
3468 out2:
3469         mnt_drop_write(path.mnt);
3470 out:
3471         path_put(&path);
3472         return error;
3473 }
3474
3475 static struct file *path_openat(struct nameidata *nd,
3476                         const struct open_flags *op, unsigned flags)
3477 {
3478         const char *s;
3479         struct file *file;
3480         int opened = 0;
3481         int error;
3482
3483         file = get_empty_filp();
3484         if (IS_ERR(file))
3485                 return file;
3486
3487         file->f_flags = op->open_flag;
3488
3489         if (unlikely(file->f_flags & __O_TMPFILE)) {
3490                 error = do_tmpfile(nd, flags, op, file, &opened);
3491                 goto out2;
3492         }
3493
3494         s = path_init(nd, flags);
3495         if (IS_ERR(s)) {
3496                 put_filp(file);
3497                 return ERR_CAST(s);
3498         }
3499         while (!(error = link_path_walk(s, nd)) &&
3500                 (error = do_last(nd, file, op, &opened)) > 0) {
3501                 nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL);
3502                 s = trailing_symlink(nd);
3503                 if (IS_ERR(s)) {
3504                         error = PTR_ERR(s);
3505                         break;
3506                 }
3507         }
3508         terminate_walk(nd);
3509 out2:
3510         if (!(opened & FILE_OPENED)) {
3511                 BUG_ON(!error);
3512                 put_filp(file);
3513         }
3514         if (unlikely(error)) {
3515                 if (error == -EOPENSTALE) {
3516                         if (flags & LOOKUP_RCU)
3517                                 error = -ECHILD;
3518                         else
3519                                 error = -ESTALE;
3520                 }
3521                 file = ERR_PTR(error);
3522         } else {
3523                 global_filetable_add(file);
3524         }
3525         return file;
3526 }
3527
3528 struct file *do_filp_open(int dfd, struct filename *pathname,
3529                 const struct open_flags *op)
3530 {
3531         struct nameidata nd;
3532         int flags = op->lookup_flags;
3533         struct file *filp;
3534
3535         set_nameidata(&nd, dfd, pathname);
3536         filp = path_openat(&nd, op, flags | LOOKUP_RCU);
3537         if (unlikely(filp == ERR_PTR(-ECHILD)))
3538                 filp = path_openat(&nd, op, flags);
3539         if (unlikely(filp == ERR_PTR(-ESTALE)))
3540                 filp = path_openat(&nd, op, flags | LOOKUP_REVAL);
3541         restore_nameidata();
3542         return filp;
3543 }
3544
3545 struct file *do_file_open_root(struct dentry *dentry, struct vfsmount *mnt,
3546                 const char *name, const struct open_flags *op)
3547 {
3548         struct nameidata nd;
3549         struct file *file;
3550         struct filename *filename;
3551         int flags = op->lookup_flags | LOOKUP_ROOT;
3552
3553         nd.root.mnt = mnt;
3554         nd.root.dentry = dentry;
3555
3556         if (d_is_symlink(dentry) && op->intent & LOOKUP_OPEN)
3557                 return ERR_PTR(-ELOOP);
3558
3559         filename = getname_kernel(name);
3560         if (IS_ERR(filename))
3561                 return ERR_CAST(filename);
3562
3563         set_nameidata(&nd, -1, filename);
3564         file = path_openat(&nd, op, flags | LOOKUP_RCU);
3565         if (unlikely(file == ERR_PTR(-ECHILD)))
3566                 file = path_openat(&nd, op, flags);
3567         if (unlikely(file == ERR_PTR(-ESTALE)))
3568                 file = path_openat(&nd, op, flags | LOOKUP_REVAL);
3569         restore_nameidata();
3570         putname(filename);
3571         return file;
3572 }
3573
3574 static struct dentry *filename_create(int dfd, struct filename *name,
3575                                 struct path *path, unsigned int lookup_flags)
3576 {
3577         struct dentry *dentry = ERR_PTR(-EEXIST);
3578         struct qstr last;
3579         int type;
3580         int err2;
3581         int error;
3582         bool is_dir = (lookup_flags & LOOKUP_DIRECTORY);
3583
3584         /*
3585          * Note that only LOOKUP_REVAL and LOOKUP_DIRECTORY matter here. Any
3586          * other flags passed in are ignored!
3587          */
3588         lookup_flags &= LOOKUP_REVAL;
3589
3590         name = filename_parentat(dfd, name, lookup_flags, path, &last, &type);
3591         if (IS_ERR(name))
3592                 return ERR_CAST(name);
3593
3594         /*
3595          * Yucky last component or no last component at all?
3596          * (foo/., foo/.., /////)
3597          */
3598         if (unlikely(type != LAST_NORM))
3599                 goto out;
3600
3601         /* don't fail immediately if it's r/o, at least try to report other errors */
3602         err2 = mnt_want_write(path->mnt);
3603         /*
3604          * Do the final lookup.
3605          */
3606         lookup_flags |= LOOKUP_CREATE | LOOKUP_EXCL;
3607         mutex_lock_nested(&path->dentry->d_inode->i_mutex, I_MUTEX_PARENT);
3608         dentry = __lookup_hash(&last, path->dentry, lookup_flags);
3609         if (IS_ERR(dentry))
3610                 goto unlock;
3611
3612         error = -EEXIST;
3613         if (d_is_positive(dentry))
3614                 goto fail;
3615
3616         /*
3617          * Special case - lookup gave negative, but... we had foo/bar/
3618          * From the vfs_mknod() POV we just have a negative dentry -
3619          * all is fine. Let's be bastards - you had / on the end, you've
3620          * been asking for (non-existent) directory. -ENOENT for you.
3621          */
3622         if (unlikely(!is_dir && last.name[last.len])) {
3623                 error = -ENOENT;
3624                 goto fail;
3625         }
3626         if (unlikely(err2)) {
3627                 error = err2;
3628                 goto fail;
3629         }
3630         putname(name);
3631         return dentry;
3632 fail:
3633         dput(dentry);
3634         dentry = ERR_PTR(error);
3635 unlock:
3636         mutex_unlock(&path->dentry->d_inode->i_mutex);
3637         if (!err2)
3638                 mnt_drop_write(path->mnt);
3639 out:
3640         path_put(path);
3641         putname(name);
3642         return dentry;
3643 }
3644
3645 struct dentry *kern_path_create(int dfd, const char *pathname,
3646                                 struct path *path, unsigned int lookup_flags)
3647 {
3648         return filename_create(dfd, getname_kernel(pathname),
3649                                 path, lookup_flags);
3650 }
3651 EXPORT_SYMBOL(kern_path_create);
3652
3653 void done_path_create(struct path *path, struct dentry *dentry)
3654 {
3655         dput(dentry);
3656         mutex_unlock(&path->dentry->d_inode->i_mutex);
3657         mnt_drop_write(path->mnt);
3658         path_put(path);
3659 }
3660 EXPORT_SYMBOL(done_path_create);
3661
3662 inline struct dentry *user_path_create(int dfd, const char __user *pathname,
3663                                 struct path *path, unsigned int lookup_flags)
3664 {
3665         return filename_create(dfd, getname(pathname), path, lookup_flags);
3666 }
3667 EXPORT_SYMBOL(user_path_create);
3668
3669 int vfs_mknod2(struct vfsmount *mnt, struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
3670 {
3671         int error = may_create(mnt, dir, dentry);
3672
3673         if (error)
3674                 return error;
3675
3676         if ((S_ISCHR(mode) || S_ISBLK(mode)) && !capable(CAP_MKNOD))
3677                 return -EPERM;
3678
3679         if (!dir->i_op->mknod)
3680                 return -EPERM;
3681
3682         error = devcgroup_inode_mknod(mode, dev);
3683         if (error)
3684                 return error;
3685
3686         error = security_inode_mknod(dir, dentry, mode, dev);
3687         if (error)
3688                 return error;
3689
3690         error = dir->i_op->mknod(dir, dentry, mode, dev);
3691         if (error)
3692                 return error;
3693
3694         error = security_inode_post_create(dir, dentry, mode);
3695         if (error)
3696                 return error;
3697
3698         if (!error)
3699                 fsnotify_create(dir, dentry);
3700
3701         return error;
3702 }
3703 EXPORT_SYMBOL(vfs_mknod2);
3704
3705 int vfs_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
3706 {
3707         return vfs_mknod2(NULL, dir, dentry, mode, dev);
3708 }
3709 EXPORT_SYMBOL(vfs_mknod);
3710
3711 static int may_mknod(umode_t mode)
3712 {
3713         switch (mode & S_IFMT) {
3714         case S_IFREG:
3715         case S_IFCHR:
3716         case S_IFBLK:
3717         case S_IFIFO:
3718         case S_IFSOCK:
3719         case 0: /* zero mode translates to S_IFREG */
3720                 return 0;
3721         case S_IFDIR:
3722                 return -EPERM;
3723         default:
3724                 return -EINVAL;
3725         }
3726 }
3727
3728 SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, umode_t, mode,
3729                 unsigned, dev)
3730 {
3731         struct dentry *dentry;
3732         struct path path;
3733         int error;
3734         unsigned int lookup_flags = 0;
3735
3736         error = may_mknod(mode);
3737         if (error)
3738                 return error;
3739 retry:
3740         dentry = user_path_create(dfd, filename, &path, lookup_flags);
3741         if (IS_ERR(dentry))
3742                 return PTR_ERR(dentry);
3743
3744         if (!IS_POSIXACL(path.dentry->d_inode))
3745                 mode &= ~current_umask();
3746         error = security_path_mknod(&path, dentry, mode, dev);
3747         if (error)
3748                 goto out;
3749         switch (mode & S_IFMT) {
3750                 case 0: case S_IFREG:
3751                         error = vfs_create2(path.mnt, path.dentry->d_inode,dentry,mode,true);
3752                         break;
3753                 case S_IFCHR: case S_IFBLK:
3754                         error = vfs_mknod2(path.mnt, path.dentry->d_inode,dentry,mode,
3755                                         new_decode_dev(dev));
3756                         break;
3757                 case S_IFIFO: case S_IFSOCK:
3758                         error = vfs_mknod(path.dentry->d_inode,dentry,mode,0);
3759                         break;
3760         }
3761 out:
3762         done_path_create(&path, dentry);
3763         if (retry_estale(error, lookup_flags)) {
3764                 lookup_flags |= LOOKUP_REVAL;
3765                 goto retry;
3766         }
3767         return error;
3768 }
3769
3770 SYSCALL_DEFINE3(mknod, const char __user *, filename, umode_t, mode, unsigned, dev)
3771 {
3772         return sys_mknodat(AT_FDCWD, filename, mode, dev);
3773 }
3774
3775 int vfs_mkdir2(struct vfsmount *mnt, struct inode *dir, struct dentry *dentry, umode_t mode)
3776 {
3777         int error = may_create(mnt, dir, dentry);
3778         unsigned max_links = dir->i_sb->s_max_links;
3779
3780         if (error)
3781                 return error;
3782
3783         if (!dir->i_op->mkdir)
3784                 return -EPERM;
3785
3786         mode &= (S_IRWXUGO|S_ISVTX);
3787         error = security_inode_mkdir(dir, dentry, mode);
3788         if (error)
3789                 return error;
3790
3791         if (max_links && dir->i_nlink >= max_links)
3792                 return -EMLINK;
3793
3794         error = dir->i_op->mkdir(dir, dentry, mode);
3795         if (!error)
3796                 fsnotify_mkdir(dir, dentry);
3797         return error;
3798 }
3799 EXPORT_SYMBOL(vfs_mkdir2);
3800
3801 int vfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
3802 {
3803         return vfs_mkdir2(NULL, dir, dentry, mode);
3804 }
3805 EXPORT_SYMBOL(vfs_mkdir);
3806
3807 SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, umode_t, mode)
3808 {
3809         struct dentry *dentry;
3810         struct path path;
3811         int error;
3812         unsigned int lookup_flags = LOOKUP_DIRECTORY;
3813
3814 retry:
3815         dentry = user_path_create(dfd, pathname, &path, lookup_flags);
3816         if (IS_ERR(dentry))
3817                 return PTR_ERR(dentry);
3818
3819         if (!IS_POSIXACL(path.dentry->d_inode))
3820                 mode &= ~current_umask();
3821         error = security_path_mkdir(&path, dentry, mode);
3822         if (!error)
3823                 error = vfs_mkdir2(path.mnt, path.dentry->d_inode, dentry, mode);
3824         done_path_create(&path, dentry);
3825         if (retry_estale(error, lookup_flags)) {
3826                 lookup_flags |= LOOKUP_REVAL;
3827                 goto retry;
3828         }
3829         return error;
3830 }
3831
3832 SYSCALL_DEFINE2(mkdir, const char __user *, pathname, umode_t, mode)
3833 {
3834         return sys_mkdirat(AT_FDCWD, pathname, mode);
3835 }
3836
3837 /*
3838  * The dentry_unhash() helper will try to drop the dentry early: we
3839  * should have a usage count of 1 if we're the only user of this
3840  * dentry, and if that is true (possibly after pruning the dcache),
3841  * then we drop the dentry now.
3842  *
3843  * A low-level filesystem can, if it choses, legally
3844  * do a
3845  *
3846  *      if (!d_unhashed(dentry))
3847  *              return -EBUSY;
3848  *
3849  * if it cannot handle the case of removing a directory
3850  * that is still in use by something else..
3851  */
3852 void dentry_unhash(struct dentry *dentry)
3853 {
3854         shrink_dcache_parent(dentry);
3855         spin_lock(&dentry->d_lock);
3856         if (dentry->d_lockref.count == 1)
3857                 __d_drop(dentry);
3858         spin_unlock(&dentry->d_lock);
3859 }
3860 EXPORT_SYMBOL(dentry_unhash);
3861
3862 int vfs_rmdir2(struct vfsmount *mnt, struct inode *dir, struct dentry *dentry)
3863 {
3864         int error = may_delete(mnt, dir, dentry, 1);
3865
3866         if (error)
3867                 return error;
3868
3869         if (!dir->i_op->rmdir)
3870                 return -EPERM;
3871
3872         dget(dentry);
3873         mutex_lock(&dentry->d_inode->i_mutex);
3874
3875         error = -EBUSY;
3876         if (is_local_mountpoint(dentry))
3877                 goto out;
3878
3879         error = security_inode_rmdir(dir, dentry);
3880         if (error)
3881                 goto out;
3882
3883         shrink_dcache_parent(dentry);
3884         error = dir->i_op->rmdir(dir, dentry);
3885         if (error)
3886                 goto out;
3887
3888         dentry->d_inode->i_flags |= S_DEAD;
3889         dont_mount(dentry);
3890         detach_mounts(dentry);
3891
3892 out:
3893         mutex_unlock(&dentry->d_inode->i_mutex);
3894         dput(dentry);
3895         if (!error)
3896                 d_delete(dentry);
3897         return error;
3898 }
3899 EXPORT_SYMBOL(vfs_rmdir2);
3900
3901 int vfs_rmdir(struct inode *dir, struct dentry *dentry)
3902 {
3903         return vfs_rmdir2(NULL, dir, dentry);
3904 }
3905 EXPORT_SYMBOL(vfs_rmdir);
3906
3907 static long do_rmdir(int dfd, const char __user *pathname)
3908 {
3909         int error = 0;
3910         struct filename *name;
3911         struct dentry *dentry;
3912         struct path path;
3913         struct qstr last;
3914         int type;
3915         unsigned int lookup_flags = 0;
3916 retry:
3917         name = user_path_parent(dfd, pathname,
3918                                 &path, &last, &type, lookup_flags);
3919         if (IS_ERR(name))
3920                 return PTR_ERR(name);
3921
3922         switch (type) {
3923         case LAST_DOTDOT:
3924                 error = -ENOTEMPTY;
3925                 goto exit1;
3926         case LAST_DOT:
3927                 error = -EINVAL;
3928                 goto exit1;
3929         case LAST_ROOT:
3930                 error = -EBUSY;
3931                 goto exit1;
3932         }
3933
3934         error = mnt_want_write(path.mnt);
3935         if (error)
3936                 goto exit1;
3937
3938         mutex_lock_nested(&path.dentry->d_inode->i_mutex, I_MUTEX_PARENT);
3939         dentry = __lookup_hash(&last, path.dentry, lookup_flags);
3940         error = PTR_ERR(dentry);
3941         if (IS_ERR(dentry))
3942                 goto exit2;
3943         if (!dentry->d_inode) {
3944                 error = -ENOENT;
3945                 goto exit3;
3946         }
3947         error = security_path_rmdir(&path, dentry);
3948         if (error)
3949                 goto exit3;
3950         error = vfs_rmdir2(path.mnt, path.dentry->d_inode, dentry);
3951 exit3:
3952         dput(dentry);
3953 exit2:
3954         mutex_unlock(&path.dentry->d_inode->i_mutex);
3955         mnt_drop_write(path.mnt);
3956 exit1:
3957         path_put(&path);
3958         putname(name);
3959         if (retry_estale(error, lookup_flags)) {
3960                 lookup_flags |= LOOKUP_REVAL;
3961                 goto retry;
3962         }
3963         return error;
3964 }
3965
3966 SYSCALL_DEFINE1(rmdir, const char __user *, pathname)
3967 {
3968         return do_rmdir(AT_FDCWD, pathname);
3969 }
3970
3971 /**
3972  * vfs_unlink - unlink a filesystem object
3973  * @dir:        parent directory
3974  * @dentry:     victim
3975  * @delegated_inode: returns victim inode, if the inode is delegated.
3976  *
3977  * The caller must hold dir->i_mutex.
3978  *
3979  * If vfs_unlink discovers a delegation, it will return -EWOULDBLOCK and
3980  * return a reference to the inode in delegated_inode.  The caller
3981  * should then break the delegation on that inode and retry.  Because
3982  * breaking a delegation may take a long time, the caller should drop
3983  * dir->i_mutex before doing so.
3984  *
3985  * Alternatively, a caller may pass NULL for delegated_inode.  This may
3986  * be appropriate for callers that expect the underlying filesystem not
3987  * to be NFS exported.
3988  */
3989 int vfs_unlink2(struct vfsmount *mnt, struct inode *dir, struct dentry *dentry, struct inode **delegated_inode)
3990 {
3991         struct inode *target = dentry->d_inode;
3992         int error = may_delete(mnt, dir, dentry, 0);
3993
3994         if (error)
3995                 return error;
3996
3997         if (!dir->i_op->unlink)
3998                 return -EPERM;
3999
4000         mutex_lock(&target->i_mutex);
4001         if (is_local_mountpoint(dentry))
4002                 error = -EBUSY;
4003         else {
4004                 error = security_inode_unlink(dir, dentry);
4005                 if (!error) {
4006                         error = try_break_deleg(target, delegated_inode);
4007                         if (error)
4008                                 goto out;
4009                         error = dir->i_op->unlink(dir, dentry);
4010                         if (!error) {
4011                                 dont_mount(dentry);
4012                                 detach_mounts(dentry);
4013                         }
4014                 }
4015         }
4016 out:
4017         mutex_unlock(&target->i_mutex);
4018
4019         /* We don't d_delete() NFS sillyrenamed files--they still exist. */
4020         if (!error && !(dentry->d_flags & DCACHE_NFSFS_RENAMED)) {
4021                 fsnotify_link_count(target);
4022                 d_delete(dentry);
4023         }
4024
4025         return error;
4026 }
4027 EXPORT_SYMBOL(vfs_unlink2);
4028
4029 int vfs_unlink(struct inode *dir, struct dentry *dentry, struct inode **delegated_inode)
4030 {
4031         return vfs_unlink2(NULL, dir, dentry, delegated_inode);
4032 }
4033 EXPORT_SYMBOL(vfs_unlink);
4034
4035 /*
4036  * Make sure that the actual truncation of the file will occur outside its
4037  * directory's i_mutex.  Truncate can take a long time if there is a lot of
4038  * writeout happening, and we don't want to prevent access to the directory
4039  * while waiting on the I/O.
4040  */
4041 static long do_unlinkat(int dfd, const char __user *pathname)
4042 {
4043         int error;
4044         struct filename *name;
4045         struct dentry *dentry;
4046         struct path path;
4047         struct qstr last;
4048         int type;
4049         struct inode *inode = NULL;
4050         struct inode *delegated_inode = NULL;
4051         unsigned int lookup_flags = 0;
4052 retry:
4053         name = user_path_parent(dfd, pathname,
4054                                 &path, &last, &type, lookup_flags);
4055         if (IS_ERR(name))
4056                 return PTR_ERR(name);
4057
4058         error = -EISDIR;
4059         if (type != LAST_NORM)
4060                 goto exit1;
4061
4062         error = mnt_want_write(path.mnt);
4063         if (error)
4064                 goto exit1;
4065 retry_deleg:
4066         mutex_lock_nested(&path.dentry->d_inode->i_mutex, I_MUTEX_PARENT);
4067         dentry = __lookup_hash(&last, path.dentry, lookup_flags);
4068         error = PTR_ERR(dentry);
4069         if (!IS_ERR(dentry)) {
4070                 /* Why not before? Because we want correct error value */
4071                 if (last.name[last.len])
4072                         goto slashes;
4073                 inode = dentry->d_inode;
4074                 if (d_is_negative(dentry))
4075                         goto slashes;
4076                 ihold(inode);
4077                 error = security_path_unlink(&path, dentry);
4078                 if (error)
4079                         goto exit2;
4080                 error = vfs_unlink2(path.mnt, path.dentry->d_inode, dentry, &delegated_inode);
4081 exit2:
4082                 dput(dentry);
4083         }
4084         mutex_unlock(&path.dentry->d_inode->i_mutex);
4085         if (inode)
4086                 iput(inode);    /* truncate the inode here */
4087         inode = NULL;
4088         if (delegated_inode) {
4089                 error = break_deleg_wait(&delegated_inode);
4090                 if (!error)
4091                         goto retry_deleg;
4092         }
4093         mnt_drop_write(path.mnt);
4094 exit1:
4095         path_put(&path);
4096         putname(name);
4097         if (retry_estale(error, lookup_flags)) {
4098                 lookup_flags |= LOOKUP_REVAL;
4099                 inode = NULL;
4100                 goto retry;
4101         }
4102         return error;
4103
4104 slashes:
4105         if (d_is_negative(dentry))
4106                 error = -ENOENT;
4107         else if (d_is_dir(dentry))
4108                 error = -EISDIR;
4109         else
4110                 error = -ENOTDIR;
4111         goto exit2;
4112 }
4113
4114 SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag)
4115 {
4116         if ((flag & ~AT_REMOVEDIR) != 0)
4117                 return -EINVAL;
4118
4119         if (flag & AT_REMOVEDIR)
4120                 return do_rmdir(dfd, pathname);
4121
4122         return do_unlinkat(dfd, pathname);
4123 }
4124
4125 SYSCALL_DEFINE1(unlink, const char __user *, pathname)
4126 {
4127         return do_unlinkat(AT_FDCWD, pathname);
4128 }
4129
4130 int vfs_symlink2(struct vfsmount *mnt, struct inode *dir, struct dentry *dentry, const char *oldname)
4131 {
4132         int error = may_create(mnt, dir, dentry);
4133
4134         if (error)
4135                 return error;
4136
4137         if (!dir->i_op->symlink)
4138                 return -EPERM;
4139
4140         error = security_inode_symlink(dir, dentry, oldname);
4141         if (error)
4142                 return error;
4143
4144         error = dir->i_op->symlink(dir, dentry, oldname);
4145         if (!error)
4146                 fsnotify_create(dir, dentry);
4147         return error;
4148 }
4149 EXPORT_SYMBOL(vfs_symlink2);
4150
4151 int vfs_symlink(struct inode *dir, struct dentry *dentry, const char *oldname)
4152 {
4153         return vfs_symlink2(NULL, dir, dentry, oldname);
4154 }
4155 EXPORT_SYMBOL(vfs_symlink);
4156
4157 SYSCALL_DEFINE3(symlinkat, const char __user *, oldname,
4158                 int, newdfd, const char __user *, newname)
4159 {
4160         int error;
4161         struct filename *from;
4162         struct dentry *dentry;
4163         struct path path;
4164         unsigned int lookup_flags = 0;
4165
4166         from = getname(oldname);
4167         if (IS_ERR(from))
4168                 return PTR_ERR(from);
4169 retry:
4170         dentry = user_path_create(newdfd, newname, &path, lookup_flags);
4171         error = PTR_ERR(dentry);
4172         if (IS_ERR(dentry))
4173                 goto out_putname;
4174
4175         error = security_path_symlink(&path, dentry, from->name);
4176         if (!error)
4177                 error = vfs_symlink2(path.mnt, path.dentry->d_inode, dentry, from->name);
4178         done_path_create(&path, dentry);
4179         if (retry_estale(error, lookup_flags)) {
4180                 lookup_flags |= LOOKUP_REVAL;
4181                 goto retry;
4182         }
4183 out_putname:
4184         putname(from);
4185         return error;
4186 }
4187
4188 SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname)
4189 {
4190         return sys_symlinkat(oldname, AT_FDCWD, newname);
4191 }
4192
4193 /**
4194  * vfs_link - create a new link
4195  * @old_dentry: object to be linked
4196  * @dir:        new parent
4197  * @new_dentry: where to create the new link
4198  * @delegated_inode: returns inode needing a delegation break
4199  *
4200  * The caller must hold dir->i_mutex
4201  *
4202  * If vfs_link discovers a delegation on the to-be-linked file in need
4203  * of breaking, it will return -EWOULDBLOCK and return a reference to the
4204  * inode in delegated_inode.  The caller should then break the delegation
4205  * and retry.  Because breaking a delegation may take a long time, the
4206  * caller should drop the i_mutex before doing so.
4207  *
4208  * Alternatively, a caller may pass NULL for delegated_inode.  This may
4209  * be appropriate for callers that expect the underlying filesystem not
4210  * to be NFS exported.
4211  */
4212 int vfs_link2(struct vfsmount *mnt, struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry, struct inode **delegated_inode)
4213 {
4214         struct inode *inode = old_dentry->d_inode;
4215         unsigned max_links = dir->i_sb->s_max_links;
4216         int error;
4217
4218         if (!inode)
4219                 return -ENOENT;
4220
4221         error = may_create(mnt, dir, new_dentry);
4222         if (error)
4223                 return error;
4224
4225         if (dir->i_sb != inode->i_sb)
4226                 return -EXDEV;
4227
4228         /*
4229          * A link to an append-only or immutable file cannot be created.
4230          */
4231         if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
4232                 return -EPERM;
4233         if (!dir->i_op->link)
4234                 return -EPERM;
4235         if (S_ISDIR(inode->i_mode))
4236                 return -EPERM;
4237
4238         error = security_inode_link(old_dentry, dir, new_dentry);
4239         if (error)
4240                 return error;
4241
4242         mutex_lock(&inode->i_mutex);
4243         /* Make sure we don't allow creating hardlink to an unlinked file */
4244         if (inode->i_nlink == 0 && !(inode->i_state & I_LINKABLE))
4245                 error =  -ENOENT;
4246         else if (max_links && inode->i_nlink >= max_links)
4247                 error = -EMLINK;
4248         else {
4249                 error = try_break_deleg(inode, delegated_inode);
4250                 if (!error)
4251                         error = dir->i_op->link(old_dentry, dir, new_dentry);
4252         }
4253
4254         if (!error && (inode->i_state & I_LINKABLE)) {
4255                 spin_lock(&inode->i_lock);
4256                 inode->i_state &= ~I_LINKABLE;
4257                 spin_unlock(&inode->i_lock);
4258         }
4259         mutex_unlock(&inode->i_mutex);
4260         if (!error)
4261                 fsnotify_link(dir, inode, new_dentry);
4262         return error;
4263 }
4264 EXPORT_SYMBOL(vfs_link2);
4265
4266 int vfs_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry, struct inode **delegated_inode)
4267 {
4268         return vfs_link2(NULL, old_dentry, dir, new_dentry, delegated_inode);
4269 }
4270 EXPORT_SYMBOL(vfs_link);
4271
4272 /*
4273  * Hardlinks are often used in delicate situations.  We avoid
4274  * security-related surprises by not following symlinks on the
4275  * newname.  --KAB
4276  *
4277  * We don't follow them on the oldname either to be compatible
4278  * with linux 2.0, and to avoid hard-linking to directories
4279  * and other special files.  --ADM
4280  */
4281 SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname,
4282                 int, newdfd, const char __user *, newname, int, flags)
4283 {
4284         struct dentry *new_dentry;
4285         struct path old_path, new_path;
4286         struct inode *delegated_inode = NULL;
4287         int how = 0;
4288         int error;
4289
4290         if ((flags & ~(AT_SYMLINK_FOLLOW | AT_EMPTY_PATH)) != 0)
4291                 return -EINVAL;
4292         /*
4293          * To use null names we require CAP_DAC_READ_SEARCH
4294          * This ensures that not everyone will be able to create
4295          * handlink using the passed filedescriptor.
4296          */
4297         if (flags & AT_EMPTY_PATH) {
4298                 if (!capable(CAP_DAC_READ_SEARCH))
4299                         return -ENOENT;
4300                 how = LOOKUP_EMPTY;
4301         }
4302
4303         if (flags & AT_SYMLINK_FOLLOW)
4304                 how |= LOOKUP_FOLLOW;
4305 retry:
4306         error = user_path_at(olddfd, oldname, how, &old_path);
4307         if (error)
4308                 return error;
4309
4310         new_dentry = user_path_create(newdfd, newname, &new_path,
4311                                         (how & LOOKUP_REVAL));
4312         error = PTR_ERR(new_dentry);
4313         if (IS_ERR(new_dentry))
4314                 goto out;
4315
4316         error = -EXDEV;
4317         if (old_path.mnt != new_path.mnt)
4318                 goto out_dput;
4319         error = may_linkat(&old_path);
4320         if (unlikely(error))
4321                 goto out_dput;
4322         error = security_path_link(old_path.dentry, &new_path, new_dentry);
4323         if (error)
4324                 goto out_dput;
4325         error = vfs_link2(old_path.mnt, old_path.dentry, new_path.dentry->d_inode, new_dentry, &delegated_inode);
4326 out_dput:
4327         done_path_create(&new_path, new_dentry);
4328         if (delegated_inode) {
4329                 error = break_deleg_wait(&delegated_inode);
4330                 if (!error) {
4331                         path_put(&old_path);
4332                         goto retry;
4333                 }
4334         }
4335         if (retry_estale(error, how)) {
4336                 path_put(&old_path);
4337                 how |= LOOKUP_REVAL;
4338                 goto retry;
4339         }
4340 out:
4341         path_put(&old_path);
4342
4343         return error;
4344 }
4345
4346 SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname)
4347 {
4348         return sys_linkat(AT_FDCWD, oldname, AT_FDCWD, newname, 0);
4349 }
4350
4351 /**
4352  * vfs_rename - rename a filesystem object
4353  * @old_dir:    parent of source
4354  * @old_dentry: source
4355  * @new_dir:    parent of destination
4356  * @new_dentry: destination
4357  * @delegated_inode: returns an inode needing a delegation break
4358  * @flags:      rename flags
4359  *
4360  * The caller must hold multiple mutexes--see lock_rename()).
4361  *
4362  * If vfs_rename discovers a delegation in need of breaking at either
4363  * the source or destination, it will return -EWOULDBLOCK and return a
4364  * reference to the inode in delegated_inode.  The caller should then
4365  * break the delegation and retry.  Because breaking a delegation may
4366  * take a long time, the caller should drop all locks before doing
4367  * so.
4368  *
4369  * Alternatively, a caller may pass NULL for delegated_inode.  This may
4370  * be appropriate for callers that expect the underlying filesystem not
4371  * to be NFS exported.
4372  *
4373  * The worst of all namespace operations - renaming directory. "Perverted"
4374  * doesn't even start to describe it. Somebody in UCB had a heck of a trip...
4375  * Problems:
4376  *      a) we can get into loop creation.
4377  *      b) race potential - two innocent renames can create a loop together.
4378  *         That's where 4.4 screws up. Current fix: serialization on
4379  *         sb->s_vfs_rename_mutex. We might be more accurate, but that's another
4380  *         story.
4381  *      c) we have to lock _four_ objects - parents and victim (if it exists),
4382  *         and source (if it is not a directory).
4383  *         And that - after we got ->i_mutex on parents (until then we don't know
4384  *         whether the target exists).  Solution: try to be smart with locking
4385  *         order for inodes.  We rely on the fact that tree topology may change
4386  *         only under ->s_vfs_rename_mutex _and_ that parent of the object we
4387  *         move will be locked.  Thus we can rank directories by the tree
4388  *         (ancestors first) and rank all non-directories after them.
4389  *         That works since everybody except rename does "lock parent, lookup,
4390  *         lock child" and rename is under ->s_vfs_rename_mutex.
4391  *         HOWEVER, it relies on the assumption that any object with ->lookup()
4392  *         has no more than 1 dentry.  If "hybrid" objects will ever appear,
4393  *         we'd better make sure that there's no link(2) for them.
4394  *      d) conversion from fhandle to dentry may come in the wrong moment - when
4395  *         we are removing the target. Solution: we will have to grab ->i_mutex
4396  *         in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on
4397  *         ->i_mutex on parents, which works but leads to some truly excessive
4398  *         locking].
4399  */
4400 int vfs_rename2(struct vfsmount *mnt,
4401                struct inode *old_dir, struct dentry *old_dentry,
4402                struct inode *new_dir, struct dentry *new_dentry,
4403                struct inode **delegated_inode, unsigned int flags)
4404 {
4405         int error;
4406         bool is_dir = d_is_dir(old_dentry);
4407         struct inode *source = old_dentry->d_inode;
4408         struct inode *target = new_dentry->d_inode;
4409         bool new_is_dir = false;
4410         unsigned max_links = new_dir->i_sb->s_max_links;
4411         struct name_snapshot old_name;
4412
4413         /*
4414          * Check source == target.
4415          * On overlayfs need to look at underlying inodes.
4416          */
4417         if (vfs_select_inode(old_dentry, 0) == vfs_select_inode(new_dentry, 0))
4418                 return 0;
4419
4420         error = may_delete(mnt, old_dir, old_dentry, is_dir);
4421         if (error)
4422                 return error;
4423
4424         if (!target) {
4425                 error = may_create(mnt, new_dir, new_dentry);
4426         } else {
4427                 new_is_dir = d_is_dir(new_dentry);
4428
4429                 if (!(flags & RENAME_EXCHANGE))
4430                         error = may_delete(mnt, new_dir, new_dentry, is_dir);
4431                 else
4432                         error = may_delete(mnt, new_dir, new_dentry, new_is_dir);
4433         }
4434         if (error)
4435                 return error;
4436
4437         if (!old_dir->i_op->rename && !old_dir->i_op->rename2)
4438                 return -EPERM;
4439
4440         if (flags && !old_dir->i_op->rename2)
4441                 return -EINVAL;
4442
4443         /*
4444          * If we are going to change the parent - check write permissions,
4445          * we'll need to flip '..'.
4446          */
4447         if (new_dir != old_dir) {
4448                 if (is_dir) {
4449                         error = inode_permission2(mnt, source, MAY_WRITE);
4450                         if (error)
4451                                 return error;
4452                 }
4453                 if ((flags & RENAME_EXCHANGE) && new_is_dir) {
4454                         error = inode_permission2(mnt, target, MAY_WRITE);
4455                         if (error)
4456                                 return error;
4457                 }
4458         }
4459
4460         error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,
4461                                       flags);
4462         if (error)
4463                 return error;
4464
4465         take_dentry_name_snapshot(&old_name, old_dentry);
4466         dget(new_dentry);
4467         if (!is_dir || (flags & RENAME_EXCHANGE))
4468                 lock_two_nondirectories(source, target);
4469         else if (target)
4470                 mutex_lock(&target->i_mutex);
4471
4472         error = -EBUSY;
4473         if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
4474                 goto out;
4475
4476         if (max_links && new_dir != old_dir) {
4477                 error = -EMLINK;
4478                 if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)
4479                         goto out;
4480                 if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&
4481                     old_dir->i_nlink >= max_links)
4482                         goto out;
4483         }
4484         if (is_dir && !(flags & RENAME_EXCHANGE) && target)
4485                 shrink_dcache_parent(new_dentry);
4486         if (!is_dir) {
4487                 error = try_break_deleg(source, delegated_inode);
4488                 if (error)
4489                         goto out;
4490         }
4491         if (target && !new_is_dir) {
4492                 error = try_break_deleg(target, delegated_inode);
4493                 if (error)
4494                         goto out;
4495         }
4496         if (!old_dir->i_op->rename2) {
4497                 error = old_dir->i_op->rename(old_dir, old_dentry,
4498                                               new_dir, new_dentry);
4499         } else {
4500                 WARN_ON(old_dir->i_op->rename != NULL);
4501                 error = old_dir->i_op->rename2(old_dir, old_dentry,
4502                                                new_dir, new_dentry, flags);
4503         }
4504         if (error)
4505                 goto out;
4506
4507         if (!(flags & RENAME_EXCHANGE) && target) {
4508                 if (is_dir)
4509                         target->i_flags |= S_DEAD;
4510                 dont_mount(new_dentry);
4511                 detach_mounts(new_dentry);
4512         }
4513         if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {
4514                 if (!(flags & RENAME_EXCHANGE))
4515                         d_move(old_dentry, new_dentry);
4516                 else
4517                         d_exchange(old_dentry, new_dentry);
4518         }
4519 out:
4520         if (!is_dir || (flags & RENAME_EXCHANGE))
4521                 unlock_two_nondirectories(source, target);
4522         else if (target)
4523                 mutex_unlock(&target->i_mutex);
4524         dput(new_dentry);
4525         if (!error) {
4526                 fsnotify_move(old_dir, new_dir, old_name.name, is_dir,
4527                               !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);
4528                 if (flags & RENAME_EXCHANGE) {
4529                         fsnotify_move(new_dir, old_dir, old_dentry->d_name.name,
4530                                       new_is_dir, NULL, new_dentry);
4531                 }
4532         }
4533         release_dentry_name_snapshot(&old_name);
4534
4535         return error;
4536 }
4537 EXPORT_SYMBOL(vfs_rename2);
4538
4539 int vfs_rename(struct inode *old_dir, struct dentry *old_dentry,
4540                struct inode *new_dir, struct dentry *new_dentry,
4541                struct inode **delegated_inode, unsigned int flags)
4542 {
4543         return vfs_rename2(NULL, old_dir, old_dentry, new_dir, new_dentry, delegated_inode, flags);
4544 }
4545 EXPORT_SYMBOL(vfs_rename);
4546
4547 SYSCALL_DEFINE5(renameat2, int, olddfd, const char __user *, oldname,
4548                 int, newdfd, const char __user *, newname, unsigned int, flags)
4549 {
4550         struct dentry *old_dentry, *new_dentry;
4551         struct dentry *trap;
4552         struct path old_path, new_path;
4553         struct qstr old_last, new_last;
4554         int old_type, new_type;
4555         struct inode *delegated_inode = NULL;
4556         struct filename *from;
4557         struct filename *to;
4558         unsigned int lookup_flags = 0, target_flags = LOOKUP_RENAME_TARGET;
4559         bool should_retry = false;
4560         int error;
4561
4562         if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
4563                 return -EINVAL;
4564
4565         if ((flags & (RENAME_NOREPLACE | RENAME_WHITEOUT)) &&
4566             (flags & RENAME_EXCHANGE))
4567                 return -EINVAL;
4568
4569         if ((flags & RENAME_WHITEOUT) && !capable(CAP_MKNOD))
4570                 return -EPERM;
4571
4572         if (flags & RENAME_EXCHANGE)
4573                 target_flags = 0;
4574
4575 retry:
4576         from = user_path_parent(olddfd, oldname,
4577                                 &old_path, &old_last, &old_type, lookup_flags);
4578         if (IS_ERR(from)) {
4579                 error = PTR_ERR(from);
4580                 goto exit;
4581         }
4582
4583         to = user_path_parent(newdfd, newname,
4584                                 &new_path, &new_last, &new_type, lookup_flags);
4585         if (IS_ERR(to)) {
4586                 error = PTR_ERR(to);
4587                 goto exit1;
4588         }
4589
4590         error = -EXDEV;
4591         if (old_path.mnt != new_path.mnt)
4592                 goto exit2;
4593
4594         error = -EBUSY;
4595         if (old_type != LAST_NORM)
4596                 goto exit2;
4597
4598         if (flags & RENAME_NOREPLACE)
4599                 error = -EEXIST;
4600         if (new_type != LAST_NORM)
4601                 goto exit2;
4602
4603         error = mnt_want_write(old_path.mnt);
4604         if (error)
4605                 goto exit2;
4606
4607 retry_deleg:
4608         trap = lock_rename(new_path.dentry, old_path.dentry);
4609
4610         old_dentry = __lookup_hash(&old_last, old_path.dentry, lookup_flags);
4611         error = PTR_ERR(old_dentry);
4612         if (IS_ERR(old_dentry))
4613                 goto exit3;
4614         /* source must exist */
4615         error = -ENOENT;
4616         if (d_is_negative(old_dentry))
4617                 goto exit4;
4618         new_dentry = __lookup_hash(&new_last, new_path.dentry, lookup_flags | target_flags);
4619         error = PTR_ERR(new_dentry);
4620         if (IS_ERR(new_dentry))
4621                 goto exit4;
4622         error = -EEXIST;
4623         if ((flags & RENAME_NOREPLACE) && d_is_positive(new_dentry))
4624                 goto exit5;
4625         if (flags & RENAME_EXCHANGE) {
4626                 error = -ENOENT;
4627                 if (d_is_negative(new_dentry))
4628                         goto exit5;
4629
4630                 if (!d_is_dir(new_dentry)) {
4631                         error = -ENOTDIR;
4632                         if (new_last.name[new_last.len])
4633                                 goto exit5;
4634                 }
4635         }
4636         /* unless the source is a directory trailing slashes give -ENOTDIR */
4637         if (!d_is_dir(old_dentry)) {
4638                 error = -ENOTDIR;
4639                 if (old_last.name[old_last.len])
4640                         goto exit5;
4641                 if (!(flags & RENAME_EXCHANGE) && new_last.name[new_last.len])
4642                         goto exit5;
4643         }
4644         /* source should not be ancestor of target */
4645         error = -EINVAL;
4646         if (old_dentry == trap)
4647                 goto exit5;
4648         /* target should not be an ancestor of source */
4649         if (!(flags & RENAME_EXCHANGE))
4650                 error = -ENOTEMPTY;
4651         if (new_dentry == trap)
4652                 goto exit5;
4653
4654         error = security_path_rename(&old_path, old_dentry,
4655                                      &new_path, new_dentry, flags);
4656         if (error)
4657                 goto exit5;
4658         error = vfs_rename2(old_path.mnt, old_path.dentry->d_inode, old_dentry,
4659                            new_path.dentry->d_inode, new_dentry,
4660                            &delegated_inode, flags);
4661 exit5:
4662         dput(new_dentry);
4663 exit4:
4664         dput(old_dentry);
4665 exit3:
4666         unlock_rename(new_path.dentry, old_path.dentry);
4667         if (delegated_inode) {
4668                 error = break_deleg_wait(&delegated_inode);
4669                 if (!error)
4670                         goto retry_deleg;
4671         }
4672         mnt_drop_write(old_path.mnt);
4673 exit2:
4674         if (retry_estale(error, lookup_flags))
4675                 should_retry = true;
4676         path_put(&new_path);
4677         putname(to);
4678 exit1:
4679         path_put(&old_path);
4680         putname(from);
4681         if (should_retry) {
4682                 should_retry = false;
4683                 lookup_flags |= LOOKUP_REVAL;
4684                 goto retry;
4685         }
4686 exit:
4687         return error;
4688 }
4689
4690 SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname,
4691                 int, newdfd, const char __user *, newname)
4692 {
4693         return sys_renameat2(olddfd, oldname, newdfd, newname, 0);
4694 }
4695
4696 SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname)
4697 {
4698         return sys_renameat2(AT_FDCWD, oldname, AT_FDCWD, newname, 0);
4699 }
4700
4701 int vfs_whiteout(struct inode *dir, struct dentry *dentry)
4702 {
4703         int error = may_create(NULL, dir, dentry);
4704         if (error)
4705                 return error;
4706
4707         if (!dir->i_op->mknod)
4708                 return -EPERM;
4709
4710         return dir->i_op->mknod(dir, dentry,
4711                                 S_IFCHR | WHITEOUT_MODE, WHITEOUT_DEV);
4712 }
4713 EXPORT_SYMBOL(vfs_whiteout);
4714
4715 int readlink_copy(char __user *buffer, int buflen, const char *link)
4716 {
4717         int len = PTR_ERR(link);
4718         if (IS_ERR(link))
4719                 goto out;
4720
4721         len = strlen(link);
4722         if (len > (unsigned) buflen)
4723                 len = buflen;
4724         if (copy_to_user(buffer, link, len))
4725                 len = -EFAULT;
4726 out:
4727         return len;
4728 }
4729 EXPORT_SYMBOL(readlink_copy);
4730
4731 /*
4732  * A helper for ->readlink().  This should be used *ONLY* for symlinks that
4733  * have ->follow_link() touching nd only in nd_set_link().  Using (or not
4734  * using) it for any given inode is up to filesystem.
4735  */
4736 int generic_readlink(struct dentry *dentry, char __user *buffer, int buflen)
4737 {
4738         void *cookie;
4739         struct inode *inode = d_inode(dentry);
4740         const char *link = inode->i_link;
4741         int res;
4742
4743         if (!link) {
4744                 link = inode->i_op->follow_link(dentry, &cookie);
4745                 if (IS_ERR(link))
4746                         return PTR_ERR(link);
4747         }
4748         res = readlink_copy(buffer, buflen, link);
4749         if (inode->i_op->put_link)
4750                 inode->i_op->put_link(inode, cookie);
4751         return res;
4752 }
4753 EXPORT_SYMBOL(generic_readlink);
4754
4755 /* get the link contents into pagecache */
4756 static char *page_getlink(struct dentry * dentry, struct page **ppage)
4757 {
4758         char *kaddr;
4759         struct page *page;
4760         struct address_space *mapping = dentry->d_inode->i_mapping;
4761         page = read_mapping_page(mapping, 0, NULL);
4762         if (IS_ERR(page))
4763                 return (char*)page;
4764         *ppage = page;
4765         kaddr = kmap(page);
4766         nd_terminate_link(kaddr, dentry->d_inode->i_size, PAGE_SIZE - 1);
4767         return kaddr;
4768 }
4769
4770 int page_readlink(struct dentry *dentry, char __user *buffer, int buflen)
4771 {
4772         struct page *page = NULL;
4773         int res = readlink_copy(buffer, buflen, page_getlink(dentry, &page));
4774         if (page) {
4775                 kunmap(page);
4776                 page_cache_release(page);
4777         }
4778         return res;
4779 }
4780 EXPORT_SYMBOL(page_readlink);
4781
4782 const char *page_follow_link_light(struct dentry *dentry, void **cookie)
4783 {
4784         struct page *page = NULL;
4785         char *res = page_getlink(dentry, &page);
4786         if (!IS_ERR(res))
4787                 *cookie = page;
4788         return res;
4789 }
4790 EXPORT_SYMBOL(page_follow_link_light);
4791
4792 void page_put_link(struct inode *unused, void *cookie)
4793 {
4794         struct page *page = cookie;
4795         kunmap(page);
4796         page_cache_release(page);
4797 }
4798 EXPORT_SYMBOL(page_put_link);
4799
4800 /*
4801  * The nofs argument instructs pagecache_write_begin to pass AOP_FLAG_NOFS
4802  */
4803 int __page_symlink(struct inode *inode, const char *symname, int len, int nofs)
4804 {
4805         struct address_space *mapping = inode->i_mapping;
4806         struct page *page;
4807         void *fsdata;
4808         int err;
4809         char *kaddr;
4810         unsigned int flags = AOP_FLAG_UNINTERRUPTIBLE;
4811         if (nofs)
4812                 flags |= AOP_FLAG_NOFS;
4813
4814 retry:
4815         err = pagecache_write_begin(NULL, mapping, 0, len-1,
4816                                 flags, &page, &fsdata);
4817         if (err)
4818                 goto fail;
4819
4820         kaddr = kmap_atomic(page);
4821         memcpy(kaddr, symname, len-1);
4822         kunmap_atomic(kaddr);
4823
4824         err = pagecache_write_end(NULL, mapping, 0, len-1, len-1,
4825                                                         page, fsdata);
4826         if (err < 0)
4827                 goto fail;
4828         if (err < len-1)
4829                 goto retry;
4830
4831         mark_inode_dirty(inode);
4832         return 0;
4833 fail:
4834         return err;
4835 }
4836 EXPORT_SYMBOL(__page_symlink);
4837
4838 int page_symlink(struct inode *inode, const char *symname, int len)
4839 {
4840         return __page_symlink(inode, symname, len,
4841                         !mapping_gfp_constraint(inode->i_mapping, __GFP_FS));
4842 }
4843 EXPORT_SYMBOL(page_symlink);
4844
4845 const struct inode_operations page_symlink_inode_operations = {
4846         .readlink       = generic_readlink,
4847         .follow_link    = page_follow_link_light,
4848         .put_link       = page_put_link,
4849 };
4850 EXPORT_SYMBOL(page_symlink_inode_operations);