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