This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

Stack switches and C function local variables

Hi,

[The following is about SYS/BIOS code for Cortex-A8. I haven't looked into code for other architectures.]

I would like to point out that switching stack in a middle of C function is a very unsafe practice. According to the C standard it can lead to unpredictable results depending on the specific compiler and compiler optimizations enabled. For example, in the following function:

void foo() {
    [local vars A];
    [local vars B];
    [do something using vars A];
    switchStack();
    [do something using vars B];
    switchStackBack();
    [do something using vars A];
}

As the compiler is not aware of the stack change, it can rearrange the assembly instructions so that they access "vars A" after stack change (or vice versa), leading to wrong (unpredicted) behaviour.
Obviously, writing unportable code that works only with specific version of specific compiler and with specific optimizations is also a very bad practice.

Now, how is this related to SYS/BIOS? SYS/BIOS had two places where the above problematic approach has been used - in Hwi IRQ handler and in Swi_schedule() function. Last SYS/BIOS release (6.35.04.50) fixed this in the IRQ handler, now the stack switch is performed in assembly code (why it was changed is clear, for the above reasons it leaded to buggy behaviour). However, the Swi code is left.

I propose to change the Swi code in the following fashion:

void Swi_schedule()
{
    [local vars A];
    [do something using vars A];
    runOnIsrStack(&innerFunc);
    [do something using vars A];
}

void innerFunc()
{
    [local vars B];
    [do something using vars B];
}

When runOnIsrStack function is implemented in assembly.

1. This will prevent the dangerous dependency on compiler optimizations introduced above.

2. Moreover, this will solve the confusing situation with local variables, thus enabling to remove comments like the following:

    /*
     * Enough room is reserved above the isr stack to handle
     * as many as 16 32-bit stack resident local variables.
     * This space is reserved for the Swi scheduler.
     *
     * If the swi scheduler requires more than this, you must
     * handle this in Hwi_Module_startup().
     */

Best regards,
Vasili