5 #include <linux/kthread.h>
6 #include <linux/list.h>
8 #include <linux/mutex.h>
9 #include <linux/shrinker.h>
11 #include "tools-util.h"
13 static LIST_HEAD(shrinker_list);
14 static DEFINE_MUTEX(shrinker_lock);
16 struct shrinker *shrinker_alloc(unsigned int flags, const char *fmt, ...)
18 return calloc(sizeof(struct shrinker), 1);
21 int shrinker_register(struct shrinker *shrinker)
23 mutex_lock(&shrinker_lock);
24 list_add_tail(&shrinker->list, &shrinker_list);
25 mutex_unlock(&shrinker_lock);
29 void unregister_shrinker(struct shrinker *shrinker)
31 mutex_lock(&shrinker_lock);
32 list_del(&shrinker->list);
33 mutex_unlock(&shrinker_lock);
36 static void run_shrinkers_allocation_failed(gfp_t gfp_mask)
38 struct shrinker *shrinker;
40 mutex_lock(&shrinker_lock);
41 list_for_each_entry(shrinker, &shrinker_list, list) {
42 struct shrink_control sc = { .gfp_mask = gfp_mask, };
44 unsigned long have = shrinker->count_objects(shrinker, &sc);
46 sc.nr_to_scan = have / 8;
48 shrinker->scan_objects(shrinker, &sc);
50 mutex_unlock(&shrinker_lock);
53 void run_shrinkers(gfp_t gfp_mask, bool allocation_failed)
55 struct shrinker *shrinker;
59 if (!(gfp_mask & GFP_KERNEL))
62 /* Fast out if there are no shrinkers to run. */
63 if (list_empty(&shrinker_list))
66 if (allocation_failed) {
67 run_shrinkers_allocation_failed(gfp_mask);
73 /* Aim for 6% of physical RAM free without anything in swap */
74 want_shrink = (info.totalram << 4) - info.freeram
75 + info.totalswap - info.freeswap;
79 mutex_lock(&shrinker_lock);
80 list_for_each_entry(shrinker, &shrinker_list, list) {
81 struct shrink_control sc = {
83 .nr_to_scan = want_shrink >> PAGE_SHIFT
86 shrinker->scan_objects(shrinker, &sc);
88 mutex_unlock(&shrinker_lock);
91 static int shrinker_thread(void *arg)
93 while (!kthread_should_stop()) {
97 clock_gettime(CLOCK_MONOTONIC, &to);
99 __set_current_state(TASK_INTERRUPTIBLE);
101 while ((v = READ_ONCE(current->state)) != TASK_RUNNING &&
103 futex(¤t->state, FUTEX_WAIT_BITSET|FUTEX_PRIVATE_FLAG,
104 v, &to, NULL, (uint32_t)~0);
105 if (kthread_should_stop())
107 if (v != TASK_RUNNING)
108 __set_current_state(TASK_RUNNING);
109 run_shrinkers(GFP_KERNEL, false);
115 struct task_struct *shrinker_task;
117 __attribute__((constructor(103)))
118 static void shrinker_thread_init(void)
120 shrinker_task = kthread_run(shrinker_thread, NULL, "shrinkers");
121 BUG_ON(IS_ERR(shrinker_task));
126 * We seem to be hitting a rare segfault when shutting down the shrinker thread.
127 * Disabling this is going to cause some harmless warnings about memory leaks:
129 __attribute__((destructor(103)))
130 static void shrinker_thread_exit(void)
132 int ret = kthread_stop(shrinker_task);
135 shrinker_task = NULL;