Chinaunix首页 | 论坛 | 博客
  • 博客访问: 295510
  • 博文数量: 44
  • 博客积分: 10
  • 博客等级: 民兵
  • 技术积分: 1354
  • 用 户 组: 普通用户
  • 注册时间: 2012-04-08 15:38
个人简介

人生像是在跑马拉松,能够完赛的都是不断地坚持向前迈进;人生就是像在跑马拉松,不断调整步伐,把握好分分秒秒;人生还是像在跑马拉松,能力决定了能跑短程、半程还是全程。人生其实就是一场马拉松,坚持不懈,珍惜时间。

文章分类

分类: LINUX

2017-01-09 08:42:05

kmemleak的工作原理很简单,主要是对kmalloc()vmalloc()kmem_cache_alloc()等接口分配的内存地址空间进行跟踪,通过对其地址、空间大小、分配调用栈等信息添加到PRIO搜索树中进行管理。当有匹配的内存释放操作时,将会把跟踪的信息从kmemleak管理中移除。

通过内存扫描(包括对保存的寄存器值),如果发现某块内存在没有任何一个指针指向其起始地址或者其空间范围,那么该内存将会被判定为孤立块。因为这意味着,该内存的地址无任何途径被传递到内存释放函数中,由此可以判定该内存存在泄漏行为。

内存扫描的算法实现也很简单:

1、 将所有跟踪的内存对象标识为白色,如果经过内存扫描后,内存对象管理树中仍标志为白色的则会被判定为孤立的;

2、 自数据段以及调用栈空间开始扫描内存,检测是否内存空间数据,判断是否存在数值与kmemleakPRIO搜索树所记录的内存地址相邻近。如果查找到存在指针值指向被标记为白色的跟踪对象,那么该跟踪对象将会被添加到灰色链表中(标记为灰色);

3、 扫描完灰色链表中的对象,检查是否存在与kmemleakPRIO搜索树管理的跟踪内存地址匹配的,因为某些标记为白色的对象可能变成了灰色的并被添加到链表的末端;

4、 经过以上步骤后,仍标记为白色的对象将会被认定为孤立的,将会上报记录到/sys/kernel/debug/kmemleak文件中。

kmemleak的主要函数可以参考/linux/kmemleak.h头文件。主要有:

kmemleak_init       - initialize kmemleak

kmemleak_alloc      - notify of a memory block allocation

kmemleak_alloc_percpu   - notify of a percpu memory block allocation

kmemleak_free       - notify of a memory block freeing

kmemleak_free_part  - notify of a partial memory block freeing

kmemleak_free_percpu    - notify of a percpu memory block freeing

kmemleak_not_leak   - mark an object as not a leak

kmemleak_ignore     - do not scan or report an object as leak

kmemleak_scan_area  - add scan areas inside a memory block

kmemleak_no_scan    - do not scan a memory block

kmemleak_erase      - erase an old value in a pointer variable

kmemleak_alloc_recursive - as kmemleak_alloc but checks the recursiveness

kmemleak_free_recursive - as kmemleak_free but checks the recursiveness

可以看到kmemleak对外提供了很多定制化的接口,比如忽略某些内存不被扫描、设置某些某些内存非泄漏的等等,对于内核开发调试提供了很多便利。毕竟kmemleak对内存泄漏的判断也是粗暴的,难免可能存在误报的情况。

按照惯例,由初始化入手。kmemleak_init()函数是kmemleak的内存管理初始化函数,它管理的是被分配出去的内存信息,在start_kernel()函数中被调用。该函数具体实现:

  1. 【file:/mm/kmemcheck.c】
  2. /*
  3.  * Kmemleak initialization.
  4.  */
  5. void __init kmemleak_init(void)
  6. {
  7.     int i;
  8.     unsigned long flags;
  9.  
  10. #ifdef CONFIG_DEBUG_KMEMLEAK_DEFAULT_OFF
  11.     if (!kmemleak_skip_disable) {
  12.         atomic_set(&kmemleak_early_log, 0);
  13.         kmemleak_disable();
  14.         return;
  15.     }
  16. #endif
  17.  
  18.     jiffies_min_age = msecs_to_jiffies(MSECS_MIN_AGE);
  19.     jiffies_scan_wait = msecs_to_jiffies(SECS_SCAN_WAIT * 1000);
  20.  
  21.     object_cache = KMEM_CACHE(kmemleak_object, SLAB_NOLEAKTRACE);
  22.     scan_area_cache = KMEM_CACHE(kmemleak_scan_area, SLAB_NOLEAKTRACE);
  23.  
  24.     if (crt_early_log >= ARRAY_SIZE(early_log))
  25.         pr_warning("Early log buffer exceeded (%d), please increase "
  26.                "DEBUG_KMEMLEAK_EARLY_LOG_SIZE\n", crt_early_log);
  27.  
  28.     /* the kernel is still in UP mode, so disabling the IRQs is enough */
  29.     local_irq_save(flags);
  30.     atomic_set(&kmemleak_early_log, 0);
  31.     if (atomic_read(&kmemleak_error)) {
  32.         local_irq_restore(flags);
  33.         return;
  34.     } else
  35.         atomic_set(&kmemleak_enabled, 1);
  36.     local_irq_restore(flags);
  37.  
  38.     /*
  39.      * This is the point where tracking allocations is safe. Automatic
  40.      * scanning is started during the late initcall. Add the early logged
  41.      * callbacks to the kmemleak infrastructure.
  42.      */
  43.     for (i = 0; i < crt_early_log; i++) {
  44.         struct early_log *log = &early_log[i];
  45.  
  46.         switch (log->op_type) {
  47.         case KMEMLEAK_ALLOC:
  48.             early_alloc(log);
  49.             break;
  50.         case KMEMLEAK_ALLOC_PERCPU:
  51.             early_alloc_percpu(log);
  52.             break;
  53.         case KMEMLEAK_FREE:
  54.             kmemleak_free(log->ptr);
  55.             break;
  56.         case KMEMLEAK_FREE_PART:
  57.             kmemleak_free_part(log->ptr, log->size);
  58.             break;
  59.         case KMEMLEAK_FREE_PERCPU:
  60.             kmemleak_free_percpu(log->ptr);
  61.             break;
  62.         case KMEMLEAK_NOT_LEAK:
  63.             kmemleak_not_leak(log->ptr);
  64.             break;
  65.         case KMEMLEAK_IGNORE:
  66.             kmemleak_ignore(log->ptr);
  67.             break;
  68.         case KMEMLEAK_SCAN_AREA:
  69.             kmemleak_scan_area(log->ptr, log->size, GFP_KERNEL);
  70.             break;
  71.         case KMEMLEAK_NO_SCAN:
  72.             kmemleak_no_scan(log->ptr);
  73.             break;
  74.         default:
  75.             kmemleak_warn("Unknown early log operation: %d\n",
  76.                       log->op_type);
  77.         }
  78.  
  79.         if (atomic_read(&kmemleak_warning)) {
  80.             print_log_trace(log);
  81.             atomic_set(&kmemleak_warning, 0);
  82.         }
  83.     }
  84. }

该函数首先将jiffies_min_agejiffies_scan_wait进行初始化,其中jiffies_scan_wait表示内存泄漏时长间隔;然后创建kmemleak_objectkmemleak_scan_area结构的slab内存池;接着设置kmemleak_early_log0,表示关闭kmemleakearly log记录功能,同时检查kmemleak_error变量判断kmemleak是否发生过严重的错误,如果有的话则直接返回,否则设置kmemleak_enabled1,表示kmemleak初始化完毕开始使能;最后的for循环early_log[]数组用于处理kmemleak初始化前的early log早期跟踪信息,该信息来自log_early()的调用采集。

其中log_early()的实现:

  1. 【file:/mm/kmemcheck.c】
  2. /*
  3.  * Log an early kmemleak_* call to the early_log buffer. These calls will be
  4.  * processed later once kmemleak is fully initialized.
  5.  */
  6. static void __init log_early(int op_type, const void *ptr, size_t size,
  7.                  int min_count)
  8. {
  9.     unsigned long flags;
  10.     struct early_log *log;
  11.  
  12.     if (atomic_read(&kmemleak_error)) {
  13.         /* kmemleak stopped recording, just count the requests */
  14.         crt_early_log++;
  15.         return;
  16.     }
  17.  
  18.     if (crt_early_log >= ARRAY_SIZE(early_log)) {
  19.         kmemleak_disable();
  20.         return;
  21.     }
  22.  
  23.     /*
  24.      * There is no need for locking since the kernel is still in UP mode
  25.      * at this stage. Disabling the IRQs is enough.
  26.      */
  27.     local_irq_save(flags);
  28.     log = &early_log[crt_early_log];
  29.     log->op_type = op_type;
  30.     log->ptr = ptr;
  31.     log->size = size;
  32.     log->min_count = min_count;
  33.     log->trace_len = __save_stack_trace(log->trace);
  34.     crt_early_log++;
  35.     local_irq_restore(flags);
  36. }

该函数实现较为简单,如果kmemleak_error不为0,即kmemleak发生错误的情况下,kmemleak将停止记录early log早期跟踪信息,但仍会将crt_early_log日志信息计数递增;如果kmemleak正常的情况下,crt_early_log计数超过了early_log[]承载的信息数量的时候,将会调用kmemleak_disable()关闭kmemleak记录功能,然后返回;最后如果在能够承载信息的情况下,将当前的内存操作记录下来,记录的信息包括操作类型、内存地址、空间大小、调用栈等信息。

log_early()被调用的地方与其记录的内存操作类型相匹配。分别为:kmemleak_alloc()kmemleak_alloc_percpu()kmemleak_free()kmemleak_free_part()kmemleak_free_percpu()kmemleak_not_leak()kmemleak_ignore()kmemleak_scan_area()kmemleak_no_scan()

 对应于类型定义:

  1. 【file:/mm/kmemcheck.c】
  2. /*
  3.  * Early object allocation/freeing logging. Kmemleak is initialized after the
  4.  * kernel allocator. However, both the kernel allocator and kmemleak may
  5.  * allocate memory blocks which need to be tracked. Kmemleak defines an
  6.  * arbitrary buffer to hold the allocation/freeing information before it is
  7.  * fully initialized.
  8.  */
  9.  
  10. /* kmemleak operation type for early logging */
  11. enum {
  12.     KMEMLEAK_ALLOC,
  13.     KMEMLEAK_ALLOC_PERCPU,
  14.     KMEMLEAK_FREE,
  15.     KMEMLEAK_FREE_PART,
  16.     KMEMLEAK_FREE_PERCPU,
  17.     KMEMLEAK_NOT_LEAK,
  18.     KMEMLEAK_IGNORE,
  19.     KMEMLEAK_SCAN_AREA,
  20.     KMEMLEAK_NO_SCAN
  21. };

这里面其实看着定义也能估计个八九不离十了,它是将各操作进行记录跟踪,再在kmemleak初始化中进行匹配操作。例如某内存在KMEMLEAK_ALLOC的操作之后,如果出现KMEMLEAK_FREE对该内存的操作记录,则表明该内存已经被释放了,由此将该内存从操作记录中剔除,以达到对内存分配的管理,同时可以监控到内存泄漏的情况。

当然这都是猜想,具体的实际情况及实现,就以初始函数中的kmemleak_init()中的KMEMLEAK_ALLOCKMEMLEAK_FREE对应的分支代码调用函数early_alloc()kmemleak_free()进行求证。

先是early_alloc()函数:

  1. 【file:/mm/kmemcheck.c】
  2. /*
  3.  * Log an early allocated block and populate the stack trace.
  4.  */
  5. static void early_alloc(struct early_log *log)
  6. {
  7.     struct kmemleak_object *object;
  8.     unsigned long flags;
  9.     int i;
  10.  
  11.     if (!atomic_read(&kmemleak_enabled) || !log->ptr || IS_ERR(log->ptr))
  12.         return;
  13.  
  14.     /*
  15.      * RCU locking needed to ensure object is not freed via put_object().
  16.      */
  17.     rcu_read_lock();
  18.     object = create_object((unsigned long)log->ptr, log->size,
  19.                    log->min_count, GFP_ATOMIC);
  20.     if (!object)
  21.         goto out;
  22.     spin_lock_irqsave(&object->lock, flags);
  23.     for (i = 0; i < log->trace_len; i++)
  24.         object->trace[i] = log->trace[i];
  25.     object->trace_len = log->trace_len;
  26.     spin_unlock_irqrestore(&object->lock, flags);
  27. out:
  28.     rcu_read_unlock();
  29. }

该函数首先将判断kmemleak是否使能以及入参合法性,接着根据需要记录的信息(内存指针、大小等信息)调用create_object()函数创建kmemleak跟踪对象,然后再是将kmemleakearly log早期跟踪信息转储到object对象中,以完成内存跟踪管理。看似简单,其实这里的主要且关键的动作在create_object()函数中。

具体看一下create_object()该函数的实现:

  1. 【file:/mm/kmemcheck.c】
  2. /*
  3.  * Create the metadata (struct kmemleak_object) corresponding to an allocated
  4.  * memory block and add it to the object_list and object_tree_root.
  5.  */
  6. static struct kmemleak_object *create_object(unsigned long ptr, size_t size,
  7.                          int min_count, gfp_t gfp)
  8. {
  9.     unsigned long flags;
  10.     struct kmemleak_object *object, *parent;
  11.     struct rb_node **link, *rb_parent;
  12.  
  13.     object = kmem_cache_alloc(object_cache, gfp_kmemleak_mask(gfp));
  14.     if (!object) {
  15.         pr_warning("Cannot allocate a kmemleak_object structure\n");
  16.         kmemleak_disable();
  17.         return NULL;
  18.     }
  19.  
  20.     INIT_LIST_HEAD(&object->object_list);
  21.     INIT_LIST_HEAD(&object->gray_list);
  22.     INIT_HLIST_HEAD(&object->area_list);
  23.     spin_lock_init(&object->lock);
  24.     atomic_set(&object->use_count, 1);
  25.     object->flags = OBJECT_ALLOCATED;
  26.     object->pointer = ptr;
  27.     object->size = size;
  28.     object->min_count = min_count;
  29.     object->count = 0; /* white color initially */
  30.     object->jiffies = jiffies;
  31.     object->checksum = 0;
  32.  
  33.     /* task information */
  34.     if (in_irq()) {
  35.         object->pid = 0;
  36.         strncpy(object->comm, "hardirq", sizeof(object->comm));
  37.     } else if (in_softirq()) {
  38.         object->pid = 0;
  39.         strncpy(object->comm, "softirq", sizeof(object->comm));
  40.     } else {
  41.         object->pid = current->pid;
  42.         /*
  43.          * There is a small chance of a race with set_task_comm(),
  44.          * however using get_task_comm() here may cause locking
  45.          * dependency issues with current->alloc_lock. In the worst
  46.          * case, the command line is not correct.
  47.          */
  48.         strncpy(object->comm, current->comm, sizeof(object->comm));
  49.     }
  50.  
  51.     /* kernel backtrace */
  52.     object->trace_len = __save_stack_trace(object->trace);
  53.  
  54.     write_lock_irqsave(&kmemleak_lock, flags);
  55.  
  56.     min_addr = min(min_addr, ptr);
  57.     max_addr = max(max_addr, ptr + size);
  58.     link = &object_tree_root.rb_node;
  59.     rb_parent = NULL;
  60.     while (*link) {
  61.         rb_parent = *link;
  62.         parent = rb_entry(rb_parent, struct kmemleak_object, rb_node);
  63.         if (ptr + size <= parent->pointer)
  64.             link = &parent->rb_node.rb_left;
  65.         else if (parent->pointer + parent->size <= ptr)
  66.             link = &parent->rb_node.rb_right;
  67.         else {
  68.             kmemleak_stop("Cannot insert 0x%lx into the object "
  69.                       "search tree (overlaps existing)\n",
  70.                       ptr);
  71.             kmem_cache_free(object_cache, object);
  72.             object = parent;
  73.             spin_lock(&object->lock);
  74.             dump_object_info(object);
  75.             spin_unlock(&object->lock);
  76.             goto out;
  77.         }
  78.     }
  79.     rb_link_node(&object->rb_node, rb_parent, link);
  80.     rb_insert_color(&object->rb_node, &object_tree_root);
  81.  
  82.     list_add_tail_rcu(&object->object_list, &object_list);
  83. out:
  84.     write_unlock_irqrestore(&kmemleak_lock, flags);
  85.     return object;
  86. }

函数中首先通过kmem_cache_alloc申请一个kmemleak_object结构的slab对象object,继而将该结构各成员数据进行初始化,包括记录内存地址、空间大小、当前时间jiffies、调用栈等(这里虽然记录了调用栈,实际上在early_alloc()函数中,会被early log早期跟踪信息所记载的调用栈覆盖),接着将会根据地址空间所在的位置进行管理挂入到object_tree_root红黑树中,最后还将通过list_add_tail_rcu()函数把object挂接到object_list链表中(这里采用的是二重管理方式)。具体的红黑树算法以后有机会再细化分析,当前暂且记着。

内存跟踪的object的结构定义需要进入分析一下,这里有些点会影响后面对代码的理解:

  1. 【file:/mm/kmemcheck.c】
  2. /*
  3.  * Structure holding the metadata for each allocated memory block.
  4.  * Modifications to such objects should be made while holding the
  5.  * object->lock. Insertions or deletions from object_list, gray_list or
  6.  * rb_node are already protected by the corresponding locks or mutex (see
  7.  * the notes on locking above). These objects are reference-counted
  8.  * (use_count) and freed using the RCU mechanism.
  9.  */
  10. struct kmemleak_object {
  11.     spinlock_t lock; /* 结构原子锁 */
  12.     unsigned long flags; /* object status flags */
  13.     struct list_head object_list; /* 挂接到object_list链表的成员 */
  14.     struct list_head gray_list; /* 挂接到gray_list链表的成员 */
  15.     struct rb_node rb_node; /* 挂接到红黑树的成员 */
  16.     struct rcu_head rcu; /* object_list lockless traversal */
  17.     /* object usage count; object freed when use_count == 0 */
  18.     atomic_t use_count; /* 该object的使用计数,如果为0时释放该object */
  19.     unsigned long pointer; /* 跟踪的内存空间地址指针 */
  20.     size_t size; /* 内存空间大小 */
  21.     /* minimum number of a pointers found before it is considered leak */
  22.     int min_count; /* 该内存对象地址最少可被找到的数量 */
  23.     /* the total number of pointers found pointing to this object */
  24.     int count; /* 找到指向该内存对象的数量 */
  25.     /* checksum for detecting modified objects */
  26.     u32 checksum; /* 跟踪内存空间数据的checksum校验码 */
  27.     /* memory ranges to be scanned inside an object (empty for all) */
  28.     struct hlist_head area_list;
  29.     unsigned long trace[MAX_TRACE]; /* 被跟踪内存的申请调用栈 */
  30.     unsigned int trace_len; /* 调用栈深度 */
  31.     unsigned long jiffies; /* creation timestamp */
  32.     pid_t pid; /* pid of the current task */
  33.     char comm[TASK_COMM_LEN]; /* executable name */
  34. };

从前面kmemleak的扫描算法描述中可以看到内存跟踪的object会被染色标记的,染色的依据主要是countmin_count。此外颜色则不仅有算法中提及的两种,实际上存在三种颜色:白色、灰色和黑色。

白色

内存处于孤立或者没有足够的指向引用(count < min_count);

灰色

内存不处于孤立、没有标识为屏蔽的(min_count == 0)或者有足够的指向引用(count >= min_count);

黑色

设置为忽略的内存(kmemleak_ignore()设置的),不包含引用的内存(例如代码文本段)(min_count == -1),由于非动态分配,所以没有泄漏的嫌疑。没有什么特别的功能应用是定义为该颜色的。

其中新创建的内存跟踪object在下次内存扫描将他们标记为白色之前,不会被标记为任何颜色。

往下分析一下KMEMLEAK_FREE对应的kmemleak_free()实现。该函数实现:

  1. 【file:/mm/kmemcheck.c】
  2. /**
  3.  * kmemleak_free - unregister a previously registered object
  4.  * @ptr: pointer to beginning of the object
  5.  *
  6.  * This function is called from the kernel allocators when an object (memory
  7.  * block) is freed (kmem_cache_free, kfree, vfree etc.).
  8.  */
  9. void __ref kmemleak_free(const void *ptr)
  10. {
  11.     pr_debug("%s(0x%p)\n", __func__, ptr);
  12.  
  13.     if (atomic_read(&kmemleak_enabled) && ptr && !IS_ERR(ptr))
  14.         delete_object_full((unsigned long)ptr);
  15.     else if (atomic_read(&kmemleak_early_log))
  16.         log_early(KMEMLEAK_FREE, ptr, 0, 0);
  17. }

该函数较为简单,里面就两个条件分支。首先是判断kmemleak是否已经使能,如果已经使能的情况下,将会调用delete_object_part()进行对象删除操作;否则将会判断是否处于early log早期跟踪信息记录阶段,继而使用log_early()记录下当前的操作。

具体分析一下delete_object_part()的实现:

  1. 【file:/mm/kmemcheck.c】
  2. /*
  3.  * Look up the metadata (struct kmemleak_object) corresponding to ptr and
  4.  * delete it. If the memory block is partially freed, the function may create
  5.  * additional metadata for the remaining parts of the block.
  6.  */
  7. static void delete_object_part(unsigned long ptr, size_t size)
  8. {
  9.     struct kmemleak_object *object;
  10.     unsigned long start, end;
  11.  
  12.     object = find_and_get_object(ptr, 1);
  13.     if (!object) {
  14. #ifdef DEBUG
  15.         kmemleak_warn("Partially freeing unknown object at 0x%08lx "
  16.                   "(size %zu)\n", ptr, size);
  17. #endif
  18.         return;
  19.     }
  20.     __delete_object(object);
  21.  
  22.     /*
  23.      * Create one or two objects that may result from the memory block
  24.      * split. Note that partial freeing is only done by free_bootmem() and
  25.      * this happens before kmemleak_init() is called. The path below is
  26.      * only executed during early log recording in kmemleak_init(), so
  27.      * GFP_KERNEL is enough.
  28.      */
  29.     start = object->pointer;
  30.     end = object->pointer + object->size;
  31.     if (ptr > start)
  32.         create_object(start, ptr - start, object->min_count,
  33.                   GFP_KERNEL);
  34.     if (ptr + size < end)
  35.         create_object(ptr + size, end - ptr - size, object->min_count,
  36.                   GFP_KERNEL);
  37.  
  38.     put_object(object);
  39. }

正如所料,该函数先是根据操作的内存地址通过find_and_get_object()查找到该内存跟踪的信息记录object,继而使用__delete_object()将对象删除;再往下的则是针对free_bootmem()对于部分内存的释放操作,所引起的内存分片后的后续跟踪管理,实现也不复杂,就是判断其释放的空间处于什么位置,剩余的空间是怎样分布的,通过create_object()将其管理起来而已;而末尾的put_object()只是将object释放后的收尾处理,包括计数的自减,同时判断该object的使用计数use_count是否为0,如果是的情况下,将会判定该object需要释放,并添加到RCU队列中。

至此,基本上也清楚了kmemleak对内存泄漏跟踪管理的模式了。虽然前面的分析也仅是针对kmemleak内存管理初始化kmemleak_init()实现的一个延伸扩展而已,但是实际上回归到正常的内存分配释放中,常用的kmemleak跟踪函数kmemleak_alloc()kmemleak_free()kmemleak_free()就已经在前面分析过了,而kmemleak_alloc()的实现则和它极为相似:

  1. 【file:/mm/kmemcheck.c】
  2. /**
  3.  * kmemleak_alloc - register a newly allocated object
  4.  * @ptr: pointer to beginning of the object
  5.  * @size: size of the object
  6.  * @min_count: minimum number of references to this object. If during memory
  7.  * scanning a number of references less than @min_count is found,
  8.  * the object is reported as a memory leak. If @min_count is 0,
  9.  * the object is never reported as a leak. If @min_count is -1,
  10.  * the object is ignored (not scanned and not reported as a leak)
  11.  * @gfp: kmalloc() flags used for kmemleak internal memory allocations
  12.  *
  13.  * This function is called from the kernel allocators when a new object
  14.  * (memory block) is allocated (kmem_cache_alloc, kmalloc, vmalloc etc.).
  15.  */
  16. void __ref kmemleak_alloc(const void *ptr, size_t size, int min_count,
  17.               gfp_t gfp)
  18. {
  19.     pr_debug("%s(0x%p, %zu, %d)\n", __func__, ptr, size, min_count);
  20.  
  21.     if (atomic_read(&kmemleak_enabled) && ptr && !IS_ERR(ptr))
  22.         create_object((unsigned long)ptr, size, min_count, gfp);
  23.     else if (atomic_read(&kmemleak_early_log))
  24.         log_early(KMEMLEAK_ALLOC, ptr, size, min_count);
  25. }

同样两个条件分支,kmemleak内存管理初始化后和初始化前的差异处理而已。

所以至此,已经对kmemleak的内存管理初始化及内存管理的实现已经分析完毕,接下来分析一下其如何实现内存泄漏检测的功能。其实这里还涉及到kmemleak的一处初始化,这里初始化的是kmemleak检测泄漏的功能主体(kmemleak_init()初始化的是内存管理),函数入口为kmemleak_late_init(),具体实现:

  1. 【file:/mm/kmemcheck.c】
  2. /*
  3.  * Late initialization function.
  4.  */
  5. static int __init kmemleak_late_init(void)
  6. {
  7.     struct dentry *dentry;
  8.  
  9.     atomic_set(&kmemleak_initialized, 1);
  10.  
  11.     if (atomic_read(&kmemleak_error)) {
  12.         /*
  13.          * Some error occurred and kmemleak was disabled. There is a
  14.          * small chance that kmemleak_disable() was called immediately
  15.          * after setting kmemleak_initialized and we may end up with
  16.          * two clean-up threads but serialized by scan_mutex.
  17.          */
  18.         schedule_work(&cleanup_work);
  19.         return -ENOMEM;
  20.     }
  21.  
  22.     dentry = debugfs_create_file("kmemleak", S_IRUGO, NULL, NULL,
  23.                      &kmemleak_fops);
  24.     if (!dentry)
  25.         pr_warning("Failed to create the debugfs kmemleak file\n");
  26.     mutex_lock(&scan_mutex);
  27.     start_scan_thread();
  28.     mutex_unlock(&scan_mutex);
  29.  
  30.     pr_info("Kernel memory leak detector initialized\n");
  31.  
  32.     return 0;
  33. }
  34. late_initcall(kmemleak_late_init);

该函数通过late_initcall()宏定义注册到系统初始化中,处于module_init()之后被调用初始化。函数实现,首先设置kmemleak初始化完毕标识kmemleak_initialized;继而判断是否kmemleak发生过错误,如果发生过错误,这里也做了一个可靠性保障动作,就是通过schedule_work调度cleanup_work工作队列,对kmemleak进行环境清理动作。

cleanup_work工作队列实现:

  1. 【file:/mm/kmemcheck.c】
  2. /*
  3.  * Stop the memory scanning thread and free the kmemleak internal objects if
  4.  * no previous scan thread (otherwise, kmemleak may still have some useful
  5.  * information on memory leaks).
  6.  */
  7. static void kmemleak_do_cleanup(struct work_struct *work)
  8. {
  9.     struct kmemleak_object *object;
  10.     bool cleanup = scan_thread == NULL;
  11.  
  12.     mutex_lock(&scan_mutex);
  13.     stop_scan_thread();
  14.  
  15.     if (cleanup) {
  16.         rcu_read_lock();
  17.         list_for_each_entry_rcu(object, &object_list, object_list)
  18.             delete_object_full(object->pointer);
  19.         rcu_read_unlock();
  20.     }
  21.     mutex_unlock(&scan_mutex);
  22. }
  23.  
  24. static DECLARE_WORK(cleanup_work, kmemleak_do_cleanup);

工作队列的实现主体是kmemleak_do_cleanu(),其先将kmemleak内存泄漏扫描线程停止,然后通过遍历object_list链表,继而delete_object_full()将所有管理的内存对象进行删除操作。

扯远了,回到kmemleak_late_init()函数实现中,如果一切正常,将会通过debugfs_create_file()debugfs文件系统中创建“kmemleak”文件,同时将文件对应的操作函数集kmemleak_fops注册进去。以便外部操作“kmemleak”文件时,响应相关的操作指令;最后则是通过start_scan_thread()创建kmemleak的内核扫描线程。

  1. 【file:/mm/kmemcheck.c】
  2. /*
  3.  * Start the automatic memory scanning thread. This function must be called
  4.  * with the scan_mutex held.
  5.  */
  6. static void start_scan_thread(void)
  7. {
  8.     if (scan_thread)
  9.         return;
  10.     scan_thread = kthread_run(kmemleak_scan_thread, NULL, "kmemleak");
  11.     if (IS_ERR(scan_thread)) {
  12.         pr_warning("Failed to create the scan thread\n");
  13.         scan_thread = NULL;
  14.     }
  15. }

通过start_scan_thread()的实现,可以看到该内核线程的实体函数为kmemleak_scan_thread()

具体kmemleak_scan_thread()实现:

  1. 【file:/mm/kmemcheck.c】
  2. /*
  3.  * Thread function performing automatic memory scanning. Unreferenced objects
  4.  * at the end of a memory scan are reported but only the first time.
  5.  */
  6. static int kmemleak_scan_thread(void *arg)
  7. {
  8.     static int first_run = 1;
  9.  
  10.     pr_info("Automatic memory scanning thread started\n");
  11.     set_user_nice(current, 10);
  12.  
  13.     /*
  14.      * Wait before the first scan to allow the system to fully initialize.
  15.      */
  16.     if (first_run) {
  17.         first_run = 0;
  18.         ssleep(SECS_FIRST_SCAN);
  19.     }
  20.  
  21.     while (!kthread_should_stop()) {
  22.         signed long timeout = jiffies_scan_wait;
  23.  
  24.         mutex_lock(&scan_mutex);
  25.         kmemleak_scan();
  26.         mutex_unlock(&scan_mutex);
  27.  
  28.         /* wait before the next scan */
  29.         while (timeout && !kthread_should_stop())
  30.             timeout = schedule_timeout_interruptible(timeout);
  31.     }
  32.  
  33.     pr_info("Automatic memory scanning thread ended\n");
  34.  
  35.     return 0;
  36. }

函数首先打印提示信息,然后设置内核线程优先级,判断是否为第一次扫描,如果是则设置标识first_run;继而开始进入扫描,只要kthread_should_stop()判断不为停止的情况下,先行首次kmemleak_scan()扫描,继而通过schedule_timeout_interruptible()控制时长间隔jiffies_scan_wait后,再次进行泄漏检测扫描。其中里面的kthread_should_stop()判断源于内核代码调用kthread_stop()停止,而非接下来看到的另外一种对kmemleak内核线程操作的关闭功能,两者是有区别的。

除了kmemleak_late_init()中通过kmemleak_late_init()启动kmemleak的内核线程之外,其实还有其他的控制途径。就是在该初始化函数中一个不起眼的动作debugfs_create_file("kmemleak", S_IRUGO, NULL, NULL,&kmemleak_fops),这里的kmemleak_fops定义了对文件操作的响应动作。

  1. 【file:/mm/kmemcheck.c】
  2. static const struct file_operations kmemleak_fops = {
  3.     .owner = THIS_MODULE,
  4.     .open = kmemleak_open,
  5.     .read = seq_read,
  6.     .write = kmemleak_write,
  7.     .llseek = seq_lseek,
  8.     .release = kmemleak_release,
  9. };

这里有一个很关键的函数kmemleak_write()

  1. 【file:/mm/kmemcheck.c】
  2. /*
  3.  * File write operation to configure kmemleak at run-time. The following
  4.  * commands can be written to the /sys/kernel/debug/kmemleak file:
  5.  * off - disable kmemleak (irreversible)
  6.  * stack=on - enable the task stacks scanning
  7.  * stack=off - disable the tasks stacks scanning
  8.  * scan=on - start the automatic memory scanning thread
  9.  * scan=off - stop the automatic memory scanning thread
  10.  * scan=... - set the automatic memory scanning period in seconds (0 to
  11.  * disable it)
  12.  * scan - trigger a memory scan
  13.  * clear - mark all current reported unreferenced kmemleak objects as
  14.  * grey to ignore printing them
  15.  * dump=... - dump information about the object found at the given address
  16.  */
  17. static ssize_t kmemleak_write(struct file *file, const char __user *user_buf,
  18.                   size_t size, loff_t *ppos)
  19. {
  20.     char buf[64];
  21.     int buf_size;
  22.     int ret;
  23.  
  24.     if (!atomic_read(&kmemleak_enabled))
  25.         return -EBUSY;
  26.  
  27.     buf_size = min(size, (sizeof(buf) - 1));
  28.     if (strncpy_from_user(buf, user_buf, buf_size) < 0)
  29.         return -EFAULT;
  30.     buf[buf_size] = 0;
  31.  
  32.     ret = mutex_lock_interruptible(&scan_mutex);
  33.     if (ret < 0)
  34.         return ret;
  35.  
  36.     if (strncmp(buf, "off", 3) == 0)
  37.         kmemleak_disable();
  38.     else if (strncmp(buf, "stack=on", 8) == 0)
  39.         kmemleak_stack_scan = 1;
  40.     else if (strncmp(buf, "stack=off", 9) == 0)
  41.         kmemleak_stack_scan = 0;
  42.     else if (strncmp(buf, "scan=on", 7) == 0)
  43.         start_scan_thread();
  44.     else if (strncmp(buf, "scan=off", 8) == 0)
  45.         stop_scan_thread();
  46.     else if (strncmp(buf, "scan=", 5) == 0) {
  47.         unsigned long secs;
  48.  
  49.         ret = kstrtoul(buf + 5, 0, &secs);
  50.         if (ret < 0)
  51.             goto out;
  52.         stop_scan_thread();
  53.         if (secs) {
  54.             jiffies_scan_wait = msecs_to_jiffies(secs * 1000);
  55.             start_scan_thread();
  56.         }
  57.     } else if (strncmp(buf, "scan", 4) == 0)
  58.         kmemleak_scan();
  59.     else if (strncmp(buf, "clear", 5) == 0)
  60.         kmemleak_clear();
  61.     else if (strncmp(buf, "dump=", 5) == 0)
  62.         ret = dump_str_object_info(buf + 5);
  63.     else
  64.         ret = -EINVAL;
  65.  
  66. out:
  67.     mutex_unlock(&scan_mutex);
  68.     if (ret < 0)
  69.         return ret;
  70.  
  71.     /* ignore the rest of the buffer, only one command at a time */
  72.     *ppos += size;
  73.     return size;
  74. }

这个函数只做一个动作,就是当/sys/kernel/debug/kmemleak写入操作指令时,将会触发调用该函数,继而解析操作指令,根据操作指令进行响应。其中就有start_scan_thread()stop_scan_thread()

再次跑远了,最后来个分析收尾,具体分析一下kmemleak_scan()函数,看一下内存泄漏扫描的实现。

  1. 【file:/mm/kmemcheck.c】
  2. /*
  3.  * Scan data sections and all the referenced memory blocks allocated via the
  4.  * kernel's standard allocators. This function must be called with the
  5.  * scan_mutex held.
  6.  */
  7. static void kmemleak_scan(void)
  8. {
  9.     unsigned long flags;
  10.     struct kmemleak_object *object;
  11.     int i;
  12.     int new_leaks = 0;
  13.  
  14.     jiffies_last_scan = jiffies;
  15.  
  16.     /* prepare the kmemleak_object's */
  17.     rcu_read_lock();
  18.     list_for_each_entry_rcu(object, &object_list, object_list) {
  19.         spin_lock_irqsave(&object->lock, flags);
  20. #ifdef DEBUG
  21.         /*
  22.          * With a few exceptions there should be a maximum of
  23.          * 1 reference to any object at this point.
  24.          */
  25.         if (atomic_read(&object->use_count) > 1) {
  26.             pr_debug("object->use_count = %d\n",
  27.                  atomic_read(&object->use_count));
  28.             dump_object_info(object);
  29.         }
  30. #endif
  31.         /* reset the reference count (whiten the object) */
  32.         object->count = 0;
  33.         if (color_gray(object) && get_object(object))
  34.             list_add_tail(&object->gray_list, &gray_list);
  35.  
  36.         spin_unlock_irqrestore(&object->lock, flags);
  37.     }
  38.     rcu_read_unlock();
  39.  
  40.     /* data/bss scanning */
  41.     scan_block(_sdata, _edata, NULL, 1);
  42.     scan_block(__bss_start, __bss_stop, NULL, 1);
  43.  
  44. #ifdef CONFIG_SMP
  45.     /* per-cpu sections scanning */
  46.     for_each_possible_cpu(i)
  47.         scan_block(__per_cpu_start + per_cpu_offset(i),
  48.                __per_cpu_end + per_cpu_offset(i), NULL, 1);
  49. #endif
  50.  
  51.     /*
  52.      * Struct page scanning for each node.
  53.      */
  54.     lock_memory_hotplug();
  55.     for_each_online_node(i) {
  56.         unsigned long start_pfn = node_start_pfn(i);
  57.         unsigned long end_pfn = node_end_pfn(i);
  58.         unsigned long pfn;
  59.  
  60.         for (pfn = start_pfn; pfn < end_pfn; pfn++) {
  61.             struct page *page;
  62.  
  63.             if (!pfn_valid(pfn))
  64.                 continue;
  65.             page = pfn_to_page(pfn);
  66.             /* only scan if page is in use */
  67.             if (page_count(page) == 0)
  68.                 continue;
  69.             scan_block(page, page + 1, NULL, 1);
  70.         }
  71.     }
  72.     unlock_memory_hotplug();
  73.  
  74.     /*
  75.      * Scanning the task stacks (may introduce false negatives).
  76.      */
  77.     if (kmemleak_stack_scan) {
  78.         struct task_struct *p, *g;
  79.  
  80.         read_lock(&tasklist_lock);
  81.         do_each_thread(g, p) {
  82.             scan_block(task_stack_page(p), task_stack_page(p) +
  83.                    THREAD_SIZE, NULL, 0);
  84.         } while_each_thread(g, p);
  85.         read_unlock(&tasklist_lock);
  86.     }
  87.  
  88.     /*
  89.      * Scan the objects already referenced from the sections scanned
  90.      * above.
  91.      */
  92.     scan_gray_list();
  93.  
  94.     /*
  95.      * Check for new or unreferenced objects modified since the previous
  96.      * scan and color them gray until the next scan.
  97.      */
  98.     rcu_read_lock();
  99.     list_for_each_entry_rcu(object, &object_list, object_list) {
  100.         spin_lock_irqsave(&object->lock, flags);
  101.         if (color_white(object) && (object->flags & OBJECT_ALLOCATED)
  102.             && update_checksum(object) && get_object(object)) {
  103.             /* color it gray temporarily */
  104.             object->count = object->min_count;
  105.             list_add_tail(&object->gray_list, &gray_list);
  106.         }
  107.         spin_unlock_irqrestore(&object->lock, flags);
  108.     }
  109.     rcu_read_unlock();
  110.  
  111.     /*
  112.      * Re-scan the gray list for modified unreferenced objects.
  113.      */
  114.     scan_gray_list();
  115.  
  116.     /*
  117.      * If scanning was stopped do not report any new unreferenced objects.
  118.      */
  119.     if (scan_should_stop())
  120.         return;
  121.  
  122.     /*
  123.      * Scanning result reporting.
  124.      */
  125.     rcu_read_lock();
  126.     list_for_each_entry_rcu(object, &object_list, object_list) {
  127.         spin_lock_irqsave(&object->lock, flags);
  128.         if (unreferenced_object(object) &&
  129.             !(object->flags & OBJECT_REPORTED)) {
  130.             object->flags |= OBJECT_REPORTED;
  131.             new_leaks++;
  132.         }
  133.         spin_unlock_irqrestore(&object->lock, flags);
  134.     }
  135.     rcu_read_unlock();
  136.  
  137.     if (new_leaks)
  138.         pr_info("%d new suspected memory leaks (see "
  139.             "/sys/kernel/debug/kmemleak)\n", new_leaks);
  140.  
  141. }

kmemleak内存扫描前,有个准备动作,遍历object_list链表,重置查找到指针值匹配对象的个数count,通过color_gray()判断object颜色是否为灰色,若是则get_object()增加object的计数,然后将该object添加到gray_list链表中。

开始正式扫描,首先是扫描data段以及bss段(代码如下),其根据_sdata_edatadata段的标识以及__bss_start__bss_stopbss段的标识进行扫描,data段和bss段都是存储程序的全局变量和静态遍历的地方,区别仅在于是否赋了初值而已;

    /* data/bss scanning */

    scan_block(_sdata, _edata, NULL, 1);

    scan_block(__bss_start, __bss_stop, NULL, 1);

继而扫描percpu内存空间(代码如下),通过for_each_possible_cpu()循环遍历每个CPU的内存段;

    /* per-cpu sections scanning */

    for_each_possible_cpu(i)

        scan_block(__per_cpu_start + per_cpu_offset(i),

               __per_cpu_end + per_cpu_offset(i), NULL, 1);

接着扫描内核内存页面空间(代码如下),主要是由于其空间来自于动态分配,所以也要进行扫描检测;

    /*

     * Struct page scanning for each node.

     */

    lock_memory_hotplug();

    for_each_online_node(i) {

        unsigned long start_pfn = node_start_pfn(i);

        unsigned long end_pfn = node_end_pfn(i);

        unsigned long pfn;


        for (pfn = start_pfn; pfn < end_pfn; pfn++) {

            struct page *page;


            if (!pfn_valid(pfn))

                continue;

            page = pfn_to_page(pfn);

            /* only scan if page is in use */

            if (page_count(page) == 0)

                continue;

            scan_block(page, page + 1, NULL, 1);

        }

    }

    unlock_memory_hotplug();

然后扫描内核进程栈空间(代码如下),do_each_thread()-while_each_thread()主要是遍历所有线程信息(包括进程),这由于每个线程有自己单独的内核栈信息;

    /*

     * Scanning the task stacks (may introduce false negatives).

     */

    if (kmemleak_stack_scan) {

        struct task_struct *p, *g;


        read_lock(&tasklist_lock);

        do_each_thread(g, p) {

            scan_block(task_stack_page(p), task_stack_page(p) +

                   THREAD_SIZE, NULL, 0);

        } while_each_thread(g, p);

        read_unlock(&tasklist_lock);

    }

最后调用scan_gray_list()扫描分配的内存块内部,具体代码这里就不拎出来了,其主要是遍历gray_list链表,对每一项调用scan_object()进行扫描;紧接着检测前面扫描中新增的或者存在修改的未引用的object,并标识色彩;再接着的是scan_gray_list()重复扫描。

扫描完毕之后,判断scan_should_stop()是否扫描停止,若是则停止上报,否则将会遍历object_list链表,查找出标记为白色的object,其跟踪的内存则是存在疑似泄漏的行为。新发现的泄漏内存将会设置为标识OBJECT_REPORTED。这里并不会直接写到kmemleak中,它通过文件操作关联,当kmemleak_open()打开文件时,才会把内容刷新到上面。

结尾前,看一下内存块扫描函数scan_block()的实现:

  1. 【file:/mm/kmemcheck.c】
  2. /*
  3.  * Scan a memory block (exclusive range) for valid pointers and add those
  4.  * found to the gray list.
  5.  */
  6. static void scan_block(void *_start, void *_end,
  7.                struct kmemleak_object *scanned, int allow_resched)
  8. {
  9.     unsigned long *ptr;
  10.     unsigned long *start = PTR_ALIGN(_start, BYTES_PER_POINTER);
  11.     unsigned long *end = _end - (BYTES_PER_POINTER - 1);
  12.  
  13.     for (ptr = start; ptr < end; ptr++) {
  14.         struct kmemleak_object *object;
  15.         unsigned long flags;
  16.         unsigned long pointer;
  17.  
  18.         if (allow_resched)
  19.             cond_resched();
  20.         if (scan_should_stop())
  21.             break;
  22.  
  23.         /* don't scan uninitialized memory */
  24.         if (!kmemcheck_is_obj_initialized((unsigned long)ptr,
  25.                           BYTES_PER_POINTER))
  26.             continue;
  27.  
  28.         pointer = *ptr;
  29.  
  30.         object = find_and_get_object(pointer, 1);
  31.         if (!object)
  32.             continue;
  33.         if (object == scanned) {
  34.             /* self referenced, ignore */
  35.             put_object(object);
  36.             continue;
  37.         }
  38.  
  39.         /*
  40.          * Avoid the lockdep recursive warning on object->lock being
  41.          * previously acquired in scan_object(). These locks are
  42.          * enclosed by scan_mutex.
  43.          */
  44.         spin_lock_irqsave_nested(&object->lock, flags,
  45.                      SINGLE_DEPTH_NESTING);
  46.         if (!color_white(object)) {
  47.             /* non-orphan, ignored or new */
  48.             spin_unlock_irqrestore(&object->lock, flags);
  49.             put_object(object);
  50.             continue;
  51.         }
  52.  
  53.         /*
  54.          * Increase the object's reference count (number of pointers
  55.          * to the memory block). If this count reaches the required
  56.          * minimum, the object's color will become gray and it will be
  57.          * added to the gray_list.
  58.          */
  59.         object->count++;
  60.         if (color_gray(object)) {
  61.             list_add_tail(&object->gray_list, &gray_list);
  62.             spin_unlock_irqrestore(&object->lock, flags);
  63.             continue;
  64.         }
  65.  
  66.         spin_unlock_irqrestore(&object->lock, flags);
  67.         put_object(object);
  68.     }
  69. }

该函数主要是for循环自_start_end进行内存遍历扫描。循环体内先是根据入参判断是否需要产生重新调度cond_resched(),继而scan_should_stop()判断kmemleak的扫描动作是否停止,接着则是通过kmemcheck_is_obj_initialized()对即将扫描的内存空间做合法性判断;每遍历的内存将会根据地址作为指针数据取值,继而通过find_and_get_object()查找该指针数据是否在内存管理树中存在,如果能够找到对应的内存管理object对象,那边表明该内存是未泄漏的,将会continue继续,但如果找不到,则判断该内存地址是否为需要做忽略处理的自引用内存;接下来则是根据countmin_count判断,做相关的颜色标识处理。


阅读(8353) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~