Page 1 of 4

Something strange with timers

Posted: Mon Jun 25, 2012 5:25 am
by king2
I have ported my app to ChibiOS and now step by step trying to switch my 'HAL needs' to ChibiOS.

I had UART protocol that worked with ChibiOS and custom IRQ/queue. But when I tried to switch it to Serial driver of ChibiOS, I found something strange.

First, function sdReadAsynchronous just not worked. It worked by itself after some minor changes in another thread.
I changed it to sdReadTimeout, tried to set breakpoint to it and step, it just jumps to start of 'while' loop instead of following to next statement.
Sometimes it worked for a second, then tried to execute empty memory content.

Couple times I have noted that something brokes variables (for example, in I2C driver of STM8S that I have ported according to STM32 driver, but without DMA).

Code: Select all

  I2C_TypeDef *dp = i2cp->i2c;   <<<----- here dp actually equal to i2cp->i2c, i.e to IO register
  VirtualTimer vt;
  msg_t rdymsg;

  chDbgCheck((rxbytes > 1), "i2c_lld_master_receive_timeout");

  /* Global timeout for the whole operation.*/
  chVTSetI(&vt, timeout, i2c_lld_safety_timeout, (void *)i2cp);

  /* Releases the lock from high level driver.*/
  chSysUnlock();

  /* Initializes driver fields, LSB = 1 -> receive.*/
  i2cp->addr = (addr << 1) | 0x01;
  i2cp->errors = 0;
  i2cp->rxbuf = rxbuf;
  i2cp->rxbytes = rxbytes;
  i2cp->rxindex = 0; // start with first byte :)

  /* Waits until BUSY flag is reset and the STOP from the previous operation
     is completed, alternatively for a timeout condition.*/
  while ((dp->SR3 & I2C_SR3_BUSY) || (dp->CR2 & I2C_CR2_STOP)) {  <<<<--- here it sometimes points to somewhere in RAM
    if (!chVTIsArmedI(&vt)) {
      chSysLock();
      return RDY_TIMEOUT;
    }
  }

I noted that 'dp' variable brokes after timer function (I didn't remember exactly, but I had breakpoint in this place in right time and tried to trace).
Increasing stack for thread that doing I2C exchange solved the problem that time.

I tried to increase stack size of threads in this case too, this helped a bit (at least it does not broking 'dp' variable in I2C driver in master_receive_timeout, yes, it started do it again!), but serial thread makes surprises from time to time (executing empty flash, or something like this).

Here is my code:

Code: Select all

// timeout(s) functions
void setTimeout(systime_t * timer, unsigned int timeout) {
    *timer = chTimeNow() + MS2ST(timeout);
}
unsigned char timeoutExpired(systime_t * timer) {
    return chTimeIsWithin(0, *timer)?0:1;
}

Code: Select all

    while (1) {
        // check if message was received
        if (sdReadTimeout(&SD3, (uint8_t *) tmp, 1, MS2ST(50)) && shproto_received(&received_msg, 0x81, tmp[0])) { // read a byte (successful)
            if (!console.found) {
                if (console.lowspeed && !timeoutExpired(&timeout_console_lowspeed)) { // found just after switching to low speed
                    error_register(ERROR_CONSOLE_LOWSPEED_OK); // console was found then lost
                }
                console.found = 1;
            }

            // collect data
            console.on = received_msg.data[1];
            console.level = received_msg.data[0];
            timeout_counter = 3; // 3 tries left from this point
            waiting_answer = 0;
            setTimeout(&timeout_console_msg, MS2ST(100)); // wait 100 ms to next query
        }

        // send message
        if (!waiting_answer && timeoutExpired(&timeout_console_msg)) {
            shproto_transmit(buffer, 0x02, 0x02, (unsigned char *) &console.led, 1);
            sdWrite(&SD3, (uint8_t const*) &buffer, 7+1);
            setTimeout(&timeout_console, TIMEOUT_CONSOLE);
            waiting_answer = 1;
        }

        // timeout condition
        if (timeoutExpired(&timeout_console)) {
            if (console.found) {
                error_register(ERROR_CONSOLE_LOST); // console was found then lost
            } else {
                error_register(ERROR_CONSOLE_NOTFOUND); // console was notfound
            }
            console.found = 0;
            console.on = 0;
            console.level = 0;

            if (!timeout_counter) {  // already tried 3 times..
                if (!console.lowspeed) { // try to switch to low speed
                    console.lowspeed = 1; // lower and lower...
                    //UART3_BRR2 = 0x1B; UART3_BRR1 = 0xA0; // set low speed (2400)
                    setTimeout(&timeout_console_lowspeed, TIMEOUT_CONSOLE_LOWSPEED);
                } // ... else work as usual and try to send messages
            } else {
                timeout_counter--;  // decrement counter
            }
            waiting_answer = 0;
        }
        chThdSleepMilliseconds(1); // we need to receive own echo from channel
    }


Here is two side effects:
1. When I increased timeout from TIME_INFINITE to MS2ST(50) in sdReadTimeout, time from start to end of transmission was increased.
2. When serial communication was stalled, I breaked execution and looked at timeout_console_msg. It was 0xFF3F, what is definitely wrong.

I have tried to be provide maximum detailed explanation of problem.
Can you give me some advice?

Thanks in advance!

p.s. and sorry for my english :)

Re: Something strange with timers

Posted: Mon Jun 25, 2012 6:24 am
by king2
I did timeout system as described in viewtopic.php?f=2&t=476.

Can it be that (while system_time_t is unsigned int):
- I set timeout as systemtime+0xF0 while systemtime==0xFF00
- another threads in action while systemtime overflows and skips to 0
- systemtime counted from zero again, but interval is not within range... :(

Can this thing be happened with another timer related functions?

Re: Something strange with timers

Posted: Mon Jun 25, 2012 7:53 am
by Giovanni
Are you sure that the context switch routine saves all the required context for your compiler? if not, you may experience that mysterious corruption of variables when more threads are involved. The current STM8 ports (Raisonance and Cosmic) have different page 0 variables to be saved, I don't know what is required for IAR.

I don't understand the timeout problem, a range from 0xff00 to 0xfff0 is perfectly valid, zero is outside that range.

Giovanni

Re: Something strange with timers

Posted: Wed Jun 27, 2012 3:57 pm
by king2
Wow, yes, I checked range from 0 to desired time. Now all is OK with timers.

But I still have a problem, my app contains 4 threads:
1. reading and writing from/To SD1 via Serial driver
2. collecting info via I2C
3. modifying variables
4. reporting variables to SD3 Serial
All information exchange is done via global variables without locks, because all information is not needed to be too actual :) MCU is STM8S208CB6, 8K RAM.

Sometimes, especially with active Serial transfer, I have transfer stalled. This happens from time to time in different places. When I reduce quantity of threads communicating, problem disappears.

I have tried to view 0x55's in threads struct, and have seen that 0x55's in all of threads, but in some cases there are two places with 0x55's inside, with some data in between. System stack limit was not exceeded, I see much of 0xCD there.

I have no ideas how to debug this...

Re: Something strange with timers

Posted: Wed Jun 27, 2012 4:15 pm
by king2
Forgot to mention, I have tried to make 'break' when thread alredy stalled, its status=0x0D and I found no timer for waking up this thread in 'vt' structure.

Is this means that thread will be never waked up?

Re: Something strange with timers

Posted: Wed Jun 27, 2012 4:34 pm
by mabl
king2 wrote:All information exchange is done via global variables without locks, because all information is not needed to be too actual :) MCU is STM8S208CB6, 8K RAM.

You are aware of the fact, that if you do not protect your read and writes and your variable cannot be accessed atomically, you might read wrong values, are you?

Re: Something strange with timers

Posted: Wed Jun 27, 2012 4:46 pm
by king2
Sure, atomic reads achieved automatically due to unsigned char values :)

What about IAR specific context switcher, I have found some information here: http://www.kelvinsthunderstorm.com/stm8 ... workbench/

But I have no knowledge to do things right porting _port_switch() routine to ChibiOS, but I think that not storing '?bxx' registers can be a reason.
Maybe, somebody can help and give me right code for _port_switch()?

Re: Something strange with timers

Posted: Wed Jun 27, 2012 6:57 pm
by Giovanni
If you look at the Raisonance and Cosmic port context switch you will see that port_switch() saves certain pseudo registers in page zero that are used by the compiler for its operations. Being those static variables the context switch routine must take care to switch them just like registers.

Reading that explanation only B8..B15 need to be saved in intctx, the others should be part of extctx, you need to examine the prologue/epilogue of ISR functions in order to assess how extctx is composed (note that extctx is not critical, it is used mainly to take its sizeof when computing the total working area size of a thread).

This is the most critical part of a port and can cause the kind of random problems you described.

Giovanni

Re: Something strange with timers

Posted: Wed Jun 27, 2012 7:54 pm
by king2
Yes, I understand this, but my knowledge is not enough to analyze extctx and intctx (and I do not know how to do this).

I have tried to just put all theese 'push ?b15' and so on to inline asm, but failed (it just does not compile, it do not know what is '?b15').
I have compiled all without optimization, but my last experience with ASM was a 10 years ago, so I have choice: or somebody will help me (i.e write switch routine for IAR), or I have to switch to another OS or do all thing in interrupts with many state machines.. :(

Ok, thanks..

Re: Something strange with timers

Posted: Wed Jun 27, 2012 8:16 pm
by Giovanni
Hi,

I am not going to buy such an expensive compiler for a platform I don't have interest in so the most I can do is give a look to the documentation, assuming it is present in the 8K limited version. 8K are not enough to test the OS.

Giovanni