Why pxTopOfStack is volatile in the TCB?

I am trying to understand why pxTopOfStack is volatile. If the port layer does not directly access TCB and instead uses a getter for the pxTopOfStack, would the return type be a volatile pointer or its okay to cast away volatileness?

The stack pointer (pxTopOfStack) can be modified asynchronously by the scheduler, interrupt service routines (ISRs), or task switching routines.
During a context switch, FreeRTOS saves and restores the stack pointer of a task.
Since context switching can happen at any time, marking it volatile ensures that every time the variable is accessed, the latest value is fetched from memory rather than using a outdated value from a register or cache.

Without volatile, an incorrect or optimized-out stack pointer could lead to undefined behavior.

3 Likes

pxCurrentTCB is accessed from assembly code directly. Are you adding a getter for it? If yes, please keep the return type as volatile. The following is from the C standard -

If an attempt is made to refer to an object defined with a volatile-qualified type through use of an lvalue with non-volatile-qualified type, the behavior is undefined.

Also, why are you adding a getter for it?

1 Like

Thank you, this makes sense.

Hi Gaurav, we are moving the portable.h out as an interface and moving port code in their own repositories not same as kernel. We are trying to avoid externing pxCurrentTCB and instead adding getters for things that port needs.

That’s interesting! Feel free to reach out to us if you face any problem.

Would you also share your motivation for doing the same? Also, do you plan to open source this work?

Interface is to minimize the dependency between the kernel and the port. For example, if non port related changes are made in the kernel, port does not need to be released. Unfortunately, we do not plan to open source this work.

Thank you for sharing!

1 Like