Linux内核——如何将驱动代码添加到内核源码树

以字符设备驱动为例s

  1. 首先,把.c文件拷贝到/driver/char中要修改源码给目录下的/driver/char中的Kconfig文件,这样才能在编译内核时看到我们驱动的配置选单,参考其他的config 有样学样

    1678061581009

    tristate字段说明 该驱动有三个选项 y m n 。 y代表编译到内核里面,m是编程驱动.ko n是不编译。

  2. 接下来到内核源码根目录下执行,

    1
    /home/dawnlake/Downloads/linux-4.9.229$ make memuconfig

1678061753376

1678061802952

1678061851658

查看help

1678061906964

  1. 接下来需要修改/drivers/char目录下的makefile文件

    1678065704335

  1. 然后再回到内核源码根目录下执行,make

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    root@dawnlake-virtual-machine:/home/dawnlake/Downloads/linux-4.9.229$ make
    scripts/kconfig/conf --silentoldconfig Kconfig
    CHK include/config/kernel.release
    CHK include/generated/uapi/linux/version.h
    CHK include/generated/utsrelease.h
    CHK include/generated/bounds.h
    CHK include/generated/timeconst.h
    CHK include/generated/asm-offsets.h
    CALL scripts/checksyscalls.sh
    CHK scripts/mod/devicetable-offsets.h
    CHK include/generated/compile.h
    CC drivers/char/helloDev.o
    LD drivers/char/built-in.o
    LD drivers/built-in.o
    LD vmlinux.o
    MODPOST vmlinux.o
    GEN .version
    CHK include/generated/compile.h
    UPD include/generated/compile.h
    CC init/version.o
    LD init/built-in.o
    KSYM .tmp_kallsyms1.o
    KSYM .tmp_kallsyms2.o
    LD vmlinux
    SORTEX vmlinux
    SYSMAP System.map
    VOFFSET arch/x86/boot/compressed/../voffset.h
    CC arch/x86/boot/compressed/misc.o
    OBJCOPY arch/x86/boot/compressed/vmlinux.bin
    GZIP arch/x86/boot/compressed/vmlinux.bin.gz
    MKPIGGY arch/x86/boot/compressed/piggy.S
    AS arch/x86/boot/compressed/piggy.o
    LD arch/x86/boot/compressed/vmlinux
    ld: arch/x86/boot/compressed/head_64.o: warning: relocation in read-only section `.head.text'
    ld: warning: creating DT_TEXTREL in a PIE
    ZOFFSET arch/x86/boot/zoffset.h
    AS arch/x86/boot/header.o
    CC arch/x86/boot/version.o
    LD arch/x86/boot/setup.elf
    OBJCOPY arch/x86/boot/setup.bin
    OBJCOPY arch/x86/boot/vmlinux.bin
    BUILD arch/x86/boot/bzImage
    Setup is 15580 bytes (padded to 15872 bytes).
    System is 6681 kB
    CRC 959cc45
    Kernel: arch/x86/boot/bzImage is ready (#2)
    Building modules, stage 2.
    MODPOST 18 modules

    现在内核启动时候就会自动加载我们的hello驱动,如果在menuconfig设置m而不是y(*) ,就会只生成.ko文件而不是直接加载,需要手动插入。