1 // SPDX-License-Identifier: GPL-2.0-only 2 /* 3 * linux/fs/file_table.c 4 * 5 * Copyright (C) 1991, 1992 Linus Torvalds 6 * Copyright (C) 1997 David S. Miller (davem@caip.rutgers.edu) 7 */ 8 9 #include <linux/string.h> 10 #include <linux/slab.h> 11 #include <linux/file.h> 12 #include <linux/init.h> 13 #include <linux/module.h> 14 #include <linux/fs.h> 15 #include <linux/filelock.h> 16 #include <linux/security.h> 17 #include <linux/cred.h> 18 #include <linux/eventpoll.h> 19 #include <linux/rcupdate.h> 20 #include <linux/mount.h> 21 #include <linux/capability.h> 22 #include <linux/cdev.h> 23 #include <linux/fsnotify.h> 24 #include <linux/sysctl.h> 25 #include <linux/percpu_counter.h> 26 #include <linux/percpu.h> 27 #include <linux/task_work.h> 28 #include <linux/swap.h> 29 #include <linux/kmemleak.h> 30 31 #include <linux/atomic.h> 32 33 #include <asm/runtime-const.h> 34 35 #include "internal.h" 36 37 /* sysctl tunables... */ 38 static struct files_stat_struct files_stat = { 39 .max_files = NR_FILE 40 }; 41 42 /* SLAB cache for file structures */ 43 static struct kmem_cache *__filp_cache __ro_after_init; 44 #define filp_cache runtime_const_ptr(__filp_cache) 45 static struct kmem_cache *__bfilp_cache __ro_after_init; 46 #define bfilp_cache runtime_const_ptr(__bfilp_cache) 47 48 static struct percpu_counter nr_files __cacheline_aligned_in_smp; 49 50 /* Container for backing file with optional user path */ 51 struct backing_file { 52 struct file file; 53 union { 54 struct path user_path; 55 freeptr_t bf_freeptr; 56 }; 57 #ifdef CONFIG_SECURITY 58 void *security; 59 #endif 60 }; 61 62 #define backing_file(f) container_of(f, struct backing_file, file) 63 64 const struct path *backing_file_user_path(const struct file *f) 65 { 66 return &backing_file(f)->user_path; 67 } 68 EXPORT_SYMBOL_GPL(backing_file_user_path); 69 70 void backing_file_set_user_path(struct file *f, const struct path *path) 71 { 72 backing_file(f)->user_path = *path; 73 } 74 EXPORT_SYMBOL_GPL(backing_file_set_user_path); 75 76 #ifdef CONFIG_SECURITY 77 void *backing_file_security(const struct file *f) 78 { 79 return backing_file(f)->security; 80 } 81 82 void backing_file_set_security(struct file *f, void *security) 83 { 84 backing_file(f)->security = security; 85 } 86 #endif /* CONFIG_SECURITY */ 87 88 static inline void backing_file_free(struct backing_file *ff) 89 { 90 security_backing_file_free(&ff->file); 91 path_put(&ff->user_path); 92 kmem_cache_free(bfilp_cache, ff); 93 } 94 95 static inline void file_free(struct file *f) 96 { 97 security_file_free(f); 98 if (likely(!(f->f_mode & FMODE_NOACCOUNT))) 99 percpu_counter_dec(&nr_files); 100 put_cred(f->f_cred); 101 if (unlikely(f->f_mode & FMODE_BACKING)) { 102 backing_file_free(backing_file(f)); 103 } else { 104 kmem_cache_free(filp_cache, f); 105 } 106 } 107 108 /* 109 * Return the total number of open files in the system 110 */ 111 static long get_nr_files(void) 112 { 113 return percpu_counter_read_positive(&nr_files); 114 } 115 116 /* 117 * Return the maximum number of open files in the system 118 */ 119 unsigned long get_max_files(void) 120 { 121 return files_stat.max_files; 122 } 123 EXPORT_SYMBOL_GPL(get_max_files); 124 125 #if defined(CONFIG_SYSCTL) && defined(CONFIG_PROC_FS) 126 127 /* 128 * Handle nr_files sysctl 129 */ 130 static int proc_nr_files(const struct ctl_table *table, int write, void *buffer, 131 size_t *lenp, loff_t *ppos) 132 { 133 files_stat.nr_files = percpu_counter_sum_positive(&nr_files); 134 return proc_doulongvec_minmax(table, write, buffer, lenp, ppos); 135 } 136 137 static const struct ctl_table fs_stat_sysctls[] = { 138 { 139 .procname = "file-nr", 140 .data = &files_stat, 141 .maxlen = sizeof(files_stat), 142 .mode = 0444, 143 .proc_handler = proc_nr_files, 144 }, 145 { 146 .procname = "file-max", 147 .data = &files_stat.max_files, 148 .maxlen = sizeof(files_stat.max_files), 149 .mode = 0644, 150 .proc_handler = proc_doulongvec_minmax, 151 .extra1 = SYSCTL_LONG_ZERO, 152 .extra2 = SYSCTL_LONG_MAX, 153 }, 154 { 155 .procname = "nr_open", 156 .data = &sysctl_nr_open, 157 .maxlen = sizeof(unsigned int), 158 .mode = 0644, 159 .proc_handler = proc_douintvec_minmax, 160 .extra1 = &sysctl_nr_open_min, 161 .extra2 = &sysctl_nr_open_max, 162 }, 163 }; 164 165 static int __init init_fs_stat_sysctls(void) 166 { 167 register_sysctl_init("fs", fs_stat_sysctls); 168 if (IS_ENABLED(CONFIG_BINFMT_MISC)) { 169 struct ctl_table_header *hdr; 170 171 hdr = register_sysctl_mount_point("fs/binfmt_misc"); 172 kmemleak_not_leak(hdr); 173 } 174 return 0; 175 } 176 fs_initcall(init_fs_stat_sysctls); 177 #endif 178 179 static int init_file(struct file *f, int flags, const struct cred *cred) 180 { 181 int error; 182 183 f->f_cred = get_cred(cred); 184 error = security_file_alloc(f); 185 if (unlikely(error)) { 186 put_cred(f->f_cred); 187 return error; 188 } 189 190 spin_lock_init(&f->f_lock); 191 /* 192 * Note that f_pos_lock is only used for files raising 193 * FMODE_ATOMIC_POS and directories. Other files such as pipes 194 * don't need it and since f_pos_lock is in a union may reuse 195 * the space for other purposes. They are expected to initialize 196 * the respective member when opening the file. 197 */ 198 mutex_init(&f->f_pos_lock); 199 memset(&f->__f_path, 0, sizeof(f->f_path)); 200 memset(&f->f_ra, 0, sizeof(f->f_ra)); 201 202 f->f_flags = flags; 203 f->f_mode = OPEN_FMODE(flags); 204 /* 205 * Disable permission and pre-content events for all files by default. 206 * They may be enabled later by fsnotify_open_perm_and_set_mode(). 207 */ 208 file_set_fsnotify_mode(f, FMODE_NONOTIFY_PERM); 209 210 f->f_op = NULL; 211 f->f_mapping = NULL; 212 f->private_data = NULL; 213 f->f_inode = NULL; 214 f->f_owner = NULL; 215 #ifdef CONFIG_EPOLL 216 f->f_ep = NULL; 217 #endif 218 219 f->f_iocb_flags = 0; 220 f->f_pos = 0; 221 f->f_wb_err = 0; 222 f->f_sb_err = 0; 223 224 /* 225 * We're SLAB_TYPESAFE_BY_RCU so initialize f_ref last. While 226 * fget-rcu pattern users need to be able to handle spurious 227 * refcount bumps we should reinitialize the reused file first. 228 */ 229 file_ref_init(&f->f_ref, 1); 230 return 0; 231 } 232 233 /* Find an unused file structure and return a pointer to it. 234 * Returns an error pointer if some error happend e.g. we over file 235 * structures limit, run out of memory or operation is not permitted. 236 * 237 * Be very careful using this. You are responsible for 238 * getting write access to any mount that you might assign 239 * to this filp, if it is opened for write. If this is not 240 * done, you will imbalance int the mount's writer count 241 * and a warning at __fput() time. 242 */ 243 struct file *alloc_empty_file(int flags, const struct cred *cred) 244 { 245 static long old_max; 246 struct file *f; 247 int error; 248 249 /* 250 * Privileged users can go above max_files 251 */ 252 if (unlikely(get_nr_files() >= files_stat.max_files) && 253 !capable(CAP_SYS_ADMIN)) { 254 /* 255 * percpu_counters are inaccurate. Do an expensive check before 256 * we go and fail. 257 */ 258 if (percpu_counter_sum_positive(&nr_files) >= files_stat.max_files) 259 goto over; 260 } 261 262 f = kmem_cache_alloc(filp_cache, GFP_KERNEL); 263 if (unlikely(!f)) 264 return ERR_PTR(-ENOMEM); 265 266 error = init_file(f, flags, cred); 267 if (unlikely(error)) { 268 kmem_cache_free(filp_cache, f); 269 return ERR_PTR(error); 270 } 271 272 percpu_counter_inc(&nr_files); 273 274 return f; 275 276 over: 277 /* Ran out of filps - report that */ 278 if (get_nr_files() > old_max) { 279 pr_info("VFS: file-max limit %lu reached\n", get_max_files()); 280 old_max = get_nr_files(); 281 } 282 return ERR_PTR(-ENFILE); 283 } 284 285 /* 286 * Variant of alloc_empty_file() that doesn't check and modify nr_files. 287 * 288 * This is only for kernel internal use, and the allocate file must not be 289 * installed into file tables or such. 290 */ 291 struct file *alloc_empty_file_noaccount(int flags, const struct cred *cred) 292 { 293 struct file *f; 294 int error; 295 296 f = kmem_cache_alloc(filp_cache, GFP_KERNEL); 297 if (unlikely(!f)) 298 return ERR_PTR(-ENOMEM); 299 300 error = init_file(f, flags, cred); 301 if (unlikely(error)) { 302 kmem_cache_free(filp_cache, f); 303 return ERR_PTR(error); 304 } 305 306 f->f_mode |= FMODE_NOACCOUNT; 307 308 return f; 309 } 310 311 static int init_backing_file(struct backing_file *ff, 312 const struct file *user_file) 313 { 314 memset(&ff->user_path, 0, sizeof(ff->user_path)); 315 backing_file_set_security(&ff->file, NULL); 316 return security_backing_file_alloc(&ff->file, user_file); 317 } 318 319 /* 320 * Variant of alloc_empty_file() that allocates a backing_file container 321 * and doesn't check and modify nr_files. 322 * 323 * This is only for kernel internal use, and the allocate file must not be 324 * installed into file tables or such. 325 */ 326 struct file *alloc_empty_backing_file(int flags, const struct cred *cred, 327 const struct file *user_file) 328 { 329 struct backing_file *ff; 330 int error; 331 332 ff = kmem_cache_alloc(bfilp_cache, GFP_KERNEL); 333 if (unlikely(!ff)) 334 return ERR_PTR(-ENOMEM); 335 336 error = init_file(&ff->file, flags, cred); 337 if (unlikely(error)) { 338 kmem_cache_free(bfilp_cache, ff); 339 return ERR_PTR(error); 340 } 341 342 /* The f_mode flags must be set before fput(). */ 343 ff->file.f_mode |= FMODE_BACKING | FMODE_NOACCOUNT; 344 error = init_backing_file(ff, user_file); 345 if (unlikely(error)) { 346 fput(&ff->file); 347 return ERR_PTR(error); 348 } 349 350 return &ff->file; 351 } 352 EXPORT_SYMBOL_GPL(alloc_empty_backing_file); 353 354 /** 355 * file_init_path - initialize a 'struct file' based on path 356 * 357 * @file: the file to set up 358 * @path: the (dentry, vfsmount) pair for the new file 359 * @fop: the 'struct file_operations' for the new file 360 */ 361 static void file_init_path(struct file *file, const struct path *path, 362 const struct file_operations *fop) 363 { 364 file->__f_path = *path; 365 file->f_inode = path->dentry->d_inode; 366 file->f_mapping = path->dentry->d_inode->i_mapping; 367 file->f_wb_err = filemap_sample_wb_err(file->f_mapping); 368 file->f_sb_err = file_sample_sb_err(file); 369 if (fop->llseek) 370 file->f_mode |= FMODE_LSEEK; 371 if ((file->f_mode & FMODE_READ) && 372 likely(fop->read || fop->read_iter)) 373 file->f_mode |= FMODE_CAN_READ; 374 if ((file->f_mode & FMODE_WRITE) && 375 likely(fop->write || fop->write_iter)) 376 file->f_mode |= FMODE_CAN_WRITE; 377 file->f_iocb_flags = iocb_flags(file); 378 file->f_mode |= FMODE_OPENED; 379 file->f_op = fop; 380 if ((file->f_mode & (FMODE_READ | FMODE_WRITE)) == FMODE_READ) 381 i_readcount_inc(path->dentry->d_inode); 382 } 383 384 /** 385 * alloc_file - allocate and initialize a 'struct file' 386 * 387 * @path: the (dentry, vfsmount) pair for the new file 388 * @flags: O_... flags with which the new file will be opened 389 * @fop: the 'struct file_operations' for the new file 390 */ 391 static struct file *alloc_file(const struct path *path, int flags, 392 const struct file_operations *fop) 393 { 394 struct file *file; 395 396 file = alloc_empty_file(flags, current_cred()); 397 if (!IS_ERR(file)) 398 file_init_path(file, path, fop); 399 return file; 400 } 401 402 static inline int alloc_path_pseudo(const char *name, struct inode *inode, 403 struct vfsmount *mnt, struct path *path) 404 { 405 if (WARN_ON_ONCE(S_ISDIR(inode->i_mode))) 406 return -EINVAL; 407 path->dentry = d_alloc_pseudo(mnt->mnt_sb, &QSTR(name)); 408 if (!path->dentry) 409 return -ENOMEM; 410 path->mnt = mntget(mnt); 411 d_instantiate(path->dentry, inode); 412 return 0; 413 } 414 415 struct file *alloc_file_pseudo(struct inode *inode, struct vfsmount *mnt, 416 const char *name, int flags, 417 const struct file_operations *fops) 418 { 419 int ret; 420 struct path path; 421 struct file *file; 422 423 ret = alloc_path_pseudo(name, inode, mnt, &path); 424 if (ret) 425 return ERR_PTR(ret); 426 427 file = alloc_file(&path, flags, fops); 428 if (IS_ERR(file)) { 429 ihold(inode); 430 path_put(&path); 431 return file; 432 } 433 /* 434 * Disable all fsnotify events for pseudo files by default. 435 * They may be enabled by caller with file_set_fsnotify_mode(). 436 */ 437 file_set_fsnotify_mode(file, FMODE_NONOTIFY); 438 return file; 439 } 440 EXPORT_SYMBOL(alloc_file_pseudo); 441 442 struct file *alloc_file_pseudo_noaccount(struct inode *inode, 443 struct vfsmount *mnt, const char *name, 444 int flags, 445 const struct file_operations *fops) 446 { 447 int ret; 448 struct path path; 449 struct file *file; 450 451 ret = alloc_path_pseudo(name, inode, mnt, &path); 452 if (ret) 453 return ERR_PTR(ret); 454 455 file = alloc_empty_file_noaccount(flags, current_cred()); 456 if (IS_ERR(file)) { 457 ihold(inode); 458 path_put(&path); 459 return file; 460 } 461 file_init_path(file, &path, fops); 462 /* 463 * Disable all fsnotify events for pseudo files by default. 464 * They may be enabled by caller with file_set_fsnotify_mode(). 465 */ 466 file_set_fsnotify_mode(file, FMODE_NONOTIFY); 467 return file; 468 } 469 EXPORT_SYMBOL_GPL(alloc_file_pseudo_noaccount); 470 471 struct file *alloc_file_clone(struct file *base, int flags, 472 const struct file_operations *fops) 473 { 474 struct file *f; 475 476 f = alloc_file(&base->f_path, flags, fops); 477 if (!IS_ERR(f)) { 478 path_get(&f->f_path); 479 f->f_mapping = base->f_mapping; 480 } 481 return f; 482 } 483 484 /* the real guts of fput() - releasing the last reference to file 485 */ 486 static void __fput(struct file *file) 487 { 488 struct dentry *dentry = file->f_path.dentry; 489 struct vfsmount *mnt = file->f_path.mnt; 490 struct inode *inode = file->f_inode; 491 fmode_t mode = file->f_mode; 492 493 if (unlikely(!(file->f_mode & FMODE_OPENED))) 494 goto out; 495 496 might_sleep(); 497 498 fsnotify_close(file); 499 /* 500 * The function eventpoll_release() should be the first called 501 * in the file cleanup chain. 502 */ 503 eventpoll_release(file); 504 locks_remove_file(file); 505 506 security_file_release(file); 507 if (unlikely(file->f_flags & FASYNC)) { 508 if (file->f_op->fasync) 509 file->f_op->fasync(-1, file, 0); 510 } 511 if (file->f_op->release) 512 file->f_op->release(inode, file); 513 if (unlikely(S_ISCHR(inode->i_mode) && inode->i_cdev != NULL && 514 !(mode & FMODE_PATH))) { 515 cdev_put(inode->i_cdev); 516 } 517 fops_put(file->f_op); 518 file_f_owner_release(file); 519 put_file_access(file); 520 dput(dentry); 521 if (unlikely(mode & FMODE_NEED_UNMOUNT)) 522 dissolve_on_fput(mnt); 523 mntput(mnt); 524 out: 525 file_free(file); 526 } 527 528 static LLIST_HEAD(delayed_fput_list); 529 static void delayed_fput(struct work_struct *unused) 530 { 531 struct llist_node *node = llist_del_all(&delayed_fput_list); 532 struct file *f, *t; 533 534 llist_for_each_entry_safe(f, t, node, f_llist) 535 __fput(f); 536 } 537 538 static void ____fput(struct callback_head *work) 539 { 540 __fput(container_of(work, struct file, f_task_work)); 541 } 542 543 static DECLARE_DELAYED_WORK(delayed_fput_work, delayed_fput); 544 545 /* 546 * If kernel thread really needs to have the final fput() it has done 547 * to complete, call this. The only user right now is the boot - we 548 * *do* need to make sure our writes to binaries on initramfs has 549 * not left us with opened struct file waiting for __fput() - execve() 550 * won't work without that. Please, don't add more callers without 551 * very good reasons; in particular, never call that with locks 552 * held and never call that from a thread that might need to do 553 * some work on any kind of umount. 554 */ 555 void flush_delayed_fput(void) 556 { 557 delayed_fput(NULL); 558 flush_delayed_work(&delayed_fput_work); 559 } 560 EXPORT_SYMBOL_GPL(flush_delayed_fput); 561 562 static void __fput_deferred(struct file *file) 563 { 564 struct task_struct *task = current; 565 566 if (unlikely(!(file->f_mode & (FMODE_BACKING | FMODE_OPENED)))) { 567 file_free(file); 568 return; 569 } 570 571 if (likely(!in_interrupt() && !(task->flags & PF_KTHREAD))) { 572 init_task_work(&file->f_task_work, ____fput); 573 if (!task_work_add(task, &file->f_task_work, TWA_RESUME)) 574 return; 575 /* 576 * After this task has run exit_task_work(), 577 * task_work_add() will fail. Fall through to delayed 578 * fput to avoid leaking *file. 579 */ 580 } 581 582 if (llist_add(&file->f_llist, &delayed_fput_list)) 583 schedule_delayed_work(&delayed_fput_work, 1); 584 } 585 586 void fput(struct file *file) 587 { 588 if (unlikely(file_ref_put(&file->f_ref))) 589 __fput_deferred(file); 590 } 591 EXPORT_SYMBOL(fput); 592 593 /* 594 * synchronous analog of fput(); for kernel threads that might be needed 595 * in some umount() (and thus can't use flush_delayed_fput() without 596 * risking deadlocks), need to wait for completion of __fput() and know 597 * for this specific struct file it won't involve anything that would 598 * need them. Use only if you really need it - at the very least, 599 * don't blindly convert fput() by kernel thread to that. 600 */ 601 void __fput_sync(struct file *file) 602 { 603 if (file_ref_put(&file->f_ref)) 604 __fput(file); 605 } 606 EXPORT_SYMBOL(__fput_sync); 607 608 /* 609 * Equivalent to __fput_sync(), but optimized for being called with the last 610 * reference. 611 * 612 * See file_ref_put_close() for details. 613 */ 614 void fput_close_sync(struct file *file) 615 { 616 if (likely(file_ref_put_close(&file->f_ref))) 617 __fput(file); 618 } 619 620 /* 621 * Equivalent to fput(), but optimized for being called with the last 622 * reference. 623 * 624 * See file_ref_put_close() for details. 625 */ 626 void fput_close(struct file *file) 627 { 628 if (file_ref_put_close(&file->f_ref)) 629 __fput_deferred(file); 630 } 631 632 void __init files_init(void) 633 { 634 struct kmem_cache_args args = { 635 .use_freeptr_offset = true, 636 .freeptr_offset = offsetof(struct file, f_freeptr), 637 }; 638 639 __filp_cache = kmem_cache_create("filp", sizeof(struct file), &args, 640 SLAB_HWCACHE_ALIGN | SLAB_PANIC | 641 SLAB_ACCOUNT | SLAB_TYPESAFE_BY_RCU); 642 runtime_const_init(ptr, __filp_cache); 643 644 args.freeptr_offset = offsetof(struct backing_file, bf_freeptr); 645 __bfilp_cache = kmem_cache_create("bfilp", sizeof(struct backing_file), 646 &args, SLAB_HWCACHE_ALIGN | SLAB_PANIC | 647 SLAB_ACCOUNT | SLAB_TYPESAFE_BY_RCU); 648 runtime_const_init(ptr, __bfilp_cache); 649 650 percpu_counter_init(&nr_files, 0, GFP_KERNEL); 651 } 652 653 /* 654 * One file with associated inode and dcache is very roughly 1K. Per default 655 * do not use more than 10% of our memory for files. 656 */ 657 void __init files_maxfiles_init(void) 658 { 659 unsigned long n; 660 unsigned long nr_pages = totalram_pages(); 661 unsigned long memreserve = (nr_pages - nr_free_pages()) * 3/2; 662 663 memreserve = min(memreserve, nr_pages - 1); 664 n = ((nr_pages - memreserve) * (PAGE_SIZE / 1024)) / 10; 665 666 files_stat.max_files = max_t(unsigned long, n, NR_FILE); 667 } 668