4 #include <linux/kthread.h>
5 #include <linux/list.h>
7 #include <linux/mutex.h>
8 #include <linux/shrinker.h>
10 #include "tools-util.h"
12 static LIST_HEAD(shrinker_list);
13 static DEFINE_MUTEX(shrinker_lock);
15 int register_shrinker(struct shrinker *shrinker, const char *fmt, ...)
17 mutex_lock(&shrinker_lock);
18 list_add_tail(&shrinker->list, &shrinker_list);
19 mutex_unlock(&shrinker_lock);
23 void unregister_shrinker(struct shrinker *shrinker)
25 mutex_lock(&shrinker_lock);
26 list_del(&shrinker->list);
27 mutex_unlock(&shrinker_lock);
35 static u64 parse_meminfo_line(const char *line)
39 if (sscanf(line, " %llu kB", &v) < 1)
44 void si_meminfo(struct sysinfo *val)
51 memset(val, 0, sizeof(*val));
54 f = fopen("/proc/meminfo", "r");
58 while ((len = getline(&line, &n, f)) != -1) {
59 if ((v = strcmp_prefix(line, "MemTotal:")))
60 val->totalram = parse_meminfo_line(v);
62 if ((v = strcmp_prefix(line, "MemAvailable:")))
63 val->freeram = parse_meminfo_line(v);
70 static void run_shrinkers_allocation_failed(gfp_t gfp_mask)
72 struct shrinker *shrinker;
74 mutex_lock(&shrinker_lock);
75 list_for_each_entry(shrinker, &shrinker_list, list) {
76 struct shrink_control sc = { .gfp_mask = gfp_mask, };
78 unsigned long have = shrinker->count_objects(shrinker, &sc);
80 sc.nr_to_scan = have / 8;
82 shrinker->scan_objects(shrinker, &sc);
84 mutex_unlock(&shrinker_lock);
87 void run_shrinkers(gfp_t gfp_mask, bool allocation_failed)
89 struct shrinker *shrinker;
93 if (!(gfp_mask & GFP_KERNEL))
96 /* Fast out if there are no shrinkers to run. */
97 if (list_empty(&shrinker_list))
100 if (allocation_failed) {
101 run_shrinkers_allocation_failed(gfp_mask);
107 if (info.totalram && info.freeram) {
108 want_shrink = (info.totalram >> 2) - info.freeram;
110 if (want_shrink <= 0)
113 /* If we weren't able to read /proc/meminfo, we must be pretty
116 want_shrink = 8 << 20;
119 mutex_lock(&shrinker_lock);
120 list_for_each_entry(shrinker, &shrinker_list, list) {
121 struct shrink_control sc = {
122 .gfp_mask = gfp_mask,
123 .nr_to_scan = want_shrink >> PAGE_SHIFT
126 shrinker->scan_objects(shrinker, &sc);
128 mutex_unlock(&shrinker_lock);
131 static int shrinker_thread(void *arg)
133 while (!kthread_should_stop()) {
135 run_shrinkers(GFP_KERNEL, false);
141 struct task_struct *shrinker_task;
143 __attribute__((constructor(103)))
144 static void shrinker_thread_init(void)
146 shrinker_task = kthread_run(shrinker_thread, NULL, "shrinkers");
147 BUG_ON(IS_ERR(shrinker_task));
150 __attribute__((destructor(103)))
151 static void shrinker_thread_exit(void)
153 int ret = kthread_stop(shrinker_task);
156 shrinker_task = NULL;