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