drop_caches.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Implement the manual drop-all-pagecache function
  4. */
  5. #include <linux/pagemap.h>
  6. #include <linux/kernel.h>
  7. #include <linux/mm.h>
  8. #include <linux/fs.h>
  9. #include <linux/writeback.h>
  10. #include <linux/sysctl.h>
  11. #include <linux/gfp.h>
  12. #include <linux/swap.h>
  13. #include "internal.h"
  14. /* A global variable is a bit ugly, but it keeps the code simple */
  15. static int sysctl_drop_caches;
  16. static void drop_pagecache_sb(struct super_block *sb, void *unused)
  17. {
  18. struct inode *inode, *toput_inode = NULL;
  19. spin_lock(&sb->s_inode_list_lock);
  20. list_for_each_entry(inode, &sb->s_inodes, i_sb_list) {
  21. spin_lock(&inode->i_lock);
  22. /*
  23. * We must skip inodes in unusual state. We may also skip
  24. * inodes without pages but we deliberately won't in case
  25. * we need to reschedule to avoid softlockups.
  26. */
  27. if ((inode_state_read(inode) & (I_FREEING | I_WILL_FREE | I_NEW)) ||
  28. (mapping_empty(inode->i_mapping) && !need_resched())) {
  29. spin_unlock(&inode->i_lock);
  30. continue;
  31. }
  32. __iget(inode);
  33. spin_unlock(&inode->i_lock);
  34. spin_unlock(&sb->s_inode_list_lock);
  35. invalidate_mapping_pages(inode->i_mapping, 0, -1);
  36. iput(toput_inode);
  37. toput_inode = inode;
  38. cond_resched();
  39. spin_lock(&sb->s_inode_list_lock);
  40. }
  41. spin_unlock(&sb->s_inode_list_lock);
  42. iput(toput_inode);
  43. }
  44. static int drop_caches_sysctl_handler(const struct ctl_table *table, int write,
  45. void *buffer, size_t *length, loff_t *ppos)
  46. {
  47. int ret;
  48. ret = proc_dointvec_minmax(table, write, buffer, length, ppos);
  49. if (ret)
  50. return ret;
  51. if (write) {
  52. static int stfu;
  53. if (sysctl_drop_caches & 1) {
  54. lru_add_drain_all();
  55. iterate_supers(drop_pagecache_sb, NULL);
  56. count_vm_event(DROP_PAGECACHE);
  57. }
  58. if (sysctl_drop_caches & 2) {
  59. drop_slab();
  60. count_vm_event(DROP_SLAB);
  61. }
  62. if (!stfu) {
  63. pr_info("%s (%d): drop_caches: %d\n",
  64. current->comm, task_pid_nr(current),
  65. sysctl_drop_caches);
  66. }
  67. stfu |= sysctl_drop_caches & 4;
  68. }
  69. return 0;
  70. }
  71. static const struct ctl_table drop_caches_table[] = {
  72. {
  73. .procname = "drop_caches",
  74. .data = &sysctl_drop_caches,
  75. .maxlen = sizeof(int),
  76. .mode = 0200,
  77. .proc_handler = drop_caches_sysctl_handler,
  78. .extra1 = SYSCTL_ONE,
  79. .extra2 = SYSCTL_FOUR,
  80. },
  81. };
  82. static int __init init_vm_drop_caches_sysctls(void)
  83. {
  84. register_sysctl_init("vm", drop_caches_table);
  85. return 0;
  86. }
  87. fs_initcall(init_vm_drop_caches_sysctls);