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