Skip to content
Advertisement

Linux kernel – Context switch when calling function from other module?

I am curious if calling a function from a different module in the Linux kernel triggers a context switch?

Basically, I’m doing something like this.

Say I have module A:

uint64_t time;
int core;
int foo(){
   time = rdtsc();
   core = smp_processor_id();
   return time;
}
EXPORT_SYMBOL_GPL("foo");

module B:

uint64_t time1, time2;
int bar(){
    time1 = rdtsc();
    time2 = foo();
    printk(KERN_INFO "Difference: %dn", time2-time1);
}

between the two measurements, I’m seeing a gap of up to 2 microseconds (after dividing through the TSC frequency). Could this gap be due to a context switch?

Advertisement

Answer

No, this does not trigger a context switch.

When loading a linux module, it is dynamically linked into the kernel, similar as how dynamic libraries (libc etc.) are linked in memory when starting a dynamically linked program. Therefore, the call to foo() is really just a jump instruction to the address of that function, which was resolved on module loading.

However, the linux kernel nowadays is preemptive, which means, that the execution of a process can be preempted even when it is currently in kernel space, so a context switch to another process is possible, but shouldn’t be reproducible deterministically.

The time difference probably results from normal code execution, i.e. the calls to rdtsc() and smp_processor_id().

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement