Page 1 of 1

Allowing thread local storage for mainthread

Posted: Thu Mar 23, 2017 3:48 am
by genosensor
ChiBiOS threads support thread local storage between the Thread struct and the thread's stack (which typically grows down toward the Thread struct). These thread local variables are handy and worked great until I tried using it on mainthread.
Then, instant segfault panic, because the mainthread's Thread struct is located just before the system's VTimer list base!

Why can't the mainthread Thread struct be at the base of the thread's stack, as is the case with all other threads?

In chsys.c, delete the mainthread declaration and change:

Code: Select all

setcurrp(_thread_init(&mainthread, NORMALPRIO));
currp->p_stklimit = &__main_thread_stack_base__;

to:

Code: Select all

setcurrp(_thread_init((Thread *)&__main_thread_stack_base__, NORMALPRIO));
currp->p_stklimit =
    &__main_thread_stack_base__ + sizeof(Thread)/sizeof(stkalign_t) + 1;


Are there ChiBiOS supported systems where this would not work?

Re: Allowing thread local storage for mainthread

Posted: Thu Mar 23, 2017 8:32 am
by Giovanni
Hi,

In RT4 the thread structure is no more placed at the base of the working area because:
1) It was a perfect target for an overflowing stack, making debugging harder.
2) It was conficting with MPU protection, now there is a guard page in that place.

You may use the thread structure extension hook and add a field pointing to your TLS, you could allocate it anywhere, not necessarily below the stack.

Giovanni