file_table.c 16 KB

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