Page 1 of 1

2.6.x chTimeNow() safe without system lock?

Posted: Tue Jul 21, 2015 10:20 pm
by lilvinz
Hi Giovanni,

chTimeNow() is a marco returning vtlist.vt_systime.

https://github.com/ChibiOS/ChibiOS/blob ... hvt.h#L216

In its doxygen header it is marked as @api which means it can be used from outside of a system lock zone.

vtlist.vt_systime is incremented here:

https://github.com/ChibiOS/ChibiOS/blob ... hvt.h#L140

But there are architectures where the variable access is not an atomic operation like e.g. AVR.
systime_t of AVR port is uint16_t but AVR registers width is 8 bits and thus more than one instruction is required to read vtlist.vt_systime from memory.
As i understand it, this means chTimeNow() could return a value which is in the middle of being incremented.

https://github.com/ChibiOS/ChibiOS/blob ... ypes.h#L53

Shouldn't there be chTimeNowI() and shouldn't chTimeNow() access vtlist.vt_systime from within a system lock
- at least if access to vtlist.vt_systime is not guaranteed to be atomic?

Thanks for clarification and best regards

Vinz

Re: 2.6.x chTimeNow() safe without system lock?

Posted: Tue Jul 21, 2015 10:33 pm
by Giovanni
Hi,

It has been modified in 3.0 because of this, on 8bits architectures it is safer to call it from a critical zone.

Code: Select all

/**
 * @brief   Current system time.
 * @details Returns the number of system ticks since the @p chSysInit()
 *          invocation.
 * @note    The counter can reach its maximum and then restart from zero.
 * @note    This function can be called from any context but its atomicity
 *          is not guaranteed on architectures whose word size is less than
 *          @p systime_t size.
 *
 * @return              The system time in ticks.
 *
 * @xclass
 */
static inline systime_t chVTGetSystemTimeX(void) {

#if CH_CFG_ST_TIMEDELTA == 0
  return ch.vtlist.vt_systime;
#else /* CH_CFG_ST_TIMEDELTA > 0 */
  return port_timer_get_time();
#endif /* CH_CFG_ST_TIMEDELTA > 0 */
}

/**
 * @brief   Current system time.
 * @details Returns the number of system ticks since the @p chSysInit()
 *          invocation.
 * @note    The counter can reach its maximum and then restart from zero.
 *
 * @return              The system time in ticks.
 *
 * @api
 */
static inline systime_t chVTGetSystemTime(void) {
  systime_t systime;

  chSysLock();
  systime = chVTGetSystemTimeX();
  chSysUnlock();

  return systime;
}


You can assume it to be an "x-class" function and be forward-compatible.

Giovanni

Re: 2.6.x chTimeNow() safe without system lock?

Posted: Wed Jul 22, 2015 5:50 pm
by lilvinz
Hi Giovanni,

thanks for the clarification!

Cheers

Vinz