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