4 * Copyright (C) 2008 ARM Limited
5 * Written by Catalin Marinas <catalin.marinas@arm.com>
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.
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.
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
21 * For more information on the algorithm and kmemleak usage, please see
22 * Documentation/dev-tools/kmemleak.rst.
27 * The following locks and mutexes are used by kmemleak:
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 red black 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
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
56 * Locks and mutexes are acquired/nested in the following order:
58 * scan_mutex [-> object->lock] -> kmemleak_lock -> other_object->lock (SINGLE_DEPTH_NESTING)
60 * No kmemleak_lock and object->lock nesting is allowed outside scan_mutex
63 * The kmemleak_object structures have a use_count incremented or decremented
64 * using the get_object()/put_object() functions. When the use_count becomes
65 * 0, this count can no longer be incremented and put_object() schedules the
66 * kmemleak_object freeing via an RCU callback. All calls to the get_object()
67 * function must be protected by rcu_read_lock() to avoid accessing a freed
71 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
73 #include <linux/init.h>
74 #include <linux/kernel.h>
75 #include <linux/list.h>
76 #include <linux/sched/signal.h>
77 #include <linux/sched/task.h>
78 #include <linux/sched/task_stack.h>
79 #include <linux/jiffies.h>
80 #include <linux/delay.h>
81 #include <linux/export.h>
82 #include <linux/kthread.h>
83 #include <linux/rbtree.h>
85 #include <linux/debugfs.h>
86 #include <linux/seq_file.h>
87 #include <linux/cpumask.h>
88 #include <linux/spinlock.h>
89 #include <linux/mutex.h>
90 #include <linux/rcupdate.h>
91 #include <linux/stacktrace.h>
92 #include <linux/cache.h>
93 #include <linux/percpu.h>
94 #include <linux/hardirq.h>
95 #include <linux/bootmem.h>
96 #include <linux/pfn.h>
97 #include <linux/mmzone.h>
98 #include <linux/slab.h>
99 #include <linux/thread_info.h>
100 #include <linux/err.h>
101 #include <linux/uaccess.h>
102 #include <linux/string.h>
103 #include <linux/nodemask.h>
104 #include <linux/mm.h>
105 #include <linux/workqueue.h>
106 #include <linux/crc32.h>
108 #include <asm/sections.h>
109 #include <asm/processor.h>
110 #include <linux/atomic.h>
112 #include <linux/kasan.h>
113 #include <linux/kmemcheck.h>
114 #include <linux/kmemleak.h>
115 #include <linux/memory_hotplug.h>
118 * Kmemleak configuration and common defines.
120 #define MAX_TRACE 16 /* stack trace length */
121 #define MSECS_MIN_AGE 5000 /* minimum object age for reporting */
122 #define SECS_FIRST_SCAN 60 /* delay before the first scan */
123 #define SECS_SCAN_WAIT 600 /* subsequent auto scanning delay */
124 #define MAX_SCAN_SIZE 4096 /* maximum size of a scanned block */
126 #define BYTES_PER_POINTER sizeof(void *)
128 /* GFP bitmask for kmemleak internal allocations */
129 #define gfp_kmemleak_mask(gfp) (((gfp) & (GFP_KERNEL | GFP_ATOMIC)) | \
130 __GFP_NORETRY | __GFP_NOMEMALLOC | \
133 /* scanning area inside a memory block */
134 struct kmemleak_scan_area
{
135 struct hlist_node node
;
140 #define KMEMLEAK_GREY 0
141 #define KMEMLEAK_BLACK -1
144 * Structure holding the metadata for each allocated memory block.
145 * Modifications to such objects should be made while holding the
146 * object->lock. Insertions or deletions from object_list, gray_list or
147 * rb_node are already protected by the corresponding locks or mutex (see
148 * the notes on locking above). These objects are reference-counted
149 * (use_count) and freed using the RCU mechanism.
151 struct kmemleak_object
{
153 unsigned int flags
; /* object status flags */
154 struct list_head object_list
;
155 struct list_head gray_list
;
156 struct rb_node rb_node
;
157 struct rcu_head rcu
; /* object_list lockless traversal */
158 /* object usage count; object freed when use_count == 0 */
160 unsigned long pointer
;
162 /* minimum number of a pointers found before it is considered leak */
164 /* the total number of pointers found pointing to this object */
166 /* checksum for detecting modified objects */
168 /* memory ranges to be scanned inside an object (empty for all) */
169 struct hlist_head area_list
;
170 unsigned long trace
[MAX_TRACE
];
171 unsigned int trace_len
;
172 unsigned long jiffies
; /* creation timestamp */
173 pid_t pid
; /* pid of the current task */
174 char comm
[TASK_COMM_LEN
]; /* executable name */
177 /* flag representing the memory block allocation status */
178 #define OBJECT_ALLOCATED (1 << 0)
179 /* flag set after the first reporting of an unreference object */
180 #define OBJECT_REPORTED (1 << 1)
181 /* flag set to not scan the object */
182 #define OBJECT_NO_SCAN (1 << 2)
184 /* number of bytes to print per line; must be 16 or 32 */
185 #define HEX_ROW_SIZE 16
186 /* number of bytes to print at a time (1, 2, 4, 8) */
187 #define HEX_GROUP_SIZE 1
188 /* include ASCII after the hex output */
190 /* max number of lines to be printed */
191 #define HEX_MAX_LINES 2
193 /* the list of all allocated objects */
194 static LIST_HEAD(object_list
);
195 /* the list of gray-colored objects (see color_gray comment below) */
196 static LIST_HEAD(gray_list
);
197 /* search tree for object boundaries */
198 static struct rb_root object_tree_root
= RB_ROOT
;
199 /* rw_lock protecting the access to object_list and object_tree_root */
200 static DEFINE_RWLOCK(kmemleak_lock
);
202 /* allocation caches for kmemleak internal data */
203 static struct kmem_cache
*object_cache
;
204 static struct kmem_cache
*scan_area_cache
;
206 /* set if tracing memory operations is enabled */
207 static int kmemleak_enabled
;
208 /* same as above but only for the kmemleak_free() callback */
209 static int kmemleak_free_enabled
;
210 /* set in the late_initcall if there were no errors */
211 static int kmemleak_initialized
;
212 /* enables or disables early logging of the memory operations */
213 static int kmemleak_early_log
= 1;
214 /* set if a kmemleak warning was issued */
215 static int kmemleak_warning
;
216 /* set if a fatal kmemleak error has occurred */
217 static int kmemleak_error
;
219 /* minimum and maximum address that may be valid pointers */
220 static unsigned long min_addr
= ULONG_MAX
;
221 static unsigned long max_addr
;
223 static struct task_struct
*scan_thread
;
224 /* used to avoid reporting of recently allocated objects */
225 static unsigned long jiffies_min_age
;
226 static unsigned long jiffies_last_scan
;
227 /* delay between automatic memory scannings */
228 static signed long jiffies_scan_wait
;
229 /* enables or disables the task stacks scanning */
230 static int kmemleak_stack_scan
= 1;
231 /* protects the memory scanning, parameters and debug/kmemleak file access */
232 static DEFINE_MUTEX(scan_mutex
);
233 /* setting kmemleak=on, will set this var, skipping the disable */
234 static int kmemleak_skip_disable
;
235 /* If there are leaks that can be reported */
236 static bool kmemleak_found_leaks
;
239 * Early object allocation/freeing logging. Kmemleak is initialized after the
240 * kernel allocator. However, both the kernel allocator and kmemleak may
241 * allocate memory blocks which need to be tracked. Kmemleak defines an
242 * arbitrary buffer to hold the allocation/freeing information before it is
246 /* kmemleak operation type for early logging */
249 KMEMLEAK_ALLOC_PERCPU
,
252 KMEMLEAK_FREE_PERCPU
,
260 * Structure holding the information passed to kmemleak callbacks during the
264 int op_type
; /* kmemleak operation type */
265 int min_count
; /* minimum reference count */
266 const void *ptr
; /* allocated/freed memory block */
267 size_t size
; /* memory block size */
268 unsigned long trace
[MAX_TRACE
]; /* stack trace */
269 unsigned int trace_len
; /* stack trace length */
272 /* early logging buffer and current position */
273 static struct early_log
274 early_log
[CONFIG_DEBUG_KMEMLEAK_EARLY_LOG_SIZE
] __initdata
;
275 static int crt_early_log __initdata
;
277 static void kmemleak_disable(void);
280 * Print a warning and dump the stack trace.
282 #define kmemleak_warn(x...) do { \
285 kmemleak_warning = 1; \
289 * Macro invoked when a serious kmemleak condition occurred and cannot be
290 * recovered from. Kmemleak will be disabled and further allocation/freeing
291 * tracing no longer available.
293 #define kmemleak_stop(x...) do { \
295 kmemleak_disable(); \
299 * Printing of the objects hex dump to the seq file. The number of lines to be
300 * printed is limited to HEX_MAX_LINES to prevent seq file spamming. The
301 * actual number of printed bytes depends on HEX_ROW_SIZE. It must be called
302 * with the object->lock held.
304 static void hex_dump_object(struct seq_file
*seq
,
305 struct kmemleak_object
*object
)
307 const u8
*ptr
= (const u8
*)object
->pointer
;
310 /* limit the number of lines to HEX_MAX_LINES */
311 len
= min_t(size_t, object
->size
, HEX_MAX_LINES
* HEX_ROW_SIZE
);
313 seq_printf(seq
, " hex dump (first %zu bytes):\n", len
);
314 kasan_disable_current();
315 seq_hex_dump(seq
, " ", DUMP_PREFIX_NONE
, HEX_ROW_SIZE
,
316 HEX_GROUP_SIZE
, ptr
, len
, HEX_ASCII
);
317 kasan_enable_current();
321 * Object colors, encoded with count and min_count:
322 * - white - orphan object, not enough references to it (count < min_count)
323 * - gray - not orphan, not marked as false positive (min_count == 0) or
324 * sufficient references to it (count >= min_count)
325 * - black - ignore, it doesn't contain references (e.g. text section)
326 * (min_count == -1). No function defined for this color.
327 * Newly created objects don't have any color assigned (object->count == -1)
328 * before the next memory scan when they become white.
330 static bool color_white(const struct kmemleak_object
*object
)
332 return object
->count
!= KMEMLEAK_BLACK
&&
333 object
->count
< object
->min_count
;
336 static bool color_gray(const struct kmemleak_object
*object
)
338 return object
->min_count
!= KMEMLEAK_BLACK
&&
339 object
->count
>= object
->min_count
;
343 * Objects are considered unreferenced only if their color is white, they have
344 * not be deleted and have a minimum age to avoid false positives caused by
345 * pointers temporarily stored in CPU registers.
347 static bool unreferenced_object(struct kmemleak_object
*object
)
349 return (color_white(object
) && object
->flags
& OBJECT_ALLOCATED
) &&
350 time_before_eq(object
->jiffies
+ jiffies_min_age
,
355 * Printing of the unreferenced objects information to the seq file. The
356 * print_unreferenced function must be called with the object->lock held.
358 static void print_unreferenced(struct seq_file
*seq
,
359 struct kmemleak_object
*object
)
362 unsigned int msecs_age
= jiffies_to_msecs(jiffies
- object
->jiffies
);
364 seq_printf(seq
, "unreferenced object 0x%08lx (size %zu):\n",
365 object
->pointer
, object
->size
);
366 seq_printf(seq
, " comm \"%s\", pid %d, jiffies %lu (age %d.%03ds)\n",
367 object
->comm
, object
->pid
, object
->jiffies
,
368 msecs_age
/ 1000, msecs_age
% 1000);
369 hex_dump_object(seq
, object
);
370 seq_printf(seq
, " backtrace:\n");
372 for (i
= 0; i
< object
->trace_len
; i
++) {
373 void *ptr
= (void *)object
->trace
[i
];
374 seq_printf(seq
, " [<%p>] %pS\n", ptr
, ptr
);
379 * Print the kmemleak_object information. This function is used mainly for
380 * debugging special cases when kmemleak operations. It must be called with
381 * the object->lock held.
383 static void dump_object_info(struct kmemleak_object
*object
)
385 struct stack_trace trace
;
387 trace
.nr_entries
= object
->trace_len
;
388 trace
.entries
= object
->trace
;
390 pr_notice("Object 0x%08lx (size %zu):\n",
391 object
->pointer
, object
->size
);
392 pr_notice(" comm \"%s\", pid %d, jiffies %lu\n",
393 object
->comm
, object
->pid
, object
->jiffies
);
394 pr_notice(" min_count = %d\n", object
->min_count
);
395 pr_notice(" count = %d\n", object
->count
);
396 pr_notice(" flags = 0x%x\n", object
->flags
);
397 pr_notice(" checksum = %u\n", object
->checksum
);
398 pr_notice(" backtrace:\n");
399 print_stack_trace(&trace
, 4);
403 * Look-up a memory block metadata (kmemleak_object) in the object search
404 * tree based on a pointer value. If alias is 0, only values pointing to the
405 * beginning of the memory block are allowed. The kmemleak_lock must be held
406 * when calling this function.
408 static struct kmemleak_object
*lookup_object(unsigned long ptr
, int alias
)
410 struct rb_node
*rb
= object_tree_root
.rb_node
;
413 struct kmemleak_object
*object
=
414 rb_entry(rb
, struct kmemleak_object
, rb_node
);
415 if (ptr
< object
->pointer
)
416 rb
= object
->rb_node
.rb_left
;
417 else if (object
->pointer
+ object
->size
<= ptr
)
418 rb
= object
->rb_node
.rb_right
;
419 else if (object
->pointer
== ptr
|| alias
)
422 kmemleak_warn("Found object by alias at 0x%08lx\n",
424 dump_object_info(object
);
432 * Increment the object use_count. Return 1 if successful or 0 otherwise. Note
433 * that once an object's use_count reached 0, the RCU freeing was already
434 * registered and the object should no longer be used. This function must be
435 * called under the protection of rcu_read_lock().
437 static int get_object(struct kmemleak_object
*object
)
439 return atomic_inc_not_zero(&object
->use_count
);
443 * RCU callback to free a kmemleak_object.
445 static void free_object_rcu(struct rcu_head
*rcu
)
447 struct hlist_node
*tmp
;
448 struct kmemleak_scan_area
*area
;
449 struct kmemleak_object
*object
=
450 container_of(rcu
, struct kmemleak_object
, rcu
);
453 * Once use_count is 0 (guaranteed by put_object), there is no other
454 * code accessing this object, hence no need for locking.
456 hlist_for_each_entry_safe(area
, tmp
, &object
->area_list
, node
) {
457 hlist_del(&area
->node
);
458 kmem_cache_free(scan_area_cache
, area
);
460 kmem_cache_free(object_cache
, object
);
464 * Decrement the object use_count. Once the count is 0, free the object using
465 * an RCU callback. Since put_object() may be called via the kmemleak_free() ->
466 * delete_object() path, the delayed RCU freeing ensures that there is no
467 * recursive call to the kernel allocator. Lock-less RCU object_list traversal
470 static void put_object(struct kmemleak_object
*object
)
472 if (!atomic_dec_and_test(&object
->use_count
))
475 /* should only get here after delete_object was called */
476 WARN_ON(object
->flags
& OBJECT_ALLOCATED
);
478 call_rcu(&object
->rcu
, free_object_rcu
);
482 * Look up an object in the object search tree and increase its use_count.
484 static struct kmemleak_object
*find_and_get_object(unsigned long ptr
, int alias
)
487 struct kmemleak_object
*object
;
490 read_lock_irqsave(&kmemleak_lock
, flags
);
491 object
= lookup_object(ptr
, alias
);
492 read_unlock_irqrestore(&kmemleak_lock
, flags
);
494 /* check whether the object is still available */
495 if (object
&& !get_object(object
))
503 * Look up an object in the object search tree and remove it from both
504 * object_tree_root and object_list. The returned object's use_count should be
505 * at least 1, as initially set by create_object().
507 static struct kmemleak_object
*find_and_remove_object(unsigned long ptr
, int alias
)
510 struct kmemleak_object
*object
;
512 write_lock_irqsave(&kmemleak_lock
, flags
);
513 object
= lookup_object(ptr
, alias
);
515 rb_erase(&object
->rb_node
, &object_tree_root
);
516 list_del_rcu(&object
->object_list
);
518 write_unlock_irqrestore(&kmemleak_lock
, flags
);
524 * Save stack trace to the given array of MAX_TRACE size.
526 static int __save_stack_trace(unsigned long *trace
)
528 struct stack_trace stack_trace
;
530 stack_trace
.max_entries
= MAX_TRACE
;
531 stack_trace
.nr_entries
= 0;
532 stack_trace
.entries
= trace
;
533 stack_trace
.skip
= 2;
534 save_stack_trace(&stack_trace
);
536 return stack_trace
.nr_entries
;
540 * Create the metadata (struct kmemleak_object) corresponding to an allocated
541 * memory block and add it to the object_list and object_tree_root.
543 static struct kmemleak_object
*create_object(unsigned long ptr
, size_t size
,
544 int min_count
, gfp_t gfp
)
547 struct kmemleak_object
*object
, *parent
;
548 struct rb_node
**link
, *rb_parent
;
550 object
= kmem_cache_alloc(object_cache
, gfp_kmemleak_mask(gfp
));
552 pr_warn("Cannot allocate a kmemleak_object structure\n");
557 INIT_LIST_HEAD(&object
->object_list
);
558 INIT_LIST_HEAD(&object
->gray_list
);
559 INIT_HLIST_HEAD(&object
->area_list
);
560 spin_lock_init(&object
->lock
);
561 atomic_set(&object
->use_count
, 1);
562 object
->flags
= OBJECT_ALLOCATED
;
563 object
->pointer
= ptr
;
565 object
->min_count
= min_count
;
566 object
->count
= 0; /* white color initially */
567 object
->jiffies
= jiffies
;
568 object
->checksum
= 0;
570 /* task information */
573 strncpy(object
->comm
, "hardirq", sizeof(object
->comm
));
574 } else if (in_softirq()) {
576 strncpy(object
->comm
, "softirq", sizeof(object
->comm
));
578 object
->pid
= current
->pid
;
580 * There is a small chance of a race with set_task_comm(),
581 * however using get_task_comm() here may cause locking
582 * dependency issues with current->alloc_lock. In the worst
583 * case, the command line is not correct.
585 strncpy(object
->comm
, current
->comm
, sizeof(object
->comm
));
588 /* kernel backtrace */
589 object
->trace_len
= __save_stack_trace(object
->trace
);
591 write_lock_irqsave(&kmemleak_lock
, flags
);
593 min_addr
= min(min_addr
, ptr
);
594 max_addr
= max(max_addr
, ptr
+ size
);
595 link
= &object_tree_root
.rb_node
;
599 parent
= rb_entry(rb_parent
, struct kmemleak_object
, rb_node
);
600 if (ptr
+ size
<= parent
->pointer
)
601 link
= &parent
->rb_node
.rb_left
;
602 else if (parent
->pointer
+ parent
->size
<= ptr
)
603 link
= &parent
->rb_node
.rb_right
;
605 kmemleak_stop("Cannot insert 0x%lx into the object search tree (overlaps existing)\n",
608 * No need for parent->lock here since "parent" cannot
609 * be freed while the kmemleak_lock is held.
611 dump_object_info(parent
);
612 kmem_cache_free(object_cache
, object
);
617 rb_link_node(&object
->rb_node
, rb_parent
, link
);
618 rb_insert_color(&object
->rb_node
, &object_tree_root
);
620 list_add_tail_rcu(&object
->object_list
, &object_list
);
622 write_unlock_irqrestore(&kmemleak_lock
, flags
);
627 * Mark the object as not allocated and schedule RCU freeing via put_object().
629 static void __delete_object(struct kmemleak_object
*object
)
633 WARN_ON(!(object
->flags
& OBJECT_ALLOCATED
));
634 WARN_ON(atomic_read(&object
->use_count
) < 1);
637 * Locking here also ensures that the corresponding memory block
638 * cannot be freed when it is being scanned.
640 spin_lock_irqsave(&object
->lock
, flags
);
641 object
->flags
&= ~OBJECT_ALLOCATED
;
642 spin_unlock_irqrestore(&object
->lock
, flags
);
647 * Look up the metadata (struct kmemleak_object) corresponding to ptr and
650 static void delete_object_full(unsigned long ptr
)
652 struct kmemleak_object
*object
;
654 object
= find_and_remove_object(ptr
, 0);
657 kmemleak_warn("Freeing unknown object at 0x%08lx\n",
662 __delete_object(object
);
666 * Look up the metadata (struct kmemleak_object) corresponding to ptr and
667 * delete it. If the memory block is partially freed, the function may create
668 * additional metadata for the remaining parts of the block.
670 static void delete_object_part(unsigned long ptr
, size_t size
)
672 struct kmemleak_object
*object
;
673 unsigned long start
, end
;
675 object
= find_and_remove_object(ptr
, 1);
678 kmemleak_warn("Partially freeing unknown object at 0x%08lx (size %zu)\n",
685 * Create one or two objects that may result from the memory block
686 * split. Note that partial freeing is only done by free_bootmem() and
687 * this happens before kmemleak_init() is called. The path below is
688 * only executed during early log recording in kmemleak_init(), so
689 * GFP_KERNEL is enough.
691 start
= object
->pointer
;
692 end
= object
->pointer
+ object
->size
;
694 create_object(start
, ptr
- start
, object
->min_count
,
696 if (ptr
+ size
< end
)
697 create_object(ptr
+ size
, end
- ptr
- size
, object
->min_count
,
700 __delete_object(object
);
703 static void __paint_it(struct kmemleak_object
*object
, int color
)
705 object
->min_count
= color
;
706 if (color
== KMEMLEAK_BLACK
)
707 object
->flags
|= OBJECT_NO_SCAN
;
710 static void paint_it(struct kmemleak_object
*object
, int color
)
714 spin_lock_irqsave(&object
->lock
, flags
);
715 __paint_it(object
, color
);
716 spin_unlock_irqrestore(&object
->lock
, flags
);
719 static void paint_ptr(unsigned long ptr
, int color
)
721 struct kmemleak_object
*object
;
723 object
= find_and_get_object(ptr
, 0);
725 kmemleak_warn("Trying to color unknown object at 0x%08lx as %s\n",
727 (color
== KMEMLEAK_GREY
) ? "Grey" :
728 (color
== KMEMLEAK_BLACK
) ? "Black" : "Unknown");
731 paint_it(object
, color
);
736 * Mark an object permanently as gray-colored so that it can no longer be
737 * reported as a leak. This is used in general to mark a false positive.
739 static void make_gray_object(unsigned long ptr
)
741 paint_ptr(ptr
, KMEMLEAK_GREY
);
745 * Mark the object as black-colored so that it is ignored from scans and
748 static void make_black_object(unsigned long ptr
)
750 paint_ptr(ptr
, KMEMLEAK_BLACK
);
754 * Add a scanning area to the object. If at least one such area is added,
755 * kmemleak will only scan these ranges rather than the whole memory block.
757 static void add_scan_area(unsigned long ptr
, size_t size
, gfp_t gfp
)
760 struct kmemleak_object
*object
;
761 struct kmemleak_scan_area
*area
;
763 object
= find_and_get_object(ptr
, 1);
765 kmemleak_warn("Adding scan area to unknown object at 0x%08lx\n",
770 area
= kmem_cache_alloc(scan_area_cache
, gfp_kmemleak_mask(gfp
));
772 pr_warn("Cannot allocate a scan area\n");
776 spin_lock_irqsave(&object
->lock
, flags
);
777 if (size
== SIZE_MAX
) {
778 size
= object
->pointer
+ object
->size
- ptr
;
779 } else if (ptr
+ size
> object
->pointer
+ object
->size
) {
780 kmemleak_warn("Scan area larger than object 0x%08lx\n", ptr
);
781 dump_object_info(object
);
782 kmem_cache_free(scan_area_cache
, area
);
786 INIT_HLIST_NODE(&area
->node
);
790 hlist_add_head(&area
->node
, &object
->area_list
);
792 spin_unlock_irqrestore(&object
->lock
, flags
);
798 * Set the OBJECT_NO_SCAN flag for the object corresponding to the give
799 * pointer. Such object will not be scanned by kmemleak but references to it
802 static void object_no_scan(unsigned long ptr
)
805 struct kmemleak_object
*object
;
807 object
= find_and_get_object(ptr
, 0);
809 kmemleak_warn("Not scanning unknown object at 0x%08lx\n", ptr
);
813 spin_lock_irqsave(&object
->lock
, flags
);
814 object
->flags
|= OBJECT_NO_SCAN
;
815 spin_unlock_irqrestore(&object
->lock
, flags
);
820 * Log an early kmemleak_* call to the early_log buffer. These calls will be
821 * processed later once kmemleak is fully initialized.
823 static void __init
log_early(int op_type
, const void *ptr
, size_t size
,
827 struct early_log
*log
;
829 if (kmemleak_error
) {
830 /* kmemleak stopped recording, just count the requests */
835 if (crt_early_log
>= ARRAY_SIZE(early_log
)) {
842 * There is no need for locking since the kernel is still in UP mode
843 * at this stage. Disabling the IRQs is enough.
845 local_irq_save(flags
);
846 log
= &early_log
[crt_early_log
];
847 log
->op_type
= op_type
;
850 log
->min_count
= min_count
;
851 log
->trace_len
= __save_stack_trace(log
->trace
);
853 local_irq_restore(flags
);
857 * Log an early allocated block and populate the stack trace.
859 static void early_alloc(struct early_log
*log
)
861 struct kmemleak_object
*object
;
865 if (!kmemleak_enabled
|| !log
->ptr
|| IS_ERR(log
->ptr
))
869 * RCU locking needed to ensure object is not freed via put_object().
872 object
= create_object((unsigned long)log
->ptr
, log
->size
,
873 log
->min_count
, GFP_ATOMIC
);
876 spin_lock_irqsave(&object
->lock
, flags
);
877 for (i
= 0; i
< log
->trace_len
; i
++)
878 object
->trace
[i
] = log
->trace
[i
];
879 object
->trace_len
= log
->trace_len
;
880 spin_unlock_irqrestore(&object
->lock
, flags
);
886 * Log an early allocated block and populate the stack trace.
888 static void early_alloc_percpu(struct early_log
*log
)
891 const void __percpu
*ptr
= log
->ptr
;
893 for_each_possible_cpu(cpu
) {
894 log
->ptr
= per_cpu_ptr(ptr
, cpu
);
900 * kmemleak_alloc - register a newly allocated object
901 * @ptr: pointer to beginning of the object
902 * @size: size of the object
903 * @min_count: minimum number of references to this object. If during memory
904 * scanning a number of references less than @min_count is found,
905 * the object is reported as a memory leak. If @min_count is 0,
906 * the object is never reported as a leak. If @min_count is -1,
907 * the object is ignored (not scanned and not reported as a leak)
908 * @gfp: kmalloc() flags used for kmemleak internal memory allocations
910 * This function is called from the kernel allocators when a new object
911 * (memory block) is allocated (kmem_cache_alloc, kmalloc, vmalloc etc.).
913 void __ref
kmemleak_alloc(const void *ptr
, size_t size
, int min_count
,
916 pr_debug("%s(0x%p, %zu, %d)\n", __func__
, ptr
, size
, min_count
);
918 if (kmemleak_enabled
&& ptr
&& !IS_ERR(ptr
))
919 create_object((unsigned long)ptr
, size
, min_count
, gfp
);
920 else if (kmemleak_early_log
)
921 log_early(KMEMLEAK_ALLOC
, ptr
, size
, min_count
);
923 EXPORT_SYMBOL_GPL(kmemleak_alloc
);
926 * kmemleak_alloc_percpu - register a newly allocated __percpu object
927 * @ptr: __percpu pointer to beginning of the object
928 * @size: size of the object
929 * @gfp: flags used for kmemleak internal memory allocations
931 * This function is called from the kernel percpu allocator when a new object
932 * (memory block) is allocated (alloc_percpu).
934 void __ref
kmemleak_alloc_percpu(const void __percpu
*ptr
, size_t size
,
939 pr_debug("%s(0x%p, %zu)\n", __func__
, ptr
, size
);
942 * Percpu allocations are only scanned and not reported as leaks
943 * (min_count is set to 0).
945 if (kmemleak_enabled
&& ptr
&& !IS_ERR(ptr
))
946 for_each_possible_cpu(cpu
)
947 create_object((unsigned long)per_cpu_ptr(ptr
, cpu
),
949 else if (kmemleak_early_log
)
950 log_early(KMEMLEAK_ALLOC_PERCPU
, ptr
, size
, 0);
952 EXPORT_SYMBOL_GPL(kmemleak_alloc_percpu
);
955 * kmemleak_free - unregister a previously registered object
956 * @ptr: pointer to beginning of the object
958 * This function is called from the kernel allocators when an object (memory
959 * block) is freed (kmem_cache_free, kfree, vfree etc.).
961 void __ref
kmemleak_free(const void *ptr
)
963 pr_debug("%s(0x%p)\n", __func__
, ptr
);
965 if (kmemleak_free_enabled
&& ptr
&& !IS_ERR(ptr
))
966 delete_object_full((unsigned long)ptr
);
967 else if (kmemleak_early_log
)
968 log_early(KMEMLEAK_FREE
, ptr
, 0, 0);
970 EXPORT_SYMBOL_GPL(kmemleak_free
);
973 * kmemleak_free_part - partially unregister a previously registered object
974 * @ptr: pointer to the beginning or inside the object. This also
975 * represents the start of the range to be freed
976 * @size: size to be unregistered
978 * This function is called when only a part of a memory block is freed
979 * (usually from the bootmem allocator).
981 void __ref
kmemleak_free_part(const void *ptr
, size_t size
)
983 pr_debug("%s(0x%p)\n", __func__
, ptr
);
985 if (kmemleak_enabled
&& ptr
&& !IS_ERR(ptr
))
986 delete_object_part((unsigned long)ptr
, size
);
987 else if (kmemleak_early_log
)
988 log_early(KMEMLEAK_FREE_PART
, ptr
, size
, 0);
990 EXPORT_SYMBOL_GPL(kmemleak_free_part
);
993 * kmemleak_free_percpu - unregister a previously registered __percpu object
994 * @ptr: __percpu pointer to beginning of the object
996 * This function is called from the kernel percpu allocator when an object
997 * (memory block) is freed (free_percpu).
999 void __ref
kmemleak_free_percpu(const void __percpu
*ptr
)
1003 pr_debug("%s(0x%p)\n", __func__
, ptr
);
1005 if (kmemleak_free_enabled
&& ptr
&& !IS_ERR(ptr
))
1006 for_each_possible_cpu(cpu
)
1007 delete_object_full((unsigned long)per_cpu_ptr(ptr
,
1009 else if (kmemleak_early_log
)
1010 log_early(KMEMLEAK_FREE_PERCPU
, ptr
, 0, 0);
1012 EXPORT_SYMBOL_GPL(kmemleak_free_percpu
);
1015 * kmemleak_update_trace - update object allocation stack trace
1016 * @ptr: pointer to beginning of the object
1018 * Override the object allocation stack trace for cases where the actual
1019 * allocation place is not always useful.
1021 void __ref
kmemleak_update_trace(const void *ptr
)
1023 struct kmemleak_object
*object
;
1024 unsigned long flags
;
1026 pr_debug("%s(0x%p)\n", __func__
, ptr
);
1028 if (!kmemleak_enabled
|| IS_ERR_OR_NULL(ptr
))
1031 object
= find_and_get_object((unsigned long)ptr
, 1);
1034 kmemleak_warn("Updating stack trace for unknown object at %p\n",
1040 spin_lock_irqsave(&object
->lock
, flags
);
1041 object
->trace_len
= __save_stack_trace(object
->trace
);
1042 spin_unlock_irqrestore(&object
->lock
, flags
);
1046 EXPORT_SYMBOL(kmemleak_update_trace
);
1049 * kmemleak_not_leak - mark an allocated object as false positive
1050 * @ptr: pointer to beginning of the object
1052 * Calling this function on an object will cause the memory block to no longer
1053 * be reported as leak and always be scanned.
1055 void __ref
kmemleak_not_leak(const void *ptr
)
1057 pr_debug("%s(0x%p)\n", __func__
, ptr
);
1059 if (kmemleak_enabled
&& ptr
&& !IS_ERR(ptr
))
1060 make_gray_object((unsigned long)ptr
);
1061 else if (kmemleak_early_log
)
1062 log_early(KMEMLEAK_NOT_LEAK
, ptr
, 0, 0);
1064 EXPORT_SYMBOL(kmemleak_not_leak
);
1067 * kmemleak_ignore - ignore an allocated object
1068 * @ptr: pointer to beginning of the object
1070 * Calling this function on an object will cause the memory block to be
1071 * ignored (not scanned and not reported as a leak). This is usually done when
1072 * it is known that the corresponding block is not a leak and does not contain
1073 * any references to other allocated memory blocks.
1075 void __ref
kmemleak_ignore(const void *ptr
)
1077 pr_debug("%s(0x%p)\n", __func__
, ptr
);
1079 if (kmemleak_enabled
&& ptr
&& !IS_ERR(ptr
))
1080 make_black_object((unsigned long)ptr
);
1081 else if (kmemleak_early_log
)
1082 log_early(KMEMLEAK_IGNORE
, ptr
, 0, 0);
1084 EXPORT_SYMBOL(kmemleak_ignore
);
1087 * kmemleak_scan_area - limit the range to be scanned in an allocated object
1088 * @ptr: pointer to beginning or inside the object. This also
1089 * represents the start of the scan area
1090 * @size: size of the scan area
1091 * @gfp: kmalloc() flags used for kmemleak internal memory allocations
1093 * This function is used when it is known that only certain parts of an object
1094 * contain references to other objects. Kmemleak will only scan these areas
1095 * reducing the number false negatives.
1097 void __ref
kmemleak_scan_area(const void *ptr
, size_t size
, gfp_t gfp
)
1099 pr_debug("%s(0x%p)\n", __func__
, ptr
);
1101 if (kmemleak_enabled
&& ptr
&& size
&& !IS_ERR(ptr
))
1102 add_scan_area((unsigned long)ptr
, size
, gfp
);
1103 else if (kmemleak_early_log
)
1104 log_early(KMEMLEAK_SCAN_AREA
, ptr
, size
, 0);
1106 EXPORT_SYMBOL(kmemleak_scan_area
);
1109 * kmemleak_no_scan - do not scan an allocated object
1110 * @ptr: pointer to beginning of the object
1112 * This function notifies kmemleak not to scan the given memory block. Useful
1113 * in situations where it is known that the given object does not contain any
1114 * references to other objects. Kmemleak will not scan such objects reducing
1115 * the number of false negatives.
1117 void __ref
kmemleak_no_scan(const void *ptr
)
1119 pr_debug("%s(0x%p)\n", __func__
, ptr
);
1121 if (kmemleak_enabled
&& ptr
&& !IS_ERR(ptr
))
1122 object_no_scan((unsigned long)ptr
);
1123 else if (kmemleak_early_log
)
1124 log_early(KMEMLEAK_NO_SCAN
, ptr
, 0, 0);
1126 EXPORT_SYMBOL(kmemleak_no_scan
);
1129 * kmemleak_alloc_phys - similar to kmemleak_alloc but taking a physical
1132 void __ref
kmemleak_alloc_phys(phys_addr_t phys
, size_t size
, int min_count
,
1135 if (!IS_ENABLED(CONFIG_HIGHMEM
) || PHYS_PFN(phys
) < max_low_pfn
)
1136 kmemleak_alloc(__va(phys
), size
, min_count
, gfp
);
1138 EXPORT_SYMBOL(kmemleak_alloc_phys
);
1141 * kmemleak_free_part_phys - similar to kmemleak_free_part but taking a
1142 * physical address argument
1144 void __ref
kmemleak_free_part_phys(phys_addr_t phys
, size_t size
)
1146 if (!IS_ENABLED(CONFIG_HIGHMEM
) || PHYS_PFN(phys
) < max_low_pfn
)
1147 kmemleak_free_part(__va(phys
), size
);
1149 EXPORT_SYMBOL(kmemleak_free_part_phys
);
1152 * kmemleak_not_leak_phys - similar to kmemleak_not_leak but taking a physical
1155 void __ref
kmemleak_not_leak_phys(phys_addr_t phys
)
1157 if (!IS_ENABLED(CONFIG_HIGHMEM
) || PHYS_PFN(phys
) < max_low_pfn
)
1158 kmemleak_not_leak(__va(phys
));
1160 EXPORT_SYMBOL(kmemleak_not_leak_phys
);
1163 * kmemleak_ignore_phys - similar to kmemleak_ignore but taking a physical
1166 void __ref
kmemleak_ignore_phys(phys_addr_t phys
)
1168 if (!IS_ENABLED(CONFIG_HIGHMEM
) || PHYS_PFN(phys
) < max_low_pfn
)
1169 kmemleak_ignore(__va(phys
));
1171 EXPORT_SYMBOL(kmemleak_ignore_phys
);
1174 * Update an object's checksum and return true if it was modified.
1176 static bool update_checksum(struct kmemleak_object
*object
)
1178 u32 old_csum
= object
->checksum
;
1180 if (!kmemcheck_is_obj_initialized(object
->pointer
, object
->size
))
1183 kasan_disable_current();
1184 object
->checksum
= crc32(0, (void *)object
->pointer
, object
->size
);
1185 kasan_enable_current();
1187 return object
->checksum
!= old_csum
;
1191 * Update an object's references. object->lock must be held by the caller.
1193 static void update_refs(struct kmemleak_object
*object
)
1195 if (!color_white(object
)) {
1196 /* non-orphan, ignored or new */
1201 * Increase the object's reference count (number of pointers to the
1202 * memory block). If this count reaches the required minimum, the
1203 * object's color will become gray and it will be added to the
1207 if (color_gray(object
)) {
1208 /* put_object() called when removing from gray_list */
1209 WARN_ON(!get_object(object
));
1210 list_add_tail(&object
->gray_list
, &gray_list
);
1215 * Memory scanning is a long process and it needs to be interruptable. This
1216 * function checks whether such interrupt condition occurred.
1218 static int scan_should_stop(void)
1220 if (!kmemleak_enabled
)
1224 * This function may be called from either process or kthread context,
1225 * hence the need to check for both stop conditions.
1228 return signal_pending(current
);
1230 return kthread_should_stop();
1236 * Scan a memory block (exclusive range) for valid pointers and add those
1237 * found to the gray list.
1239 static void scan_block(void *_start
, void *_end
,
1240 struct kmemleak_object
*scanned
)
1243 unsigned long *start
= PTR_ALIGN(_start
, BYTES_PER_POINTER
);
1244 unsigned long *end
= _end
- (BYTES_PER_POINTER
- 1);
1245 unsigned long flags
;
1247 read_lock_irqsave(&kmemleak_lock
, flags
);
1248 for (ptr
= start
; ptr
< end
; ptr
++) {
1249 struct kmemleak_object
*object
;
1250 unsigned long pointer
;
1252 if (scan_should_stop())
1255 /* don't scan uninitialized memory */
1256 if (!kmemcheck_is_obj_initialized((unsigned long)ptr
,
1260 kasan_disable_current();
1262 kasan_enable_current();
1264 if (pointer
< min_addr
|| pointer
>= max_addr
)
1268 * No need for get_object() here since we hold kmemleak_lock.
1269 * object->use_count cannot be dropped to 0 while the object
1270 * is still present in object_tree_root and object_list
1271 * (with updates protected by kmemleak_lock).
1273 object
= lookup_object(pointer
, 1);
1276 if (object
== scanned
)
1277 /* self referenced, ignore */
1281 * Avoid the lockdep recursive warning on object->lock being
1282 * previously acquired in scan_object(). These locks are
1283 * enclosed by scan_mutex.
1285 spin_lock_nested(&object
->lock
, SINGLE_DEPTH_NESTING
);
1286 update_refs(object
);
1287 spin_unlock(&object
->lock
);
1289 read_unlock_irqrestore(&kmemleak_lock
, flags
);
1293 * Scan a large memory block in MAX_SCAN_SIZE chunks to reduce the latency.
1295 static void scan_large_block(void *start
, void *end
)
1299 while (start
< end
) {
1300 next
= min(start
+ MAX_SCAN_SIZE
, end
);
1301 scan_block(start
, next
, NULL
);
1308 * Scan a memory block corresponding to a kmemleak_object. A condition is
1309 * that object->use_count >= 1.
1311 static void scan_object(struct kmemleak_object
*object
)
1313 struct kmemleak_scan_area
*area
;
1314 unsigned long flags
;
1317 * Once the object->lock is acquired, the corresponding memory block
1318 * cannot be freed (the same lock is acquired in delete_object).
1320 spin_lock_irqsave(&object
->lock
, flags
);
1321 if (object
->flags
& OBJECT_NO_SCAN
)
1323 if (!(object
->flags
& OBJECT_ALLOCATED
))
1324 /* already freed object */
1326 if (hlist_empty(&object
->area_list
)) {
1327 void *start
= (void *)object
->pointer
;
1328 void *end
= (void *)(object
->pointer
+ object
->size
);
1332 next
= min(start
+ MAX_SCAN_SIZE
, end
);
1333 scan_block(start
, next
, object
);
1339 spin_unlock_irqrestore(&object
->lock
, flags
);
1341 spin_lock_irqsave(&object
->lock
, flags
);
1342 } while (object
->flags
& OBJECT_ALLOCATED
);
1344 hlist_for_each_entry(area
, &object
->area_list
, node
)
1345 scan_block((void *)area
->start
,
1346 (void *)(area
->start
+ area
->size
),
1349 spin_unlock_irqrestore(&object
->lock
, flags
);
1353 * Scan the objects already referenced (gray objects). More objects will be
1354 * referenced and, if there are no memory leaks, all the objects are scanned.
1356 static void scan_gray_list(void)
1358 struct kmemleak_object
*object
, *tmp
;
1361 * The list traversal is safe for both tail additions and removals
1362 * from inside the loop. The kmemleak objects cannot be freed from
1363 * outside the loop because their use_count was incremented.
1365 object
= list_entry(gray_list
.next
, typeof(*object
), gray_list
);
1366 while (&object
->gray_list
!= &gray_list
) {
1369 /* may add new objects to the list */
1370 if (!scan_should_stop())
1371 scan_object(object
);
1373 tmp
= list_entry(object
->gray_list
.next
, typeof(*object
),
1376 /* remove the object from the list and release it */
1377 list_del(&object
->gray_list
);
1382 WARN_ON(!list_empty(&gray_list
));
1386 * Scan data sections and all the referenced memory blocks allocated via the
1387 * kernel's standard allocators. This function must be called with the
1390 static void kmemleak_scan(void)
1392 unsigned long flags
;
1393 struct kmemleak_object
*object
;
1397 jiffies_last_scan
= jiffies
;
1399 /* prepare the kmemleak_object's */
1401 list_for_each_entry_rcu(object
, &object_list
, object_list
) {
1402 spin_lock_irqsave(&object
->lock
, flags
);
1405 * With a few exceptions there should be a maximum of
1406 * 1 reference to any object at this point.
1408 if (atomic_read(&object
->use_count
) > 1) {
1409 pr_debug("object->use_count = %d\n",
1410 atomic_read(&object
->use_count
));
1411 dump_object_info(object
);
1414 /* reset the reference count (whiten the object) */
1416 if (color_gray(object
) && get_object(object
))
1417 list_add_tail(&object
->gray_list
, &gray_list
);
1419 spin_unlock_irqrestore(&object
->lock
, flags
);
1423 /* data/bss scanning */
1424 scan_large_block(_sdata
, _edata
);
1425 scan_large_block(__bss_start
, __bss_stop
);
1426 scan_large_block(__start_ro_after_init
, __end_ro_after_init
);
1429 /* per-cpu sections scanning */
1430 for_each_possible_cpu(i
)
1431 scan_large_block(__per_cpu_start
+ per_cpu_offset(i
),
1432 __per_cpu_end
+ per_cpu_offset(i
));
1436 * Struct page scanning for each node.
1439 for_each_online_node(i
) {
1440 unsigned long start_pfn
= node_start_pfn(i
);
1441 unsigned long end_pfn
= node_end_pfn(i
);
1444 for (pfn
= start_pfn
; pfn
< end_pfn
; pfn
++) {
1447 if (!pfn_valid(pfn
))
1449 page
= pfn_to_page(pfn
);
1450 /* only scan if page is in use */
1451 if (page_count(page
) == 0)
1453 scan_block(page
, page
+ 1, NULL
);
1459 * Scanning the task stacks (may introduce false negatives).
1461 if (kmemleak_stack_scan
) {
1462 struct task_struct
*p
, *g
;
1464 read_lock(&tasklist_lock
);
1465 do_each_thread(g
, p
) {
1466 void *stack
= try_get_task_stack(p
);
1468 scan_block(stack
, stack
+ THREAD_SIZE
, NULL
);
1471 } while_each_thread(g
, p
);
1472 read_unlock(&tasklist_lock
);
1476 * Scan the objects already referenced from the sections scanned
1482 * Check for new or unreferenced objects modified since the previous
1483 * scan and color them gray until the next scan.
1486 list_for_each_entry_rcu(object
, &object_list
, object_list
) {
1487 spin_lock_irqsave(&object
->lock
, flags
);
1488 if (color_white(object
) && (object
->flags
& OBJECT_ALLOCATED
)
1489 && update_checksum(object
) && get_object(object
)) {
1490 /* color it gray temporarily */
1491 object
->count
= object
->min_count
;
1492 list_add_tail(&object
->gray_list
, &gray_list
);
1494 spin_unlock_irqrestore(&object
->lock
, flags
);
1499 * Re-scan the gray list for modified unreferenced objects.
1504 * If scanning was stopped do not report any new unreferenced objects.
1506 if (scan_should_stop())
1510 * Scanning result reporting.
1513 list_for_each_entry_rcu(object
, &object_list
, object_list
) {
1514 spin_lock_irqsave(&object
->lock
, flags
);
1515 if (unreferenced_object(object
) &&
1516 !(object
->flags
& OBJECT_REPORTED
)) {
1517 object
->flags
|= OBJECT_REPORTED
;
1520 spin_unlock_irqrestore(&object
->lock
, flags
);
1525 kmemleak_found_leaks
= true;
1527 pr_info("%d new suspected memory leaks (see /sys/kernel/debug/kmemleak)\n",
1534 * Thread function performing automatic memory scanning. Unreferenced objects
1535 * at the end of a memory scan are reported but only the first time.
1537 static int kmemleak_scan_thread(void *arg
)
1539 static int first_run
= 1;
1541 pr_info("Automatic memory scanning thread started\n");
1542 set_user_nice(current
, 10);
1545 * Wait before the first scan to allow the system to fully initialize.
1548 signed long timeout
= msecs_to_jiffies(SECS_FIRST_SCAN
* 1000);
1550 while (timeout
&& !kthread_should_stop())
1551 timeout
= schedule_timeout_interruptible(timeout
);
1554 while (!kthread_should_stop()) {
1555 signed long timeout
= jiffies_scan_wait
;
1557 mutex_lock(&scan_mutex
);
1559 mutex_unlock(&scan_mutex
);
1561 /* wait before the next scan */
1562 while (timeout
&& !kthread_should_stop())
1563 timeout
= schedule_timeout_interruptible(timeout
);
1566 pr_info("Automatic memory scanning thread ended\n");
1572 * Start the automatic memory scanning thread. This function must be called
1573 * with the scan_mutex held.
1575 static void start_scan_thread(void)
1579 scan_thread
= kthread_run(kmemleak_scan_thread
, NULL
, "kmemleak");
1580 if (IS_ERR(scan_thread
)) {
1581 pr_warn("Failed to create the scan thread\n");
1587 * Stop the automatic memory scanning thread. This function must be called
1588 * with the scan_mutex held.
1590 static void stop_scan_thread(void)
1593 kthread_stop(scan_thread
);
1599 * Iterate over the object_list and return the first valid object at or after
1600 * the required position with its use_count incremented. The function triggers
1601 * a memory scanning when the pos argument points to the first position.
1603 static void *kmemleak_seq_start(struct seq_file
*seq
, loff_t
*pos
)
1605 struct kmemleak_object
*object
;
1609 err
= mutex_lock_interruptible(&scan_mutex
);
1611 return ERR_PTR(err
);
1614 list_for_each_entry_rcu(object
, &object_list
, object_list
) {
1617 if (get_object(object
))
1626 * Return the next object in the object_list. The function decrements the
1627 * use_count of the previous object and increases that of the next one.
1629 static void *kmemleak_seq_next(struct seq_file
*seq
, void *v
, loff_t
*pos
)
1631 struct kmemleak_object
*prev_obj
= v
;
1632 struct kmemleak_object
*next_obj
= NULL
;
1633 struct kmemleak_object
*obj
= prev_obj
;
1637 list_for_each_entry_continue_rcu(obj
, &object_list
, object_list
) {
1638 if (get_object(obj
)) {
1644 put_object(prev_obj
);
1649 * Decrement the use_count of the last object required, if any.
1651 static void kmemleak_seq_stop(struct seq_file
*seq
, void *v
)
1655 * kmemleak_seq_start may return ERR_PTR if the scan_mutex
1656 * waiting was interrupted, so only release it if !IS_ERR.
1659 mutex_unlock(&scan_mutex
);
1666 * Print the information for an unreferenced object to the seq file.
1668 static int kmemleak_seq_show(struct seq_file
*seq
, void *v
)
1670 struct kmemleak_object
*object
= v
;
1671 unsigned long flags
;
1673 spin_lock_irqsave(&object
->lock
, flags
);
1674 if ((object
->flags
& OBJECT_REPORTED
) && unreferenced_object(object
))
1675 print_unreferenced(seq
, object
);
1676 spin_unlock_irqrestore(&object
->lock
, flags
);
1680 static const struct seq_operations kmemleak_seq_ops
= {
1681 .start
= kmemleak_seq_start
,
1682 .next
= kmemleak_seq_next
,
1683 .stop
= kmemleak_seq_stop
,
1684 .show
= kmemleak_seq_show
,
1687 static int kmemleak_open(struct inode
*inode
, struct file
*file
)
1689 return seq_open(file
, &kmemleak_seq_ops
);
1692 static int dump_str_object_info(const char *str
)
1694 unsigned long flags
;
1695 struct kmemleak_object
*object
;
1698 if (kstrtoul(str
, 0, &addr
))
1700 object
= find_and_get_object(addr
, 0);
1702 pr_info("Unknown object at 0x%08lx\n", addr
);
1706 spin_lock_irqsave(&object
->lock
, flags
);
1707 dump_object_info(object
);
1708 spin_unlock_irqrestore(&object
->lock
, flags
);
1715 * We use grey instead of black to ensure we can do future scans on the same
1716 * objects. If we did not do future scans these black objects could
1717 * potentially contain references to newly allocated objects in the future and
1718 * we'd end up with false positives.
1720 static void kmemleak_clear(void)
1722 struct kmemleak_object
*object
;
1723 unsigned long flags
;
1726 list_for_each_entry_rcu(object
, &object_list
, object_list
) {
1727 spin_lock_irqsave(&object
->lock
, flags
);
1728 if ((object
->flags
& OBJECT_REPORTED
) &&
1729 unreferenced_object(object
))
1730 __paint_it(object
, KMEMLEAK_GREY
);
1731 spin_unlock_irqrestore(&object
->lock
, flags
);
1735 kmemleak_found_leaks
= false;
1738 static void __kmemleak_do_cleanup(void);
1741 * File write operation to configure kmemleak at run-time. The following
1742 * commands can be written to the /sys/kernel/debug/kmemleak file:
1743 * off - disable kmemleak (irreversible)
1744 * stack=on - enable the task stacks scanning
1745 * stack=off - disable the tasks stacks scanning
1746 * scan=on - start the automatic memory scanning thread
1747 * scan=off - stop the automatic memory scanning thread
1748 * scan=... - set the automatic memory scanning period in seconds (0 to
1750 * scan - trigger a memory scan
1751 * clear - mark all current reported unreferenced kmemleak objects as
1752 * grey to ignore printing them, or free all kmemleak objects
1753 * if kmemleak has been disabled.
1754 * dump=... - dump information about the object found at the given address
1756 static ssize_t
kmemleak_write(struct file
*file
, const char __user
*user_buf
,
1757 size_t size
, loff_t
*ppos
)
1763 buf_size
= min(size
, (sizeof(buf
) - 1));
1764 if (strncpy_from_user(buf
, user_buf
, buf_size
) < 0)
1768 ret
= mutex_lock_interruptible(&scan_mutex
);
1772 if (strncmp(buf
, "clear", 5) == 0) {
1773 if (kmemleak_enabled
)
1776 __kmemleak_do_cleanup();
1780 if (!kmemleak_enabled
) {
1785 if (strncmp(buf
, "off", 3) == 0)
1787 else if (strncmp(buf
, "stack=on", 8) == 0)
1788 kmemleak_stack_scan
= 1;
1789 else if (strncmp(buf
, "stack=off", 9) == 0)
1790 kmemleak_stack_scan
= 0;
1791 else if (strncmp(buf
, "scan=on", 7) == 0)
1792 start_scan_thread();
1793 else if (strncmp(buf
, "scan=off", 8) == 0)
1795 else if (strncmp(buf
, "scan=", 5) == 0) {
1798 ret
= kstrtoul(buf
+ 5, 0, &secs
);
1803 jiffies_scan_wait
= msecs_to_jiffies(secs
* 1000);
1804 start_scan_thread();
1806 } else if (strncmp(buf
, "scan", 4) == 0)
1808 else if (strncmp(buf
, "dump=", 5) == 0)
1809 ret
= dump_str_object_info(buf
+ 5);
1814 mutex_unlock(&scan_mutex
);
1818 /* ignore the rest of the buffer, only one command at a time */
1823 static const struct file_operations kmemleak_fops
= {
1824 .owner
= THIS_MODULE
,
1825 .open
= kmemleak_open
,
1827 .write
= kmemleak_write
,
1828 .llseek
= seq_lseek
,
1829 .release
= seq_release
,
1832 static void __kmemleak_do_cleanup(void)
1834 struct kmemleak_object
*object
;
1837 list_for_each_entry_rcu(object
, &object_list
, object_list
)
1838 delete_object_full(object
->pointer
);
1843 * Stop the memory scanning thread and free the kmemleak internal objects if
1844 * no previous scan thread (otherwise, kmemleak may still have some useful
1845 * information on memory leaks).
1847 static void kmemleak_do_cleanup(struct work_struct
*work
)
1852 * Once the scan thread has stopped, it is safe to no longer track
1853 * object freeing. Ordering of the scan thread stopping and the memory
1854 * accesses below is guaranteed by the kthread_stop() function.
1856 kmemleak_free_enabled
= 0;
1858 if (!kmemleak_found_leaks
)
1859 __kmemleak_do_cleanup();
1861 pr_info("Kmemleak disabled without freeing internal data. Reclaim the memory with \"echo clear > /sys/kernel/debug/kmemleak\".\n");
1864 static DECLARE_WORK(cleanup_work
, kmemleak_do_cleanup
);
1867 * Disable kmemleak. No memory allocation/freeing will be traced once this
1868 * function is called. Disabling kmemleak is an irreversible operation.
1870 static void kmemleak_disable(void)
1872 /* atomically check whether it was already invoked */
1873 if (cmpxchg(&kmemleak_error
, 0, 1))
1876 /* stop any memory operation tracing */
1877 kmemleak_enabled
= 0;
1879 /* check whether it is too early for a kernel thread */
1880 if (kmemleak_initialized
)
1881 schedule_work(&cleanup_work
);
1883 kmemleak_free_enabled
= 0;
1885 pr_info("Kernel memory leak detector disabled\n");
1889 * Allow boot-time kmemleak disabling (enabled by default).
1891 static int kmemleak_boot_config(char *str
)
1895 if (strcmp(str
, "off") == 0)
1897 else if (strcmp(str
, "on") == 0)
1898 kmemleak_skip_disable
= 1;
1903 early_param("kmemleak", kmemleak_boot_config
);
1905 static void __init
print_log_trace(struct early_log
*log
)
1907 struct stack_trace trace
;
1909 trace
.nr_entries
= log
->trace_len
;
1910 trace
.entries
= log
->trace
;
1912 pr_notice("Early log backtrace:\n");
1913 print_stack_trace(&trace
, 2);
1917 * Kmemleak initialization.
1919 void __init
kmemleak_init(void)
1922 unsigned long flags
;
1924 #ifdef CONFIG_DEBUG_KMEMLEAK_DEFAULT_OFF
1925 if (!kmemleak_skip_disable
) {
1926 kmemleak_early_log
= 0;
1932 jiffies_min_age
= msecs_to_jiffies(MSECS_MIN_AGE
);
1933 jiffies_scan_wait
= msecs_to_jiffies(SECS_SCAN_WAIT
* 1000);
1935 object_cache
= KMEM_CACHE(kmemleak_object
, SLAB_NOLEAKTRACE
);
1936 scan_area_cache
= KMEM_CACHE(kmemleak_scan_area
, SLAB_NOLEAKTRACE
);
1938 if (crt_early_log
> ARRAY_SIZE(early_log
))
1939 pr_warn("Early log buffer exceeded (%d), please increase DEBUG_KMEMLEAK_EARLY_LOG_SIZE\n",
1942 /* the kernel is still in UP mode, so disabling the IRQs is enough */
1943 local_irq_save(flags
);
1944 kmemleak_early_log
= 0;
1945 if (kmemleak_error
) {
1946 local_irq_restore(flags
);
1949 kmemleak_enabled
= 1;
1950 kmemleak_free_enabled
= 1;
1952 local_irq_restore(flags
);
1955 * This is the point where tracking allocations is safe. Automatic
1956 * scanning is started during the late initcall. Add the early logged
1957 * callbacks to the kmemleak infrastructure.
1959 for (i
= 0; i
< crt_early_log
; i
++) {
1960 struct early_log
*log
= &early_log
[i
];
1962 switch (log
->op_type
) {
1963 case KMEMLEAK_ALLOC
:
1966 case KMEMLEAK_ALLOC_PERCPU
:
1967 early_alloc_percpu(log
);
1970 kmemleak_free(log
->ptr
);
1972 case KMEMLEAK_FREE_PART
:
1973 kmemleak_free_part(log
->ptr
, log
->size
);
1975 case KMEMLEAK_FREE_PERCPU
:
1976 kmemleak_free_percpu(log
->ptr
);
1978 case KMEMLEAK_NOT_LEAK
:
1979 kmemleak_not_leak(log
->ptr
);
1981 case KMEMLEAK_IGNORE
:
1982 kmemleak_ignore(log
->ptr
);
1984 case KMEMLEAK_SCAN_AREA
:
1985 kmemleak_scan_area(log
->ptr
, log
->size
, GFP_KERNEL
);
1987 case KMEMLEAK_NO_SCAN
:
1988 kmemleak_no_scan(log
->ptr
);
1991 kmemleak_warn("Unknown early log operation: %d\n",
1995 if (kmemleak_warning
) {
1996 print_log_trace(log
);
1997 kmemleak_warning
= 0;
2003 * Late initialization function.
2005 static int __init
kmemleak_late_init(void)
2007 struct dentry
*dentry
;
2009 kmemleak_initialized
= 1;
2011 if (kmemleak_error
) {
2013 * Some error occurred and kmemleak was disabled. There is a
2014 * small chance that kmemleak_disable() was called immediately
2015 * after setting kmemleak_initialized and we may end up with
2016 * two clean-up threads but serialized by scan_mutex.
2018 schedule_work(&cleanup_work
);
2022 dentry
= debugfs_create_file("kmemleak", S_IRUGO
, NULL
, NULL
,
2025 pr_warn("Failed to create the debugfs kmemleak file\n");
2026 mutex_lock(&scan_mutex
);
2027 start_scan_thread();
2028 mutex_unlock(&scan_mutex
);
2030 pr_info("Kernel memory leak detector initialized\n");
2034 late_initcall(kmemleak_late_init
);