kmemleak: Allow rescheduling during an object scanning
[GitHub/exynos8895/android_kernel_samsung_universal8895.git] / mm / kmemleak.c
CommitLineData
3c7b4e6b
CM
1/*
2 * mm/kmemleak.c
3 *
4 * Copyright (C) 2008 ARM Limited
5 * Written by Catalin Marinas <catalin.marinas@arm.com>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License version 2 as
9 * published by the Free Software Foundation.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 *
20 *
21 * For more information on the algorithm and kmemleak usage, please see
22 * Documentation/kmemleak.txt.
23 *
24 * Notes on locking
25 * ----------------
26 *
27 * The following locks and mutexes are used by kmemleak:
28 *
29 * - kmemleak_lock (rwlock): protects the object_list modifications and
30 * accesses to the object_tree_root. The object_list is the main list
31 * holding the metadata (struct kmemleak_object) for the allocated memory
32 * blocks. The object_tree_root is a priority search tree used to look-up
33 * metadata based on a pointer to the corresponding memory block. The
34 * kmemleak_object structures are added to the object_list and
35 * object_tree_root in the create_object() function called from the
36 * kmemleak_alloc() callback and removed in delete_object() called from the
37 * kmemleak_free() callback
38 * - kmemleak_object.lock (spinlock): protects a kmemleak_object. Accesses to
39 * the metadata (e.g. count) are protected by this lock. Note that some
40 * members of this structure may be protected by other means (atomic or
41 * kmemleak_lock). This lock is also held when scanning the corresponding
42 * memory block to avoid the kernel freeing it via the kmemleak_free()
43 * callback. This is less heavyweight than holding a global lock like
44 * kmemleak_lock during scanning
45 * - scan_mutex (mutex): ensures that only one thread may scan the memory for
46 * unreferenced objects at a time. The gray_list contains the objects which
47 * are already referenced or marked as false positives and need to be
48 * scanned. This list is only modified during a scanning episode when the
49 * scan_mutex is held. At the end of a scan, the gray_list is always empty.
50 * Note that the kmemleak_object.use_count is incremented when an object is
4698c1f2
CM
51 * added to the gray_list and therefore cannot be freed. This mutex also
52 * prevents multiple users of the "kmemleak" debugfs file together with
53 * modifications to the memory scanning parameters including the scan_thread
54 * pointer
3c7b4e6b
CM
55 *
56 * The kmemleak_object structures have a use_count incremented or decremented
57 * using the get_object()/put_object() functions. When the use_count becomes
58 * 0, this count can no longer be incremented and put_object() schedules the
59 * kmemleak_object freeing via an RCU callback. All calls to the get_object()
60 * function must be protected by rcu_read_lock() to avoid accessing a freed
61 * structure.
62 */
63
ae281064
JP
64#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
65
3c7b4e6b
CM
66#include <linux/init.h>
67#include <linux/kernel.h>
68#include <linux/list.h>
69#include <linux/sched.h>
70#include <linux/jiffies.h>
71#include <linux/delay.h>
72#include <linux/module.h>
73#include <linux/kthread.h>
74#include <linux/prio_tree.h>
75#include <linux/gfp.h>
76#include <linux/fs.h>
77#include <linux/debugfs.h>
78#include <linux/seq_file.h>
79#include <linux/cpumask.h>
80#include <linux/spinlock.h>
81#include <linux/mutex.h>
82#include <linux/rcupdate.h>
83#include <linux/stacktrace.h>
84#include <linux/cache.h>
85#include <linux/percpu.h>
86#include <linux/hardirq.h>
87#include <linux/mmzone.h>
88#include <linux/slab.h>
89#include <linux/thread_info.h>
90#include <linux/err.h>
91#include <linux/uaccess.h>
92#include <linux/string.h>
93#include <linux/nodemask.h>
94#include <linux/mm.h>
95
96#include <asm/sections.h>
97#include <asm/processor.h>
98#include <asm/atomic.h>
99
100#include <linux/kmemleak.h>
101
102/*
103 * Kmemleak configuration and common defines.
104 */
105#define MAX_TRACE 16 /* stack trace length */
3c7b4e6b 106#define MSECS_MIN_AGE 5000 /* minimum object age for reporting */
3c7b4e6b
CM
107#define SECS_FIRST_SCAN 60 /* delay before the first scan */
108#define SECS_SCAN_WAIT 600 /* subsequent auto scanning delay */
2587362e 109#define GRAY_LIST_PASSES 25 /* maximum number of gray list scans */
af98603d 110#define MAX_SCAN_SIZE 4096 /* maximum size of a scanned block */
3c7b4e6b
CM
111
112#define BYTES_PER_POINTER sizeof(void *)
113
216c04b0
CM
114/* GFP bitmask for kmemleak internal allocations */
115#define GFP_KMEMLEAK_MASK (GFP_KERNEL | GFP_ATOMIC)
116
3c7b4e6b
CM
117/* scanning area inside a memory block */
118struct kmemleak_scan_area {
119 struct hlist_node node;
120 unsigned long offset;
121 size_t length;
122};
123
124/*
125 * Structure holding the metadata for each allocated memory block.
126 * Modifications to such objects should be made while holding the
127 * object->lock. Insertions or deletions from object_list, gray_list or
128 * tree_node are already protected by the corresponding locks or mutex (see
129 * the notes on locking above). These objects are reference-counted
130 * (use_count) and freed using the RCU mechanism.
131 */
132struct kmemleak_object {
133 spinlock_t lock;
134 unsigned long flags; /* object status flags */
135 struct list_head object_list;
136 struct list_head gray_list;
137 struct prio_tree_node tree_node;
138 struct rcu_head rcu; /* object_list lockless traversal */
139 /* object usage count; object freed when use_count == 0 */
140 atomic_t use_count;
141 unsigned long pointer;
142 size_t size;
143 /* minimum number of a pointers found before it is considered leak */
144 int min_count;
145 /* the total number of pointers found pointing to this object */
146 int count;
147 /* memory ranges to be scanned inside an object (empty for all) */
148 struct hlist_head area_list;
149 unsigned long trace[MAX_TRACE];
150 unsigned int trace_len;
151 unsigned long jiffies; /* creation timestamp */
152 pid_t pid; /* pid of the current task */
153 char comm[TASK_COMM_LEN]; /* executable name */
154};
155
156/* flag representing the memory block allocation status */
157#define OBJECT_ALLOCATED (1 << 0)
158/* flag set after the first reporting of an unreference object */
159#define OBJECT_REPORTED (1 << 1)
160/* flag set to not scan the object */
161#define OBJECT_NO_SCAN (1 << 2)
2587362e
CM
162/* flag set on newly allocated objects */
163#define OBJECT_NEW (1 << 3)
3c7b4e6b
CM
164
165/* the list of all allocated objects */
166static LIST_HEAD(object_list);
167/* the list of gray-colored objects (see color_gray comment below) */
168static LIST_HEAD(gray_list);
169/* prio search tree for object boundaries */
170static struct prio_tree_root object_tree_root;
171/* rw_lock protecting the access to object_list and prio_tree_root */
172static DEFINE_RWLOCK(kmemleak_lock);
173
174/* allocation caches for kmemleak internal data */
175static struct kmem_cache *object_cache;
176static struct kmem_cache *scan_area_cache;
177
178/* set if tracing memory operations is enabled */
179static atomic_t kmemleak_enabled = ATOMIC_INIT(0);
180/* set in the late_initcall if there were no errors */
181static atomic_t kmemleak_initialized = ATOMIC_INIT(0);
182/* enables or disables early logging of the memory operations */
183static atomic_t kmemleak_early_log = ATOMIC_INIT(1);
184/* set if a fata kmemleak error has occurred */
185static atomic_t kmemleak_error = ATOMIC_INIT(0);
186
187/* minimum and maximum address that may be valid pointers */
188static unsigned long min_addr = ULONG_MAX;
189static unsigned long max_addr;
190
3c7b4e6b 191static struct task_struct *scan_thread;
acf4968e 192/* used to avoid reporting of recently allocated objects */
3c7b4e6b 193static unsigned long jiffies_min_age;
acf4968e 194static unsigned long jiffies_last_scan;
3c7b4e6b
CM
195/* delay between automatic memory scannings */
196static signed long jiffies_scan_wait;
197/* enables or disables the task stacks scanning */
e0a2a160 198static int kmemleak_stack_scan = 1;
4698c1f2 199/* protects the memory scanning, parameters and debug/kmemleak file access */
3c7b4e6b 200static DEFINE_MUTEX(scan_mutex);
3c7b4e6b 201
3c7b4e6b 202/*
2030117d 203 * Early object allocation/freeing logging. Kmemleak is initialized after the
3c7b4e6b 204 * kernel allocator. However, both the kernel allocator and kmemleak may
2030117d 205 * allocate memory blocks which need to be tracked. Kmemleak defines an
3c7b4e6b
CM
206 * arbitrary buffer to hold the allocation/freeing information before it is
207 * fully initialized.
208 */
209
210/* kmemleak operation type for early logging */
211enum {
212 KMEMLEAK_ALLOC,
213 KMEMLEAK_FREE,
53238a60 214 KMEMLEAK_FREE_PART,
3c7b4e6b
CM
215 KMEMLEAK_NOT_LEAK,
216 KMEMLEAK_IGNORE,
217 KMEMLEAK_SCAN_AREA,
218 KMEMLEAK_NO_SCAN
219};
220
221/*
222 * Structure holding the information passed to kmemleak callbacks during the
223 * early logging.
224 */
225struct early_log {
226 int op_type; /* kmemleak operation type */
227 const void *ptr; /* allocated/freed memory block */
228 size_t size; /* memory block size */
229 int min_count; /* minimum reference count */
230 unsigned long offset; /* scan area offset */
231 size_t length; /* scan area length */
232};
233
234/* early logging buffer and current position */
a9d9058a 235static struct early_log early_log[CONFIG_DEBUG_KMEMLEAK_EARLY_LOG_SIZE];
3c7b4e6b
CM
236static int crt_early_log;
237
238static void kmemleak_disable(void);
239
240/*
241 * Print a warning and dump the stack trace.
242 */
243#define kmemleak_warn(x...) do { \
244 pr_warning(x); \
245 dump_stack(); \
246} while (0)
247
248/*
249 * Macro invoked when a serious kmemleak condition occured and cannot be
2030117d 250 * recovered from. Kmemleak will be disabled and further allocation/freeing
3c7b4e6b
CM
251 * tracing no longer available.
252 */
000814f4 253#define kmemleak_stop(x...) do { \
3c7b4e6b
CM
254 kmemleak_warn(x); \
255 kmemleak_disable(); \
256} while (0)
257
258/*
259 * Object colors, encoded with count and min_count:
260 * - white - orphan object, not enough references to it (count < min_count)
261 * - gray - not orphan, not marked as false positive (min_count == 0) or
262 * sufficient references to it (count >= min_count)
263 * - black - ignore, it doesn't contain references (e.g. text section)
264 * (min_count == -1). No function defined for this color.
265 * Newly created objects don't have any color assigned (object->count == -1)
266 * before the next memory scan when they become white.
267 */
268static int color_white(const struct kmemleak_object *object)
269{
270 return object->count != -1 && object->count < object->min_count;
271}
272
273static int color_gray(const struct kmemleak_object *object)
274{
275 return object->min_count != -1 && object->count >= object->min_count;
276}
277
2587362e
CM
278static int color_black(const struct kmemleak_object *object)
279{
280 return object->min_count == -1;
281}
282
3c7b4e6b
CM
283/*
284 * Objects are considered unreferenced only if their color is white, they have
285 * not be deleted and have a minimum age to avoid false positives caused by
286 * pointers temporarily stored in CPU registers.
287 */
288static int unreferenced_object(struct kmemleak_object *object)
289{
290 return (object->flags & OBJECT_ALLOCATED) && color_white(object) &&
acf4968e
CM
291 time_before_eq(object->jiffies + jiffies_min_age,
292 jiffies_last_scan);
3c7b4e6b
CM
293}
294
295/*
bab4a34a
CM
296 * Printing of the unreferenced objects information to the seq file. The
297 * print_unreferenced function must be called with the object->lock held.
3c7b4e6b 298 */
3c7b4e6b
CM
299static void print_unreferenced(struct seq_file *seq,
300 struct kmemleak_object *object)
301{
302 int i;
303
bab4a34a
CM
304 seq_printf(seq, "unreferenced object 0x%08lx (size %zu):\n",
305 object->pointer, object->size);
306 seq_printf(seq, " comm \"%s\", pid %d, jiffies %lu\n",
307 object->comm, object->pid, object->jiffies);
308 seq_printf(seq, " backtrace:\n");
3c7b4e6b
CM
309
310 for (i = 0; i < object->trace_len; i++) {
311 void *ptr = (void *)object->trace[i];
bab4a34a 312 seq_printf(seq, " [<%p>] %pS\n", ptr, ptr);
3c7b4e6b
CM
313 }
314}
315
316/*
317 * Print the kmemleak_object information. This function is used mainly for
318 * debugging special cases when kmemleak operations. It must be called with
319 * the object->lock held.
320 */
321static void dump_object_info(struct kmemleak_object *object)
322{
323 struct stack_trace trace;
324
325 trace.nr_entries = object->trace_len;
326 trace.entries = object->trace;
327
ae281064 328 pr_notice("Object 0x%08lx (size %zu):\n",
3c7b4e6b
CM
329 object->tree_node.start, object->size);
330 pr_notice(" comm \"%s\", pid %d, jiffies %lu\n",
331 object->comm, object->pid, object->jiffies);
332 pr_notice(" min_count = %d\n", object->min_count);
333 pr_notice(" count = %d\n", object->count);
334 pr_notice(" backtrace:\n");
335 print_stack_trace(&trace, 4);
336}
337
338/*
339 * Look-up a memory block metadata (kmemleak_object) in the priority search
340 * tree based on a pointer value. If alias is 0, only values pointing to the
341 * beginning of the memory block are allowed. The kmemleak_lock must be held
342 * when calling this function.
343 */
344static struct kmemleak_object *lookup_object(unsigned long ptr, int alias)
345{
346 struct prio_tree_node *node;
347 struct prio_tree_iter iter;
348 struct kmemleak_object *object;
349
350 prio_tree_iter_init(&iter, &object_tree_root, ptr, ptr);
351 node = prio_tree_next(&iter);
352 if (node) {
353 object = prio_tree_entry(node, struct kmemleak_object,
354 tree_node);
355 if (!alias && object->pointer != ptr) {
ae281064 356 kmemleak_warn("Found object by alias");
3c7b4e6b
CM
357 object = NULL;
358 }
359 } else
360 object = NULL;
361
362 return object;
363}
364
365/*
366 * Increment the object use_count. Return 1 if successful or 0 otherwise. Note
367 * that once an object's use_count reached 0, the RCU freeing was already
368 * registered and the object should no longer be used. This function must be
369 * called under the protection of rcu_read_lock().
370 */
371static int get_object(struct kmemleak_object *object)
372{
373 return atomic_inc_not_zero(&object->use_count);
374}
375
376/*
377 * RCU callback to free a kmemleak_object.
378 */
379static void free_object_rcu(struct rcu_head *rcu)
380{
381 struct hlist_node *elem, *tmp;
382 struct kmemleak_scan_area *area;
383 struct kmemleak_object *object =
384 container_of(rcu, struct kmemleak_object, rcu);
385
386 /*
387 * Once use_count is 0 (guaranteed by put_object), there is no other
388 * code accessing this object, hence no need for locking.
389 */
390 hlist_for_each_entry_safe(area, elem, tmp, &object->area_list, node) {
391 hlist_del(elem);
392 kmem_cache_free(scan_area_cache, area);
393 }
394 kmem_cache_free(object_cache, object);
395}
396
397/*
398 * Decrement the object use_count. Once the count is 0, free the object using
399 * an RCU callback. Since put_object() may be called via the kmemleak_free() ->
400 * delete_object() path, the delayed RCU freeing ensures that there is no
401 * recursive call to the kernel allocator. Lock-less RCU object_list traversal
402 * is also possible.
403 */
404static void put_object(struct kmemleak_object *object)
405{
406 if (!atomic_dec_and_test(&object->use_count))
407 return;
408
409 /* should only get here after delete_object was called */
410 WARN_ON(object->flags & OBJECT_ALLOCATED);
411
412 call_rcu(&object->rcu, free_object_rcu);
413}
414
415/*
416 * Look up an object in the prio search tree and increase its use_count.
417 */
418static struct kmemleak_object *find_and_get_object(unsigned long ptr, int alias)
419{
420 unsigned long flags;
421 struct kmemleak_object *object = NULL;
422
423 rcu_read_lock();
424 read_lock_irqsave(&kmemleak_lock, flags);
425 if (ptr >= min_addr && ptr < max_addr)
426 object = lookup_object(ptr, alias);
427 read_unlock_irqrestore(&kmemleak_lock, flags);
428
429 /* check whether the object is still available */
430 if (object && !get_object(object))
431 object = NULL;
432 rcu_read_unlock();
433
434 return object;
435}
436
437/*
438 * Create the metadata (struct kmemleak_object) corresponding to an allocated
439 * memory block and add it to the object_list and object_tree_root.
440 */
441static void create_object(unsigned long ptr, size_t size, int min_count,
442 gfp_t gfp)
443{
444 unsigned long flags;
445 struct kmemleak_object *object;
446 struct prio_tree_node *node;
447 struct stack_trace trace;
448
216c04b0 449 object = kmem_cache_alloc(object_cache, gfp & GFP_KMEMLEAK_MASK);
3c7b4e6b 450 if (!object) {
ae281064 451 kmemleak_stop("Cannot allocate a kmemleak_object structure\n");
3c7b4e6b
CM
452 return;
453 }
454
455 INIT_LIST_HEAD(&object->object_list);
456 INIT_LIST_HEAD(&object->gray_list);
457 INIT_HLIST_HEAD(&object->area_list);
458 spin_lock_init(&object->lock);
459 atomic_set(&object->use_count, 1);
2587362e 460 object->flags = OBJECT_ALLOCATED | OBJECT_NEW;
3c7b4e6b
CM
461 object->pointer = ptr;
462 object->size = size;
463 object->min_count = min_count;
464 object->count = -1; /* no color initially */
465 object->jiffies = jiffies;
466
467 /* task information */
468 if (in_irq()) {
469 object->pid = 0;
470 strncpy(object->comm, "hardirq", sizeof(object->comm));
471 } else if (in_softirq()) {
472 object->pid = 0;
473 strncpy(object->comm, "softirq", sizeof(object->comm));
474 } else {
475 object->pid = current->pid;
476 /*
477 * There is a small chance of a race with set_task_comm(),
478 * however using get_task_comm() here may cause locking
479 * dependency issues with current->alloc_lock. In the worst
480 * case, the command line is not correct.
481 */
482 strncpy(object->comm, current->comm, sizeof(object->comm));
483 }
484
485 /* kernel backtrace */
486 trace.max_entries = MAX_TRACE;
487 trace.nr_entries = 0;
488 trace.entries = object->trace;
489 trace.skip = 1;
490 save_stack_trace(&trace);
491 object->trace_len = trace.nr_entries;
492
493 INIT_PRIO_TREE_NODE(&object->tree_node);
494 object->tree_node.start = ptr;
495 object->tree_node.last = ptr + size - 1;
496
497 write_lock_irqsave(&kmemleak_lock, flags);
498 min_addr = min(min_addr, ptr);
499 max_addr = max(max_addr, ptr + size);
500 node = prio_tree_insert(&object_tree_root, &object->tree_node);
501 /*
502 * The code calling the kernel does not yet have the pointer to the
503 * memory block to be able to free it. However, we still hold the
504 * kmemleak_lock here in case parts of the kernel started freeing
505 * random memory blocks.
506 */
507 if (node != &object->tree_node) {
508 unsigned long flags;
509
ae281064
JP
510 kmemleak_stop("Cannot insert 0x%lx into the object search tree "
511 "(already existing)\n", ptr);
3c7b4e6b
CM
512 object = lookup_object(ptr, 1);
513 spin_lock_irqsave(&object->lock, flags);
514 dump_object_info(object);
515 spin_unlock_irqrestore(&object->lock, flags);
516
517 goto out;
518 }
519 list_add_tail_rcu(&object->object_list, &object_list);
520out:
521 write_unlock_irqrestore(&kmemleak_lock, flags);
522}
523
524/*
525 * Remove the metadata (struct kmemleak_object) for a memory block from the
526 * object_list and object_tree_root and decrement its use_count.
527 */
53238a60 528static void __delete_object(struct kmemleak_object *object)
3c7b4e6b
CM
529{
530 unsigned long flags;
3c7b4e6b
CM
531
532 write_lock_irqsave(&kmemleak_lock, flags);
3c7b4e6b
CM
533 prio_tree_remove(&object_tree_root, &object->tree_node);
534 list_del_rcu(&object->object_list);
535 write_unlock_irqrestore(&kmemleak_lock, flags);
536
537 WARN_ON(!(object->flags & OBJECT_ALLOCATED));
53238a60 538 WARN_ON(atomic_read(&object->use_count) < 2);
3c7b4e6b
CM
539
540 /*
541 * Locking here also ensures that the corresponding memory block
542 * cannot be freed when it is being scanned.
543 */
544 spin_lock_irqsave(&object->lock, flags);
3c7b4e6b
CM
545 object->flags &= ~OBJECT_ALLOCATED;
546 spin_unlock_irqrestore(&object->lock, flags);
547 put_object(object);
548}
549
53238a60
CM
550/*
551 * Look up the metadata (struct kmemleak_object) corresponding to ptr and
552 * delete it.
553 */
554static void delete_object_full(unsigned long ptr)
555{
556 struct kmemleak_object *object;
557
558 object = find_and_get_object(ptr, 0);
559 if (!object) {
560#ifdef DEBUG
561 kmemleak_warn("Freeing unknown object at 0x%08lx\n",
562 ptr);
563#endif
564 return;
565 }
566 __delete_object(object);
567 put_object(object);
568}
569
570/*
571 * Look up the metadata (struct kmemleak_object) corresponding to ptr and
572 * delete it. If the memory block is partially freed, the function may create
573 * additional metadata for the remaining parts of the block.
574 */
575static void delete_object_part(unsigned long ptr, size_t size)
576{
577 struct kmemleak_object *object;
578 unsigned long start, end;
579
580 object = find_and_get_object(ptr, 1);
581 if (!object) {
582#ifdef DEBUG
583 kmemleak_warn("Partially freeing unknown object at 0x%08lx "
584 "(size %zu)\n", ptr, size);
585#endif
586 return;
587 }
588 __delete_object(object);
589
590 /*
591 * Create one or two objects that may result from the memory block
592 * split. Note that partial freeing is only done by free_bootmem() and
593 * this happens before kmemleak_init() is called. The path below is
594 * only executed during early log recording in kmemleak_init(), so
595 * GFP_KERNEL is enough.
596 */
597 start = object->pointer;
598 end = object->pointer + object->size;
599 if (ptr > start)
600 create_object(start, ptr - start, object->min_count,
601 GFP_KERNEL);
602 if (ptr + size < end)
603 create_object(ptr + size, end - ptr - size, object->min_count,
604 GFP_KERNEL);
605
606 put_object(object);
607}
3c7b4e6b
CM
608/*
609 * Make a object permanently as gray-colored so that it can no longer be
610 * reported as a leak. This is used in general to mark a false positive.
611 */
612static void make_gray_object(unsigned long ptr)
613{
614 unsigned long flags;
615 struct kmemleak_object *object;
616
617 object = find_and_get_object(ptr, 0);
618 if (!object) {
ae281064 619 kmemleak_warn("Graying unknown object at 0x%08lx\n", ptr);
3c7b4e6b
CM
620 return;
621 }
622
623 spin_lock_irqsave(&object->lock, flags);
624 object->min_count = 0;
625 spin_unlock_irqrestore(&object->lock, flags);
626 put_object(object);
627}
628
629/*
630 * Mark the object as black-colored so that it is ignored from scans and
631 * reporting.
632 */
633static void make_black_object(unsigned long ptr)
634{
635 unsigned long flags;
636 struct kmemleak_object *object;
637
638 object = find_and_get_object(ptr, 0);
639 if (!object) {
ae281064 640 kmemleak_warn("Blacking unknown object at 0x%08lx\n", ptr);
3c7b4e6b
CM
641 return;
642 }
643
644 spin_lock_irqsave(&object->lock, flags);
645 object->min_count = -1;
af98603d 646 object->flags |= OBJECT_NO_SCAN;
3c7b4e6b
CM
647 spin_unlock_irqrestore(&object->lock, flags);
648 put_object(object);
649}
650
651/*
652 * Add a scanning area to the object. If at least one such area is added,
653 * kmemleak will only scan these ranges rather than the whole memory block.
654 */
655static void add_scan_area(unsigned long ptr, unsigned long offset,
656 size_t length, gfp_t gfp)
657{
658 unsigned long flags;
659 struct kmemleak_object *object;
660 struct kmemleak_scan_area *area;
661
662 object = find_and_get_object(ptr, 0);
663 if (!object) {
ae281064
JP
664 kmemleak_warn("Adding scan area to unknown object at 0x%08lx\n",
665 ptr);
3c7b4e6b
CM
666 return;
667 }
668
216c04b0 669 area = kmem_cache_alloc(scan_area_cache, gfp & GFP_KMEMLEAK_MASK);
3c7b4e6b 670 if (!area) {
ae281064 671 kmemleak_warn("Cannot allocate a scan area\n");
3c7b4e6b
CM
672 goto out;
673 }
674
675 spin_lock_irqsave(&object->lock, flags);
676 if (offset + length > object->size) {
ae281064 677 kmemleak_warn("Scan area larger than object 0x%08lx\n", ptr);
3c7b4e6b
CM
678 dump_object_info(object);
679 kmem_cache_free(scan_area_cache, area);
680 goto out_unlock;
681 }
682
683 INIT_HLIST_NODE(&area->node);
684 area->offset = offset;
685 area->length = length;
686
687 hlist_add_head(&area->node, &object->area_list);
688out_unlock:
689 spin_unlock_irqrestore(&object->lock, flags);
690out:
691 put_object(object);
692}
693
694/*
695 * Set the OBJECT_NO_SCAN flag for the object corresponding to the give
696 * pointer. Such object will not be scanned by kmemleak but references to it
697 * are searched.
698 */
699static void object_no_scan(unsigned long ptr)
700{
701 unsigned long flags;
702 struct kmemleak_object *object;
703
704 object = find_and_get_object(ptr, 0);
705 if (!object) {
ae281064 706 kmemleak_warn("Not scanning unknown object at 0x%08lx\n", ptr);
3c7b4e6b
CM
707 return;
708 }
709
710 spin_lock_irqsave(&object->lock, flags);
711 object->flags |= OBJECT_NO_SCAN;
712 spin_unlock_irqrestore(&object->lock, flags);
713 put_object(object);
714}
715
716/*
717 * Log an early kmemleak_* call to the early_log buffer. These calls will be
718 * processed later once kmemleak is fully initialized.
719 */
720static void log_early(int op_type, const void *ptr, size_t size,
721 int min_count, unsigned long offset, size_t length)
722{
723 unsigned long flags;
724 struct early_log *log;
725
726 if (crt_early_log >= ARRAY_SIZE(early_log)) {
a9d9058a
CM
727 pr_warning("Early log buffer exceeded\n");
728 kmemleak_disable();
3c7b4e6b
CM
729 return;
730 }
731
732 /*
733 * There is no need for locking since the kernel is still in UP mode
734 * at this stage. Disabling the IRQs is enough.
735 */
736 local_irq_save(flags);
737 log = &early_log[crt_early_log];
738 log->op_type = op_type;
739 log->ptr = ptr;
740 log->size = size;
741 log->min_count = min_count;
742 log->offset = offset;
743 log->length = length;
744 crt_early_log++;
745 local_irq_restore(flags);
746}
747
748/*
749 * Memory allocation function callback. This function is called from the
750 * kernel allocators when a new block is allocated (kmem_cache_alloc, kmalloc,
751 * vmalloc etc.).
752 */
753void kmemleak_alloc(const void *ptr, size_t size, int min_count, gfp_t gfp)
754{
755 pr_debug("%s(0x%p, %zu, %d)\n", __func__, ptr, size, min_count);
756
757 if (atomic_read(&kmemleak_enabled) && ptr && !IS_ERR(ptr))
758 create_object((unsigned long)ptr, size, min_count, gfp);
759 else if (atomic_read(&kmemleak_early_log))
760 log_early(KMEMLEAK_ALLOC, ptr, size, min_count, 0, 0);
761}
762EXPORT_SYMBOL_GPL(kmemleak_alloc);
763
764/*
765 * Memory freeing function callback. This function is called from the kernel
766 * allocators when a block is freed (kmem_cache_free, kfree, vfree etc.).
767 */
768void kmemleak_free(const void *ptr)
769{
770 pr_debug("%s(0x%p)\n", __func__, ptr);
771
772 if (atomic_read(&kmemleak_enabled) && ptr && !IS_ERR(ptr))
53238a60 773 delete_object_full((unsigned long)ptr);
3c7b4e6b
CM
774 else if (atomic_read(&kmemleak_early_log))
775 log_early(KMEMLEAK_FREE, ptr, 0, 0, 0, 0);
776}
777EXPORT_SYMBOL_GPL(kmemleak_free);
778
53238a60
CM
779/*
780 * Partial memory freeing function callback. This function is usually called
781 * from bootmem allocator when (part of) a memory block is freed.
782 */
783void kmemleak_free_part(const void *ptr, size_t size)
784{
785 pr_debug("%s(0x%p)\n", __func__, ptr);
786
787 if (atomic_read(&kmemleak_enabled) && ptr && !IS_ERR(ptr))
788 delete_object_part((unsigned long)ptr, size);
789 else if (atomic_read(&kmemleak_early_log))
790 log_early(KMEMLEAK_FREE_PART, ptr, size, 0, 0, 0);
791}
792EXPORT_SYMBOL_GPL(kmemleak_free_part);
793
3c7b4e6b
CM
794/*
795 * Mark an already allocated memory block as a false positive. This will cause
796 * the block to no longer be reported as leak and always be scanned.
797 */
798void kmemleak_not_leak(const void *ptr)
799{
800 pr_debug("%s(0x%p)\n", __func__, ptr);
801
802 if (atomic_read(&kmemleak_enabled) && ptr && !IS_ERR(ptr))
803 make_gray_object((unsigned long)ptr);
804 else if (atomic_read(&kmemleak_early_log))
805 log_early(KMEMLEAK_NOT_LEAK, ptr, 0, 0, 0, 0);
806}
807EXPORT_SYMBOL(kmemleak_not_leak);
808
809/*
810 * Ignore a memory block. This is usually done when it is known that the
811 * corresponding block is not a leak and does not contain any references to
812 * other allocated memory blocks.
813 */
814void kmemleak_ignore(const void *ptr)
815{
816 pr_debug("%s(0x%p)\n", __func__, ptr);
817
818 if (atomic_read(&kmemleak_enabled) && ptr && !IS_ERR(ptr))
819 make_black_object((unsigned long)ptr);
820 else if (atomic_read(&kmemleak_early_log))
821 log_early(KMEMLEAK_IGNORE, ptr, 0, 0, 0, 0);
822}
823EXPORT_SYMBOL(kmemleak_ignore);
824
825/*
826 * Limit the range to be scanned in an allocated memory block.
827 */
828void kmemleak_scan_area(const void *ptr, unsigned long offset, size_t length,
829 gfp_t gfp)
830{
831 pr_debug("%s(0x%p)\n", __func__, ptr);
832
833 if (atomic_read(&kmemleak_enabled) && ptr && !IS_ERR(ptr))
834 add_scan_area((unsigned long)ptr, offset, length, gfp);
835 else if (atomic_read(&kmemleak_early_log))
836 log_early(KMEMLEAK_SCAN_AREA, ptr, 0, 0, offset, length);
837}
838EXPORT_SYMBOL(kmemleak_scan_area);
839
840/*
841 * Inform kmemleak not to scan the given memory block.
842 */
843void kmemleak_no_scan(const void *ptr)
844{
845 pr_debug("%s(0x%p)\n", __func__, ptr);
846
847 if (atomic_read(&kmemleak_enabled) && ptr && !IS_ERR(ptr))
848 object_no_scan((unsigned long)ptr);
849 else if (atomic_read(&kmemleak_early_log))
850 log_early(KMEMLEAK_NO_SCAN, ptr, 0, 0, 0, 0);
851}
852EXPORT_SYMBOL(kmemleak_no_scan);
853
3c7b4e6b
CM
854/*
855 * Memory scanning is a long process and it needs to be interruptable. This
856 * function checks whether such interrupt condition occured.
857 */
858static int scan_should_stop(void)
859{
860 if (!atomic_read(&kmemleak_enabled))
861 return 1;
862
863 /*
864 * This function may be called from either process or kthread context,
865 * hence the need to check for both stop conditions.
866 */
867 if (current->mm)
868 return signal_pending(current);
869 else
870 return kthread_should_stop();
871
872 return 0;
873}
874
875/*
876 * Scan a memory block (exclusive range) for valid pointers and add those
877 * found to the gray list.
878 */
879static void scan_block(void *_start, void *_end,
4b8a9674 880 struct kmemleak_object *scanned, int allow_resched)
3c7b4e6b
CM
881{
882 unsigned long *ptr;
883 unsigned long *start = PTR_ALIGN(_start, BYTES_PER_POINTER);
884 unsigned long *end = _end - (BYTES_PER_POINTER - 1);
885
886 for (ptr = start; ptr < end; ptr++) {
887 unsigned long flags;
888 unsigned long pointer = *ptr;
889 struct kmemleak_object *object;
890
4b8a9674
CM
891 if (allow_resched)
892 cond_resched();
3c7b4e6b
CM
893 if (scan_should_stop())
894 break;
895
3c7b4e6b
CM
896 object = find_and_get_object(pointer, 1);
897 if (!object)
898 continue;
899 if (object == scanned) {
900 /* self referenced, ignore */
901 put_object(object);
902 continue;
903 }
904
905 /*
906 * Avoid the lockdep recursive warning on object->lock being
907 * previously acquired in scan_object(). These locks are
908 * enclosed by scan_mutex.
909 */
910 spin_lock_irqsave_nested(&object->lock, flags,
911 SINGLE_DEPTH_NESTING);
912 if (!color_white(object)) {
913 /* non-orphan, ignored or new */
914 spin_unlock_irqrestore(&object->lock, flags);
915 put_object(object);
916 continue;
917 }
918
919 /*
920 * Increase the object's reference count (number of pointers
921 * to the memory block). If this count reaches the required
922 * minimum, the object's color will become gray and it will be
923 * added to the gray_list.
924 */
925 object->count++;
926 if (color_gray(object))
927 list_add_tail(&object->gray_list, &gray_list);
928 else
929 put_object(object);
930 spin_unlock_irqrestore(&object->lock, flags);
931 }
932}
933
934/*
935 * Scan a memory block corresponding to a kmemleak_object. A condition is
936 * that object->use_count >= 1.
937 */
938static void scan_object(struct kmemleak_object *object)
939{
940 struct kmemleak_scan_area *area;
941 struct hlist_node *elem;
942 unsigned long flags;
943
944 /*
945 * Once the object->lock is aquired, the corresponding memory block
946 * cannot be freed (the same lock is aquired in delete_object).
947 */
948 spin_lock_irqsave(&object->lock, flags);
949 if (object->flags & OBJECT_NO_SCAN)
950 goto out;
951 if (!(object->flags & OBJECT_ALLOCATED))
952 /* already freed object */
953 goto out;
af98603d
CM
954 if (hlist_empty(&object->area_list)) {
955 void *start = (void *)object->pointer;
956 void *end = (void *)(object->pointer + object->size);
957
958 while (start < end && (object->flags & OBJECT_ALLOCATED) &&
959 !(object->flags & OBJECT_NO_SCAN)) {
960 scan_block(start, min(start + MAX_SCAN_SIZE, end),
961 object, 0);
962 start += MAX_SCAN_SIZE;
963
964 spin_unlock_irqrestore(&object->lock, flags);
965 cond_resched();
966 spin_lock_irqsave(&object->lock, flags);
967 }
968 } else
3c7b4e6b
CM
969 hlist_for_each_entry(area, elem, &object->area_list, node)
970 scan_block((void *)(object->pointer + area->offset),
971 (void *)(object->pointer + area->offset
4b8a9674 972 + area->length), object, 0);
3c7b4e6b
CM
973out:
974 spin_unlock_irqrestore(&object->lock, flags);
975}
976
977/*
978 * Scan data sections and all the referenced memory blocks allocated via the
979 * kernel's standard allocators. This function must be called with the
980 * scan_mutex held.
981 */
982static void kmemleak_scan(void)
983{
984 unsigned long flags;
985 struct kmemleak_object *object, *tmp;
986 struct task_struct *task;
987 int i;
4698c1f2 988 int new_leaks = 0;
2587362e 989 int gray_list_pass = 0;
3c7b4e6b 990
acf4968e
CM
991 jiffies_last_scan = jiffies;
992
3c7b4e6b
CM
993 /* prepare the kmemleak_object's */
994 rcu_read_lock();
995 list_for_each_entry_rcu(object, &object_list, object_list) {
996 spin_lock_irqsave(&object->lock, flags);
997#ifdef DEBUG
998 /*
999 * With a few exceptions there should be a maximum of
1000 * 1 reference to any object at this point.
1001 */
1002 if (atomic_read(&object->use_count) > 1) {
ae281064 1003 pr_debug("object->use_count = %d\n",
3c7b4e6b
CM
1004 atomic_read(&object->use_count));
1005 dump_object_info(object);
1006 }
1007#endif
1008 /* reset the reference count (whiten the object) */
1009 object->count = 0;
2587362e 1010 object->flags &= ~OBJECT_NEW;
3c7b4e6b
CM
1011 if (color_gray(object) && get_object(object))
1012 list_add_tail(&object->gray_list, &gray_list);
1013
1014 spin_unlock_irqrestore(&object->lock, flags);
1015 }
1016 rcu_read_unlock();
1017
1018 /* data/bss scanning */
4b8a9674
CM
1019 scan_block(_sdata, _edata, NULL, 1);
1020 scan_block(__bss_start, __bss_stop, NULL, 1);
3c7b4e6b
CM
1021
1022#ifdef CONFIG_SMP
1023 /* per-cpu sections scanning */
1024 for_each_possible_cpu(i)
1025 scan_block(__per_cpu_start + per_cpu_offset(i),
4b8a9674 1026 __per_cpu_end + per_cpu_offset(i), NULL, 1);
3c7b4e6b
CM
1027#endif
1028
1029 /*
1030 * Struct page scanning for each node. The code below is not yet safe
1031 * with MEMORY_HOTPLUG.
1032 */
1033 for_each_online_node(i) {
1034 pg_data_t *pgdat = NODE_DATA(i);
1035 unsigned long start_pfn = pgdat->node_start_pfn;
1036 unsigned long end_pfn = start_pfn + pgdat->node_spanned_pages;
1037 unsigned long pfn;
1038
1039 for (pfn = start_pfn; pfn < end_pfn; pfn++) {
1040 struct page *page;
1041
1042 if (!pfn_valid(pfn))
1043 continue;
1044 page = pfn_to_page(pfn);
1045 /* only scan if page is in use */
1046 if (page_count(page) == 0)
1047 continue;
4b8a9674 1048 scan_block(page, page + 1, NULL, 1);
3c7b4e6b
CM
1049 }
1050 }
1051
1052 /*
1053 * Scanning the task stacks may introduce false negatives and it is
1054 * not enabled by default.
1055 */
1056 if (kmemleak_stack_scan) {
1057 read_lock(&tasklist_lock);
1058 for_each_process(task)
1059 scan_block(task_stack_page(task),
4b8a9674
CM
1060 task_stack_page(task) + THREAD_SIZE,
1061 NULL, 0);
3c7b4e6b
CM
1062 read_unlock(&tasklist_lock);
1063 }
1064
1065 /*
1066 * Scan the objects already referenced from the sections scanned
1067 * above. More objects will be referenced and, if there are no memory
1068 * leaks, all the objects will be scanned. The list traversal is safe
1069 * for both tail additions and removals from inside the loop. The
1070 * kmemleak objects cannot be freed from outside the loop because their
1071 * use_count was increased.
1072 */
2587362e 1073repeat:
3c7b4e6b
CM
1074 object = list_entry(gray_list.next, typeof(*object), gray_list);
1075 while (&object->gray_list != &gray_list) {
57d81f6f 1076 cond_resched();
3c7b4e6b
CM
1077
1078 /* may add new objects to the list */
1079 if (!scan_should_stop())
1080 scan_object(object);
1081
1082 tmp = list_entry(object->gray_list.next, typeof(*object),
1083 gray_list);
1084
1085 /* remove the object from the list and release it */
1086 list_del(&object->gray_list);
1087 put_object(object);
1088
1089 object = tmp;
1090 }
2587362e
CM
1091
1092 if (scan_should_stop() || ++gray_list_pass >= GRAY_LIST_PASSES)
1093 goto scan_end;
1094
1095 /*
1096 * Check for new objects allocated during this scanning and add them
1097 * to the gray list.
1098 */
1099 rcu_read_lock();
1100 list_for_each_entry_rcu(object, &object_list, object_list) {
1101 spin_lock_irqsave(&object->lock, flags);
1102 if ((object->flags & OBJECT_NEW) && !color_black(object) &&
1103 get_object(object)) {
1104 object->flags &= ~OBJECT_NEW;
1105 list_add_tail(&object->gray_list, &gray_list);
1106 }
1107 spin_unlock_irqrestore(&object->lock, flags);
1108 }
1109 rcu_read_unlock();
1110
1111 if (!list_empty(&gray_list))
1112 goto repeat;
1113
1114scan_end:
3c7b4e6b 1115 WARN_ON(!list_empty(&gray_list));
4698c1f2 1116
17bb9e0d 1117 /*
2587362e
CM
1118 * If scanning was stopped or new objects were being allocated at a
1119 * higher rate than gray list scanning, do not report any new
1120 * unreferenced objects.
17bb9e0d 1121 */
2587362e 1122 if (scan_should_stop() || gray_list_pass >= GRAY_LIST_PASSES)
17bb9e0d
CM
1123 return;
1124
4698c1f2
CM
1125 /*
1126 * Scanning result reporting.
1127 */
1128 rcu_read_lock();
1129 list_for_each_entry_rcu(object, &object_list, object_list) {
1130 spin_lock_irqsave(&object->lock, flags);
1131 if (unreferenced_object(object) &&
1132 !(object->flags & OBJECT_REPORTED)) {
1133 object->flags |= OBJECT_REPORTED;
1134 new_leaks++;
1135 }
1136 spin_unlock_irqrestore(&object->lock, flags);
1137 }
1138 rcu_read_unlock();
1139
1140 if (new_leaks)
1141 pr_info("%d new suspected memory leaks (see "
1142 "/sys/kernel/debug/kmemleak)\n", new_leaks);
1143
3c7b4e6b
CM
1144}
1145
1146/*
1147 * Thread function performing automatic memory scanning. Unreferenced objects
1148 * at the end of a memory scan are reported but only the first time.
1149 */
1150static int kmemleak_scan_thread(void *arg)
1151{
1152 static int first_run = 1;
1153
ae281064 1154 pr_info("Automatic memory scanning thread started\n");
bf2a76b3 1155 set_user_nice(current, 10);
3c7b4e6b
CM
1156
1157 /*
1158 * Wait before the first scan to allow the system to fully initialize.
1159 */
1160 if (first_run) {
1161 first_run = 0;
1162 ssleep(SECS_FIRST_SCAN);
1163 }
1164
1165 while (!kthread_should_stop()) {
3c7b4e6b
CM
1166 signed long timeout = jiffies_scan_wait;
1167
1168 mutex_lock(&scan_mutex);
3c7b4e6b 1169 kmemleak_scan();
3c7b4e6b 1170 mutex_unlock(&scan_mutex);
4698c1f2 1171
3c7b4e6b
CM
1172 /* wait before the next scan */
1173 while (timeout && !kthread_should_stop())
1174 timeout = schedule_timeout_interruptible(timeout);
1175 }
1176
ae281064 1177 pr_info("Automatic memory scanning thread ended\n");
3c7b4e6b
CM
1178
1179 return 0;
1180}
1181
1182/*
1183 * Start the automatic memory scanning thread. This function must be called
4698c1f2 1184 * with the scan_mutex held.
3c7b4e6b
CM
1185 */
1186void start_scan_thread(void)
1187{
1188 if (scan_thread)
1189 return;
1190 scan_thread = kthread_run(kmemleak_scan_thread, NULL, "kmemleak");
1191 if (IS_ERR(scan_thread)) {
ae281064 1192 pr_warning("Failed to create the scan thread\n");
3c7b4e6b
CM
1193 scan_thread = NULL;
1194 }
1195}
1196
1197/*
1198 * Stop the automatic memory scanning thread. This function must be called
4698c1f2 1199 * with the scan_mutex held.
3c7b4e6b
CM
1200 */
1201void stop_scan_thread(void)
1202{
1203 if (scan_thread) {
1204 kthread_stop(scan_thread);
1205 scan_thread = NULL;
1206 }
1207}
1208
1209/*
1210 * Iterate over the object_list and return the first valid object at or after
1211 * the required position with its use_count incremented. The function triggers
1212 * a memory scanning when the pos argument points to the first position.
1213 */
1214static void *kmemleak_seq_start(struct seq_file *seq, loff_t *pos)
1215{
1216 struct kmemleak_object *object;
1217 loff_t n = *pos;
b87324d0
CM
1218 int err;
1219
1220 err = mutex_lock_interruptible(&scan_mutex);
1221 if (err < 0)
1222 return ERR_PTR(err);
3c7b4e6b 1223
3c7b4e6b
CM
1224 rcu_read_lock();
1225 list_for_each_entry_rcu(object, &object_list, object_list) {
1226 if (n-- > 0)
1227 continue;
1228 if (get_object(object))
1229 goto out;
1230 }
1231 object = NULL;
1232out:
3c7b4e6b
CM
1233 return object;
1234}
1235
1236/*
1237 * Return the next object in the object_list. The function decrements the
1238 * use_count of the previous object and increases that of the next one.
1239 */
1240static void *kmemleak_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1241{
1242 struct kmemleak_object *prev_obj = v;
1243 struct kmemleak_object *next_obj = NULL;
1244 struct list_head *n = &prev_obj->object_list;
1245
1246 ++(*pos);
3c7b4e6b 1247
3c7b4e6b
CM
1248 list_for_each_continue_rcu(n, &object_list) {
1249 next_obj = list_entry(n, struct kmemleak_object, object_list);
1250 if (get_object(next_obj))
1251 break;
1252 }
288c857d 1253
3c7b4e6b
CM
1254 put_object(prev_obj);
1255 return next_obj;
1256}
1257
1258/*
1259 * Decrement the use_count of the last object required, if any.
1260 */
1261static void kmemleak_seq_stop(struct seq_file *seq, void *v)
1262{
b87324d0
CM
1263 if (!IS_ERR(v)) {
1264 /*
1265 * kmemleak_seq_start may return ERR_PTR if the scan_mutex
1266 * waiting was interrupted, so only release it if !IS_ERR.
1267 */
f5886c7f 1268 rcu_read_unlock();
b87324d0
CM
1269 mutex_unlock(&scan_mutex);
1270 if (v)
1271 put_object(v);
1272 }
3c7b4e6b
CM
1273}
1274
1275/*
1276 * Print the information for an unreferenced object to the seq file.
1277 */
1278static int kmemleak_seq_show(struct seq_file *seq, void *v)
1279{
1280 struct kmemleak_object *object = v;
1281 unsigned long flags;
1282
1283 spin_lock_irqsave(&object->lock, flags);
288c857d 1284 if ((object->flags & OBJECT_REPORTED) && unreferenced_object(object))
17bb9e0d 1285 print_unreferenced(seq, object);
3c7b4e6b
CM
1286 spin_unlock_irqrestore(&object->lock, flags);
1287 return 0;
1288}
1289
1290static const struct seq_operations kmemleak_seq_ops = {
1291 .start = kmemleak_seq_start,
1292 .next = kmemleak_seq_next,
1293 .stop = kmemleak_seq_stop,
1294 .show = kmemleak_seq_show,
1295};
1296
1297static int kmemleak_open(struct inode *inode, struct file *file)
1298{
3c7b4e6b
CM
1299 if (!atomic_read(&kmemleak_enabled))
1300 return -EBUSY;
1301
b87324d0 1302 return seq_open(file, &kmemleak_seq_ops);
3c7b4e6b
CM
1303}
1304
1305static int kmemleak_release(struct inode *inode, struct file *file)
1306{
b87324d0 1307 return seq_release(inode, file);
3c7b4e6b
CM
1308}
1309
1310/*
1311 * File write operation to configure kmemleak at run-time. The following
1312 * commands can be written to the /sys/kernel/debug/kmemleak file:
1313 * off - disable kmemleak (irreversible)
1314 * stack=on - enable the task stacks scanning
1315 * stack=off - disable the tasks stacks scanning
1316 * scan=on - start the automatic memory scanning thread
1317 * scan=off - stop the automatic memory scanning thread
1318 * scan=... - set the automatic memory scanning period in seconds (0 to
1319 * disable it)
4698c1f2 1320 * scan - trigger a memory scan
3c7b4e6b
CM
1321 */
1322static ssize_t kmemleak_write(struct file *file, const char __user *user_buf,
1323 size_t size, loff_t *ppos)
1324{
1325 char buf[64];
1326 int buf_size;
b87324d0 1327 int ret;
3c7b4e6b
CM
1328
1329 buf_size = min(size, (sizeof(buf) - 1));
1330 if (strncpy_from_user(buf, user_buf, buf_size) < 0)
1331 return -EFAULT;
1332 buf[buf_size] = 0;
1333
b87324d0
CM
1334 ret = mutex_lock_interruptible(&scan_mutex);
1335 if (ret < 0)
1336 return ret;
1337
3c7b4e6b
CM
1338 if (strncmp(buf, "off", 3) == 0)
1339 kmemleak_disable();
1340 else if (strncmp(buf, "stack=on", 8) == 0)
1341 kmemleak_stack_scan = 1;
1342 else if (strncmp(buf, "stack=off", 9) == 0)
1343 kmemleak_stack_scan = 0;
1344 else if (strncmp(buf, "scan=on", 7) == 0)
1345 start_scan_thread();
1346 else if (strncmp(buf, "scan=off", 8) == 0)
1347 stop_scan_thread();
1348 else if (strncmp(buf, "scan=", 5) == 0) {
1349 unsigned long secs;
3c7b4e6b 1350
b87324d0
CM
1351 ret = strict_strtoul(buf + 5, 0, &secs);
1352 if (ret < 0)
1353 goto out;
3c7b4e6b
CM
1354 stop_scan_thread();
1355 if (secs) {
1356 jiffies_scan_wait = msecs_to_jiffies(secs * 1000);
1357 start_scan_thread();
1358 }
4698c1f2
CM
1359 } else if (strncmp(buf, "scan", 4) == 0)
1360 kmemleak_scan();
1361 else
b87324d0
CM
1362 ret = -EINVAL;
1363
1364out:
1365 mutex_unlock(&scan_mutex);
1366 if (ret < 0)
1367 return ret;
3c7b4e6b
CM
1368
1369 /* ignore the rest of the buffer, only one command at a time */
1370 *ppos += size;
1371 return size;
1372}
1373
1374static const struct file_operations kmemleak_fops = {
1375 .owner = THIS_MODULE,
1376 .open = kmemleak_open,
1377 .read = seq_read,
1378 .write = kmemleak_write,
1379 .llseek = seq_lseek,
1380 .release = kmemleak_release,
1381};
1382
1383/*
1384 * Perform the freeing of the kmemleak internal objects after waiting for any
1385 * current memory scan to complete.
1386 */
1387static int kmemleak_cleanup_thread(void *arg)
1388{
1389 struct kmemleak_object *object;
1390
4698c1f2 1391 mutex_lock(&scan_mutex);
3c7b4e6b 1392 stop_scan_thread();
3c7b4e6b 1393
3c7b4e6b
CM
1394 rcu_read_lock();
1395 list_for_each_entry_rcu(object, &object_list, object_list)
53238a60 1396 delete_object_full(object->pointer);
3c7b4e6b
CM
1397 rcu_read_unlock();
1398 mutex_unlock(&scan_mutex);
1399
1400 return 0;
1401}
1402
1403/*
1404 * Start the clean-up thread.
1405 */
1406static void kmemleak_cleanup(void)
1407{
1408 struct task_struct *cleanup_thread;
1409
1410 cleanup_thread = kthread_run(kmemleak_cleanup_thread, NULL,
1411 "kmemleak-clean");
1412 if (IS_ERR(cleanup_thread))
ae281064 1413 pr_warning("Failed to create the clean-up thread\n");
3c7b4e6b
CM
1414}
1415
1416/*
1417 * Disable kmemleak. No memory allocation/freeing will be traced once this
1418 * function is called. Disabling kmemleak is an irreversible operation.
1419 */
1420static void kmemleak_disable(void)
1421{
1422 /* atomically check whether it was already invoked */
1423 if (atomic_cmpxchg(&kmemleak_error, 0, 1))
1424 return;
1425
1426 /* stop any memory operation tracing */
1427 atomic_set(&kmemleak_early_log, 0);
1428 atomic_set(&kmemleak_enabled, 0);
1429
1430 /* check whether it is too early for a kernel thread */
1431 if (atomic_read(&kmemleak_initialized))
1432 kmemleak_cleanup();
1433
1434 pr_info("Kernel memory leak detector disabled\n");
1435}
1436
1437/*
1438 * Allow boot-time kmemleak disabling (enabled by default).
1439 */
1440static int kmemleak_boot_config(char *str)
1441{
1442 if (!str)
1443 return -EINVAL;
1444 if (strcmp(str, "off") == 0)
1445 kmemleak_disable();
1446 else if (strcmp(str, "on") != 0)
1447 return -EINVAL;
1448 return 0;
1449}
1450early_param("kmemleak", kmemleak_boot_config);
1451
1452/*
2030117d 1453 * Kmemleak initialization.
3c7b4e6b
CM
1454 */
1455void __init kmemleak_init(void)
1456{
1457 int i;
1458 unsigned long flags;
1459
3c7b4e6b
CM
1460 jiffies_min_age = msecs_to_jiffies(MSECS_MIN_AGE);
1461 jiffies_scan_wait = msecs_to_jiffies(SECS_SCAN_WAIT * 1000);
1462
1463 object_cache = KMEM_CACHE(kmemleak_object, SLAB_NOLEAKTRACE);
1464 scan_area_cache = KMEM_CACHE(kmemleak_scan_area, SLAB_NOLEAKTRACE);
1465 INIT_PRIO_TREE_ROOT(&object_tree_root);
1466
1467 /* the kernel is still in UP mode, so disabling the IRQs is enough */
1468 local_irq_save(flags);
1469 if (!atomic_read(&kmemleak_error)) {
1470 atomic_set(&kmemleak_enabled, 1);
1471 atomic_set(&kmemleak_early_log, 0);
1472 }
1473 local_irq_restore(flags);
1474
1475 /*
1476 * This is the point where tracking allocations is safe. Automatic
1477 * scanning is started during the late initcall. Add the early logged
1478 * callbacks to the kmemleak infrastructure.
1479 */
1480 for (i = 0; i < crt_early_log; i++) {
1481 struct early_log *log = &early_log[i];
1482
1483 switch (log->op_type) {
1484 case KMEMLEAK_ALLOC:
1485 kmemleak_alloc(log->ptr, log->size, log->min_count,
1486 GFP_KERNEL);
1487 break;
1488 case KMEMLEAK_FREE:
1489 kmemleak_free(log->ptr);
1490 break;
53238a60
CM
1491 case KMEMLEAK_FREE_PART:
1492 kmemleak_free_part(log->ptr, log->size);
1493 break;
3c7b4e6b
CM
1494 case KMEMLEAK_NOT_LEAK:
1495 kmemleak_not_leak(log->ptr);
1496 break;
1497 case KMEMLEAK_IGNORE:
1498 kmemleak_ignore(log->ptr);
1499 break;
1500 case KMEMLEAK_SCAN_AREA:
1501 kmemleak_scan_area(log->ptr, log->offset, log->length,
1502 GFP_KERNEL);
1503 break;
1504 case KMEMLEAK_NO_SCAN:
1505 kmemleak_no_scan(log->ptr);
1506 break;
1507 default:
1508 WARN_ON(1);
1509 }
1510 }
1511}
1512
1513/*
1514 * Late initialization function.
1515 */
1516static int __init kmemleak_late_init(void)
1517{
1518 struct dentry *dentry;
1519
1520 atomic_set(&kmemleak_initialized, 1);
1521
1522 if (atomic_read(&kmemleak_error)) {
1523 /*
1524 * Some error occured and kmemleak was disabled. There is a
1525 * small chance that kmemleak_disable() was called immediately
1526 * after setting kmemleak_initialized and we may end up with
1527 * two clean-up threads but serialized by scan_mutex.
1528 */
1529 kmemleak_cleanup();
1530 return -ENOMEM;
1531 }
1532
1533 dentry = debugfs_create_file("kmemleak", S_IRUGO, NULL, NULL,
1534 &kmemleak_fops);
1535 if (!dentry)
ae281064 1536 pr_warning("Failed to create the debugfs kmemleak file\n");
4698c1f2 1537 mutex_lock(&scan_mutex);
3c7b4e6b 1538 start_scan_thread();
4698c1f2 1539 mutex_unlock(&scan_mutex);
3c7b4e6b
CM
1540
1541 pr_info("Kernel memory leak detector initialized\n");
1542
1543 return 0;
1544}
1545late_initcall(kmemleak_late_init);