drop_caches.c 1.8 KB

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