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