Queues and compiler optimization (GCC)

dorianabs wrote on Friday, September 29, 2006:

Hi all,

I had a bunch of problems with FreeRTOS queues in my MCU serial communication. I’ve made the H8S-2633 port of FreeRTOS (if someone is interested I can upload it somewhere), and started
my project with a modified version of serial.c of GCC H8S2329 demo example. In my application, the serial port is “hammered” with a protocol packets, and sometimes data byte inserted in queue (from serial RX ISR) with xQueueSendFromISR was “lost” in the queue itself ( or “delayed” of some positions inside the queue ). This because uxMessagesWaiting, uxLength and uxItemSize aren’t
updated in compilation level with -O2 parameter.

The solution is modify QueueDefinition in queue.c like this :

volatile unsigned portBASE_TYPE uxMessagesWaiting;
volatile unsigned portBASE_TYPE uxLength;
volatile unsigned portBASE_TYPE uxItemSize;

I hope this solution can be useful :slight_smile:

Luca

nobody wrote on Friday, September 29, 2006:

Why just those three members?  This would seem to also apply to the pcWriteTo, pcReadFrom, xRxLock and xTxLock members?

nobody wrote on Friday, September 29, 2006:

Why would the optimizer not change them?

uxLength is set once when the queue is created.  It is set at the same time as all the other members so if it were not set I would not expect any of the other members to be set either.  The structure being created is passed back as the return value so the optimizer cannot guess how the values are used so should do what the C code says.

Likewise of uxItemSize.

Messages waiting is a bit different.  This is set and tested from both task level and ISR level.  However it is only ever accessed via a pointer parameter, so again the optimizer cannot determine how the set value is used, if at all, so should do what the C code says.

dorianabs wrote on Friday, September 29, 2006:

Probably the “volatile” key isn’t need in all three members, in my spare time I can investigate more deeply. Anyway these changes at QueueDefinition structure, resolved my all my communication problems…

nobody wrote on Friday, September 29, 2006:

Maybe some of the parameters need to be declared volatile as

portBASE_TYPE xQueueSend( volatile portBASE_TYPE xQueueHandle xQueue, const void * pvItemToQueue, portTickType xTicksToWait );

Although I think maybe this is a red herring and that it is a GCC peculiarity.  I used VxWorks/GCC once and had to turn off certain optimization options to get that to work.  Never found the actual problem, just removing which option made the problem go away.