Problem with queues

ChibiOS public support forum for all topics not covered by a specific support forum.

Moderators: RoccoMarco, lbednarz, tfAteba

Post Reply
qzole
Posts: 4
Joined: Wed May 18, 2011 9:24 am

Problem with queues

Post by qzole »

Hi Giovanni,
I've got a problem with queues that are implemented in chibiOS 2.0 (same in newest version), it seems they can over-write/over-read in some special scenarios, I'll make a short example here, using an output queue and
chOQPutTimeout

Code: Select all

msg_t chOQPutTimeout(OutputQueue *oqp, uint8_t b, systime_t time) {
   msg_t msg;
 
   chSysLock();
   if ((msg = chSemWaitTimeoutS(&oqp->q_sem, time)) < RDY_OK) {
     chSysUnlock();
     return msg;
   }
   *oqp->q_wrptr++ = b;
   if (oqp->q_wrptr >= oqp->q_top)
     oqp->q_wrptr = oqp->q_buffer;
 
   if (oqp->q_notify)
     oqp->q_notify(oqp);
 
   chSysUnlock();
   return Q_OK;
}

Thread W tries to write to the queue, but it is full, so it will start sleeping in chSemWaitTimeoutS, after this Thread A, a high priority thread starts running and does some important and a bit lengthy operation.
While this is happening the interrupt that reads the output queue kicks in and reads one byte, and signals the semaphore, that there is room in the queue again, which will put the thread in ready state, but since Thread A has higher priority, the scheduler won't actually start the writer thread again. Again the interrupt kicks in, and reads a byte, and it actually kicks in so many times that it reads the whole queue empty, while the writer thread had no opportunity to finish the writing, and since the semaphore was already decreased when the waiting started, the interrupt reads the byte that was supposed to be written by Thread W.

This happened with an STM32 while trying to upload a GSM firmware (2.5 MB) through a serial port.

I have a suggested fix for this with putting additional logic in to the queues, a counter which only gets modified in the lock zone, and additional checks after we come out of the sleep:

new field in the GenericQueue struct: cnt_t q_counter, acts the same way as the semaphore, but won't go into negative values, and only get's modified in lock zone, where no sleeping occurs
chQSpace(q) uses this new counter, so: #define chQSpace(q) (q)->q_counter

The additional if after the semaphore wait, is required to detect whether there was a queue reset, after the semaphore was signaled.
Actual case that happened:
With input queue, a thread was trying to read from it, but it was empty, so it went into the semaphore wait. A high priority thread started running, and an interrupt put a byte into the queue, and signaled the semaphore, which again did not resume running because of the high priority thread. The interrupt got called again, but something bad happened and it decided that the queue has to be reseted, so it resets it. The high priority thread stops running, and the reader thread can resume, and now would read from a reseted queue. (Code was slightly different then, and it caused an infinite loop in syslock, and thus a hardware watchdog reset)

Code: Select all

msg_t chOQPutTimeout(OutputQueue *oqp, uint8_t b, systime_t time) {
  msg_t msg;

  chSysLock();
  if ((msg = chSemWaitTimeoutS(&oqp->q_sem, time)) < RDY_OK) {
   chSysUnlock();
   return msg;
  }
  if (oqp->q_sem.s_cnt >= oqp->q_counter) {
   chSysUnlock();
   return RDY_RESET;
  }
  *oqp->q_wrptr++ = b;
  --oqp->q_counter;
  if (oqp->q_wrptr >= oqp->q_top)
    oqp->q_wrptr = oqp->q_buffer;

  if (oqp->q_notify)
    oqp->q_notify();

  chSysUnlock();
  return Q_OK;
}

If you'd like, I can upload the modified files, just tell me, where should I do that.
User avatar
Giovanni
Site Admin
Posts: 14895
Joined: Wed May 27, 2009 8:48 am
Has thanked: 1202 times
Been thanked: 997 times

Re: Problem with queues

Post by Giovanni »

Hi qzole,

Thanks for finding this, could you post a patch (or simply a zip file) or the forum? If you want to access the repository you have to register on SF first then I can enable you as developer.

Giovanni
qzole
Posts: 4
Joined: Wed May 18, 2011 9:24 am

Re: Problem with queues

Post by qzole »

Hi again,

Of course, here is a zip file of the .h and .c, I tried to attach them before, but I didn't know what kind of extensions were allowed.
These are modified from version 2.0, and the comments weren't changed.
Also this kind of problem probably exists in similar structures, like the mailbox.

Regards,
qzole
Attachments
chqueues.zip
(5.71 KiB) Downloaded 615 times
User avatar
Giovanni
Site Admin
Posts: 14895
Joined: Wed May 27, 2009 8:48 am
Has thanked: 1202 times
Been thanked: 997 times

Re: Problem with queues

Post by Giovanni »

I found an user Qzole on SF, registered 5 hours ago, is that you? please confirm so I can enable you.

About the problem, I think it would be possible to use the counter as you proposed and remove the semaphore entirely by replacing it with a simpler ThreadQueue object, this way we would not add 4 more bytes to the queue structure. Using an external counter the semaphore becomes unnecessary.

The function would become:

Code: Select all

msg_t chOQPutTimeout(OutputQueue *oqp, uint8_t b, systime_t time) {
  chSysLock();
 
  while (oqp->q_cnt <= 0) {
    msg_t msg;

    if ((msg = queue_sleep(oqp, time)) < RDY_OK) {
      chSysUnlock();
      return msg;
    }
  }

  oqp->q_cnt++;
  *oqp->q_wrptr++ = b;
  if (oqp->q_wrptr >= oqp->q_top)
    oqp->q_wrptr = oqp->q_buffer;

  if (oqp->q_notify)
    oqp->q_notify(oqp);

  chSysUnlock();
  return Q_OK;
}


Note the sleep within a "while" in order to re-check the condition on after exiting the sleep in case some higher priority thread took the freed queue slot.

Giovanni
User avatar
Giovanni
Site Admin
Posts: 14895
Joined: Wed May 27, 2009 8:48 am
Has thanked: 1202 times
Been thanked: 997 times

Re: Problem with queues

Post by Giovanni »

qzole wrote:Also this kind of problem probably exists in similar structures, like the mailbox.


I'll verify but the mailbox is a bit different, it has both an empty and a full counters.

Thanks,
Giovanni
qzole
Posts: 4
Joined: Wed May 18, 2011 9:24 am

Re: Problem with queues

Post by qzole »

Yes, I am that Qzole.

I think the change you proposed would be unable to check if the queue has been reset while it was waiting for a higher priority thread after the sleep.
This could mean potentially unwanted writes/reads, to/from a queue.

Now that I think of it, the check I proposed with the semaphore counter and resource counter maybe wouldn't always work.

Some examples for these problems:
W1 wants to write to the queue, but the queue is full, so it starts waiting.
An interrupt reads from the queue, and signals W1, that there is space in the queue, but another higher priority thread is running, so it won't resume yet.
That higher priority thread decides that the queue should be reset, and now expects that data written to the queue will be now new data.
Now when W1 resumes, it will find the queue empty, so it will write to it.
The check I proposed could see here that the queue had been reset, so would exit with RDY_RESET.

I will come up with a feasible scenario where my reset check won't work, but I'll post this until then.

Also, I did not find queue_sleep in the 2.3.1 docs/files, neither in the 2.0 source, so I assumed it works similarly as a semaphore wait.

qzole
User avatar
Giovanni
Site Admin
Posts: 14895
Joined: Wed May 27, 2009 8:48 am
Has thanked: 1202 times
Been thanked: 997 times

Re: Problem with queues

Post by Giovanni »

The function queue_sleep() does not exist, it would be implemented as queue_insert() followed by a chSchGoSleepTimeoutS().

About the RDY_RESET condition I think we should clarify the behavior.

The intended behavior is that when a queue is reset all the threads waiting on the queue are awakened with a RDY_RESET message. If the thread W1 is not waiting in the moment that the queue has been reset (it is ready, so not waiting anymore) then the write can be performed, it would be logically performed after the queue reset.

Those kind of low level messages (RDY_RESET, RDY_TIMEOUT) can only be fetched when exiting a sleep state, signaling the RDY_RESET to a thread that entered chOQPutTimeout() but is no more in the sleep state would require some kind of flagging and extra code.

Giovanni
User avatar
Giovanni
Site Admin
Posts: 14895
Joined: Wed May 27, 2009 8:48 am
Has thanked: 1202 times
Been thanked: 997 times

Re: Problem with queues

Post by Giovanni »

Hi again,

I committed a tentative fix on the repository, do you mind to test it in your application? the complete fix is quite extensive but the subsystem seems too be faster too looking at the benchmark results.

Let's continue evaluating the RDY_RESET issue, I just want to verify the correct behavior of the queues.

BTW, now you have write permission on the repository but please do not commit directly on the trunk, I need to keep it always in an "almost stable" state. It is better to work on private branches then merge when it is done and discussed.

Giovanni
qzole
Posts: 4
Joined: Wed May 18, 2011 9:24 am

Re: Problem with queues

Post by qzole »

I'm running the application the fix you committed, there seems to be no problems with it thus far.
One thing though, is that in chIQGetTimeout the notify call is before the read, which could lead to the loss of notification (read from empty queue, so it waits, and other thread fills up the queue meanwhile, finally when reader resumes, will read a byte from full queue, but now will not give out a notification).

I agree on what you said about the RDY_RESET, but I'll give you an example of what started my pondering.

When there is a thread that's purpose is to read from an input queue, and I want to be able to turn on or off this reading functionality, I'd like a way to stop the reading without the need to wait for the read to timeout.

Code: Select all

msg_t readerThdFunc()
{
   msg_t data;
   bool readerEnabledLocal;
   while (1) {
                chMtxLock(readerMtx);
      readerEnabledLocal = readerEnabled;
                //possible other paramteres
      chMtxUnlock;
      if (readerEnabledLocal && data = chIQGetTimeout(iqp, S2St(10)) > 0) {
         //do something with data
      } else if (!readerEnabledLocal) {
         chMtxLock(readerMtx);
                        if (chCondWaitTimeout(readerCondVar, S2ST(10)) != RDY_TIMEOUT) {
                             chMtxUnlock();
                        }
      }
   }
   return 0;
}

void  enableReader(bool enable)
{
        chMtxLock(readerMtx);
   readerEnabled = enable;
        chSysLock();
        chIQResetI(iqp);
        chSysUnlock();
        chCondBroadcast(readerCondVar);
        chMtxUnlock();
}


I can't seem to find a way to make this work without waiting for the queue read to timeout, but this also seems a bit unconnected to the RDY_RESET issue, since the queue could be reset just before the call to chIQGetTimeout.

Maybe if the condition variable could be connected to the queue, that way the mutex could be extended through the whole reading thread, since it would go to sleep (and would also wait on the condition) if the queue is empty, but this sounds messy, and doesn't seem like a general solution to this kind of problem.

regards,
qzole
User avatar
Giovanni
Site Admin
Posts: 14895
Joined: Wed May 27, 2009 8:48 am
Has thanked: 1202 times
Been thanked: 997 times

Re: Problem with queues

Post by Giovanni »

Hi,

Thanks for noticing, probably the notification should go inside the loop so it is sent each time the thread reenters qwait().

About your issue, probably the queues would need a "close" feature in addition to reset, the I/O functions would then return Q_CLOSED, this would better fit in the scenario you were proposing, of course it should also be present a way to reopen the queue (may be resetting it).

Probably not a bad feature to add, the state could be encoded as a NULL pointer or a special q_counter value like ((size_t)-1), this would not increase the structure size.

Giovanni
Post Reply