Retrieving current process/task_struct in linux kernel

As you know, processes are represented in the kernel by a 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.

[terminal]
struct thread_info {
struct task_struct *task; /* main task structure */

*****
[/terminal]

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

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

[/terminal]
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, the kernel makes use of below macro in an effective way.

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

[/terminal]

line number “2” performs 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 currently 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)