您的位置:首页 > 运维架构 > Linux

linux中的__init 宏

2016-12-25 17:40 253 查看
在内核里经常可以看到__init, __devinit这样的语句,这都是在init.h中定义的宏,gcc在编译时会将被修饰的内容放到这些宏所代表的section。

其典型的定义如下:

#define __init        __section(.init.text) __cold notrace

#define __initdata    __section(.init.data)

#define __initconst    __section(.init.rodata)

#define __exitdata    __section(.exit.data)

#define __exit_call    __used __section(.exitcall.exit)

其典型用法如下:

static int __init xxx_drv_init(void)

{

     return pci_register_driver(&xxx_driver);

}

根据上面的定义与用法,xxx_drv_init()函数将会被link到.init.text段。

之所以加入这样的宏,原因有2:

1,一部分内核初始化机制依赖与它。如kernel将初始化要执行的init函数,分为7个级别,core_initcall, postcore_initcall, arch_initcall, subsys_initcall, fs_iitcall, device_initcall, late_initcall。这7个级别优先级递减,即先执行core_initcall, 最后执行late_initcall。通过使用文中提到的宏,gcc会将初始化代码按下面的结构安排:

在内核初始化时,从__initcall_start到__initcall_end之间的initcall被一次执行。

2,提高系统效率

初始化代码的特点是,在系统启动时运行,且一旦运行后马上推出内存,不再占用内存。

================================================================================

常用的宏:

__init,标记内核启动时所用的初始化代码,内核启动完成后就不再使用。其所修饰的内容被放到.init.text section中。

__exit,标记模块退出代码,对非模块无效

__initdata,标记内核启动时所用的初始化数据结构,内核启动完成后不再使用。其所修饰的内容被放到.init.data section中。

__devinit,标记设备初始化所用的代码

__devinitdata,标记设备初始化所用的数据结构

__devexit,标记设备移除时所用的代码

xxx_initcall,7个级别的初始化函数

==================================================================================

These are only macros to locate some parts of the linux code into special areas in the final executing binary. 
__init
,
for example (or better the 
__attribute__
((__section__(".init.text")))
 this macro expands to) instructs the compiler to mark this function in a special way. At the end the linker collects all functions with this mark at the end (or begin) of the binary file.

When the kernel starts, this code runs only once (initialization). After it runs, the kernel can free this memory to reuse it and you will see the kernel message:

Freeing unused kernel memory: 108k freed

To use this feature, you need a special linker script file, that tells the linker where to locate all the marked functions.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: