Search code examples
linux-kernelsystems-programmingmemory-management

How to handle memory obtained by module_param when writing a Linux kernel module?


When writing a kernel module for Linux, module_param and its variants can take a string as a module parameter, and the memory space required for that string is allocated behind the scenes without having to do anything explicitly. My question is, how should you handle this piece of memory? Do you have to explicitly free it if you don't need it anymore? What should you do if you want to change the string from inside the module?


Solution

  • Memory allocated by module_param for string (charp type) argument is maintained by callbacks for this parameter's type, see param_set_charp, param_get_charp and param_free_charp functions defined in kernel/params.c.

    1. The easiest way for operate with such param is to declare it as Read Only, and accessing it from the module only for read. In that case one needn't to bother about locking on access or freeing parameter's value.

    2. If you want to write from the module to Read Only parameter, you need:

      1) Free old value of parameter via param_free_charp.

      2) Assign new value for the parameter. If this value is allocated, you need to manually deallocate it in module_exit or in the next writting into the parameter.

      Both these actions should be performed inside single critical section kernel_param_lock(THIS_MODULE)/kernel_param_unlock(THIS_MODULE), so possible reading parameter's value from user space will found its value fully initialized.

    3. If you declare parameter as writable, then reading it inside the module requires critical section kernel_param_lock(THIS_MODULE)/kernel_param_unlock(THIS_MODULE).

    4. Writing to writable parameter is allowed only when new value is stored somewhere else, so if the parameter will be rewritten from user space, its previous value can be found and freed if needed.

      Writing and reading such parameter inside the module should follow same requiremens as cases 2 and 3 cases correspondingly.