OSDN Git Service

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