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