]> git.ipfire.org Git - people/ms/linux.git/blame - fs/namei.c
fs: move S_ISGID stripping into the vfs_*() helpers
[people/ms/linux.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;
84a2bd39
AV
821 if (unlikely(read_seqcount_retry(&dentry->d_seq, seq)))
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;
965 if (unlikely(read_seqcount_retry(&d->d_seq, nd->seq)))
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;
1508 continue;
1509 }
1510 if (read_seqretry(&mount_lock, nd->m_seq))
1511 return false;
1512 }
1513 return !(flags & DCACHE_NEED_AUTOMOUNT);
9875cf80 1514 }
287548e4
AV
1515}
1516
db3c9ade
AV
1517static inline int handle_mounts(struct nameidata *nd, struct dentry *dentry,
1518 struct path *path, struct inode **inode,
1519 unsigned int *seqp)
bd7c4b50 1520{
9deed3eb 1521 bool jumped;
db3c9ade 1522 int ret;
bd7c4b50 1523
db3c9ade
AV
1524 path->mnt = nd->path.mnt;
1525 path->dentry = dentry;
c153007b
AV
1526 if (nd->flags & LOOKUP_RCU) {
1527 unsigned int seq = *seqp;
1528 if (unlikely(!*inode))
1529 return -ENOENT;
1530 if (likely(__follow_mount_rcu(nd, path, inode, seqp)))
9deed3eb 1531 return 0;
ae66db45 1532 if (!try_to_unlazy_next(nd, dentry, seq))
c153007b
AV
1533 return -ECHILD;
1534 // *path might've been clobbered by __follow_mount_rcu()
1535 path->mnt = nd->path.mnt;
1536 path->dentry = dentry;
1537 }
9deed3eb
AV
1538 ret = traverse_mounts(path, &jumped, &nd->total_link_count, nd->flags);
1539 if (jumped) {
1540 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1541 ret = -EXDEV;
1542 else
bcba1e7d 1543 nd->state |= ND_JUMPED;
9deed3eb
AV
1544 }
1545 if (unlikely(ret)) {
1546 dput(path->dentry);
1547 if (path->mnt != nd->path.mnt)
1548 mntput(path->mnt);
1549 } else {
bd7c4b50
AV
1550 *inode = d_backing_inode(path->dentry);
1551 *seqp = 0; /* out of RCU mode, so the value doesn't matter */
1552 }
1553 return ret;
1554}
1555
baa03890 1556/*
f4fdace9
OD
1557 * This looks up the name in dcache and possibly revalidates the found dentry.
1558 * NULL is returned if the dentry does not exist in the cache.
baa03890 1559 */
e3c13928
AV
1560static struct dentry *lookup_dcache(const struct qstr *name,
1561 struct dentry *dir,
6c51e513 1562 unsigned int flags)
baa03890 1563{
a89f8337 1564 struct dentry *dentry = d_lookup(dir, name);
bad61189 1565 if (dentry) {
a89f8337
AV
1566 int error = d_revalidate(dentry, flags);
1567 if (unlikely(error <= 0)) {
1568 if (!error)
1569 d_invalidate(dentry);
1570 dput(dentry);
1571 return ERR_PTR(error);
bad61189
MS
1572 }
1573 }
baa03890
NP
1574 return dentry;
1575}
1576
44396f4b 1577/*
a03ece5f
AV
1578 * Parent directory has inode locked exclusive. This is one
1579 * and only case when ->lookup() gets called on non in-lookup
1580 * dentries - as the matter of fact, this only gets called
1581 * when directory is guaranteed to have no in-lookup children
1582 * at all.
44396f4b 1583 */
e3c13928 1584static struct dentry *__lookup_hash(const struct qstr *name,
72bd866a 1585 struct dentry *base, unsigned int flags)
a3255546 1586{
6c51e513 1587 struct dentry *dentry = lookup_dcache(name, base, flags);
a03ece5f
AV
1588 struct dentry *old;
1589 struct inode *dir = base->d_inode;
a3255546 1590
6c51e513 1591 if (dentry)
bad61189 1592 return dentry;
a3255546 1593
a03ece5f
AV
1594 /* Don't create child dentry for a dead directory. */
1595 if (unlikely(IS_DEADDIR(dir)))
1596 return ERR_PTR(-ENOENT);
1597
6c51e513
AV
1598 dentry = d_alloc(base, name);
1599 if (unlikely(!dentry))
1600 return ERR_PTR(-ENOMEM);
1601
a03ece5f
AV
1602 old = dir->i_op->lookup(dir, dentry, flags);
1603 if (unlikely(old)) {
1604 dput(dentry);
1605 dentry = old;
1606 }
1607 return dentry;
a3255546
AV
1608}
1609
20e34357
AV
1610static struct dentry *lookup_fast(struct nameidata *nd,
1611 struct inode **inode,
1612 unsigned *seqp)
1da177e4 1613{
31e6b01f 1614 struct dentry *dentry, *parent = nd->path.dentry;
5a18fff2 1615 int status = 1;
9875cf80 1616
b04f784e
NP
1617 /*
1618 * Rename seqlock is not required here because in the off chance
5d0f49c1
AV
1619 * of a false negative due to a concurrent rename, the caller is
1620 * going to fall back to non-racy lookup.
b04f784e 1621 */
31e6b01f
NP
1622 if (nd->flags & LOOKUP_RCU) {
1623 unsigned seq;
da53be12 1624 dentry = __d_lookup_rcu(parent, &nd->last, &seq);
5d0f49c1 1625 if (unlikely(!dentry)) {
e36cffed 1626 if (!try_to_unlazy(nd))
20e34357
AV
1627 return ERR_PTR(-ECHILD);
1628 return NULL;
5d0f49c1 1629 }
5a18fff2 1630
12f8ad4b
LT
1631 /*
1632 * This sequence count validates that the inode matches
1633 * the dentry name information from lookup.
1634 */
63afdfc7 1635 *inode = d_backing_inode(dentry);
5d0f49c1 1636 if (unlikely(read_seqcount_retry(&dentry->d_seq, seq)))
20e34357 1637 return ERR_PTR(-ECHILD);
12f8ad4b
LT
1638
1639 /*
1640 * This sequence count validates that the parent had no
1641 * changes while we did the lookup of the dentry above.
1642 *
1643 * The memory barrier in read_seqcount_begin of child is
1644 * enough, we can use __read_seqcount_retry here.
1645 */
5d0f49c1 1646 if (unlikely(__read_seqcount_retry(&parent->d_seq, nd->seq)))
20e34357 1647 return ERR_PTR(-ECHILD);
5a18fff2 1648
254cf582 1649 *seqp = seq;
a89f8337 1650 status = d_revalidate(dentry, nd->flags);
c153007b 1651 if (likely(status > 0))
20e34357 1652 return dentry;
ae66db45 1653 if (!try_to_unlazy_next(nd, dentry, seq))
20e34357 1654 return ERR_PTR(-ECHILD);
26ddb45e 1655 if (status == -ECHILD)
209a7fb2
AV
1656 /* we'd been told to redo it in non-rcu mode */
1657 status = d_revalidate(dentry, nd->flags);
5a18fff2 1658 } else {
e97cdc87 1659 dentry = __d_lookup(parent, &nd->last);
5d0f49c1 1660 if (unlikely(!dentry))
20e34357 1661 return NULL;
a89f8337 1662 status = d_revalidate(dentry, nd->flags);
9875cf80 1663 }
5a18fff2 1664 if (unlikely(status <= 0)) {
e9742b53 1665 if (!status)
5d0f49c1 1666 d_invalidate(dentry);
5542aa2f 1667 dput(dentry);
20e34357 1668 return ERR_PTR(status);
24643087 1669 }
20e34357 1670 return dentry;
697f514d
MS
1671}
1672
1673/* Fast lookup failed, do it the slow way */
88d8331a
AV
1674static struct dentry *__lookup_slow(const struct qstr *name,
1675 struct dentry *dir,
1676 unsigned int flags)
697f514d 1677{
88d8331a 1678 struct dentry *dentry, *old;
1936386e 1679 struct inode *inode = dir->d_inode;
d9171b93 1680 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
1936386e 1681
1936386e 1682 /* Don't go there if it's already dead */
94bdd655 1683 if (unlikely(IS_DEADDIR(inode)))
88d8331a 1684 return ERR_PTR(-ENOENT);
94bdd655 1685again:
d9171b93 1686 dentry = d_alloc_parallel(dir, name, &wq);
94bdd655 1687 if (IS_ERR(dentry))
88d8331a 1688 return dentry;
94bdd655 1689 if (unlikely(!d_in_lookup(dentry))) {
c64cd6e3
AV
1690 int error = d_revalidate(dentry, flags);
1691 if (unlikely(error <= 0)) {
1692 if (!error) {
1693 d_invalidate(dentry);
949a852e 1694 dput(dentry);
c64cd6e3 1695 goto again;
949a852e 1696 }
c64cd6e3
AV
1697 dput(dentry);
1698 dentry = ERR_PTR(error);
949a852e 1699 }
94bdd655
AV
1700 } else {
1701 old = inode->i_op->lookup(inode, dentry, flags);
1702 d_lookup_done(dentry);
1703 if (unlikely(old)) {
1704 dput(dentry);
1705 dentry = old;
949a852e
AV
1706 }
1707 }
e3c13928 1708 return dentry;
1da177e4
LT
1709}
1710
88d8331a
AV
1711static struct dentry *lookup_slow(const struct qstr *name,
1712 struct dentry *dir,
1713 unsigned int flags)
1714{
1715 struct inode *inode = dir->d_inode;
1716 struct dentry *res;
1717 inode_lock_shared(inode);
1718 res = __lookup_slow(name, dir, flags);
1719 inode_unlock_shared(inode);
1720 return res;
1721}
1722
ba73d987
CB
1723static inline int may_lookup(struct user_namespace *mnt_userns,
1724 struct nameidata *nd)
52094c8a
AV
1725{
1726 if (nd->flags & LOOKUP_RCU) {
7d6beb71 1727 int err = inode_permission(mnt_userns, nd->inode, MAY_EXEC|MAY_NOT_BLOCK);
e36cffed 1728 if (err != -ECHILD || !try_to_unlazy(nd))
52094c8a 1729 return err;
52094c8a 1730 }
ba73d987 1731 return inode_permission(mnt_userns, nd->inode, MAY_EXEC);
52094c8a
AV
1732}
1733
49055906
AV
1734static int reserve_stack(struct nameidata *nd, struct path *link, unsigned seq)
1735{
49055906
AV
1736 if (unlikely(nd->total_link_count++ >= MAXSYMLINKS))
1737 return -ELOOP;
4542576b
AV
1738
1739 if (likely(nd->depth != EMBEDDED_LEVELS))
1740 return 0;
1741 if (likely(nd->stack != nd->internal))
1742 return 0;
60ef60c7 1743 if (likely(nd_alloc_stack(nd)))
49055906 1744 return 0;
60ef60c7
AV
1745
1746 if (nd->flags & LOOKUP_RCU) {
1747 // we need to grab link before we do unlazy. And we can't skip
1748 // unlazy even if we fail to grab the link - cleanup needs it
49055906 1749 bool grabbed_link = legitimize_path(nd, link, seq);
60ef60c7 1750
e5ca024e 1751 if (!try_to_unlazy(nd) || !grabbed_link)
60ef60c7
AV
1752 return -ECHILD;
1753
1754 if (nd_alloc_stack(nd))
1755 return 0;
49055906 1756 }
60ef60c7 1757 return -ENOMEM;
49055906
AV
1758}
1759
b1a81972
AV
1760enum {WALK_TRAILING = 1, WALK_MORE = 2, WALK_NOFOLLOW = 4};
1761
06708adb 1762static const char *pick_link(struct nameidata *nd, struct path *link,
b1a81972 1763 struct inode *inode, unsigned seq, int flags)
d63ff28f 1764{
1cf2665b 1765 struct saved *last;
ad6cc4c3 1766 const char *res;
49055906 1767 int error = reserve_stack(nd, link, seq);
ad6cc4c3 1768
626de996 1769 if (unlikely(error)) {
49055906 1770 if (!(nd->flags & LOOKUP_RCU))
bc40aee0 1771 path_put(link);
49055906 1772 return ERR_PTR(error);
626de996 1773 }
ab104923 1774 last = nd->stack + nd->depth++;
1cf2665b 1775 last->link = *link;
fceef393 1776 clear_delayed_call(&last->done);
0450b2d1 1777 last->seq = seq;
ad6cc4c3 1778
b1a81972 1779 if (flags & WALK_TRAILING) {
ad6cc4c3
AV
1780 error = may_follow_link(nd, inode);
1781 if (unlikely(error))
1782 return ERR_PTR(error);
1783 }
1784
dab741e0
MN
1785 if (unlikely(nd->flags & LOOKUP_NO_SYMLINKS) ||
1786 unlikely(link->mnt->mnt_flags & MNT_NOSYMFOLLOW))
ad6cc4c3
AV
1787 return ERR_PTR(-ELOOP);
1788
1789 if (!(nd->flags & LOOKUP_RCU)) {
1790 touch_atime(&last->link);
1791 cond_resched();
1792 } else if (atime_needs_update(&last->link, inode)) {
e36cffed 1793 if (!try_to_unlazy(nd))
ad6cc4c3
AV
1794 return ERR_PTR(-ECHILD);
1795 touch_atime(&last->link);
1796 }
1797
1798 error = security_inode_follow_link(link->dentry, inode,
1799 nd->flags & LOOKUP_RCU);
1800 if (unlikely(error))
1801 return ERR_PTR(error);
1802
ad6cc4c3
AV
1803 res = READ_ONCE(inode->i_link);
1804 if (!res) {
1805 const char * (*get)(struct dentry *, struct inode *,
1806 struct delayed_call *);
1807 get = inode->i_op->get_link;
1808 if (nd->flags & LOOKUP_RCU) {
1809 res = get(NULL, inode, &last->done);
e36cffed 1810 if (res == ERR_PTR(-ECHILD) && try_to_unlazy(nd))
ad6cc4c3 1811 res = get(link->dentry, inode, &last->done);
ad6cc4c3
AV
1812 } else {
1813 res = get(link->dentry, inode, &last->done);
1814 }
1815 if (!res)
1816 goto all_done;
1817 if (IS_ERR(res))
1818 return res;
1819 }
1820 if (*res == '/') {
1821 error = nd_jump_root(nd);
1822 if (unlikely(error))
1823 return ERR_PTR(error);
1824 while (unlikely(*++res == '/'))
1825 ;
1826 }
1827 if (*res)
1828 return res;
1829all_done: // pure jump
1830 put_link(nd);
1831 return NULL;
d63ff28f
AV
1832}
1833
3ddcd056
LT
1834/*
1835 * Do we need to follow links? We _really_ want to be able
1836 * to do this check without having to look at inode->i_op,
1837 * so we keep a cache of "no, this doesn't need follow_link"
1838 * for the common case.
1839 */
b0417d2c 1840static const char *step_into(struct nameidata *nd, int flags,
cbae4d12 1841 struct dentry *dentry, struct inode *inode, unsigned seq)
3ddcd056 1842{
cbae4d12
AV
1843 struct path path;
1844 int err = handle_mounts(nd, dentry, &path, &inode, &seq);
1845
1846 if (err < 0)
b0417d2c 1847 return ERR_PTR(err);
cbae4d12 1848 if (likely(!d_is_symlink(path.dentry)) ||
8c4efe22 1849 ((flags & WALK_TRAILING) && !(nd->flags & LOOKUP_FOLLOW)) ||
aca2903e 1850 (flags & WALK_NOFOLLOW)) {
8f64fb1c 1851 /* not a symlink or should not follow */
c99687a0
AV
1852 if (!(nd->flags & LOOKUP_RCU)) {
1853 dput(nd->path.dentry);
1854 if (nd->path.mnt != path.mnt)
1855 mntput(nd->path.mnt);
1856 }
1857 nd->path = path;
8f64fb1c
AV
1858 nd->inode = inode;
1859 nd->seq = seq;
b0417d2c 1860 return NULL;
8f64fb1c 1861 }
a7f77542 1862 if (nd->flags & LOOKUP_RCU) {
84f0cd9e 1863 /* make sure that d_is_symlink above matches inode */
cbae4d12 1864 if (read_seqcount_retry(&path.dentry->d_seq, seq))
b0417d2c 1865 return ERR_PTR(-ECHILD);
84f0cd9e
AV
1866 } else {
1867 if (path.mnt == nd->path.mnt)
1868 mntget(path.mnt);
a7f77542 1869 }
b1a81972 1870 return pick_link(nd, &path, inode, seq, flags);
3ddcd056
LT
1871}
1872
c2df1968
AV
1873static struct dentry *follow_dotdot_rcu(struct nameidata *nd,
1874 struct inode **inodep,
1875 unsigned *seqp)
957dd41d 1876{
12487f30 1877 struct dentry *parent, *old;
957dd41d 1878
12487f30
AV
1879 if (path_equal(&nd->path, &nd->root))
1880 goto in_root;
1881 if (unlikely(nd->path.dentry == nd->path.mnt->mnt_root)) {
7ef482fa 1882 struct path path;
efe772d6 1883 unsigned seq;
7ef482fa
AV
1884 if (!choose_mountpoint_rcu(real_mount(nd->path.mnt),
1885 &nd->root, &path, &seq))
1886 goto in_root;
efe772d6
AV
1887 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1888 return ERR_PTR(-ECHILD);
1889 nd->path = path;
1890 nd->inode = path.dentry->d_inode;
1891 nd->seq = seq;
1892 if (unlikely(read_seqretry(&mount_lock, nd->m_seq)))
1893 return ERR_PTR(-ECHILD);
1894 /* we know that mountpoint was pinned */
957dd41d 1895 }
12487f30
AV
1896 old = nd->path.dentry;
1897 parent = old->d_parent;
1898 *inodep = parent->d_inode;
1899 *seqp = read_seqcount_begin(&parent->d_seq);
1900 if (unlikely(read_seqcount_retry(&old->d_seq, nd->seq)))
1901 return ERR_PTR(-ECHILD);
1902 if (unlikely(!path_connected(nd->path.mnt, parent)))
1903 return ERR_PTR(-ECHILD);
1904 return parent;
1905in_root:
efe772d6
AV
1906 if (unlikely(read_seqretry(&mount_lock, nd->m_seq)))
1907 return ERR_PTR(-ECHILD);
c2df1968
AV
1908 if (unlikely(nd->flags & LOOKUP_BENEATH))
1909 return ERR_PTR(-ECHILD);
1910 return NULL;
957dd41d
AV
1911}
1912
c2df1968
AV
1913static struct dentry *follow_dotdot(struct nameidata *nd,
1914 struct inode **inodep,
1915 unsigned *seqp)
957dd41d 1916{
12487f30
AV
1917 struct dentry *parent;
1918
1919 if (path_equal(&nd->path, &nd->root))
1920 goto in_root;
1921 if (unlikely(nd->path.dentry == nd->path.mnt->mnt_root)) {
2aa38470
AV
1922 struct path path;
1923
1924 if (!choose_mountpoint(real_mount(nd->path.mnt),
1925 &nd->root, &path))
1926 goto in_root;
165200d6
AV
1927 path_put(&nd->path);
1928 nd->path = path;
2aa38470 1929 nd->inode = path.dentry->d_inode;
165200d6
AV
1930 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1931 return ERR_PTR(-EXDEV);
957dd41d 1932 }
12487f30
AV
1933 /* rare case of legitimate dget_parent()... */
1934 parent = dget_parent(nd->path.dentry);
1935 if (unlikely(!path_connected(nd->path.mnt, parent))) {
1936 dput(parent);
1937 return ERR_PTR(-ENOENT);
1938 }
1939 *seqp = 0;
1940 *inodep = parent->d_inode;
1941 return parent;
1942
1943in_root:
c2df1968
AV
1944 if (unlikely(nd->flags & LOOKUP_BENEATH))
1945 return ERR_PTR(-EXDEV);
1946 dget(nd->path.dentry);
1947 return NULL;
957dd41d
AV
1948}
1949
7521f22b 1950static const char *handle_dots(struct nameidata *nd, int type)
957dd41d
AV
1951{
1952 if (type == LAST_DOTDOT) {
7521f22b 1953 const char *error = NULL;
c2df1968
AV
1954 struct dentry *parent;
1955 struct inode *inode;
1956 unsigned seq;
957dd41d
AV
1957
1958 if (!nd->root.mnt) {
7521f22b 1959 error = ERR_PTR(set_root(nd));
957dd41d
AV
1960 if (error)
1961 return error;
1962 }
1963 if (nd->flags & LOOKUP_RCU)
c2df1968 1964 parent = follow_dotdot_rcu(nd, &inode, &seq);
957dd41d 1965 else
c2df1968
AV
1966 parent = follow_dotdot(nd, &inode, &seq);
1967 if (IS_ERR(parent))
1968 return ERR_CAST(parent);
1969 if (unlikely(!parent))
1970 error = step_into(nd, WALK_NOFOLLOW,
1971 nd->path.dentry, nd->inode, nd->seq);
1972 else
1973 error = step_into(nd, WALK_NOFOLLOW,
1974 parent, inode, seq);
1975 if (unlikely(error))
957dd41d
AV
1976 return error;
1977
1978 if (unlikely(nd->flags & LOOKUP_IS_SCOPED)) {
1979 /*
1980 * If there was a racing rename or mount along our
1981 * path, then we can't be sure that ".." hasn't jumped
1982 * above nd->root (and so userspace should retry or use
1983 * some fallback).
1984 */
1985 smp_rmb();
1986 if (unlikely(__read_seqcount_retry(&mount_lock.seqcount, nd->m_seq)))
7521f22b 1987 return ERR_PTR(-EAGAIN);
957dd41d 1988 if (unlikely(__read_seqcount_retry(&rename_lock.seqcount, nd->r_seq)))
7521f22b 1989 return ERR_PTR(-EAGAIN);
957dd41d
AV
1990 }
1991 }
7521f22b 1992 return NULL;
957dd41d
AV
1993}
1994
92d27016 1995static const char *walk_component(struct nameidata *nd, int flags)
ce57dfc1 1996{
db3c9ade 1997 struct dentry *dentry;
ce57dfc1 1998 struct inode *inode;
254cf582 1999 unsigned seq;
ce57dfc1
AV
2000 /*
2001 * "." and ".." are special - ".." especially so because it has
2002 * to be able to know about the current root directory and
2003 * parent relationships.
2004 */
4693a547 2005 if (unlikely(nd->last_type != LAST_NORM)) {
1c4ff1a8 2006 if (!(flags & WALK_MORE) && nd->depth)
4693a547 2007 put_link(nd);
7521f22b 2008 return handle_dots(nd, nd->last_type);
4693a547 2009 }
20e34357
AV
2010 dentry = lookup_fast(nd, &inode, &seq);
2011 if (IS_ERR(dentry))
92d27016 2012 return ERR_CAST(dentry);
20e34357 2013 if (unlikely(!dentry)) {
db3c9ade
AV
2014 dentry = lookup_slow(&nd->last, nd->path.dentry, nd->flags);
2015 if (IS_ERR(dentry))
92d27016 2016 return ERR_CAST(dentry);
ce57dfc1 2017 }
56676ec3
AV
2018 if (!(flags & WALK_MORE) && nd->depth)
2019 put_link(nd);
b0417d2c 2020 return step_into(nd, flags, dentry, inode, seq);
ce57dfc1
AV
2021}
2022
bfcfaa77
LT
2023/*
2024 * We can do the critical dentry name comparison and hashing
2025 * operations one word at a time, but we are limited to:
2026 *
2027 * - Architectures with fast unaligned word accesses. We could
2028 * do a "get_unaligned()" if this helps and is sufficiently
2029 * fast.
2030 *
bfcfaa77
LT
2031 * - non-CONFIG_DEBUG_PAGEALLOC configurations (so that we
2032 * do not trap on the (extremely unlikely) case of a page
2033 * crossing operation.
2034 *
2035 * - Furthermore, we need an efficient 64-bit compile for the
2036 * 64-bit case in order to generate the "number of bytes in
2037 * the final mask". Again, that could be replaced with a
2038 * efficient population count instruction or similar.
2039 */
2040#ifdef CONFIG_DCACHE_WORD_ACCESS
2041
f68e556e 2042#include <asm/word-at-a-time.h>
bfcfaa77 2043
468a9428 2044#ifdef HASH_MIX
bfcfaa77 2045
468a9428 2046/* Architecture provides HASH_MIX and fold_hash() in <asm/hash.h> */
bfcfaa77 2047
468a9428 2048#elif defined(CONFIG_64BIT)
0fed3ac8 2049/*
2a18da7a
GS
2050 * Register pressure in the mixing function is an issue, particularly
2051 * on 32-bit x86, but almost any function requires one state value and
2052 * one temporary. Instead, use a function designed for two state values
2053 * and no temporaries.
2054 *
2055 * This function cannot create a collision in only two iterations, so
2056 * we have two iterations to achieve avalanche. In those two iterations,
2057 * we have six layers of mixing, which is enough to spread one bit's
2058 * influence out to 2^6 = 64 state bits.
2059 *
2060 * Rotate constants are scored by considering either 64 one-bit input
2061 * deltas or 64*63/2 = 2016 two-bit input deltas, and finding the
2062 * probability of that delta causing a change to each of the 128 output
2063 * bits, using a sample of random initial states.
2064 *
2065 * The Shannon entropy of the computed probabilities is then summed
2066 * to produce a score. Ideally, any input change has a 50% chance of
2067 * toggling any given output bit.
2068 *
2069 * Mixing scores (in bits) for (12,45):
2070 * Input delta: 1-bit 2-bit
2071 * 1 round: 713.3 42542.6
2072 * 2 rounds: 2753.7 140389.8
2073 * 3 rounds: 5954.1 233458.2
2074 * 4 rounds: 7862.6 256672.2
2075 * Perfect: 8192 258048
2076 * (64*128) (64*63/2 * 128)
0fed3ac8 2077 */
2a18da7a
GS
2078#define HASH_MIX(x, y, a) \
2079 ( x ^= (a), \
2080 y ^= x, x = rol64(x,12),\
2081 x += y, y = rol64(y,45),\
2082 y *= 9 )
bfcfaa77 2083
0fed3ac8 2084/*
2a18da7a
GS
2085 * Fold two longs into one 32-bit hash value. This must be fast, but
2086 * latency isn't quite as critical, as there is a fair bit of additional
2087 * work done before the hash value is used.
0fed3ac8 2088 */
2a18da7a 2089static inline unsigned int fold_hash(unsigned long x, unsigned long y)
0fed3ac8 2090{
2a18da7a
GS
2091 y ^= x * GOLDEN_RATIO_64;
2092 y *= GOLDEN_RATIO_64;
2093 return y >> 32;
0fed3ac8
GS
2094}
2095
bfcfaa77
LT
2096#else /* 32-bit case */
2097
2a18da7a
GS
2098/*
2099 * Mixing scores (in bits) for (7,20):
2100 * Input delta: 1-bit 2-bit
2101 * 1 round: 330.3 9201.6
2102 * 2 rounds: 1246.4 25475.4
2103 * 3 rounds: 1907.1 31295.1
2104 * 4 rounds: 2042.3 31718.6
2105 * Perfect: 2048 31744
2106 * (32*64) (32*31/2 * 64)
2107 */
2108#define HASH_MIX(x, y, a) \
2109 ( x ^= (a), \
2110 y ^= x, x = rol32(x, 7),\
2111 x += y, y = rol32(y,20),\
2112 y *= 9 )
bfcfaa77 2113
2a18da7a 2114static inline unsigned int fold_hash(unsigned long x, unsigned long y)
0fed3ac8 2115{
2a18da7a
GS
2116 /* Use arch-optimized multiply if one exists */
2117 return __hash_32(y ^ __hash_32(x));
0fed3ac8
GS
2118}
2119
bfcfaa77
LT
2120#endif
2121
2a18da7a
GS
2122/*
2123 * Return the hash of a string of known length. This is carfully
2124 * designed to match hash_name(), which is the more critical function.
2125 * In particular, we must end by hashing a final word containing 0..7
2126 * payload bytes, to match the way that hash_name() iterates until it
2127 * finds the delimiter after the name.
2128 */
8387ff25 2129unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
bfcfaa77 2130{
8387ff25 2131 unsigned long a, x = 0, y = (unsigned long)salt;
bfcfaa77
LT
2132
2133 for (;;) {
fcfd2fbf
GS
2134 if (!len)
2135 goto done;
e419b4cc 2136 a = load_unaligned_zeropad(name);
bfcfaa77
LT
2137 if (len < sizeof(unsigned long))
2138 break;
2a18da7a 2139 HASH_MIX(x, y, a);
bfcfaa77
LT
2140 name += sizeof(unsigned long);
2141 len -= sizeof(unsigned long);
bfcfaa77 2142 }
2a18da7a 2143 x ^= a & bytemask_from_count(len);
bfcfaa77 2144done:
2a18da7a 2145 return fold_hash(x, y);
bfcfaa77
LT
2146}
2147EXPORT_SYMBOL(full_name_hash);
2148
fcfd2fbf 2149/* Return the "hash_len" (hash and length) of a null-terminated string */
8387ff25 2150u64 hashlen_string(const void *salt, const char *name)
fcfd2fbf 2151{
8387ff25
LT
2152 unsigned long a = 0, x = 0, y = (unsigned long)salt;
2153 unsigned long adata, mask, len;
fcfd2fbf
GS
2154 const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2155
8387ff25
LT
2156 len = 0;
2157 goto inside;
2158
fcfd2fbf 2159 do {
2a18da7a 2160 HASH_MIX(x, y, a);
fcfd2fbf 2161 len += sizeof(unsigned long);
8387ff25 2162inside:
fcfd2fbf
GS
2163 a = load_unaligned_zeropad(name+len);
2164 } while (!has_zero(a, &adata, &constants));
2165
2166 adata = prep_zero_mask(a, adata, &constants);
2167 mask = create_zero_mask(adata);
2a18da7a 2168 x ^= a & zero_bytemask(mask);
fcfd2fbf 2169
2a18da7a 2170 return hashlen_create(fold_hash(x, y), len + find_zero(mask));
fcfd2fbf
GS
2171}
2172EXPORT_SYMBOL(hashlen_string);
2173
bfcfaa77
LT
2174/*
2175 * Calculate the length and hash of the path component, and
d6bb3e90 2176 * return the "hash_len" as the result.
bfcfaa77 2177 */
8387ff25 2178static inline u64 hash_name(const void *salt, const char *name)
bfcfaa77 2179{
8387ff25
LT
2180 unsigned long a = 0, b, x = 0, y = (unsigned long)salt;
2181 unsigned long adata, bdata, mask, len;
36126f8f 2182 const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
bfcfaa77 2183
8387ff25
LT
2184 len = 0;
2185 goto inside;
2186
bfcfaa77 2187 do {
2a18da7a 2188 HASH_MIX(x, y, a);
bfcfaa77 2189 len += sizeof(unsigned long);
8387ff25 2190inside:
e419b4cc 2191 a = load_unaligned_zeropad(name+len);
36126f8f
LT
2192 b = a ^ REPEAT_BYTE('/');
2193 } while (!(has_zero(a, &adata, &constants) | has_zero(b, &bdata, &constants)));
2194
2195 adata = prep_zero_mask(a, adata, &constants);
2196 bdata = prep_zero_mask(b, bdata, &constants);
36126f8f 2197 mask = create_zero_mask(adata | bdata);
2a18da7a 2198 x ^= a & zero_bytemask(mask);
36126f8f 2199
2a18da7a 2200 return hashlen_create(fold_hash(x, y), len + find_zero(mask));
bfcfaa77
LT
2201}
2202
2a18da7a 2203#else /* !CONFIG_DCACHE_WORD_ACCESS: Slow, byte-at-a-time version */
bfcfaa77 2204
fcfd2fbf 2205/* Return the hash of a string of known length */
8387ff25 2206unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
0145acc2 2207{
8387ff25 2208 unsigned long hash = init_name_hash(salt);
0145acc2 2209 while (len--)
fcfd2fbf 2210 hash = partial_name_hash((unsigned char)*name++, hash);
0145acc2
LT
2211 return end_name_hash(hash);
2212}
ae942ae7 2213EXPORT_SYMBOL(full_name_hash);
0145acc2 2214
fcfd2fbf 2215/* Return the "hash_len" (hash and length) of a null-terminated string */
8387ff25 2216u64 hashlen_string(const void *salt, const char *name)
fcfd2fbf 2217{
8387ff25 2218 unsigned long hash = init_name_hash(salt);
fcfd2fbf
GS
2219 unsigned long len = 0, c;
2220
2221 c = (unsigned char)*name;
e0ab7af9 2222 while (c) {
fcfd2fbf
GS
2223 len++;
2224 hash = partial_name_hash(c, hash);
2225 c = (unsigned char)name[len];
e0ab7af9 2226 }
fcfd2fbf
GS
2227 return hashlen_create(end_name_hash(hash), len);
2228}
f2a031b6 2229EXPORT_SYMBOL(hashlen_string);
fcfd2fbf 2230
200e9ef7
LT
2231/*
2232 * We know there's a real path component here of at least
2233 * one character.
2234 */
8387ff25 2235static inline u64 hash_name(const void *salt, const char *name)
200e9ef7 2236{
8387ff25 2237 unsigned long hash = init_name_hash(salt);
200e9ef7
LT
2238 unsigned long len = 0, c;
2239
2240 c = (unsigned char)*name;
2241 do {
2242 len++;
2243 hash = partial_name_hash(c, hash);
2244 c = (unsigned char)name[len];
2245 } while (c && c != '/');
d6bb3e90 2246 return hashlen_create(end_name_hash(hash), len);
200e9ef7
LT
2247}
2248
bfcfaa77
LT
2249#endif
2250
1da177e4
LT
2251/*
2252 * Name resolution.
ea3834d9
PM
2253 * This is the basic name resolution function, turning a pathname into
2254 * the final dentry. We expect 'base' to be positive and a directory.
1da177e4 2255 *
ea3834d9
PM
2256 * Returns 0 and nd will have valid dentry and mnt on success.
2257 * Returns error and drops reference to input namei data on failure.
1da177e4 2258 */
6de88d72 2259static int link_path_walk(const char *name, struct nameidata *nd)
1da177e4 2260{
d8d4611a 2261 int depth = 0; // depth <= nd->depth
1da177e4 2262 int err;
32cd7468 2263
b4c03536 2264 nd->last_type = LAST_ROOT;
c108837e 2265 nd->flags |= LOOKUP_PARENT;
9b5858e9
AV
2266 if (IS_ERR(name))
2267 return PTR_ERR(name);
1da177e4
LT
2268 while (*name=='/')
2269 name++;
1a97d899
AV
2270 if (!*name) {
2271 nd->dir_mode = 0; // short-circuit the 'hardening' idiocy
9e18f10a 2272 return 0;
1a97d899 2273 }
1da177e4 2274
1da177e4
LT
2275 /* At this point we know we have a real path component. */
2276 for(;;) {
549c7297 2277 struct user_namespace *mnt_userns;
92d27016 2278 const char *link;
d6bb3e90 2279 u64 hash_len;
fe479a58 2280 int type;
1da177e4 2281
549c7297
CB
2282 mnt_userns = mnt_user_ns(nd->path.mnt);
2283 err = may_lookup(mnt_userns, nd);
2a18da7a 2284 if (err)
3595e234 2285 return err;
1da177e4 2286
8387ff25 2287 hash_len = hash_name(nd->path.dentry, name);
1da177e4 2288
fe479a58 2289 type = LAST_NORM;
d6bb3e90 2290 if (name[0] == '.') switch (hashlen_len(hash_len)) {
fe479a58 2291 case 2:
200e9ef7 2292 if (name[1] == '.') {
fe479a58 2293 type = LAST_DOTDOT;
bcba1e7d 2294 nd->state |= ND_JUMPED;
16c2cd71 2295 }
fe479a58
AV
2296 break;
2297 case 1:
2298 type = LAST_DOT;
2299 }
5a202bcd
AV
2300 if (likely(type == LAST_NORM)) {
2301 struct dentry *parent = nd->path.dentry;
bcba1e7d 2302 nd->state &= ~ND_JUMPED;
5a202bcd 2303 if (unlikely(parent->d_flags & DCACHE_OP_HASH)) {
a060dc50 2304 struct qstr this = { { .hash_len = hash_len }, .name = name };
da53be12 2305 err = parent->d_op->d_hash(parent, &this);
5a202bcd 2306 if (err < 0)
3595e234 2307 return err;
d6bb3e90
LT
2308 hash_len = this.hash_len;
2309 name = this.name;
5a202bcd
AV
2310 }
2311 }
fe479a58 2312
d6bb3e90
LT
2313 nd->last.hash_len = hash_len;
2314 nd->last.name = name;
5f4a6a69
AV
2315 nd->last_type = type;
2316
d6bb3e90
LT
2317 name += hashlen_len(hash_len);
2318 if (!*name)
bdf6cbf1 2319 goto OK;
200e9ef7
LT
2320 /*
2321 * If it wasn't NUL, we know it was '/'. Skip that
2322 * slash, and continue until no more slashes.
2323 */
2324 do {
d6bb3e90
LT
2325 name++;
2326 } while (unlikely(*name == '/'));
8620c238
AV
2327 if (unlikely(!*name)) {
2328OK:
d8d4611a 2329 /* pathname or trailing symlink, done */
c108837e 2330 if (!depth) {
549c7297 2331 nd->dir_uid = i_uid_into_mnt(mnt_userns, nd->inode);
0f705953 2332 nd->dir_mode = nd->inode->i_mode;
c108837e 2333 nd->flags &= ~LOOKUP_PARENT;
8620c238 2334 return 0;
c108837e 2335 }
8620c238 2336 /* last component of nested symlink */
d8d4611a 2337 name = nd->stack[--depth].name;
8c4efe22 2338 link = walk_component(nd, 0);
1c4ff1a8
AV
2339 } else {
2340 /* not the last component */
8c4efe22 2341 link = walk_component(nd, WALK_MORE);
8620c238 2342 }
92d27016
AV
2343 if (unlikely(link)) {
2344 if (IS_ERR(link))
2345 return PTR_ERR(link);
2346 /* a symlink to follow */
d8d4611a 2347 nd->stack[depth++].name = name;
92d27016
AV
2348 name = link;
2349 continue;
31e6b01f 2350 }
97242f99
AV
2351 if (unlikely(!d_can_lookup(nd->path.dentry))) {
2352 if (nd->flags & LOOKUP_RCU) {
e36cffed 2353 if (!try_to_unlazy(nd))
97242f99
AV
2354 return -ECHILD;
2355 }
3595e234 2356 return -ENOTDIR;
97242f99 2357 }
1da177e4 2358 }
1da177e4
LT
2359}
2360
edc2b1da 2361/* must be paired with terminate_walk() */
c8a53ee5 2362static const char *path_init(struct nameidata *nd, unsigned flags)
31e6b01f 2363{
740a1678 2364 int error;
c8a53ee5 2365 const char *s = nd->name->name;
31e6b01f 2366
6c6ec2b0
JA
2367 /* LOOKUP_CACHED requires RCU, ask caller to retry */
2368 if ((flags & (LOOKUP_RCU | LOOKUP_CACHED)) == LOOKUP_CACHED)
2369 return ERR_PTR(-EAGAIN);
2370
c0eb027e
LT
2371 if (!*s)
2372 flags &= ~LOOKUP_RCU;
edc2b1da
AV
2373 if (flags & LOOKUP_RCU)
2374 rcu_read_lock();
c0eb027e 2375
bcba1e7d
AV
2376 nd->flags = flags;
2377 nd->state |= ND_JUMPED;
ab87f9a5
AS
2378
2379 nd->m_seq = __read_seqcount_begin(&mount_lock.seqcount);
2380 nd->r_seq = __read_seqcount_begin(&rename_lock.seqcount);
2381 smp_rmb();
2382
bcba1e7d 2383 if (nd->state & ND_ROOT_PRESET) {
b18825a7
DH
2384 struct dentry *root = nd->root.dentry;
2385 struct inode *inode = root->d_inode;
93893862
AV
2386 if (*s && unlikely(!d_can_lookup(root)))
2387 return ERR_PTR(-ENOTDIR);
5b6ca027
AV
2388 nd->path = nd->root;
2389 nd->inode = inode;
2390 if (flags & LOOKUP_RCU) {
ab87f9a5 2391 nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
8f47a016 2392 nd->root_seq = nd->seq;
5b6ca027
AV
2393 } else {
2394 path_get(&nd->path);
2395 }
368ee9ba 2396 return s;
5b6ca027
AV
2397 }
2398
31e6b01f 2399 nd->root.mnt = NULL;
31e6b01f 2400
8db52c7e
AS
2401 /* Absolute pathname -- fetch the root (LOOKUP_IN_ROOT uses nd->dfd). */
2402 if (*s == '/' && !(flags & LOOKUP_IN_ROOT)) {
740a1678
AS
2403 error = nd_jump_root(nd);
2404 if (unlikely(error))
2405 return ERR_PTR(error);
2406 return s;
8db52c7e
AS
2407 }
2408
2409 /* Relative pathname -- get the starting-point it is relative to. */
2410 if (nd->dfd == AT_FDCWD) {
e41f7d4e
AV
2411 if (flags & LOOKUP_RCU) {
2412 struct fs_struct *fs = current->fs;
2413 unsigned seq;
31e6b01f 2414
e41f7d4e
AV
2415 do {
2416 seq = read_seqcount_begin(&fs->seq);
2417 nd->path = fs->pwd;
ef55d917 2418 nd->inode = nd->path.dentry->d_inode;
e41f7d4e
AV
2419 nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
2420 } while (read_seqcount_retry(&fs->seq, seq));
2421 } else {
2422 get_fs_pwd(current->fs, &nd->path);
ef55d917 2423 nd->inode = nd->path.dentry->d_inode;
e41f7d4e 2424 }
31e6b01f 2425 } else {
582aa64a 2426 /* Caller must check execute permissions on the starting path component */
c8a53ee5 2427 struct fd f = fdget_raw(nd->dfd);
31e6b01f
NP
2428 struct dentry *dentry;
2429
2903ff01 2430 if (!f.file)
368ee9ba 2431 return ERR_PTR(-EBADF);
31e6b01f 2432
2903ff01 2433 dentry = f.file->f_path.dentry;
31e6b01f 2434
edc2b1da
AV
2435 if (*s && unlikely(!d_can_lookup(dentry))) {
2436 fdput(f);
2437 return ERR_PTR(-ENOTDIR);
f52e0c11 2438 }
31e6b01f 2439
2903ff01 2440 nd->path = f.file->f_path;
e41f7d4e 2441 if (flags & LOOKUP_RCU) {
34a26b99
AV
2442 nd->inode = nd->path.dentry->d_inode;
2443 nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
e41f7d4e 2444 } else {
2903ff01 2445 path_get(&nd->path);
34a26b99 2446 nd->inode = nd->path.dentry->d_inode;
e41f7d4e 2447 }
34a26b99 2448 fdput(f);
31e6b01f 2449 }
8db52c7e 2450
adb21d2b
AS
2451 /* For scoped-lookups we need to set the root to the dirfd as well. */
2452 if (flags & LOOKUP_IS_SCOPED) {
2453 nd->root = nd->path;
2454 if (flags & LOOKUP_RCU) {
2455 nd->root_seq = nd->seq;
2456 } else {
2457 path_get(&nd->root);
bcba1e7d 2458 nd->state |= ND_ROOT_GRABBED;
adb21d2b
AS
2459 }
2460 }
2461 return s;
9b4a9b14
AV
2462}
2463
1ccac622 2464static inline const char *lookup_last(struct nameidata *nd)
bd92d7fe
AV
2465{
2466 if (nd->last_type == LAST_NORM && nd->last.name[nd->last.len])
2467 nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
2468
c108837e 2469 return walk_component(nd, WALK_TRAILING);
bd92d7fe
AV
2470}
2471
4f757f3c
AV
2472static int handle_lookup_down(struct nameidata *nd)
2473{
c153007b 2474 if (!(nd->flags & LOOKUP_RCU))
db3c9ade 2475 dget(nd->path.dentry);
b0417d2c
AV
2476 return PTR_ERR(step_into(nd, WALK_NOFOLLOW,
2477 nd->path.dentry, nd->inode, nd->seq));
4f757f3c
AV
2478}
2479
9b4a9b14 2480/* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
c8a53ee5 2481static int path_lookupat(struct nameidata *nd, unsigned flags, struct path *path)
9b4a9b14 2482{
c8a53ee5 2483 const char *s = path_init(nd, flags);
bd92d7fe 2484 int err;
31e6b01f 2485
9b5858e9 2486 if (unlikely(flags & LOOKUP_DOWN) && !IS_ERR(s)) {
4f757f3c 2487 err = handle_lookup_down(nd);
5f336e72
AV
2488 if (unlikely(err < 0))
2489 s = ERR_PTR(err);
4f757f3c
AV
2490 }
2491
1ccac622
AV
2492 while (!(err = link_path_walk(s, nd)) &&
2493 (s = lookup_last(nd)) != NULL)
2494 ;
4f0ed93f
AV
2495 if (!err && unlikely(nd->flags & LOOKUP_MOUNTPOINT)) {
2496 err = handle_lookup_down(nd);
bcba1e7d 2497 nd->state &= ~ND_JUMPED; // no d_weak_revalidate(), please...
4f0ed93f 2498 }
9f1fafee
AV
2499 if (!err)
2500 err = complete_walk(nd);
bd92d7fe 2501
deb106c6
AV
2502 if (!err && nd->flags & LOOKUP_DIRECTORY)
2503 if (!d_can_lookup(nd->path.dentry))
bd23a539 2504 err = -ENOTDIR;
625b6d10
AV
2505 if (!err) {
2506 *path = nd->path;
2507 nd->path.mnt = NULL;
2508 nd->path.dentry = NULL;
2509 }
2510 terminate_walk(nd);
bd92d7fe 2511 return err;
ee0827cd 2512}
31e6b01f 2513
794ebcea 2514int filename_lookup(int dfd, struct filename *name, unsigned flags,
31d921c7 2515 struct path *path, struct path *root)
ee0827cd 2516{
894bc8c4 2517 int retval;
9883d185 2518 struct nameidata nd;
abc9f5be
AV
2519 if (IS_ERR(name))
2520 return PTR_ERR(name);
06422964 2521 set_nameidata(&nd, dfd, name, root);
c8a53ee5 2522 retval = path_lookupat(&nd, flags | LOOKUP_RCU, path);
ee0827cd 2523 if (unlikely(retval == -ECHILD))
c8a53ee5 2524 retval = path_lookupat(&nd, flags, path);
ee0827cd 2525 if (unlikely(retval == -ESTALE))
c8a53ee5 2526 retval = path_lookupat(&nd, flags | LOOKUP_REVAL, path);
31e6b01f 2527
f78570dd 2528 if (likely(!retval))
161aff1d
AV
2529 audit_inode(name, path->dentry,
2530 flags & LOOKUP_MOUNTPOINT ? AUDIT_INODE_NOEVAL : 0);
9883d185 2531 restore_nameidata();
020250f3
DK
2532 return retval;
2533}
2534
8bcb77fa 2535/* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
c8a53ee5 2536static int path_parentat(struct nameidata *nd, unsigned flags,
391172c4 2537 struct path *parent)
8bcb77fa 2538{
c8a53ee5 2539 const char *s = path_init(nd, flags);
9b5858e9 2540 int err = link_path_walk(s, nd);
8bcb77fa
AV
2541 if (!err)
2542 err = complete_walk(nd);
391172c4
AV
2543 if (!err) {
2544 *parent = nd->path;
2545 nd->path.mnt = NULL;
2546 nd->path.dentry = NULL;
2547 }
2548 terminate_walk(nd);
8bcb77fa
AV
2549 return err;
2550}
2551
0766ec82 2552/* Note: this does not consume "name" */
c5f563f9 2553static int filename_parentat(int dfd, struct filename *name,
0766ec82
SB
2554 unsigned int flags, struct path *parent,
2555 struct qstr *last, int *type)
8bcb77fa
AV
2556{
2557 int retval;
9883d185 2558 struct nameidata nd;
8bcb77fa 2559
5c31b6ce 2560 if (IS_ERR(name))
0ee50b47 2561 return PTR_ERR(name);
06422964 2562 set_nameidata(&nd, dfd, name, NULL);
c8a53ee5 2563 retval = path_parentat(&nd, flags | LOOKUP_RCU, parent);
8bcb77fa 2564 if (unlikely(retval == -ECHILD))
c8a53ee5 2565 retval = path_parentat(&nd, flags, parent);
8bcb77fa 2566 if (unlikely(retval == -ESTALE))
c8a53ee5 2567 retval = path_parentat(&nd, flags | LOOKUP_REVAL, parent);
391172c4
AV
2568 if (likely(!retval)) {
2569 *last = nd.last;
2570 *type = nd.last_type;
c9b07eab 2571 audit_inode(name, parent->dentry, AUDIT_INODE_PARENT);
391172c4 2572 }
9883d185 2573 restore_nameidata();
0ee50b47
DK
2574 return retval;
2575}
2576
79714f72 2577/* does lookup, returns the object with parent locked */
0766ec82 2578static struct dentry *__kern_path_locked(struct filename *name, struct path *path)
5590ff0d 2579{
5c31b6ce 2580 struct dentry *d;
391172c4 2581 struct qstr last;
0ee50b47 2582 int type, error;
51689104 2583
c5f563f9 2584 error = filename_parentat(AT_FDCWD, name, 0, path, &last, &type);
0ee50b47
DK
2585 if (error)
2586 return ERR_PTR(error);
5c31b6ce 2587 if (unlikely(type != LAST_NORM)) {
391172c4 2588 path_put(path);
5c31b6ce 2589 return ERR_PTR(-EINVAL);
79714f72 2590 }
5955102c 2591 inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
391172c4 2592 d = __lookup_hash(&last, path->dentry, 0);
79714f72 2593 if (IS_ERR(d)) {
5955102c 2594 inode_unlock(path->dentry->d_inode);
391172c4 2595 path_put(path);
79714f72 2596 }
79714f72 2597 return d;
5590ff0d
UD
2598}
2599
0766ec82
SB
2600struct dentry *kern_path_locked(const char *name, struct path *path)
2601{
2602 struct filename *filename = getname_kernel(name);
2603 struct dentry *res = __kern_path_locked(filename, path);
2604
2605 putname(filename);
2606 return res;
2607}
2608
d1811465
AV
2609int kern_path(const char *name, unsigned int flags, struct path *path)
2610{
794ebcea
SB
2611 struct filename *filename = getname_kernel(name);
2612 int ret = filename_lookup(AT_FDCWD, filename, flags, path, NULL);
2613
2614 putname(filename);
2615 return ret;
2616
d1811465 2617}
4d359507 2618EXPORT_SYMBOL(kern_path);
d1811465 2619
16f18200
JJS
2620/**
2621 * vfs_path_lookup - lookup a file path relative to a dentry-vfsmount pair
2622 * @dentry: pointer to dentry of the base directory
2623 * @mnt: pointer to vfs mount of the base directory
2624 * @name: pointer to file name
2625 * @flags: lookup flags
e0a01249 2626 * @path: pointer to struct path to fill
16f18200
JJS
2627 */
2628int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt,
2629 const char *name, unsigned int flags,
e0a01249 2630 struct path *path)
16f18200 2631{
794ebcea 2632 struct filename *filename;
9ad1aaa6 2633 struct path root = {.mnt = mnt, .dentry = dentry};
794ebcea
SB
2634 int ret;
2635
2636 filename = getname_kernel(name);
9ad1aaa6 2637 /* the first argument of filename_lookup() is ignored with root */
794ebcea
SB
2638 ret = filename_lookup(AT_FDCWD, filename, flags, path, &root);
2639 putname(filename);
2640 return ret;
16f18200 2641}
4d359507 2642EXPORT_SYMBOL(vfs_path_lookup);
16f18200 2643
c2fd68b6
CB
2644static int lookup_one_common(struct user_namespace *mnt_userns,
2645 const char *name, struct dentry *base, int len,
2646 struct qstr *this)
057f6c01 2647{
3c95f0dc
AV
2648 this->name = name;
2649 this->len = len;
2650 this->hash = full_name_hash(base, name, len);
6a96ba54 2651 if (!len)
3c95f0dc 2652 return -EACCES;
6a96ba54 2653
21d8a15a
AV
2654 if (unlikely(name[0] == '.')) {
2655 if (len < 2 || (len == 2 && name[1] == '.'))
3c95f0dc 2656 return -EACCES;
21d8a15a
AV
2657 }
2658
6a96ba54 2659 while (len--) {
3c95f0dc 2660 unsigned int c = *(const unsigned char *)name++;
6a96ba54 2661 if (c == '/' || c == '\0')
3c95f0dc 2662 return -EACCES;
6a96ba54 2663 }
5a202bcd
AV
2664 /*
2665 * See if the low-level filesystem might want
2666 * to use its own hash..
2667 */
2668 if (base->d_flags & DCACHE_OP_HASH) {
3c95f0dc 2669 int err = base->d_op->d_hash(base, this);
5a202bcd 2670 if (err < 0)
3c95f0dc 2671 return err;
5a202bcd 2672 }
eead1911 2673
c2fd68b6 2674 return inode_permission(mnt_userns, base->d_inode, MAY_EXEC);
3c95f0dc
AV
2675}
2676
0da0b7fd
DH
2677/**
2678 * try_lookup_one_len - filesystem helper to lookup single pathname component
2679 * @name: pathname component to lookup
2680 * @base: base directory to lookup from
2681 * @len: maximum length @len should be interpreted to
2682 *
2683 * Look up a dentry by name in the dcache, returning NULL if it does not
2684 * currently exist. The function does not try to create a dentry.
2685 *
2686 * Note that this routine is purely a helper for filesystem usage and should
2687 * not be called by generic code.
2688 *
2689 * The caller must hold base->i_mutex.
2690 */
2691struct dentry *try_lookup_one_len(const char *name, struct dentry *base, int len)
2692{
2693 struct qstr this;
2694 int err;
2695
2696 WARN_ON_ONCE(!inode_is_locked(base->d_inode));
2697
c2fd68b6 2698 err = lookup_one_common(&init_user_ns, name, base, len, &this);
0da0b7fd
DH
2699 if (err)
2700 return ERR_PTR(err);
2701
2702 return lookup_dcache(&this, base, 0);
2703}
2704EXPORT_SYMBOL(try_lookup_one_len);
2705
3c95f0dc
AV
2706/**
2707 * lookup_one_len - filesystem helper to lookup single pathname component
2708 * @name: pathname component to lookup
2709 * @base: base directory to lookup from
2710 * @len: maximum length @len should be interpreted to
2711 *
2712 * Note that this routine is purely a helper for filesystem usage and should
2713 * not be called by generic code.
2714 *
2715 * The caller must hold base->i_mutex.
2716 */
2717struct dentry *lookup_one_len(const char *name, struct dentry *base, int len)
2718{
8613a209 2719 struct dentry *dentry;
3c95f0dc
AV
2720 struct qstr this;
2721 int err;
2722
2723 WARN_ON_ONCE(!inode_is_locked(base->d_inode));
2724
c2fd68b6 2725 err = lookup_one_common(&init_user_ns, name, base, len, &this);
cda309de
MS
2726 if (err)
2727 return ERR_PTR(err);
2728
8613a209
AV
2729 dentry = lookup_dcache(&this, base, 0);
2730 return dentry ? dentry : __lookup_slow(&this, base, 0);
057f6c01 2731}
4d359507 2732EXPORT_SYMBOL(lookup_one_len);
057f6c01 2733
c2fd68b6
CB
2734/**
2735 * lookup_one - filesystem helper to lookup single pathname component
2736 * @mnt_userns: user namespace of the mount the lookup is performed from
2737 * @name: pathname component to lookup
2738 * @base: base directory to lookup from
2739 * @len: maximum length @len should be interpreted to
2740 *
2741 * Note that this routine is purely a helper for filesystem usage and should
2742 * not be called by generic code.
2743 *
2744 * The caller must hold base->i_mutex.
2745 */
2746struct dentry *lookup_one(struct user_namespace *mnt_userns, const char *name,
2747 struct dentry *base, int len)
2748{
2749 struct dentry *dentry;
2750 struct qstr this;
2751 int err;
2752
2753 WARN_ON_ONCE(!inode_is_locked(base->d_inode));
2754
2755 err = lookup_one_common(mnt_userns, name, base, len, &this);
2756 if (err)
2757 return ERR_PTR(err);
2758
2759 dentry = lookup_dcache(&this, base, 0);
2760 return dentry ? dentry : __lookup_slow(&this, base, 0);
2761}
2762EXPORT_SYMBOL(lookup_one);
2763
bbddca8e 2764/**
00675017
CB
2765 * lookup_one_unlocked - filesystem helper to lookup single pathname component
2766 * @mnt_userns: idmapping of the mount the lookup is performed from
bbddca8e
N
2767 * @name: pathname component to lookup
2768 * @base: base directory to lookup from
2769 * @len: maximum length @len should be interpreted to
2770 *
2771 * Note that this routine is purely a helper for filesystem usage and should
2772 * not be called by generic code.
2773 *
2774 * Unlike lookup_one_len, it should be called without the parent
2775 * i_mutex held, and will take the i_mutex itself if necessary.
2776 */
00675017
CB
2777struct dentry *lookup_one_unlocked(struct user_namespace *mnt_userns,
2778 const char *name, struct dentry *base,
2779 int len)
bbddca8e
N
2780{
2781 struct qstr this;
bbddca8e 2782 int err;
20d00ee8 2783 struct dentry *ret;
bbddca8e 2784
00675017 2785 err = lookup_one_common(mnt_userns, name, base, len, &this);
bbddca8e
N
2786 if (err)
2787 return ERR_PTR(err);
2788
20d00ee8
LT
2789 ret = lookup_dcache(&this, base, 0);
2790 if (!ret)
2791 ret = lookup_slow(&this, base, 0);
2792 return ret;
bbddca8e 2793}
00675017
CB
2794EXPORT_SYMBOL(lookup_one_unlocked);
2795
2796/**
2797 * lookup_one_positive_unlocked - filesystem helper to lookup single
2798 * pathname component
2799 * @mnt_userns: idmapping of the mount the lookup is performed from
2800 * @name: pathname component to lookup
2801 * @base: base directory to lookup from
2802 * @len: maximum length @len should be interpreted to
2803 *
2804 * This helper will yield ERR_PTR(-ENOENT) on negatives. The helper returns
2805 * known positive or ERR_PTR(). This is what most of the users want.
2806 *
2807 * Note that pinned negative with unlocked parent _can_ become positive at any
2808 * time, so callers of lookup_one_unlocked() need to be very careful; pinned
2809 * positives have >d_inode stable, so this one avoids such problems.
2810 *
2811 * Note that this routine is purely a helper for filesystem usage and should
2812 * not be called by generic code.
2813 *
2814 * The helper should be called without i_mutex held.
2815 */
2816struct dentry *lookup_one_positive_unlocked(struct user_namespace *mnt_userns,
2817 const char *name,
2818 struct dentry *base, int len)
2819{
2820 struct dentry *ret = lookup_one_unlocked(mnt_userns, name, base, len);
2821
2822 if (!IS_ERR(ret) && d_flags_negative(smp_load_acquire(&ret->d_flags))) {
2823 dput(ret);
2824 ret = ERR_PTR(-ENOENT);
2825 }
2826 return ret;
2827}
2828EXPORT_SYMBOL(lookup_one_positive_unlocked);
2829
2830/**
2831 * lookup_one_len_unlocked - filesystem helper to lookup single pathname component
2832 * @name: pathname component to lookup
2833 * @base: base directory to lookup from
2834 * @len: maximum length @len should be interpreted to
2835 *
2836 * Note that this routine is purely a helper for filesystem usage and should
2837 * not be called by generic code.
2838 *
2839 * Unlike lookup_one_len, it should be called without the parent
2840 * i_mutex held, and will take the i_mutex itself if necessary.
2841 */
2842struct dentry *lookup_one_len_unlocked(const char *name,
2843 struct dentry *base, int len)
2844{
2845 return lookup_one_unlocked(&init_user_ns, name, base, len);
2846}
bbddca8e
N
2847EXPORT_SYMBOL(lookup_one_len_unlocked);
2848
6c2d4798
AV
2849/*
2850 * Like lookup_one_len_unlocked(), except that it yields ERR_PTR(-ENOENT)
2851 * on negatives. Returns known positive or ERR_PTR(); that's what
2852 * most of the users want. Note that pinned negative with unlocked parent
2853 * _can_ become positive at any time, so callers of lookup_one_len_unlocked()
2854 * need to be very careful; pinned positives have ->d_inode stable, so
2855 * this one avoids such problems.
2856 */
2857struct dentry *lookup_positive_unlocked(const char *name,
2858 struct dentry *base, int len)
2859{
00675017 2860 return lookup_one_positive_unlocked(&init_user_ns, name, base, len);
6c2d4798
AV
2861}
2862EXPORT_SYMBOL(lookup_positive_unlocked);
2863
eedf265a
EB
2864#ifdef CONFIG_UNIX98_PTYS
2865int path_pts(struct path *path)
2866{
2867 /* Find something mounted on "pts" in the same directory as
2868 * the input path.
2869 */
a6a7eb76
AV
2870 struct dentry *parent = dget_parent(path->dentry);
2871 struct dentry *child;
19f6028a 2872 struct qstr this = QSTR_INIT("pts", 3);
eedf265a 2873
a6a7eb76
AV
2874 if (unlikely(!path_connected(path->mnt, parent))) {
2875 dput(parent);
63b27720 2876 return -ENOENT;
a6a7eb76 2877 }
63b27720
AV
2878 dput(path->dentry);
2879 path->dentry = parent;
eedf265a
EB
2880 child = d_hash_and_lookup(parent, &this);
2881 if (!child)
2882 return -ENOENT;
2883
2884 path->dentry = child;
2885 dput(parent);
19f6028a 2886 follow_down(path);
eedf265a
EB
2887 return 0;
2888}
2889#endif
2890
1fa1e7f6
AW
2891int user_path_at_empty(int dfd, const char __user *name, unsigned flags,
2892 struct path *path, int *empty)
1da177e4 2893{
794ebcea
SB
2894 struct filename *filename = getname_flags(name, flags, empty);
2895 int ret = filename_lookup(dfd, filename, flags, path, NULL);
2896
2897 putname(filename);
2898 return ret;
1da177e4 2899}
b853a161 2900EXPORT_SYMBOL(user_path_at_empty);
1fa1e7f6 2901
ba73d987
CB
2902int __check_sticky(struct user_namespace *mnt_userns, struct inode *dir,
2903 struct inode *inode)
1da177e4 2904{
8e96e3b7 2905 kuid_t fsuid = current_fsuid();
da9592ed 2906
ba73d987 2907 if (uid_eq(i_uid_into_mnt(mnt_userns, inode), fsuid))
1da177e4 2908 return 0;
ba73d987 2909 if (uid_eq(i_uid_into_mnt(mnt_userns, dir), fsuid))
1da177e4 2910 return 0;
ba73d987 2911 return !capable_wrt_inode_uidgid(mnt_userns, inode, CAP_FOWNER);
1da177e4 2912}
cbdf35bc 2913EXPORT_SYMBOL(__check_sticky);
1da177e4
LT
2914
2915/*
2916 * Check whether we can remove a link victim from directory dir, check
2917 * whether the type of victim is right.
2918 * 1. We can't do it if dir is read-only (done in permission())
2919 * 2. We should have write and exec permissions on dir
2920 * 3. We can't remove anything from append-only dir
2921 * 4. We can't do anything with immutable dir (done in permission())
2922 * 5. If the sticky bit on dir is set we should either
2923 * a. be owner of dir, or
2924 * b. be owner of victim, or
2925 * c. have CAP_FOWNER capability
2926 * 6. If the victim is append-only or immutable we can't do antyhing with
2927 * links pointing to it.
0bd23d09
EB
2928 * 7. If the victim has an unknown uid or gid we can't change the inode.
2929 * 8. If we were asked to remove a directory and victim isn't one - ENOTDIR.
2930 * 9. If we were asked to remove a non-directory and victim isn't one - EISDIR.
2931 * 10. We can't remove a root or mountpoint.
2932 * 11. We don't allow removal of NFS sillyrenamed files; it's handled by
1da177e4
LT
2933 * nfs_async_unlink().
2934 */
ba73d987
CB
2935static int may_delete(struct user_namespace *mnt_userns, struct inode *dir,
2936 struct dentry *victim, bool isdir)
1da177e4 2937{
63afdfc7 2938 struct inode *inode = d_backing_inode(victim);
1da177e4
LT
2939 int error;
2940
b18825a7 2941 if (d_is_negative(victim))
1da177e4 2942 return -ENOENT;
b18825a7 2943 BUG_ON(!inode);
1da177e4
LT
2944
2945 BUG_ON(victim->d_parent->d_inode != dir);
593d1ce8
EB
2946
2947 /* Inode writeback is not safe when the uid or gid are invalid. */
ba73d987
CB
2948 if (!uid_valid(i_uid_into_mnt(mnt_userns, inode)) ||
2949 !gid_valid(i_gid_into_mnt(mnt_userns, inode)))
593d1ce8
EB
2950 return -EOVERFLOW;
2951
4fa6b5ec 2952 audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
1da177e4 2953
ba73d987 2954 error = inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
1da177e4
LT
2955 if (error)
2956 return error;
2957 if (IS_APPEND(dir))
2958 return -EPERM;
b18825a7 2959
ba73d987
CB
2960 if (check_sticky(mnt_userns, dir, inode) || IS_APPEND(inode) ||
2961 IS_IMMUTABLE(inode) || IS_SWAPFILE(inode) ||
2962 HAS_UNMAPPED_ID(mnt_userns, inode))
1da177e4
LT
2963 return -EPERM;
2964 if (isdir) {
44b1d530 2965 if (!d_is_dir(victim))
1da177e4
LT
2966 return -ENOTDIR;
2967 if (IS_ROOT(victim))
2968 return -EBUSY;
44b1d530 2969 } else if (d_is_dir(victim))
1da177e4
LT
2970 return -EISDIR;
2971 if (IS_DEADDIR(dir))
2972 return -ENOENT;
2973 if (victim->d_flags & DCACHE_NFSFS_RENAMED)
2974 return -EBUSY;
2975 return 0;
2976}
2977
2978/* Check whether we can create an object with dentry child in directory
2979 * dir.
2980 * 1. We can't do it if child already exists (open has special treatment for
2981 * this case, but since we are inlined it's OK)
2982 * 2. We can't do it if dir is read-only (done in permission())
036d5236
EB
2983 * 3. We can't do it if the fs can't represent the fsuid or fsgid.
2984 * 4. We should have write and exec permissions on dir
2985 * 5. We can't do it if dir is immutable (done in permission())
1da177e4 2986 */
ba73d987
CB
2987static inline int may_create(struct user_namespace *mnt_userns,
2988 struct inode *dir, struct dentry *child)
1da177e4 2989{
14e972b4 2990 audit_inode_child(dir, child, AUDIT_TYPE_CHILD_CREATE);
1da177e4
LT
2991 if (child->d_inode)
2992 return -EEXIST;
2993 if (IS_DEADDIR(dir))
2994 return -ENOENT;
8e538913 2995 if (!fsuidgid_has_mapping(dir->i_sb, mnt_userns))
036d5236 2996 return -EOVERFLOW;
8e538913 2997
ba73d987 2998 return inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
1da177e4
LT
2999}
3000
1da177e4
LT
3001/*
3002 * p1 and p2 should be directories on the same fs.
3003 */
3004struct dentry *lock_rename(struct dentry *p1, struct dentry *p2)
3005{
3006 struct dentry *p;
3007
3008 if (p1 == p2) {
5955102c 3009 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
1da177e4
LT
3010 return NULL;
3011 }
3012
fc64005c 3013 mutex_lock(&p1->d_sb->s_vfs_rename_mutex);
1da177e4 3014
e2761a11
OH
3015 p = d_ancestor(p2, p1);
3016 if (p) {
5955102c
AV
3017 inode_lock_nested(p2->d_inode, I_MUTEX_PARENT);
3018 inode_lock_nested(p1->d_inode, I_MUTEX_CHILD);
e2761a11 3019 return p;
1da177e4
LT
3020 }
3021
e2761a11
OH
3022 p = d_ancestor(p1, p2);
3023 if (p) {
5955102c
AV
3024 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
3025 inode_lock_nested(p2->d_inode, I_MUTEX_CHILD);
e2761a11 3026 return p;
1da177e4
LT
3027 }
3028
5955102c
AV
3029 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
3030 inode_lock_nested(p2->d_inode, I_MUTEX_PARENT2);
1da177e4
LT
3031 return NULL;
3032}
4d359507 3033EXPORT_SYMBOL(lock_rename);
1da177e4
LT
3034
3035void unlock_rename(struct dentry *p1, struct dentry *p2)
3036{
5955102c 3037 inode_unlock(p1->d_inode);
1da177e4 3038 if (p1 != p2) {
5955102c 3039 inode_unlock(p2->d_inode);
fc64005c 3040 mutex_unlock(&p1->d_sb->s_vfs_rename_mutex);
1da177e4
LT
3041 }
3042}
4d359507 3043EXPORT_SYMBOL(unlock_rename);
1da177e4 3044
1639a49c
YX
3045/**
3046 * mode_strip_umask - handle vfs umask stripping
3047 * @dir: parent directory of the new inode
3048 * @mode: mode of the new inode to be created in @dir
3049 *
3050 * Umask stripping depends on whether or not the filesystem supports POSIX
3051 * ACLs. If the filesystem doesn't support it umask stripping is done directly
3052 * in here. If the filesystem does support POSIX ACLs umask stripping is
3053 * deferred until the filesystem calls posix_acl_create().
3054 *
3055 * Returns: mode
3056 */
3057static inline umode_t mode_strip_umask(const struct inode *dir, umode_t mode)
3058{
3059 if (!IS_POSIXACL(dir))
3060 mode &= ~current_umask();
3061 return mode;
3062}
3063
3064/**
3065 * vfs_prepare_mode - prepare the mode to be used for a new inode
3066 * @mnt_userns: user namespace of the mount the inode was found from
3067 * @dir: parent directory of the new inode
3068 * @mode: mode of the new inode
3069 * @mask_perms: allowed permission by the vfs
3070 * @type: type of file to be created
3071 *
3072 * This helper consolidates and enforces vfs restrictions on the @mode of a new
3073 * object to be created.
3074 *
3075 * Umask stripping depends on whether the filesystem supports POSIX ACLs (see
3076 * the kernel documentation for mode_strip_umask()). Moving umask stripping
3077 * after setgid stripping allows the same ordering for both non-POSIX ACL and
3078 * POSIX ACL supporting filesystems.
3079 *
3080 * Note that it's currently valid for @type to be 0 if a directory is created.
3081 * Filesystems raise that flag individually and we need to check whether each
3082 * filesystem can deal with receiving S_IFDIR from the vfs before we enforce a
3083 * non-zero type.
3084 *
3085 * Returns: mode to be passed to the filesystem
3086 */
3087static inline umode_t vfs_prepare_mode(struct user_namespace *mnt_userns,
3088 const struct inode *dir, umode_t mode,
3089 umode_t mask_perms, umode_t type)
3090{
3091 mode = mode_strip_sgid(mnt_userns, dir, mode);
3092 mode = mode_strip_umask(dir, mode);
3093
3094 /*
3095 * Apply the vfs mandated allowed permission mask and set the type of
3096 * file to be created before we call into the filesystem.
3097 */
3098 mode &= (mask_perms & ~S_IFMT);
3099 mode |= (type & S_IFMT);
3100
3101 return mode;
3102}
3103
6521f891
CB
3104/**
3105 * vfs_create - create new file
3106 * @mnt_userns: user namespace of the mount the inode was found from
3107 * @dir: inode of @dentry
3108 * @dentry: pointer to dentry of the base directory
3109 * @mode: mode of the new file
3110 * @want_excl: whether the file must not yet exist
3111 *
3112 * Create a new file.
3113 *
3114 * If the inode has been found through an idmapped mount the user namespace of
3115 * the vfsmount must be passed through @mnt_userns. This function will then take
3116 * care to map the inode according to @mnt_userns before checking permissions.
3117 * On non-idmapped mounts or if permission checking is to be performed on the
3118 * raw inode simply passs init_user_ns.
3119 */
3120int vfs_create(struct user_namespace *mnt_userns, struct inode *dir,
3121 struct dentry *dentry, umode_t mode, bool want_excl)
1da177e4 3122{
6521f891 3123 int error = may_create(mnt_userns, dir, dentry);
1da177e4
LT
3124 if (error)
3125 return error;
3126
acfa4380 3127 if (!dir->i_op->create)
1da177e4 3128 return -EACCES; /* shouldn't it be ENOSYS? */
1639a49c
YX
3129
3130 mode = vfs_prepare_mode(mnt_userns, dir, mode, S_IALLUGO, S_IFREG);
1da177e4
LT
3131 error = security_inode_create(dir, dentry, mode);
3132 if (error)
3133 return error;
549c7297 3134 error = dir->i_op->create(mnt_userns, dir, dentry, mode, want_excl);
a74574aa 3135 if (!error)
f38aa942 3136 fsnotify_create(dir, dentry);
1da177e4
LT
3137 return error;
3138}
4d359507 3139EXPORT_SYMBOL(vfs_create);
1da177e4 3140
8e6c848e
AV
3141int vfs_mkobj(struct dentry *dentry, umode_t mode,
3142 int (*f)(struct dentry *, umode_t, void *),
3143 void *arg)
3144{
3145 struct inode *dir = dentry->d_parent->d_inode;
ba73d987 3146 int error = may_create(&init_user_ns, dir, dentry);
8e6c848e
AV
3147 if (error)
3148 return error;
3149
3150 mode &= S_IALLUGO;
3151 mode |= S_IFREG;
3152 error = security_inode_create(dir, dentry, mode);
3153 if (error)
3154 return error;
3155 error = f(dentry, mode, arg);
3156 if (!error)
3157 fsnotify_create(dir, dentry);
3158 return error;
3159}
3160EXPORT_SYMBOL(vfs_mkobj);
3161
a2982cc9
EB
3162bool may_open_dev(const struct path *path)
3163{
3164 return !(path->mnt->mnt_flags & MNT_NODEV) &&
3165 !(path->mnt->mnt_sb->s_iflags & SB_I_NODEV);
3166}
3167
ba73d987
CB
3168static int may_open(struct user_namespace *mnt_userns, const struct path *path,
3169 int acc_mode, int flag)
1da177e4 3170{
3fb64190 3171 struct dentry *dentry = path->dentry;
1da177e4
LT
3172 struct inode *inode = dentry->d_inode;
3173 int error;
3174
3175 if (!inode)
3176 return -ENOENT;
3177
c8fe8f30
CH
3178 switch (inode->i_mode & S_IFMT) {
3179 case S_IFLNK:
1da177e4 3180 return -ELOOP;
c8fe8f30 3181 case S_IFDIR:
fc4177be 3182 if (acc_mode & MAY_WRITE)
c8fe8f30 3183 return -EISDIR;
fc4177be
KC
3184 if (acc_mode & MAY_EXEC)
3185 return -EACCES;
c8fe8f30
CH
3186 break;
3187 case S_IFBLK:
3188 case S_IFCHR:
a2982cc9 3189 if (!may_open_dev(path))
1da177e4 3190 return -EACCES;
633fb6ac 3191 fallthrough;
c8fe8f30
CH
3192 case S_IFIFO:
3193 case S_IFSOCK:
633fb6ac
KC
3194 if (acc_mode & MAY_EXEC)
3195 return -EACCES;
1da177e4 3196 flag &= ~O_TRUNC;
c8fe8f30 3197 break;
0fd338b2
KC
3198 case S_IFREG:
3199 if ((acc_mode & MAY_EXEC) && path_noexec(path))
3200 return -EACCES;
3201 break;
4a3fd211 3202 }
b41572e9 3203
ba73d987 3204 error = inode_permission(mnt_userns, inode, MAY_OPEN | acc_mode);
b41572e9
DH
3205 if (error)
3206 return error;
6146f0d5 3207
1da177e4
LT
3208 /*
3209 * An append-only file must be opened in append mode for writing.
3210 */
3211 if (IS_APPEND(inode)) {
8737c930 3212 if ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND))
7715b521 3213 return -EPERM;
1da177e4 3214 if (flag & O_TRUNC)
7715b521 3215 return -EPERM;
1da177e4
LT
3216 }
3217
3218 /* O_NOATIME can only be set by the owner or superuser */
ba73d987 3219 if (flag & O_NOATIME && !inode_owner_or_capable(mnt_userns, inode))
7715b521 3220 return -EPERM;
1da177e4 3221
f3c7691e 3222 return 0;
7715b521 3223}
1da177e4 3224
549c7297 3225static int handle_truncate(struct user_namespace *mnt_userns, struct file *filp)
7715b521 3226{
f0bb5aaf 3227 const struct path *path = &filp->f_path;
7715b521
AV
3228 struct inode *inode = path->dentry->d_inode;
3229 int error = get_write_access(inode);
3230 if (error)
3231 return error;
482e0007 3232
f7e33bdb 3233 error = security_path_truncate(path);
7715b521 3234 if (!error) {
549c7297 3235 error = do_truncate(mnt_userns, path->dentry, 0,
7715b521 3236 ATTR_MTIME|ATTR_CTIME|ATTR_OPEN,
e1181ee6 3237 filp);
7715b521
AV
3238 }
3239 put_write_access(inode);
acd0c935 3240 return error;
1da177e4
LT
3241}
3242
d57999e1
DH
3243static inline int open_to_namei_flags(int flag)
3244{
8a5e929d
AV
3245 if ((flag & O_ACCMODE) == 3)
3246 flag--;
d57999e1
DH
3247 return flag;
3248}
3249
ba73d987
CB
3250static int may_o_create(struct user_namespace *mnt_userns,
3251 const struct path *dir, struct dentry *dentry,
3252 umode_t mode)
d18e9008
MS
3253{
3254 int error = security_path_mknod(dir, dentry, mode, 0);
3255 if (error)
3256 return error;
3257
8e538913 3258 if (!fsuidgid_has_mapping(dir->dentry->d_sb, mnt_userns))
1328c727
SF
3259 return -EOVERFLOW;
3260
ba73d987 3261 error = inode_permission(mnt_userns, dir->dentry->d_inode,
47291baa 3262 MAY_WRITE | MAY_EXEC);
d18e9008
MS
3263 if (error)
3264 return error;
3265
3266 return security_inode_create(dir->dentry->d_inode, dentry, mode);
3267}
3268
1acf0af9
DH
3269/*
3270 * Attempt to atomically look up, create and open a file from a negative
3271 * dentry.
3272 *
3273 * Returns 0 if successful. The file will have been created and attached to
3274 * @file by the filesystem calling finish_open().
3275 *
00a07c15
AV
3276 * If the file was looked up only or didn't need creating, FMODE_OPENED won't
3277 * be set. The caller will need to perform the open themselves. @path will
3278 * have been updated to point to the new dentry. This may be negative.
1acf0af9
DH
3279 *
3280 * Returns an error code otherwise.
3281 */
239eb983
AV
3282static struct dentry *atomic_open(struct nameidata *nd, struct dentry *dentry,
3283 struct file *file,
239eb983 3284 int open_flag, umode_t mode)
d18e9008 3285{
384f26e2 3286 struct dentry *const DENTRY_NOT_SET = (void *) -1UL;
d18e9008 3287 struct inode *dir = nd->path.dentry->d_inode;
d18e9008 3288 int error;
d18e9008 3289
d18e9008
MS
3290 if (nd->flags & LOOKUP_DIRECTORY)
3291 open_flag |= O_DIRECTORY;
3292
30d90494
AV
3293 file->f_path.dentry = DENTRY_NOT_SET;
3294 file->f_path.mnt = nd->path.mnt;
0fb1ea09 3295 error = dir->i_op->atomic_open(dir, dentry, file,
44907d79 3296 open_to_namei_flags(open_flag), mode);
6fbd0714 3297 d_lookup_done(dentry);
384f26e2 3298 if (!error) {
64e1ac4d 3299 if (file->f_mode & FMODE_OPENED) {
6fb968cd
AV
3300 if (unlikely(dentry != file->f_path.dentry)) {
3301 dput(dentry);
3302 dentry = dget(file->f_path.dentry);
3303 }
64e1ac4d 3304 } else if (WARN_ON(file->f_path.dentry == DENTRY_NOT_SET)) {
2675a4eb 3305 error = -EIO;
03da633a 3306 } else {
384f26e2
AV
3307 if (file->f_path.dentry) {
3308 dput(dentry);
3309 dentry = file->f_path.dentry;
03da633a 3310 }
239eb983 3311 if (unlikely(d_is_negative(dentry)))
a01e718f 3312 error = -ENOENT;
62b2ce96 3313 }
d18e9008 3314 }
239eb983
AV
3315 if (error) {
3316 dput(dentry);
3317 dentry = ERR_PTR(error);
3318 }
3319 return dentry;
d18e9008
MS
3320}
3321
d58ffd35 3322/*
1acf0af9 3323 * Look up and maybe create and open the last component.
d58ffd35 3324 *
00a07c15 3325 * Must be called with parent locked (exclusive in O_CREAT case).
1acf0af9 3326 *
00a07c15
AV
3327 * Returns 0 on success, that is, if
3328 * the file was successfully atomically created (if necessary) and opened, or
3329 * the file was not completely opened at this time, though lookups and
3330 * creations were performed.
3331 * These case are distinguished by presence of FMODE_OPENED on file->f_mode.
3332 * In the latter case dentry returned in @path might be negative if O_CREAT
3333 * hadn't been specified.
1acf0af9 3334 *
00a07c15 3335 * An error code is returned on failure.
d58ffd35 3336 */
da5ebf5a
AV
3337static struct dentry *lookup_open(struct nameidata *nd, struct file *file,
3338 const struct open_flags *op,
3339 bool got_write)
d58ffd35 3340{
549c7297 3341 struct user_namespace *mnt_userns;
d58ffd35 3342 struct dentry *dir = nd->path.dentry;
54ef4872 3343 struct inode *dir_inode = dir->d_inode;
1643b43f 3344 int open_flag = op->open_flag;
d58ffd35 3345 struct dentry *dentry;
1643b43f 3346 int error, create_error = 0;
1643b43f 3347 umode_t mode = op->mode;
6fbd0714 3348 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
d58ffd35 3349
ce8644fc 3350 if (unlikely(IS_DEADDIR(dir_inode)))
da5ebf5a 3351 return ERR_PTR(-ENOENT);
d58ffd35 3352
73a09dd9 3353 file->f_mode &= ~FMODE_CREATED;
6fbd0714
AV
3354 dentry = d_lookup(dir, &nd->last);
3355 for (;;) {
3356 if (!dentry) {
3357 dentry = d_alloc_parallel(dir, &nd->last, &wq);
3358 if (IS_ERR(dentry))
da5ebf5a 3359 return dentry;
6fbd0714
AV
3360 }
3361 if (d_in_lookup(dentry))
3362 break;
d58ffd35 3363
6fbd0714
AV
3364 error = d_revalidate(dentry, nd->flags);
3365 if (likely(error > 0))
3366 break;
3367 if (error)
3368 goto out_dput;
3369 d_invalidate(dentry);
3370 dput(dentry);
3371 dentry = NULL;
3372 }
3373 if (dentry->d_inode) {
6c51e513 3374 /* Cached positive dentry: will open in f_op->open */
da5ebf5a 3375 return dentry;
6c51e513 3376 }
d18e9008 3377
1643b43f
AV
3378 /*
3379 * Checking write permission is tricky, bacuse we don't know if we are
3380 * going to actually need it: O_CREAT opens should work as long as the
3381 * file exists. But checking existence breaks atomicity. The trick is
3382 * to check access and if not granted clear O_CREAT from the flags.
3383 *
3384 * Another problem is returing the "right" error value (e.g. for an
3385 * O_EXCL open we want to return EEXIST not EROFS).
3386 */
99a4a90c
AV
3387 if (unlikely(!got_write))
3388 open_flag &= ~O_TRUNC;
549c7297 3389 mnt_userns = mnt_user_ns(nd->path.mnt);
1643b43f 3390 if (open_flag & O_CREAT) {
99a4a90c
AV
3391 if (open_flag & O_EXCL)
3392 open_flag &= ~O_TRUNC;
1639a49c 3393 mode = vfs_prepare_mode(mnt_userns, dir->d_inode, mode, mode, mode);
99a4a90c 3394 if (likely(got_write))
549c7297 3395 create_error = may_o_create(mnt_userns, &nd->path,
ba73d987 3396 dentry, mode);
99a4a90c
AV
3397 else
3398 create_error = -EROFS;
d18e9008 3399 }
99a4a90c
AV
3400 if (create_error)
3401 open_flag &= ~O_CREAT;
6ac08709 3402 if (dir_inode->i_op->atomic_open) {
d489cf9a 3403 dentry = atomic_open(nd, dentry, file, open_flag, mode);
da5ebf5a
AV
3404 if (unlikely(create_error) && dentry == ERR_PTR(-ENOENT))
3405 dentry = ERR_PTR(create_error);
3406 return dentry;
d18e9008 3407 }
54ef4872 3408
6fbd0714 3409 if (d_in_lookup(dentry)) {
12fa5e24
AV
3410 struct dentry *res = dir_inode->i_op->lookup(dir_inode, dentry,
3411 nd->flags);
6fbd0714 3412 d_lookup_done(dentry);
12fa5e24
AV
3413 if (unlikely(res)) {
3414 if (IS_ERR(res)) {
3415 error = PTR_ERR(res);
3416 goto out_dput;
3417 }
3418 dput(dentry);
3419 dentry = res;
3420 }
54ef4872
MS
3421 }
3422
d58ffd35 3423 /* Negative dentry, just create the file */
1643b43f 3424 if (!dentry->d_inode && (open_flag & O_CREAT)) {
73a09dd9 3425 file->f_mode |= FMODE_CREATED;
ce8644fc 3426 audit_inode_child(dir_inode, dentry, AUDIT_TYPE_CHILD_CREATE);
ce8644fc
AV
3427 if (!dir_inode->i_op->create) {
3428 error = -EACCES;
d58ffd35 3429 goto out_dput;
ce8644fc 3430 }
549c7297
CB
3431
3432 error = dir_inode->i_op->create(mnt_userns, dir_inode, dentry,
3433 mode, open_flag & O_EXCL);
d58ffd35
MS
3434 if (error)
3435 goto out_dput;
3436 }
1643b43f
AV
3437 if (unlikely(create_error) && !dentry->d_inode) {
3438 error = create_error;
3439 goto out_dput;
d58ffd35 3440 }
da5ebf5a 3441 return dentry;
d58ffd35
MS
3442
3443out_dput:
3444 dput(dentry);
da5ebf5a 3445 return ERR_PTR(error);
d58ffd35
MS
3446}
3447
c981a482 3448static const char *open_last_lookups(struct nameidata *nd,
3ec2eef1 3449 struct file *file, const struct open_flags *op)
fb1cc555 3450{
a1e28038 3451 struct dentry *dir = nd->path.dentry;
ca344a89 3452 int open_flag = op->open_flag;
64894cf8 3453 bool got_write = false;
254cf582 3454 unsigned seq;
a1eb3315 3455 struct inode *inode;
da5ebf5a 3456 struct dentry *dentry;
b0417d2c 3457 const char *res;
1f36f774 3458
c3e380b0
AV
3459 nd->flags |= op->intent;
3460
bc77daa7 3461 if (nd->last_type != LAST_NORM) {
56676ec3
AV
3462 if (nd->depth)
3463 put_link(nd);
ff326a32 3464 return handle_dots(nd, nd->last_type);
1f36f774 3465 }
67ee3ad2 3466
ca344a89 3467 if (!(open_flag & O_CREAT)) {
fe2d35ff
AV
3468 if (nd->last.name[nd->last.len])
3469 nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
3470 /* we _can_ be in RCU mode here */
20e34357
AV
3471 dentry = lookup_fast(nd, &inode, &seq);
3472 if (IS_ERR(dentry))
1ccac622 3473 return ERR_CAST(dentry);
20e34357 3474 if (likely(dentry))
71574865
MS
3475 goto finish_lookup;
3476
6583fe22 3477 BUG_ON(nd->flags & LOOKUP_RCU);
b6183df7
MS
3478 } else {
3479 /* create side of things */
72287417 3480 if (nd->flags & LOOKUP_RCU) {
e36cffed
JA
3481 if (!try_to_unlazy(nd))
3482 return ERR_PTR(-ECHILD);
72287417 3483 }
c9b07eab 3484 audit_inode(nd->name, dir, AUDIT_INODE_PARENT);
b6183df7 3485 /* trailing slashes? */
deb106c6 3486 if (unlikely(nd->last.name[nd->last.len]))
1ccac622 3487 return ERR_PTR(-EISDIR);
b6183df7 3488 }
a2c36b45 3489
9cf843e3 3490 if (open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) {
e36cffed 3491 got_write = !mnt_want_write(nd->path.mnt);
64894cf8
AV
3492 /*
3493 * do _not_ fail yet - we might not need that or fail with
3494 * a different error; let lookup_open() decide; we'll be
3495 * dropping this one anyway.
3496 */
3497 }
9cf843e3
AV
3498 if (open_flag & O_CREAT)
3499 inode_lock(dir->d_inode);
3500 else
3501 inode_lock_shared(dir->d_inode);
da5ebf5a 3502 dentry = lookup_open(nd, file, op, got_write);
f7bb959d
AV
3503 if (!IS_ERR(dentry) && (file->f_mode & FMODE_CREATED))
3504 fsnotify_create(dir->d_inode, dentry);
9cf843e3
AV
3505 if (open_flag & O_CREAT)
3506 inode_unlock(dir->d_inode);
3507 else
3508 inode_unlock_shared(dir->d_inode);
a1e28038 3509
c981a482 3510 if (got_write)
59e96e65 3511 mnt_drop_write(nd->path.mnt);
d18e9008 3512
59e96e65
AV
3513 if (IS_ERR(dentry))
3514 return ERR_CAST(dentry);
3515
973d4b73 3516 if (file->f_mode & (FMODE_OPENED | FMODE_CREATED)) {
e73cabff
AV
3517 dput(nd->path.dentry);
3518 nd->path.dentry = dentry;
c981a482 3519 return NULL;
fb1cc555
AV
3520 }
3521
20e34357 3522finish_lookup:
56676ec3
AV
3523 if (nd->depth)
3524 put_link(nd);
8c4efe22 3525 res = step_into(nd, WALK_TRAILING, dentry, inode, seq);
ff326a32 3526 if (unlikely(res))
b0417d2c 3527 nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL);
ff326a32 3528 return res;
c981a482
AV
3529}
3530
3531/*
3532 * Handle the last step of open()
3533 */
c5971b8c 3534static int do_open(struct nameidata *nd,
c981a482
AV
3535 struct file *file, const struct open_flags *op)
3536{
549c7297 3537 struct user_namespace *mnt_userns;
c981a482
AV
3538 int open_flag = op->open_flag;
3539 bool do_truncate;
3540 int acc_mode;
c981a482
AV
3541 int error;
3542
ff326a32
AV
3543 if (!(file->f_mode & (FMODE_OPENED | FMODE_CREATED))) {
3544 error = complete_walk(nd);
3545 if (error)
3546 return error;
3547 }
973d4b73
AV
3548 if (!(file->f_mode & FMODE_CREATED))
3549 audit_inode(nd->name, nd->path.dentry, 0);
549c7297 3550 mnt_userns = mnt_user_ns(nd->path.mnt);
30aba665 3551 if (open_flag & O_CREAT) {
b94e0b32
AV
3552 if ((open_flag & O_EXCL) && !(file->f_mode & FMODE_CREATED))
3553 return -EEXIST;
30aba665 3554 if (d_is_dir(nd->path.dentry))
c5971b8c 3555 return -EISDIR;
549c7297 3556 error = may_create_in_sticky(mnt_userns, nd,
30aba665
SM
3557 d_backing_inode(nd->path.dentry));
3558 if (unlikely(error))
c5971b8c 3559 return error;
30aba665 3560 }
44b1d530 3561 if ((nd->flags & LOOKUP_DIRECTORY) && !d_can_lookup(nd->path.dentry))
c5971b8c 3562 return -ENOTDIR;
6c0d46c4 3563
8795e7d4
AV
3564 do_truncate = false;
3565 acc_mode = op->acc_mode;
5a2d3edd
AV
3566 if (file->f_mode & FMODE_CREATED) {
3567 /* Don't check for write permission, don't truncate */
3568 open_flag &= ~O_TRUNC;
5a2d3edd 3569 acc_mode = 0;
8795e7d4 3570 } else if (d_is_reg(nd->path.dentry) && open_flag & O_TRUNC) {
0f9d1a10
AV
3571 error = mnt_want_write(nd->path.mnt);
3572 if (error)
c5971b8c 3573 return error;
8795e7d4 3574 do_truncate = true;
0f9d1a10 3575 }
549c7297 3576 error = may_open(mnt_userns, &nd->path, acc_mode, open_flag);
8795e7d4 3577 if (!error && !(file->f_mode & FMODE_OPENED))
3ad5615a 3578 error = vfs_open(&nd->path, file);
8795e7d4
AV
3579 if (!error)
3580 error = ima_file_check(file, op->acc_mode);
3581 if (!error && do_truncate)
549c7297 3582 error = handle_truncate(mnt_userns, file);
c80567c8
AV
3583 if (unlikely(error > 0)) {
3584 WARN_ON(1);
3585 error = -EINVAL;
3586 }
8795e7d4 3587 if (do_truncate)
0f9d1a10 3588 mnt_drop_write(nd->path.mnt);
c5971b8c 3589 return error;
fb1cc555
AV
3590}
3591
6521f891
CB
3592/**
3593 * vfs_tmpfile - create tmpfile
3594 * @mnt_userns: user namespace of the mount the inode was found from
3595 * @dentry: pointer to dentry of the base directory
3596 * @mode: mode of the new tmpfile
2111c3c0 3597 * @open_flag: flags
6521f891
CB
3598 *
3599 * Create a temporary file.
3600 *
3601 * If the inode has been found through an idmapped mount the user namespace of
3602 * the vfsmount must be passed through @mnt_userns. This function will then take
3603 * care to map the inode according to @mnt_userns before checking permissions.
3604 * On non-idmapped mounts or if permission checking is to be performed on the
3605 * raw inode simply passs init_user_ns.
3606 */
3607struct dentry *vfs_tmpfile(struct user_namespace *mnt_userns,
3608 struct dentry *dentry, umode_t mode, int open_flag)
af7bd4dc 3609{
af7bd4dc
AG
3610 struct dentry *child = NULL;
3611 struct inode *dir = dentry->d_inode;
3612 struct inode *inode;
3613 int error;
3614
3615 /* we want directory to be writable */
6521f891 3616 error = inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
af7bd4dc
AG
3617 if (error)
3618 goto out_err;
3619 error = -EOPNOTSUPP;
3620 if (!dir->i_op->tmpfile)
3621 goto out_err;
3622 error = -ENOMEM;
cdf01226 3623 child = d_alloc(dentry, &slash_name);
af7bd4dc
AG
3624 if (unlikely(!child))
3625 goto out_err;
1639a49c 3626 mode = vfs_prepare_mode(mnt_userns, dir, mode, mode, mode);
549c7297 3627 error = dir->i_op->tmpfile(mnt_userns, dir, child, mode);
af7bd4dc
AG
3628 if (error)
3629 goto out_err;
3630 error = -ENOENT;
3631 inode = child->d_inode;
3632 if (unlikely(!inode))
3633 goto out_err;
3634 if (!(open_flag & O_EXCL)) {
3635 spin_lock(&inode->i_lock);
3636 inode->i_state |= I_LINKABLE;
3637 spin_unlock(&inode->i_lock);
3638 }
a2d2329e 3639 ima_post_create_tmpfile(mnt_userns, inode);
af7bd4dc
AG
3640 return child;
3641
3642out_err:
3643 dput(child);
3644 return ERR_PTR(error);
3645}
3646EXPORT_SYMBOL(vfs_tmpfile);
3647
c8a53ee5 3648static int do_tmpfile(struct nameidata *nd, unsigned flags,
60545d0d 3649 const struct open_flags *op,
3ec2eef1 3650 struct file *file)
60545d0d 3651{
6521f891 3652 struct user_namespace *mnt_userns;
625b6d10 3653 struct dentry *child;
625b6d10 3654 struct path path;
c8a53ee5 3655 int error = path_lookupat(nd, flags | LOOKUP_DIRECTORY, &path);
60545d0d
AV
3656 if (unlikely(error))
3657 return error;
625b6d10 3658 error = mnt_want_write(path.mnt);
60545d0d
AV
3659 if (unlikely(error))
3660 goto out;
6521f891
CB
3661 mnt_userns = mnt_user_ns(path.mnt);
3662 child = vfs_tmpfile(mnt_userns, path.dentry, op->mode, op->open_flag);
af7bd4dc 3663 error = PTR_ERR(child);
684e73be 3664 if (IS_ERR(child))
60545d0d 3665 goto out2;
625b6d10
AV
3666 dput(path.dentry);
3667 path.dentry = child;
c8a53ee5 3668 audit_inode(nd->name, child, 0);
69a91c23 3669 /* Don't check for other permissions, the inode was just created */
549c7297 3670 error = may_open(mnt_userns, &path, 0, op->open_flag);
1e8f44f1
AV
3671 if (!error)
3672 error = vfs_open(&path, file);
60545d0d 3673out2:
625b6d10 3674 mnt_drop_write(path.mnt);
60545d0d 3675out:
625b6d10 3676 path_put(&path);
60545d0d
AV
3677 return error;
3678}
3679
6ac08709
AV
3680static int do_o_path(struct nameidata *nd, unsigned flags, struct file *file)
3681{
3682 struct path path;
3683 int error = path_lookupat(nd, flags, &path);
3684 if (!error) {
3685 audit_inode(nd->name, path.dentry, 0);
ae2bb293 3686 error = vfs_open(&path, file);
6ac08709
AV
3687 path_put(&path);
3688 }
3689 return error;
3690}
3691
c8a53ee5
AV
3692static struct file *path_openat(struct nameidata *nd,
3693 const struct open_flags *op, unsigned flags)
1da177e4 3694{
30d90494 3695 struct file *file;
13aab428 3696 int error;
31e6b01f 3697
ea73ea72 3698 file = alloc_empty_file(op->open_flag, current_cred());
1afc99be
AV
3699 if (IS_ERR(file))
3700 return file;
31e6b01f 3701
bb458c64 3702 if (unlikely(file->f_flags & __O_TMPFILE)) {
3ec2eef1 3703 error = do_tmpfile(nd, flags, op, file);
5f336e72 3704 } else if (unlikely(file->f_flags & O_PATH)) {
6ac08709 3705 error = do_o_path(nd, flags, file);
5f336e72
AV
3706 } else {
3707 const char *s = path_init(nd, flags);
3708 while (!(error = link_path_walk(s, nd)) &&
c5971b8c 3709 (s = open_last_lookups(nd, file, op)) != NULL)
1ccac622 3710 ;
c5971b8c
AV
3711 if (!error)
3712 error = do_open(nd, file, op);
5f336e72 3713 terminate_walk(nd);
806b681c 3714 }
7c1c01ec 3715 if (likely(!error)) {
aad888f8 3716 if (likely(file->f_mode & FMODE_OPENED))
7c1c01ec
AV
3717 return file;
3718 WARN_ON(1);
3719 error = -EINVAL;
16b1c1cd 3720 }
7c1c01ec
AV
3721 fput(file);
3722 if (error == -EOPENSTALE) {
3723 if (flags & LOOKUP_RCU)
3724 error = -ECHILD;
3725 else
3726 error = -ESTALE;
2675a4eb 3727 }
7c1c01ec 3728 return ERR_PTR(error);
1da177e4
LT
3729}
3730
669abf4e 3731struct file *do_filp_open(int dfd, struct filename *pathname,
f9652e10 3732 const struct open_flags *op)
13aab428 3733{
9883d185 3734 struct nameidata nd;
f9652e10 3735 int flags = op->lookup_flags;
13aab428
AV
3736 struct file *filp;
3737
06422964 3738 set_nameidata(&nd, dfd, pathname, NULL);
c8a53ee5 3739 filp = path_openat(&nd, op, flags | LOOKUP_RCU);
13aab428 3740 if (unlikely(filp == ERR_PTR(-ECHILD)))
c8a53ee5 3741 filp = path_openat(&nd, op, flags);
13aab428 3742 if (unlikely(filp == ERR_PTR(-ESTALE)))
c8a53ee5 3743 filp = path_openat(&nd, op, flags | LOOKUP_REVAL);
9883d185 3744 restore_nameidata();
13aab428
AV
3745 return filp;
3746}
3747
ffb37ca3 3748struct file *do_file_open_root(const struct path *root,
f9652e10 3749 const char *name, const struct open_flags *op)
73d049a4 3750{
9883d185 3751 struct nameidata nd;
73d049a4 3752 struct file *file;
51689104 3753 struct filename *filename;
bcba1e7d 3754 int flags = op->lookup_flags;
73d049a4 3755
ffb37ca3 3756 if (d_is_symlink(root->dentry) && op->intent & LOOKUP_OPEN)
73d049a4
AV
3757 return ERR_PTR(-ELOOP);
3758
51689104 3759 filename = getname_kernel(name);
a1c83681 3760 if (IS_ERR(filename))
51689104
PM
3761 return ERR_CAST(filename);
3762
06422964 3763 set_nameidata(&nd, -1, filename, root);
c8a53ee5 3764 file = path_openat(&nd, op, flags | LOOKUP_RCU);
73d049a4 3765 if (unlikely(file == ERR_PTR(-ECHILD)))
c8a53ee5 3766 file = path_openat(&nd, op, flags);
73d049a4 3767 if (unlikely(file == ERR_PTR(-ESTALE)))
c8a53ee5 3768 file = path_openat(&nd, op, flags | LOOKUP_REVAL);
9883d185 3769 restore_nameidata();
51689104 3770 putname(filename);
73d049a4
AV
3771 return file;
3772}
3773
b4a4f213
SB
3774static struct dentry *filename_create(int dfd, struct filename *name,
3775 struct path *path, unsigned int lookup_flags)
1da177e4 3776{
c663e5d8 3777 struct dentry *dentry = ERR_PTR(-EEXIST);
391172c4 3778 struct qstr last;
b3d4650d
N
3779 bool want_dir = lookup_flags & LOOKUP_DIRECTORY;
3780 unsigned int reval_flag = lookup_flags & LOOKUP_REVAL;
3781 unsigned int create_flags = LOOKUP_CREATE | LOOKUP_EXCL;
391172c4 3782 int type;
c30dabfe 3783 int err2;
1ac12b4b 3784 int error;
1ac12b4b 3785
b3d4650d 3786 error = filename_parentat(dfd, name, reval_flag, path, &last, &type);
0ee50b47
DK
3787 if (error)
3788 return ERR_PTR(error);
1da177e4 3789
c663e5d8
CH
3790 /*
3791 * Yucky last component or no last component at all?
3792 * (foo/., foo/.., /////)
3793 */
5c31b6ce 3794 if (unlikely(type != LAST_NORM))
ed75e95d 3795 goto out;
c663e5d8 3796
c30dabfe 3797 /* don't fail immediately if it's r/o, at least try to report other errors */
391172c4 3798 err2 = mnt_want_write(path->mnt);
c663e5d8 3799 /*
b3d4650d
N
3800 * Do the final lookup. Suppress 'create' if there is a trailing
3801 * '/', and a directory wasn't requested.
c663e5d8 3802 */
b3d4650d
N
3803 if (last.name[last.len] && !want_dir)
3804 create_flags = 0;
5955102c 3805 inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
b3d4650d 3806 dentry = __lookup_hash(&last, path->dentry, reval_flag | create_flags);
1da177e4 3807 if (IS_ERR(dentry))
a8104a9f 3808 goto unlock;
c663e5d8 3809
a8104a9f 3810 error = -EEXIST;
b18825a7 3811 if (d_is_positive(dentry))
a8104a9f 3812 goto fail;
b18825a7 3813
c663e5d8
CH
3814 /*
3815 * Special case - lookup gave negative, but... we had foo/bar/
3816 * From the vfs_mknod() POV we just have a negative dentry -
3817 * all is fine. Let's be bastards - you had / on the end, you've
3818 * been asking for (non-existent) directory. -ENOENT for you.
3819 */
b3d4650d 3820 if (unlikely(!create_flags)) {
a8104a9f 3821 error = -ENOENT;
ed75e95d 3822 goto fail;
e9baf6e5 3823 }
c30dabfe
JK
3824 if (unlikely(err2)) {
3825 error = err2;
a8104a9f 3826 goto fail;
c30dabfe 3827 }
1da177e4 3828 return dentry;
1da177e4 3829fail:
a8104a9f
AV
3830 dput(dentry);
3831 dentry = ERR_PTR(error);
3832unlock:
5955102c 3833 inode_unlock(path->dentry->d_inode);
c30dabfe 3834 if (!err2)
391172c4 3835 mnt_drop_write(path->mnt);
ed75e95d 3836out:
391172c4 3837 path_put(path);
1da177e4
LT
3838 return dentry;
3839}
fa14a0b8 3840
b4a4f213 3841struct dentry *kern_path_create(int dfd, const char *pathname,
584d3226
DK
3842 struct path *path, unsigned int lookup_flags)
3843{
b4a4f213
SB
3844 struct filename *filename = getname_kernel(pathname);
3845 struct dentry *res = filename_create(dfd, filename, path, lookup_flags);
584d3226 3846
b4a4f213 3847 putname(filename);
584d3226
DK
3848 return res;
3849}
dae6ad8f
AV
3850EXPORT_SYMBOL(kern_path_create);
3851
921a1650
AV
3852void done_path_create(struct path *path, struct dentry *dentry)
3853{
3854 dput(dentry);
5955102c 3855 inode_unlock(path->dentry->d_inode);
a8104a9f 3856 mnt_drop_write(path->mnt);
921a1650
AV
3857 path_put(path);
3858}
3859EXPORT_SYMBOL(done_path_create);
3860
520ae687 3861inline struct dentry *user_path_create(int dfd, const char __user *pathname,
1ac12b4b 3862 struct path *path, unsigned int lookup_flags)
dae6ad8f 3863{
b4a4f213
SB
3864 struct filename *filename = getname(pathname);
3865 struct dentry *res = filename_create(dfd, filename, path, lookup_flags);
3866
3867 putname(filename);
3868 return res;
dae6ad8f
AV
3869}
3870EXPORT_SYMBOL(user_path_create);
3871
6521f891
CB
3872/**
3873 * vfs_mknod - create device node or file
3874 * @mnt_userns: user namespace of the mount the inode was found from
3875 * @dir: inode of @dentry
3876 * @dentry: pointer to dentry of the base directory
3877 * @mode: mode of the new device node or file
3878 * @dev: device number of device to create
3879 *
3880 * Create a device node or file.
3881 *
3882 * If the inode has been found through an idmapped mount the user namespace of
3883 * the vfsmount must be passed through @mnt_userns. This function will then take
3884 * care to map the inode according to @mnt_userns before checking permissions.
3885 * On non-idmapped mounts or if permission checking is to be performed on the
3886 * raw inode simply passs init_user_ns.
3887 */
3888int vfs_mknod(struct user_namespace *mnt_userns, struct inode *dir,
3889 struct dentry *dentry, umode_t mode, dev_t dev)
1da177e4 3890{
a3c751a5 3891 bool is_whiteout = S_ISCHR(mode) && dev == WHITEOUT_DEV;
6521f891 3892 int error = may_create(mnt_userns, dir, dentry);
1da177e4
LT
3893
3894 if (error)
3895 return error;
3896
a3c751a5
MS
3897 if ((S_ISCHR(mode) || S_ISBLK(mode)) && !is_whiteout &&
3898 !capable(CAP_MKNOD))
1da177e4
LT
3899 return -EPERM;
3900
acfa4380 3901 if (!dir->i_op->mknod)
1da177e4
LT
3902 return -EPERM;
3903
1639a49c 3904 mode = vfs_prepare_mode(mnt_userns, dir, mode, mode, mode);
08ce5f16
SH
3905 error = devcgroup_inode_mknod(mode, dev);
3906 if (error)
3907 return error;
3908
1da177e4
LT
3909 error = security_inode_mknod(dir, dentry, mode, dev);
3910 if (error)
3911 return error;
3912
549c7297 3913 error = dir->i_op->mknod(mnt_userns, dir, dentry, mode, dev);
a74574aa 3914 if (!error)
f38aa942 3915 fsnotify_create(dir, dentry);
1da177e4
LT
3916 return error;
3917}
4d359507 3918EXPORT_SYMBOL(vfs_mknod);
1da177e4 3919
f69aac00 3920static int may_mknod(umode_t mode)
463c3197
DH
3921{
3922 switch (mode & S_IFMT) {
3923 case S_IFREG:
3924 case S_IFCHR:
3925 case S_IFBLK:
3926 case S_IFIFO:
3927 case S_IFSOCK:
3928 case 0: /* zero mode translates to S_IFREG */
3929 return 0;
3930 case S_IFDIR:
3931 return -EPERM;
3932 default:
3933 return -EINVAL;
3934 }
3935}
3936
45f30dab 3937static int do_mknodat(int dfd, struct filename *name, umode_t mode,
87c4e192 3938 unsigned int dev)
1da177e4 3939{
6521f891 3940 struct user_namespace *mnt_userns;
2ad94ae6 3941 struct dentry *dentry;
dae6ad8f
AV
3942 struct path path;
3943 int error;
972567f1 3944 unsigned int lookup_flags = 0;
1da177e4 3945
8e4bfca1
AV
3946 error = may_mknod(mode);
3947 if (error)
7797251b 3948 goto out1;
972567f1 3949retry:
b4a4f213 3950 dentry = filename_create(dfd, name, &path, lookup_flags);
7797251b 3951 error = PTR_ERR(dentry);
dae6ad8f 3952 if (IS_ERR(dentry))
7797251b 3953 goto out1;
2ad94ae6 3954
1639a49c
YX
3955 error = security_path_mknod(&path, dentry,
3956 mode_strip_umask(path.dentry->d_inode, mode), dev);
be6d3e56 3957 if (error)
7797251b 3958 goto out2;
6521f891
CB
3959
3960 mnt_userns = mnt_user_ns(path.mnt);
463c3197 3961 switch (mode & S_IFMT) {
1da177e4 3962 case 0: case S_IFREG:
6521f891
CB
3963 error = vfs_create(mnt_userns, path.dentry->d_inode,
3964 dentry, mode, true);
05d1a717 3965 if (!error)
a2d2329e 3966 ima_post_path_mknod(mnt_userns, dentry);
1da177e4
LT
3967 break;
3968 case S_IFCHR: case S_IFBLK:
6521f891
CB
3969 error = vfs_mknod(mnt_userns, path.dentry->d_inode,
3970 dentry, mode, new_decode_dev(dev));
1da177e4
LT
3971 break;
3972 case S_IFIFO: case S_IFSOCK:
6521f891
CB
3973 error = vfs_mknod(mnt_userns, path.dentry->d_inode,
3974 dentry, mode, 0);
1da177e4 3975 break;
1da177e4 3976 }
7797251b 3977out2:
921a1650 3978 done_path_create(&path, dentry);
972567f1
JL
3979 if (retry_estale(error, lookup_flags)) {
3980 lookup_flags |= LOOKUP_REVAL;
3981 goto retry;
3982 }
7797251b
DK
3983out1:
3984 putname(name);
1da177e4
LT
3985 return error;
3986}
3987
87c4e192
DB
3988SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, umode_t, mode,
3989 unsigned int, dev)
3990{
7797251b 3991 return do_mknodat(dfd, getname(filename), mode, dev);
87c4e192
DB
3992}
3993
8208a22b 3994SYSCALL_DEFINE3(mknod, const char __user *, filename, umode_t, mode, unsigned, dev)
5590ff0d 3995{
7797251b 3996 return do_mknodat(AT_FDCWD, getname(filename), mode, dev);
5590ff0d
UD
3997}
3998
6521f891
CB
3999/**
4000 * vfs_mkdir - create directory
4001 * @mnt_userns: user namespace of the mount the inode was found from
4002 * @dir: inode of @dentry
4003 * @dentry: pointer to dentry of the base directory
4004 * @mode: mode of the new directory
4005 *
4006 * Create a directory.
4007 *
4008 * If the inode has been found through an idmapped mount the user namespace of
4009 * the vfsmount must be passed through @mnt_userns. This function will then take
4010 * care to map the inode according to @mnt_userns before checking permissions.
4011 * On non-idmapped mounts or if permission checking is to be performed on the
4012 * raw inode simply passs init_user_ns.
4013 */
4014int vfs_mkdir(struct user_namespace *mnt_userns, struct inode *dir,
4015 struct dentry *dentry, umode_t mode)
1da177e4 4016{
6521f891 4017 int error = may_create(mnt_userns, dir, dentry);
8de52778 4018 unsigned max_links = dir->i_sb->s_max_links;
1da177e4
LT
4019
4020 if (error)
4021 return error;
4022
acfa4380 4023 if (!dir->i_op->mkdir)
1da177e4
LT
4024 return -EPERM;
4025
1639a49c 4026 mode = vfs_prepare_mode(mnt_userns, dir, mode, S_IRWXUGO | S_ISVTX, 0);
1da177e4
LT
4027 error = security_inode_mkdir(dir, dentry, mode);
4028 if (error)
4029 return error;
4030
8de52778
AV
4031 if (max_links && dir->i_nlink >= max_links)
4032 return -EMLINK;
4033
549c7297 4034 error = dir->i_op->mkdir(mnt_userns, dir, dentry, mode);
a74574aa 4035 if (!error)
f38aa942 4036 fsnotify_mkdir(dir, dentry);
1da177e4
LT
4037 return error;
4038}
4d359507 4039EXPORT_SYMBOL(vfs_mkdir);
1da177e4 4040
45f30dab 4041int do_mkdirat(int dfd, struct filename *name, umode_t mode)
1da177e4 4042{
6902d925 4043 struct dentry *dentry;
dae6ad8f
AV
4044 struct path path;
4045 int error;
b76d8b82 4046 unsigned int lookup_flags = LOOKUP_DIRECTORY;
1da177e4 4047
b76d8b82 4048retry:
b4a4f213 4049 dentry = filename_create(dfd, name, &path, lookup_flags);
584d3226 4050 error = PTR_ERR(dentry);
6902d925 4051 if (IS_ERR(dentry))
584d3226 4052 goto out_putname;
1da177e4 4053
1639a49c
YX
4054 error = security_path_mkdir(&path, dentry,
4055 mode_strip_umask(path.dentry->d_inode, mode));
6521f891
CB
4056 if (!error) {
4057 struct user_namespace *mnt_userns;
4058 mnt_userns = mnt_user_ns(path.mnt);
549c7297
CB
4059 error = vfs_mkdir(mnt_userns, path.dentry->d_inode, dentry,
4060 mode);
6521f891 4061 }
921a1650 4062 done_path_create(&path, dentry);
b76d8b82
JL
4063 if (retry_estale(error, lookup_flags)) {
4064 lookup_flags |= LOOKUP_REVAL;
4065 goto retry;
4066 }
584d3226
DK
4067out_putname:
4068 putname(name);
1da177e4
LT
4069 return error;
4070}
4071
0101db7a
DB
4072SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, umode_t, mode)
4073{
584d3226 4074 return do_mkdirat(dfd, getname(pathname), mode);
0101db7a
DB
4075}
4076
a218d0fd 4077SYSCALL_DEFINE2(mkdir, const char __user *, pathname, umode_t, mode)
5590ff0d 4078{
584d3226 4079 return do_mkdirat(AT_FDCWD, getname(pathname), mode);
5590ff0d
UD
4080}
4081
6521f891
CB
4082/**
4083 * vfs_rmdir - remove directory
4084 * @mnt_userns: user namespace of the mount the inode was found from
4085 * @dir: inode of @dentry
4086 * @dentry: pointer to dentry of the base directory
4087 *
4088 * Remove a directory.
4089 *
4090 * If the inode has been found through an idmapped mount the user namespace of
4091 * the vfsmount must be passed through @mnt_userns. This function will then take
4092 * care to map the inode according to @mnt_userns before checking permissions.
4093 * On non-idmapped mounts or if permission checking is to be performed on the
4094 * raw inode simply passs init_user_ns.
4095 */
4096int vfs_rmdir(struct user_namespace *mnt_userns, struct inode *dir,
4097 struct dentry *dentry)
1da177e4 4098{
6521f891 4099 int error = may_delete(mnt_userns, dir, dentry, 1);
1da177e4
LT
4100
4101 if (error)
4102 return error;
4103
acfa4380 4104 if (!dir->i_op->rmdir)
1da177e4
LT
4105 return -EPERM;
4106
1d2ef590 4107 dget(dentry);
5955102c 4108 inode_lock(dentry->d_inode);
912dbc15
SW
4109
4110 error = -EBUSY;
1bd9c4e4
DH
4111 if (is_local_mountpoint(dentry) ||
4112 (dentry->d_inode->i_flags & S_KERNEL_FILE))
912dbc15
SW
4113 goto out;
4114
4115 error = security_inode_rmdir(dir, dentry);
4116 if (error)
4117 goto out;
4118
4119 error = dir->i_op->rmdir(dir, dentry);
4120 if (error)
4121 goto out;
4122
8767712f 4123 shrink_dcache_parent(dentry);
912dbc15
SW
4124 dentry->d_inode->i_flags |= S_DEAD;
4125 dont_mount(dentry);
8ed936b5 4126 detach_mounts(dentry);
912dbc15
SW
4127
4128out:
5955102c 4129 inode_unlock(dentry->d_inode);
1d2ef590 4130 dput(dentry);
912dbc15 4131 if (!error)
a37d9a17 4132 d_delete_notify(dir, dentry);
1da177e4
LT
4133 return error;
4134}
4d359507 4135EXPORT_SYMBOL(vfs_rmdir);
1da177e4 4136
45f30dab 4137int do_rmdir(int dfd, struct filename *name)
1da177e4 4138{
6521f891 4139 struct user_namespace *mnt_userns;
0ee50b47 4140 int error;
1da177e4 4141 struct dentry *dentry;
f5beed75
AV
4142 struct path path;
4143 struct qstr last;
4144 int type;
c6ee9206
JL
4145 unsigned int lookup_flags = 0;
4146retry:
c5f563f9 4147 error = filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
0ee50b47
DK
4148 if (error)
4149 goto exit1;
1da177e4 4150
f5beed75 4151 switch (type) {
0612d9fb
OH
4152 case LAST_DOTDOT:
4153 error = -ENOTEMPTY;
0ee50b47 4154 goto exit2;
0612d9fb
OH
4155 case LAST_DOT:
4156 error = -EINVAL;
0ee50b47 4157 goto exit2;
0612d9fb
OH
4158 case LAST_ROOT:
4159 error = -EBUSY;
0ee50b47 4160 goto exit2;
1da177e4 4161 }
0612d9fb 4162
f5beed75 4163 error = mnt_want_write(path.mnt);
c30dabfe 4164 if (error)
0ee50b47 4165 goto exit2;
0612d9fb 4166
5955102c 4167 inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
f5beed75 4168 dentry = __lookup_hash(&last, path.dentry, lookup_flags);
1da177e4 4169 error = PTR_ERR(dentry);
6902d925 4170 if (IS_ERR(dentry))
0ee50b47 4171 goto exit3;
e6bc45d6
TT
4172 if (!dentry->d_inode) {
4173 error = -ENOENT;
0ee50b47 4174 goto exit4;
e6bc45d6 4175 }
f5beed75 4176 error = security_path_rmdir(&path, dentry);
be6d3e56 4177 if (error)
0ee50b47 4178 goto exit4;
6521f891
CB
4179 mnt_userns = mnt_user_ns(path.mnt);
4180 error = vfs_rmdir(mnt_userns, path.dentry->d_inode, dentry);
0ee50b47 4181exit4:
6902d925 4182 dput(dentry);
0ee50b47 4183exit3:
5955102c 4184 inode_unlock(path.dentry->d_inode);
f5beed75 4185 mnt_drop_write(path.mnt);
0ee50b47 4186exit2:
f5beed75 4187 path_put(&path);
c6ee9206
JL
4188 if (retry_estale(error, lookup_flags)) {
4189 lookup_flags |= LOOKUP_REVAL;
4190 goto retry;
4191 }
0ee50b47 4192exit1:
24fb33d4 4193 putname(name);
1da177e4
LT
4194 return error;
4195}
4196
3cdad428 4197SYSCALL_DEFINE1(rmdir, const char __user *, pathname)
5590ff0d 4198{
e24ab0ef 4199 return do_rmdir(AT_FDCWD, getname(pathname));
5590ff0d
UD
4200}
4201
b21996e3
BF
4202/**
4203 * vfs_unlink - unlink a filesystem object
6521f891 4204 * @mnt_userns: user namespace of the mount the inode was found from
b21996e3
BF
4205 * @dir: parent directory
4206 * @dentry: victim
4207 * @delegated_inode: returns victim inode, if the inode is delegated.
4208 *
4209 * The caller must hold dir->i_mutex.
4210 *
4211 * If vfs_unlink discovers a delegation, it will return -EWOULDBLOCK and
4212 * return a reference to the inode in delegated_inode. The caller
4213 * should then break the delegation on that inode and retry. Because
4214 * breaking a delegation may take a long time, the caller should drop
4215 * dir->i_mutex before doing so.
4216 *
4217 * Alternatively, a caller may pass NULL for delegated_inode. This may
4218 * be appropriate for callers that expect the underlying filesystem not
4219 * to be NFS exported.
6521f891
CB
4220 *
4221 * If the inode has been found through an idmapped mount the user namespace of
4222 * the vfsmount must be passed through @mnt_userns. This function will then take
4223 * care to map the inode according to @mnt_userns before checking permissions.
4224 * On non-idmapped mounts or if permission checking is to be performed on the
4225 * raw inode simply passs init_user_ns.
b21996e3 4226 */
6521f891
CB
4227int vfs_unlink(struct user_namespace *mnt_userns, struct inode *dir,
4228 struct dentry *dentry, struct inode **delegated_inode)
1da177e4 4229{
9accbb97 4230 struct inode *target = dentry->d_inode;
6521f891 4231 int error = may_delete(mnt_userns, dir, dentry, 0);
1da177e4
LT
4232
4233 if (error)
4234 return error;
4235
acfa4380 4236 if (!dir->i_op->unlink)
1da177e4
LT
4237 return -EPERM;
4238
5955102c 4239 inode_lock(target);
51cc3a66
HD
4240 if (IS_SWAPFILE(target))
4241 error = -EPERM;
4242 else if (is_local_mountpoint(dentry))
1da177e4
LT
4243 error = -EBUSY;
4244 else {
4245 error = security_inode_unlink(dir, dentry);
bec1052e 4246 if (!error) {
5a14696c
BF
4247 error = try_break_deleg(target, delegated_inode);
4248 if (error)
b21996e3 4249 goto out;
1da177e4 4250 error = dir->i_op->unlink(dir, dentry);
8ed936b5 4251 if (!error) {
d83c49f3 4252 dont_mount(dentry);
8ed936b5
EB
4253 detach_mounts(dentry);
4254 }
bec1052e 4255 }
1da177e4 4256 }
b21996e3 4257out:
5955102c 4258 inode_unlock(target);
1da177e4
LT
4259
4260 /* We don't d_delete() NFS sillyrenamed files--they still exist. */
a37d9a17
AG
4261 if (!error && dentry->d_flags & DCACHE_NFSFS_RENAMED) {
4262 fsnotify_unlink(dir, dentry);
4263 } else if (!error) {
9accbb97 4264 fsnotify_link_count(target);
a37d9a17 4265 d_delete_notify(dir, dentry);
1da177e4 4266 }
0eeca283 4267
1da177e4
LT
4268 return error;
4269}
4d359507 4270EXPORT_SYMBOL(vfs_unlink);
1da177e4
LT
4271
4272/*
4273 * Make sure that the actual truncation of the file will occur outside its
1b1dcc1b 4274 * directory's i_mutex. Truncate can take a long time if there is a lot of
1da177e4
LT
4275 * writeout happening, and we don't want to prevent access to the directory
4276 * while waiting on the I/O.
4277 */
45f30dab 4278int do_unlinkat(int dfd, struct filename *name)
1da177e4 4279{
2ad94ae6 4280 int error;
1da177e4 4281 struct dentry *dentry;
f5beed75
AV
4282 struct path path;
4283 struct qstr last;
4284 int type;
1da177e4 4285 struct inode *inode = NULL;
b21996e3 4286 struct inode *delegated_inode = NULL;
5d18f813
JL
4287 unsigned int lookup_flags = 0;
4288retry:
c5f563f9 4289 error = filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
0ee50b47
DK
4290 if (error)
4291 goto exit1;
2ad94ae6 4292
1da177e4 4293 error = -EISDIR;
f5beed75 4294 if (type != LAST_NORM)
0ee50b47 4295 goto exit2;
0612d9fb 4296
f5beed75 4297 error = mnt_want_write(path.mnt);
c30dabfe 4298 if (error)
0ee50b47 4299 goto exit2;
b21996e3 4300retry_deleg:
5955102c 4301 inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
f5beed75 4302 dentry = __lookup_hash(&last, path.dentry, lookup_flags);
1da177e4
LT
4303 error = PTR_ERR(dentry);
4304 if (!IS_ERR(dentry)) {
6521f891
CB
4305 struct user_namespace *mnt_userns;
4306
1da177e4 4307 /* Why not before? Because we want correct error value */
f5beed75 4308 if (last.name[last.len])
50338b88 4309 goto slashes;
1da177e4 4310 inode = dentry->d_inode;
b18825a7 4311 if (d_is_negative(dentry))
e6bc45d6
TT
4312 goto slashes;
4313 ihold(inode);
f5beed75 4314 error = security_path_unlink(&path, dentry);
be6d3e56 4315 if (error)
0ee50b47 4316 goto exit3;
6521f891 4317 mnt_userns = mnt_user_ns(path.mnt);
549c7297
CB
4318 error = vfs_unlink(mnt_userns, path.dentry->d_inode, dentry,
4319 &delegated_inode);
0ee50b47 4320exit3:
1da177e4
LT
4321 dput(dentry);
4322 }
5955102c 4323 inode_unlock(path.dentry->d_inode);
1da177e4
LT
4324 if (inode)
4325 iput(inode); /* truncate the inode here */
b21996e3
BF
4326 inode = NULL;
4327 if (delegated_inode) {
5a14696c 4328 error = break_deleg_wait(&delegated_inode);
b21996e3
BF
4329 if (!error)
4330 goto retry_deleg;
4331 }
f5beed75 4332 mnt_drop_write(path.mnt);
0ee50b47 4333exit2:
f5beed75 4334 path_put(&path);
5d18f813
JL
4335 if (retry_estale(error, lookup_flags)) {
4336 lookup_flags |= LOOKUP_REVAL;
4337 inode = NULL;
4338 goto retry;
4339 }
0ee50b47 4340exit1:
da2f1362 4341 putname(name);
1da177e4
LT
4342 return error;
4343
4344slashes:
b18825a7
DH
4345 if (d_is_negative(dentry))
4346 error = -ENOENT;
44b1d530 4347 else if (d_is_dir(dentry))
b18825a7
DH
4348 error = -EISDIR;
4349 else
4350 error = -ENOTDIR;
0ee50b47 4351 goto exit3;
1da177e4
LT
4352}
4353
2e4d0924 4354SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag)
5590ff0d
UD
4355{
4356 if ((flag & ~AT_REMOVEDIR) != 0)
4357 return -EINVAL;
4358
4359 if (flag & AT_REMOVEDIR)
e24ab0ef 4360 return do_rmdir(dfd, getname(pathname));
da2f1362 4361 return do_unlinkat(dfd, getname(pathname));
5590ff0d
UD
4362}
4363
3480b257 4364SYSCALL_DEFINE1(unlink, const char __user *, pathname)
5590ff0d 4365{
da2f1362 4366 return do_unlinkat(AT_FDCWD, getname(pathname));
5590ff0d
UD
4367}
4368
6521f891
CB
4369/**
4370 * vfs_symlink - create symlink
4371 * @mnt_userns: user namespace of the mount the inode was found from
4372 * @dir: inode of @dentry
4373 * @dentry: pointer to dentry of the base directory
4374 * @oldname: name of the file to link to
4375 *
4376 * Create a symlink.
4377 *
4378 * If the inode has been found through an idmapped mount the user namespace of
4379 * the vfsmount must be passed through @mnt_userns. This function will then take
4380 * care to map the inode according to @mnt_userns before checking permissions.
4381 * On non-idmapped mounts or if permission checking is to be performed on the
4382 * raw inode simply passs init_user_ns.
4383 */
4384int vfs_symlink(struct user_namespace *mnt_userns, struct inode *dir,
4385 struct dentry *dentry, const char *oldname)
1da177e4 4386{
6521f891 4387 int error = may_create(mnt_userns, dir, dentry);
1da177e4
LT
4388
4389 if (error)
4390 return error;
4391
acfa4380 4392 if (!dir->i_op->symlink)
1da177e4
LT
4393 return -EPERM;
4394
4395 error = security_inode_symlink(dir, dentry, oldname);
4396 if (error)
4397 return error;
4398
549c7297 4399 error = dir->i_op->symlink(mnt_userns, dir, dentry, oldname);
a74574aa 4400 if (!error)
f38aa942 4401 fsnotify_create(dir, dentry);
1da177e4
LT
4402 return error;
4403}
4d359507 4404EXPORT_SYMBOL(vfs_symlink);
1da177e4 4405
7a8721f8 4406int do_symlinkat(struct filename *from, int newdfd, struct filename *to)
1da177e4 4407{
2ad94ae6 4408 int error;
6902d925 4409 struct dentry *dentry;
dae6ad8f 4410 struct path path;
f46d3567 4411 unsigned int lookup_flags = 0;
1da177e4 4412
da2d0ced
DK
4413 if (IS_ERR(from)) {
4414 error = PTR_ERR(from);
4415 goto out_putnames;
4416 }
f46d3567 4417retry:
b4a4f213 4418 dentry = filename_create(newdfd, to, &path, lookup_flags);
6902d925
DH
4419 error = PTR_ERR(dentry);
4420 if (IS_ERR(dentry))
da2d0ced 4421 goto out_putnames;
6902d925 4422
91a27b2a 4423 error = security_path_symlink(&path, dentry, from->name);
6521f891
CB
4424 if (!error) {
4425 struct user_namespace *mnt_userns;
4426
4427 mnt_userns = mnt_user_ns(path.mnt);
4428 error = vfs_symlink(mnt_userns, path.dentry->d_inode, dentry,
4429 from->name);
4430 }
921a1650 4431 done_path_create(&path, dentry);
f46d3567
JL
4432 if (retry_estale(error, lookup_flags)) {
4433 lookup_flags |= LOOKUP_REVAL;
4434 goto retry;
4435 }
da2d0ced
DK
4436out_putnames:
4437 putname(to);
1da177e4
LT
4438 putname(from);
4439 return error;
4440}
4441
b724e846
DB
4442SYSCALL_DEFINE3(symlinkat, const char __user *, oldname,
4443 int, newdfd, const char __user *, newname)
4444{
da2d0ced 4445 return do_symlinkat(getname(oldname), newdfd, getname(newname));
b724e846
DB
4446}
4447
3480b257 4448SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname)
5590ff0d 4449{
da2d0ced 4450 return do_symlinkat(getname(oldname), AT_FDCWD, getname(newname));
5590ff0d
UD
4451}
4452
146a8595
BF
4453/**
4454 * vfs_link - create a new link
4455 * @old_dentry: object to be linked
6521f891 4456 * @mnt_userns: the user namespace of the mount
146a8595
BF
4457 * @dir: new parent
4458 * @new_dentry: where to create the new link
4459 * @delegated_inode: returns inode needing a delegation break
4460 *
4461 * The caller must hold dir->i_mutex
4462 *
4463 * If vfs_link discovers a delegation on the to-be-linked file in need
4464 * of breaking, it will return -EWOULDBLOCK and return a reference to the
4465 * inode in delegated_inode. The caller should then break the delegation
4466 * and retry. Because breaking a delegation may take a long time, the
4467 * caller should drop the i_mutex before doing so.
4468 *
4469 * Alternatively, a caller may pass NULL for delegated_inode. This may
4470 * be appropriate for callers that expect the underlying filesystem not
4471 * to be NFS exported.
6521f891
CB
4472 *
4473 * If the inode has been found through an idmapped mount the user namespace of
4474 * the vfsmount must be passed through @mnt_userns. This function will then take
4475 * care to map the inode according to @mnt_userns before checking permissions.
4476 * On non-idmapped mounts or if permission checking is to be performed on the
4477 * raw inode simply passs init_user_ns.
146a8595 4478 */
6521f891
CB
4479int vfs_link(struct dentry *old_dentry, struct user_namespace *mnt_userns,
4480 struct inode *dir, struct dentry *new_dentry,
4481 struct inode **delegated_inode)
1da177e4
LT
4482{
4483 struct inode *inode = old_dentry->d_inode;
8de52778 4484 unsigned max_links = dir->i_sb->s_max_links;
1da177e4
LT
4485 int error;
4486
4487 if (!inode)
4488 return -ENOENT;
4489
6521f891 4490 error = may_create(mnt_userns, dir, new_dentry);
1da177e4
LT
4491 if (error)
4492 return error;
4493
4494 if (dir->i_sb != inode->i_sb)
4495 return -EXDEV;
4496
4497 /*
4498 * A link to an append-only or immutable file cannot be created.
4499 */
4500 if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
4501 return -EPERM;
0bd23d09
EB
4502 /*
4503 * Updating the link count will likely cause i_uid and i_gid to
4504 * be writen back improperly if their true value is unknown to
4505 * the vfs.
4506 */
6521f891 4507 if (HAS_UNMAPPED_ID(mnt_userns, inode))
0bd23d09 4508 return -EPERM;
acfa4380 4509 if (!dir->i_op->link)
1da177e4 4510 return -EPERM;
7e79eedb 4511 if (S_ISDIR(inode->i_mode))
1da177e4
LT
4512 return -EPERM;
4513
4514 error = security_inode_link(old_dentry, dir, new_dentry);
4515 if (error)
4516 return error;
4517
5955102c 4518 inode_lock(inode);
aae8a97d 4519 /* Make sure we don't allow creating hardlink to an unlinked file */
f4e0c30c 4520 if (inode->i_nlink == 0 && !(inode->i_state & I_LINKABLE))
aae8a97d 4521 error = -ENOENT;
8de52778
AV
4522 else if (max_links && inode->i_nlink >= max_links)
4523 error = -EMLINK;
146a8595
BF
4524 else {
4525 error = try_break_deleg(inode, delegated_inode);
4526 if (!error)
4527 error = dir->i_op->link(old_dentry, dir, new_dentry);
4528 }
f4e0c30c
AV
4529
4530 if (!error && (inode->i_state & I_LINKABLE)) {
4531 spin_lock(&inode->i_lock);
4532 inode->i_state &= ~I_LINKABLE;
4533 spin_unlock(&inode->i_lock);
4534 }
5955102c 4535 inode_unlock(inode);
e31e14ec 4536 if (!error)
7e79eedb 4537 fsnotify_link(dir, inode, new_dentry);
1da177e4
LT
4538 return error;
4539}
4d359507 4540EXPORT_SYMBOL(vfs_link);
1da177e4
LT
4541
4542/*
4543 * Hardlinks are often used in delicate situations. We avoid
4544 * security-related surprises by not following symlinks on the
4545 * newname. --KAB
4546 *
4547 * We don't follow them on the oldname either to be compatible
4548 * with linux 2.0, and to avoid hard-linking to directories
4549 * and other special files. --ADM
4550 */
cf30da90 4551int do_linkat(int olddfd, struct filename *old, int newdfd,
020250f3 4552 struct filename *new, int flags)
1da177e4 4553{
6521f891 4554 struct user_namespace *mnt_userns;
1da177e4 4555 struct dentry *new_dentry;
dae6ad8f 4556 struct path old_path, new_path;
146a8595 4557 struct inode *delegated_inode = NULL;
11a7b371 4558 int how = 0;
1da177e4 4559 int error;
1da177e4 4560
020250f3
DK
4561 if ((flags & ~(AT_SYMLINK_FOLLOW | AT_EMPTY_PATH)) != 0) {
4562 error = -EINVAL;
4563 goto out_putnames;
4564 }
11a7b371 4565 /*
f0cc6ffb
LT
4566 * To use null names we require CAP_DAC_READ_SEARCH
4567 * This ensures that not everyone will be able to create
4568 * handlink using the passed filedescriptor.
11a7b371 4569 */
020250f3
DK
4570 if (flags & AT_EMPTY_PATH && !capable(CAP_DAC_READ_SEARCH)) {
4571 error = -ENOENT;
4572 goto out_putnames;
f0cc6ffb 4573 }
11a7b371
AK
4574
4575 if (flags & AT_SYMLINK_FOLLOW)
4576 how |= LOOKUP_FOLLOW;
442e31ca 4577retry:
794ebcea 4578 error = filename_lookup(olddfd, old, how, &old_path, NULL);
1da177e4 4579 if (error)
020250f3 4580 goto out_putnames;
2ad94ae6 4581
b4a4f213 4582 new_dentry = filename_create(newdfd, new, &new_path,
442e31ca 4583 (how & LOOKUP_REVAL));
1da177e4 4584 error = PTR_ERR(new_dentry);
6902d925 4585 if (IS_ERR(new_dentry))
020250f3 4586 goto out_putpath;
dae6ad8f
AV
4587
4588 error = -EXDEV;
4589 if (old_path.mnt != new_path.mnt)
4590 goto out_dput;
549c7297
CB
4591 mnt_userns = mnt_user_ns(new_path.mnt);
4592 error = may_linkat(mnt_userns, &old_path);
800179c9
KC
4593 if (unlikely(error))
4594 goto out_dput;
dae6ad8f 4595 error = security_path_link(old_path.dentry, &new_path, new_dentry);
be6d3e56 4596 if (error)
a8104a9f 4597 goto out_dput;
6521f891
CB
4598 error = vfs_link(old_path.dentry, mnt_userns, new_path.dentry->d_inode,
4599 new_dentry, &delegated_inode);
75c3f29d 4600out_dput:
921a1650 4601 done_path_create(&new_path, new_dentry);
146a8595
BF
4602 if (delegated_inode) {
4603 error = break_deleg_wait(&delegated_inode);
d22e6338
OD
4604 if (!error) {
4605 path_put(&old_path);
146a8595 4606 goto retry;
d22e6338 4607 }
146a8595 4608 }
442e31ca 4609 if (retry_estale(error, how)) {
d22e6338 4610 path_put(&old_path);
442e31ca
JL
4611 how |= LOOKUP_REVAL;
4612 goto retry;
4613 }
020250f3 4614out_putpath:
2d8f3038 4615 path_put(&old_path);
020250f3
DK
4616out_putnames:
4617 putname(old);
4618 putname(new);
1da177e4
LT
4619
4620 return error;
4621}
4622
46ea89eb
DB
4623SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname,
4624 int, newdfd, const char __user *, newname, int, flags)
4625{
020250f3
DK
4626 return do_linkat(olddfd, getname_uflags(oldname, flags),
4627 newdfd, getname(newname), flags);
46ea89eb
DB
4628}
4629
3480b257 4630SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname)
5590ff0d 4631{
020250f3 4632 return do_linkat(AT_FDCWD, getname(oldname), AT_FDCWD, getname(newname), 0);
5590ff0d
UD
4633}
4634
bc27027a
MS
4635/**
4636 * vfs_rename - rename a filesystem object
2111c3c0 4637 * @rd: pointer to &struct renamedata info
bc27027a
MS
4638 *
4639 * The caller must hold multiple mutexes--see lock_rename()).
4640 *
4641 * If vfs_rename discovers a delegation in need of breaking at either
4642 * the source or destination, it will return -EWOULDBLOCK and return a
4643 * reference to the inode in delegated_inode. The caller should then
4644 * break the delegation and retry. Because breaking a delegation may
4645 * take a long time, the caller should drop all locks before doing
4646 * so.
4647 *
4648 * Alternatively, a caller may pass NULL for delegated_inode. This may
4649 * be appropriate for callers that expect the underlying filesystem not
4650 * to be NFS exported.
4651 *
1da177e4
LT
4652 * The worst of all namespace operations - renaming directory. "Perverted"
4653 * doesn't even start to describe it. Somebody in UCB had a heck of a trip...
4654 * Problems:
0117d427 4655 *
d03b29a2 4656 * a) we can get into loop creation.
1da177e4
LT
4657 * b) race potential - two innocent renames can create a loop together.
4658 * That's where 4.4 screws up. Current fix: serialization on
a11f3a05 4659 * sb->s_vfs_rename_mutex. We might be more accurate, but that's another
1da177e4 4660 * story.
6cedba89
BF
4661 * c) we have to lock _four_ objects - parents and victim (if it exists),
4662 * and source (if it is not a directory).
1b1dcc1b 4663 * And that - after we got ->i_mutex on parents (until then we don't know
1da177e4
LT
4664 * whether the target exists). Solution: try to be smart with locking
4665 * order for inodes. We rely on the fact that tree topology may change
a11f3a05 4666 * only under ->s_vfs_rename_mutex _and_ that parent of the object we
1da177e4
LT
4667 * move will be locked. Thus we can rank directories by the tree
4668 * (ancestors first) and rank all non-directories after them.
4669 * That works since everybody except rename does "lock parent, lookup,
a11f3a05 4670 * lock child" and rename is under ->s_vfs_rename_mutex.
1da177e4
LT
4671 * HOWEVER, it relies on the assumption that any object with ->lookup()
4672 * has no more than 1 dentry. If "hybrid" objects will ever appear,
4673 * we'd better make sure that there's no link(2) for them.
e4eaac06 4674 * d) conversion from fhandle to dentry may come in the wrong moment - when
1b1dcc1b 4675 * we are removing the target. Solution: we will have to grab ->i_mutex
1da177e4 4676 * in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on
c41b20e7 4677 * ->i_mutex on parents, which works but leads to some truly excessive
1da177e4
LT
4678 * locking].
4679 */
9fe61450 4680int vfs_rename(struct renamedata *rd)
1da177e4 4681{
bc27027a 4682 int error;
9fe61450
CB
4683 struct inode *old_dir = rd->old_dir, *new_dir = rd->new_dir;
4684 struct dentry *old_dentry = rd->old_dentry;
4685 struct dentry *new_dentry = rd->new_dentry;
4686 struct inode **delegated_inode = rd->delegated_inode;
4687 unsigned int flags = rd->flags;
bc27027a 4688 bool is_dir = d_is_dir(old_dentry);
bc27027a 4689 struct inode *source = old_dentry->d_inode;
9055cba7 4690 struct inode *target = new_dentry->d_inode;
da1ce067
MS
4691 bool new_is_dir = false;
4692 unsigned max_links = new_dir->i_sb->s_max_links;
49d31c2f 4693 struct name_snapshot old_name;
bc27027a 4694
8d3e2936 4695 if (source == target)
bc27027a
MS
4696 return 0;
4697
6521f891 4698 error = may_delete(rd->old_mnt_userns, old_dir, old_dentry, is_dir);
bc27027a
MS
4699 if (error)
4700 return error;
4701
da1ce067 4702 if (!target) {
6521f891 4703 error = may_create(rd->new_mnt_userns, new_dir, new_dentry);
da1ce067
MS
4704 } else {
4705 new_is_dir = d_is_dir(new_dentry);
4706
4707 if (!(flags & RENAME_EXCHANGE))
6521f891
CB
4708 error = may_delete(rd->new_mnt_userns, new_dir,
4709 new_dentry, is_dir);
da1ce067 4710 else
6521f891
CB
4711 error = may_delete(rd->new_mnt_userns, new_dir,
4712 new_dentry, new_is_dir);
da1ce067 4713 }
bc27027a
MS
4714 if (error)
4715 return error;
4716
2773bf00 4717 if (!old_dir->i_op->rename)
bc27027a 4718 return -EPERM;
1da177e4
LT
4719
4720 /*
4721 * If we are going to change the parent - check write permissions,
4722 * we'll need to flip '..'.
4723 */
da1ce067
MS
4724 if (new_dir != old_dir) {
4725 if (is_dir) {
6521f891 4726 error = inode_permission(rd->old_mnt_userns, source,
47291baa 4727 MAY_WRITE);
da1ce067
MS
4728 if (error)
4729 return error;
4730 }
4731 if ((flags & RENAME_EXCHANGE) && new_is_dir) {
6521f891 4732 error = inode_permission(rd->new_mnt_userns, target,
47291baa 4733 MAY_WRITE);
da1ce067
MS
4734 if (error)
4735 return error;
4736 }
1da177e4
LT
4737 }
4738
0b3974eb
MS
4739 error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,
4740 flags);
1da177e4
LT
4741 if (error)
4742 return error;
4743
49d31c2f 4744 take_dentry_name_snapshot(&old_name, old_dentry);
1d2ef590 4745 dget(new_dentry);
da1ce067 4746 if (!is_dir || (flags & RENAME_EXCHANGE))
bc27027a
MS
4747 lock_two_nondirectories(source, target);
4748 else if (target)
5955102c 4749 inode_lock(target);
9055cba7 4750
51cc3a66
HD
4751 error = -EPERM;
4752 if (IS_SWAPFILE(source) || (target && IS_SWAPFILE(target)))
4753 goto out;
4754
9055cba7 4755 error = -EBUSY;
7af1364f 4756 if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
9055cba7
SW
4757 goto out;
4758
da1ce067 4759 if (max_links && new_dir != old_dir) {
bc27027a 4760 error = -EMLINK;
da1ce067 4761 if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)
bc27027a 4762 goto out;
da1ce067
MS
4763 if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&
4764 old_dir->i_nlink >= max_links)
4765 goto out;
4766 }
da1ce067 4767 if (!is_dir) {
bc27027a 4768 error = try_break_deleg(source, delegated_inode);
8e6d782c
BF
4769 if (error)
4770 goto out;
da1ce067
MS
4771 }
4772 if (target && !new_is_dir) {
4773 error = try_break_deleg(target, delegated_inode);
4774 if (error)
4775 goto out;
8e6d782c 4776 }
549c7297
CB
4777 error = old_dir->i_op->rename(rd->new_mnt_userns, old_dir, old_dentry,
4778 new_dir, new_dentry, flags);
51892bbb
SW
4779 if (error)
4780 goto out;
4781
da1ce067 4782 if (!(flags & RENAME_EXCHANGE) && target) {
8767712f
AV
4783 if (is_dir) {
4784 shrink_dcache_parent(new_dentry);
bc27027a 4785 target->i_flags |= S_DEAD;
8767712f 4786 }
51892bbb 4787 dont_mount(new_dentry);
8ed936b5 4788 detach_mounts(new_dentry);
bc27027a 4789 }
da1ce067
MS
4790 if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {
4791 if (!(flags & RENAME_EXCHANGE))
4792 d_move(old_dentry, new_dentry);
4793 else
4794 d_exchange(old_dentry, new_dentry);
4795 }
51892bbb 4796out:
da1ce067 4797 if (!is_dir || (flags & RENAME_EXCHANGE))
bc27027a
MS
4798 unlock_two_nondirectories(source, target);
4799 else if (target)
5955102c 4800 inode_unlock(target);
1da177e4 4801 dput(new_dentry);
da1ce067 4802 if (!error) {
f4ec3a3d 4803 fsnotify_move(old_dir, new_dir, &old_name.name, is_dir,
da1ce067
MS
4804 !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);
4805 if (flags & RENAME_EXCHANGE) {
f4ec3a3d 4806 fsnotify_move(new_dir, old_dir, &old_dentry->d_name,
da1ce067
MS
4807 new_is_dir, NULL, new_dentry);
4808 }
4809 }
49d31c2f 4810 release_dentry_name_snapshot(&old_name);
0eeca283 4811
1da177e4
LT
4812 return error;
4813}
4d359507 4814EXPORT_SYMBOL(vfs_rename);
1da177e4 4815
e886663c
JA
4816int do_renameat2(int olddfd, struct filename *from, int newdfd,
4817 struct filename *to, unsigned int flags)
1da177e4 4818{
9fe61450 4819 struct renamedata rd;
2ad94ae6
AV
4820 struct dentry *old_dentry, *new_dentry;
4821 struct dentry *trap;
f5beed75
AV
4822 struct path old_path, new_path;
4823 struct qstr old_last, new_last;
4824 int old_type, new_type;
8e6d782c 4825 struct inode *delegated_inode = NULL;
f5beed75 4826 unsigned int lookup_flags = 0, target_flags = LOOKUP_RENAME_TARGET;
c6a94284 4827 bool should_retry = false;
e886663c 4828 int error = -EINVAL;
520c8b16 4829
0d7a8555 4830 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
0ee50b47 4831 goto put_names;
da1ce067 4832
0d7a8555
MS
4833 if ((flags & (RENAME_NOREPLACE | RENAME_WHITEOUT)) &&
4834 (flags & RENAME_EXCHANGE))
0ee50b47 4835 goto put_names;
520c8b16 4836
f5beed75
AV
4837 if (flags & RENAME_EXCHANGE)
4838 target_flags = 0;
4839
c6a94284 4840retry:
c5f563f9
AV
4841 error = filename_parentat(olddfd, from, lookup_flags, &old_path,
4842 &old_last, &old_type);
0ee50b47
DK
4843 if (error)
4844 goto put_names;
1da177e4 4845
c5f563f9
AV
4846 error = filename_parentat(newdfd, to, lookup_flags, &new_path, &new_last,
4847 &new_type);
0ee50b47 4848 if (error)
1da177e4
LT
4849 goto exit1;
4850
4851 error = -EXDEV;
f5beed75 4852 if (old_path.mnt != new_path.mnt)
1da177e4
LT
4853 goto exit2;
4854
1da177e4 4855 error = -EBUSY;
f5beed75 4856 if (old_type != LAST_NORM)
1da177e4
LT
4857 goto exit2;
4858
0a7c3937
MS
4859 if (flags & RENAME_NOREPLACE)
4860 error = -EEXIST;
f5beed75 4861 if (new_type != LAST_NORM)
1da177e4
LT
4862 goto exit2;
4863
f5beed75 4864 error = mnt_want_write(old_path.mnt);
c30dabfe
JK
4865 if (error)
4866 goto exit2;
4867
8e6d782c 4868retry_deleg:
f5beed75 4869 trap = lock_rename(new_path.dentry, old_path.dentry);
1da177e4 4870
f5beed75 4871 old_dentry = __lookup_hash(&old_last, old_path.dentry, lookup_flags);
1da177e4
LT
4872 error = PTR_ERR(old_dentry);
4873 if (IS_ERR(old_dentry))
4874 goto exit3;
4875 /* source must exist */
4876 error = -ENOENT;
b18825a7 4877 if (d_is_negative(old_dentry))
1da177e4 4878 goto exit4;
f5beed75 4879 new_dentry = __lookup_hash(&new_last, new_path.dentry, lookup_flags | target_flags);
0a7c3937
MS
4880 error = PTR_ERR(new_dentry);
4881 if (IS_ERR(new_dentry))
4882 goto exit4;
4883 error = -EEXIST;
4884 if ((flags & RENAME_NOREPLACE) && d_is_positive(new_dentry))
4885 goto exit5;
da1ce067
MS
4886 if (flags & RENAME_EXCHANGE) {
4887 error = -ENOENT;
4888 if (d_is_negative(new_dentry))
4889 goto exit5;
4890
4891 if (!d_is_dir(new_dentry)) {
4892 error = -ENOTDIR;
f5beed75 4893 if (new_last.name[new_last.len])
da1ce067
MS
4894 goto exit5;
4895 }
4896 }
1da177e4 4897 /* unless the source is a directory trailing slashes give -ENOTDIR */
44b1d530 4898 if (!d_is_dir(old_dentry)) {
1da177e4 4899 error = -ENOTDIR;
f5beed75 4900 if (old_last.name[old_last.len])
0a7c3937 4901 goto exit5;
f5beed75 4902 if (!(flags & RENAME_EXCHANGE) && new_last.name[new_last.len])
0a7c3937 4903 goto exit5;
1da177e4
LT
4904 }
4905 /* source should not be ancestor of target */
4906 error = -EINVAL;
4907 if (old_dentry == trap)
0a7c3937 4908 goto exit5;
1da177e4 4909 /* target should not be an ancestor of source */
da1ce067
MS
4910 if (!(flags & RENAME_EXCHANGE))
4911 error = -ENOTEMPTY;
1da177e4
LT
4912 if (new_dentry == trap)
4913 goto exit5;
4914
f5beed75
AV
4915 error = security_path_rename(&old_path, old_dentry,
4916 &new_path, new_dentry, flags);
be6d3e56 4917 if (error)
c30dabfe 4918 goto exit5;
9fe61450
CB
4919
4920 rd.old_dir = old_path.dentry->d_inode;
4921 rd.old_dentry = old_dentry;
6521f891 4922 rd.old_mnt_userns = mnt_user_ns(old_path.mnt);
9fe61450
CB
4923 rd.new_dir = new_path.dentry->d_inode;
4924 rd.new_dentry = new_dentry;
6521f891 4925 rd.new_mnt_userns = mnt_user_ns(new_path.mnt);
9fe61450
CB
4926 rd.delegated_inode = &delegated_inode;
4927 rd.flags = flags;
4928 error = vfs_rename(&rd);
1da177e4
LT
4929exit5:
4930 dput(new_dentry);
4931exit4:
4932 dput(old_dentry);
4933exit3:
f5beed75 4934 unlock_rename(new_path.dentry, old_path.dentry);
8e6d782c
BF
4935 if (delegated_inode) {
4936 error = break_deleg_wait(&delegated_inode);
4937 if (!error)
4938 goto retry_deleg;
4939 }
f5beed75 4940 mnt_drop_write(old_path.mnt);
1da177e4 4941exit2:
c6a94284
JL
4942 if (retry_estale(error, lookup_flags))
4943 should_retry = true;
f5beed75 4944 path_put(&new_path);
1da177e4 4945exit1:
f5beed75 4946 path_put(&old_path);
c6a94284
JL
4947 if (should_retry) {
4948 should_retry = false;
4949 lookup_flags |= LOOKUP_REVAL;
4950 goto retry;
4951 }
0ee50b47 4952put_names:
91ef658f 4953 putname(from);
91ef658f 4954 putname(to);
1da177e4
LT
4955 return error;
4956}
4957
ee81feb6
DB
4958SYSCALL_DEFINE5(renameat2, int, olddfd, const char __user *, oldname,
4959 int, newdfd, const char __user *, newname, unsigned int, flags)
4960{
e886663c
JA
4961 return do_renameat2(olddfd, getname(oldname), newdfd, getname(newname),
4962 flags);
ee81feb6
DB
4963}
4964
520c8b16
MS
4965SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname,
4966 int, newdfd, const char __user *, newname)
4967{
e886663c
JA
4968 return do_renameat2(olddfd, getname(oldname), newdfd, getname(newname),
4969 0);
520c8b16
MS
4970}
4971
a26eab24 4972SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname)
5590ff0d 4973{
e886663c
JA
4974 return do_renameat2(AT_FDCWD, getname(oldname), AT_FDCWD,
4975 getname(newname), 0);
5590ff0d
UD
4976}
4977
5d826c84 4978int readlink_copy(char __user *buffer, int buflen, const char *link)
1da177e4 4979{
5d826c84 4980 int len = PTR_ERR(link);
1da177e4
LT
4981 if (IS_ERR(link))
4982 goto out;
4983
4984 len = strlen(link);
4985 if (len > (unsigned) buflen)
4986 len = buflen;
4987 if (copy_to_user(buffer, link, len))
4988 len = -EFAULT;
4989out:
4990 return len;
4991}
4992
fd4a0edf
MS
4993/**
4994 * vfs_readlink - copy symlink body into userspace buffer
4995 * @dentry: dentry on which to get symbolic link
4996 * @buffer: user memory pointer
4997 * @buflen: size of buffer
4998 *
4999 * Does not touch atime. That's up to the caller if necessary
5000 *
5001 * Does not call security hook.
5002 */
5003int vfs_readlink(struct dentry *dentry, char __user *buffer, int buflen)
5004{
5005 struct inode *inode = d_inode(dentry);
f2df5da6
AV
5006 DEFINE_DELAYED_CALL(done);
5007 const char *link;
5008 int res;
fd4a0edf 5009
76fca90e
MS
5010 if (unlikely(!(inode->i_opflags & IOP_DEFAULT_READLINK))) {
5011 if (unlikely(inode->i_op->readlink))
5012 return inode->i_op->readlink(dentry, buffer, buflen);
5013
5014 if (!d_is_symlink(dentry))
5015 return -EINVAL;
5016
5017 spin_lock(&inode->i_lock);
5018 inode->i_opflags |= IOP_DEFAULT_READLINK;
5019 spin_unlock(&inode->i_lock);
5020 }
fd4a0edf 5021
4c4f7c19 5022 link = READ_ONCE(inode->i_link);
f2df5da6
AV
5023 if (!link) {
5024 link = inode->i_op->get_link(dentry, inode, &done);
5025 if (IS_ERR(link))
5026 return PTR_ERR(link);
5027 }
5028 res = readlink_copy(buffer, buflen, link);
5029 do_delayed_call(&done);
5030 return res;
fd4a0edf
MS
5031}
5032EXPORT_SYMBOL(vfs_readlink);
1da177e4 5033
d60874cd
MS
5034/**
5035 * vfs_get_link - get symlink body
5036 * @dentry: dentry on which to get symbolic link
5037 * @done: caller needs to free returned data with this
5038 *
5039 * Calls security hook and i_op->get_link() on the supplied inode.
5040 *
5041 * It does not touch atime. That's up to the caller if necessary.
5042 *
5043 * Does not work on "special" symlinks like /proc/$$/fd/N
5044 */
5045const char *vfs_get_link(struct dentry *dentry, struct delayed_call *done)
5046{
5047 const char *res = ERR_PTR(-EINVAL);
5048 struct inode *inode = d_inode(dentry);
5049
5050 if (d_is_symlink(dentry)) {
5051 res = ERR_PTR(security_inode_readlink(dentry));
5052 if (!res)
5053 res = inode->i_op->get_link(dentry, inode, done);
5054 }
5055 return res;
5056}
5057EXPORT_SYMBOL(vfs_get_link);
5058
1da177e4 5059/* get the link contents into pagecache */
6b255391 5060const char *page_get_link(struct dentry *dentry, struct inode *inode,
fceef393 5061 struct delayed_call *callback)
1da177e4 5062{
ebd09abb
DG
5063 char *kaddr;
5064 struct page *page;
6b255391
AV
5065 struct address_space *mapping = inode->i_mapping;
5066
d3883d4f
AV
5067 if (!dentry) {
5068 page = find_get_page(mapping, 0);
5069 if (!page)
5070 return ERR_PTR(-ECHILD);
5071 if (!PageUptodate(page)) {
5072 put_page(page);
5073 return ERR_PTR(-ECHILD);
5074 }
5075 } else {
5076 page = read_mapping_page(mapping, 0, NULL);
5077 if (IS_ERR(page))
5078 return (char*)page;
5079 }
fceef393 5080 set_delayed_call(callback, page_put_link, page);
21fc61c7
AV
5081 BUG_ON(mapping_gfp_mask(mapping) & __GFP_HIGHMEM);
5082 kaddr = page_address(page);
6b255391 5083 nd_terminate_link(kaddr, inode->i_size, PAGE_SIZE - 1);
ebd09abb 5084 return kaddr;
1da177e4
LT
5085}
5086
6b255391 5087EXPORT_SYMBOL(page_get_link);
1da177e4 5088
fceef393 5089void page_put_link(void *arg)
1da177e4 5090{
fceef393 5091 put_page(arg);
1da177e4 5092}
4d359507 5093EXPORT_SYMBOL(page_put_link);
1da177e4 5094
aa80deab
AV
5095int page_readlink(struct dentry *dentry, char __user *buffer, int buflen)
5096{
fceef393 5097 DEFINE_DELAYED_CALL(done);
6b255391
AV
5098 int res = readlink_copy(buffer, buflen,
5099 page_get_link(dentry, d_inode(dentry),
fceef393
AV
5100 &done));
5101 do_delayed_call(&done);
aa80deab
AV
5102 return res;
5103}
5104EXPORT_SYMBOL(page_readlink);
5105
56f5746c 5106int page_symlink(struct inode *inode, const char *symname, int len)
1da177e4
LT
5107{
5108 struct address_space *mapping = inode->i_mapping;
27a77913 5109 const struct address_space_operations *aops = mapping->a_ops;
56f5746c 5110 bool nofs = !mapping_gfp_constraint(mapping, __GFP_FS);
0adb25d2 5111 struct page *page;
afddba49 5112 void *fsdata;
beb497ab 5113 int err;
2d878178 5114 unsigned int flags;
1da177e4 5115
7e53cac4 5116retry:
2d878178
MWO
5117 if (nofs)
5118 flags = memalloc_nofs_save();
27a77913 5119 err = aops->write_begin(NULL, mapping, 0, len-1, &page, &fsdata);
2d878178
MWO
5120 if (nofs)
5121 memalloc_nofs_restore(flags);
1da177e4 5122 if (err)
afddba49
NP
5123 goto fail;
5124
21fc61c7 5125 memcpy(page_address(page), symname, len-1);
afddba49 5126
27a77913 5127 err = aops->write_end(NULL, mapping, 0, len-1, len-1,
afddba49 5128 page, fsdata);
1da177e4
LT
5129 if (err < 0)
5130 goto fail;
afddba49
NP
5131 if (err < len-1)
5132 goto retry;
5133
1da177e4
LT
5134 mark_inode_dirty(inode);
5135 return 0;
1da177e4
LT
5136fail:
5137 return err;
5138}
4d359507 5139EXPORT_SYMBOL(page_symlink);
0adb25d2 5140
92e1d5be 5141const struct inode_operations page_symlink_inode_operations = {
6b255391 5142 .get_link = page_get_link,
1da177e4 5143};
1da177e4 5144EXPORT_SYMBOL(page_symlink_inode_operations);