I was trying to write an example code for Per CPU Variable after reading from the book, but I am unable to get the expected output after updating the per cpu variable of one of the counter.

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

MODULE_LICENSE("GPL");
DEFINE_PER_CPU(int, counter);
static int test_percpu_init(void)
{
    int num_cpus = num_online_cpus();
    int i = 0;
    int val;

    pr_info("Number of cpus available:%d\n", num_cpus);
    for (i = 0; i < num_cpus; i++) {
        int value = per_cpu(counter, i);
        pr_info("Value of counter is %d at Processor:%d\n", value, i);
    }

    val = get_cpu_var(counter);
    val = 10;
    put_cpu_var(counter);

    pr_info("Printing counter value of all processor after updating current processor:%d\n",
            smp_processor_id());

    for (i = 0; i < num_cpus; i++) {
        int value = per_cpu(counter, i);
        pr_info("Value of counter is %d at Processor:%d\n", value, i);
    }


    return 0;
}

static void test_percpu_exit(void)
{
}

module_init(test_percpu_init);
module_exit(test_percpu_exit);

dmesg output:

[14516.661529] Number of cpus available:6
[14516.661531] Value of counter is 0 at Processor:0
[14516.661532] Value of counter is 0 at Processor:1
[14516.661532] Value of counter is 0 at Processor:2
[14516.661533] Value of counter is 0 at Processor:3
[14516.661533] Value of counter is 0 at Processor:4
[14516.661534] Value of counter is 0 at Processor:5
[14516.661534] Printing counter value of all processor after updating current processor:5
[14516.661534] Value of counter is 0 at Processor:0
[14516.661535] Value of counter is 0 at Processor:1
[14516.661535] Value of counter is 0 at Processor:2
[14516.661536] Value of counter is 0 at Processor:3
[14516.661536] Value of counter is 0 at Processor:4
[14516.661536] Value of counter is 0 at Processor:5

Can you please have a look, why is the value of the current processor not updating. Am I making any mistake in using the API's or passing any wrong arguments.

Thanks for your help

1 Answers

1
Tsyvarev On Best Solutions

Macro get_cpu_var returns a per-CPU variable on given CPU in form of lvalue, that is it can be treated in the very similar way as a simple variable:

// read per-CPU variable counter
int value = get_cpu_var(counter);
// write per-CPU variable counter
get_cpu_var(counter) = 10;
// get a pointer to per CPU variable
int* p_counter = &get_cpu_var(counter);
// read per-CPU variable via a pointer
int value = *p_counter;
// write per-CPU variable via a pointer
*p_counter = 10;