Retrieving current process/task_struct in linux kernel


As you know, processes are represented in kernel by structure called ‘task_struct.… All the processes in kernel got its own kernel stack.. There is also an important structure called “thread_info” which is of size “52” bytes. .. Where “task” field in the thread_info structure is the association of process descriptor with the thread_info. The “rsp” or “esp”  ( stack pointers) can be effectively used by the kernel to retrieve information about the active process on the cpu.

struct thread_info {
        struct task_struct      *task;          /* main task structure */


‘thread_info’ and the ‘stack’ is a union as shown below..

union thread_union {
        struct thread_info thread_info;
        unsigned long stack[THREAD_SIZE/sizeof(long)];

Where  THREAD_SIZE is equal ( After macro filling)  to  ((_AC(1,UL) << 12) << 1)     which is 8192 ( for 8k stack).

To get ‘current’ process information, kernel make use of below macro in an effective way..

 movl $0xffffe000,%ecx /* or 0xfffff000 for 4KB stacks */
 andl %esp,%ecx
 movl (%ecx),p

line number “2” perform the main operation here.. The stack pointer “esp”‘s last “13” or “12” bits are masked ( 8k and 4k stacks effectively) to get the thread_info structure. The thread_info structure’s “0th” offset holds a pointer to the ‘task_struct’. Thus kernel can easily retrieve the current running process (line 3) from the cpu.

The  “current” variable in kernel code refers to this task_struct.

 #define get_current() (current_thread_info()->task)


Leave a Reply

Your email address will not be published. Required fields are marked *