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

TOMOYO Linux Cross Reference
Linux/fs/namei.c

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

~ [ 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