Linux Kernel code "current" macro

I was going through the Linux code, i stuck with few inline assembly language code,

I have tried online but in vain. Any help is much appreciated. Thanks.

/* how to get the thread information struct from C */
static inline struct thread_info *current_thread_info(void)
{
    struct thread_info *ti;
    __asm__("andl %%esp,%0; ":"=r" (ti) : "0" (~(THREAD_SIZE - 1)));
    return ti;
}

I have understood the point that it is being taken from kernel mode stack of size 8192 bytes. But couldn't understand the assembly langauage instruction.

I believe you find the answer here:
Extended Asm - Using the GNU Compiler Collection (GCC)

esp would be the x86 stack pointer. And %0 is a variable parameter which in this case means ~(THREAD_SIZE-1) The stack is the context which thread-local variables, among other things, reside inside. Each thread gets their own little independent chunk.

I believe they're doing something similar to aligning a pointer along page boundaries. If the stack pointer was, say 0xfeff7352 and THREAD_SIZE was 0x00010000, they'd be doing 0xfeff7352 & 0xffff0000, you'd get 0xfeff0000 out of it. I suppose doing this would get you the very top of the thread's stack instance, where (I think) things like the thread ID are kept handy.

THREAD_SIZE may not be the system page size but is probably at least a power-of-two multiple of it.

1 Like

Thanks for your explanation Corona.

I would like add few things about the context where the code is found. This acutaly found inside the marco current, which will hold the process descriptor being accessed by the process running on a particular CPU.

the process desccriptor pointer is stored in one end of the kernel stack which usually of 8192 bytes.