__init在Linux内核代码中的含义是什么?

Jee*_*tel 81 c linux

在Linux内核源代码中我找到了这个函数:

static int __init clk_disable_unused(void) 
{
   // some code
}
Run Code Online (Sandbox Code Playgroud)

在这里,我无法理解它__init意味着什么.

San*_*raj 66

include/linux/init.h

/* These macros are used to mark some functions or 
 * initialized data (doesn't apply to uninitialized data)
 * as `initialization' functions. The kernel can take this
 * as hint that the function is used only during the initialization
 * phase and free up used memory resources after
 *
 * Usage:
 * For functions:
 * 
 * You should add __init immediately before the function name, like:
 *
 * static void __init initme(int x, int y)
 * {
 *    extern int z; z = x * y;
 * }
 *
 * If the function has a prototype somewhere, you can also add
 * __init between closing brace of the prototype and semicolon:
 *
 * extern int initialize_foobar_device(int, int, int) __init;
 *
 * For initialized data:
 * You should insert __initdata between the variable name and equal
 * sign followed by value, e.g.:
 *
 * static int init_variable __initdata = 0;
 * static const char linux_logo[] __initconst = { 0x32, 0x36, ... };
 *
 * Don't forget to initialize data not at file scope, i.e. within a function,
 * as gcc otherwise puts the data into the bss section and not into the init
 * section.
 * 
 * Also note, that this data cannot be "const".
 */

/* These are for everybody (although not all archs will actually
   discard it in modules) */
#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)
Run Code Online (Sandbox Code Playgroud)


sas*_*alm 48

这些只是将linux代码的某些部分定位到最终执行二进制文件中的特殊区域的宏. __init例如(或者__attribute__ ((__section__ (".init.text")))这个宏扩展为更好)指示编译器以特殊方式标记此函数.最后,链接器在二进制文件的末尾(或开头)收集带有此标记的所有函数.

内核启动时,此代码只运行一次(初始化).运行后,内核可以释放这个内存来重用它,你会看到内核消息:

释放未使用的内核内存:释放108k

要使用此功能,您需要一个特殊的链接描述文件,该文件告诉链接器在何处找到所有标记的功能.

  • 聪明!这就是"释放未使用的内核内存:108k释放"的含义.:-)这些年来,我有点想知道.我以为它是某种缓冲区或东西,而不是代码. (9认同)

小智 6

这演示了内核 2.2 及更高版本的功能。注意initcleanup函数定义的变化。该__init宏导致的init被丢弃的功能和它的内存一旦释放init功能完成对内置的驱动程序,但没有可加载模块。如果您考虑init调用函数的时间,这是完全合理的。

来源


Geo*_*roy 5

__init 是 ./include/linux/init.h 中定义的宏,它扩展为__attribute__ ((__section__(".init.text"))).

它指示编译器以特殊方式标记此函数。最后,链接器收集二进制文件末尾(或开头)带有此标记的所有函数。当内核启动时,这段代码只运行一次(初始化)。它运行后,内核可以释放这块内存以重用它,您将看到内核