file_table.c 14 KB

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