bittterbotter
bittterbotter

Reputation: 445

Need of using MACROS like module_init and module_exit while writing Loadable Kernel Modules

What is the need of using MACROs like module_init and module_exit while writing Loadable Kernel Modules? Also, Why are we using MACROs like __init or __exit. Even though we can do the job without using them.

  1. Without MACROS

     /*
     Without using MACROS
     Date: 14 Dec 2014
     */
     #include <linux/module.h>
     #include <linux/kernel.h>
     int init_module(void){
         printk(KERN_ALERT "This is our first program.");
         return 0;
     }
     void cleanup_module(void){
         printk(KERN_ALERT "End of our first program.");
     }
    
  2. With MACROs

     /* 
     Edited first.c; Added macros module_init and module_exit
     Date: 14 Dec 2014
     */
     #include <linux/module.h>
     #include <linux/kernel.h>
     #include <linux/init.h>
    
     static int __init first_init(void)
     {
         printk(KERN_ALERT "This is our first program.");
         return 0;
     }
    
     static void __exit first_exit(void)
     {
         printk(KERN_ALERT "End of our first program.");
     }
    
     module_init(first_init);
     module_exit(first_exit);
    

What is the difference?

Upvotes: 4

Views: 3812

Answers (1)

askb
askb

Reputation: 6786

module_{init,exit}() adds the necessary boilerplate to initialize / cleanup the module and run the entry / exit code, when the module file is loaded / unloaded into or from the kernel space.

__init is telling kernel that this function is executed once and never come back mainly for built-in drivers while module_init() is to initialize the module when it is being insmod.

Refer Rubini & Corbet

"

The attribute __init, , will cause the initialization function to be discarded, and its memory reclaimed, after initialization is complete. It only works, however, for built-in drivers; it has no effect on modules. __exit, instead, causes the omission of the marked function when the driver is not built as a module; again, in modules, it has no effect.

The use of __init (and __initdata for data items) can reduce the amount of memory used by the kernel. There is no harm in marking module initialization functions with __init, even though currently there is no benefit either. Management of initialization sections has not been implemented yet for modules, but it's a possible enhancement for the future.

"

Upvotes: 6

Related Questions