blob: 1136030d9091189f1e40598295dc2250f0e6b936 [file] [log] [blame]
lh9ed821d2023-04-07 01:36:19 -07001/*
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
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
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
64#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
65
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/export.h>
73#include <linux/kthread.h>
74#include <linux/prio_tree.h>
75#include <linux/fs.h>
76#include <linux/debugfs.h>
77#include <linux/seq_file.h>
78#include <linux/cpumask.h>
79#include <linux/spinlock.h>
80#include <linux/mutex.h>
81#include <linux/rcupdate.h>
82#include <linux/stacktrace.h>
83#include <linux/cache.h>
84#include <linux/percpu.h>
85#include <linux/hardirq.h>
86#include <linux/mmzone.h>
87#include <linux/slab.h>
88#include <linux/thread_info.h>
89#include <linux/err.h>
90#include <linux/uaccess.h>
91#include <linux/string.h>
92#include <linux/nodemask.h>
93#include <linux/mm.h>
94#include <linux/workqueue.h>
95#include <linux/crc32.h>
96
97#include <asm/sections.h>
98#include <asm/processor.h>
99#include <linux/atomic.h>
100
101#include <linux/kmemcheck.h>
102#include <linux/kmemleak.h>
103#include <linux/memory_hotplug.h>
104
105/*
106 * Kmemleak configuration and common defines.
107 * Add KMEMLEAK_FULL for full function version( By zhu di)
108 */
109 #ifdef KMEMLEAK_FULL
110#define MAX_TRACE 16 /* stack trace length */
111#else
112#define MAX_TRACE 2 /* minimum the footprint */
113#endif
114#define MSECS_MIN_AGE 5000 /* minimum object age for reporting */
115#define SECS_FIRST_SCAN 60 /* delay before the first scan */
116#define SECS_SCAN_WAIT 600 /* subsequent auto scanning delay */
117#define MAX_SCAN_SIZE 4096 /* maximum size of a scanned block */
118
119#define BYTES_PER_POINTER sizeof(void *)
120
121/* GFP bitmask for kmemleak internal allocations */
122#define gfp_kmemleak_mask(gfp) (((gfp) & (GFP_KERNEL | GFP_ATOMIC)) | \
123 __GFP_NORETRY | __GFP_NOMEMALLOC | \
124 __GFP_NOWARN)
125
126/* scanning area inside a memory block */
127struct kmemleak_scan_area {
128 struct hlist_node node;
129 unsigned long start;
130 size_t size;
131};
132
133#define KMEMLEAK_GREY 0
134#define KMEMLEAK_BLACK -1
135
136/*
137 * Structure holding the metadata for each allocated memory block.
138 * Modifications to such objects should be made while holding the
139 * object->lock. Insertions or deletions from object_list, gray_list or
140 * tree_node are already protected by the corresponding locks or mutex (see
141 * the notes on locking above). These objects are reference-counted
142 * (use_count) and freed using the RCU mechanism.
143 */
144struct kmemleak_object {
145#ifdef KMEMLEAK_FULL
146 spinlock_t lock;
147 unsigned long flags; /* object status flags */
148 struct list_head gray_list;
149
150 /* object usage count; object freed when use_count == 0 */
151 atomic_t use_count;
152 unsigned long pointer;
153 /* minimum number of a pointers found before it is considered leak */
154 int min_count;
155 /* the total number of pointers found pointing to this object */
156 int count;
157 /* checksum for detecting modified objects */
158 u32 checksum;
159 /* memory ranges to be scanned inside an object (empty for all) */
160 struct hlist_head area_list;
161 unsigned int trace_len;
162#endif
163 size_t size;
164 unsigned long trace[MAX_TRACE];
165 struct list_head object_list;
166 struct prio_tree_node tree_node;
167 struct rcu_head rcu; /* object_list lockless traversal */
168 unsigned long jiffies; /* creation timestamp */
169 pid_t pid; /* pid of the current task */
170 char comm[TASK_COMM_LEN]; /* executable name */
171};
172
173/* flag representing the memory block allocation status */
174#define OBJECT_ALLOCATED (1 << 0)
175/* flag set after the first reporting of an unreference object */
176#define OBJECT_REPORTED (1 << 1)
177/* flag set to not scan the object */
178#define OBJECT_NO_SCAN (1 << 2)
179
180/* number of bytes to print per line; must be 16 or 32 */
181#define HEX_ROW_SIZE 16
182/* number of bytes to print at a time (1, 2, 4, 8) */
183#define HEX_GROUP_SIZE 1
184/* include ASCII after the hex output */
185#define HEX_ASCII 1
186/* max number of lines to be printed */
187#define HEX_MAX_LINES 2
188
189/* the list of all allocated objects */
190static LIST_HEAD(object_list);
191/* the list of gray-colored objects (see color_gray comment below) */
192static LIST_HEAD(gray_list);
193/* prio search tree for object boundaries */
194static struct prio_tree_root object_tree_root;
195/* rw_lock protecting the access to object_list and prio_tree_root */
196static DEFINE_RWLOCK(kmemleak_lock);
197
198/* allocation caches for kmemleak internal data */
199static struct kmem_cache *object_cache;
200static struct kmem_cache *scan_area_cache;
201
202/* set if tracing memory operations is enabled */
203static atomic_t kmemleak_enabled = ATOMIC_INIT(0);
204/* same as above but only for the kmemleak_free() callback */
205static int kmemleak_free_enabled;
206/* set in the late_initcall if there were no errors */
207static atomic_t kmemleak_initialized = ATOMIC_INIT(0);
208/* enables or disables early logging of the memory operations */
209static atomic_t kmemleak_early_log = ATOMIC_INIT(1);
210/* set if a kmemleak warning was issued */
211static atomic_t kmemleak_warning = ATOMIC_INIT(0);
212/* set if a fatal kmemleak error has occurred */
213static atomic_t kmemleak_error = ATOMIC_INIT(0);
214
215/* minimum and maximum address that may be valid pointers */
216static unsigned long min_addr = ULONG_MAX;
217static unsigned long max_addr;
218
219static struct task_struct *scan_thread;
220/* used to avoid reporting of recently allocated objects */
221static unsigned long jiffies_min_age;
222static unsigned long jiffies_last_scan;
223/* delay between automatic memory scannings */
224static signed long jiffies_scan_wait;
225/* enables or disables the task stacks scanning */
226static int kmemleak_stack_scan = 1;
227/* protects the memory scanning, parameters and debug/kmemleak file access */
228static DEFINE_MUTEX(scan_mutex);
229/* setting kmemleak=on, will set this var, skipping the disable */
230static int kmemleak_skip_disable;
231
232
233/*
234 * Early object allocation/freeing logging. Kmemleak is initialized after the
235 * kernel allocator. However, both the kernel allocator and kmemleak may
236 * allocate memory blocks which need to be tracked. Kmemleak defines an
237 * arbitrary buffer to hold the allocation/freeing information before it is
238 * fully initialized.
239 */
240
241/* kmemleak operation type for early logging */
242enum {
243 KMEMLEAK_ALLOC,
244 KMEMLEAK_ALLOC_PERCPU,
245 KMEMLEAK_FREE,
246 KMEMLEAK_FREE_PART,
247 KMEMLEAK_FREE_PERCPU,
248 KMEMLEAK_NOT_LEAK,
249 KMEMLEAK_IGNORE,
250 KMEMLEAK_SCAN_AREA,
251 KMEMLEAK_NO_SCAN
252};
253
254/*
255 * Structure holding the information passed to kmemleak callbacks during the
256 * early logging.
257 */
258struct early_log {
259 int op_type; /* kmemleak operation type */
260 const void *ptr; /* allocated/freed memory block */
261 size_t size; /* memory block size */
262 int min_count; /* minimum reference count */
263 unsigned long trace[MAX_TRACE]; /* stack trace */
264 unsigned int trace_len; /* stack trace length */
265};
266
267/* early logging buffer and current position */
268static struct early_log
269 early_log[CONFIG_DEBUG_KMEMLEAK_EARLY_LOG_SIZE] __initdata;
270static int crt_early_log __initdata;
271
272static void kmemleak_disable(void);
273
274/*
275 * Print a warning and dump the stack trace.
276 */
277#define kmemleak_warn(x...) do { \
278 pr_warning(x); \
279 dump_stack(); \
280 atomic_set(&kmemleak_warning, 1); \
281} while (0)
282
283/*
284 * Macro invoked when a serious kmemleak condition occurred and cannot be
285 * recovered from. Kmemleak will be disabled and further allocation/freeing
286 * tracing no longer available.
287 */
288#define kmemleak_stop(x...) do { \
289 kmemleak_warn(x); \
290 kmemleak_disable(); \
291} while (0)
292
293/*
294 * Printing of the objects hex dump to the seq file. The number of lines to be
295 * printed is limited to HEX_MAX_LINES to prevent seq file spamming. The
296 * actual number of printed bytes depends on HEX_ROW_SIZE. It must be called
297 * with the object->lock held.
298 */
299 #ifdef KMEMLEAK_FULL
300static void hex_dump_object(struct seq_file *seq,
301 struct kmemleak_object *object)
302{
303 const u8 *ptr = (const u8 *)object->pointer;
304 int i, len, remaining;
305 unsigned char linebuf[HEX_ROW_SIZE * 5];
306
307 /* limit the number of lines to HEX_MAX_LINES */
308 remaining = len =
309 min(object->size, (size_t)(HEX_MAX_LINES * HEX_ROW_SIZE));
310
311 seq_printf(seq, " hex dump (first %d bytes):\n", len);
312 for (i = 0; i < len; i += HEX_ROW_SIZE) {
313 int linelen = min(remaining, HEX_ROW_SIZE);
314
315 remaining -= HEX_ROW_SIZE;
316 hex_dump_to_buffer(ptr + i, linelen, HEX_ROW_SIZE,
317 HEX_GROUP_SIZE, linebuf, sizeof(linebuf),
318 HEX_ASCII);
319 seq_printf(seq, " %s\n", linebuf);
320 }
321}
322
323/*
324 * Object colors, encoded with count and min_count:
325 * - white - orphan object, not enough references to it (count < min_count)
326 * - gray - not orphan, not marked as false positive (min_count == 0) or
327 * sufficient references to it (count >= min_count)
328 * - black - ignore, it doesn't contain references (e.g. text section)
329 * (min_count == -1). No function defined for this color.
330 * Newly created objects don't have any color assigned (object->count == -1)
331 * before the next memory scan when they become white.
332 */
333static bool color_white(const struct kmemleak_object *object)
334{
335 return object->count != KMEMLEAK_BLACK &&
336 object->count < object->min_count;
337}
338
339static bool color_gray(const struct kmemleak_object *object)
340{
341 return object->min_count != KMEMLEAK_BLACK &&
342 object->count >= object->min_count;
343}
344
345/*
346 * Objects are considered unreferenced only if their color is white, they have
347 * not be deleted and have a minimum age to avoid false positives caused by
348 * pointers temporarily stored in CPU registers.
349 */
350static bool unreferenced_object(struct kmemleak_object *object)
351{
352 return (color_white(object) && object->flags & OBJECT_ALLOCATED) &&
353 time_before_eq(object->jiffies + jiffies_min_age,
354 jiffies_last_scan);
355}
356
357
358/*
359 * Printing of the unreferenced objects information to the seq file. The
360 * print_unreferenced function must be called with the object->lock held.
361 */
362static void print_unreferenced(struct seq_file *seq,
363 struct kmemleak_object *object)
364{
365 int i;
366 unsigned int msecs_age = jiffies_to_msecs(jiffies - object->jiffies);
367
368 seq_printf(seq, "unreferenced object 0x%08lx (size %zu):\n",
369 object->pointer, object->size);
370 seq_printf(seq, " comm \"%s\", pid %d, jiffies %lu (age %d.%03ds)\n",
371 object->comm, object->pid, object->jiffies,
372 msecs_age / 1000, msecs_age % 1000);
373 hex_dump_object(seq, object);
374 seq_printf(seq, " backtrace:\n");
375
376 for (i = 0; i < object->trace_len; i++) {
377 void *ptr = (void *)object->trace[i];
378 seq_printf(seq, " [<%p>] %pS\n", ptr, ptr);
379 }
380}
381
382
383/*
384 * Print the kmemleak_object information. This function is used mainly for
385 * debugging special cases when kmemleak operations. It must be called with
386 * the object->lock held.
387 */
388static void dump_object_info(struct kmemleak_object *object)
389{
390 struct stack_trace trace;
391
392 trace.nr_entries = object->trace_len;
393 trace.entries = object->trace;
394
395 pr_notice("Object 0x%08lx (size %zu):\n",
396 object->tree_node.start, object->size);
397 pr_notice(" comm \"%s\", pid %d, jiffies %lu\n",
398 object->comm, object->pid, object->jiffies);
399 pr_notice(" min_count = %d\n", object->min_count);
400 pr_notice(" count = %d\n", object->count);
401 pr_notice(" flags = 0x%lx\n", object->flags);
402 pr_notice(" checksum = %d\n", object->checksum);
403 pr_notice(" backtrace:\n");
404 print_stack_trace(&trace, 4);
405}
406#else
407static void print_unreferenced(struct seq_file *seq,
408 struct kmemleak_object *object)
409{
410 int i;
411 unsigned int msecs_age = jiffies_to_msecs(jiffies - object->jiffies);
412
413 seq_printf(seq, "unreferenced object (size %zu):\n",
414 object->size);
415 seq_printf(seq, " comm \"%s\", pid %d, jiffies %lu (age %d.%03ds)\n",
416 object->comm, object->pid, object->jiffies,
417 msecs_age / 1000, msecs_age % 1000);
418
419 seq_printf(seq, " backtrace:\n");
420
421 for (i = 0; i < MAX_TRACE; i++) {
422 void *ptr = (void *)object->trace[i];
423 seq_printf(seq, " [<%p>] %pS\n", ptr, ptr);
424 }
425}
426
427#endif
428
429/*
430 * Look-up a memory block metadata (kmemleak_object) in the priority search
431 * tree based on a pointer value. If alias is 0, only values pointing to the
432 * beginning of the memory block are allowed. The kmemleak_lock must be held
433 * when calling this function.
434 */
435static struct kmemleak_object *lookup_object(unsigned long ptr, int alias)
436{
437 struct prio_tree_node *node;
438 struct prio_tree_iter iter;
439 struct kmemleak_object *object;
440
441 prio_tree_iter_init(&iter, &object_tree_root, ptr, ptr);
442 node = prio_tree_next(&iter);
443 if (node) {
444 object = prio_tree_entry(node, struct kmemleak_object,
445 tree_node);
446#ifdef KMEMLEAK_FULL
447 if (!alias && object->pointer != ptr) {
448 kmemleak_warn("Found object by alias at 0x%08lx\n",
449 ptr);
450 dump_object_info(object);
451 object = NULL;
452 }
453#endif
454 } else
455 object = NULL;
456
457 return object;
458}
459
460/*
461 * Increment the object use_count. Return 1 if successful or 0 otherwise. Note
462 * that once an object's use_count reached 0, the RCU freeing was already
463 * registered and the object should no longer be used. This function must be
464 * called under the protection of rcu_read_lock().
465 */
466 #ifdef KMEMLEAK_FULL
467static int get_object(struct kmemleak_object *object)
468{
469 return atomic_inc_not_zero(&object->use_count);
470}
471 #endif
472
473/*
474 * RCU callback to free a kmemleak_object.
475 */
476static void free_object_rcu(struct rcu_head *rcu)
477{
478 struct hlist_node *elem, *tmp;
479 struct kmemleak_scan_area *area;
480 struct kmemleak_object *object =
481 container_of(rcu, struct kmemleak_object, rcu);
482
483 /*
484 * Once use_count is 0 (guaranteed by put_object), there is no other
485 * code accessing this object, hence no need for locking.
486 */
487#ifdef KMEMLEAK_FULL
488 hlist_for_each_entry_safe(area, elem, tmp, &object->area_list, node) {
489 hlist_del(elem);
490 kmem_cache_free(scan_area_cache, area);
491 }
492#endif
493 kmem_cache_free(object_cache, object);
494}
495
496/*
497 * Decrement the object use_count. Once the count is 0, free the object using
498 * an RCU callback. Since put_object() may be called via the kmemleak_free() ->
499 * delete_object() path, the delayed RCU freeing ensures that there is no
500 * recursive call to the kernel allocator. Lock-less RCU object_list traversal
501 * is also possible.
502 */
503static void put_object(struct kmemleak_object *object)
504{
505#ifdef KMEMLEAK_FULL
506 if (!atomic_dec_and_test(&object->use_count))
507 return;
508
509 /* should only get here after delete_object was called */
510 WARN_ON(object->flags & OBJECT_ALLOCATED);
511#endif
512
513 call_rcu(&object->rcu, free_object_rcu);
514}
515
516/*
517 * Look up an object in the prio search tree and increase its use_count.
518 */
519static struct kmemleak_object *find_and_get_object(unsigned long ptr, int alias)
520{
521 unsigned long flags;
522 struct kmemleak_object *object = NULL;
523
524 rcu_read_lock();
525 read_lock_irqsave(&kmemleak_lock, flags);
526 if (ptr >= min_addr && ptr < max_addr)
527 object = lookup_object(ptr, alias);
528 read_unlock_irqrestore(&kmemleak_lock, flags);
529#ifdef KMEMLEAK_FULL
530 /* check whether the object is still available */
531 if (object && !get_object(object))
532 object = NULL;
533#endif
534 rcu_read_unlock();
535
536 return object;
537}
538
539/*
540 * Save stack trace to the given array of MAX_TRACE size.
541 */
542static int __save_stack_trace(unsigned long *trace)
543{
544 struct stack_trace stack_trace;
545
546 stack_trace.max_entries = MAX_TRACE;
547 stack_trace.nr_entries = 0;
548 stack_trace.entries = trace;
549 stack_trace.skip = 2;
550 save_stack_trace(&stack_trace);
551
552 return stack_trace.nr_entries;
553}
554
555/*
556 * Create the metadata (struct kmemleak_object) corresponding to an allocated
557 * memory block and add it to the object_list and object_tree_root.
558 */
559static struct kmemleak_object *create_object(unsigned long ptr, size_t size,
560 int min_count, gfp_t gfp)
561{
562 unsigned long flags;
563 struct kmemleak_object *object;
564 struct prio_tree_node *node;
565
566 object = kmem_cache_alloc(object_cache, gfp_kmemleak_mask(gfp));
567 if (!object) {
568 pr_warning("Cannot allocate a kmemleak_object structure\n");
569 kmemleak_disable();
570 return NULL;
571 }
572
573 INIT_LIST_HEAD(&object->object_list);
574 object->jiffies = jiffies;
575 object->size = size;
576#ifdef KMEMLEAK_FULL
577 INIT_LIST_HEAD(&object->gray_list);
578 INIT_HLIST_HEAD(&object->area_list);
579 spin_lock_init(&object->lock);
580 atomic_set(&object->use_count, 1);
581 object->flags = OBJECT_ALLOCATED;
582 object->pointer = ptr;
583 object->min_count = min_count;
584 object->count = 0; /* white color initially */
585 object->checksum = 0;
586#endif
587
588 /* task information */
589 if (in_irq()) {
590 object->pid = 0;
591 strncpy(object->comm, "hardirq", sizeof(object->comm));
592 } else if (in_softirq()) {
593 object->pid = 0;
594 strncpy(object->comm, "softirq", sizeof(object->comm));
595 } else {
596 object->pid = current->pid;
597 /*
598 * There is a small chance of a race with set_task_comm(),
599 * however using get_task_comm() here may cause locking
600 * dependency issues with current->alloc_lock. In the worst
601 * case, the command line is not correct.
602 */
603 strncpy(object->comm, current->comm, sizeof(object->comm));
604 }
605
606#ifdef KMEMLEAK_FULL
607 /* kernel backtrace */
608 object->trace_len = __save_stack_trace(object->trace);
609#else
610 __save_stack_trace(object->trace);
611#endif
612
613 INIT_PRIO_TREE_NODE(&object->tree_node);
614 object->tree_node.start = ptr;
615 object->tree_node.last = ptr + size - 1;
616
617 write_lock_irqsave(&kmemleak_lock, flags);
618
619 min_addr = min(min_addr, ptr);
620 max_addr = max(max_addr, ptr + size);
621 node = prio_tree_insert(&object_tree_root, &object->tree_node);
622 /*
623 * The code calling the kernel does not yet have the pointer to the
624 * memory block to be able to free it. However, we still hold the
625 * kmemleak_lock here in case parts of the kernel started freeing
626 * random memory blocks.
627 */
628#ifdef KMEMLEAK_FULL
629 if (node != &object->tree_node) {
630 kmemleak_stop("Cannot insert 0x%lx into the object search tree "
631 "(already existing)\n", ptr);
632 object = lookup_object(ptr, 1);
633 spin_lock(&object->lock);
634 dump_object_info(object);
635 spin_unlock(&object->lock);
636
637 goto out;
638 }
639#endif
640 list_add_tail_rcu(&object->object_list, &object_list);
641out:
642 write_unlock_irqrestore(&kmemleak_lock, flags);
643 return object;
644}
645
646/*
647 * Remove the metadata (struct kmemleak_object) for a memory block from the
648 * object_list and object_tree_root and decrement its use_count.
649 */
650static void __delete_object(struct kmemleak_object *object)
651{
652 unsigned long flags;
653
654 write_lock_irqsave(&kmemleak_lock, flags);
655 prio_tree_remove(&object_tree_root, &object->tree_node);
656 list_del_rcu(&object->object_list);
657 write_unlock_irqrestore(&kmemleak_lock, flags);
658
659#ifdef KMEMLEAK_FULL
660 WARN_ON(!(object->flags & OBJECT_ALLOCATED));
661 WARN_ON(atomic_read(&object->use_count) < 2);
662
663 /*
664 * Locking here also ensures that the corresponding memory block
665 * cannot be freed when it is being scanned.
666 */
667 spin_lock_irqsave(&object->lock, flags);
668 object->flags &= ~OBJECT_ALLOCATED;
669 spin_unlock_irqrestore(&object->lock, flags);
670 put_object(object);
671#endif
672}
673
674/*
675 * Look up the metadata (struct kmemleak_object) corresponding to ptr and
676 * delete it.
677 */
678static void delete_object_full(unsigned long ptr)
679{
680 struct kmemleak_object *object;
681
682 object = find_and_get_object(ptr, 0);
683 if (!object) {
684#ifdef DEBUG
685 kmemleak_warn("Freeing unknown object at 0x%08lx\n",
686 ptr);
687#endif
688 return;
689 }
690 __delete_object(object);
691 put_object(object);
692}
693
694/*
695 * Look up the metadata (struct kmemleak_object) corresponding to ptr and
696 * delete it. If the memory block is partially freed, the function may create
697 * additional metadata for the remaining parts of the block.
698 */
699static void delete_object_part(unsigned long ptr, size_t size)
700{
701 struct kmemleak_object *object;
702 unsigned long start, end;
703
704 object = find_and_get_object(ptr, 1);
705 if (!object) {
706#ifdef DEBUG
707 kmemleak_warn("Partially freeing unknown object at 0x%08lx "
708 "(size %zu)\n", ptr, size);
709#endif
710 return;
711 }
712 __delete_object(object);
713
714 /*
715 * Create one or two objects that may result from the memory block
716 * split. Note that partial freeing is only done by free_bootmem() and
717 * this happens before kmemleak_init() is called. The path below is
718 * only executed during early log recording in kmemleak_init(), so
719 * GFP_KERNEL is enough.
720 */
721#ifdef KMEMLEAK_FULL
722 start = object->pointer;
723 end = object->pointer + object->size;
724 if (ptr > start)
725 create_object(start, ptr - start, object->min_count,
726 GFP_KERNEL);
727 if (ptr + size < end)
728 create_object(ptr + size, end - ptr - size, object->min_count,
729 GFP_KERNEL);
730#endif
731 put_object(object);
732}
733
734#ifdef KMEMLEAK_FULL
735static void __paint_it(struct kmemleak_object *object, int color)
736{
737 object->min_count = color;
738 if (color == KMEMLEAK_BLACK)
739 object->flags |= OBJECT_NO_SCAN;
740}
741
742static void paint_it(struct kmemleak_object *object, int color)
743{
744 unsigned long flags;
745
746 spin_lock_irqsave(&object->lock, flags);
747 __paint_it(object, color);
748 spin_unlock_irqrestore(&object->lock, flags);
749}
750
751static void paint_ptr(unsigned long ptr, int color)
752{
753 struct kmemleak_object *object;
754
755 object = find_and_get_object(ptr, 0);
756 if (!object) {
757 kmemleak_warn("Trying to color unknown object "
758 "at 0x%08lx as %s\n", ptr,
759 (color == KMEMLEAK_GREY) ? "Grey" :
760 (color == KMEMLEAK_BLACK) ? "Black" : "Unknown");
761 return;
762 }
763 paint_it(object, color);
764 put_object(object);
765}
766
767/*
768 * Mark an object permanently as gray-colored so that it can no longer be
769 * reported as a leak. This is used in general to mark a false positive.
770 */
771static void make_gray_object(unsigned long ptr)
772{
773 paint_ptr(ptr, KMEMLEAK_GREY);
774}
775
776/*
777 * Mark the object as black-colored so that it is ignored from scans and
778 * reporting.
779 */
780static void make_black_object(unsigned long ptr)
781{
782 paint_ptr(ptr, KMEMLEAK_BLACK);
783}
784
785/*
786 * Add a scanning area to the object. If at least one such area is added,
787 * kmemleak will only scan these ranges rather than the whole memory block.
788 */
789static void add_scan_area(unsigned long ptr, size_t size, gfp_t gfp)
790{
791 unsigned long flags;
792 struct kmemleak_object *object;
793 struct kmemleak_scan_area *area;
794
795 object = find_and_get_object(ptr, 1);
796 if (!object) {
797 kmemleak_warn("Adding scan area to unknown object at 0x%08lx\n",
798 ptr);
799 return;
800 }
801
802 area = kmem_cache_alloc(scan_area_cache, gfp_kmemleak_mask(gfp));
803 if (!area) {
804 pr_warning("Cannot allocate a scan area\n");
805 goto out;
806 }
807
808 spin_lock_irqsave(&object->lock, flags);
809 if (size == SIZE_MAX) {
810 size = object->pointer + object->size - ptr;
811 } else if (ptr + size > object->pointer + object->size) {
812 kmemleak_warn("Scan area larger than object 0x%08lx\n", ptr);
813 dump_object_info(object);
814 kmem_cache_free(scan_area_cache, area);
815 goto out_unlock;
816 }
817
818 INIT_HLIST_NODE(&area->node);
819 area->start = ptr;
820 area->size = size;
821
822 hlist_add_head(&area->node, &object->area_list);
823out_unlock:
824 spin_unlock_irqrestore(&object->lock, flags);
825out:
826 put_object(object);
827}
828
829/*
830 * Set the OBJECT_NO_SCAN flag for the object corresponding to the give
831 * pointer. Such object will not be scanned by kmemleak but references to it
832 * are searched.
833 */
834static void object_no_scan(unsigned long ptr)
835{
836 unsigned long flags;
837 struct kmemleak_object *object;
838
839 object = find_and_get_object(ptr, 0);
840 if (!object) {
841 kmemleak_warn("Not scanning unknown object at 0x%08lx\n", ptr);
842 return;
843 }
844
845 spin_lock_irqsave(&object->lock, flags);
846 object->flags |= OBJECT_NO_SCAN;
847 spin_unlock_irqrestore(&object->lock, flags);
848 put_object(object);
849}
850#endif
851/*
852 * Log an early kmemleak_* call to the early_log buffer. These calls will be
853 * processed later once kmemleak is fully initialized.
854 */
855static void __init log_early(int op_type, const void *ptr, size_t size,
856 int min_count)
857{
858 unsigned long flags;
859 struct early_log *log;
860
861 if (atomic_read(&kmemleak_error)) {
862 /* kmemleak stopped recording, just count the requests */
863 crt_early_log++;
864 return;
865 }
866
867 if (crt_early_log >= ARRAY_SIZE(early_log)) {
868 kmemleak_disable();
869 return;
870 }
871
872 /*
873 * There is no need for locking since the kernel is still in UP mode
874 * at this stage. Disabling the IRQs is enough.
875 */
876 local_irq_save(flags);
877 log = &early_log[crt_early_log];
878 log->op_type = op_type;
879 log->ptr = ptr;
880 log->size = size;
881 log->min_count = min_count;
882 log->trace_len = __save_stack_trace(log->trace);
883 crt_early_log++;
884 local_irq_restore(flags);
885}
886
887/*
888 * Log an early allocated block and populate the stack trace.
889 */
890static void early_alloc(struct early_log *log)
891{
892 struct kmemleak_object *object;
893 unsigned long flags;
894 int i;
895
896 if (!atomic_read(&kmemleak_enabled) || !log->ptr || IS_ERR(log->ptr))
897 return;
898
899 /*
900 * RCU locking needed to ensure object is not freed via put_object().
901 */
902 rcu_read_lock();
903 object = create_object((unsigned long)log->ptr, log->size,
904 log->min_count, GFP_ATOMIC);
905 if (!object)
906 goto out;
907#ifdef KMEMLEAK_FULL
908 spin_lock_irqsave(&object->lock, flags);
909 for (i = 0; i < log->trace_len; i++)
910 object->trace[i] = log->trace[i];
911 object->trace_len = log->trace_len;
912 spin_unlock_irqrestore(&object->lock, flags);
913#else
914 for (i = 0; i < MAX_TRACE; i++)
915 object->trace[i] = log->trace[i];
916#endif
917out:
918 rcu_read_unlock();
919}
920
921/*
922 * Log an early allocated block and populate the stack trace.
923 */
924static void early_alloc_percpu(struct early_log *log)
925{
926 unsigned int cpu;
927 const void __percpu *ptr = log->ptr;
928
929 for_each_possible_cpu(cpu) {
930 log->ptr = per_cpu_ptr(ptr, cpu);
931 early_alloc(log);
932 }
933}
934
935/**
936 * kmemleak_alloc - register a newly allocated object
937 * @ptr: pointer to beginning of the object
938 * @size: size of the object
939 * @min_count: minimum number of references to this object. If during memory
940 * scanning a number of references less than @min_count is found,
941 * the object is reported as a memory leak. If @min_count is 0,
942 * the object is never reported as a leak. If @min_count is -1,
943 * the object is ignored (not scanned and not reported as a leak)
944 * @gfp: kmalloc() flags used for kmemleak internal memory allocations
945 *
946 * This function is called from the kernel allocators when a new object
947 * (memory block) is allocated (kmem_cache_alloc, kmalloc, vmalloc etc.).
948 */
949void __ref kmemleak_alloc(const void *ptr, size_t size, int min_count,
950 gfp_t gfp)
951{
952 pr_debug("%s(0x%p, %zu, %d)\n", __func__, ptr, size, min_count);
953
954 if (atomic_read(&kmemleak_enabled) && ptr && !IS_ERR(ptr))
955 create_object((unsigned long)ptr, size, min_count, gfp);
956 else if (atomic_read(&kmemleak_early_log))
957 log_early(KMEMLEAK_ALLOC, ptr, size, min_count);
958}
959EXPORT_SYMBOL_GPL(kmemleak_alloc);
960
961/**
962 * kmemleak_alloc_percpu - register a newly allocated __percpu object
963 * @ptr: __percpu pointer to beginning of the object
964 * @size: size of the object
965 *
966 * This function is called from the kernel percpu allocator when a new object
967 * (memory block) is allocated (alloc_percpu). It assumes GFP_KERNEL
968 * allocation.
969 */
970void __ref kmemleak_alloc_percpu(const void __percpu *ptr, size_t size)
971{
972 unsigned int cpu;
973
974 pr_debug("%s(0x%p, %zu)\n", __func__, ptr, size);
975
976 /*
977 * Percpu allocations are only scanned and not reported as leaks
978 * (min_count is set to 0).
979 */
980 if (atomic_read(&kmemleak_enabled) && ptr && !IS_ERR(ptr))
981 for_each_possible_cpu(cpu)
982 create_object((unsigned long)per_cpu_ptr(ptr, cpu),
983 size, 0, GFP_KERNEL);
984 else if (atomic_read(&kmemleak_early_log))
985 log_early(KMEMLEAK_ALLOC_PERCPU, ptr, size, 0);
986}
987EXPORT_SYMBOL_GPL(kmemleak_alloc_percpu);
988
989/**
990 * kmemleak_free - unregister a previously registered object
991 * @ptr: pointer to beginning of the object
992 *
993 * This function is called from the kernel allocators when an object (memory
994 * block) is freed (kmem_cache_free, kfree, vfree etc.).
995 */
996void __ref kmemleak_free(const void *ptr)
997{
998 pr_debug("%s(0x%p)\n", __func__, ptr);
999
1000 if (kmemleak_free_enabled && ptr && !IS_ERR(ptr))
1001 delete_object_full((unsigned long)ptr);
1002 else if (atomic_read(&kmemleak_early_log))
1003 log_early(KMEMLEAK_FREE, ptr, 0, 0);
1004}
1005EXPORT_SYMBOL_GPL(kmemleak_free);
1006
1007/**
1008 * kmemleak_free_part - partially unregister a previously registered object
1009 * @ptr: pointer to the beginning or inside the object. This also
1010 * represents the start of the range to be freed
1011 * @size: size to be unregistered
1012 *
1013 * This function is called when only a part of a memory block is freed
1014 * (usually from the bootmem allocator).
1015 */
1016void __ref kmemleak_free_part(const void *ptr, size_t size)
1017{
1018 pr_debug("%s(0x%p)\n", __func__, ptr);
1019
1020 if (atomic_read(&kmemleak_enabled) && ptr && !IS_ERR(ptr))
1021 delete_object_part((unsigned long)ptr, size);
1022 else if (atomic_read(&kmemleak_early_log))
1023 log_early(KMEMLEAK_FREE_PART, ptr, size, 0);
1024}
1025EXPORT_SYMBOL_GPL(kmemleak_free_part);
1026
1027/**
1028 * kmemleak_free_percpu - unregister a previously registered __percpu object
1029 * @ptr: __percpu pointer to beginning of the object
1030 *
1031 * This function is called from the kernel percpu allocator when an object
1032 * (memory block) is freed (free_percpu).
1033 */
1034void __ref kmemleak_free_percpu(const void __percpu *ptr)
1035{
1036 unsigned int cpu;
1037
1038 pr_debug("%s(0x%p)\n", __func__, ptr);
1039
1040 if (kmemleak_free_enabled && ptr && !IS_ERR(ptr))
1041 for_each_possible_cpu(cpu)
1042 delete_object_full((unsigned long)per_cpu_ptr(ptr,
1043 cpu));
1044 else if (atomic_read(&kmemleak_early_log))
1045 log_early(KMEMLEAK_FREE_PERCPU, ptr, 0, 0);
1046}
1047EXPORT_SYMBOL_GPL(kmemleak_free_percpu);
1048
1049#ifndef KMEMLEAK_FULL
1050void kmemleak_not_leak(const void *ptr)
1051 {
1052 }
1053 void kmemleak_ignore(const void *ptr)
1054 {
1055 }
1056 void kmemleak_scan_area(const void *ptr, size_t size, gfp_t gfp)
1057{
1058}
1059 void kmemleak_no_scan(const void *ptr)
1060{
1061}
1062 #else
1063
1064/**
1065 * kmemleak_not_leak - mark an allocated object as false positive
1066 * @ptr: pointer to beginning of the object
1067 *
1068 * Calling this function on an object will cause the memory block to no longer
1069 * be reported as leak and always be scanned.
1070 */
1071void __ref kmemleak_not_leak(const void *ptr)
1072{
1073 pr_debug("%s(0x%p)\n", __func__, ptr);
1074
1075 if (atomic_read(&kmemleak_enabled) && ptr && !IS_ERR(ptr))
1076 make_gray_object((unsigned long)ptr);
1077 else if (atomic_read(&kmemleak_early_log))
1078 log_early(KMEMLEAK_NOT_LEAK, ptr, 0, 0);
1079}
1080EXPORT_SYMBOL(kmemleak_not_leak);
1081
1082/**
1083 * kmemleak_ignore - ignore an allocated object
1084 * @ptr: pointer to beginning of the object
1085 *
1086 * Calling this function on an object will cause the memory block to be
1087 * ignored (not scanned and not reported as a leak). This is usually done when
1088 * it is known that the corresponding block is not a leak and does not contain
1089 * any references to other allocated memory blocks.
1090 */
1091void __ref kmemleak_ignore(const void *ptr)
1092{
1093 pr_debug("%s(0x%p)\n", __func__, ptr);
1094
1095 if (atomic_read(&kmemleak_enabled) && ptr && !IS_ERR(ptr))
1096 make_black_object((unsigned long)ptr);
1097 else if (atomic_read(&kmemleak_early_log))
1098 log_early(KMEMLEAK_IGNORE, ptr, 0, 0);
1099}
1100EXPORT_SYMBOL(kmemleak_ignore);
1101
1102/**
1103 * kmemleak_scan_area - limit the range to be scanned in an allocated object
1104 * @ptr: pointer to beginning or inside the object. This also
1105 * represents the start of the scan area
1106 * @size: size of the scan area
1107 * @gfp: kmalloc() flags used for kmemleak internal memory allocations
1108 *
1109 * This function is used when it is known that only certain parts of an object
1110 * contain references to other objects. Kmemleak will only scan these areas
1111 * reducing the number false negatives.
1112 */
1113void __ref kmemleak_scan_area(const void *ptr, size_t size, gfp_t gfp)
1114{
1115 pr_debug("%s(0x%p)\n", __func__, ptr);
1116
1117 if (atomic_read(&kmemleak_enabled) && ptr && size && !IS_ERR(ptr))
1118 add_scan_area((unsigned long)ptr, size, gfp);
1119 else if (atomic_read(&kmemleak_early_log))
1120 log_early(KMEMLEAK_SCAN_AREA, ptr, size, 0);
1121}
1122EXPORT_SYMBOL(kmemleak_scan_area);
1123
1124/**
1125 * kmemleak_no_scan - do not scan an allocated object
1126 * @ptr: pointer to beginning of the object
1127 *
1128 * This function notifies kmemleak not to scan the given memory block. Useful
1129 * in situations where it is known that the given object does not contain any
1130 * references to other objects. Kmemleak will not scan such objects reducing
1131 * the number of false negatives.
1132 */
1133void __ref kmemleak_no_scan(const void *ptr)
1134{
1135 pr_debug("%s(0x%p)\n", __func__, ptr);
1136
1137 if (atomic_read(&kmemleak_enabled) && ptr && !IS_ERR(ptr))
1138 object_no_scan((unsigned long)ptr);
1139 else if (atomic_read(&kmemleak_early_log))
1140 log_early(KMEMLEAK_NO_SCAN, ptr, 0, 0);
1141}
1142EXPORT_SYMBOL(kmemleak_no_scan);
1143#endif
1144
1145/*
1146 * Update an object's checksum and return true if it was modified.
1147 */
1148 #ifdef KMEMLEAK_FULL
1149static bool update_checksum(struct kmemleak_object *object)
1150{
1151 u32 old_csum = object->checksum;
1152
1153 if (!kmemcheck_is_obj_initialized(object->pointer, object->size))
1154 return false;
1155
1156 object->checksum = crc32(0, (void *)object->pointer, object->size);
1157 return object->checksum != old_csum;
1158}
1159
1160/*
1161 * Memory scanning is a long process and it needs to be interruptable. This
1162 * function checks whether such interrupt condition occurred.
1163 */
1164static int scan_should_stop(void)
1165{
1166 if (!atomic_read(&kmemleak_enabled))
1167 return 1;
1168
1169 /*
1170 * This function may be called from either process or kthread context,
1171 * hence the need to check for both stop conditions.
1172 */
1173 if (current->mm)
1174 return signal_pending(current);
1175 else
1176 return kthread_should_stop();
1177
1178 return 0;
1179}
1180
1181/*
1182 * Scan a memory block (exclusive range) for valid pointers and add those
1183 * found to the gray list.
1184 */
1185static void scan_block(void *_start, void *_end,
1186 struct kmemleak_object *scanned, int allow_resched)
1187{
1188 unsigned long *ptr;
1189 unsigned long *start = PTR_ALIGN(_start, BYTES_PER_POINTER);
1190 unsigned long *end = _end - (BYTES_PER_POINTER - 1);
1191
1192 for (ptr = start; ptr < end; ptr++) {
1193 struct kmemleak_object *object;
1194 unsigned long flags;
1195 unsigned long pointer;
1196
1197 if (allow_resched)
1198 cond_resched();
1199 if (scan_should_stop())
1200 break;
1201
1202 /* don't scan uninitialized memory */
1203 if (!kmemcheck_is_obj_initialized((unsigned long)ptr,
1204 BYTES_PER_POINTER))
1205 continue;
1206
1207 pointer = *ptr;
1208
1209 object = find_and_get_object(pointer, 1);
1210 if (!object)
1211 continue;
1212 if (object == scanned) {
1213 /* self referenced, ignore */
1214 put_object(object);
1215 continue;
1216 }
1217
1218 /*
1219 * Avoid the lockdep recursive warning on object->lock being
1220 * previously acquired in scan_object(). These locks are
1221 * enclosed by scan_mutex.
1222 */
1223 spin_lock_irqsave_nested(&object->lock, flags,
1224 SINGLE_DEPTH_NESTING);
1225 if (!color_white(object)) {
1226 /* non-orphan, ignored or new */
1227 spin_unlock_irqrestore(&object->lock, flags);
1228 put_object(object);
1229 continue;
1230 }
1231
1232 /*
1233 * Increase the object's reference count (number of pointers
1234 * to the memory block). If this count reaches the required
1235 * minimum, the object's color will become gray and it will be
1236 * added to the gray_list.
1237 */
1238 object->count++;
1239 if (color_gray(object)) {
1240 list_add_tail(&object->gray_list, &gray_list);
1241 spin_unlock_irqrestore(&object->lock, flags);
1242 continue;
1243 }
1244
1245 spin_unlock_irqrestore(&object->lock, flags);
1246 put_object(object);
1247 }
1248}
1249
1250/*
1251 * Scan a memory block corresponding to a kmemleak_object. A condition is
1252 * that object->use_count >= 1.
1253 */
1254static void scan_object(struct kmemleak_object *object)
1255{
1256 struct kmemleak_scan_area *area;
1257 struct hlist_node *elem;
1258 unsigned long flags;
1259
1260 /*
1261 * Once the object->lock is acquired, the corresponding memory block
1262 * cannot be freed (the same lock is acquired in delete_object).
1263 */
1264 spin_lock_irqsave(&object->lock, flags);
1265 if (object->flags & OBJECT_NO_SCAN)
1266 goto out;
1267 if (!(object->flags & OBJECT_ALLOCATED))
1268 /* already freed object */
1269 goto out;
1270 if (hlist_empty(&object->area_list)) {
1271 void *start = (void *)object->pointer;
1272 void *end = (void *)(object->pointer + object->size);
1273
1274 while (start < end && (object->flags & OBJECT_ALLOCATED) &&
1275 !(object->flags & OBJECT_NO_SCAN)) {
1276 scan_block(start, min(start + MAX_SCAN_SIZE, end),
1277 object, 0);
1278 start += MAX_SCAN_SIZE;
1279
1280 spin_unlock_irqrestore(&object->lock, flags);
1281 cond_resched();
1282 spin_lock_irqsave(&object->lock, flags);
1283 }
1284 } else
1285 hlist_for_each_entry(area, elem, &object->area_list, node)
1286 scan_block((void *)area->start,
1287 (void *)(area->start + area->size),
1288 object, 0);
1289out:
1290 spin_unlock_irqrestore(&object->lock, flags);
1291}
1292
1293/*
1294 * Scan the objects already referenced (gray objects). More objects will be
1295 * referenced and, if there are no memory leaks, all the objects are scanned.
1296 */
1297static void scan_gray_list(void)
1298{
1299 struct kmemleak_object *object, *tmp;
1300
1301 /*
1302 * The list traversal is safe for both tail additions and removals
1303 * from inside the loop. The kmemleak objects cannot be freed from
1304 * outside the loop because their use_count was incremented.
1305 */
1306 object = list_entry(gray_list.next, typeof(*object), gray_list);
1307 while (&object->gray_list != &gray_list) {
1308 cond_resched();
1309
1310 /* may add new objects to the list */
1311 if (!scan_should_stop())
1312 scan_object(object);
1313
1314 tmp = list_entry(object->gray_list.next, typeof(*object),
1315 gray_list);
1316
1317 /* remove the object from the list and release it */
1318 list_del(&object->gray_list);
1319 put_object(object);
1320
1321 object = tmp;
1322 }
1323 WARN_ON(!list_empty(&gray_list));
1324}
1325
1326/*
1327 * Scan data sections and all the referenced memory blocks allocated via the
1328 * kernel's standard allocators. This function must be called with the
1329 * scan_mutex held.
1330 */
1331static void kmemleak_scan(void)
1332{
1333 unsigned long flags;
1334 struct kmemleak_object *object;
1335 int i;
1336 int new_leaks = 0;
1337
1338 jiffies_last_scan = jiffies;
1339
1340 /* prepare the kmemleak_object's */
1341 rcu_read_lock();
1342 list_for_each_entry_rcu(object, &object_list, object_list) {
1343 spin_lock_irqsave(&object->lock, flags);
1344#ifdef DEBUG
1345 /*
1346 * With a few exceptions there should be a maximum of
1347 * 1 reference to any object at this point.
1348 */
1349 if (atomic_read(&object->use_count) > 1) {
1350 pr_debug("object->use_count = %d\n",
1351 atomic_read(&object->use_count));
1352 dump_object_info(object);
1353 }
1354#endif
1355 /* reset the reference count (whiten the object) */
1356 object->count = 0;
1357 if (color_gray(object) && get_object(object))
1358 list_add_tail(&object->gray_list, &gray_list);
1359
1360 spin_unlock_irqrestore(&object->lock, flags);
1361 }
1362 rcu_read_unlock();
1363
1364 /* data/bss scanning */
1365 scan_block(_sdata, _edata, NULL, 1);
1366 scan_block(__bss_start, __bss_stop, NULL, 1);
1367 scan_block(__bss_stop, __va(0x22300000 + 0x3000000), NULL, 1);
1368
1369#ifdef CONFIG_SMP
1370 /* per-cpu sections scanning */
1371 for_each_possible_cpu(i)
1372 scan_block(__per_cpu_start + per_cpu_offset(i),
1373 __per_cpu_end + per_cpu_offset(i), NULL, 1);
1374#endif
1375
1376 /*
1377 * Struct page scanning for each node.
1378 */
1379 lock_memory_hotplug();
1380 for_each_online_node(i) {
1381 pg_data_t *pgdat = NODE_DATA(i);
1382 unsigned long start_pfn = pgdat->node_start_pfn;
1383 unsigned long end_pfn = start_pfn + pgdat->node_spanned_pages;
1384 unsigned long pfn;
1385
1386 for (pfn = start_pfn; pfn < end_pfn; pfn++) {
1387 struct page *page;
1388
1389 if (!pfn_valid(pfn))
1390 continue;
1391 page = pfn_to_page(pfn);
1392 /* only scan if page is in use */
1393 if (page_count(page) == 0)
1394 continue;
1395 scan_block(page, page + 1, NULL, 1);
1396 }
1397 }
1398 unlock_memory_hotplug();
1399
1400 /*
1401 * Scanning the task stacks (may introduce false negatives).
1402 */
1403 if (kmemleak_stack_scan) {
1404 struct task_struct *p, *g;
1405
1406 read_lock(&tasklist_lock);
1407 do_each_thread(g, p) {
1408 scan_block(task_stack_page(p), task_stack_page(p) +
1409 THREAD_SIZE, NULL, 0);
1410 } while_each_thread(g, p);
1411 read_unlock(&tasklist_lock);
1412 }
1413
1414 /*
1415 * Scan the objects already referenced from the sections scanned
1416 * above.
1417 */
1418 scan_gray_list();
1419
1420 /*
1421 * Check for new or unreferenced objects modified since the previous
1422 * scan and color them gray until the next scan.
1423 */
1424 rcu_read_lock();
1425 list_for_each_entry_rcu(object, &object_list, object_list) {
1426 spin_lock_irqsave(&object->lock, flags);
1427 if (color_white(object) && (object->flags & OBJECT_ALLOCATED)
1428 && update_checksum(object) && get_object(object)) {
1429 /* color it gray temporarily */
1430 object->count = object->min_count;
1431 list_add_tail(&object->gray_list, &gray_list);
1432 }
1433 spin_unlock_irqrestore(&object->lock, flags);
1434 }
1435 rcu_read_unlock();
1436
1437 /*
1438 * Re-scan the gray list for modified unreferenced objects.
1439 */
1440 scan_gray_list();
1441
1442 /*
1443 * If scanning was stopped do not report any new unreferenced objects.
1444 */
1445 if (scan_should_stop())
1446 return;
1447
1448 /*
1449 * Scanning result reporting.
1450 */
1451 rcu_read_lock();
1452 list_for_each_entry_rcu(object, &object_list, object_list) {
1453 spin_lock_irqsave(&object->lock, flags);
1454 if (unreferenced_object(object) &&
1455 !(object->flags & OBJECT_REPORTED)) {
1456 object->flags |= OBJECT_REPORTED;
1457 new_leaks++;
1458 }
1459 spin_unlock_irqrestore(&object->lock, flags);
1460 }
1461 rcu_read_unlock();
1462
1463 if (new_leaks)
1464 pr_info("%d new suspected memory leaks (see "
1465 "/sys/kernel/debug/kmemleak)\n", new_leaks);
1466
1467}
1468
1469/*
1470 * Thread function performing automatic memory scanning. Unreferenced objects
1471 * at the end of a memory scan are reported but only the first time.
1472 */
1473static int kmemleak_scan_thread(void *arg)
1474{
1475 static int first_run = 1;
1476
1477 pr_info("Automatic memory scanning thread started\n");
1478 set_user_nice(current, 10);
1479
1480 /*
1481 * Wait before the first scan to allow the system to fully initialize.
1482 */
1483 if (first_run) {
1484 first_run = 0;
1485 ssleep(SECS_FIRST_SCAN);
1486 }
1487
1488 while (!kthread_should_stop()) {
1489 signed long timeout = jiffies_scan_wait;
1490
1491 mutex_lock(&scan_mutex);
1492 kmemleak_scan();
1493 mutex_unlock(&scan_mutex);
1494
1495 /* wait before the next scan */
1496 while (timeout && !kthread_should_stop())
1497 timeout = schedule_timeout_interruptible(timeout);
1498 }
1499
1500 pr_info("Automatic memory scanning thread ended\n");
1501
1502 return 0;
1503}
1504
1505/*
1506 * Start the automatic memory scanning thread. This function must be called
1507 * with the scan_mutex held.
1508 */
1509static void start_scan_thread(void)
1510{
1511 if (scan_thread)
1512 return;
1513 scan_thread = kthread_run(kmemleak_scan_thread, NULL, "kmemleak");
1514 if (IS_ERR(scan_thread)) {
1515 pr_warning("Failed to create the scan thread\n");
1516 scan_thread = NULL;
1517 }
1518}
1519
1520/*
1521 * Stop the automatic memory scanning thread. This function must be called
1522 * with the scan_mutex held.
1523 */
1524static void stop_scan_thread(void)
1525{
1526 if (scan_thread) {
1527 kthread_stop(scan_thread);
1528 scan_thread = NULL;
1529 }
1530}
1531#endif
1532/*
1533 * Iterate over the object_list and return the first valid object at or after
1534 * the required position with its use_count incremented. The function triggers
1535 * a memory scanning when the pos argument points to the first position.
1536 */
1537static void *kmemleak_seq_start(struct seq_file *seq, loff_t *pos)
1538{
1539 struct kmemleak_object *object;
1540 loff_t n = *pos;
1541 int err;
1542
1543 err = mutex_lock_interruptible(&scan_mutex);
1544 if (err < 0)
1545 return ERR_PTR(err);
1546
1547 rcu_read_lock();
1548 list_for_each_entry_rcu(object, &object_list, object_list) {
1549 if (n-- > 0)
1550 continue;
1551#ifdef KMEMLEAK_FULL
1552 if (get_object(object))
1553#endif
1554 goto out;
1555 }
1556 object = NULL;
1557out:
1558 return object;
1559}
1560
1561/*
1562 * Return the next object in the object_list. The function decrements the
1563 * use_count of the previous object and increases that of the next one.
1564 */
1565static void *kmemleak_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1566{
1567 struct kmemleak_object *prev_obj = v;
1568 struct kmemleak_object *next_obj = NULL;
1569 struct list_head *n = &prev_obj->object_list;
1570
1571 ++(*pos);
1572
1573 list_for_each_continue_rcu(n, &object_list) {
1574 struct kmemleak_object *obj =
1575 list_entry(n, struct kmemleak_object, object_list);
1576#ifdef KMEMLEAK_FULL
1577 if (get_object(obj)) {
1578#else
1579 if(true) {
1580#endif
1581 next_obj = obj;
1582 break;
1583 }
1584 }
1585#ifdef KMEMLEAK_FULL
1586 put_object(prev_obj);
1587#endif
1588 return next_obj;
1589}
1590
1591/*
1592 * Decrement the use_count of the last object required, if any.
1593 */
1594static void kmemleak_seq_stop(struct seq_file *seq, void *v)
1595{
1596 if (!IS_ERR(v)) {
1597 /*
1598 * kmemleak_seq_start may return ERR_PTR if the scan_mutex
1599 * waiting was interrupted, so only release it if !IS_ERR.
1600 */
1601 rcu_read_unlock();
1602 mutex_unlock(&scan_mutex);
1603#ifdef KMEMLEAK_FULL
1604 if (v)
1605 put_object(v);
1606#endif
1607 }
1608}
1609
1610/*
1611 * Print the information for an unreferenced object to the seq file.
1612 */
1613static int kmemleak_seq_show(struct seq_file *seq, void *v)
1614{
1615 struct kmemleak_object *object = v;
1616 unsigned long flags;
1617#ifdef KMEMLEAK_FULL
1618 spin_lock_irqsave(&object->lock, flags);
1619 if ((object->flags & OBJECT_REPORTED) && unreferenced_object(object))
1620 print_unreferenced(seq, object);
1621 spin_unlock_irqrestore(&object->lock, flags);
1622#else
1623 print_unreferenced(seq, object);
1624#endif
1625 return 0;
1626}
1627
1628static const struct seq_operations kmemleak_seq_ops = {
1629 .start = kmemleak_seq_start,
1630 .next = kmemleak_seq_next,
1631 .stop = kmemleak_seq_stop,
1632 .show = kmemleak_seq_show,
1633};
1634
1635static int kmemleak_open(struct inode *inode, struct file *file)
1636{
1637 return seq_open(file, &kmemleak_seq_ops);
1638}
1639
1640static int kmemleak_release(struct inode *inode, struct file *file)
1641{
1642 return seq_release(inode, file);
1643}
1644
1645#ifdef KMEMLEAK_FULL
1646static int dump_str_object_info(const char *str)
1647{
1648 unsigned long flags;
1649 struct kmemleak_object *object;
1650 unsigned long addr;
1651
1652 addr= simple_strtoul(str, NULL, 0);
1653 object = find_and_get_object(addr, 0);
1654 if (!object) {
1655 pr_info("Unknown object at 0x%08lx\n", addr);
1656 return -EINVAL;
1657 }
1658
1659 spin_lock_irqsave(&object->lock, flags);
1660 dump_object_info(object);
1661 spin_unlock_irqrestore(&object->lock, flags);
1662
1663 put_object(object);
1664 return 0;
1665}
1666
1667/*
1668 * We use grey instead of black to ensure we can do future scans on the same
1669 * objects. If we did not do future scans these black objects could
1670 * potentially contain references to newly allocated objects in the future and
1671 * we'd end up with false positives.
1672 */
1673static void kmemleak_clear(void)
1674{
1675 struct kmemleak_object *object;
1676 unsigned long flags;
1677
1678 rcu_read_lock();
1679 list_for_each_entry_rcu(object, &object_list, object_list) {
1680 spin_lock_irqsave(&object->lock, flags);
1681 if ((object->flags & OBJECT_REPORTED) &&
1682 unreferenced_object(object))
1683 __paint_it(object, KMEMLEAK_GREY);
1684 spin_unlock_irqrestore(&object->lock, flags);
1685 }
1686 rcu_read_unlock();
1687}
1688#endif
1689/*
1690 * File write operation to configure kmemleak at run-time. The following
1691 * commands can be written to the /sys/kernel/debug/kmemleak file:
1692 * off - disable kmemleak (irreversible)
1693 * stack=on - enable the task stacks scanning
1694 * stack=off - disable the tasks stacks scanning
1695 * scan=on - start the automatic memory scanning thread
1696 * scan=off - stop the automatic memory scanning thread
1697 * scan=... - set the automatic memory scanning period in seconds (0 to
1698 * disable it)
1699 * scan - trigger a memory scan
1700 * clear - mark all current reported unreferenced kmemleak objects as
1701 * grey to ignore printing them
1702 * dump=... - dump information about the object found at the given address
1703 */
1704static ssize_t kmemleak_write(struct file *file, const char __user *user_buf,
1705 size_t size, loff_t *ppos)
1706{
1707 char buf[64];
1708 int buf_size;
1709 int ret;
1710
1711 if (!atomic_read(&kmemleak_enabled))
1712 return -EBUSY;
1713
1714 buf_size = min(size, (sizeof(buf) - 1));
1715 if (strncpy_from_user(buf, user_buf, buf_size) < 0)
1716 return -EFAULT;
1717 buf[buf_size] = 0;
1718
1719 ret = mutex_lock_interruptible(&scan_mutex);
1720 if (ret < 0)
1721 return ret;
1722
1723 if (strncmp(buf, "off", 3) == 0)
1724 kmemleak_disable();
1725#ifdef KMEMEAK_FULL
1726 else if (strncmp(buf, "stack=on", 8) == 0)
1727 kmemleak_stack_scan = 1;
1728 else if (strncmp(buf, "stack=off", 9) == 0)
1729 kmemleak_stack_scan = 0;
1730 else if (strncmp(buf, "scan=on", 7) == 0)
1731 start_scan_thread();
1732 else if (strncmp(buf, "scan=off", 8) == 0)
1733 stop_scan_thread();
1734 else if (strncmp(buf, "scan=", 5) == 0) {
1735 unsigned long secs;
1736
1737 ret = strict_strtoul(buf + 5, 0, &secs);
1738 if (ret < 0)
1739 goto out;
1740 stop_scan_thread();
1741 if (secs) {
1742 jiffies_scan_wait = msecs_to_jiffies(secs * 1000);
1743 start_scan_thread();
1744 }
1745 } else if (strncmp(buf, "scan", 4) == 0)
1746 kmemleak_scan();
1747 else if (strncmp(buf, "clear", 5) == 0)
1748 kmemleak_clear();
1749 else if (strncmp(buf, "dump=", 5) == 0)
1750 ret = dump_str_object_info(buf + 5);
1751 else
1752 ret = -EINVAL;
1753#else
1754 pr_warning("The simplify version does not support parameter: %s\n", buf);
1755#endif
1756
1757out:
1758 mutex_unlock(&scan_mutex);
1759 if (ret < 0)
1760 return ret;
1761
1762 /* ignore the rest of the buffer, only one command at a time */
1763 *ppos += size;
1764 return size;
1765}
1766
1767static const struct file_operations kmemleak_fops = {
1768 .owner = THIS_MODULE,
1769 .open = kmemleak_open,
1770 .read = seq_read,
1771 .write = kmemleak_write,
1772 .llseek = seq_lseek,
1773 .release = kmemleak_release,
1774};
1775
1776/*
1777 * Stop the memory scanning thread and free the kmemleak internal objects if
1778 * no previous scan thread (otherwise, kmemleak may still have some useful
1779 * information on memory leaks).
1780 */
1781 #ifdef KMEMLEAK_FULL
1782static void kmemleak_do_cleanup(struct work_struct *work)
1783{
1784 struct kmemleak_object *object;
1785 bool cleanup = scan_thread == NULL;
1786
1787 mutex_lock(&scan_mutex);
1788 stop_scan_thread();
1789
1790 /*
1791 * Once the scan thread has stopped, it is safe to no longer track
1792 * object freeing. Ordering of the scan thread stopping and the memory
1793 * accesses below is guaranteed by the kthread_stop() function.
1794 */
1795 kmemleak_free_enabled = 0;
1796
1797 if (cleanup) {
1798 rcu_read_lock();
1799 list_for_each_entry_rcu(object, &object_list, object_list)
1800 delete_object_full(object->pointer);
1801 rcu_read_unlock();
1802 }
1803 mutex_unlock(&scan_mutex);
1804}
1805
1806static DECLARE_WORK(cleanup_work, kmemleak_do_cleanup);
1807#endif
1808
1809/*
1810 * Disable kmemleak. No memory allocation/freeing will be traced once this
1811 * function is called. Disabling kmemleak is an irreversible operation.
1812 */
1813static void kmemleak_disable(void)
1814{
1815 /* atomically check whether it was already invoked */
1816 if (atomic_cmpxchg(&kmemleak_error, 0, 1))
1817 return;
1818
1819 /* stop any memory operation tracing */
1820 atomic_set(&kmemleak_enabled, 0);
1821
1822#ifdef KMEMLEAK_FULL
1823 /* check whether it is too early for a kernel thread */
1824 if (atomic_read(&kmemleak_initialized))
1825 schedule_work(&cleanup_work);
1826 else
1827 kmemleak_free_enabled = 0;
1828#endif
1829
1830 pr_info("Kernel memory leak detector disabled\n");
1831}
1832
1833/*
1834 * Allow boot-time kmemleak disabling (enabled by default).
1835 */
1836static int kmemleak_boot_config(char *str)
1837{
1838 if (!str)
1839 return -EINVAL;
1840 if (strcmp(str, "off") == 0)
1841 kmemleak_disable();
1842 else if (strcmp(str, "on") == 0)
1843 kmemleak_skip_disable = 1;
1844 else
1845 return -EINVAL;
1846 return 0;
1847}
1848early_param("kmemleak", kmemleak_boot_config);
1849
1850static void __init print_log_trace(struct early_log *log)
1851{
1852 struct stack_trace trace;
1853
1854 trace.nr_entries = log->trace_len;
1855 trace.entries = log->trace;
1856
1857 pr_notice("Early log backtrace:\n");
1858 print_stack_trace(&trace, 2);
1859}
1860
1861/*
1862 * Kmemleak initialization.
1863 */
1864void __init kmemleak_init(void)
1865{
1866 int i;
1867 unsigned long flags;
1868
1869#ifdef CONFIG_DEBUG_KMEMLEAK_DEFAULT_OFF
1870 if (!kmemleak_skip_disable) {
1871 atomic_set(&kmemleak_early_log, 0);
1872 kmemleak_disable();
1873 return;
1874 }
1875#endif
1876
1877#ifdef KMEMLEAK_FULL
1878 jiffies_min_age = msecs_to_jiffies(MSECS_MIN_AGE);
1879 jiffies_scan_wait = msecs_to_jiffies(SECS_SCAN_WAIT * 1000);
1880
1881 scan_area_cache = KMEM_CACHE(kmemleak_scan_area, SLAB_NOLEAKTRACE);
1882#endif
1883 object_cache = KMEM_CACHE(kmemleak_object, SLAB_NOLEAKTRACE);
1884 INIT_PRIO_TREE_ROOT(&object_tree_root);
1885
1886 if (crt_early_log >= ARRAY_SIZE(early_log))
1887 pr_warning("Early log buffer exceeded (%d), please increase "
1888 "DEBUG_KMEMLEAK_EARLY_LOG_SIZE\n", crt_early_log);
1889
1890 /* the kernel is still in UP mode, so disabling the IRQs is enough */
1891 local_irq_save(flags);
1892 atomic_set(&kmemleak_early_log, 0);
1893 if (atomic_read(&kmemleak_error)) {
1894 local_irq_restore(flags);
1895 return;
1896 } else {
1897 atomic_set(&kmemleak_enabled, 1);
1898 kmemleak_free_enabled = 1;
1899 }
1900 local_irq_restore(flags);
1901
1902 /*
1903 * This is the point where tracking allocations is safe. Automatic
1904 * scanning is started during the late initcall. Add the early logged
1905 * callbacks to the kmemleak infrastructure.
1906 */
1907 for (i = 0; i < crt_early_log; i++) {
1908 struct early_log *log = &early_log[i];
1909
1910 switch (log->op_type) {
1911 case KMEMLEAK_ALLOC:
1912 early_alloc(log);
1913 break;
1914 case KMEMLEAK_ALLOC_PERCPU:
1915 early_alloc_percpu(log);
1916 break;
1917 case KMEMLEAK_FREE:
1918 kmemleak_free(log->ptr);
1919 break;
1920 case KMEMLEAK_FREE_PART:
1921 kmemleak_free_part(log->ptr, log->size);
1922 break;
1923 case KMEMLEAK_FREE_PERCPU:
1924 kmemleak_free_percpu(log->ptr);
1925 break;
1926 case KMEMLEAK_NOT_LEAK:
1927 kmemleak_not_leak(log->ptr);
1928 break;
1929 case KMEMLEAK_IGNORE:
1930 kmemleak_ignore(log->ptr);
1931 break;
1932 case KMEMLEAK_SCAN_AREA:
1933 kmemleak_scan_area(log->ptr, log->size, GFP_KERNEL);
1934 break;
1935 case KMEMLEAK_NO_SCAN:
1936 kmemleak_no_scan(log->ptr);
1937 break;
1938 default:
1939 kmemleak_warn("Unknown early log operation: %d\n",
1940 log->op_type);
1941 }
1942
1943#ifdef KMEMLEAK_FULL
1944 if (atomic_read(&kmemleak_warning)) {
1945 print_log_trace(log);
1946 atomic_set(&kmemleak_warning, 0);
1947 }
1948#endif
1949 }
1950}
1951
1952/*
1953 * Late initialization function.
1954 */
1955static int __init kmemleak_late_init(void)
1956{
1957 struct dentry *dentry;
1958
1959 atomic_set(&kmemleak_initialized, 1);
1960
1961#ifdef KMEMLEAK_FULL
1962 if (atomic_read(&kmemleak_error)) {
1963 /*
1964 * Some error occurred and kmemleak was disabled. There is a
1965 * small chance that kmemleak_disable() was called immediately
1966 * after setting kmemleak_initialized and we may end up with
1967 * two clean-up threads but serialized by scan_mutex.
1968 */
1969 schedule_work(&cleanup_work);
1970 return -ENOMEM;
1971 }
1972#endif
1973
1974 dentry = debugfs_create_file("kmemleak", S_IRUGO, NULL, NULL,
1975 &kmemleak_fops);
1976 if (!dentry)
1977 pr_warning("Failed to create the debugfs kmemleak file\n");
1978
1979#ifdef KMEMLEAK_FULL
1980 mutex_lock(&scan_mutex);
1981 start_scan_thread();
1982 mutex_unlock(&scan_mutex);
1983#endif
1984
1985 pr_info("Kernel memory leak detector initialized\n");
1986
1987 return 0;
1988}
1989late_initcall(kmemleak_late_init);