Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Significance of having thread_struct in Process Stack

Wanted to know why thread_struct is a part of the Process Stack in Linux. Robert Love says, it could be at the lowest memory address of the process stack.

1) Why do we need to have it in the first place in the Process Stack?

2) If we need to have it at a fixed address (lowest memory address) of the process stack - does this mean the size of the Process Stack is Fixed?

like image 824
S22 Avatar asked Mar 03 '26 13:03

S22


1 Answers

The reason thread_struct is located at a fixed offset from the stack is because it is a data structure that is accessed a lot and a separate one is needed per task.

As such, the best thing to do is put the address of the thread_struct into a register. This way its address is already in a register every time we need it in order to access it AND since registers are swapped as part of task context switch the address would be automatically changed every time we switch tasks.

There is only one problem - some architecture, like x86, have a very limited supply of registers. "Wasting" a whole register just for the thread_struct address is not feasible.

However, we already have a dedicated register pointing to the stack. By placing the thread_struct at a fixed offset from the stack start we are able to get the address of this important data structure by applying a bit mask to the value of the stack pointer register - so we get the best of both worlds - cheap access to thread_stuck AND not wasting a register.

And yes, kernel space task stacks are limited, typically to either one or two architecture pages, but trick with the thread_struct and stack pointer is not the reason.

like image 109
gby Avatar answered Mar 05 '26 21:03

gby