Merge tag 'pci-v6.16-fixes-3' of git://git.kernel.org/pub/scm/linux/kernel/git/pci/pci
[linux-2.6-block.git] / fs / open.c
CommitLineData
457c8996 1// SPDX-License-Identifier: GPL-2.0-only
1da177e4
LT
2/*
3 * linux/fs/open.c
4 *
5 * Copyright (C) 1991, 1992 Linus Torvalds
6 */
7
8#include <linux/string.h>
9#include <linux/mm.h>
1da177e4 10#include <linux/file.h>
9f3acc31 11#include <linux/fdtable.h>
0eeca283 12#include <linux/fsnotify.h>
1da177e4 13#include <linux/module.h>
1da177e4
LT
14#include <linux/tty.h>
15#include <linux/namei.h>
16#include <linux/backing-dev.h>
16f7e0fe 17#include <linux/capability.h>
086f7316 18#include <linux/securebits.h>
1da177e4
LT
19#include <linux/security.h>
20#include <linux/mount.h>
5590ff0d 21#include <linux/fcntl.h>
5a0e3ad6 22#include <linux/slab.h>
7c0f6ba6 23#include <linux/uaccess.h>
1da177e4 24#include <linux/fs.h>
ef3daeda 25#include <linux/personality.h>
1da177e4
LT
26#include <linux/pagemap.h>
27#include <linux/syscalls.h>
ab2af1f5 28#include <linux/rcupdate.h>
73241ccc 29#include <linux/audit.h>
97ac7350 30#include <linux/falloc.h>
5ad4e53b 31#include <linux/fs_struct.h>
2dfc1cae 32#include <linux/dnotify.h>
3f6d078d 33#include <linux/compat.h>
a793d79e 34#include <linux/mnt_idmapping.h>
5970e15d 35#include <linux/filelock.h>
1da177e4 36
e81e3f4d
EP
37#include "internal.h"
38
abf08576 39int do_truncate(struct mnt_idmap *idmap, struct dentry *dentry,
643fe55a 40 loff_t length, unsigned int time_attrs, struct file *filp)
1da177e4 41{
939a9421 42 int ret;
1da177e4
LT
43 struct iattr newattrs;
44
45 /* Not pretty: "inode->i_size" shouldn't really be signed. But it is. */
46 if (length < 0)
47 return -EINVAL;
48
49 newattrs.ia_size = length;
4a30131e 50 newattrs.ia_valid = ATTR_SIZE | time_attrs;
cc4e69de
MS
51 if (filp) {
52 newattrs.ia_file = filp;
53 newattrs.ia_valid |= ATTR_FILE;
54 }
1da177e4 55
45f147a1 56 /* Remove suid, sgid, and file capabilities on truncate too */
9452e93e 57 ret = dentry_needs_remove_privs(idmap, dentry);
45f147a1
JK
58 if (ret < 0)
59 return ret;
939a9421
AW
60 if (ret)
61 newattrs.ia_valid |= ret | ATTR_FORCE;
7b82dc0e 62
d6868756
MK
63 ret = inode_lock_killable(dentry->d_inode);
64 if (ret)
65 return ret;
66
27ac0ffe 67 /* Note any delegations or leases have already been broken: */
abf08576 68 ret = notify_change(idmap, dentry, &newattrs, NULL);
5955102c 69 inode_unlock(dentry->d_inode);
939a9421 70 return ret;
1da177e4
LT
71}
72
29d80d50 73int vfs_truncate(const struct path *path, loff_t length)
1da177e4 74{
abf08576 75 struct mnt_idmap *idmap;
2d8f3038 76 struct inode *inode;
29d80d50 77 int error;
1da177e4 78
a02de960 79 inode = path->dentry->d_inode;
1da177e4
LT
80
81 /* For directories it's -EISDIR, for other non-regulars - -EINVAL */
1da177e4 82 if (S_ISDIR(inode->i_mode))
a02de960 83 return -EISDIR;
1da177e4 84 if (!S_ISREG(inode->i_mode))
a02de960 85 return -EINVAL;
1da177e4 86
abf08576 87 idmap = mnt_idmap(path->mnt);
4609e1f1 88 error = inode_permission(idmap, inode, MAY_WRITE);
9ac9b847 89 if (error)
4acf3bc7
AG
90 return error;
91
92 error = fsnotify_truncate_perm(path, length);
93 if (error)
94 return error;
95
96 error = mnt_want_write(path->mnt);
97 if (error)
98 return error;
1da177e4
LT
99
100 error = -EPERM;
c82e42da 101 if (IS_APPEND(inode))
9ac9b847 102 goto mnt_drop_write_and_out;
1da177e4 103
8cf9ee50 104 error = get_write_access(inode);
1da177e4 105 if (error)
9ac9b847 106 goto mnt_drop_write_and_out;
1da177e4 107
9700382c 108 /*
109 * Make sure that there are no leases. get_write_access() protects
110 * against the truncate racing with a lease-granting setlease().
111 */
8737c930 112 error = break_lease(inode, O_WRONLY);
1da177e4 113 if (error)
9700382c 114 goto put_write_and_out;
1da177e4 115
f7e33bdb 116 error = security_path_truncate(path);
907f4554 117 if (!error)
abf08576 118 error = do_truncate(idmap, path->dentry, length, 0, NULL);
1da177e4 119
9700382c 120put_write_and_out:
8cf9ee50 121 put_write_access(inode);
9ac9b847 122mnt_drop_write_and_out:
a02de960 123 mnt_drop_write(path->mnt);
4acf3bc7 124
1da177e4
LT
125 return error;
126}
a02de960
DH
127EXPORT_SYMBOL_GPL(vfs_truncate);
128
29d80d50 129int do_sys_truncate(const char __user *pathname, loff_t length)
a02de960 130{
48f7530d 131 unsigned int lookup_flags = LOOKUP_FOLLOW;
a02de960
DH
132 struct path path;
133 int error;
134
135 if (length < 0) /* sorry, but loff_t says... */
136 return -EINVAL;
137
48f7530d
JL
138retry:
139 error = user_path_at(AT_FDCWD, pathname, lookup_flags, &path);
a02de960
DH
140 if (!error) {
141 error = vfs_truncate(&path, length);
142 path_put(&path);
143 }
48f7530d
JL
144 if (retry_estale(error, lookup_flags)) {
145 lookup_flags |= LOOKUP_REVAL;
146 goto retry;
147 }
a02de960
DH
148 return error;
149}
1da177e4 150
4fd8da8d 151SYSCALL_DEFINE2(truncate, const char __user *, path, long, length)
1da177e4 152{
4fd8da8d 153 return do_sys_truncate(path, length);
1da177e4
LT
154}
155
3f6d078d
AV
156#ifdef CONFIG_COMPAT
157COMPAT_SYSCALL_DEFINE2(truncate, const char __user *, path, compat_off_t, length)
158{
159 return do_sys_truncate(path, length);
160}
161#endif
162
29d80d50 163int do_ftruncate(struct file *file, loff_t length, int small)
1da177e4 164{
bf2965d5 165 struct inode *inode;
1da177e4 166 struct dentry *dentry;
1da177e4
LT
167 int error;
168
1da177e4 169 /* explicitly opened as large or we are on 64-bit box */
5f0d594c 170 if (file->f_flags & O_LARGEFILE)
1da177e4
LT
171 small = 0;
172
5f0d594c 173 dentry = file->f_path.dentry;
1da177e4 174 inode = dentry->d_inode;
5f0d594c
TS
175 if (!S_ISREG(inode->i_mode) || !(file->f_mode & FMODE_WRITE))
176 return -EINVAL;
1da177e4 177
1da177e4
LT
178 /* Cannot ftruncate over 2^31 bytes without large file support */
179 if (small && length > MAX_NON_LFS)
5f0d594c 180 return -EINVAL;
1da177e4 181
78757af6 182 /* Check IS_APPEND on real upper inode */
5f0d594c
TS
183 if (IS_APPEND(file_inode(file)))
184 return -EPERM;
4acf3bc7 185
5f0d594c 186 error = security_file_truncate(file);
4acf3bc7
AG
187 if (error)
188 return error;
189
190 error = fsnotify_truncate_perm(&file->f_path, length);
191 if (error)
192 return error;
193
194 sb_start_write(inode->i_sb);
195 error = do_truncate(file_mnt_idmap(file), dentry, length,
196 ATTR_MTIME | ATTR_CTIME, file);
14da9200 197 sb_end_write(inode->i_sb);
5f0d594c
TS
198
199 return error;
200}
201
29d80d50 202int do_sys_ftruncate(unsigned int fd, loff_t length, int small)
5f0d594c 203{
5f0d594c
TS
204 if (length < 0)
205 return -EINVAL;
8152f820
AV
206 CLASS(fd, f)(fd);
207 if (fd_empty(f))
5f0d594c
TS
208 return -EBADF;
209
8152f820 210 return do_ftruncate(fd_file(f), length, small);
1da177e4
LT
211}
212
4b8e88e5 213SYSCALL_DEFINE2(ftruncate, unsigned int, fd, off_t, length)
1da177e4 214{
2cf09666 215 return do_sys_ftruncate(fd, length, 1);
1da177e4
LT
216}
217
3f6d078d 218#ifdef CONFIG_COMPAT
4b8e88e5 219COMPAT_SYSCALL_DEFINE2(ftruncate, unsigned int, fd, compat_off_t, length)
3f6d078d
AV
220{
221 return do_sys_ftruncate(fd, length, 1);
222}
223#endif
224
1da177e4
LT
225/* LFS versions of truncate are only needed on 32 bit machines */
226#if BITS_PER_LONG == 32
4a0fd5bf 227SYSCALL_DEFINE2(truncate64, const char __user *, path, loff_t, length)
1da177e4
LT
228{
229 return do_sys_truncate(path, length);
230}
231
4a0fd5bf 232SYSCALL_DEFINE2(ftruncate64, unsigned int, fd, loff_t, length)
1da177e4 233{
2cf09666 234 return do_sys_ftruncate(fd, length, 0);
1da177e4 235}
6673e0c3 236#endif /* BITS_PER_LONG == 32 */
1da177e4 237
59c10c52
GR
238#if defined(CONFIG_COMPAT) && defined(__ARCH_WANT_COMPAT_TRUNCATE64)
239COMPAT_SYSCALL_DEFINE3(truncate64, const char __user *, pathname,
240 compat_arg_u64_dual(length))
241{
242 return ksys_truncate(pathname, compat_arg_u64_glue(length));
243}
244#endif
245
246#if defined(CONFIG_COMPAT) && defined(__ARCH_WANT_COMPAT_FTRUNCATE64)
247COMPAT_SYSCALL_DEFINE3(ftruncate64, unsigned int, fd,
248 compat_arg_u64_dual(length))
249{
250 return ksys_ftruncate(fd, compat_arg_u64_glue(length));
251}
252#endif
3e63cbb1 253
72c72bdf 254int vfs_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
97ac7350 255{
496ad9aa 256 struct inode *inode = file_inode(file);
29d80d50 257 int ret;
23cc6ef6 258 loff_t sum;
97ac7350
AA
259
260 if (offset < 0 || len <= 0)
3e63cbb1 261 return -EINVAL;
97ac7350 262
57413d8e 263 if (mode & ~(FALLOC_FL_MODE_MASK | FALLOC_FL_KEEP_SIZE))
409332b6
LC
264 return -EOPNOTSUPP;
265
57413d8e
CH
266 /*
267 * Modes are exclusive, even if that is not obvious from the encoding
268 * as bit masks and the mix with the flag in the same namespace.
269 *
270 * To make things even more complicated, FALLOC_FL_ALLOCATE_RANGE is
271 * encoded as no bit set.
272 */
273 switch (mode & FALLOC_FL_MODE_MASK) {
274 case FALLOC_FL_ALLOCATE_RANGE:
275 case FALLOC_FL_UNSHARE_RANGE:
276 case FALLOC_FL_ZERO_RANGE:
277 break;
278 case FALLOC_FL_PUNCH_HOLE:
279 if (!(mode & FALLOC_FL_KEEP_SIZE))
280 return -EOPNOTSUPP;
281 break;
282 case FALLOC_FL_COLLAPSE_RANGE:
283 case FALLOC_FL_INSERT_RANGE:
284 if (mode & FALLOC_FL_KEEP_SIZE)
285 return -EOPNOTSUPP;
286 break;
287 default:
3e63cbb1 288 return -EOPNOTSUPP;
57413d8e 289 }
71be6b49 290
97ac7350 291 if (!(file->f_mode & FMODE_WRITE))
3e63cbb1 292 return -EBADF;
1ca551c6 293
00f5e619 294 /*
57413d8e 295 * On append-only files only space preallocation is supported.
00f5e619 296 */
8fc61d92 297 if ((mode & ~FALLOC_FL_KEEP_SIZE) && IS_APPEND(inode))
1ca551c6
MS
298 return -EPERM;
299
300 if (IS_IMMUTABLE(inode))
301 return -EPERM;
302
0790b31b 303 /*
6d2b6170 304 * We cannot allow any fallocate operation on an active swapfile
0790b31b
LC
305 */
306 if (IS_SWAPFILE(inode))
6d2b6170 307 return -ETXTBSY;
0790b31b 308
97ac7350
AA
309 /*
310 * Revalidate the write permissions, in case security policy has
311 * changed since the files were opened.
312 */
313 ret = security_file_permission(file, MAY_WRITE);
314 if (ret)
3e63cbb1 315 return ret;
97ac7350 316
d9e5d310
AG
317 ret = fsnotify_file_area_perm(file, MAY_WRITE, &offset, len);
318 if (ret)
319 return ret;
320
97ac7350 321 if (S_ISFIFO(inode->i_mode))
3e63cbb1 322 return -ESPIPE;
97ac7350 323
9e79b132
AG
324 if (S_ISDIR(inode->i_mode))
325 return -EISDIR;
326
327 if (!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode))
3e63cbb1 328 return -ENODEV;
97ac7350 329
23cc6ef6
JS
330 /* Check for wraparound */
331 if (check_add_overflow(offset, len, &sum))
332 return -EFBIG;
333
334 if (sum > inode->i_sb->s_maxbytes)
3e63cbb1 335 return -EFBIG;
97ac7350 336
2fe17c10 337 if (!file->f_op->fallocate)
3e63cbb1 338 return -EOPNOTSUPP;
97ac7350 339
bfe219d3 340 file_start_write(file);
14da9200 341 ret = file->f_op->fallocate(file, mode, offset, len);
820c12d5
HS
342
343 /*
344 * Create inotify and fanotify events.
345 *
346 * To keep the logic simple always create events if fallocate succeeds.
347 * This implies that events are even created if the file size remains
348 * unchanged, e.g. when using flag FALLOC_FL_KEEP_SIZE.
349 */
350 if (ret == 0)
351 fsnotify_modify(file);
352
bfe219d3 353 file_end_write(file);
14da9200 354 return ret;
3e63cbb1 355}
72c72bdf 356EXPORT_SYMBOL_GPL(vfs_fallocate);
3e63cbb1 357
edf292c7 358int ksys_fallocate(int fd, int mode, loff_t offset, loff_t len)
3e63cbb1 359{
6348be02 360 CLASS(fd, f)(fd);
3e63cbb1 361
6348be02
AV
362 if (fd_empty(f))
363 return -EBADF;
364
365 return vfs_fallocate(fd_file(f), mode, offset, len);
97ac7350 366}
3e63cbb1 367
edf292c7
DB
368SYSCALL_DEFINE4(fallocate, int, fd, int, mode, loff_t, offset, loff_t, len)
369{
370 return ksys_fallocate(fd, mode, offset, len);
371}
372
59c10c52
GR
373#if defined(CONFIG_COMPAT) && defined(__ARCH_WANT_COMPAT_FALLOCATE)
374COMPAT_SYSCALL_DEFINE6(fallocate, int, fd, int, mode, compat_arg_u64_dual(offset),
375 compat_arg_u64_dual(len))
376{
377 return ksys_fallocate(fd, mode, compat_arg_u64_glue(offset),
378 compat_arg_u64_glue(len));
379}
380#endif
381
1da177e4
LT
382/*
383 * access() needs to use the real uid/gid, not the effective uid/gid.
384 * We do this by temporarily clearing all FS-related capabilities and
385 * switching the fsuid/fsgid around to the real ones.
981ee95c
MG
386 *
387 * Creating new credentials is expensive, so we try to skip doing it,
388 * which we can if the result would match what we already got.
1da177e4 389 */
981ee95c
MG
390static bool access_need_override_creds(int flags)
391{
392 const struct cred *cred;
393
394 if (flags & AT_EACCESS)
395 return false;
396
397 cred = current_cred();
398 if (!uid_eq(cred->fsuid, cred->uid) ||
399 !gid_eq(cred->fsgid, cred->gid))
400 return true;
401
402 if (!issecure(SECURE_NO_SETUID_FIXUP)) {
403 kuid_t root_uid = make_kuid(cred->user_ns, 0);
404 if (!uid_eq(cred->uid, root_uid)) {
405 if (!cap_isclear(cred->cap_effective))
406 return true;
407 } else {
408 if (!cap_isidentical(cred->cap_effective,
409 cred->cap_permitted))
410 return true;
411 }
412 }
413
414 return false;
415}
416
94704515 417static const struct cred *access_override_creds(void)
1da177e4 418{
d84f4f99 419 struct cred *override_cred;
1da177e4 420
d84f4f99
DH
421 override_cred = prepare_creds();
422 if (!override_cred)
94704515 423 return NULL;
1da177e4 424
981ee95c
MG
425 /*
426 * XXX access_need_override_creds performs checks in hopes of skipping
427 * this work. Make sure it stays in sync if making any changes in this
428 * routine.
429 */
430
d84f4f99
DH
431 override_cred->fsuid = override_cred->uid;
432 override_cred->fsgid = override_cred->gid;
1da177e4 433
086f7316 434 if (!issecure(SECURE_NO_SETUID_FIXUP)) {
1cdcbec1 435 /* Clear the capabilities if we switch to a non-root user */
18815a18
EB
436 kuid_t root_uid = make_kuid(override_cred->user_ns, 0);
437 if (!uid_eq(override_cred->uid, root_uid))
d84f4f99 438 cap_clear(override_cred->cap_effective);
086f7316 439 else
d84f4f99
DH
440 override_cred->cap_effective =
441 override_cred->cap_permitted;
086f7316 442 }
1da177e4 443
d7852fbd
LT
444 /*
445 * The new set of credentials can *only* be used in
446 * task-synchronous circumstances, and does not need
447 * RCU freeing, unless somebody then takes a separate
448 * reference to it.
449 *
450 * NOTE! This is _only_ true because this credential
451 * is used purely for override_creds() that installs
452 * it as the subjective cred. Other threads will be
453 * accessing ->real_cred, not the subjective cred.
454 *
455 * If somebody _does_ make a copy of this (using the
456 * 'get_current_cred()' function), that will clear the
457 * non_rcu field, because now that other user may be
458 * expecting RCU freeing. But normal thread-synchronous
d2185690
BS
459 * cred accesses will keep things non-racy to avoid RCU
460 * freeing.
d7852fbd
LT
461 */
462 override_cred->non_rcu = 1;
7708f3a7 463 return override_creds(override_cred);
94704515
MS
464}
465
29d80d50 466static int do_faccessat(int dfd, const char __user *filename, int mode, int flags)
94704515
MS
467{
468 struct path path;
469 struct inode *inode;
470 int res;
471 unsigned int lookup_flags = LOOKUP_FOLLOW;
c8ffd8bc 472 const struct cred *old_cred = NULL;
94704515
MS
473
474 if (mode & ~S_IRWXO) /* where's F_OK, X_OK, W_OK, R_OK? */
475 return -EINVAL;
476
c8ffd8bc
MS
477 if (flags & ~(AT_EACCESS | AT_SYMLINK_NOFOLLOW | AT_EMPTY_PATH))
478 return -EINVAL;
479
480 if (flags & AT_SYMLINK_NOFOLLOW)
481 lookup_flags &= ~LOOKUP_FOLLOW;
482 if (flags & AT_EMPTY_PATH)
483 lookup_flags |= LOOKUP_EMPTY;
484
981ee95c 485 if (access_need_override_creds(flags)) {
c8ffd8bc
MS
486 old_cred = access_override_creds();
487 if (!old_cred)
488 return -ENOMEM;
489 }
94704515 490
87fa5595
JL
491retry:
492 res = user_path_at(dfd, filename, lookup_flags, &path);
6902d925
DH
493 if (res)
494 goto out;
495
63afdfc7 496 inode = d_backing_inode(path.dentry);
256984a8
AV
497
498 if ((mode & MAY_EXEC) && S_ISREG(inode->i_mode)) {
30524472
AV
499 /*
500 * MAY_EXEC on regular files is denied if the fs is mounted
501 * with the "noexec" flag.
502 */
503 res = -EACCES;
90f8572b 504 if (path_noexec(&path))
30524472
AV
505 goto out_path_release;
506 }
507
4609e1f1 508 res = inode_permission(mnt_idmap(path.mnt), inode, mode | MAY_ACCESS);
6902d925 509 /* SuS v2 requires we report a read only fs too */
256984a8 510 if (res || !(mode & S_IWOTH) || special_file(inode->i_mode))
6902d925 511 goto out_path_release;
2f676cbc
DH
512 /*
513 * This is a rare case where using __mnt_is_readonly()
514 * is OK without a mnt_want/drop_write() pair. Since
515 * no actual write to the fs is performed here, we do
516 * not need to telegraph to that to anyone.
517 *
518 * By doing this, we accept that this access is
519 * inherently racy and know that the fs may change
520 * state before we even see this result.
521 */
2d8f3038 522 if (__mnt_is_readonly(path.mnt))
6902d925 523 res = -EROFS;
1da177e4 524
6902d925 525out_path_release:
2d8f3038 526 path_put(&path);
87fa5595
JL
527 if (retry_estale(res, lookup_flags)) {
528 lookup_flags |= LOOKUP_REVAL;
529 goto retry;
530 }
6902d925 531out:
c8ffd8bc 532 if (old_cred)
51c0bcf0 533 put_cred(revert_creds(old_cred));
c8ffd8bc 534
1da177e4
LT
535 return res;
536}
537
cbfe20f5
DB
538SYSCALL_DEFINE3(faccessat, int, dfd, const char __user *, filename, int, mode)
539{
c8ffd8bc
MS
540 return do_faccessat(dfd, filename, mode, 0);
541}
542
543SYSCALL_DEFINE4(faccessat2, int, dfd, const char __user *, filename, int, mode,
544 int, flags)
545{
546 return do_faccessat(dfd, filename, mode, flags);
cbfe20f5
DB
547}
548
ca013e94 549SYSCALL_DEFINE2(access, const char __user *, filename, int, mode)
5590ff0d 550{
c8ffd8bc 551 return do_faccessat(AT_FDCWD, filename, mode, 0);
5590ff0d
UD
552}
553
db63f1e3 554SYSCALL_DEFINE1(chdir, const char __user *, filename)
1da177e4 555{
2d8f3038 556 struct path path;
1da177e4 557 int error;
0291c0a5
JL
558 unsigned int lookup_flags = LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
559retry:
560 error = user_path_at(AT_FDCWD, filename, lookup_flags, &path);
1da177e4
LT
561 if (error)
562 goto out;
563
02f92b38 564 error = path_permission(&path, MAY_EXEC | MAY_CHDIR);
1da177e4
LT
565 if (error)
566 goto dput_and_out;
567
2d8f3038 568 set_fs_pwd(current->fs, &path);
1da177e4
LT
569
570dput_and_out:
2d8f3038 571 path_put(&path);
0291c0a5
JL
572 if (retry_estale(error, lookup_flags)) {
573 lookup_flags |= LOOKUP_REVAL;
574 goto retry;
575 }
1da177e4
LT
576out:
577 return error;
578}
579
3cdad428 580SYSCALL_DEFINE1(fchdir, unsigned int, fd)
1da177e4 581{
04818199 582 CLASS(fd_raw, f)(fd);
159b0956 583 int error;
1da177e4 584
04818199
AV
585 if (fd_empty(f))
586 return -EBADF;
1da177e4 587
1da91ea8 588 if (!d_can_lookup(fd_file(f)->f_path.dentry))
04818199 589 return -ENOTDIR;
1da177e4 590
1da91ea8 591 error = file_permission(fd_file(f), MAY_EXEC | MAY_CHDIR);
1da177e4 592 if (!error)
1da91ea8 593 set_fs_pwd(current->fs, &fd_file(f)->f_path);
1da177e4
LT
594 return error;
595}
596
4b7ca501 597SYSCALL_DEFINE1(chroot, const char __user *, filename)
1da177e4 598{
2d8f3038 599 struct path path;
1da177e4 600 int error;
2771261e
JL
601 unsigned int lookup_flags = LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
602retry:
603 error = user_path_at(AT_FDCWD, filename, lookup_flags, &path);
1da177e4
LT
604 if (error)
605 goto out;
606
02f92b38 607 error = path_permission(&path, MAY_EXEC | MAY_CHDIR);
1da177e4
LT
608 if (error)
609 goto dput_and_out;
610
611 error = -EPERM;
c7b96acf 612 if (!ns_capable(current_user_ns(), CAP_SYS_CHROOT))
1da177e4 613 goto dput_and_out;
8b8efb44
TH
614 error = security_path_chroot(&path);
615 if (error)
616 goto dput_and_out;
1da177e4 617
2d8f3038 618 set_fs_root(current->fs, &path);
1da177e4
LT
619 error = 0;
620dput_and_out:
2d8f3038 621 path_put(&path);
2771261e
JL
622 if (retry_estale(error, lookup_flags)) {
623 lookup_flags |= LOOKUP_REVAL;
624 goto retry;
625 }
1da177e4
LT
626out:
627 return error;
628}
629
1097742e 630int chmod_common(const struct path *path, umode_t mode)
1da177e4 631{
e57712eb 632 struct inode *inode = path->dentry->d_inode;
27ac0ffe 633 struct inode *delegated_inode = NULL;
1da177e4 634 struct iattr newattrs;
e57712eb 635 int error;
1da177e4 636
e57712eb
AV
637 error = mnt_want_write(path->mnt);
638 if (error)
639 return error;
27ac0ffe 640retry_deleg:
28a3f6ab
MK
641 error = inode_lock_killable(inode);
642 if (error)
643 goto out_mnt_unlock;
cdcf116d 644 error = security_path_chmod(path, mode);
e57712eb 645 if (error)
fe542cf5 646 goto out_unlock;
1da177e4
LT
647 newattrs.ia_mode = (mode & S_IALLUGO) | (inode->i_mode & ~S_IALLUGO);
648 newattrs.ia_valid = ATTR_MODE | ATTR_CTIME;
abf08576 649 error = notify_change(mnt_idmap(path->mnt), path->dentry,
b8b546a0 650 &newattrs, &delegated_inode);
fe542cf5 651out_unlock:
5955102c 652 inode_unlock(inode);
27ac0ffe
BF
653 if (delegated_inode) {
654 error = break_deleg_wait(&delegated_inode);
655 if (!error)
656 goto retry_deleg;
657 }
28a3f6ab 658out_mnt_unlock:
e57712eb
AV
659 mnt_drop_write(path->mnt);
660 return error;
661}
662
9e96c8c0
CH
663int vfs_fchmod(struct file *file, umode_t mode)
664{
665 audit_file(file);
666 return chmod_common(&file->f_path, mode);
667}
668
b25ba7c3 669SYSCALL_DEFINE2(fchmod, unsigned int, fd, umode_t, mode)
e57712eb 670{
6348be02 671 CLASS(fd, f)(fd);
e57712eb 672
6348be02
AV
673 if (fd_empty(f))
674 return -EBADF;
675
676 return vfs_fchmod(fd_file(f), mode);
1da177e4
LT
677}
678
09da082b
AG
679static int do_fchmodat(int dfd, const char __user *filename, umode_t mode,
680 unsigned int flags)
1da177e4 681{
2d8f3038 682 struct path path;
1da177e4 683 int error;
09da082b
AG
684 unsigned int lookup_flags;
685
5daeb41a 686 if (unlikely(flags & ~(AT_SYMLINK_NOFOLLOW | AT_EMPTY_PATH)))
09da082b
AG
687 return -EINVAL;
688
689 lookup_flags = (flags & AT_SYMLINK_NOFOLLOW) ? 0 : LOOKUP_FOLLOW;
5daeb41a
AS
690 if (flags & AT_EMPTY_PATH)
691 lookup_flags |= LOOKUP_EMPTY;
09da082b 692
14ff690c
JL
693retry:
694 error = user_path_at(dfd, filename, lookup_flags, &path);
e57712eb
AV
695 if (!error) {
696 error = chmod_common(&path, mode);
697 path_put(&path);
14ff690c
JL
698 if (retry_estale(error, lookup_flags)) {
699 lookup_flags |= LOOKUP_REVAL;
700 goto retry;
701 }
e57712eb 702 }
1da177e4
LT
703 return error;
704}
705
09da082b
AG
706SYSCALL_DEFINE4(fchmodat2, int, dfd, const char __user *, filename,
707 umode_t, mode, unsigned int, flags)
708{
709 return do_fchmodat(dfd, filename, mode, flags);
710}
711
03450e27
DB
712SYSCALL_DEFINE3(fchmodat, int, dfd, const char __user *, filename,
713 umode_t, mode)
714{
09da082b 715 return do_fchmodat(dfd, filename, mode, 0);
03450e27
DB
716}
717
49f0a076 718SYSCALL_DEFINE2(chmod, const char __user *, filename, umode_t, mode)
5590ff0d 719{
09da082b 720 return do_fchmodat(AT_FDCWD, filename, mode, 0);
5590ff0d
UD
721}
722
55650b2f 723/*
b27c82e1
CB
724 * Check whether @kuid is valid and if so generate and set vfsuid_t in
725 * ia_vfsuid.
726 *
727 * Return: true if @kuid is valid, false if not.
728 */
729static inline bool setattr_vfsuid(struct iattr *attr, kuid_t kuid)
730{
731 if (!uid_valid(kuid))
732 return false;
733 attr->ia_valid |= ATTR_UID;
734 attr->ia_vfsuid = VFSUIDT_INIT(kuid);
735 return true;
736}
737
55650b2f 738/*
b27c82e1
CB
739 * Check whether @kgid is valid and if so generate and set vfsgid_t in
740 * ia_vfsgid.
741 *
742 * Return: true if @kgid is valid, false if not.
743 */
744static inline bool setattr_vfsgid(struct iattr *attr, kgid_t kgid)
745{
746 if (!gid_valid(kgid))
747 return false;
748 attr->ia_valid |= ATTR_GID;
749 attr->ia_vfsgid = VFSGIDT_INIT(kgid);
750 return true;
751}
752
b873498f 753int chown_common(const struct path *path, uid_t user, gid_t group)
1da177e4 754{
abf08576 755 struct mnt_idmap *idmap;
4d7ca409 756 struct user_namespace *fs_userns;
fe542cf5 757 struct inode *inode = path->dentry->d_inode;
27ac0ffe 758 struct inode *delegated_inode = NULL;
1da177e4
LT
759 int error;
760 struct iattr newattrs;
52137abe
EB
761 kuid_t uid;
762 kgid_t gid;
763
764 uid = make_kuid(current_user_ns(), user);
765 gid = make_kgid(current_user_ns(), group);
1da177e4 766
abf08576 767 idmap = mnt_idmap(path->mnt);
bd303368 768 fs_userns = i_user_ns(inode);
b8b546a0 769
c1b8940b 770retry_deleg:
f52d74b1
TH
771 newattrs.ia_vfsuid = INVALID_VFSUID;
772 newattrs.ia_vfsgid = INVALID_VFSGID;
1da177e4 773 newattrs.ia_valid = ATTR_CTIME;
b27c82e1
CB
774 if ((user != (uid_t)-1) && !setattr_vfsuid(&newattrs, uid))
775 return -EINVAL;
776 if ((group != (gid_t)-1) && !setattr_vfsgid(&newattrs, gid))
777 return -EINVAL;
28a3f6ab
MK
778 error = inode_lock_killable(inode);
779 if (error)
780 return error;
ed5a7047
CB
781 if (!S_ISDIR(inode->i_mode))
782 newattrs.ia_valid |= ATTR_KILL_SUID | ATTR_KILL_PRIV |
9452e93e 783 setattr_should_drop_sgid(idmap, inode);
b27c82e1
CB
784 /* Continue to send actual fs values, not the mount values. */
785 error = security_path_chown(
786 path,
4d7ca409
CB
787 from_vfsuid(idmap, fs_userns, newattrs.ia_vfsuid),
788 from_vfsgid(idmap, fs_userns, newattrs.ia_vfsgid));
fe542cf5 789 if (!error)
abf08576 790 error = notify_change(idmap, path->dentry, &newattrs,
2f221d6f 791 &delegated_inode);
5955102c 792 inode_unlock(inode);
27ac0ffe
BF
793 if (delegated_inode) {
794 error = break_deleg_wait(&delegated_inode);
795 if (!error)
796 goto retry_deleg;
797 }
1da177e4
LT
798 return error;
799}
800
55731b3c
DB
801int do_fchownat(int dfd, const char __user *filename, uid_t user, gid_t group,
802 int flag)
5590ff0d 803{
2d8f3038 804 struct path path;
5590ff0d 805 int error = -EINVAL;
65cfc672 806 int lookup_flags;
5590ff0d 807
65cfc672 808 if ((flag & ~(AT_SYMLINK_NOFOLLOW | AT_EMPTY_PATH)) != 0)
5590ff0d
UD
809 goto out;
810
65cfc672
AV
811 lookup_flags = (flag & AT_SYMLINK_NOFOLLOW) ? 0 : LOOKUP_FOLLOW;
812 if (flag & AT_EMPTY_PATH)
813 lookup_flags |= LOOKUP_EMPTY;
99a5df37 814retry:
65cfc672 815 error = user_path_at(dfd, filename, lookup_flags, &path);
6902d925
DH
816 if (error)
817 goto out;
2d8f3038 818 error = mnt_want_write(path.mnt);
2af482a7
DH
819 if (error)
820 goto out_release;
fe542cf5 821 error = chown_common(&path, user, group);
2d8f3038 822 mnt_drop_write(path.mnt);
2af482a7 823out_release:
2d8f3038 824 path_put(&path);
99a5df37
JL
825 if (retry_estale(error, lookup_flags)) {
826 lookup_flags |= LOOKUP_REVAL;
827 goto retry;
828 }
5590ff0d
UD
829out:
830 return error;
831}
832
55731b3c
DB
833SYSCALL_DEFINE5(fchownat, int, dfd, const char __user *, filename, uid_t, user,
834 gid_t, group, int, flag)
835{
836 return do_fchownat(dfd, filename, user, group, flag);
837}
838
55e4def0 839SYSCALL_DEFINE3(chown, const char __user *, filename, uid_t, user, gid_t, group)
1da177e4 840{
55731b3c 841 return do_fchownat(AT_FDCWD, filename, user, group, 0);
55e4def0 842}
1da177e4 843
55e4def0
DH
844SYSCALL_DEFINE3(lchown, const char __user *, filename, uid_t, user, gid_t, group)
845{
55731b3c
DB
846 return do_fchownat(AT_FDCWD, filename, user, group,
847 AT_SYMLINK_NOFOLLOW);
1da177e4
LT
848}
849
c04011fe
CH
850int vfs_fchown(struct file *file, uid_t user, gid_t group)
851{
852 int error;
853
854 error = mnt_want_write_file(file);
855 if (error)
856 return error;
857 audit_file(file);
858 error = chown_common(&file->f_path, user, group);
859 mnt_drop_write_file(file);
860 return error;
861}
862
55731b3c 863int ksys_fchown(unsigned int fd, uid_t user, gid_t group)
1da177e4 864{
6348be02 865 CLASS(fd, f)(fd);
1da177e4 866
6348be02
AV
867 if (fd_empty(f))
868 return -EBADF;
869
870 return vfs_fchown(fd_file(f), user, group);
1da177e4
LT
871}
872
55731b3c
DB
873SYSCALL_DEFINE3(fchown, unsigned int, fd, uid_t, user, gid_t, group)
874{
875 return ksys_fchown(fd, user, group);
876}
877
83bc1d29
AG
878static inline int file_get_write_access(struct file *f)
879{
880 int error;
881
882 error = get_write_access(f->f_inode);
883 if (unlikely(error))
884 return error;
885 error = mnt_get_write_access(f->f_path.mnt);
886 if (unlikely(error))
887 goto cleanup_inode;
888 if (unlikely(f->f_mode & FMODE_BACKING)) {
def3ae83 889 error = mnt_get_write_access(backing_file_user_path(f)->mnt);
83bc1d29
AG
890 if (unlikely(error))
891 goto cleanup_mnt;
892 }
893 return 0;
894
895cleanup_mnt:
896 mnt_put_write_access(f->f_path.mnt);
897cleanup_inode:
898 put_write_access(f->f_inode);
899 return error;
900}
901
02e5180d 902static int do_dentry_open(struct file *f,
ae2bb293 903 int (*open)(struct inode *, struct file *))
1da177e4 904{
1abf0c71 905 static const struct file_operations empty_fops = {};
0f4a2ceb 906 struct inode *inode = f->f_path.dentry->d_inode;
1da177e4
LT
907 int error;
908
b5bcdda3 909 path_get(&f->f_path);
4bacc9c9 910 f->f_inode = inode;
1da177e4 911 f->f_mapping = inode->i_mapping;
5660e13d 912 f->f_wb_err = filemap_sample_wb_err(f->f_mapping);
735e4ae5 913 f->f_sb_err = file_sample_sb_err(f);
5660e13d 914
3f4d5a00 915 if (unlikely(f->f_flags & O_PATH)) {
95101401
AG
916 f->f_mode = FMODE_PATH | FMODE_OPENED;
917 file_set_fsnotify_mode(f, FMODE_NONOTIFY);
1abf0c71 918 f->f_op = &empty_fops;
af04fadc 919 return 0;
1abf0c71
AV
920 }
921
d6da19c9
AG
922 if ((f->f_mode & (FMODE_READ | FMODE_WRITE)) == FMODE_READ) {
923 i_readcount_inc(inode);
924 } else if (f->f_mode & FMODE_WRITE && !special_file(inode->i_mode)) {
83bc1d29 925 error = file_get_write_access(f);
3f4d5a00 926 if (unlikely(error))
1da177e4 927 goto cleanup_file;
83f936c7 928 f->f_mode |= FMODE_WRITER;
1da177e4
LT
929 }
930
2be7d348
LT
931 /* POSIX.1-2008/SUSv4 Section XSI 2.9.7 */
932 if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode))
933 f->f_mode |= FMODE_ATOMIC_POS;
934
1abf0c71 935 f->f_op = fops_get(inode->i_fop);
7159d544 936 if (WARN_ON(!f->f_op)) {
72c2d531
AV
937 error = -ENODEV;
938 goto cleanup_all;
939 }
1abf0c71 940
e3f20ae2 941 error = security_file_open(f);
788e7dd4
YN
942 if (error)
943 goto cleanup_all;
944
a94204f4
AG
945 /*
946 * Set FMODE_NONOTIFY_* bits according to existing permission watches.
2a42754b
AG
947 * If FMODE_NONOTIFY mode was already set for an fanotify fd or for a
948 * pseudo file, this call will not change the mode.
a94204f4 949 */
95101401 950 file_set_fsnotify_mode_from_watchers(f);
1cda52f1
SL
951 error = fsnotify_open_perm(f);
952 if (error)
953 goto cleanup_all;
954
c65454a9 955 error = break_lease(file_inode(f), f->f_flags);
f3c7691e
BF
956 if (error)
957 goto cleanup_all;
958
ea73ea72
AV
959 /* normally all 3 are set; ->open() can clear them if needed */
960 f->f_mode |= FMODE_LSEEK | FMODE_PREAD | FMODE_PWRITE;
72c2d531 961 if (!open)
834f2a4a
TM
962 open = f->f_op->open;
963 if (open) {
964 error = open(inode, f);
1da177e4
LT
965 if (error)
966 goto cleanup_all;
967 }
f5d11409 968 f->f_mode |= FMODE_OPENED;
293bc982 969 if ((f->f_mode & FMODE_READ) &&
84363182 970 likely(f->f_op->read || f->f_op->read_iter))
7f7f25e8 971 f->f_mode |= FMODE_CAN_READ;
293bc982 972 if ((f->f_mode & FMODE_WRITE) &&
84363182 973 likely(f->f_op->write || f->f_op->write_iter))
7f7f25e8 974 f->f_mode |= FMODE_CAN_WRITE;
e7478158
JD
975 if ((f->f_mode & FMODE_LSEEK) && !f->f_op->llseek)
976 f->f_mode &= ~FMODE_LSEEK;
a2ad63da
N
977 if (f->f_mapping->a_ops && f->f_mapping->a_ops->direct_IO)
978 f->f_mode |= FMODE_CAN_ODIRECT;
834f2a4a 979
1da177e4 980 f->f_flags &= ~(O_CREAT | O_EXCL | O_NOCTTY | O_TRUNC);
164f4064 981 f->f_iocb_flags = iocb_flags(f);
1da177e4
LT
982
983 file_ra_state_init(&f->f_ra, f->f_mapping->host->i_mapping);
af04fadc 984
a2ad63da
N
985 if ((f->f_flags & O_DIRECT) && !(f->f_mode & FMODE_CAN_ODIRECT))
986 return -EINVAL;
09d91cda
SL
987
988 /*
989 * XXX: Huge page cache doesn't support writing yet. Drop all page
990 * cache for this file before processing writes.
991 */
eb6ecbed
CF
992 if (f->f_mode & FMODE_WRITE) {
993 /*
8e344782
MG
994 * Depends on full fence from get_write_access() to synchronize
995 * against collapse_file() regarding i_writecount and nr_thps
996 * updates. Ensures subsequent insertion of THPs into the page
997 * cache will fail.
eb6ecbed 998 */
55fc0d91 999 if (filemap_nr_thps(inode->i_mapping)) {
8468e937
RW
1000 struct address_space *mapping = inode->i_mapping;
1001
55fc0d91 1002 filemap_invalidate_lock(inode->i_mapping);
8468e937
RW
1003 /*
1004 * unmap_mapping_range just need to be called once
1005 * here, because the private pages is not need to be
1006 * unmapped mapping (e.g. data segment of dynamic
1007 * shared libraries here).
1008 */
1009 unmap_mapping_range(mapping, 0, 0, 0);
1010 truncate_inode_pages(mapping, 0);
55fc0d91
RW
1011 filemap_invalidate_unlock(inode->i_mapping);
1012 }
eb6ecbed 1013 }
09d91cda 1014
96b7e579 1015 return 0;
1da177e4
LT
1016
1017cleanup_all:
6b4e8085
AV
1018 if (WARN_ON_ONCE(error > 0))
1019 error = -EINVAL;
1da177e4 1020 fops_put(f->f_op);
d6da19c9 1021 put_file_access(f);
1da177e4 1022cleanup_file:
02e5180d
AV
1023 path_put(&f->f_path);
1024 f->f_path.mnt = NULL;
1025 f->f_path.dentry = NULL;
dd37978c 1026 f->f_inode = NULL;
96b7e579 1027 return error;
1da177e4
LT
1028}
1029
d18e9008
MS
1030/**
1031 * finish_open - finish opening a file
0854d450 1032 * @file: file pointer
d18e9008
MS
1033 * @dentry: pointer to dentry
1034 * @open: open callback
1035 *
1036 * This can be used to finish opening a file passed to i_op->atomic_open().
1037 *
1038 * If the open callback is set to NULL, then the standard f_op->open()
1039 * filesystem callback is substituted.
0854d450
MS
1040 *
1041 * NB: the dentry reference is _not_ consumed. If, for example, the dentry is
1042 * the return value of d_splice_alias(), then the caller needs to perform dput()
1043 * on it after finish_open().
1044 *
0854d450 1045 * Returns zero on success or -errno if the open failed.
d18e9008 1046 */
30d90494 1047int finish_open(struct file *file, struct dentry *dentry,
be12af3e 1048 int (*open)(struct inode *, struct file *))
d18e9008 1049{
aad888f8 1050 BUG_ON(file->f_mode & FMODE_OPENED); /* once it's opened, it's opened */
d18e9008 1051
b5bcdda3 1052 file->f_path.dentry = dentry;
0f4a2ceb 1053 return do_dentry_open(file, open);
d18e9008
MS
1054}
1055EXPORT_SYMBOL(finish_open);
1056
1057/**
1058 * finish_no_open - finish ->atomic_open() without opening the file
1059 *
0854d450 1060 * @file: file pointer
d18e9008
MS
1061 * @dentry: dentry or NULL (as returned from ->lookup())
1062 *
1063 * This can be used to set the result of a successful lookup in ->atomic_open().
0854d450
MS
1064 *
1065 * NB: unlike finish_open() this function does consume the dentry reference and
1066 * the caller need not dput() it.
1067 *
64e1ac4d 1068 * Returns "0" which must be the return value of ->atomic_open() after having
0854d450 1069 * called this function.
d18e9008 1070 */
e45198a6 1071int finish_no_open(struct file *file, struct dentry *dentry)
d18e9008 1072{
30d90494 1073 file->f_path.dentry = dentry;
64e1ac4d 1074 return 0;
d18e9008
MS
1075}
1076EXPORT_SYMBOL(finish_no_open);
1077
9bf39ab2
MS
1078char *file_path(struct file *filp, char *buf, int buflen)
1079{
1080 return d_path(&filp->f_path, buf, buflen);
1081}
1082EXPORT_SYMBOL(file_path);
1083
4bacc9c9
DH
1084/**
1085 * vfs_open - open the file at the given path
1086 * @path: path to open
1087 * @file: newly allocated file with f_flag initialized
4bacc9c9 1088 */
ae2bb293 1089int vfs_open(const struct path *path, struct file *file)
4bacc9c9 1090{
7d1cf5e6
N
1091 int ret;
1092
54d5ca87 1093 file->f_path = *path;
7d1cf5e6
N
1094 ret = do_dentry_open(file, NULL);
1095 if (!ret) {
1096 /*
1097 * Once we return a file with FMODE_OPENED, __fput() will call
1098 * fsnotify_close(), so we need fsnotify_open() here for
1099 * symmetry.
1100 */
1101 fsnotify_open(file);
1102 }
1103 return ret;
4bacc9c9
DH
1104}
1105
765927b2 1106struct file *dentry_open(const struct path *path, int flags,
745ca247 1107 const struct cred *cred)
a1a5b3d9
PS
1108{
1109 int error;
1110 struct file *f;
1111
c212f9aa 1112 /* We must always pass in a valid mount pointer. */
765927b2 1113 BUG_ON(!path->mnt);
322ee5b3 1114
ea73ea72 1115 f = alloc_empty_file(flags, cred);
af04fadc 1116 if (!IS_ERR(f)) {
ae2bb293 1117 error = vfs_open(path, f);
4d27f326
AV
1118 if (error) {
1119 fput(f);
af04fadc
AV
1120 f = ERR_PTR(error);
1121 }
2a027e7a
AV
1122 }
1123 return f;
a1a5b3d9 1124}
1da177e4
LT
1125EXPORT_SYMBOL(dentry_open);
1126
ebe55960
AV
1127struct file *dentry_open_nonotify(const struct path *path, int flags,
1128 const struct cred *cred)
1129{
1130 struct file *f = alloc_empty_file(flags, cred);
1131 if (!IS_ERR(f)) {
1132 int error;
1133
95101401 1134 file_set_fsnotify_mode(f, FMODE_NONOTIFY);
ebe55960
AV
1135 error = vfs_open(path, f);
1136 if (error) {
1137 fput(f);
1138 f = ERR_PTR(error);
1139 }
1140 }
1141 return f;
1142}
1143
fb70bf12
CL
1144/**
1145 * dentry_create - Create and open a file
1146 * @path: path to create
1147 * @flags: O_ flags
1148 * @mode: mode bits for new file
1149 * @cred: credentials to use
1150 *
1151 * Caller must hold the parent directory's lock, and have prepared
1152 * a negative dentry, placed in @path->dentry, for the new file.
1153 *
1154 * Caller sets @path->mnt to the vfsmount of the filesystem where
1155 * the new file is to be created. The parent directory and the
1156 * negative dentry must reside on the same filesystem instance.
1157 *
1158 * On success, returns a "struct file *". Otherwise a ERR_PTR
1159 * is returned.
1160 */
1161struct file *dentry_create(const struct path *path, int flags, umode_t mode,
1162 const struct cred *cred)
1163{
1164 struct file *f;
1165 int error;
1166
fb70bf12
CL
1167 f = alloc_empty_file(flags, cred);
1168 if (IS_ERR(f))
1169 return f;
1170
abf08576 1171 error = vfs_create(mnt_idmap(path->mnt),
fb70bf12
CL
1172 d_inode(path->dentry->d_parent),
1173 path->dentry, mode, true);
1174 if (!error)
1175 error = vfs_open(path, f);
1176
1177 if (unlikely(error)) {
1178 fput(f);
1179 return ERR_PTR(error);
1180 }
1181 return f;
1182}
1183EXPORT_SYMBOL(dentry_create);
1184
cbb0b9d4
AG
1185/**
1186 * kernel_file_open - open a file for kernel internal use
1187 * @path: path of the file to open
1188 * @flags: open flags
cbb0b9d4
AG
1189 * @cred: credentials for open
1190 *
1191 * Open a file for use by in-kernel consumers. The file is not accounted
1192 * against nr_files and must not be installed into the file descriptor
1193 * table.
1194 *
1195 * Return: Opened file on success, an error pointer on failure.
1196 */
1197struct file *kernel_file_open(const struct path *path, int flags,
af58dc1f 1198 const struct cred *cred)
2abc77af 1199{
cbb0b9d4
AG
1200 struct file *f;
1201 int error;
2abc77af 1202
cbb0b9d4
AG
1203 f = alloc_empty_file_noaccount(flags, cred);
1204 if (IS_ERR(f))
1205 return f;
1206
1207 f->f_path = *path;
0f4a2ceb 1208 error = do_dentry_open(f, NULL);
cbb0b9d4
AG
1209 if (error) {
1210 fput(f);
7d1cf5e6 1211 return ERR_PTR(error);
2abc77af 1212 }
7d1cf5e6
N
1213
1214 fsnotify_open(f);
2abc77af
AV
1215 return f;
1216}
cbb0b9d4
AG
1217EXPORT_SYMBOL_GPL(kernel_file_open);
1218
fddb5d43
AS
1219#define WILL_CREATE(flags) (flags & (O_CREAT | __O_TMPFILE))
1220#define O_PATH_FLAGS (O_DIRECTORY | O_NOFOLLOW | O_PATH | O_CLOEXEC)
1221
35cb6d54 1222inline struct open_how build_open_how(int flags, umode_t mode)
fddb5d43
AS
1223{
1224 struct open_how how = {
1225 .flags = flags & VALID_OPEN_FLAGS,
1226 .mode = mode & S_IALLUGO,
1227 };
1228
1229 /* O_PATH beats everything else. */
1230 if (how.flags & O_PATH)
1231 how.flags &= O_PATH_FLAGS;
1232 /* Modes should only be set for create-like flags. */
1233 if (!WILL_CREATE(how.flags))
1234 how.mode = 0;
1235 return how;
1236}
1237
35cb6d54 1238inline int build_open_flags(const struct open_how *how, struct open_flags *op)
47c805dc 1239{
cfe80306 1240 u64 flags = how->flags;
ebe55960 1241 u64 strip = O_CLOEXEC;
47c805dc 1242 int lookup_flags = 0;
62fb4a15 1243 int acc_mode = ACC_MODE(flags);
47c805dc 1244
cfe80306
CB
1245 BUILD_BUG_ON_MSG(upper_32_bits(VALID_OPEN_FLAGS),
1246 "struct open_flags doesn't yet handle flags > 32 bits");
1247
1248 /*
ebe55960 1249 * Strip flags that aren't relevant in determining struct open_flags.
cfe80306
CB
1250 */
1251 flags &= ~strip;
fddb5d43 1252
629e014b 1253 /*
fddb5d43
AS
1254 * Older syscalls implicitly clear all of the invalid flags or argument
1255 * values before calling build_open_flags(), but openat2(2) checks all
1256 * of its arguments.
629e014b 1257 */
fddb5d43
AS
1258 if (flags & ~VALID_OPEN_FLAGS)
1259 return -EINVAL;
1260 if (how->resolve & ~VALID_RESOLVE_FLAGS)
1261 return -EINVAL;
629e014b 1262
398840f8
AS
1263 /* Scoping flags are mutually exclusive. */
1264 if ((how->resolve & RESOLVE_BENEATH) && (how->resolve & RESOLVE_IN_ROOT))
1265 return -EINVAL;
1266
fddb5d43
AS
1267 /* Deal with the mode. */
1268 if (WILL_CREATE(flags)) {
1269 if (how->mode & ~S_IALLUGO)
1270 return -EINVAL;
1271 op->mode = how->mode | S_IFREG;
1272 } else {
1273 if (how->mode != 0)
1274 return -EINVAL;
e68726ff 1275 op->mode = 0;
fddb5d43 1276 }
47c805dc
AV
1277
1278 /*
43b45063
CB
1279 * Block bugs where O_DIRECTORY | O_CREAT created regular files.
1280 * Note, that blocking O_DIRECTORY | O_CREAT here also protects
1281 * O_TMPFILE below which requires O_DIRECTORY being raised.
47c805dc 1282 */
43b45063
CB
1283 if ((flags & (O_DIRECTORY | O_CREAT)) == (O_DIRECTORY | O_CREAT))
1284 return -EINVAL;
1285
1286 /* Now handle the creative implementation of O_TMPFILE. */
bb458c64 1287 if (flags & __O_TMPFILE) {
43b45063
CB
1288 /*
1289 * In order to ensure programs get explicit errors when trying
1290 * to use O_TMPFILE on old kernels we enforce that O_DIRECTORY
1291 * is raised alongside __O_TMPFILE.
1292 */
1293 if (!(flags & O_DIRECTORY))
60545d0d 1294 return -EINVAL;
ba57ea64
AV
1295 if (!(acc_mode & MAY_WRITE))
1296 return -EINVAL;
fddb5d43
AS
1297 }
1298 if (flags & O_PATH) {
1299 /* O_PATH only permits certain other flags to be set. */
1300 if (flags & ~O_PATH_FLAGS)
1301 return -EINVAL;
1abf0c71 1302 acc_mode = 0;
1abf0c71 1303 }
47c805dc 1304
fddb5d43
AS
1305 /*
1306 * O_SYNC is implemented as __O_SYNC|O_DSYNC. As many places only
1307 * check for O_DSYNC if the need any syncing at all we enforce it's
1308 * always set instead of having to deal with possibly weird behaviour
1309 * for malicious applications setting only __O_SYNC.
1310 */
1311 if (flags & __O_SYNC)
1312 flags |= O_DSYNC;
1313
1abf0c71 1314 op->open_flag = flags;
47c805dc
AV
1315
1316 /* O_TRUNC implies we need access checks for write permissions */
1317 if (flags & O_TRUNC)
1318 acc_mode |= MAY_WRITE;
1319
1320 /* Allow the LSM permission hook to distinguish append
1321 access from general write access. */
1322 if (flags & O_APPEND)
1323 acc_mode |= MAY_APPEND;
1324
1325 op->acc_mode = acc_mode;
1326
1abf0c71
AV
1327 op->intent = flags & O_PATH ? 0 : LOOKUP_OPEN;
1328
47c805dc
AV
1329 if (flags & O_CREAT) {
1330 op->intent |= LOOKUP_CREATE;
31d1726d 1331 if (flags & O_EXCL) {
47c805dc 1332 op->intent |= LOOKUP_EXCL;
31d1726d
AV
1333 flags |= O_NOFOLLOW;
1334 }
47c805dc
AV
1335 }
1336
1337 if (flags & O_DIRECTORY)
1338 lookup_flags |= LOOKUP_DIRECTORY;
1339 if (!(flags & O_NOFOLLOW))
1340 lookup_flags |= LOOKUP_FOLLOW;
fddb5d43
AS
1341
1342 if (how->resolve & RESOLVE_NO_XDEV)
1343 lookup_flags |= LOOKUP_NO_XDEV;
1344 if (how->resolve & RESOLVE_NO_MAGICLINKS)
1345 lookup_flags |= LOOKUP_NO_MAGICLINKS;
1346 if (how->resolve & RESOLVE_NO_SYMLINKS)
1347 lookup_flags |= LOOKUP_NO_SYMLINKS;
1348 if (how->resolve & RESOLVE_BENEATH)
1349 lookup_flags |= LOOKUP_BENEATH;
1350 if (how->resolve & RESOLVE_IN_ROOT)
1351 lookup_flags |= LOOKUP_IN_ROOT;
99668f61
JA
1352 if (how->resolve & RESOLVE_CACHED) {
1353 /* Don't bother even trying for create/truncate/tmpfile open */
a0fc452a 1354 if (flags & (O_TRUNC | O_CREAT | __O_TMPFILE))
99668f61
JA
1355 return -EAGAIN;
1356 lookup_flags |= LOOKUP_CACHED;
1357 }
fddb5d43 1358
f9652e10
AV
1359 op->lookup_flags = lookup_flags;
1360 return 0;
47c805dc
AV
1361}
1362
669abf4e
JL
1363/**
1364 * file_open_name - open file and return file pointer
1365 *
1366 * @name: struct filename containing path to open
1367 * @flags: open flags as per the open(2) second argument
1368 * @mode: mode for the new file if O_CREAT is set, else ignored
1369 *
1370 * This is the helper to open a file from kernelspace if you really
1371 * have to. But in generally you should not do this, so please move
1372 * along, nothing to see here..
1373 */
1374struct file *file_open_name(struct filename *name, int flags, umode_t mode)
1375{
1376 struct open_flags op;
fddb5d43
AS
1377 struct open_how how = build_open_how(flags, mode);
1378 int err = build_open_flags(&how, &op);
1379 if (err)
1380 return ERR_PTR(err);
1381 return do_filp_open(AT_FDCWD, name, &op);
669abf4e
JL
1382}
1383
47c805dc
AV
1384/**
1385 * filp_open - open file and return file pointer
1386 *
1387 * @filename: path to open
1388 * @flags: open flags as per the open(2) second argument
1389 * @mode: mode for the new file if O_CREAT is set, else ignored
1390 *
1391 * This is the helper to open a file from kernelspace if you really
1392 * have to. But in generally you should not do this, so please move
1393 * along, nothing to see here..
1394 */
a218d0fd 1395struct file *filp_open(const char *filename, int flags, umode_t mode)
47c805dc 1396{
51689104
PM
1397 struct filename *name = getname_kernel(filename);
1398 struct file *file = ERR_CAST(name);
a69ce85e 1399
51689104
PM
1400 if (!IS_ERR(name)) {
1401 file = file_open_name(name, flags, mode);
1402 putname(name);
1403 }
1404 return file;
47c805dc
AV
1405}
1406EXPORT_SYMBOL(filp_open);
1407
ffb37ca3 1408struct file *file_open_root(const struct path *root,
378c6520 1409 const char *filename, int flags, umode_t mode)
73d049a4
AV
1410{
1411 struct open_flags op;
fddb5d43
AS
1412 struct open_how how = build_open_how(flags, mode);
1413 int err = build_open_flags(&how, &op);
f9652e10
AV
1414 if (err)
1415 return ERR_PTR(err);
ffb37ca3 1416 return do_file_open_root(root, filename, &op);
73d049a4
AV
1417}
1418EXPORT_SYMBOL(file_open_root);
1419
29d80d50
YT
1420static int do_sys_openat2(int dfd, const char __user *filename,
1421 struct open_how *how)
1da177e4 1422{
47c805dc 1423 struct open_flags op;
f9652e10 1424 struct filename *tmp;
d5a05a5a 1425 int err, fd;
f9652e10 1426
d5a05a5a
MG
1427 err = build_open_flags(how, &op);
1428 if (unlikely(err))
1429 return err;
f9652e10
AV
1430
1431 tmp = getname(filename);
1432 if (IS_ERR(tmp))
1433 return PTR_ERR(tmp);
1434
fddb5d43 1435 fd = get_unused_fd_flags(how->flags);
d5a05a5a 1436 if (likely(fd >= 0)) {
f9652e10
AV
1437 struct file *f = do_filp_open(dfd, tmp, &op);
1438 if (IS_ERR(f)) {
1439 put_unused_fd(fd);
1440 fd = PTR_ERR(f);
1441 } else {
f9652e10 1442 fd_install(fd, f);
1da177e4 1443 }
1da177e4 1444 }
f9652e10 1445 putname(tmp);
1da177e4 1446 return fd;
1da177e4 1447}
e922efc3 1448
29d80d50 1449int do_sys_open(int dfd, const char __user *filename, int flags, umode_t mode)
e922efc3 1450{
fddb5d43
AS
1451 struct open_how how = build_open_how(flags, mode);
1452 return do_sys_openat2(dfd, filename, &how);
1453}
e922efc3 1454
fddb5d43
AS
1455
1456SYSCALL_DEFINE3(open, const char __user *, filename, int, flags, umode_t, mode)
1457{
166e07c3
CH
1458 if (force_o_largefile())
1459 flags |= O_LARGEFILE;
1460 return do_sys_open(AT_FDCWD, filename, flags, mode);
e922efc3 1461}
1da177e4 1462
6559eed8 1463SYSCALL_DEFINE4(openat, int, dfd, const char __user *, filename, int, flags,
a218d0fd 1464 umode_t, mode)
5590ff0d
UD
1465{
1466 if (force_o_largefile())
1467 flags |= O_LARGEFILE;
2cf09666 1468 return do_sys_open(dfd, filename, flags, mode);
5590ff0d 1469}
5590ff0d 1470
fddb5d43
AS
1471SYSCALL_DEFINE4(openat2, int, dfd, const char __user *, filename,
1472 struct open_how __user *, how, size_t, usize)
1473{
1474 int err;
1475 struct open_how tmp;
1476
1477 BUILD_BUG_ON(sizeof(struct open_how) < OPEN_HOW_SIZE_VER0);
1478 BUILD_BUG_ON(sizeof(struct open_how) != OPEN_HOW_SIZE_LATEST);
1479
1480 if (unlikely(usize < OPEN_HOW_SIZE_VER0))
1481 return -EINVAL;
f92f0a1b
AS
1482 if (unlikely(usize > PAGE_SIZE))
1483 return -E2BIG;
fddb5d43
AS
1484
1485 err = copy_struct_from_user(&tmp, sizeof(tmp), how, usize);
1486 if (err)
1487 return err;
1488
571e5c0e
RGB
1489 audit_openat2_how(&tmp);
1490
fddb5d43
AS
1491 /* O_LARGEFILE is only allowed for non-O_PATH. */
1492 if (!(tmp.flags & O_PATH) && force_o_largefile())
1493 tmp.flags |= O_LARGEFILE;
1494
1495 return do_sys_openat2(dfd, filename, &tmp);
1496}
1497
e35d49f6
AV
1498#ifdef CONFIG_COMPAT
1499/*
1500 * Exactly like sys_open(), except that it doesn't set the
1501 * O_LARGEFILE flag.
1502 */
1503COMPAT_SYSCALL_DEFINE3(open, const char __user *, filename, int, flags, umode_t, mode)
1504{
1505 return do_sys_open(AT_FDCWD, filename, flags, mode);
1506}
1507
1508/*
1509 * Exactly like sys_openat(), except that it doesn't set the
1510 * O_LARGEFILE flag.
1511 */
1512COMPAT_SYSCALL_DEFINE4(openat, int, dfd, const char __user *, filename, int, flags, umode_t, mode)
1513{
1514 return do_sys_open(dfd, filename, flags, mode);
1515}
1516#endif
1517
1da177e4
LT
1518#ifndef __alpha__
1519
1520/*
1521 * For backward compatibility? Maybe this should be moved
1522 * into arch/i386 instead?
1523 */
a218d0fd 1524SYSCALL_DEFINE2(creat, const char __user *, pathname, umode_t, mode)
1da177e4 1525{
166e07c3 1526 int flags = O_CREAT | O_WRONLY | O_TRUNC;
1da177e4 1527
166e07c3
CH
1528 if (force_o_largefile())
1529 flags |= O_LARGEFILE;
1530 return do_sys_open(AT_FDCWD, pathname, flags, mode);
1531}
1da177e4
LT
1532#endif
1533
1534/*
1535 * "id" is the POSIX thread ID. We use the
1536 * files pointer for this..
1537 */
021a160a 1538static int filp_flush(struct file *filp, fl_owner_t id)
1da177e4 1539{
45778ca8 1540 int retval = 0;
1da177e4 1541
30cee1e4 1542 if (CHECK_DATA_CORRUPTION(file_count(filp) == 0, filp,
47d58691
JH
1543 "VFS: Close: file count is 0 (f_op=%ps)",
1544 filp->f_op)) {
45778ca8 1545 return 0;
1da177e4
LT
1546 }
1547
72c2d531 1548 if (filp->f_op->flush)
75e1fcc0 1549 retval = filp->f_op->flush(filp, id);
1da177e4 1550
1abf0c71
AV
1551 if (likely(!(filp->f_mode & FMODE_PATH))) {
1552 dnotify_flush(filp, id);
1553 locks_remove_posix(filp, id);
1554 }
1da177e4
LT
1555 return retval;
1556}
1557
021a160a
LT
1558int filp_close(struct file *filp, fl_owner_t id)
1559{
1560 int retval;
1561
1562 retval = filp_flush(filp, id);
a914bd93 1563 fput_close(filp);
021a160a
LT
1564
1565 return retval;
1566}
1da177e4
LT
1567EXPORT_SYMBOL(filp_close);
1568
1569/*
1570 * Careful here! We test whether the file pointer is NULL before
1571 * releasing the fd. This ensures that one clone task can't release
1572 * an fd while another clone is opening it.
1573 */
ca013e94 1574SYSCALL_DEFINE1(close, unsigned int, fd)
1da177e4 1575{
021a160a
LT
1576 int retval;
1577 struct file *file;
1578
a88c955f 1579 file = file_close_fd(fd);
021a160a
LT
1580 if (!file)
1581 return -EBADF;
1582
1583 retval = filp_flush(file, current->files);
1584
1585 /*
1586 * We're returning to user space. Don't bother
1587 * with any delayed fput() cases.
1588 */
3e46a92a 1589 fput_close_sync(file);
ee731f4f 1590
23e49033
MG
1591 if (likely(retval == 0))
1592 return 0;
ee731f4f
EP
1593
1594 /* can't restart close syscall because file table entry was cleared */
23e49033
MG
1595 if (retval == -ERESTARTSYS ||
1596 retval == -ERESTARTNOINTR ||
1597 retval == -ERESTARTNOHAND ||
1598 retval == -ERESTART_RESTARTBLOCK)
ee731f4f
EP
1599 retval = -EINTR;
1600
1601 return retval;
1da177e4 1602}
1da177e4
LT
1603
1604/*
1605 * This routine simulates a hangup on the tty, to arrange that users
1606 * are given clean terminals at login time.
1607 */
ca013e94 1608SYSCALL_DEFINE0(vhangup)
1da177e4
LT
1609{
1610 if (capable(CAP_SYS_TTY_CONFIG)) {
2cb5998b 1611 tty_vhangup_self();
1da177e4
LT
1612 return 0;
1613 }
1614 return -EPERM;
1615}
1616
1617/*
1618 * Called when an inode is about to be open.
1619 * We use this to disallow opening large files on 32bit systems if
1620 * the caller didn't specify O_LARGEFILE. On 64bit systems we force
1621 * on this flag in sys_open.
1622 */
1623int generic_file_open(struct inode * inode, struct file * filp)
1624{
1625 if (!(filp->f_flags & O_LARGEFILE) && i_size_read(inode) > MAX_NON_LFS)
a9c62a18 1626 return -EOVERFLOW;
1da177e4
LT
1627 return 0;
1628}
1629
1630EXPORT_SYMBOL(generic_file_open);
1631
1632/*
1633 * This is used by subsystems that don't want seekable
06b1e104
DT
1634 * file descriptors. The function is not supposed to ever fail, the only
1635 * reason it returns an 'int' and not 'void' is so that it can be plugged
1636 * directly into file_operations structure.
1da177e4
LT
1637 */
1638int nonseekable_open(struct inode *inode, struct file *filp)
1639{
1640 filp->f_mode &= ~(FMODE_LSEEK | FMODE_PREAD | FMODE_PWRITE);
1641 return 0;
1642}
1643
1644EXPORT_SYMBOL(nonseekable_open);
10dce8af
KS
1645
1646/*
1647 * stream_open is used by subsystems that want stream-like file descriptors.
1648 * Such file descriptors are not seekable and don't have notion of position
438ab720
KS
1649 * (file.f_pos is always 0 and ppos passed to .read()/.write() is always NULL).
1650 * Contrary to file descriptors of other regular files, .read() and .write()
1651 * can run simultaneously.
10dce8af
KS
1652 *
1653 * stream_open never fails and is marked to return int so that it could be
1654 * directly used as file_operations.open .
1655 */
1656int stream_open(struct inode *inode, struct file *filp)
1657{
2be7d348 1658 filp->f_mode &= ~(FMODE_LSEEK | FMODE_PREAD | FMODE_PWRITE | FMODE_ATOMIC_POS);
10dce8af
KS
1659 filp->f_mode |= FMODE_STREAM;
1660 return 0;
1661}
1662
1663EXPORT_SYMBOL(stream_open);