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