Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

context of linux kernel threads

I wrote a simple kernel module that loops through all processes and extracts their registers saved when these were descheduled (especially EIP).

If I'm not wrong, what I need is saved on the kernel stack pointed by sp0 in the thread_struct of every process. This is what I do:

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

int init_module(void){
    struct task_struct *t;
    struct pt_regs regs;
    for_each_process(t){
       memcpy(&regs, (unsigned long*)(t->thread.sp0-sizeof(struct pt_regs)), sizeof(struct pt_regs));
       printk(KERN_INFO "%s eip: %lx\n", t->comm, regs.ip);
    }
    return 0;
}

void cleanup_module(void){
}

MODULE_LICENSE("GPL");

Now, the output about user-level processes seems legit:

[ 3558.322088] bash eip: b770b430

BUT all I get from kernel threads is always 0.

[ 3558.322095] kworker/0:0 eip: 0

I don't get it. Does the kernel save registers somewhere else when it comes to kernel threads?
Is it by chance related to kernel preemption?

I'm on a 3.14-1-486 kernel.

Thank you in advance.

like image 825
progacci Avatar asked Nov 01 '22 19:11

progacci


1 Answers

thread.sp0 is the userland SP. The kernel SP is thread.sp (and kernel ip is just thread.ip; this seems to exist on x86-32, but not x86-64).

A context switch always happens in kernel in the switch_to (one of definitions) macro, called from context_switch called from schedule. So the IP and SP used there point to kernel space.

When returning to userland, another SP and IP are needed. That is what you are reading.

kworker is a thread created internally in kernel for scheduling things that shouldn't be done in interrupts and don't have any particular process in context of which they would run. As such it does not have any userland code and therefore it's userland SP and IP are both zero. You can look at the kernel SP and IP, they should be non-zero (the IP should almost always be the same, pointing to the same place in context_switch)

like image 93
Jan Hudec Avatar answered Nov 09 '22 05:11

Jan Hudec