Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "sched_setaffinity()" in Linux Kernel

Lots of posts on sched_setaffinity, but almost none on using this in Kernel Space.

I am on Kernel 4.14.79.

I tried using the User Space method of calling sched_setaffinity in the form of:

cpu_set_t my_set;        
CPU_ZERO(&my_set);       
CPU_SET(7, &my_set);     
sched_setaffinity(0, sizeof(cpu_set_t), &my_set);

But upon trying to compile the Kernel, I got errors and realized this form will not work in Kernel Space.

I see that sched_affinity is defined in sched.h and has the form:

extern long sched_setaffinity(pid_t pid, const struct cpumask *new_mask);

But I am confused on how to correctly create the new_mask parameter with the correct CPU number. The documentation on it is not very helpful.

Can someone show an example of how to use this function in Kernel Space to set a process to a specific CPU?

like image 566
Mr.Mips Avatar asked Sep 21 '26 18:09

Mr.Mips


1 Answers

Found an answer myself after digging through Kernel files looking for where cpumask makes an appearance.

You can use these two functions:

cpumask_clear(struct cpumask *dstp) //clear the mask you are about to use

cpumask_set_cpu(unsigned int cpu, struct cpumask *dstp) //set the cpu number

So something like this is what I used:

struct cpumask mask;  
cpumask_clear(&mask); 
cpumask_set_cpu(cpuNumber, &mask); 
sched_setaffinity(pid, &mask); 
like image 166
Mr.Mips Avatar answered Sep 24 '26 17:09

Mr.Mips



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!