1 // SPDX-License-Identifier: GPL-2.0-only
5 * Copyright (C) 1991, 1992 Linus Torvalds
8 #include <linux/string.h>
10 #include <linux/file.h>
11 #include <linux/fdtable.h>
12 #include <linux/fsnotify.h>
13 #include <linux/module.h>
14 #include <linux/tty.h>
15 #include <linux/namei.h>
16 #include <linux/backing-dev.h>
17 #include <linux/capability.h>
18 #include <linux/securebits.h>
19 #include <linux/security.h>
20 #include <linux/mount.h>
21 #include <linux/fcntl.h>
22 #include <linux/slab.h>
23 #include <linux/uaccess.h>
25 #include <linux/personality.h>
26 #include <linux/pagemap.h>
27 #include <linux/syscalls.h>
28 #include <linux/rcupdate.h>
29 #include <linux/audit.h>
30 #include <linux/falloc.h>
31 #include <linux/fs_struct.h>
32 #include <linux/dnotify.h>
33 #include <linux/compat.h>
34 #include <linux/mnt_idmapping.h>
35 #include <linux/filelock.h>
39 int do_truncate(struct mnt_idmap *idmap, struct dentry *dentry,
40 loff_t length, unsigned int time_attrs, struct file *filp)
43 struct iattr newattrs;
45 /* Not pretty: "inode->i_size" shouldn't really be signed. But it is. */
49 newattrs.ia_size = length;
50 newattrs.ia_valid = ATTR_SIZE | time_attrs;
52 newattrs.ia_file = filp;
53 newattrs.ia_valid |= ATTR_FILE;
56 /* Remove suid, sgid, and file capabilities on truncate too */
57 ret = dentry_needs_remove_privs(idmap, dentry);
61 newattrs.ia_valid |= ret | ATTR_FORCE;
63 inode_lock(dentry->d_inode);
64 /* Note any delegations or leases have already been broken: */
65 ret = notify_change(idmap, dentry, &newattrs, NULL);
66 inode_unlock(dentry->d_inode);
70 long vfs_truncate(const struct path *path, loff_t length)
72 struct mnt_idmap *idmap;
76 inode = path->dentry->d_inode;
78 /* For directories it's -EISDIR, for other non-regulars - -EINVAL */
79 if (S_ISDIR(inode->i_mode))
81 if (!S_ISREG(inode->i_mode))
84 error = mnt_want_write(path->mnt);
88 idmap = mnt_idmap(path->mnt);
89 error = inode_permission(idmap, inode, MAY_WRITE);
91 goto mnt_drop_write_and_out;
95 goto mnt_drop_write_and_out;
97 error = get_write_access(inode);
99 goto mnt_drop_write_and_out;
102 * Make sure that there are no leases. get_write_access() protects
103 * against the truncate racing with a lease-granting setlease().
105 error = break_lease(inode, O_WRONLY);
107 goto put_write_and_out;
109 error = security_path_truncate(path);
111 error = do_truncate(idmap, path->dentry, length, 0, NULL);
114 put_write_access(inode);
115 mnt_drop_write_and_out:
116 mnt_drop_write(path->mnt);
120 EXPORT_SYMBOL_GPL(vfs_truncate);
122 long do_sys_truncate(const char __user *pathname, loff_t length)
124 unsigned int lookup_flags = LOOKUP_FOLLOW;
128 if (length < 0) /* sorry, but loff_t says... */
132 error = user_path_at(AT_FDCWD, pathname, lookup_flags, &path);
134 error = vfs_truncate(&path, length);
137 if (retry_estale(error, lookup_flags)) {
138 lookup_flags |= LOOKUP_REVAL;
144 SYSCALL_DEFINE2(truncate, const char __user *, path, long, length)
146 return do_sys_truncate(path, length);
150 COMPAT_SYSCALL_DEFINE2(truncate, const char __user *, path, compat_off_t, length)
152 return do_sys_truncate(path, length);
156 long do_ftruncate(struct file *file, loff_t length, int small)
159 struct dentry *dentry;
162 /* explicitly opened as large or we are on 64-bit box */
163 if (file->f_flags & O_LARGEFILE)
166 dentry = file->f_path.dentry;
167 inode = dentry->d_inode;
168 if (!S_ISREG(inode->i_mode) || !(file->f_mode & FMODE_WRITE))
171 /* Cannot ftruncate over 2^31 bytes without large file support */
172 if (small && length > MAX_NON_LFS)
175 /* Check IS_APPEND on real upper inode */
176 if (IS_APPEND(file_inode(file)))
178 sb_start_write(inode->i_sb);
179 error = security_file_truncate(file);
181 error = do_truncate(file_mnt_idmap(file), dentry, length,
182 ATTR_MTIME | ATTR_CTIME, file);
183 sb_end_write(inode->i_sb);
188 long do_sys_ftruncate(unsigned int fd, loff_t length, int small)
199 error = do_ftruncate(f.file, length, small);
205 SYSCALL_DEFINE2(ftruncate, unsigned int, fd, off_t, length)
207 return do_sys_ftruncate(fd, length, 1);
211 COMPAT_SYSCALL_DEFINE2(ftruncate, unsigned int, fd, compat_off_t, length)
213 return do_sys_ftruncate(fd, length, 1);
217 /* LFS versions of truncate are only needed on 32 bit machines */
218 #if BITS_PER_LONG == 32
219 SYSCALL_DEFINE2(truncate64, const char __user *, path, loff_t, length)
221 return do_sys_truncate(path, length);
224 SYSCALL_DEFINE2(ftruncate64, unsigned int, fd, loff_t, length)
226 return do_sys_ftruncate(fd, length, 0);
228 #endif /* BITS_PER_LONG == 32 */
230 #if defined(CONFIG_COMPAT) && defined(__ARCH_WANT_COMPAT_TRUNCATE64)
231 COMPAT_SYSCALL_DEFINE3(truncate64, const char __user *, pathname,
232 compat_arg_u64_dual(length))
234 return ksys_truncate(pathname, compat_arg_u64_glue(length));
238 #if defined(CONFIG_COMPAT) && defined(__ARCH_WANT_COMPAT_FTRUNCATE64)
239 COMPAT_SYSCALL_DEFINE3(ftruncate64, unsigned int, fd,
240 compat_arg_u64_dual(length))
242 return ksys_ftruncate(fd, compat_arg_u64_glue(length));
246 int vfs_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
248 struct inode *inode = file_inode(file);
252 if (offset < 0 || len <= 0)
255 /* Return error if mode is not supported */
256 if (mode & ~FALLOC_FL_SUPPORTED_MASK)
259 /* Punch hole and zero range are mutually exclusive */
260 if ((mode & (FALLOC_FL_PUNCH_HOLE | FALLOC_FL_ZERO_RANGE)) ==
261 (FALLOC_FL_PUNCH_HOLE | FALLOC_FL_ZERO_RANGE))
264 /* Punch hole must have keep size set */
265 if ((mode & FALLOC_FL_PUNCH_HOLE) &&
266 !(mode & FALLOC_FL_KEEP_SIZE))
269 /* Collapse range should only be used exclusively. */
270 if ((mode & FALLOC_FL_COLLAPSE_RANGE) &&
271 (mode & ~FALLOC_FL_COLLAPSE_RANGE))
274 /* Insert range should only be used exclusively. */
275 if ((mode & FALLOC_FL_INSERT_RANGE) &&
276 (mode & ~FALLOC_FL_INSERT_RANGE))
279 /* Unshare range should only be used with allocate mode. */
280 if ((mode & FALLOC_FL_UNSHARE_RANGE) &&
281 (mode & ~(FALLOC_FL_UNSHARE_RANGE | FALLOC_FL_KEEP_SIZE)))
284 if (!(file->f_mode & FMODE_WRITE))
288 * We can only allow pure fallocate on append only files
290 if ((mode & ~FALLOC_FL_KEEP_SIZE) && IS_APPEND(inode))
293 if (IS_IMMUTABLE(inode))
297 * We cannot allow any fallocate operation on an active swapfile
299 if (IS_SWAPFILE(inode))
303 * Revalidate the write permissions, in case security policy has
304 * changed since the files were opened.
306 ret = security_file_permission(file, MAY_WRITE);
310 ret = fsnotify_file_area_perm(file, MAY_WRITE, &offset, len);
314 if (S_ISFIFO(inode->i_mode))
317 if (S_ISDIR(inode->i_mode))
320 if (!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode))
323 /* Check for wraparound */
324 if (check_add_overflow(offset, len, &sum))
327 if (sum > inode->i_sb->s_maxbytes)
330 if (!file->f_op->fallocate)
333 file_start_write(file);
334 ret = file->f_op->fallocate(file, mode, offset, len);
337 * Create inotify and fanotify events.
339 * To keep the logic simple always create events if fallocate succeeds.
340 * This implies that events are even created if the file size remains
341 * unchanged, e.g. when using flag FALLOC_FL_KEEP_SIZE.
344 fsnotify_modify(file);
346 file_end_write(file);
349 EXPORT_SYMBOL_GPL(vfs_fallocate);
351 int ksys_fallocate(int fd, int mode, loff_t offset, loff_t len)
353 struct fd f = fdget(fd);
357 error = vfs_fallocate(f.file, mode, offset, len);
363 SYSCALL_DEFINE4(fallocate, int, fd, int, mode, loff_t, offset, loff_t, len)
365 return ksys_fallocate(fd, mode, offset, len);
368 #if defined(CONFIG_COMPAT) && defined(__ARCH_WANT_COMPAT_FALLOCATE)
369 COMPAT_SYSCALL_DEFINE6(fallocate, int, fd, int, mode, compat_arg_u64_dual(offset),
370 compat_arg_u64_dual(len))
372 return ksys_fallocate(fd, mode, compat_arg_u64_glue(offset),
373 compat_arg_u64_glue(len));
378 * access() needs to use the real uid/gid, not the effective uid/gid.
379 * We do this by temporarily clearing all FS-related capabilities and
380 * switching the fsuid/fsgid around to the real ones.
382 * Creating new credentials is expensive, so we try to skip doing it,
383 * which we can if the result would match what we already got.
385 static bool access_need_override_creds(int flags)
387 const struct cred *cred;
389 if (flags & AT_EACCESS)
392 cred = current_cred();
393 if (!uid_eq(cred->fsuid, cred->uid) ||
394 !gid_eq(cred->fsgid, cred->gid))
397 if (!issecure(SECURE_NO_SETUID_FIXUP)) {
398 kuid_t root_uid = make_kuid(cred->user_ns, 0);
399 if (!uid_eq(cred->uid, root_uid)) {
400 if (!cap_isclear(cred->cap_effective))
403 if (!cap_isidentical(cred->cap_effective,
404 cred->cap_permitted))
412 static const struct cred *access_override_creds(void)
414 const struct cred *old_cred;
415 struct cred *override_cred;
417 override_cred = prepare_creds();
422 * XXX access_need_override_creds performs checks in hopes of skipping
423 * this work. Make sure it stays in sync if making any changes in this
427 override_cred->fsuid = override_cred->uid;
428 override_cred->fsgid = override_cred->gid;
430 if (!issecure(SECURE_NO_SETUID_FIXUP)) {
431 /* Clear the capabilities if we switch to a non-root user */
432 kuid_t root_uid = make_kuid(override_cred->user_ns, 0);
433 if (!uid_eq(override_cred->uid, root_uid))
434 cap_clear(override_cred->cap_effective);
436 override_cred->cap_effective =
437 override_cred->cap_permitted;
441 * The new set of credentials can *only* be used in
442 * task-synchronous circumstances, and does not need
443 * RCU freeing, unless somebody then takes a separate
446 * NOTE! This is _only_ true because this credential
447 * is used purely for override_creds() that installs
448 * it as the subjective cred. Other threads will be
449 * accessing ->real_cred, not the subjective cred.
451 * If somebody _does_ make a copy of this (using the
452 * 'get_current_cred()' function), that will clear the
453 * non_rcu field, because now that other user may be
454 * expecting RCU freeing. But normal thread-synchronous
455 * cred accesses will keep things non-racy to avoid RCU
458 override_cred->non_rcu = 1;
460 old_cred = override_creds(override_cred);
462 /* override_cred() gets its own ref */
463 put_cred(override_cred);
468 static long do_faccessat(int dfd, const char __user *filename, int mode, int flags)
473 unsigned int lookup_flags = LOOKUP_FOLLOW;
474 const struct cred *old_cred = NULL;
476 if (mode & ~S_IRWXO) /* where's F_OK, X_OK, W_OK, R_OK? */
479 if (flags & ~(AT_EACCESS | AT_SYMLINK_NOFOLLOW | AT_EMPTY_PATH))
482 if (flags & AT_SYMLINK_NOFOLLOW)
483 lookup_flags &= ~LOOKUP_FOLLOW;
484 if (flags & AT_EMPTY_PATH)
485 lookup_flags |= LOOKUP_EMPTY;
487 if (access_need_override_creds(flags)) {
488 old_cred = access_override_creds();
494 res = user_path_at(dfd, filename, lookup_flags, &path);
498 inode = d_backing_inode(path.dentry);
500 if ((mode & MAY_EXEC) && S_ISREG(inode->i_mode)) {
502 * MAY_EXEC on regular files is denied if the fs is mounted
503 * with the "noexec" flag.
506 if (path_noexec(&path))
507 goto out_path_release;
510 res = inode_permission(mnt_idmap(path.mnt), inode, mode | MAY_ACCESS);
511 /* SuS v2 requires we report a read only fs too */
512 if (res || !(mode & S_IWOTH) || special_file(inode->i_mode))
513 goto out_path_release;
515 * This is a rare case where using __mnt_is_readonly()
516 * is OK without a mnt_want/drop_write() pair. Since
517 * no actual write to the fs is performed here, we do
518 * not need to telegraph to that to anyone.
520 * By doing this, we accept that this access is
521 * inherently racy and know that the fs may change
522 * state before we even see this result.
524 if (__mnt_is_readonly(path.mnt))
529 if (retry_estale(res, lookup_flags)) {
530 lookup_flags |= LOOKUP_REVAL;
535 revert_creds(old_cred);
540 SYSCALL_DEFINE3(faccessat, int, dfd, const char __user *, filename, int, mode)
542 return do_faccessat(dfd, filename, mode, 0);
545 SYSCALL_DEFINE4(faccessat2, int, dfd, const char __user *, filename, int, mode,
548 return do_faccessat(dfd, filename, mode, flags);
551 SYSCALL_DEFINE2(access, const char __user *, filename, int, mode)
553 return do_faccessat(AT_FDCWD, filename, mode, 0);
556 SYSCALL_DEFINE1(chdir, const char __user *, filename)
560 unsigned int lookup_flags = LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
562 error = user_path_at(AT_FDCWD, filename, lookup_flags, &path);
566 error = path_permission(&path, MAY_EXEC | MAY_CHDIR);
570 set_fs_pwd(current->fs, &path);
574 if (retry_estale(error, lookup_flags)) {
575 lookup_flags |= LOOKUP_REVAL;
582 SYSCALL_DEFINE1(fchdir, unsigned int, fd)
584 struct fd f = fdget_raw(fd);
592 if (!d_can_lookup(f.file->f_path.dentry))
595 error = file_permission(f.file, MAY_EXEC | MAY_CHDIR);
597 set_fs_pwd(current->fs, &f.file->f_path);
604 SYSCALL_DEFINE1(chroot, const char __user *, filename)
608 unsigned int lookup_flags = LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
610 error = user_path_at(AT_FDCWD, filename, lookup_flags, &path);
614 error = path_permission(&path, MAY_EXEC | MAY_CHDIR);
619 if (!ns_capable(current_user_ns(), CAP_SYS_CHROOT))
621 error = security_path_chroot(&path);
625 set_fs_root(current->fs, &path);
629 if (retry_estale(error, lookup_flags)) {
630 lookup_flags |= LOOKUP_REVAL;
637 int chmod_common(const struct path *path, umode_t mode)
639 struct inode *inode = path->dentry->d_inode;
640 struct inode *delegated_inode = NULL;
641 struct iattr newattrs;
644 error = mnt_want_write(path->mnt);
649 error = security_path_chmod(path, mode);
652 newattrs.ia_mode = (mode & S_IALLUGO) | (inode->i_mode & ~S_IALLUGO);
653 newattrs.ia_valid = ATTR_MODE | ATTR_CTIME;
654 error = notify_change(mnt_idmap(path->mnt), path->dentry,
655 &newattrs, &delegated_inode);
658 if (delegated_inode) {
659 error = break_deleg_wait(&delegated_inode);
663 mnt_drop_write(path->mnt);
667 int vfs_fchmod(struct file *file, umode_t mode)
670 return chmod_common(&file->f_path, mode);
673 SYSCALL_DEFINE2(fchmod, unsigned int, fd, umode_t, mode)
675 struct fd f = fdget(fd);
679 err = vfs_fchmod(f.file, mode);
685 static int do_fchmodat(int dfd, const char __user *filename, umode_t mode,
690 unsigned int lookup_flags;
692 if (unlikely(flags & ~(AT_SYMLINK_NOFOLLOW | AT_EMPTY_PATH)))
695 lookup_flags = (flags & AT_SYMLINK_NOFOLLOW) ? 0 : LOOKUP_FOLLOW;
696 if (flags & AT_EMPTY_PATH)
697 lookup_flags |= LOOKUP_EMPTY;
700 error = user_path_at(dfd, filename, lookup_flags, &path);
702 error = chmod_common(&path, mode);
704 if (retry_estale(error, lookup_flags)) {
705 lookup_flags |= LOOKUP_REVAL;
712 SYSCALL_DEFINE4(fchmodat2, int, dfd, const char __user *, filename,
713 umode_t, mode, unsigned int, flags)
715 return do_fchmodat(dfd, filename, mode, flags);
718 SYSCALL_DEFINE3(fchmodat, int, dfd, const char __user *, filename,
721 return do_fchmodat(dfd, filename, mode, 0);
724 SYSCALL_DEFINE2(chmod, const char __user *, filename, umode_t, mode)
726 return do_fchmodat(AT_FDCWD, filename, mode, 0);
730 * Check whether @kuid is valid and if so generate and set vfsuid_t in
733 * Return: true if @kuid is valid, false if not.
735 static inline bool setattr_vfsuid(struct iattr *attr, kuid_t kuid)
737 if (!uid_valid(kuid))
739 attr->ia_valid |= ATTR_UID;
740 attr->ia_vfsuid = VFSUIDT_INIT(kuid);
745 * Check whether @kgid is valid and if so generate and set vfsgid_t in
748 * Return: true if @kgid is valid, false if not.
750 static inline bool setattr_vfsgid(struct iattr *attr, kgid_t kgid)
752 if (!gid_valid(kgid))
754 attr->ia_valid |= ATTR_GID;
755 attr->ia_vfsgid = VFSGIDT_INIT(kgid);
759 int chown_common(const struct path *path, uid_t user, gid_t group)
761 struct mnt_idmap *idmap;
762 struct user_namespace *fs_userns;
763 struct inode *inode = path->dentry->d_inode;
764 struct inode *delegated_inode = NULL;
766 struct iattr newattrs;
770 uid = make_kuid(current_user_ns(), user);
771 gid = make_kgid(current_user_ns(), group);
773 idmap = mnt_idmap(path->mnt);
774 fs_userns = i_user_ns(inode);
777 newattrs.ia_vfsuid = INVALID_VFSUID;
778 newattrs.ia_vfsgid = INVALID_VFSGID;
779 newattrs.ia_valid = ATTR_CTIME;
780 if ((user != (uid_t)-1) && !setattr_vfsuid(&newattrs, uid))
782 if ((group != (gid_t)-1) && !setattr_vfsgid(&newattrs, gid))
785 if (!S_ISDIR(inode->i_mode))
786 newattrs.ia_valid |= ATTR_KILL_SUID | ATTR_KILL_PRIV |
787 setattr_should_drop_sgid(idmap, inode);
788 /* Continue to send actual fs values, not the mount values. */
789 error = security_path_chown(
791 from_vfsuid(idmap, fs_userns, newattrs.ia_vfsuid),
792 from_vfsgid(idmap, fs_userns, newattrs.ia_vfsgid));
794 error = notify_change(idmap, path->dentry, &newattrs,
797 if (delegated_inode) {
798 error = break_deleg_wait(&delegated_inode);
805 int do_fchownat(int dfd, const char __user *filename, uid_t user, gid_t group,
812 if ((flag & ~(AT_SYMLINK_NOFOLLOW | AT_EMPTY_PATH)) != 0)
815 lookup_flags = (flag & AT_SYMLINK_NOFOLLOW) ? 0 : LOOKUP_FOLLOW;
816 if (flag & AT_EMPTY_PATH)
817 lookup_flags |= LOOKUP_EMPTY;
819 error = user_path_at(dfd, filename, lookup_flags, &path);
822 error = mnt_want_write(path.mnt);
825 error = chown_common(&path, user, group);
826 mnt_drop_write(path.mnt);
829 if (retry_estale(error, lookup_flags)) {
830 lookup_flags |= LOOKUP_REVAL;
837 SYSCALL_DEFINE5(fchownat, int, dfd, const char __user *, filename, uid_t, user,
838 gid_t, group, int, flag)
840 return do_fchownat(dfd, filename, user, group, flag);
843 SYSCALL_DEFINE3(chown, const char __user *, filename, uid_t, user, gid_t, group)
845 return do_fchownat(AT_FDCWD, filename, user, group, 0);
848 SYSCALL_DEFINE3(lchown, const char __user *, filename, uid_t, user, gid_t, group)
850 return do_fchownat(AT_FDCWD, filename, user, group,
851 AT_SYMLINK_NOFOLLOW);
854 int vfs_fchown(struct file *file, uid_t user, gid_t group)
858 error = mnt_want_write_file(file);
862 error = chown_common(&file->f_path, user, group);
863 mnt_drop_write_file(file);
867 int ksys_fchown(unsigned int fd, uid_t user, gid_t group)
869 struct fd f = fdget(fd);
873 error = vfs_fchown(f.file, user, group);
879 SYSCALL_DEFINE3(fchown, unsigned int, fd, uid_t, user, gid_t, group)
881 return ksys_fchown(fd, user, group);
884 static inline int file_get_write_access(struct file *f)
888 error = get_write_access(f->f_inode);
891 error = mnt_get_write_access(f->f_path.mnt);
894 if (unlikely(f->f_mode & FMODE_BACKING)) {
895 error = mnt_get_write_access(backing_file_user_path(f)->mnt);
902 mnt_put_write_access(f->f_path.mnt);
904 put_write_access(f->f_inode);
908 static int do_dentry_open(struct file *f,
909 int (*open)(struct inode *, struct file *))
911 static const struct file_operations empty_fops = {};
912 struct inode *inode = f->f_path.dentry->d_inode;
915 path_get(&f->f_path);
917 f->f_mapping = inode->i_mapping;
918 f->f_wb_err = filemap_sample_wb_err(f->f_mapping);
919 f->f_sb_err = file_sample_sb_err(f);
921 if (unlikely(f->f_flags & O_PATH)) {
922 f->f_mode = FMODE_PATH | FMODE_OPENED;
923 f->f_op = &empty_fops;
927 if ((f->f_mode & (FMODE_READ | FMODE_WRITE)) == FMODE_READ) {
928 i_readcount_inc(inode);
929 } else if (f->f_mode & FMODE_WRITE && !special_file(inode->i_mode)) {
930 error = file_get_write_access(f);
933 f->f_mode |= FMODE_WRITER;
936 /* POSIX.1-2008/SUSv4 Section XSI 2.9.7 */
937 if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode))
938 f->f_mode |= FMODE_ATOMIC_POS;
940 f->f_op = fops_get(inode->i_fop);
941 if (WARN_ON(!f->f_op)) {
946 error = security_file_open(f);
950 error = break_lease(file_inode(f), f->f_flags);
954 /* normally all 3 are set; ->open() can clear them if needed */
955 f->f_mode |= FMODE_LSEEK | FMODE_PREAD | FMODE_PWRITE;
957 open = f->f_op->open;
959 error = open(inode, f);
963 f->f_mode |= FMODE_OPENED;
964 if ((f->f_mode & FMODE_READ) &&
965 likely(f->f_op->read || f->f_op->read_iter))
966 f->f_mode |= FMODE_CAN_READ;
967 if ((f->f_mode & FMODE_WRITE) &&
968 likely(f->f_op->write || f->f_op->write_iter))
969 f->f_mode |= FMODE_CAN_WRITE;
970 if ((f->f_mode & FMODE_LSEEK) && !f->f_op->llseek)
971 f->f_mode &= ~FMODE_LSEEK;
972 if (f->f_mapping->a_ops && f->f_mapping->a_ops->direct_IO)
973 f->f_mode |= FMODE_CAN_ODIRECT;
975 f->f_flags &= ~(O_CREAT | O_EXCL | O_NOCTTY | O_TRUNC);
976 f->f_iocb_flags = iocb_flags(f);
978 file_ra_state_init(&f->f_ra, f->f_mapping->host->i_mapping);
980 if ((f->f_flags & O_DIRECT) && !(f->f_mode & FMODE_CAN_ODIRECT))
984 * XXX: Huge page cache doesn't support writing yet. Drop all page
985 * cache for this file before processing writes.
987 if (f->f_mode & FMODE_WRITE) {
989 * Depends on full fence from get_write_access() to synchronize
990 * against collapse_file() regarding i_writecount and nr_thps
991 * updates. Ensures subsequent insertion of THPs into the page
994 if (filemap_nr_thps(inode->i_mapping)) {
995 struct address_space *mapping = inode->i_mapping;
997 filemap_invalidate_lock(inode->i_mapping);
999 * unmap_mapping_range just need to be called once
1000 * here, because the private pages is not need to be
1001 * unmapped mapping (e.g. data segment of dynamic
1002 * shared libraries here).
1004 unmap_mapping_range(mapping, 0, 0, 0);
1005 truncate_inode_pages(mapping, 0);
1006 filemap_invalidate_unlock(inode->i_mapping);
1013 if (WARN_ON_ONCE(error > 0))
1018 path_put(&f->f_path);
1019 f->f_path.mnt = NULL;
1020 f->f_path.dentry = NULL;
1026 * finish_open - finish opening a file
1027 * @file: file pointer
1028 * @dentry: pointer to dentry
1029 * @open: open callback
1031 * This can be used to finish opening a file passed to i_op->atomic_open().
1033 * If the open callback is set to NULL, then the standard f_op->open()
1034 * filesystem callback is substituted.
1036 * NB: the dentry reference is _not_ consumed. If, for example, the dentry is
1037 * the return value of d_splice_alias(), then the caller needs to perform dput()
1038 * on it after finish_open().
1040 * Returns zero on success or -errno if the open failed.
1042 int finish_open(struct file *file, struct dentry *dentry,
1043 int (*open)(struct inode *, struct file *))
1045 BUG_ON(file->f_mode & FMODE_OPENED); /* once it's opened, it's opened */
1047 file->f_path.dentry = dentry;
1048 return do_dentry_open(file, open);
1050 EXPORT_SYMBOL(finish_open);
1053 * finish_no_open - finish ->atomic_open() without opening the file
1055 * @file: file pointer
1056 * @dentry: dentry or NULL (as returned from ->lookup())
1058 * This can be used to set the result of a successful lookup in ->atomic_open().
1060 * NB: unlike finish_open() this function does consume the dentry reference and
1061 * the caller need not dput() it.
1063 * Returns "0" which must be the return value of ->atomic_open() after having
1064 * called this function.
1066 int finish_no_open(struct file *file, struct dentry *dentry)
1068 file->f_path.dentry = dentry;
1071 EXPORT_SYMBOL(finish_no_open);
1073 char *file_path(struct file *filp, char *buf, int buflen)
1075 return d_path(&filp->f_path, buf, buflen);
1077 EXPORT_SYMBOL(file_path);
1080 * vfs_open - open the file at the given path
1081 * @path: path to open
1082 * @file: newly allocated file with f_flag initialized
1084 int vfs_open(const struct path *path, struct file *file)
1088 file->f_path = *path;
1089 ret = do_dentry_open(file, NULL);
1092 * Once we return a file with FMODE_OPENED, __fput() will call
1093 * fsnotify_close(), so we need fsnotify_open() here for
1096 fsnotify_open(file);
1101 struct file *dentry_open(const struct path *path, int flags,
1102 const struct cred *cred)
1107 /* We must always pass in a valid mount pointer. */
1110 f = alloc_empty_file(flags, cred);
1112 error = vfs_open(path, f);
1120 EXPORT_SYMBOL(dentry_open);
1123 * dentry_create - Create and open a file
1124 * @path: path to create
1126 * @mode: mode bits for new file
1127 * @cred: credentials to use
1129 * Caller must hold the parent directory's lock, and have prepared
1130 * a negative dentry, placed in @path->dentry, for the new file.
1132 * Caller sets @path->mnt to the vfsmount of the filesystem where
1133 * the new file is to be created. The parent directory and the
1134 * negative dentry must reside on the same filesystem instance.
1136 * On success, returns a "struct file *". Otherwise a ERR_PTR
1139 struct file *dentry_create(const struct path *path, int flags, umode_t mode,
1140 const struct cred *cred)
1145 f = alloc_empty_file(flags, cred);
1149 error = vfs_create(mnt_idmap(path->mnt),
1150 d_inode(path->dentry->d_parent),
1151 path->dentry, mode, true);
1153 error = vfs_open(path, f);
1155 if (unlikely(error)) {
1157 return ERR_PTR(error);
1161 EXPORT_SYMBOL(dentry_create);
1164 * kernel_file_open - open a file for kernel internal use
1165 * @path: path of the file to open
1166 * @flags: open flags
1167 * @cred: credentials for open
1169 * Open a file for use by in-kernel consumers. The file is not accounted
1170 * against nr_files and must not be installed into the file descriptor
1173 * Return: Opened file on success, an error pointer on failure.
1175 struct file *kernel_file_open(const struct path *path, int flags,
1176 const struct cred *cred)
1181 f = alloc_empty_file_noaccount(flags, cred);
1186 error = do_dentry_open(f, NULL);
1189 return ERR_PTR(error);
1195 EXPORT_SYMBOL_GPL(kernel_file_open);
1197 #define WILL_CREATE(flags) (flags & (O_CREAT | __O_TMPFILE))
1198 #define O_PATH_FLAGS (O_DIRECTORY | O_NOFOLLOW | O_PATH | O_CLOEXEC)
1200 inline struct open_how build_open_how(int flags, umode_t mode)
1202 struct open_how how = {
1203 .flags = flags & VALID_OPEN_FLAGS,
1204 .mode = mode & S_IALLUGO,
1207 /* O_PATH beats everything else. */
1208 if (how.flags & O_PATH)
1209 how.flags &= O_PATH_FLAGS;
1210 /* Modes should only be set for create-like flags. */
1211 if (!WILL_CREATE(how.flags))
1216 inline int build_open_flags(const struct open_how *how, struct open_flags *op)
1218 u64 flags = how->flags;
1219 u64 strip = __FMODE_NONOTIFY | O_CLOEXEC;
1220 int lookup_flags = 0;
1221 int acc_mode = ACC_MODE(flags);
1223 BUILD_BUG_ON_MSG(upper_32_bits(VALID_OPEN_FLAGS),
1224 "struct open_flags doesn't yet handle flags > 32 bits");
1227 * Strip flags that either shouldn't be set by userspace like
1228 * FMODE_NONOTIFY or that aren't relevant in determining struct
1229 * open_flags like O_CLOEXEC.
1234 * Older syscalls implicitly clear all of the invalid flags or argument
1235 * values before calling build_open_flags(), but openat2(2) checks all
1238 if (flags & ~VALID_OPEN_FLAGS)
1240 if (how->resolve & ~VALID_RESOLVE_FLAGS)
1243 /* Scoping flags are mutually exclusive. */
1244 if ((how->resolve & RESOLVE_BENEATH) && (how->resolve & RESOLVE_IN_ROOT))
1247 /* Deal with the mode. */
1248 if (WILL_CREATE(flags)) {
1249 if (how->mode & ~S_IALLUGO)
1251 op->mode = how->mode | S_IFREG;
1259 * Block bugs where O_DIRECTORY | O_CREAT created regular files.
1260 * Note, that blocking O_DIRECTORY | O_CREAT here also protects
1261 * O_TMPFILE below which requires O_DIRECTORY being raised.
1263 if ((flags & (O_DIRECTORY | O_CREAT)) == (O_DIRECTORY | O_CREAT))
1266 /* Now handle the creative implementation of O_TMPFILE. */
1267 if (flags & __O_TMPFILE) {
1269 * In order to ensure programs get explicit errors when trying
1270 * to use O_TMPFILE on old kernels we enforce that O_DIRECTORY
1271 * is raised alongside __O_TMPFILE.
1273 if (!(flags & O_DIRECTORY))
1275 if (!(acc_mode & MAY_WRITE))
1278 if (flags & O_PATH) {
1279 /* O_PATH only permits certain other flags to be set. */
1280 if (flags & ~O_PATH_FLAGS)
1286 * O_SYNC is implemented as __O_SYNC|O_DSYNC. As many places only
1287 * check for O_DSYNC if the need any syncing at all we enforce it's
1288 * always set instead of having to deal with possibly weird behaviour
1289 * for malicious applications setting only __O_SYNC.
1291 if (flags & __O_SYNC)
1294 op->open_flag = flags;
1296 /* O_TRUNC implies we need access checks for write permissions */
1297 if (flags & O_TRUNC)
1298 acc_mode |= MAY_WRITE;
1300 /* Allow the LSM permission hook to distinguish append
1301 access from general write access. */
1302 if (flags & O_APPEND)
1303 acc_mode |= MAY_APPEND;
1305 op->acc_mode = acc_mode;
1307 op->intent = flags & O_PATH ? 0 : LOOKUP_OPEN;
1309 if (flags & O_CREAT) {
1310 op->intent |= LOOKUP_CREATE;
1311 if (flags & O_EXCL) {
1312 op->intent |= LOOKUP_EXCL;
1313 flags |= O_NOFOLLOW;
1317 if (flags & O_DIRECTORY)
1318 lookup_flags |= LOOKUP_DIRECTORY;
1319 if (!(flags & O_NOFOLLOW))
1320 lookup_flags |= LOOKUP_FOLLOW;
1322 if (how->resolve & RESOLVE_NO_XDEV)
1323 lookup_flags |= LOOKUP_NO_XDEV;
1324 if (how->resolve & RESOLVE_NO_MAGICLINKS)
1325 lookup_flags |= LOOKUP_NO_MAGICLINKS;
1326 if (how->resolve & RESOLVE_NO_SYMLINKS)
1327 lookup_flags |= LOOKUP_NO_SYMLINKS;
1328 if (how->resolve & RESOLVE_BENEATH)
1329 lookup_flags |= LOOKUP_BENEATH;
1330 if (how->resolve & RESOLVE_IN_ROOT)
1331 lookup_flags |= LOOKUP_IN_ROOT;
1332 if (how->resolve & RESOLVE_CACHED) {
1333 /* Don't bother even trying for create/truncate/tmpfile open */
1334 if (flags & (O_TRUNC | O_CREAT | __O_TMPFILE))
1336 lookup_flags |= LOOKUP_CACHED;
1339 op->lookup_flags = lookup_flags;
1344 * file_open_name - open file and return file pointer
1346 * @name: struct filename containing path to open
1347 * @flags: open flags as per the open(2) second argument
1348 * @mode: mode for the new file if O_CREAT is set, else ignored
1350 * This is the helper to open a file from kernelspace if you really
1351 * have to. But in generally you should not do this, so please move
1352 * along, nothing to see here..
1354 struct file *file_open_name(struct filename *name, int flags, umode_t mode)
1356 struct open_flags op;
1357 struct open_how how = build_open_how(flags, mode);
1358 int err = build_open_flags(&how, &op);
1360 return ERR_PTR(err);
1361 return do_filp_open(AT_FDCWD, name, &op);
1365 * filp_open - open file and return file pointer
1367 * @filename: path to open
1368 * @flags: open flags as per the open(2) second argument
1369 * @mode: mode for the new file if O_CREAT is set, else ignored
1371 * This is the helper to open a file from kernelspace if you really
1372 * have to. But in generally you should not do this, so please move
1373 * along, nothing to see here..
1375 struct file *filp_open(const char *filename, int flags, umode_t mode)
1377 struct filename *name = getname_kernel(filename);
1378 struct file *file = ERR_CAST(name);
1380 if (!IS_ERR(name)) {
1381 file = file_open_name(name, flags, mode);
1386 EXPORT_SYMBOL(filp_open);
1388 struct file *file_open_root(const struct path *root,
1389 const char *filename, int flags, umode_t mode)
1391 struct open_flags op;
1392 struct open_how how = build_open_how(flags, mode);
1393 int err = build_open_flags(&how, &op);
1395 return ERR_PTR(err);
1396 return do_file_open_root(root, filename, &op);
1398 EXPORT_SYMBOL(file_open_root);
1400 static long do_sys_openat2(int dfd, const char __user *filename,
1401 struct open_how *how)
1403 struct open_flags op;
1404 int fd = build_open_flags(how, &op);
1405 struct filename *tmp;
1410 tmp = getname(filename);
1412 return PTR_ERR(tmp);
1414 fd = get_unused_fd_flags(how->flags);
1416 struct file *f = do_filp_open(dfd, tmp, &op);
1428 long do_sys_open(int dfd, const char __user *filename, int flags, umode_t mode)
1430 struct open_how how = build_open_how(flags, mode);
1431 return do_sys_openat2(dfd, filename, &how);
1435 SYSCALL_DEFINE3(open, const char __user *, filename, int, flags, umode_t, mode)
1437 if (force_o_largefile())
1438 flags |= O_LARGEFILE;
1439 return do_sys_open(AT_FDCWD, filename, flags, mode);
1442 SYSCALL_DEFINE4(openat, int, dfd, const char __user *, filename, int, flags,
1445 if (force_o_largefile())
1446 flags |= O_LARGEFILE;
1447 return do_sys_open(dfd, filename, flags, mode);
1450 SYSCALL_DEFINE4(openat2, int, dfd, const char __user *, filename,
1451 struct open_how __user *, how, size_t, usize)
1454 struct open_how tmp;
1456 BUILD_BUG_ON(sizeof(struct open_how) < OPEN_HOW_SIZE_VER0);
1457 BUILD_BUG_ON(sizeof(struct open_how) != OPEN_HOW_SIZE_LATEST);
1459 if (unlikely(usize < OPEN_HOW_SIZE_VER0))
1462 err = copy_struct_from_user(&tmp, sizeof(tmp), how, usize);
1466 audit_openat2_how(&tmp);
1468 /* O_LARGEFILE is only allowed for non-O_PATH. */
1469 if (!(tmp.flags & O_PATH) && force_o_largefile())
1470 tmp.flags |= O_LARGEFILE;
1472 return do_sys_openat2(dfd, filename, &tmp);
1475 #ifdef CONFIG_COMPAT
1477 * Exactly like sys_open(), except that it doesn't set the
1480 COMPAT_SYSCALL_DEFINE3(open, const char __user *, filename, int, flags, umode_t, mode)
1482 return do_sys_open(AT_FDCWD, filename, flags, mode);
1486 * Exactly like sys_openat(), except that it doesn't set the
1489 COMPAT_SYSCALL_DEFINE4(openat, int, dfd, const char __user *, filename, int, flags, umode_t, mode)
1491 return do_sys_open(dfd, filename, flags, mode);
1498 * For backward compatibility? Maybe this should be moved
1499 * into arch/i386 instead?
1501 SYSCALL_DEFINE2(creat, const char __user *, pathname, umode_t, mode)
1503 int flags = O_CREAT | O_WRONLY | O_TRUNC;
1505 if (force_o_largefile())
1506 flags |= O_LARGEFILE;
1507 return do_sys_open(AT_FDCWD, pathname, flags, mode);
1512 * "id" is the POSIX thread ID. We use the
1513 * files pointer for this..
1515 static int filp_flush(struct file *filp, fl_owner_t id)
1519 if (CHECK_DATA_CORRUPTION(file_count(filp) == 0,
1520 "VFS: Close: file count is 0 (f_op=%ps)",
1525 if (filp->f_op->flush)
1526 retval = filp->f_op->flush(filp, id);
1528 if (likely(!(filp->f_mode & FMODE_PATH))) {
1529 dnotify_flush(filp, id);
1530 locks_remove_posix(filp, id);
1535 int filp_close(struct file *filp, fl_owner_t id)
1539 retval = filp_flush(filp, id);
1544 EXPORT_SYMBOL(filp_close);
1547 * Careful here! We test whether the file pointer is NULL before
1548 * releasing the fd. This ensures that one clone task can't release
1549 * an fd while another clone is opening it.
1551 SYSCALL_DEFINE1(close, unsigned int, fd)
1556 file = file_close_fd(fd);
1560 retval = filp_flush(file, current->files);
1563 * We're returning to user space. Don't bother
1564 * with any delayed fput() cases.
1568 /* can't restart close syscall because file table entry was cleared */
1569 if (unlikely(retval == -ERESTARTSYS ||
1570 retval == -ERESTARTNOINTR ||
1571 retval == -ERESTARTNOHAND ||
1572 retval == -ERESTART_RESTARTBLOCK))
1579 * sys_close_range() - Close all file descriptors in a given range.
1581 * @fd: starting file descriptor to close
1582 * @max_fd: last file descriptor to close
1583 * @flags: reserved for future extensions
1585 * This closes a range of file descriptors. All file descriptors
1586 * from @fd up to and including @max_fd are closed.
1587 * Currently, errors to close a given file descriptor are ignored.
1589 SYSCALL_DEFINE3(close_range, unsigned int, fd, unsigned int, max_fd,
1590 unsigned int, flags)
1592 return __close_range(fd, max_fd, flags);
1596 * This routine simulates a hangup on the tty, to arrange that users
1597 * are given clean terminals at login time.
1599 SYSCALL_DEFINE0(vhangup)
1601 if (capable(CAP_SYS_TTY_CONFIG)) {
1609 * Called when an inode is about to be open.
1610 * We use this to disallow opening large files on 32bit systems if
1611 * the caller didn't specify O_LARGEFILE. On 64bit systems we force
1612 * on this flag in sys_open.
1614 int generic_file_open(struct inode * inode, struct file * filp)
1616 if (!(filp->f_flags & O_LARGEFILE) && i_size_read(inode) > MAX_NON_LFS)
1621 EXPORT_SYMBOL(generic_file_open);
1624 * This is used by subsystems that don't want seekable
1625 * file descriptors. The function is not supposed to ever fail, the only
1626 * reason it returns an 'int' and not 'void' is so that it can be plugged
1627 * directly into file_operations structure.
1629 int nonseekable_open(struct inode *inode, struct file *filp)
1631 filp->f_mode &= ~(FMODE_LSEEK | FMODE_PREAD | FMODE_PWRITE);
1635 EXPORT_SYMBOL(nonseekable_open);
1638 * stream_open is used by subsystems that want stream-like file descriptors.
1639 * Such file descriptors are not seekable and don't have notion of position
1640 * (file.f_pos is always 0 and ppos passed to .read()/.write() is always NULL).
1641 * Contrary to file descriptors of other regular files, .read() and .write()
1642 * can run simultaneously.
1644 * stream_open never fails and is marked to return int so that it could be
1645 * directly used as file_operations.open .
1647 int stream_open(struct inode *inode, struct file *filp)
1649 filp->f_mode &= ~(FMODE_LSEEK | FMODE_PREAD | FMODE_PWRITE | FMODE_ATOMIC_POS);
1650 filp->f_mode |= FMODE_STREAM;
1654 EXPORT_SYMBOL(stream_open);