Linux Kernel Module Parameters and Floating-Point Operations

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Kernel Module Parameters & Floating Point in Linux Kernel

Free Linux Kernel Development Course — EmbeddedPathashala

📚 Free Linux Device Drivers Course
💻 Hands-On Code Examples
✅ Linux 6.x Updated

← Previous Lecture Next Lecture →

What You Will Learn

In this free Linux kernel development course lecture, you will learn:

  • How kernel module parameters work and why they are useful
  • How to rename a module parameter using module_param_named()
  • What hardware-specific kernel parameters are and when to use them
  • Why floating-point arithmetic is not allowed in Linux kernel space
  • How to safely handle floating-point values when writing kernel modules
  • Best practices for integer-only arithmetic in the Linux kernel
Topics Covered:
module_param_named kernel module parameters module_param_hw floating point kernel kernel_fpu_begin Linux 6.x kernel free kernel programming course
Prerequisites

Before reading this lecture from our free Linux device drivers course, you should be comfortable with:

  • Writing and building a basic Linux kernel module (.ko file)
  • Using insmod, rmmod, and modinfo commands
  • Basic understanding of module_param() macro
  • Familiarity with Linux kernel logging via pr_info() and printk()

Kernel Module Parameters — A Quick Refresher

When you load a kernel module using insmod, you can pass values to it from the command line — very much like passing arguments to a regular userspace program. These are called kernel module parameters. They let you control the behavior of a module without recompiling it.

The most common macro for declaring a module parameter is module_param(name, type, permissions). This registers a variable so that the kernel’s parameter parser picks it up when the module is loaded.

In this lecture from our free Linux kernel development course, we go deeper — looking at advanced parameter macros that solve specific real-world problems you will encounter when writing Linux device drivers.

Overriding the Module Parameter Name with module_param_named()

Sometimes the internal variable name in your driver code is long, descriptive, or follows a naming convention that is not user-friendly. You might have a variable called dm_bufio_current_allocated inside your driver, but you want the user to type simply current_allocated_bytes on the command line when loading the module.

This is exactly the problem that module_param_named() solves. It lets you expose a different, friendlier name to the outside world while keeping your internal variable name unchanged in the source code.

How module_param_named() Works
User Types:
current_allocated_bytes=4096
→ Kernel Parameter Parser
module_param_named()
→ Internal Variable:
dm_bufio_current_allocated = 4096

Syntax of module_param_named()

The macro takes four arguments:

module_param_named() — Argument Breakdown
Argument What It Means Example
name The external name — what the user types at insmod current_allocated_bytes
variable The actual internal C variable in your driver dm_bufio_current_allocated
type The data type (int, ulong, bool, charp, etc.) ulong
perm Sysfs permissions for /sys/module/<name>/parameters/ S_IRUGO (read-only)

Code Example — Using module_param_named()

Here is how you declare and use it in a real kernel module:

#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>

MODULE_LICENSE("GPL");
MODULE_AUTHOR("EmbeddedPathashala");
MODULE_DESCRIPTION("Demo: module_param_named usage");

/* Internal variable — long, not user-friendly */
static unsigned long my_internal_buffer_size = 4096;

/* Expose it to the user as 'buffer_size_bytes' */
module_param_named(buffer_size_bytes, my_internal_buffer_size, ulong, S_IRUGO);
MODULE_PARM_DESC(buffer_size_bytes, "Buffer size in bytes (default: 4096)");

static int __init named_param_init(void)
{
    pr_info("Module loaded. buffer size = %lu bytes\n",
            my_internal_buffer_size);
    return 0;
}

static void __exit named_param_exit(void)
{
    pr_info("Module unloaded.\n");
}

module_init(named_param_init);
module_exit(named_param_exit);

Loading this module:

sudo insmod named_param.ko buffer_size_bytes=8192

The kernel parameter parser sees buffer_size_bytes, looks up the mapping from module_param_named(), and stores 8192 into my_internal_buffer_size.

You can also check the parameter via sysfs after loading:

cat /sys/module/named_param/parameters/buffer_size_bytes
💡 Practical Tip:

Always pair module_param_named() with MODULE_PARM_DESC() using the external name. This description shows up when someone runs modinfo your_module.ko — very helpful for users of your driver.

Hardware-Specific Kernel Parameters — module_param_hw()

Regular module parameters are fine for general settings. But when a parameter represents a hardware resource — like an I/O port address, an IRQ number, a DMA channel, or a physical memory address — there is a dedicated family of macros for that purpose.

These are the module_param_hw(), module_param_hw_named(), and module_param_hw_array() macros. They were introduced specifically to support secure boot scenarios, where locking down hardware resource parameters is important for system security.

The core idea is simple: the kernel’s parameter parser can identify these as hardware parameters and apply additional security checks — for example, preventing unauthorized changes to I/O port assignments on a locked-down secure boot system.

Hardware Parameter Types Supported by module_param_hw()
hw_type Keyword What It Represents Typical Use Case
ioport I/O port addresses Legacy ISA/PCI device I/O ports
iomem I/O memory mapped addresses MMIO regions for device registers
irq Hardware interrupt numbers Device interrupt line assignment
dma DMA channel numbers Legacy DMA device setup
dma_addr Fixed DMA buffer addresses Pre-allocated DMA regions
other Any other hardware resource Custom hardware-specific values

Code Example — module_param_hw() for IRQ

#include <linux/module.h>
#include <linux/moduleparam.h>

MODULE_LICENSE("GPL");

static int my_irq = 7;    /* default IRQ number */
static int my_ioport = 0x3F8; /* default I/O port */

/* Declare as hardware parameters — lockdown-aware */
module_param_hw(my_irq, int, irq, S_IRUGO);
MODULE_PARM_DESC(my_irq, "IRQ number for the device (default: 7)");

module_param_hw(my_ioport, int, ioport, S_IRUGO);
MODULE_PARM_DESC(my_ioport, "I/O port base address (default: 0x3F8)");

static int __init hw_param_init(void)
{
    pr_info("Device IRQ=%d, I/O Port=0x%X\n", my_irq, my_ioport);
    return 0;
}

static void __exit hw_param_exit(void)
{
    pr_info("Unloaded hw_param module\n");
}

module_init(hw_param_init);
module_exit(hw_param_exit);
⚠ Important Note — Secure Boot Systems:

On systems with Secure Boot enabled, hardware module parameters declared with module_param_hw() may be locked and cannot be overridden from the command line. This is intentional — it prevents malicious code from remapping hardware resources. Always use module_param_hw() instead of plain module_param() when your parameter controls a hardware resource.

Why Floating-Point Arithmetic is Not Allowed in the Linux Kernel

This is one of the most important rules every kernel and device driver developer must know. You cannot use floating-point arithmetic in Linux kernel space. This is not a bug or a limitation — it is a deliberate design decision made for performance and correctness reasons.

The Root Cause — Processor FPU State

Modern CPUs have a separate Floating-Point Unit (FPU) — sometimes also called the SSE or SIMD unit on x86 systems. When a userspace process uses floating-point math, the operating system saves and restores the FPU state as part of context switching.

However, the Linux kernel does not save and restore FPU state during normal kernel execution. The kernel code runs in a context where the FPU state belongs to whatever userspace process was running before. If kernel code were to use the FPU freely, it would silently corrupt that process’s floating-point registers. This would cause mysterious, hard-to-debug bugs in running user applications.

Saving and restoring the FPU state is an expensive operation. Doing it for every kernel code path that might want to use a float would add unacceptable overhead to every context switch and every kernel entry/exit. The kernel designers made the clean decision: no floating-point in kernel space.

Why Floating-Point Corrupts Userspace — Visual Explanation
Userspace Process A
(FPU holds: x=3.14, y=2.71)
↓
Syscall / Interrupt
(FPU state NOT saved)
Kernel Code Runs
(uses FPU freely)
↓
Return to userspace
(FPU now corrupted!)
Process A Reads FPU
(x=???, y=???)
Silent data corruption!

What Happens if You Try Anyway?

If you write a kernel module that uses double, float, or %f in a printk() format string, the kernel does not silently ignore it. Here is what actually happens:

  • Using %f in printk() triggers a WARN_ONCE() in the kernel, which prints a stack trace to the kernel log.
  • The kernel log message says: “Please remove unsupported %f in format string”
  • On a development system, this is a warning — the system does not crash immediately.
  • On a production system, /proc/sys/kernel/panic_on_warn is typically set to 1, which means the system will kernel panic.
  • The %f format specifier is not implemented in the kernel’s internal printk() — it is simply not supported.
🛑 Never Do This in Kernel Space:
/* WRONG — will cause WARN_ONCE or kernel panic on production */
double temperature;
temperature = raw_value / 1000.0;
printk(KERN_INFO "Temp: %.3f C\n", temperature); /* %f NOT supported! */

The Exception — kernel_fpu_begin() and kernel_fpu_end()

There is one narrow exception. If you absolutely must perform floating-point operations in the kernel — which is extremely rare and reserved for specific subsystems — you can bracket your FP code with two special macros: kernel_fpu_begin() and kernel_fpu_end().

These macros explicitly save and restore the FPU state, making it safe to use floating-point math in that protected section. You will find this technique used in a small number of places inside the kernel itself — primarily in cryptography code paths (AES acceleration), CRC computation, and similar performance-critical areas where hardware floating-point or SIMD instructions are needed.

#include <linux/module.h>
#include <linux/fpu.h>      /* kernel_fpu_begin/end — arch-specific */

MODULE_LICENSE("GPL");

static int __init fpu_demo_init(void)
{
    double result;

    /*
     * kernel_fpu_begin() saves the current FPU state.
     * After this point, it is safe to use floating-point ops.
     */
    kernel_fpu_begin();

    result = 22.0 / 7.0;   /* FP math is safe inside this block */

    kernel_fpu_end();       /* Restore FPU state for userspace */

    /*
     * STILL CANNOT use %f here!
     * printk() does not support floating-point format specifiers.
     * The FPU save/restore only makes the math safe — not printk().
     */
    pr_info("Result computed (cannot display with %%f)\n");
    return 0;
}

static void __exit fpu_demo_exit(void) { }

module_init(fpu_demo_init);
module_exit(fpu_demo_exit);
⚠ Critical Limitation:

Even with kernel_fpu_begin() / kernel_fpu_end(), you still cannot use %f in printk(). The FPU state save/restore only makes the arithmetic safe — it has nothing to do with printk’s format string handling. The kernel’s printk simply does not implement floating-point format specifiers.

kernel_fpu_begin/end — Decision Flow
Do I need floating-point in my kernel module?
NO (99% of cases)
Use integer arithmetic only.
Multiply/divide in userspace.
↕ YES (crypto, CRC, rare cases)
Use kernel_fpu_begin() before
and kernel_fpu_end() after.
✅ Safe, correct, recommended ⚠ Use only when unavoidable

The Right Way — Integer Arithmetic in the Kernel

The recommended approach for any calculation that would normally need floating-point is to do it with integer arithmetic in the kernel and let userspace handle the display or final computation. This is simpler, faster, and correct.

The classic example is a temperature sensor driver. A hardware sensor gives you a raw value in millidegrees Celsius. You do not need to divide by 1000.0 in the kernel — just pass the raw integer to userspace and divide there.

/*
 * Temperature sensor driver — correct kernel approach
 * Raw hardware value is in millidegrees Celsius (integer)
 */
static int __init temp_sensor_init(void)
{
    int raw_temp_millidegrees = 23750;  /* e.g., from hardware register */

    /*
     * Do NOT divide by 1000.0 here using floating point.
     * Instead, expose the raw integer value via sysfs or a char device.
     * Let userspace do: temperature_C = raw_value / 1000.0
     */

    /* If you must log it in the kernel, use integer split: */
    int whole = raw_temp_millidegrees / 1000;
    int frac  = raw_temp_millidegrees % 1000;

    pr_info("Temperature: %d.%03d degrees C\n", whole, frac);
    /* Output: Temperature: 23.750 degrees C */

    return 0;
}
Integer Split Trick — Displaying Decimal Values Without Floating Point
Step Operation Example (23750 millideg) Result
1 whole = raw / 1000 23750 / 1000 23
2 frac = raw % 1000 23750 % 1000 750
3 pr_info(“%d.%03d”, whole, frac) pr_info(“%d.%03d”, 23, 750) 23.750

Common Mistakes and How to Avoid Them

❌ Mistake 1: Using float or double in a kernel module

The compiler may accept it, but at runtime you risk FPU state corruption or a kernel panic.

Fix: Always work with integers. Scale your values (millidegrees, microvolts, etc.) instead of using decimal types.

❌ Mistake 2: Using %f in printk()

printk() does not support the %f format specifier. It will trigger WARN_ONCE() or panic.

Fix: Use the integer split trick shown above, or output the raw integer value and format it in userspace.

❌ Mistake 3: Using module_param() for hardware resource values

On secure boot systems, plain module_param() for IRQ or I/O port values bypasses lockdown checks.

Fix: Use module_param_hw() whenever the parameter represents a hardware resource.

❌ Mistake 4: Not pairing MODULE_PARM_DESC() with module_param_named()

Users running modinfo will see the external parameter name but no description.

Fix: Always write MODULE_PARM_DESC(external_name, "description here") for every parameter.

Best Practices for Kernel Module Parameters

✅ Use clear, short external parameter names — the user types these at insmod time.

✅ Always write MODULE_PARM_DESC() — this shows up in modinfo output and is the only documentation most users will see.

✅ Choose the smallest appropriate type — use bool, int, uint, or ulong as needed.

✅ Validate parameter values in your init function — do not trust user input; check ranges before using parameter values.

✅ Use S_IRUGO for read-only params, S_IRUGO|S_IWUSR for writable ones — think about whether the parameter should be changeable at runtime via sysfs.

✅ Use module_param_hw() for all hardware-resource parameters — this enables secure boot compatibility.

✅ Never use floating-point in kernel code — without exception (unless you are in a specialized subsystem and have wrapped everything in kernel_fpu_begin/end, and even then, avoid it if possible).

Key Takeaways

Summary — What You Learned in This Lecture
# Concept Key Point
1 module_param_named() Expose a user-friendly parameter name while keeping a different internal variable name
2 module_param_hw() Use for hardware resource parameters (IRQ, I/O port, DMA, IOMEM) — enables secure boot lockdown
3 Floating-point rule No float/double in kernel space — FPU state is not preserved during kernel execution
4 kernel_fpu_begin/end The only exception — wraps FP code safely, but %f in printk still not supported
5 Integer-only trick Split integer / modulo to display decimal-like values without any floating point

Frequently Asked Questions (FAQ)

Q1. What is the difference between module_param() and module_param_named()?

module_param() uses the same name for both the internal C variable and the external insmod argument. module_param_named() lets you use a different external name — useful when your internal variable name follows a subsystem-specific convention but you want a cleaner name for users.

Q2. Can I change a module parameter after the module is loaded?

Yes, if the sysfs permission is writable (e.g., S_IRUGO|S_IWUSR), you can change it at runtime via /sys/module/<modname>/parameters/<paramname>. However, your driver must handle this safely — there is no automatic callback when the value changes unless you use module_param_cb().

Q3. Why does the kernel not just save and restore FPU state automatically?

Saving and restoring FPU state adds significant overhead to every kernel entry and exit point. Since the vast majority of kernel code has no need for floating-point, making it mandatory would slow down the entire kernel for zero benefit. The opt-in approach with kernel_fpu_begin()/end() is the right trade-off.

Q4. What data types can I use with module_param()?

The supported types are: bool, invbool, charp (string pointer), short, ushort, int, uint, long, ulong. There is no float or double support — for the reasons discussed in this lecture.

Q5. Is module_param_hw() available in all Linux kernel versions?

The module_param_hw() family was introduced in Linux 4.10. It is fully available in all Linux 5.x and 6.x kernels. If you are building for very old kernels (pre-4.10), you would fall back to plain module_param(), but modern kernel development should always use module_param_hw() for hardware resources.

Q6. What happens to the FPU state during an interrupt handler?

Interrupt handlers run in a context where the FPU state definitely belongs to a running user process. Using floating-point inside an interrupt handler would be even more dangerous than in regular kernel code. The same rules apply — no floating-point in interrupt context, period.

Q7. How do I pass a string parameter to a kernel module?

Use the charp type with module_param():
static char *device_name = "default"; module_param(device_name, charp, S_IRUGO);
Then load with sudo insmod mymod.ko device_name="uart0".

Q8. Can I use module_param_array() with module_param_named()?

Yes. module_param_array_named(external_name, internal_array, type, nump, perm) combines array support with name overriding. This is useful when you want to pass multiple values (e.g., multiple IRQ numbers) while keeping a clean external name.

Q9. Does the no-floating-point rule apply to ARM and other architectures?

Yes, the rule applies to all Linux-supported architectures — x86, ARM, ARM64, RISC-V, MIPS, and others. The FPU state management issue is universal. The kernel_fpu_begin()/end() APIs are architecture-specific in implementation but exist (or have equivalents) across all major architectures.

Q10. Is there a way to verify my module’s parameters before loading it?

Yes. Run modinfo yourmodule.ko — it lists all declared parameters with their types and descriptions (from MODULE_PARM_DESC()). This works without loading the module and is the best way to document your driver’s configurable options.

Conclusion

In this lecture from EmbeddedPathashala’s free Linux kernel development course, you covered two important topics that every serious kernel and device driver developer must understand deeply.

First, you learned that module_param_named() gives you the flexibility to decouple internal variable names from the user-facing parameter interface — a small but valuable tool for writing clean, professional Linux device drivers. You also learned that module_param_hw() is the right choice whenever a parameter controls a hardware resource, because it enables kernel-level lockdown support for secure boot systems.

Second, and most importantly, you learned why floating-point arithmetic is forbidden in kernel space. This is not a restriction to fight against — it is a design principle that keeps the kernel fast and correct. The integer arithmetic techniques shown here are the professional way to handle measurements and calculations in Linux kernel modules.

These concepts are tested in kernel driver reviews and interviews frequently. Make sure you can explain both topics confidently. Happy kernel hacking!

Continue Your Free Linux Kernel Development Journey

EmbeddedPathashala offers completely free courses on Linux kernel programming, Linux device drivers, and embedded systems.

Browse All Free Courses Next Lecture →

← Previous Lecture Next Lecture →

💬 Need help or career guidance? Ask us!Contact Us →

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →