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 (!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_CHILD);
2782 return p;
2783 }
2784
2785 p = d_ancestor(p1, p2);
2786 if (p) {
2787 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
2788 inode_lock_nested(p2->d_inode, I_MUTEX_CHILD);
2789 return p;
2790 }
2791
2792 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
2793 inode_lock_nested(p2->d_inode, I_MUTEX_PARENT2);
2794 return NULL;
2795 }
2796 EXPORT_SYMBOL(lock_rename);
2797
unlock_rename(struct dentry * p1,struct dentry * p2)2798 void unlock_rename(struct dentry *p1, struct dentry *p2)
2799 {
2800 inode_unlock(p1->d_inode);
2801 if (p1 != p2) {
2802 inode_unlock(p2->d_inode);
2803 mutex_unlock(&p1->d_sb->s_vfs_rename_mutex);
2804 }
2805 }
2806 EXPORT_SYMBOL(unlock_rename);
2807
vfs_create(struct inode * dir,struct dentry * dentry,umode_t mode,bool want_excl)2808 int vfs_create(struct inode *dir, struct dentry *dentry, umode_t mode,
2809 bool want_excl)
2810 {
2811 int error = may_create(dir, dentry);
2812 if (error)
2813 return error;
2814
2815 if (!dir->i_op->create)
2816 return -EACCES; /* shouldn't it be ENOSYS? */
2817 mode &= S_IALLUGO;
2818 mode |= S_IFREG;
2819 error = security_inode_create(dir, dentry, mode);
2820 if (error)
2821 return error;
2822 error = dir->i_op->create(dir, dentry, mode, want_excl);
2823 if (!error)
2824 fsnotify_create(dir, dentry);
2825 return error;
2826 }
2827 EXPORT_SYMBOL(vfs_create);
2828
vfs_mkobj(struct dentry * dentry,umode_t mode,int (* f)(struct dentry *,umode_t,void *),void * arg)2829 int vfs_mkobj(struct dentry *dentry, umode_t mode,
2830 int (*f)(struct dentry *, umode_t, void *),
2831 void *arg)
2832 {
2833 struct inode *dir = dentry->d_parent->d_inode;
2834 int error = may_create(dir, dentry);
2835 if (error)
2836 return error;
2837
2838 mode &= S_IALLUGO;
2839 mode |= S_IFREG;
2840 error = security_inode_create(dir, dentry, mode);
2841 if (error)
2842 return error;
2843 error = f(dentry, mode, arg);
2844 if (!error)
2845 fsnotify_create(dir, dentry);
2846 return error;
2847 }
2848 EXPORT_SYMBOL(vfs_mkobj);
2849
may_open_dev(const struct path * path)2850 bool may_open_dev(const struct path *path)
2851 {
2852 return !(path->mnt->mnt_flags & MNT_NODEV) &&
2853 !(path->mnt->mnt_sb->s_iflags & SB_I_NODEV);
2854 }
2855
may_open(const struct path * path,int acc_mode,int flag)2856 static int may_open(const struct path *path, int acc_mode, int flag)
2857 {
2858 struct dentry *dentry = path->dentry;
2859 struct inode *inode = dentry->d_inode;
2860 int error;
2861
2862 if (!inode)
2863 return -ENOENT;
2864
2865 switch (inode->i_mode & S_IFMT) {
2866 case S_IFLNK:
2867 return -ELOOP;
2868 case S_IFDIR:
2869 if (acc_mode & MAY_WRITE)
2870 return -EISDIR;
2871 if (acc_mode & MAY_EXEC)
2872 return -EACCES;
2873 break;
2874 case S_IFBLK:
2875 case S_IFCHR:
2876 if (!may_open_dev(path))
2877 return -EACCES;
2878 fallthrough;
2879 case S_IFIFO:
2880 case S_IFSOCK:
2881 if (acc_mode & MAY_EXEC)
2882 return -EACCES;
2883 flag &= ~O_TRUNC;
2884 break;
2885 case S_IFREG:
2886 if ((acc_mode & MAY_EXEC) && path_noexec(path))
2887 return -EACCES;
2888 break;
2889 }
2890
2891 error = inode_permission(inode, MAY_OPEN | acc_mode);
2892 if (error)
2893 return error;
2894
2895 /*
2896 * An append-only file must be opened in append mode for writing.
2897 */
2898 if (IS_APPEND(inode)) {
2899 if ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND))
2900 return -EPERM;
2901 if (flag & O_TRUNC)
2902 return -EPERM;
2903 }
2904
2905 /* O_NOATIME can only be set by the owner or superuser */
2906 if (flag & O_NOATIME && !inode_owner_or_capable(inode))
2907 return -EPERM;
2908
2909 return 0;
2910 }
2911
handle_truncate(struct file * filp)2912 static int handle_truncate(struct file *filp)
2913 {
2914 const struct path *path = &filp->f_path;
2915 struct inode *inode = path->dentry->d_inode;
2916 int error = get_write_access(inode);
2917 if (error)
2918 return error;
2919 /*
2920 * Refuse to truncate files with mandatory locks held on them.
2921 */
2922 error = locks_verify_locked(filp);
2923 if (!error)
2924 error = security_path_truncate(path);
2925 if (!error) {
2926 error = do_truncate(path->dentry, 0,
2927 ATTR_MTIME|ATTR_CTIME|ATTR_OPEN,
2928 filp);
2929 }
2930 put_write_access(inode);
2931 return error;
2932 }
2933
open_to_namei_flags(int flag)2934 static inline int open_to_namei_flags(int flag)
2935 {
2936 if ((flag & O_ACCMODE) == 3)
2937 flag--;
2938 return flag;
2939 }
2940
may_o_create(const struct path * dir,struct dentry * dentry,umode_t mode)2941 static int may_o_create(const struct path *dir, struct dentry *dentry, umode_t mode)
2942 {
2943 struct user_namespace *s_user_ns;
2944 int error = security_path_mknod(dir, dentry, mode, 0);
2945 if (error)
2946 return error;
2947
2948 s_user_ns = dir->dentry->d_sb->s_user_ns;
2949 if (!kuid_has_mapping(s_user_ns, current_fsuid()) ||
2950 !kgid_has_mapping(s_user_ns, current_fsgid()))
2951 return -EOVERFLOW;
2952
2953 error = inode_permission(dir->dentry->d_inode, MAY_WRITE | MAY_EXEC);
2954 if (error)
2955 return error;
2956
2957 return security_inode_create(dir->dentry->d_inode, dentry, mode);
2958 }
2959
2960 /*
2961 * Attempt to atomically look up, create and open a file from a negative
2962 * dentry.
2963 *
2964 * Returns 0 if successful. The file will have been created and attached to
2965 * @file by the filesystem calling finish_open().
2966 *
2967 * If the file was looked up only or didn't need creating, FMODE_OPENED won't
2968 * be set. The caller will need to perform the open themselves. @path will
2969 * have been updated to point to the new dentry. This may be negative.
2970 *
2971 * Returns an error code otherwise.
2972 */
atomic_open(struct nameidata * nd,struct dentry * dentry,struct file * file,int open_flag,umode_t mode)2973 static struct dentry *atomic_open(struct nameidata *nd, struct dentry *dentry,
2974 struct file *file,
2975 int open_flag, umode_t mode)
2976 {
2977 struct dentry *const DENTRY_NOT_SET = (void *) -1UL;
2978 struct inode *dir = nd->path.dentry->d_inode;
2979 int error;
2980
2981 if (nd->flags & LOOKUP_DIRECTORY)
2982 open_flag |= O_DIRECTORY;
2983
2984 file->f_path.dentry = DENTRY_NOT_SET;
2985 file->f_path.mnt = nd->path.mnt;
2986 error = dir->i_op->atomic_open(dir, dentry, file,
2987 open_to_namei_flags(open_flag), mode);
2988 d_lookup_done(dentry);
2989 if (!error) {
2990 if (file->f_mode & FMODE_OPENED) {
2991 if (unlikely(dentry != file->f_path.dentry)) {
2992 dput(dentry);
2993 dentry = dget(file->f_path.dentry);
2994 }
2995 } else if (WARN_ON(file->f_path.dentry == DENTRY_NOT_SET)) {
2996 error = -EIO;
2997 } else {
2998 if (file->f_path.dentry) {
2999 dput(dentry);
3000 dentry = file->f_path.dentry;
3001 }
3002 if (unlikely(d_is_negative(dentry)))
3003 error = -ENOENT;
3004 }
3005 }
3006 if (error) {
3007 dput(dentry);
3008 dentry = ERR_PTR(error);
3009 }
3010 return dentry;
3011 }
3012
3013 /*
3014 * Look up and maybe create and open the last component.
3015 *
3016 * Must be called with parent locked (exclusive in O_CREAT case).
3017 *
3018 * Returns 0 on success, that is, if
3019 * the file was successfully atomically created (if necessary) and opened, or
3020 * the file was not completely opened at this time, though lookups and
3021 * creations were performed.
3022 * These case are distinguished by presence of FMODE_OPENED on file->f_mode.
3023 * In the latter case dentry returned in @path might be negative if O_CREAT
3024 * hadn't been specified.
3025 *
3026 * An error code is returned on failure.
3027 */
lookup_open(struct nameidata * nd,struct file * file,const struct open_flags * op,bool got_write)3028 static struct dentry *lookup_open(struct nameidata *nd, struct file *file,
3029 const struct open_flags *op,
3030 bool got_write)
3031 {
3032 struct dentry *dir = nd->path.dentry;
3033 struct inode *dir_inode = dir->d_inode;
3034 int open_flag = op->open_flag;
3035 struct dentry *dentry;
3036 int error, create_error = 0;
3037 umode_t mode = op->mode;
3038 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
3039
3040 if (unlikely(IS_DEADDIR(dir_inode)))
3041 return ERR_PTR(-ENOENT);
3042
3043 file->f_mode &= ~FMODE_CREATED;
3044 dentry = d_lookup(dir, &nd->last);
3045 for (;;) {
3046 if (!dentry) {
3047 dentry = d_alloc_parallel(dir, &nd->last, &wq);
3048 if (IS_ERR(dentry))
3049 return dentry;
3050 }
3051 if (d_in_lookup(dentry))
3052 break;
3053
3054 error = d_revalidate(dentry, nd->flags);
3055 if (likely(error > 0))
3056 break;
3057 if (error)
3058 goto out_dput;
3059 d_invalidate(dentry);
3060 dput(dentry);
3061 dentry = NULL;
3062 }
3063 if (dentry->d_inode) {
3064 /* Cached positive dentry: will open in f_op->open */
3065 return dentry;
3066 }
3067
3068 /*
3069 * Checking write permission is tricky, bacuse we don't know if we are
3070 * going to actually need it: O_CREAT opens should work as long as the
3071 * file exists. But checking existence breaks atomicity. The trick is
3072 * to check access and if not granted clear O_CREAT from the flags.
3073 *
3074 * Another problem is returing the "right" error value (e.g. for an
3075 * O_EXCL open we want to return EEXIST not EROFS).
3076 */
3077 if (unlikely(!got_write))
3078 open_flag &= ~O_TRUNC;
3079 if (open_flag & O_CREAT) {
3080 if (open_flag & O_EXCL)
3081 open_flag &= ~O_TRUNC;
3082 if (!IS_POSIXACL(dir->d_inode))
3083 mode &= ~current_umask();
3084 if (likely(got_write))
3085 create_error = may_o_create(&nd->path, dentry, mode);
3086 else
3087 create_error = -EROFS;
3088 }
3089 if (create_error)
3090 open_flag &= ~O_CREAT;
3091 if (dir_inode->i_op->atomic_open) {
3092 dentry = atomic_open(nd, dentry, file, open_flag, mode);
3093 if (unlikely(create_error) && dentry == ERR_PTR(-ENOENT))
3094 dentry = ERR_PTR(create_error);
3095 return dentry;
3096 }
3097
3098 if (d_in_lookup(dentry)) {
3099 struct dentry *res = dir_inode->i_op->lookup(dir_inode, dentry,
3100 nd->flags);
3101 d_lookup_done(dentry);
3102 if (unlikely(res)) {
3103 if (IS_ERR(res)) {
3104 error = PTR_ERR(res);
3105 goto out_dput;
3106 }
3107 dput(dentry);
3108 dentry = res;
3109 }
3110 }
3111
3112 /* Negative dentry, just create the file */
3113 if (!dentry->d_inode && (open_flag & O_CREAT)) {
3114 file->f_mode |= FMODE_CREATED;
3115 audit_inode_child(dir_inode, dentry, AUDIT_TYPE_CHILD_CREATE);
3116 if (!dir_inode->i_op->create) {
3117 error = -EACCES;
3118 goto out_dput;
3119 }
3120 error = dir_inode->i_op->create(dir_inode, dentry, mode,
3121 open_flag & O_EXCL);
3122 if (error)
3123 goto out_dput;
3124 }
3125 if (unlikely(create_error) && !dentry->d_inode) {
3126 error = create_error;
3127 goto out_dput;
3128 }
3129 return dentry;
3130
3131 out_dput:
3132 dput(dentry);
3133 return ERR_PTR(error);
3134 }
3135
open_last_lookups(struct nameidata * nd,struct file * file,const struct open_flags * op)3136 static const char *open_last_lookups(struct nameidata *nd,
3137 struct file *file, const struct open_flags *op)
3138 {
3139 struct dentry *dir = nd->path.dentry;
3140 int open_flag = op->open_flag;
3141 bool got_write = false;
3142 unsigned seq;
3143 struct inode *inode;
3144 struct dentry *dentry;
3145 const char *res;
3146
3147 nd->flags |= op->intent;
3148
3149 if (nd->last_type != LAST_NORM) {
3150 if (nd->depth)
3151 put_link(nd);
3152 return handle_dots(nd, nd->last_type);
3153 }
3154
3155 if (!(open_flag & O_CREAT)) {
3156 if (nd->last.name[nd->last.len])
3157 nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
3158 /* we _can_ be in RCU mode here */
3159 dentry = lookup_fast(nd, &inode, &seq);
3160 if (IS_ERR(dentry))
3161 return ERR_CAST(dentry);
3162 if (likely(dentry))
3163 goto finish_lookup;
3164
3165 BUG_ON(nd->flags & LOOKUP_RCU);
3166 } else {
3167 /* create side of things */
3168 if (nd->flags & LOOKUP_RCU) {
3169 if (!try_to_unlazy(nd))
3170 return ERR_PTR(-ECHILD);
3171 }
3172 audit_inode(nd->name, dir, AUDIT_INODE_PARENT);
3173 /* trailing slashes? */
3174 if (unlikely(nd->last.name[nd->last.len]))
3175 return ERR_PTR(-EISDIR);
3176 }
3177
3178 if (open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) {
3179 got_write = !mnt_want_write(nd->path.mnt);
3180 /*
3181 * do _not_ fail yet - we might not need that or fail with
3182 * a different error; let lookup_open() decide; we'll be
3183 * dropping this one anyway.
3184 */
3185 }
3186 if (open_flag & O_CREAT)
3187 inode_lock(dir->d_inode);
3188 else
3189 inode_lock_shared(dir->d_inode);
3190 dentry = lookup_open(nd, file, op, got_write);
3191 if (!IS_ERR(dentry) && (file->f_mode & FMODE_CREATED))
3192 fsnotify_create(dir->d_inode, dentry);
3193 if (open_flag & O_CREAT)
3194 inode_unlock(dir->d_inode);
3195 else
3196 inode_unlock_shared(dir->d_inode);
3197
3198 if (got_write)
3199 mnt_drop_write(nd->path.mnt);
3200
3201 if (IS_ERR(dentry))
3202 return ERR_CAST(dentry);
3203
3204 if (file->f_mode & (FMODE_OPENED | FMODE_CREATED)) {
3205 dput(nd->path.dentry);
3206 nd->path.dentry = dentry;
3207 return NULL;
3208 }
3209
3210 finish_lookup:
3211 if (nd->depth)
3212 put_link(nd);
3213 res = step_into(nd, WALK_TRAILING, dentry, inode, seq);
3214 if (unlikely(res))
3215 nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL);
3216 return res;
3217 }
3218
3219 /*
3220 * Handle the last step of open()
3221 */
do_open(struct nameidata * nd,struct file * file,const struct open_flags * op)3222 static int do_open(struct nameidata *nd,
3223 struct file *file, const struct open_flags *op)
3224 {
3225 int open_flag = op->open_flag;
3226 bool do_truncate;
3227 int acc_mode;
3228 int error;
3229
3230 if (!(file->f_mode & (FMODE_OPENED | FMODE_CREATED))) {
3231 error = complete_walk(nd);
3232 if (error)
3233 return error;
3234 }
3235 if (!(file->f_mode & FMODE_CREATED))
3236 audit_inode(nd->name, nd->path.dentry, 0);
3237 if (open_flag & O_CREAT) {
3238 if ((open_flag & O_EXCL) && !(file->f_mode & FMODE_CREATED))
3239 return -EEXIST;
3240 if (d_is_dir(nd->path.dentry))
3241 return -EISDIR;
3242 error = may_create_in_sticky(nd->dir_mode, nd->dir_uid,
3243 d_backing_inode(nd->path.dentry));
3244 if (unlikely(error))
3245 return error;
3246 }
3247 if ((nd->flags & LOOKUP_DIRECTORY) && !d_can_lookup(nd->path.dentry))
3248 return -ENOTDIR;
3249
3250 do_truncate = false;
3251 acc_mode = op->acc_mode;
3252 if (file->f_mode & FMODE_CREATED) {
3253 /* Don't check for write permission, don't truncate */
3254 open_flag &= ~O_TRUNC;
3255 acc_mode = 0;
3256 } else if (d_is_reg(nd->path.dentry) && open_flag & O_TRUNC) {
3257 error = mnt_want_write(nd->path.mnt);
3258 if (error)
3259 return error;
3260 do_truncate = true;
3261 }
3262 error = may_open(&nd->path, acc_mode, open_flag);
3263 if (!error && !(file->f_mode & FMODE_OPENED))
3264 error = vfs_open(&nd->path, file);
3265 if (!error)
3266 error = ima_file_check(file, op->acc_mode);
3267 if (!error && do_truncate)
3268 error = handle_truncate(file);
3269 if (unlikely(error > 0)) {
3270 WARN_ON(1);
3271 error = -EINVAL;
3272 }
3273 if (do_truncate)
3274 mnt_drop_write(nd->path.mnt);
3275 return error;
3276 }
3277
vfs_tmpfile(struct dentry * dentry,umode_t mode,int open_flag)3278 struct dentry *vfs_tmpfile(struct dentry *dentry, umode_t mode, int open_flag)
3279 {
3280 struct dentry *child = NULL;
3281 struct inode *dir = dentry->d_inode;
3282 struct inode *inode;
3283 int error;
3284
3285 /* we want directory to be writable */
3286 error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
3287 if (error)
3288 goto out_err;
3289 error = -EOPNOTSUPP;
3290 if (!dir->i_op->tmpfile)
3291 goto out_err;
3292 error = -ENOMEM;
3293 child = d_alloc(dentry, &slash_name);
3294 if (unlikely(!child))
3295 goto out_err;
3296 if (!IS_POSIXACL(dir))
3297 mode &= ~current_umask();
3298 error = dir->i_op->tmpfile(dir, child, mode);
3299 if (error)
3300 goto out_err;
3301 error = -ENOENT;
3302 inode = child->d_inode;
3303 if (unlikely(!inode))
3304 goto out_err;
3305 if (!(open_flag & O_EXCL)) {
3306 spin_lock(&inode->i_lock);
3307 inode->i_state |= I_LINKABLE;
3308 spin_unlock(&inode->i_lock);
3309 }
3310 ima_post_create_tmpfile(inode);
3311 return child;
3312
3313 out_err:
3314 dput(child);
3315 return ERR_PTR(error);
3316 }
3317 EXPORT_SYMBOL(vfs_tmpfile);
3318
do_tmpfile(struct nameidata * nd,unsigned flags,const struct open_flags * op,struct file * file)3319 static int do_tmpfile(struct nameidata *nd, unsigned flags,
3320 const struct open_flags *op,
3321 struct file *file)
3322 {
3323 struct dentry *child;
3324 struct path path;
3325 int error = path_lookupat(nd, flags | LOOKUP_DIRECTORY, &path);
3326 if (unlikely(error))
3327 return error;
3328 error = mnt_want_write(path.mnt);
3329 if (unlikely(error))
3330 goto out;
3331 child = vfs_tmpfile(path.dentry, op->mode, op->open_flag);
3332 error = PTR_ERR(child);
3333 if (IS_ERR(child))
3334 goto out2;
3335 dput(path.dentry);
3336 path.dentry = child;
3337 audit_inode(nd->name, child, 0);
3338 /* Don't check for other permissions, the inode was just created */
3339 error = may_open(&path, 0, op->open_flag);
3340 if (error)
3341 goto out2;
3342 file->f_path.mnt = path.mnt;
3343 error = finish_open(file, child, NULL);
3344 out2:
3345 mnt_drop_write(path.mnt);
3346 out:
3347 path_put(&path);
3348 return error;
3349 }
3350
do_o_path(struct nameidata * nd,unsigned flags,struct file * file)3351 static int do_o_path(struct nameidata *nd, unsigned flags, struct file *file)
3352 {
3353 struct path path;
3354 int error = path_lookupat(nd, flags, &path);
3355 if (!error) {
3356 audit_inode(nd->name, path.dentry, 0);
3357 error = vfs_open(&path, file);
3358 path_put(&path);
3359 }
3360 return error;
3361 }
3362
path_openat(struct nameidata * nd,const struct open_flags * op,unsigned flags)3363 static struct file *path_openat(struct nameidata *nd,
3364 const struct open_flags *op, unsigned flags)
3365 {
3366 struct file *file;
3367 int error;
3368
3369 file = alloc_empty_file(op->open_flag, current_cred());
3370 if (IS_ERR(file))
3371 return file;
3372
3373 if (unlikely(file->f_flags & __O_TMPFILE)) {
3374 error = do_tmpfile(nd, flags, op, file);
3375 } else if (unlikely(file->f_flags & O_PATH)) {
3376 error = do_o_path(nd, flags, file);
3377 } else {
3378 const char *s = path_init(nd, flags);
3379 while (!(error = link_path_walk(s, nd)) &&
3380 (s = open_last_lookups(nd, file, op)) != NULL)
3381 ;
3382 if (!error)
3383 error = do_open(nd, file, op);
3384 terminate_walk(nd);
3385 }
3386 if (likely(!error)) {
3387 if (likely(file->f_mode & FMODE_OPENED))
3388 return file;
3389 WARN_ON(1);
3390 error = -EINVAL;
3391 }
3392 fput(file);
3393 if (error == -EOPENSTALE) {
3394 if (flags & LOOKUP_RCU)
3395 error = -ECHILD;
3396 else
3397 error = -ESTALE;
3398 }
3399 return ERR_PTR(error);
3400 }
3401
do_filp_open(int dfd,struct filename * pathname,const struct open_flags * op)3402 struct file *do_filp_open(int dfd, struct filename *pathname,
3403 const struct open_flags *op)
3404 {
3405 struct nameidata nd;
3406 int flags = op->lookup_flags;
3407 struct file *filp;
3408
3409 set_nameidata(&nd, dfd, pathname);
3410 filp = path_openat(&nd, op, flags | LOOKUP_RCU);
3411 if (unlikely(filp == ERR_PTR(-ECHILD)))
3412 filp = path_openat(&nd, op, flags);
3413 if (unlikely(filp == ERR_PTR(-ESTALE)))
3414 filp = path_openat(&nd, op, flags | LOOKUP_REVAL);
3415 restore_nameidata();
3416 return filp;
3417 }
3418
do_file_open_root(const struct path * root,const char * name,const struct open_flags * op)3419 struct file *do_file_open_root(const struct path *root,
3420 const char *name, const struct open_flags *op)
3421 {
3422 struct nameidata nd;
3423 struct file *file;
3424 struct filename *filename;
3425 int flags = op->lookup_flags;
3426
3427 if (d_is_symlink(root->dentry) && op->intent & LOOKUP_OPEN)
3428 return ERR_PTR(-ELOOP);
3429
3430 filename = getname_kernel(name);
3431 if (IS_ERR(filename))
3432 return ERR_CAST(filename);
3433
3434 set_nameidata(&nd, -1, filename);
3435 nd.root = *root;
3436 nd.state = ND_ROOT_PRESET;
3437 file = path_openat(&nd, op, flags | LOOKUP_RCU);
3438 if (unlikely(file == ERR_PTR(-ECHILD)))
3439 file = path_openat(&nd, op, flags);
3440 if (unlikely(file == ERR_PTR(-ESTALE)))
3441 file = path_openat(&nd, op, flags | LOOKUP_REVAL);
3442 restore_nameidata();
3443 putname(filename);
3444 return file;
3445 }
3446
filename_create(int dfd,struct filename * name,struct path * path,unsigned int lookup_flags)3447 static struct dentry *filename_create(int dfd, struct filename *name,
3448 struct path *path, unsigned int lookup_flags)
3449 {
3450 struct dentry *dentry = ERR_PTR(-EEXIST);
3451 struct qstr last;
3452 int type;
3453 int err2;
3454 int error;
3455 bool is_dir = (lookup_flags & LOOKUP_DIRECTORY);
3456
3457 /*
3458 * Note that only LOOKUP_REVAL and LOOKUP_DIRECTORY matter here. Any
3459 * other flags passed in are ignored!
3460 */
3461 lookup_flags &= LOOKUP_REVAL;
3462
3463 name = filename_parentat(dfd, name, lookup_flags, path, &last, &type);
3464 if (IS_ERR(name))
3465 return ERR_CAST(name);
3466
3467 /*
3468 * Yucky last component or no last component at all?
3469 * (foo/., foo/.., /////)
3470 */
3471 if (unlikely(type != LAST_NORM))
3472 goto out;
3473
3474 /* don't fail immediately if it's r/o, at least try to report other errors */
3475 err2 = mnt_want_write(path->mnt);
3476 /*
3477 * Do the final lookup.
3478 */
3479 lookup_flags |= LOOKUP_CREATE | LOOKUP_EXCL;
3480 inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
3481 dentry = __lookup_hash(&last, path->dentry, lookup_flags);
3482 if (IS_ERR(dentry))
3483 goto unlock;
3484
3485 error = -EEXIST;
3486 if (d_is_positive(dentry))
3487 goto fail;
3488
3489 /*
3490 * Special case - lookup gave negative, but... we had foo/bar/
3491 * From the vfs_mknod() POV we just have a negative dentry -
3492 * all is fine. Let's be bastards - you had / on the end, you've
3493 * been asking for (non-existent) directory. -ENOENT for you.
3494 */
3495 if (unlikely(!is_dir && last.name[last.len])) {
3496 error = -ENOENT;
3497 goto fail;
3498 }
3499 if (unlikely(err2)) {
3500 error = err2;
3501 goto fail;
3502 }
3503 putname(name);
3504 return dentry;
3505 fail:
3506 dput(dentry);
3507 dentry = ERR_PTR(error);
3508 unlock:
3509 inode_unlock(path->dentry->d_inode);
3510 if (!err2)
3511 mnt_drop_write(path->mnt);
3512 out:
3513 path_put(path);
3514 putname(name);
3515 return dentry;
3516 }
3517
kern_path_create(int dfd,const char * pathname,struct path * path,unsigned int lookup_flags)3518 struct dentry *kern_path_create(int dfd, const char *pathname,
3519 struct path *path, unsigned int lookup_flags)
3520 {
3521 return filename_create(dfd, getname_kernel(pathname),
3522 path, lookup_flags);
3523 }
3524 EXPORT_SYMBOL(kern_path_create);
3525
done_path_create(struct path * path,struct dentry * dentry)3526 void done_path_create(struct path *path, struct dentry *dentry)
3527 {
3528 dput(dentry);
3529 inode_unlock(path->dentry->d_inode);
3530 mnt_drop_write(path->mnt);
3531 path_put(path);
3532 }
3533 EXPORT_SYMBOL(done_path_create);
3534
user_path_create(int dfd,const char __user * pathname,struct path * path,unsigned int lookup_flags)3535 inline struct dentry *user_path_create(int dfd, const char __user *pathname,
3536 struct path *path, unsigned int lookup_flags)
3537 {
3538 return filename_create(dfd, getname(pathname), path, lookup_flags);
3539 }
3540 EXPORT_SYMBOL(user_path_create);
3541
vfs_mknod(struct inode * dir,struct dentry * dentry,umode_t mode,dev_t dev)3542 int vfs_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
3543 {
3544 bool is_whiteout = S_ISCHR(mode) && dev == WHITEOUT_DEV;
3545 int error = may_create(dir, dentry);
3546
3547 if (error)
3548 return error;
3549
3550 if ((S_ISCHR(mode) || S_ISBLK(mode)) && !is_whiteout &&
3551 !capable(CAP_MKNOD))
3552 return -EPERM;
3553
3554 if (!dir->i_op->mknod)
3555 return -EPERM;
3556
3557 error = devcgroup_inode_mknod(mode, dev);
3558 if (error)
3559 return error;
3560
3561 error = security_inode_mknod(dir, dentry, mode, dev);
3562 if (error)
3563 return error;
3564
3565 error = dir->i_op->mknod(dir, dentry, mode, dev);
3566 if (!error)
3567 fsnotify_create(dir, dentry);
3568 return error;
3569 }
3570 EXPORT_SYMBOL(vfs_mknod);
3571
may_mknod(umode_t mode)3572 static int may_mknod(umode_t mode)
3573 {
3574 switch (mode & S_IFMT) {
3575 case S_IFREG:
3576 case S_IFCHR:
3577 case S_IFBLK:
3578 case S_IFIFO:
3579 case S_IFSOCK:
3580 case 0: /* zero mode translates to S_IFREG */
3581 return 0;
3582 case S_IFDIR:
3583 return -EPERM;
3584 default:
3585 return -EINVAL;
3586 }
3587 }
3588
do_mknodat(int dfd,const char __user * filename,umode_t mode,unsigned int dev)3589 static long do_mknodat(int dfd, const char __user *filename, umode_t mode,
3590 unsigned int dev)
3591 {
3592 struct dentry *dentry;
3593 struct path path;
3594 int error;
3595 unsigned int lookup_flags = 0;
3596
3597 error = may_mknod(mode);
3598 if (error)
3599 return error;
3600 retry:
3601 dentry = user_path_create(dfd, filename, &path, lookup_flags);
3602 if (IS_ERR(dentry))
3603 return PTR_ERR(dentry);
3604
3605 if (!IS_POSIXACL(path.dentry->d_inode))
3606 mode &= ~current_umask();
3607 error = security_path_mknod(&path, dentry, mode, dev);
3608 if (error)
3609 goto out;
3610 switch (mode & S_IFMT) {
3611 case 0: case S_IFREG:
3612 error = vfs_create(path.dentry->d_inode,dentry,mode,true);
3613 if (!error)
3614 ima_post_path_mknod(dentry);
3615 break;
3616 case S_IFCHR: case S_IFBLK:
3617 error = vfs_mknod(path.dentry->d_inode,dentry,mode,
3618 new_decode_dev(dev));
3619 break;
3620 case S_IFIFO: case S_IFSOCK:
3621 error = vfs_mknod(path.dentry->d_inode,dentry,mode,0);
3622 break;
3623 }
3624 out:
3625 done_path_create(&path, dentry);
3626 if (retry_estale(error, lookup_flags)) {
3627 lookup_flags |= LOOKUP_REVAL;
3628 goto retry;
3629 }
3630 return error;
3631 }
3632
SYSCALL_DEFINE4(mknodat,int,dfd,const char __user *,filename,umode_t,mode,unsigned int,dev)3633 SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, umode_t, mode,
3634 unsigned int, dev)
3635 {
3636 return do_mknodat(dfd, filename, mode, dev);
3637 }
3638
SYSCALL_DEFINE3(mknod,const char __user *,filename,umode_t,mode,unsigned,dev)3639 SYSCALL_DEFINE3(mknod, const char __user *, filename, umode_t, mode, unsigned, dev)
3640 {
3641 return do_mknodat(AT_FDCWD, filename, mode, dev);
3642 }
3643
vfs_mkdir(struct inode * dir,struct dentry * dentry,umode_t mode)3644 int vfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
3645 {
3646 int error = may_create(dir, dentry);
3647 unsigned max_links = dir->i_sb->s_max_links;
3648
3649 if (error)
3650 return error;
3651
3652 if (!dir->i_op->mkdir)
3653 return -EPERM;
3654
3655 mode &= (S_IRWXUGO|S_ISVTX);
3656 error = security_inode_mkdir(dir, dentry, mode);
3657 if (error)
3658 return error;
3659
3660 if (max_links && dir->i_nlink >= max_links)
3661 return -EMLINK;
3662
3663 error = dir->i_op->mkdir(dir, dentry, mode);
3664 if (!error)
3665 fsnotify_mkdir(dir, dentry);
3666 return error;
3667 }
3668 EXPORT_SYMBOL(vfs_mkdir);
3669
do_mkdirat(int dfd,const char __user * pathname,umode_t mode)3670 static long do_mkdirat(int dfd, const char __user *pathname, umode_t mode)
3671 {
3672 struct dentry *dentry;
3673 struct path path;
3674 int error;
3675 unsigned int lookup_flags = LOOKUP_DIRECTORY;
3676
3677 retry:
3678 dentry = user_path_create(dfd, pathname, &path, lookup_flags);
3679 if (IS_ERR(dentry))
3680 return PTR_ERR(dentry);
3681
3682 if (!IS_POSIXACL(path.dentry->d_inode))
3683 mode &= ~current_umask();
3684 error = security_path_mkdir(&path, dentry, mode);
3685 if (!error)
3686 error = vfs_mkdir(path.dentry->d_inode, dentry, mode);
3687 done_path_create(&path, dentry);
3688 if (retry_estale(error, lookup_flags)) {
3689 lookup_flags |= LOOKUP_REVAL;
3690 goto retry;
3691 }
3692 return error;
3693 }
3694
SYSCALL_DEFINE3(mkdirat,int,dfd,const char __user *,pathname,umode_t,mode)3695 SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, umode_t, mode)
3696 {
3697 return do_mkdirat(dfd, pathname, mode);
3698 }
3699
SYSCALL_DEFINE2(mkdir,const char __user *,pathname,umode_t,mode)3700 SYSCALL_DEFINE2(mkdir, const char __user *, pathname, umode_t, mode)
3701 {
3702 return do_mkdirat(AT_FDCWD, pathname, mode);
3703 }
3704
vfs_rmdir(struct inode * dir,struct dentry * dentry)3705 int vfs_rmdir(struct inode *dir, struct dentry *dentry)
3706 {
3707 int error = may_delete(dir, dentry, 1);
3708
3709 if (error)
3710 return error;
3711
3712 if (!dir->i_op->rmdir)
3713 return -EPERM;
3714
3715 dget(dentry);
3716 inode_lock(dentry->d_inode);
3717
3718 error = -EBUSY;
3719 if (is_local_mountpoint(dentry))
3720 goto out;
3721
3722 error = security_inode_rmdir(dir, dentry);
3723 if (error)
3724 goto out;
3725
3726 error = dir->i_op->rmdir(dir, dentry);
3727 if (error)
3728 goto out;
3729
3730 shrink_dcache_parent(dentry);
3731 dentry->d_inode->i_flags |= S_DEAD;
3732 dont_mount(dentry);
3733 detach_mounts(dentry);
3734
3735 out:
3736 inode_unlock(dentry->d_inode);
3737 dput(dentry);
3738 if (!error)
3739 d_delete_notify(dir, dentry);
3740 return error;
3741 }
3742 EXPORT_SYMBOL(vfs_rmdir);
3743
do_rmdir(int dfd,struct filename * name)3744 long do_rmdir(int dfd, struct filename *name)
3745 {
3746 int error = 0;
3747 struct dentry *dentry;
3748 struct path path;
3749 struct qstr last;
3750 int type;
3751 unsigned int lookup_flags = 0;
3752 retry:
3753 name = filename_parentat(dfd, name, lookup_flags,
3754 &path, &last, &type);
3755 if (IS_ERR(name))
3756 return PTR_ERR(name);
3757
3758 switch (type) {
3759 case LAST_DOTDOT:
3760 error = -ENOTEMPTY;
3761 goto exit1;
3762 case LAST_DOT:
3763 error = -EINVAL;
3764 goto exit1;
3765 case LAST_ROOT:
3766 error = -EBUSY;
3767 goto exit1;
3768 }
3769
3770 error = mnt_want_write(path.mnt);
3771 if (error)
3772 goto exit1;
3773
3774 inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
3775 dentry = __lookup_hash(&last, path.dentry, lookup_flags);
3776 error = PTR_ERR(dentry);
3777 if (IS_ERR(dentry))
3778 goto exit2;
3779 if (!dentry->d_inode) {
3780 error = -ENOENT;
3781 goto exit3;
3782 }
3783 error = security_path_rmdir(&path, dentry);
3784 if (error)
3785 goto exit3;
3786 error = vfs_rmdir(path.dentry->d_inode, dentry);
3787 exit3:
3788 dput(dentry);
3789 exit2:
3790 inode_unlock(path.dentry->d_inode);
3791 mnt_drop_write(path.mnt);
3792 exit1:
3793 path_put(&path);
3794 if (retry_estale(error, lookup_flags)) {
3795 lookup_flags |= LOOKUP_REVAL;
3796 goto retry;
3797 }
3798 putname(name);
3799 return error;
3800 }
3801
SYSCALL_DEFINE1(rmdir,const char __user *,pathname)3802 SYSCALL_DEFINE1(rmdir, const char __user *, pathname)
3803 {
3804 return do_rmdir(AT_FDCWD, getname(pathname));
3805 }
3806
3807 /**
3808 * vfs_unlink - unlink a filesystem object
3809 * @dir: parent directory
3810 * @dentry: victim
3811 * @delegated_inode: returns victim inode, if the inode is delegated.
3812 *
3813 * The caller must hold dir->i_mutex.
3814 *
3815 * If vfs_unlink discovers a delegation, it will return -EWOULDBLOCK and
3816 * return a reference to the inode in delegated_inode. The caller
3817 * should then break the delegation on that inode and retry. Because
3818 * breaking a delegation may take a long time, the caller should drop
3819 * dir->i_mutex before doing so.
3820 *
3821 * Alternatively, a caller may pass NULL for delegated_inode. This may
3822 * be appropriate for callers that expect the underlying filesystem not
3823 * to be NFS exported.
3824 */
vfs_unlink(struct inode * dir,struct dentry * dentry,struct inode ** delegated_inode)3825 int vfs_unlink(struct inode *dir, struct dentry *dentry, struct inode **delegated_inode)
3826 {
3827 struct inode *target = dentry->d_inode;
3828 int error = may_delete(dir, dentry, 0);
3829
3830 if (error)
3831 return error;
3832
3833 if (!dir->i_op->unlink)
3834 return -EPERM;
3835
3836 inode_lock(target);
3837 if (is_local_mountpoint(dentry))
3838 error = -EBUSY;
3839 else {
3840 error = security_inode_unlink(dir, dentry);
3841 if (!error) {
3842 error = try_break_deleg(target, delegated_inode);
3843 if (error)
3844 goto out;
3845 error = dir->i_op->unlink(dir, dentry);
3846 if (!error) {
3847 dont_mount(dentry);
3848 detach_mounts(dentry);
3849 }
3850 }
3851 }
3852 out:
3853 inode_unlock(target);
3854
3855 /* We don't d_delete() NFS sillyrenamed files--they still exist. */
3856 if (!error && dentry->d_flags & DCACHE_NFSFS_RENAMED) {
3857 fsnotify_unlink(dir, dentry);
3858 } else if (!error) {
3859 fsnotify_link_count(target);
3860 d_delete_notify(dir, dentry);
3861 }
3862
3863 return error;
3864 }
3865 EXPORT_SYMBOL(vfs_unlink);
3866
3867 /*
3868 * Make sure that the actual truncation of the file will occur outside its
3869 * directory's i_mutex. Truncate can take a long time if there is a lot of
3870 * writeout happening, and we don't want to prevent access to the directory
3871 * while waiting on the I/O.
3872 */
do_unlinkat(int dfd,struct filename * name)3873 long do_unlinkat(int dfd, struct filename *name)
3874 {
3875 int error;
3876 struct dentry *dentry;
3877 struct path path;
3878 struct qstr last;
3879 int type;
3880 struct inode *inode = NULL;
3881 struct inode *delegated_inode = NULL;
3882 unsigned int lookup_flags = 0;
3883 retry:
3884 name = filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
3885 if (IS_ERR(name))
3886 return PTR_ERR(name);
3887
3888 error = -EISDIR;
3889 if (type != LAST_NORM)
3890 goto exit1;
3891
3892 error = mnt_want_write(path.mnt);
3893 if (error)
3894 goto exit1;
3895 retry_deleg:
3896 inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
3897 dentry = __lookup_hash(&last, path.dentry, lookup_flags);
3898 error = PTR_ERR(dentry);
3899 if (!IS_ERR(dentry)) {
3900 /* Why not before? Because we want correct error value */
3901 if (last.name[last.len])
3902 goto slashes;
3903 inode = dentry->d_inode;
3904 if (d_is_negative(dentry))
3905 goto slashes;
3906 ihold(inode);
3907 error = security_path_unlink(&path, dentry);
3908 if (error)
3909 goto exit2;
3910 error = vfs_unlink(path.dentry->d_inode, dentry, &delegated_inode);
3911 exit2:
3912 dput(dentry);
3913 }
3914 inode_unlock(path.dentry->d_inode);
3915 if (inode)
3916 iput(inode); /* truncate the inode here */
3917 inode = NULL;
3918 if (delegated_inode) {
3919 error = break_deleg_wait(&delegated_inode);
3920 if (!error)
3921 goto retry_deleg;
3922 }
3923 mnt_drop_write(path.mnt);
3924 exit1:
3925 path_put(&path);
3926 if (retry_estale(error, lookup_flags)) {
3927 lookup_flags |= LOOKUP_REVAL;
3928 inode = NULL;
3929 goto retry;
3930 }
3931 putname(name);
3932 return error;
3933
3934 slashes:
3935 if (d_is_negative(dentry))
3936 error = -ENOENT;
3937 else if (d_is_dir(dentry))
3938 error = -EISDIR;
3939 else
3940 error = -ENOTDIR;
3941 goto exit2;
3942 }
3943
SYSCALL_DEFINE3(unlinkat,int,dfd,const char __user *,pathname,int,flag)3944 SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag)
3945 {
3946 if ((flag & ~AT_REMOVEDIR) != 0)
3947 return -EINVAL;
3948
3949 if (flag & AT_REMOVEDIR)
3950 return do_rmdir(dfd, getname(pathname));
3951 return do_unlinkat(dfd, getname(pathname));
3952 }
3953
SYSCALL_DEFINE1(unlink,const char __user *,pathname)3954 SYSCALL_DEFINE1(unlink, const char __user *, pathname)
3955 {
3956 return do_unlinkat(AT_FDCWD, getname(pathname));
3957 }
3958
vfs_symlink(struct inode * dir,struct dentry * dentry,const char * oldname)3959 int vfs_symlink(struct inode *dir, struct dentry *dentry, const char *oldname)
3960 {
3961 int error = may_create(dir, dentry);
3962
3963 if (error)
3964 return error;
3965
3966 if (!dir->i_op->symlink)
3967 return -EPERM;
3968
3969 error = security_inode_symlink(dir, dentry, oldname);
3970 if (error)
3971 return error;
3972
3973 error = dir->i_op->symlink(dir, dentry, oldname);
3974 if (!error)
3975 fsnotify_create(dir, dentry);
3976 return error;
3977 }
3978 EXPORT_SYMBOL(vfs_symlink);
3979
do_symlinkat(const char __user * oldname,int newdfd,const char __user * newname)3980 static long do_symlinkat(const char __user *oldname, int newdfd,
3981 const char __user *newname)
3982 {
3983 int error;
3984 struct filename *from;
3985 struct dentry *dentry;
3986 struct path path;
3987 unsigned int lookup_flags = 0;
3988
3989 from = getname(oldname);
3990 if (IS_ERR(from))
3991 return PTR_ERR(from);
3992 retry:
3993 dentry = user_path_create(newdfd, newname, &path, lookup_flags);
3994 error = PTR_ERR(dentry);
3995 if (IS_ERR(dentry))
3996 goto out_putname;
3997
3998 error = security_path_symlink(&path, dentry, from->name);
3999 if (!error)
4000 error = vfs_symlink(path.dentry->d_inode, dentry, from->name);
4001 done_path_create(&path, dentry);
4002 if (retry_estale(error, lookup_flags)) {
4003 lookup_flags |= LOOKUP_REVAL;
4004 goto retry;
4005 }
4006 out_putname:
4007 putname(from);
4008 return error;
4009 }
4010
SYSCALL_DEFINE3(symlinkat,const char __user *,oldname,int,newdfd,const char __user *,newname)4011 SYSCALL_DEFINE3(symlinkat, const char __user *, oldname,
4012 int, newdfd, const char __user *, newname)
4013 {
4014 return do_symlinkat(oldname, newdfd, newname);
4015 }
4016
SYSCALL_DEFINE2(symlink,const char __user *,oldname,const char __user *,newname)4017 SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname)
4018 {
4019 return do_symlinkat(oldname, AT_FDCWD, newname);
4020 }
4021
4022 /**
4023 * vfs_link - create a new link
4024 * @old_dentry: object to be linked
4025 * @dir: new parent
4026 * @new_dentry: where to create the new link
4027 * @delegated_inode: returns inode needing a delegation break
4028 *
4029 * The caller must hold dir->i_mutex
4030 *
4031 * If vfs_link discovers a delegation on the to-be-linked file in need
4032 * of breaking, it will return -EWOULDBLOCK and return a reference to the
4033 * inode in delegated_inode. The caller should then break the delegation
4034 * and retry. Because breaking a delegation may take a long time, the
4035 * caller should drop the i_mutex before doing so.
4036 *
4037 * Alternatively, a caller may pass NULL for delegated_inode. This may
4038 * be appropriate for callers that expect the underlying filesystem not
4039 * to be NFS exported.
4040 */
vfs_link(struct dentry * old_dentry,struct inode * dir,struct dentry * new_dentry,struct inode ** delegated_inode)4041 int vfs_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry, struct inode **delegated_inode)
4042 {
4043 struct inode *inode = old_dentry->d_inode;
4044 unsigned max_links = dir->i_sb->s_max_links;
4045 int error;
4046
4047 if (!inode)
4048 return -ENOENT;
4049
4050 error = may_create(dir, new_dentry);
4051 if (error)
4052 return error;
4053
4054 if (dir->i_sb != inode->i_sb)
4055 return -EXDEV;
4056
4057 /*
4058 * A link to an append-only or immutable file cannot be created.
4059 */
4060 if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
4061 return -EPERM;
4062 /*
4063 * Updating the link count will likely cause i_uid and i_gid to
4064 * be writen back improperly if their true value is unknown to
4065 * the vfs.
4066 */
4067 if (HAS_UNMAPPED_ID(inode))
4068 return -EPERM;
4069 if (!dir->i_op->link)
4070 return -EPERM;
4071 if (S_ISDIR(inode->i_mode))
4072 return -EPERM;
4073
4074 error = security_inode_link(old_dentry, dir, new_dentry);
4075 if (error)
4076 return error;
4077
4078 inode_lock(inode);
4079 /* Make sure we don't allow creating hardlink to an unlinked file */
4080 if (inode->i_nlink == 0 && !(inode->i_state & I_LINKABLE))
4081 error = -ENOENT;
4082 else if (max_links && inode->i_nlink >= max_links)
4083 error = -EMLINK;
4084 else {
4085 error = try_break_deleg(inode, delegated_inode);
4086 if (!error)
4087 error = dir->i_op->link(old_dentry, dir, new_dentry);
4088 }
4089
4090 if (!error && (inode->i_state & I_LINKABLE)) {
4091 spin_lock(&inode->i_lock);
4092 inode->i_state &= ~I_LINKABLE;
4093 spin_unlock(&inode->i_lock);
4094 }
4095 inode_unlock(inode);
4096 if (!error)
4097 fsnotify_link(dir, inode, new_dentry);
4098 return error;
4099 }
4100 EXPORT_SYMBOL(vfs_link);
4101
4102 /*
4103 * Hardlinks are often used in delicate situations. We avoid
4104 * security-related surprises by not following symlinks on the
4105 * newname. --KAB
4106 *
4107 * We don't follow them on the oldname either to be compatible
4108 * with linux 2.0, and to avoid hard-linking to directories
4109 * and other special files. --ADM
4110 */
do_linkat(int olddfd,const char __user * oldname,int newdfd,const char __user * newname,int flags)4111 static int do_linkat(int olddfd, const char __user *oldname, int newdfd,
4112 const char __user *newname, int flags)
4113 {
4114 struct dentry *new_dentry;
4115 struct path old_path, new_path;
4116 struct inode *delegated_inode = NULL;
4117 int how = 0;
4118 int error;
4119
4120 if ((flags & ~(AT_SYMLINK_FOLLOW | AT_EMPTY_PATH)) != 0)
4121 return -EINVAL;
4122 /*
4123 * To use null names we require CAP_DAC_READ_SEARCH
4124 * This ensures that not everyone will be able to create
4125 * handlink using the passed filedescriptor.
4126 */
4127 if (flags & AT_EMPTY_PATH) {
4128 if (!capable(CAP_DAC_READ_SEARCH))
4129 return -ENOENT;
4130 how = LOOKUP_EMPTY;
4131 }
4132
4133 if (flags & AT_SYMLINK_FOLLOW)
4134 how |= LOOKUP_FOLLOW;
4135 retry:
4136 error = user_path_at(olddfd, oldname, how, &old_path);
4137 if (error)
4138 return error;
4139
4140 new_dentry = user_path_create(newdfd, newname, &new_path,
4141 (how & LOOKUP_REVAL));
4142 error = PTR_ERR(new_dentry);
4143 if (IS_ERR(new_dentry))
4144 goto out;
4145
4146 error = -EXDEV;
4147 if (old_path.mnt != new_path.mnt)
4148 goto out_dput;
4149 error = may_linkat(&old_path);
4150 if (unlikely(error))
4151 goto out_dput;
4152 error = security_path_link(old_path.dentry, &new_path, new_dentry);
4153 if (error)
4154 goto out_dput;
4155 error = vfs_link(old_path.dentry, new_path.dentry->d_inode, new_dentry, &delegated_inode);
4156 out_dput:
4157 done_path_create(&new_path, new_dentry);
4158 if (delegated_inode) {
4159 error = break_deleg_wait(&delegated_inode);
4160 if (!error) {
4161 path_put(&old_path);
4162 goto retry;
4163 }
4164 }
4165 if (retry_estale(error, how)) {
4166 path_put(&old_path);
4167 how |= LOOKUP_REVAL;
4168 goto retry;
4169 }
4170 out:
4171 path_put(&old_path);
4172
4173 return error;
4174 }
4175
SYSCALL_DEFINE5(linkat,int,olddfd,const char __user *,oldname,int,newdfd,const char __user *,newname,int,flags)4176 SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname,
4177 int, newdfd, const char __user *, newname, int, flags)
4178 {
4179 return do_linkat(olddfd, oldname, newdfd, newname, flags);
4180 }
4181
SYSCALL_DEFINE2(link,const char __user *,oldname,const char __user *,newname)4182 SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname)
4183 {
4184 return do_linkat(AT_FDCWD, oldname, AT_FDCWD, newname, 0);
4185 }
4186
4187 /**
4188 * vfs_rename - rename a filesystem object
4189 * @old_dir: parent of source
4190 * @old_dentry: source
4191 * @new_dir: parent of destination
4192 * @new_dentry: destination
4193 * @delegated_inode: returns an inode needing a delegation break
4194 * @flags: rename flags
4195 *
4196 * The caller must hold multiple mutexes--see lock_rename()).
4197 *
4198 * If vfs_rename discovers a delegation in need of breaking at either
4199 * the source or destination, it will return -EWOULDBLOCK and return a
4200 * reference to the inode in delegated_inode. The caller should then
4201 * break the delegation and retry. Because breaking a delegation may
4202 * take a long time, the caller should drop all locks before doing
4203 * so.
4204 *
4205 * Alternatively, a caller may pass NULL for delegated_inode. This may
4206 * be appropriate for callers that expect the underlying filesystem not
4207 * to be NFS exported.
4208 *
4209 * The worst of all namespace operations - renaming directory. "Perverted"
4210 * doesn't even start to describe it. Somebody in UCB had a heck of a trip...
4211 * Problems:
4212 *
4213 * a) we can get into loop creation.
4214 * b) race potential - two innocent renames can create a loop together.
4215 * That's where 4.4 screws up. Current fix: serialization on
4216 * sb->s_vfs_rename_mutex. We might be more accurate, but that's another
4217 * story.
4218 * c) we have to lock _four_ objects - parents and victim (if it exists),
4219 * and source (if it is not a directory).
4220 * And that - after we got ->i_mutex on parents (until then we don't know
4221 * whether the target exists). Solution: try to be smart with locking
4222 * order for inodes. We rely on the fact that tree topology may change
4223 * only under ->s_vfs_rename_mutex _and_ that parent of the object we
4224 * move will be locked. Thus we can rank directories by the tree
4225 * (ancestors first) and rank all non-directories after them.
4226 * That works since everybody except rename does "lock parent, lookup,
4227 * lock child" and rename is under ->s_vfs_rename_mutex.
4228 * HOWEVER, it relies on the assumption that any object with ->lookup()
4229 * has no more than 1 dentry. If "hybrid" objects will ever appear,
4230 * we'd better make sure that there's no link(2) for them.
4231 * d) conversion from fhandle to dentry may come in the wrong moment - when
4232 * we are removing the target. Solution: we will have to grab ->i_mutex
4233 * in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on
4234 * ->i_mutex on parents, which works but leads to some truly excessive
4235 * locking].
4236 */
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)4237 int vfs_rename(struct inode *old_dir, struct dentry *old_dentry,
4238 struct inode *new_dir, struct dentry *new_dentry,
4239 struct inode **delegated_inode, unsigned int flags)
4240 {
4241 int error;
4242 bool is_dir = d_is_dir(old_dentry);
4243 struct inode *source = old_dentry->d_inode;
4244 struct inode *target = new_dentry->d_inode;
4245 bool new_is_dir = false;
4246 unsigned max_links = new_dir->i_sb->s_max_links;
4247 struct name_snapshot old_name;
4248
4249 if (source == target)
4250 return 0;
4251
4252 error = may_delete(old_dir, old_dentry, is_dir);
4253 if (error)
4254 return error;
4255
4256 if (!target) {
4257 error = may_create(new_dir, new_dentry);
4258 } else {
4259 new_is_dir = d_is_dir(new_dentry);
4260
4261 if (!(flags & RENAME_EXCHANGE))
4262 error = may_delete(new_dir, new_dentry, is_dir);
4263 else
4264 error = may_delete(new_dir, new_dentry, new_is_dir);
4265 }
4266 if (error)
4267 return error;
4268
4269 if (!old_dir->i_op->rename)
4270 return -EPERM;
4271
4272 /*
4273 * If we are going to change the parent - check write permissions,
4274 * we'll need to flip '..'.
4275 */
4276 if (new_dir != old_dir) {
4277 if (is_dir) {
4278 error = inode_permission(source, MAY_WRITE);
4279 if (error)
4280 return error;
4281 }
4282 if ((flags & RENAME_EXCHANGE) && new_is_dir) {
4283 error = inode_permission(target, MAY_WRITE);
4284 if (error)
4285 return error;
4286 }
4287 }
4288
4289 error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,
4290 flags);
4291 if (error)
4292 return error;
4293
4294 take_dentry_name_snapshot(&old_name, old_dentry);
4295 dget(new_dentry);
4296 if (!is_dir || (flags & RENAME_EXCHANGE))
4297 lock_two_nondirectories(source, target);
4298 else if (target)
4299 inode_lock(target);
4300
4301 error = -EBUSY;
4302 if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
4303 goto out;
4304
4305 if (max_links && new_dir != old_dir) {
4306 error = -EMLINK;
4307 if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)
4308 goto out;
4309 if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&
4310 old_dir->i_nlink >= max_links)
4311 goto out;
4312 }
4313 if (!is_dir) {
4314 error = try_break_deleg(source, delegated_inode);
4315 if (error)
4316 goto out;
4317 }
4318 if (target && !new_is_dir) {
4319 error = try_break_deleg(target, delegated_inode);
4320 if (error)
4321 goto out;
4322 }
4323 error = old_dir->i_op->rename(old_dir, old_dentry,
4324 new_dir, new_dentry, flags);
4325 if (error)
4326 goto out;
4327
4328 if (!(flags & RENAME_EXCHANGE) && target) {
4329 if (is_dir) {
4330 shrink_dcache_parent(new_dentry);
4331 target->i_flags |= S_DEAD;
4332 }
4333 dont_mount(new_dentry);
4334 detach_mounts(new_dentry);
4335 }
4336 if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {
4337 if (!(flags & RENAME_EXCHANGE))
4338 d_move(old_dentry, new_dentry);
4339 else
4340 d_exchange(old_dentry, new_dentry);
4341 }
4342 out:
4343 if (!is_dir || (flags & RENAME_EXCHANGE))
4344 unlock_two_nondirectories(source, target);
4345 else if (target)
4346 inode_unlock(target);
4347 dput(new_dentry);
4348 if (!error) {
4349 fsnotify_move(old_dir, new_dir, &old_name.name, is_dir,
4350 !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);
4351 if (flags & RENAME_EXCHANGE) {
4352 fsnotify_move(new_dir, old_dir, &old_dentry->d_name,
4353 new_is_dir, NULL, new_dentry);
4354 }
4355 }
4356 release_dentry_name_snapshot(&old_name);
4357
4358 return error;
4359 }
4360 EXPORT_SYMBOL(vfs_rename);
4361
do_renameat2(int olddfd,struct filename * from,int newdfd,struct filename * to,unsigned int flags)4362 int do_renameat2(int olddfd, struct filename *from, int newdfd,
4363 struct filename *to, unsigned int flags)
4364 {
4365 struct dentry *old_dentry, *new_dentry;
4366 struct dentry *trap;
4367 struct path old_path, new_path;
4368 struct qstr old_last, new_last;
4369 int old_type, new_type;
4370 struct inode *delegated_inode = NULL;
4371 unsigned int lookup_flags = 0, target_flags = LOOKUP_RENAME_TARGET;
4372 bool should_retry = false;
4373 int error = -EINVAL;
4374
4375 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
4376 goto put_both;
4377
4378 if ((flags & (RENAME_NOREPLACE | RENAME_WHITEOUT)) &&
4379 (flags & RENAME_EXCHANGE))
4380 goto put_both;
4381
4382 if (flags & RENAME_EXCHANGE)
4383 target_flags = 0;
4384
4385 retry:
4386 from = filename_parentat(olddfd, from, lookup_flags, &old_path,
4387 &old_last, &old_type);
4388 if (IS_ERR(from)) {
4389 error = PTR_ERR(from);
4390 goto put_new;
4391 }
4392
4393 to = filename_parentat(newdfd, to, lookup_flags, &new_path, &new_last,
4394 &new_type);
4395 if (IS_ERR(to)) {
4396 error = PTR_ERR(to);
4397 goto exit1;
4398 }
4399
4400 error = -EXDEV;
4401 if (old_path.mnt != new_path.mnt)
4402 goto exit2;
4403
4404 error = -EBUSY;
4405 if (old_type != LAST_NORM)
4406 goto exit2;
4407
4408 if (flags & RENAME_NOREPLACE)
4409 error = -EEXIST;
4410 if (new_type != LAST_NORM)
4411 goto exit2;
4412
4413 error = mnt_want_write(old_path.mnt);
4414 if (error)
4415 goto exit2;
4416
4417 retry_deleg:
4418 trap = lock_rename(new_path.dentry, old_path.dentry);
4419
4420 old_dentry = __lookup_hash(&old_last, old_path.dentry, lookup_flags);
4421 error = PTR_ERR(old_dentry);
4422 if (IS_ERR(old_dentry))
4423 goto exit3;
4424 /* source must exist */
4425 error = -ENOENT;
4426 if (d_is_negative(old_dentry))
4427 goto exit4;
4428 new_dentry = __lookup_hash(&new_last, new_path.dentry, lookup_flags | target_flags);
4429 error = PTR_ERR(new_dentry);
4430 if (IS_ERR(new_dentry))
4431 goto exit4;
4432 error = -EEXIST;
4433 if ((flags & RENAME_NOREPLACE) && d_is_positive(new_dentry))
4434 goto exit5;
4435 if (flags & RENAME_EXCHANGE) {
4436 error = -ENOENT;
4437 if (d_is_negative(new_dentry))
4438 goto exit5;
4439
4440 if (!d_is_dir(new_dentry)) {
4441 error = -ENOTDIR;
4442 if (new_last.name[new_last.len])
4443 goto exit5;
4444 }
4445 }
4446 /* unless the source is a directory trailing slashes give -ENOTDIR */
4447 if (!d_is_dir(old_dentry)) {
4448 error = -ENOTDIR;
4449 if (old_last.name[old_last.len])
4450 goto exit5;
4451 if (!(flags & RENAME_EXCHANGE) && new_last.name[new_last.len])
4452 goto exit5;
4453 }
4454 /* source should not be ancestor of target */
4455 error = -EINVAL;
4456 if (old_dentry == trap)
4457 goto exit5;
4458 /* target should not be an ancestor of source */
4459 if (!(flags & RENAME_EXCHANGE))
4460 error = -ENOTEMPTY;
4461 if (new_dentry == trap)
4462 goto exit5;
4463
4464 error = security_path_rename(&old_path, old_dentry,
4465 &new_path, new_dentry, flags);
4466 if (error)
4467 goto exit5;
4468 error = vfs_rename(old_path.dentry->d_inode, old_dentry,
4469 new_path.dentry->d_inode, new_dentry,
4470 &delegated_inode, flags);
4471 exit5:
4472 dput(new_dentry);
4473 exit4:
4474 dput(old_dentry);
4475 exit3:
4476 unlock_rename(new_path.dentry, old_path.dentry);
4477 if (delegated_inode) {
4478 error = break_deleg_wait(&delegated_inode);
4479 if (!error)
4480 goto retry_deleg;
4481 }
4482 mnt_drop_write(old_path.mnt);
4483 exit2:
4484 if (retry_estale(error, lookup_flags))
4485 should_retry = true;
4486 path_put(&new_path);
4487 exit1:
4488 path_put(&old_path);
4489 if (should_retry) {
4490 should_retry = false;
4491 lookup_flags |= LOOKUP_REVAL;
4492 goto retry;
4493 }
4494 put_both:
4495 if (!IS_ERR(from))
4496 putname(from);
4497 put_new:
4498 if (!IS_ERR(to))
4499 putname(to);
4500 return error;
4501 }
4502
SYSCALL_DEFINE5(renameat2,int,olddfd,const char __user *,oldname,int,newdfd,const char __user *,newname,unsigned int,flags)4503 SYSCALL_DEFINE5(renameat2, int, olddfd, const char __user *, oldname,
4504 int, newdfd, const char __user *, newname, unsigned int, flags)
4505 {
4506 return do_renameat2(olddfd, getname(oldname), newdfd, getname(newname),
4507 flags);
4508 }
4509
SYSCALL_DEFINE4(renameat,int,olddfd,const char __user *,oldname,int,newdfd,const char __user *,newname)4510 SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname,
4511 int, newdfd, const char __user *, newname)
4512 {
4513 return do_renameat2(olddfd, getname(oldname), newdfd, getname(newname),
4514 0);
4515 }
4516
SYSCALL_DEFINE2(rename,const char __user *,oldname,const char __user *,newname)4517 SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname)
4518 {
4519 return do_renameat2(AT_FDCWD, getname(oldname), AT_FDCWD,
4520 getname(newname), 0);
4521 }
4522
readlink_copy(char __user * buffer,int buflen,const char * link)4523 int readlink_copy(char __user *buffer, int buflen, const char *link)
4524 {
4525 int len = PTR_ERR(link);
4526 if (IS_ERR(link))
4527 goto out;
4528
4529 len = strlen(link);
4530 if (len > (unsigned) buflen)
4531 len = buflen;
4532 if (copy_to_user(buffer, link, len))
4533 len = -EFAULT;
4534 out:
4535 return len;
4536 }
4537
4538 /**
4539 * vfs_readlink - copy symlink body into userspace buffer
4540 * @dentry: dentry on which to get symbolic link
4541 * @buffer: user memory pointer
4542 * @buflen: size of buffer
4543 *
4544 * Does not touch atime. That's up to the caller if necessary
4545 *
4546 * Does not call security hook.
4547 */
vfs_readlink(struct dentry * dentry,char __user * buffer,int buflen)4548 int vfs_readlink(struct dentry *dentry, char __user *buffer, int buflen)
4549 {
4550 struct inode *inode = d_inode(dentry);
4551 DEFINE_DELAYED_CALL(done);
4552 const char *link;
4553 int res;
4554
4555 if (unlikely(!(inode->i_opflags & IOP_DEFAULT_READLINK))) {
4556 if (unlikely(inode->i_op->readlink))
4557 return inode->i_op->readlink(dentry, buffer, buflen);
4558
4559 if (!d_is_symlink(dentry))
4560 return -EINVAL;
4561
4562 spin_lock(&inode->i_lock);
4563 inode->i_opflags |= IOP_DEFAULT_READLINK;
4564 spin_unlock(&inode->i_lock);
4565 }
4566
4567 link = READ_ONCE(inode->i_link);
4568 if (!link) {
4569 link = inode->i_op->get_link(dentry, inode, &done);
4570 if (IS_ERR(link))
4571 return PTR_ERR(link);
4572 }
4573 res = readlink_copy(buffer, buflen, link);
4574 do_delayed_call(&done);
4575 return res;
4576 }
4577 EXPORT_SYMBOL(vfs_readlink);
4578
4579 /**
4580 * vfs_get_link - get symlink body
4581 * @dentry: dentry on which to get symbolic link
4582 * @done: caller needs to free returned data with this
4583 *
4584 * Calls security hook and i_op->get_link() on the supplied inode.
4585 *
4586 * It does not touch atime. That's up to the caller if necessary.
4587 *
4588 * Does not work on "special" symlinks like /proc/$$/fd/N
4589 */
vfs_get_link(struct dentry * dentry,struct delayed_call * done)4590 const char *vfs_get_link(struct dentry *dentry, struct delayed_call *done)
4591 {
4592 const char *res = ERR_PTR(-EINVAL);
4593 struct inode *inode = d_inode(dentry);
4594
4595 if (d_is_symlink(dentry)) {
4596 res = ERR_PTR(security_inode_readlink(dentry));
4597 if (!res)
4598 res = inode->i_op->get_link(dentry, inode, done);
4599 }
4600 return res;
4601 }
4602 EXPORT_SYMBOL(vfs_get_link);
4603
4604 /* get the link contents into pagecache */
page_get_link(struct dentry * dentry,struct inode * inode,struct delayed_call * callback)4605 const char *page_get_link(struct dentry *dentry, struct inode *inode,
4606 struct delayed_call *callback)
4607 {
4608 char *kaddr;
4609 struct page *page;
4610 struct address_space *mapping = inode->i_mapping;
4611
4612 if (!dentry) {
4613 page = find_get_page(mapping, 0);
4614 if (!page)
4615 return ERR_PTR(-ECHILD);
4616 if (!PageUptodate(page)) {
4617 put_page(page);
4618 return ERR_PTR(-ECHILD);
4619 }
4620 } else {
4621 page = read_mapping_page(mapping, 0, NULL);
4622 if (IS_ERR(page))
4623 return (char*)page;
4624 }
4625 set_delayed_call(callback, page_put_link, page);
4626 BUG_ON(mapping_gfp_mask(mapping) & __GFP_HIGHMEM);
4627 kaddr = page_address(page);
4628 nd_terminate_link(kaddr, inode->i_size, PAGE_SIZE - 1);
4629 return kaddr;
4630 }
4631
4632 EXPORT_SYMBOL(page_get_link);
4633
page_put_link(void * arg)4634 void page_put_link(void *arg)
4635 {
4636 put_page(arg);
4637 }
4638 EXPORT_SYMBOL(page_put_link);
4639
page_readlink(struct dentry * dentry,char __user * buffer,int buflen)4640 int page_readlink(struct dentry *dentry, char __user *buffer, int buflen)
4641 {
4642 DEFINE_DELAYED_CALL(done);
4643 int res = readlink_copy(buffer, buflen,
4644 page_get_link(dentry, d_inode(dentry),
4645 &done));
4646 do_delayed_call(&done);
4647 return res;
4648 }
4649 EXPORT_SYMBOL(page_readlink);
4650
4651 /*
4652 * The nofs argument instructs pagecache_write_begin to pass AOP_FLAG_NOFS
4653 */
__page_symlink(struct inode * inode,const char * symname,int len,int nofs)4654 int __page_symlink(struct inode *inode, const char *symname, int len, int nofs)
4655 {
4656 struct address_space *mapping = inode->i_mapping;
4657 struct page *page;
4658 void *fsdata = NULL;
4659 int err;
4660 unsigned int flags = 0;
4661 if (nofs)
4662 flags |= AOP_FLAG_NOFS;
4663
4664 retry:
4665 err = pagecache_write_begin(NULL, mapping, 0, len-1,
4666 flags, &page, &fsdata);
4667 if (err)
4668 goto fail;
4669
4670 memcpy(page_address(page), symname, len-1);
4671
4672 err = pagecache_write_end(NULL, mapping, 0, len-1, len-1,
4673 page, fsdata);
4674 if (err < 0)
4675 goto fail;
4676 if (err < len-1)
4677 goto retry;
4678
4679 mark_inode_dirty(inode);
4680 return 0;
4681 fail:
4682 return err;
4683 }
4684 EXPORT_SYMBOL(__page_symlink);
4685
page_symlink(struct inode * inode,const char * symname,int len)4686 int page_symlink(struct inode *inode, const char *symname, int len)
4687 {
4688 return __page_symlink(inode, symname, len,
4689 !mapping_gfp_constraint(inode->i_mapping, __GFP_FS));
4690 }
4691 EXPORT_SYMBOL(page_symlink);
4692
4693 const struct inode_operations page_symlink_inode_operations = {
4694 .get_link = page_get_link,
4695 };
4696 EXPORT_SYMBOL(page_symlink_inode_operations);
4697