~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/fs/namei.c

Version: ~ [ linux-5.17-rc1 ] ~ [ linux-5.16.2 ] ~ [ linux-5.15.16 ] ~ [ linux-5.14.21 ] ~ [ linux-5.13.19 ] ~ [ linux-5.12.19 ] ~ [ linux-5.11.22 ] ~ [ linux-5.10.93 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.173 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.225 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.262 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.297 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.299 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.18.140 ] ~ [ linux-3.16.85 ] ~ [ linux-3.14.79 ] ~ [ linux-3.12.74 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

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

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

osdn.jp