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