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