xref: /linux/mm/kasan/quarantine.c (revision 60433a9d038db006ca2f49e3c5f050dc46aaad3a)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * KASAN quarantine.
4  *
5  * Author: Alexander Potapenko <glider@google.com>
6  * Copyright (C) 2016 Google, Inc.
7  *
8  * Based on code by Dmitry Chernenkov.
9  */
10 
11 #define pr_fmt(fmt) "kasan: " fmt
12 
13 #include <linux/gfp.h>
14 #include <linux/hash.h>
15 #include <linux/kernel.h>
16 #include <linux/mm.h>
17 #include <linux/percpu.h>
18 #include <linux/printk.h>
19 #include <linux/shrinker.h>
20 #include <linux/slab.h>
21 #include <linux/srcu.h>
22 #include <linux/string.h>
23 #include <linux/types.h>
24 #include <linux/cpuhotplug.h>
25 
26 #include "../slab.h"
27 #include "kasan.h"
28 
29 /* Data structure and operations for quarantine queues. */
30 
31 /*
32  * Each queue is a single-linked list, which also stores the total size of
33  * objects inside of it.
34  */
35 struct qlist_head {
36 	struct qlist_node *head;
37 	struct qlist_node *tail;
38 	size_t bytes;
39 	bool offline;
40 };
41 
42 #define QLIST_INIT { NULL, NULL, 0 }
43 
44 static bool qlist_empty(struct qlist_head *q)
45 {
46 	return !q->head;
47 }
48 
49 static void qlist_init(struct qlist_head *q)
50 {
51 	q->head = q->tail = NULL;
52 	q->bytes = 0;
53 }
54 
55 static void qlist_put(struct qlist_head *q, struct qlist_node *qlink,
56 		size_t size)
57 {
58 	if (unlikely(qlist_empty(q)))
59 		q->head = qlink;
60 	else
61 		q->tail->next = qlink;
62 	q->tail = qlink;
63 	qlink->next = NULL;
64 	q->bytes += size;
65 }
66 
67 static void qlist_move_all(struct qlist_head *from, struct qlist_head *to)
68 {
69 	if (unlikely(qlist_empty(from)))
70 		return;
71 
72 	if (qlist_empty(to)) {
73 		*to = *from;
74 		qlist_init(from);
75 		return;
76 	}
77 
78 	to->tail->next = from->head;
79 	to->tail = from->tail;
80 	to->bytes += from->bytes;
81 
82 	qlist_init(from);
83 }
84 
85 #define QUARANTINE_PERCPU_SIZE (1 << 20)
86 #define QUARANTINE_BATCHES \
87 	(1024 > 4 * CONFIG_NR_CPUS ? 1024 : 4 * CONFIG_NR_CPUS)
88 
89 /*
90  * The object quarantine consists of per-cpu queues and a global queue,
91  * guarded by quarantine_lock.
92  */
93 static DEFINE_PER_CPU(struct qlist_head, cpu_quarantine);
94 
95 /* Round-robin FIFO array of batches. */
96 static struct qlist_head global_quarantine[QUARANTINE_BATCHES];
97 static int quarantine_head;
98 static int quarantine_tail;
99 /* Total size of all objects in global_quarantine across all batches. */
100 static unsigned long quarantine_size;
101 static DEFINE_RAW_SPINLOCK(quarantine_lock);
102 DEFINE_STATIC_SRCU(remove_cache_srcu);
103 
104 struct cpu_shrink_qlist {
105 	raw_spinlock_t lock;
106 	struct qlist_head qlist;
107 };
108 
109 static DEFINE_PER_CPU(struct cpu_shrink_qlist, shrink_qlist) = {
110 	.lock = __RAW_SPIN_LOCK_UNLOCKED(shrink_qlist.lock),
111 };
112 
113 /* Maximum size of the global queue. */
114 static unsigned long quarantine_max_size;
115 
116 /*
117  * Target size of a batch in global_quarantine.
118  * Usually equal to QUARANTINE_PERCPU_SIZE unless we have too much RAM.
119  */
120 static unsigned long quarantine_batch_size;
121 
122 /*
123  * The fraction of physical memory the quarantine is allowed to occupy.
124  * Quarantine doesn't support memory shrinker with SLAB allocator, so we keep
125  * the ratio low to avoid OOM.
126  */
127 #define QUARANTINE_FRACTION 32
128 
129 static struct kmem_cache *qlink_to_cache(struct qlist_node *qlink)
130 {
131 	return virt_to_slab(qlink)->slab_cache;
132 }
133 
134 static void *qlink_to_object(struct qlist_node *qlink, struct kmem_cache *cache)
135 {
136 	struct kasan_free_meta *free_info =
137 		container_of(qlink, struct kasan_free_meta,
138 			     quarantine_link);
139 
140 	return ((void *)free_info) - cache->kasan_info.free_meta_offset;
141 }
142 
143 static void qlink_free(struct qlist_node *qlink, struct kmem_cache *cache)
144 {
145 	void *object = qlink_to_object(qlink, cache);
146 	struct kasan_alloc_meta *alloc_meta = kasan_get_alloc_meta(cache, object);
147 	struct kasan_free_meta *free_meta = kasan_get_free_meta(cache, object);
148 	unsigned long flags;
149 
150 	if (alloc_meta) {
151 		stack_depot_put(alloc_meta->alloc_track.stack);
152 		stack_depot_put(alloc_meta->aux_stack[0]);
153 		stack_depot_put(alloc_meta->aux_stack[1]);
154 		__memset(alloc_meta, 0, sizeof(*alloc_meta));
155 	}
156 
157 	if (free_meta &&
158 	    *(u8 *)kasan_mem_to_shadow(object) == KASAN_SLAB_FREETRACK) {
159 		stack_depot_put(free_meta->free_track.stack);
160 		free_meta->free_track.stack = 0;
161 	}
162 
163 	/*
164 	 * If init_on_free is enabled and KASAN's free metadata is stored in
165 	 * the object, zero the metadata. Otherwise, the object's memory will
166 	 * not be properly zeroed, as KASAN saves the metadata after the slab
167 	 * allocator zeroes the object.
168 	 */
169 	if (slab_want_init_on_free(cache) &&
170 	    cache->kasan_info.free_meta_offset == 0)
171 		memzero_explicit(free_meta, sizeof(*free_meta));
172 
173 	/*
174 	 * As the object now gets freed from the quarantine,
175 	 * take note that its free track is no longer exists.
176 	 */
177 	*(u8 *)kasan_mem_to_shadow(object) = KASAN_SLAB_FREE;
178 
179 	if (IS_ENABLED(CONFIG_SLAB))
180 		local_irq_save(flags);
181 
182 	___cache_free(cache, object, _THIS_IP_);
183 
184 	if (IS_ENABLED(CONFIG_SLAB))
185 		local_irq_restore(flags);
186 }
187 
188 static void qlist_free_all(struct qlist_head *q, struct kmem_cache *cache)
189 {
190 	struct qlist_node *qlink;
191 
192 	if (unlikely(qlist_empty(q)))
193 		return;
194 
195 	qlink = q->head;
196 	while (qlink) {
197 		struct kmem_cache *obj_cache =
198 			cache ? cache :	qlink_to_cache(qlink);
199 		struct qlist_node *next = qlink->next;
200 
201 		qlink_free(qlink, obj_cache);
202 		qlink = next;
203 	}
204 	qlist_init(q);
205 }
206 
207 bool kasan_quarantine_put(struct kmem_cache *cache, void *object)
208 {
209 	unsigned long flags;
210 	struct qlist_head *q;
211 	struct qlist_head temp = QLIST_INIT;
212 	struct kasan_free_meta *meta = kasan_get_free_meta(cache, object);
213 
214 	/*
215 	 * If there's no metadata for this object, don't put it into
216 	 * quarantine.
217 	 */
218 	if (!meta)
219 		return false;
220 
221 	/*
222 	 * Note: irq must be disabled until after we move the batch to the
223 	 * global quarantine. Otherwise kasan_quarantine_remove_cache() can
224 	 * miss some objects belonging to the cache if they are in our local
225 	 * temp list. kasan_quarantine_remove_cache() executes on_each_cpu()
226 	 * at the beginning which ensures that it either sees the objects in
227 	 * per-cpu lists or in the global quarantine.
228 	 */
229 	local_irq_save(flags);
230 
231 	q = this_cpu_ptr(&cpu_quarantine);
232 	if (q->offline) {
233 		local_irq_restore(flags);
234 		return false;
235 	}
236 	qlist_put(q, &meta->quarantine_link, cache->size);
237 	if (unlikely(q->bytes > QUARANTINE_PERCPU_SIZE)) {
238 		qlist_move_all(q, &temp);
239 
240 		raw_spin_lock(&quarantine_lock);
241 		WRITE_ONCE(quarantine_size, quarantine_size + temp.bytes);
242 		qlist_move_all(&temp, &global_quarantine[quarantine_tail]);
243 		if (global_quarantine[quarantine_tail].bytes >=
244 				READ_ONCE(quarantine_batch_size)) {
245 			int new_tail;
246 
247 			new_tail = quarantine_tail + 1;
248 			if (new_tail == QUARANTINE_BATCHES)
249 				new_tail = 0;
250 			if (new_tail != quarantine_head)
251 				quarantine_tail = new_tail;
252 		}
253 		raw_spin_unlock(&quarantine_lock);
254 	}
255 
256 	local_irq_restore(flags);
257 
258 	return true;
259 }
260 
261 void kasan_quarantine_reduce(void)
262 {
263 	size_t total_size, new_quarantine_size, percpu_quarantines;
264 	unsigned long flags;
265 	int srcu_idx;
266 	struct qlist_head to_free = QLIST_INIT;
267 
268 	if (likely(READ_ONCE(quarantine_size) <=
269 		   READ_ONCE(quarantine_max_size)))
270 		return;
271 
272 	/*
273 	 * srcu critical section ensures that kasan_quarantine_remove_cache()
274 	 * will not miss objects belonging to the cache while they are in our
275 	 * local to_free list. srcu is chosen because (1) it gives us private
276 	 * grace period domain that does not interfere with anything else,
277 	 * and (2) it allows synchronize_srcu() to return without waiting
278 	 * if there are no pending read critical sections (which is the
279 	 * expected case).
280 	 */
281 	srcu_idx = srcu_read_lock(&remove_cache_srcu);
282 	raw_spin_lock_irqsave(&quarantine_lock, flags);
283 
284 	/*
285 	 * Update quarantine size in case of hotplug. Allocate a fraction of
286 	 * the installed memory to quarantine minus per-cpu queue limits.
287 	 */
288 	total_size = (totalram_pages() << PAGE_SHIFT) /
289 		QUARANTINE_FRACTION;
290 	percpu_quarantines = QUARANTINE_PERCPU_SIZE * num_online_cpus();
291 	new_quarantine_size = (total_size < percpu_quarantines) ?
292 		0 : total_size - percpu_quarantines;
293 	WRITE_ONCE(quarantine_max_size, new_quarantine_size);
294 	/* Aim at consuming at most 1/2 of slots in quarantine. */
295 	WRITE_ONCE(quarantine_batch_size, max((size_t)QUARANTINE_PERCPU_SIZE,
296 		2 * total_size / QUARANTINE_BATCHES));
297 
298 	if (likely(quarantine_size > quarantine_max_size)) {
299 		qlist_move_all(&global_quarantine[quarantine_head], &to_free);
300 		WRITE_ONCE(quarantine_size, quarantine_size - to_free.bytes);
301 		quarantine_head++;
302 		if (quarantine_head == QUARANTINE_BATCHES)
303 			quarantine_head = 0;
304 	}
305 
306 	raw_spin_unlock_irqrestore(&quarantine_lock, flags);
307 
308 	qlist_free_all(&to_free, NULL);
309 	srcu_read_unlock(&remove_cache_srcu, srcu_idx);
310 }
311 
312 static void qlist_move_cache(struct qlist_head *from,
313 				   struct qlist_head *to,
314 				   struct kmem_cache *cache)
315 {
316 	struct qlist_node *curr;
317 
318 	if (unlikely(qlist_empty(from)))
319 		return;
320 
321 	curr = from->head;
322 	qlist_init(from);
323 	while (curr) {
324 		struct qlist_node *next = curr->next;
325 		struct kmem_cache *obj_cache = qlink_to_cache(curr);
326 
327 		if (obj_cache == cache)
328 			qlist_put(to, curr, obj_cache->size);
329 		else
330 			qlist_put(from, curr, obj_cache->size);
331 
332 		curr = next;
333 	}
334 }
335 
336 static void __per_cpu_remove_cache(struct qlist_head *q, void *arg)
337 {
338 	struct kmem_cache *cache = arg;
339 	unsigned long flags;
340 	struct cpu_shrink_qlist *sq;
341 
342 	sq = this_cpu_ptr(&shrink_qlist);
343 	raw_spin_lock_irqsave(&sq->lock, flags);
344 	qlist_move_cache(q, &sq->qlist, cache);
345 	raw_spin_unlock_irqrestore(&sq->lock, flags);
346 }
347 
348 static void per_cpu_remove_cache(void *arg)
349 {
350 	struct qlist_head *q;
351 
352 	q = this_cpu_ptr(&cpu_quarantine);
353 	/*
354 	 * Ensure the ordering between the writing to q->offline and
355 	 * per_cpu_remove_cache.  Prevent cpu_quarantine from being corrupted
356 	 * by interrupt.
357 	 */
358 	if (READ_ONCE(q->offline))
359 		return;
360 	__per_cpu_remove_cache(q, arg);
361 }
362 
363 /* Free all quarantined objects belonging to cache. */
364 void kasan_quarantine_remove_cache(struct kmem_cache *cache)
365 {
366 	unsigned long flags, i;
367 	struct qlist_head to_free = QLIST_INIT;
368 	int cpu;
369 	struct cpu_shrink_qlist *sq;
370 
371 	/*
372 	 * Must be careful to not miss any objects that are being moved from
373 	 * per-cpu list to the global quarantine in kasan_quarantine_put(),
374 	 * nor objects being freed in kasan_quarantine_reduce(). on_each_cpu()
375 	 * achieves the first goal, while synchronize_srcu() achieves the
376 	 * second.
377 	 */
378 	on_each_cpu(per_cpu_remove_cache, cache, 1);
379 
380 	for_each_online_cpu(cpu) {
381 		sq = per_cpu_ptr(&shrink_qlist, cpu);
382 		raw_spin_lock_irqsave(&sq->lock, flags);
383 		qlist_move_cache(&sq->qlist, &to_free, cache);
384 		raw_spin_unlock_irqrestore(&sq->lock, flags);
385 	}
386 	qlist_free_all(&to_free, cache);
387 
388 	raw_spin_lock_irqsave(&quarantine_lock, flags);
389 	for (i = 0; i < QUARANTINE_BATCHES; i++) {
390 		if (qlist_empty(&global_quarantine[i]))
391 			continue;
392 		qlist_move_cache(&global_quarantine[i], &to_free, cache);
393 		/* Scanning whole quarantine can take a while. */
394 		raw_spin_unlock_irqrestore(&quarantine_lock, flags);
395 		cond_resched();
396 		raw_spin_lock_irqsave(&quarantine_lock, flags);
397 	}
398 	raw_spin_unlock_irqrestore(&quarantine_lock, flags);
399 
400 	qlist_free_all(&to_free, cache);
401 
402 	synchronize_srcu(&remove_cache_srcu);
403 }
404 
405 static int kasan_cpu_online(unsigned int cpu)
406 {
407 	this_cpu_ptr(&cpu_quarantine)->offline = false;
408 	return 0;
409 }
410 
411 static int kasan_cpu_offline(unsigned int cpu)
412 {
413 	struct qlist_head *q;
414 
415 	q = this_cpu_ptr(&cpu_quarantine);
416 	/* Ensure the ordering between the writing to q->offline and
417 	 * qlist_free_all. Otherwise, cpu_quarantine may be corrupted
418 	 * by interrupt.
419 	 */
420 	WRITE_ONCE(q->offline, true);
421 	barrier();
422 	qlist_free_all(q, NULL);
423 	return 0;
424 }
425 
426 static int __init kasan_cpu_quarantine_init(void)
427 {
428 	int ret = 0;
429 
430 	ret = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "mm/kasan:online",
431 				kasan_cpu_online, kasan_cpu_offline);
432 	if (ret < 0)
433 		pr_err("cpu quarantine register failed [%d]\n", ret);
434 	return ret;
435 }
436 late_initcall(kasan_cpu_quarantine_init);
437