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