OSDN Git Service

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