OSDN Git Service

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