Search code examples
clinuxlinux-kernelkernel-moduleprintk

how to perform arithmetic on fractions in a Linux module


I want to perform arithmetic on fractions, and I know that you can't perform floating-point arithmetic in kernel code, and I understand the reasons why the kernel doesn't allow that. What I am trying to do exactly is to load a module and calculate the elapsed time in seconds since the time the kernel module has been loaded and removed. I know how to do that using the value of jiffies and HZ like this:

#include <linux/jiffies.h>
unsigned long int first_jiff;

int start_init(void){
    first_jiff = jiffies;
    printk(KERN_INFO "loading kernel module\n");
    return 0;
}

void exit_init(void){
   float elapsed_seconds;
   //calculate the difference between first value of jiffies and the current one
   first_jiff = jiffies - first_jiff;

   elapsed_seconds = (float)(first_jiff / HZ);
   printk(KERN_INFO "elapsed_time:%f", elapsed_seconds);
}
module_init(start_init);
module_exit(exit_init);

but of course, I get this error

/include/linux/printk.h:464:44: error: SSE register return with SSE disabled

Is there any way to get around this?


Solution

  • You don't need floating point types here. Just do the division, which will be integer division, and store the result in an integer.

    void exit_init(void){
       unsigned long elapsed_seconds;
       //calculate the difference between first value of jiffies and the current one
       first_jiff = jiffies - first_jiff;
    
       elapsed_seconds = first_jiff / HZ;
       printk(KERN_INFO "elapsed_time:%lu", elapsed_seconds);
    }