sysprog21 / fibdrv

Linux kernel module that calculates Fibonacci numbers
https://hackmd.io/@sysprog/linux2023-fibdrv
MIT License
41 stars 335 forks source link

Fix cdev memory leak #3

Closed dungru closed 4 years ago

dungru commented 4 years ago

kmemleak tool found the unreferenced object when removing the fibdrv.ko module. There is no need to use the cdev_alloc() and cdev_init() simultaneously.

  1. Enable the kmemleak config and rebuild the kernel.
    CONFIG_SLUB_DEBUG_ON=y
    CONFIG_SLUB_STATS=y
    CONFIG_HAVE_DEBUG_KMEMLEAK=y
    CONFIG_DEBUG_KMEMLEAK=y
    CONFIG_DEBUG_KMEMLEAK_EARLY_LOG_SIZE=8192
  2. Reproduce Step:

    To clear the list of all current possible memory leaks

    echo clear > /sys/kernel/debug/kmemleak

    Insert the module

    insmod fibdrv.ko

    Start scan the kernel memory

    echo scan=2 > /sys/kernel/debug/kmemleak

    Remove the module

    rmmod fibdrv.ko

    To display the details of all the possible scanned memory leaks

    cat /sys/kernel/debug/kmemleak

    unreferenced object 0xffff88001fc941e8 (size 128):
    comm "insmod", pid 7577, jiffies 4295124450 (age 113.372s)
    hex dump (first 32 bytes):
    00 00 00 00 00 00 00 00 f0 41 c9 1f 00 88 ff ff  .........A......
    f0 41 c9 1f 00 88 ff ff 00 00 00 00 00 00 00 00  .A..............
    backtrace:
    [ffffffff9c6b9d4a] kmemleak_alloc+0x4a/0xa0
    [ffffffff9bb71287] kmem_cache_alloc_trace+0x127/0x220
    [ffffffff9bbba9ee] cdev_alloc+0x2e/0x70
    [ffffffffc0d60057] 0xffffffffc0d60057
    [ffffffff9b802276] do_one_initcall+0xa6/0x210
    [ffffffff9b9be8c2] do_init_module+0xf4/0x322
    [ffffffff9b9bd1be] load_module+0x420e/0x4950
    [ffffffff9b9bdc99] SYSC_finit_module+0x189/0x1c0
    [ffffffff9b9bdcee] SyS_finit_module+0xe/0x10
    [ffffffff9c80008b] entry_SYSCALL_64_fastpath+0x1e/0x81
    [ffffffffffffffff]         0xffffffffffffffff