Android – How to run code on each CPU

How to run code on each CPU… here is a solution to the problem.

How to run code on each CPU

I’m trying to set the Performance Monitor user mode enable register on all CPUs on a Nexus 4 running mako kernel.

Now I’m setting the register in a loadable module:

    void enable_registers(void* info)
        unsigned int set = 1;
        /* enable user-mode access to the performance counter*/
        asm volatile ("mcr p15,  0, %0, c9,  c14, 0\n\t" : : "r" (set));

int init_module(void)
       online = num_online_cpus();
       possible = num_possible_cpus();
       present = num_present_cpus();
       printk (KERN_INFO "Online Cpus=%d\nPossible Cpus=%d\nPresent Cpus=%d\n", online, possible, present);
       on_each_cpu(enable_registers , NULL, 1);
       return 0;

The problem is that on_each_cpu only runs functions on the online CPU, as shown in the printk statement:

Online Cpus=1
Possible Cpus=4
Present Cpus=4

When I call on_each_cpu, only one out of four is online. So my question is, how do you force a CPU online, or how do you force a CPU to execute code?


You don’t need to run code on every CPU now. What you need to do is schedule it so that when the offline CPU comes back online, your code is able to execute and enable access to the PMU.

One way to achieve this is to use a CPU hot-plug notifier.

Related Problems and Solutions