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