How does linux handle overflow in jiffies? - c

Suppose we have a following code:
if (timeout > jiffies)
{
/* we did not time out, good ... */
}
else
{
/* we timed out, error ...*
}
This code works fine when jiffies value do not overflow.
However, when jiffies overflow and wrap around to zero, this code doesn't work properly.
Linux apparently provides macros for dealing with this overflow problem
#define time_before(unknown, known) ((long)(unkown) - (long)(known) < 0)
and code above is supposed to be safe against overflow when replaced with this macro:
// SAFE AGAINST OVERFLOW
if (time_before(jiffies, timeout)
{
/* we did not time out, good ... */
}
else
{
/* we timed out, error ...*
}
But, what is the rationale behind time_before (and other time_ macros?
time_before(jiffies, timeout) will be expanded to
((long)(jiffies) - (long)(timeout) < 0)
How does this code prevent overflow problems?

Let's actually give it a try:
#define time_before(unknown, known) ((long)(unkown) - (long)(known) < 0)
I'll simplify things down a lot by saying that a long is only two bytes, so in hex it can have a value in the range [0, 0xFFFF].
Now, it's signed, so the range [0, 0xFFFF] can be broken into two separate ranges [0, 0x7FFF], [0x8000, 0xFFFF]. Those correspond to the values [0, 32767], [ -32768, -1]. Here's a diagram:
[0x0 - - - 0xFFFF]
[0x0 0x7FFF][0x8000 0xFFFF]
[0 32,767][-32,768 -1]
Say timeout is 32,000. We want to check if we're inside our timeout, but in truth we overflowed, so jiffies is -31,000. So if we naively tried to evaluate jiffies < timeout we'd get True. But, plugging in the values:
time_before(jiffies, offset)
== ((long)(jiffies) - (long)(offset) < 0)
== (-31000 - 32000 < 0) // WTF is this. Clearly NOT -63000
== (-31000 - 1768 - 1 - 30231 < 0) // simply expanded 32000
== (-32768 - 1 - 30232 < 0) // this -1 causes an underflow
== (32767 - 30232 < 0)
== (2535 < 0)
== False
jiffies are 4 bytes, not 2, but the same principle applies. Does that help at all?

See for example here: http://fixunix.com/kernel/266713-%5Bpatch-1-4%5D-fs-autofs-use-time_before-time_before_eq-etc.html
Code with checking overflow against some fixed small constant was converted to use time_before. Why?
I'm just summarizing the comment that goes with the definition of the
time_after etc functions:
include/linux/jiffies.h:93
93 /*
94 * These inlines deal with timer wrapping correctly. You are
95 * strongly encouraged to use them
96 * 1. Because people otherwise forget
97 * 2. Because if the timer wrap changes in future you won't have to
98 * alter your driver code.
99 *
100 * time_after(a,b) returns true if the time a is after time b.
101 *
So, time_before and time_after is the better effort of handling overflow.
Your testcase is more likely to be timeout < jiffles (w/o overflow) than timeout > jiffles (with overflow):
unsigned long jiffies = 2147483658;
unsigned long timeout = 10;
And if you will change timeout to
unsigned long timeout = -2146483000;
what will be an answer?
Or you can change the check from
printf("%d",time_before(jiffies,timeout));
to
printf("%d",time_before(jiffies,old_jiffles+timeout));
where old_jiffles is saved value of jiffles at the timer's start.
So, I think the usage of time_before can be like:
old_jiffles=jiffles;
timeout=10; // or even 10*HZ for ten-seconds
do_a_long_work_or_wait();
//check is the timeout reached or not
if(time_before(jiffies,old_jiffles+timeout) ) {
do_another_long_work_or_wait();
} else {
printk("ERRROR: the timeout is reached; here is a problem");
panic();
}

Given that jiffies is an unsigned value, a simple comparison is safe across one wraparound point (where signed values would jump from positive to negative) but not safe across the other point (where signed values would jump from negative to positive, and where unsigned values jump from high to low). It's protection against this second point that the macro is intended to solve.
There is a fundamental assumption that timeout was initially calculated as jiffies + some_offset at some prior recent point in time -- specifically, less than half the range of the variables. If you're trying to measure times longer than this then things break down and you'll get the wrong answer.
If we pretend that jiffies is 16-bit wide for convenience in the explanation (similar to the other answers):
timeout > jiffies
This is an unsigned comparison that is intended to return true if we have not yet reached the timeout. Some examples:
timeout == 0x0300, jiffies == 0x0100: result is true, as expected.
timeout == 0x8100, jiffies == 0x7F00: result is true, as expected.
timeout == 0x0100, jiffies == 0xFF00: oops, result is false, but we haven't really reached the timeout, it just wrapped the counter.
timeout == 0x0100, jiffies == 0x0300: result is false, as expected.
timeout == 0x7F00, jiffies == 0x8100: result is false, as expected.
timeout == 0xFF00, jiffies == 0x0100: oops, result is true, but we did pass the timeout.
time_before(jiffies, timeout)
This does a signed comparison on the difference of the values rather than the values themselves, and again is expected to return true if the timeout has not yet been reached. Provided that the assumption above is upheld, the same examples:
timeout == 0x0300, jiffies == 0x0100: result is true, as expected.
timeout == 0x8100, jiffies == 0x7F00: result is true, as expected.
timeout == 0x0100, jiffies == 0xFF00: result is true, as expected.
timeout == 0x0100, jiffies == 0x0300: result is false, as expected.
timeout == 0x7F00, jiffies == 0x8100: result is false, as expected.
timeout == 0xFF00, jiffies == 0x0100: result is false, as expected.
If the offset you used when calculating timeout is too large or you allow too much time to pass after calculating timeout, then the result can still be wrong. eg. if you calculate timeout once but then just keep testing it repeatedly, then time_before will initially be true, then change to false after the offset time has passed -- and then change back to true again after 0x8000 time has passed (however long that is; it depends on the tick rate). This is why when you reach the timeout, you're supposed to remember this and stop checking the time (or recalculate a new timeout).
In the real kernel, jiffies is longer than 16 bits so it will take longer for it to wrap, but it's still possible if the machine is run for long enough. (And typically it's set to wrap shortly after boot, to catch these bugs more quickly.)

I couldn't easily understand the above answers, so hoping to help with my own:
#define time_after(a,b) (long) ( (b) - (a) )
Here brackets around 'b' and 'a' make them signed.
Example overflow:
For convenience, imagine 8-bit integers, jiffy1 is changing and timeout is fixed and greater than jiffy1
like : jiffy1 = 252, timeout = 254 and jiffy2 becomes 0 or 1 after overflow
When we use unsigned:
jiffy1 < timeout and
jiffy2 < timeout (mistakenly due to overflow which we need to fix via MACRO)
When we use signed:
jiffy1 < timeout (more-negative < less-negative)
and
jiffy2 > timeout (positive > negative)
(because it will consider MSB as the sign bit, hence timeout will appear negative while our jiffy2 has become positive due to the overflow)
Do correct me if there is something wrong

Related

What is the else part in this code mean?

I was browsing some embedded programming link
http://www.micromouseonline.com/2016/02/02/systick-configuration-made-easy-on-the-stm32/
[Note that the author of the code at the above link has since updated the code, and the delay_ms() implementation in the article no longer uses the solution shown below.]
and ended up with this following code. This is for ARM architecture but basically this is a function which will cause a delay of certain milliseconds passed as a parameter. So I could understand the if condition but why is the else condition necessary here? can someone please explain it to me?
void delay_ms (uint32_t t)
{
uint32_t start, end;
start = millis();//This millis function will return the system clock in
//milliseconds
end = start + t;
if (start < end) {
while ((millis() >= start) && (millis() < end))
{ // do nothing }
}
else{
while ((millis() >= start) || (millis() < end))
{
// do nothing
};
}
}
If start + t caused an overflow, end will be less than start, so the if part deals with that, and the else with the "normal" case.
To be honest, it would take some thinking about to determine whether it is actually correct, but it is hardly worth it since it is a somewhat over-complicated means of solving a simple problem. All that is needed is the following:
void delay_ms( uint32_t t )
{
uint32_t start = millis() ;
while( (uint32_t)millis() - start < t )
{
// do nothing
}
}
To understand how this works imagine start is 0xFFFFFFFF, and t is 0x00000002, after two milliseconds, millis() will be 0x00000001, and millis() - start will be 2.
The loop will terminate when millis() - start == 3. Arguably you might prefer millis() - start <= t, but then the delay will be between t-1 to t milliseconds rather than at least t milliseconds (t to t+1). Your choice, but the point is that you should compare calculate and compare time periods rather then trying to compare the absolute timestamp values - much simpler.
Note that the second while loop has || instead of &&. This is to handle overflow. What happens if start + t is a bigger number than end can hold? The answer is that you will get an overflow. When you add 1 to an unsigned integer that holds its maximum value, it overflows to 0.
Here is a short snippet to show the effects of overflow:
uint8_t c = 255;
uint8_t d = c+1;
printf("%d %d", c, d);
This will print 255 0
This overflow is not even an unlikely scenario in this case. The maximum value an uint32_t can hold is approx 4*10⁹. That is the amount of milliseconds that passes in 46 days.
Here is a code snippet to test it yourself:
#include <stdio.h>
#include <stdint.h>
int main()
{
uint32_t s = -2; // Initialize s to it's maximum number
// minus one via overflow
uint32_t e, t;
scanf("%d", &t);
e = s+t;
if(s<e)
printf("foo\n");
else
printf("bar\n");
}
And when I run it with different inputs:
$ ./a.out
0
bar
$ ./a.out
1
foo
However, the code is awful. See Cliffords answer for an explanation why.
This code is trying to deal with the rollover. Take an 8 bit counter/timer counts up lets say from 0x00 to 0xFF then rolls over to 0x00 again. If I want to use this timer to wait 16 timer ticks (0x10) (using polling) and when I start that delay the timer is at 0x1B, then I want to wait for 0x1B+0x10 = 0x2B.
Start = 0x1B, end = 0x2B, for the values 0x1B, 0x1C 0x1D...0x29, 0x2A we want to delay, start is less than end so there is no counter rollover in this code so long as t is not larger than the timer which it cant be we assume based on this code, so:
while((now>=start)&&(now<end)) continue;
Where now is sampled in that loop (while((millis()>=start).
As you pointed out, lets say
start = 0xF5, all the variables are the same size, 32 bits, mine they
are all 8 for this demonstration so 0xF5 + 0x10 = 0x05, end = 0x05 so we want to delay while now is 0xF5, 0xF6, 0xF7, 0xF8...0xFF 0x00 0x01 0x02 0x03 0x04. So we we have to split cases we have to cover, now >= start to cover the 0xF5 to 0xFF and now
while((now>=start)||(now
But as Clifford has pointed out, fundamental programming knowledge, some of the magic of twos complement the now being the first number (0xFD to 0x05):
(0xFD - 0xF5) & 0xFF = 0x08
(0xFE - 0xF5) & 0xFF = 0x09
(0xFF - 0xF5) & 0xFF = 0x0A
(0x00 - 0xF5) & 0xFF = 0x0B
(0x01 - 0xF5) & 0xFF = 0x0C
(0x02 - 0xF5) & 0xFF = 0x0D
(0x03 - 0xF5) & 0xFF = 0x0E
(0x04 - 0xF5) & 0xFF = 0x0F
(0x05 - 0xF5) & 0xFF = 0x10
Works perfect, we just need to subtract now - start for an up counter and mask the math to the size of the counter and/or variables whichever is smaller
while(((now-start)&0xFF)
For a downcounter use start - now.
The author of that code was trying to deal with the rollover without understanding twos complement. Back in the day before I learned this my code was even worse I was probably computing the math for the number of counts before the rollover then the number of counts after, whatever didnt last long I convinced myself that the rollover math works so long as you mask it right.
NOW SAYING THAT
If your timer does NOT rollover between all ones to all zeros or all zeros to all ones, which many microcontroller timers can be programmed to do and you are not using the timers features completely then the above wont work. If you have an 8 bit timer and it counts from 0x00 to 0x53 then rolls over to 0x00, because that is how you set it for some reason, or you are re-using a timer that you have set for a periodic interrupt as a polled timer, then you have to do in a better way, what the author of that code did:
while(now<0x53) continue;
while(now>end) continue;
sampling now each loop.
But the math for end does not roll over naturally you have to compute end as
end = start + t;
if(end>0x53) end = end - 0x54;
In that case though one would have to wonder why you are using a timer like that for polled timeouts, use a timer that counts all the bits and rolls over for polled timeouts use a timer that counts to N or counts to zero from N for regular periodic interrupts or can poll those as well, but in that case you are not doing generic delays necessarily....well...you could...set the timer to one millisecond, then count the rollover flags until you get to t. Easier than the now - start math. and can count as high as you want.
Millis() puts an abstraction layer between you and the timer though and we assume that millis rolls over from all ones to all zeros.
if you have a timer that counts from 0x00000000 to 0x55555555 for example and rolls over you also cannot clip it to try to get this math to work
while(((start-now)&0xFFFF)<t) continue;
that wont work because there is a point where 0xXXXX5555 rolls to 0xXXXX0000 giving you a short count that one time.
This shortcut of while(((start-now)&mask)
Otherwise you have to do something like the code you found with some modifications.
I also recommend as a habit not to sample the timer multiple times. I have seen this bug all to often:
while((timer()-start)<timeout)
{
if(read_register(n)&0x10) break;
}
if((timer()-start)>=timeout)
{
printf("Timed out\n");
return 1;
}
return 0;
Perhaps because the same coworker would implement it over and over again...
You want to sample the timer once for both use cases, if you re-sample it later
it may result in a different time. The condition may have passed within the timeout but then re-sampling the timer now times out.
instead something like
while(1)
{
delta=timer()-start;
if(delta>t) break;
if(register_read(n)&0x10) break;
}
if(delta>t)
{
printf(...
return 1;
}
return 0;
For the same reason you cant necessarily go back and read the register again to see if it was the reason why the loop was broken. Depends on that register.
And yes some folks may hate the coding style here, and consider that a bug too, point was minimize the number of times you sample the timer if you are re-using that timestamp more than once, in the case of the code you posted as written it is okay as C is supposed to evaluate left to right
millis() >= start
then
millis() < end
had it been written
while ((millis() < end) && (millis() >= start))
while ((millis() < end) || (millis() >= start))
for start
for the start>end case if the first read is less than end and it increments so it
is equal to or larger than end for the second read to compare to start, then same
deal you have to loop again to catch millis() not less than end.
So it is an extra sample but works fine. The code could have been simplified to
if(start<end)
{
while(millis()<end) continue;
}
else
{
while(millis()>=start) continue;
while(millis()<end) continue;
}
sampling once per loop.
And also note this kind of polled timer only works if you are for the most part outrunning the timer with your polling loop, you dont have interrupts that take a long time to bump you another rollover of the timer. If you are not sampling that fast, then you might want to put a limit on the size of t, make it so it cant be more than half the number of bits in the timer. How much you should limit it depends on how fast you can sample this thing.
Polled time loops should only be used for at that time or greater, if you want to time a specific amount of time the delay may run long unless you are careful, if you have interrupts or other things you may run long, maybe very long. So if you want to time say at least 10ms but 100ms now and again is okay, like bit banging i2c or spi, thats fine. But if you are trying to bit bang a uart a polled timer might not be the best way to go, depends on your system design.

Preventing torn reads with an HCS12 microcontroller

Summary
I'm trying to write an embedded application for an MC9S12VR microcontroller. This is a 16-bit microcontroller but some of the values I deal with are 32 bits wide and while debugging I've captured some anomalous values that seem to be due to torn reads.
I'm writing the firmware for this micro in C89 and running it through the Freescale HC12 compiler, and I'm wondering if anyone has any suggestions on how to prevent them on this particular microcontroller assuming that this is the case.
Details
Part of my application involves driving a motor and estimating its position and speed based on pulses generated by an encoder (a pulse is generated on every full rotation of the motor).
For this to work, I need to configure one of the MCU timers so that I can track the time elapsed between pulses. However, the timer has a clock rate of 3 MHz (after prescaling) and the timer counter register is only 16-bit, so the counter overflows every ~22ms. To compensate, I set up an interrupt handler that fires on a timer counter overflow, and this increments an "overflow" variable by 1:
// TEMP
static volatile unsigned long _timerOverflowsNoReset;
// ...
#ifndef __INTELLISENSE__
__interrupt VectorNumber_Vtimovf
#endif
void timovf_isr(void)
{
// Clear the interrupt.
TFLG2_TOF = 1;
// TEMP
_timerOverflowsNoReset++;
// ...
}
I can then work out the current time from this:
// TEMP
unsigned long MOTOR_GetCurrentTime(void)
{
const unsigned long ticksPerCycle = 0xFFFF;
const unsigned long ticksPerMicrosecond = 3; // 24 MHZ / 8 (prescaler)
const unsigned long ticks = _timerOverflowsNoReset * ticksPerCycle + TCNT;
const unsigned long microseconds = ticks / ticksPerMicrosecond;
return microseconds;
}
In main.c, I've temporarily written some debugging code that drives the motor in one direction and then takes "snapshots" of various data at regular intervals:
// Test
for (iter = 0; iter < 10; iter++)
{
nextWait += SECONDS(secondsPerIteration);
while ((_test2Snapshots[iter].elapsed = MOTOR_GetCurrentTime() - startTime) < nextWait);
_test2Snapshots[iter].position = MOTOR_GetCount();
_test2Snapshots[iter].phase = MOTOR_GetPhase();
_test2Snapshots[iter].time = MOTOR_GetCurrentTime() - startTime;
// ...
In this test I'm reading MOTOR_GetCurrentTime() in two places very close together in code and assign them to properties of a globally available struct.
In almost every case, I find that the first value read is a few microseconds beyond the point the while loop should terminate, and the second read is a few microseconds after that - this is expected. However, occasionally I find the first read is significantly higher than the point the while loop should terminate at, and then the second read is less than the first value (as well as the termination value).
The screenshot below gives an example of this. It took about 20 repeats of the test before I was able to reproduce it. In the code, <snapshot>.elapsed is written to before <snapshot>.time so I expect it to have a slightly smaller value:
For snapshot[8], my application first reads 20010014 (over 10ms beyond where it should have terminated the busy-loop) and then reads 19988209. As I mentioned above, an overflow occurs every 22ms - specifically, a difference in _timerOverflowsNoReset of one unit will produce a difference of 65535 / 3 in the calculated microsecond value. If we account for this:
A difference of 40 isn't that far off the discrepancy I see between my other pairs of reads (~23/24), so my guess is that there's some kind of tear going on involving an off-by-one read of _timerOverflowsNoReset. As in while busy-looping, it will perform one call to MOTOR_GetCurrentTime() that erroneously sees _timerOverflowsNoReset as one greater than it actually is, causing the loop to end early, and then on the next read after that it sees the correct value again.
I have other problems with my application that I'm having trouble pinning down, and I'm hoping that if I resolve this, it might resolve these other problems as well if they share a similar cause.
Edit: Among other changes, I've changed _timerOverflowsNoReset and some other globals from 32-bit unsigned to 16-bit unsigned in the implementation I now have.
You can read this value TWICE:
unsigned long GetTmrOverflowNo()
{
unsigned long ovfl1, ovfl2;
do {
ovfl1 = _timerOverflowsNoReset;
ovfl2 = _timerOverflowsNoReset;
} while (ovfl1 != ovfl2);
return ovfl1;
}
unsigned long MOTOR_GetCurrentTime(void)
{
const unsigned long ticksPerCycle = 0xFFFF;
const unsigned long ticksPerMicrosecond = 3; // 24 MHZ / 8 (prescaler)
const unsigned long ticks = GetTmrOverflowNo() * ticksPerCycle + TCNT;
const unsigned long microseconds = ticks / ticksPerMicrosecond;
return microseconds;
}
If _timerOverflowsNoReset increments much slower then execution of GetTmrOverflowNo(), in worst case inner loop runs only two times. In most cases ovfl1 and ovfl2 will be equal after first run of while() loop.
Calculate the tick count, then check if while doing that the overflow changed, and if so repeat;
#define TCNT_BITS 16 ; // TCNT register width
uint32_t MOTOR_GetCurrentTicks(void)
{
uint32_t ticks = 0 ;
uint32_t overflow_count = 0;
do
{
overflow_count = _timerOverflowsNoReset ;
ticks = (overflow_count << TCNT_BITS) | TCNT;
}
while( overflow_count != _timerOverflowsNoReset ) ;
return ticks ;
}
the while loop will iterate either once or twice no more.
Based on the answers #AlexeyEsaulenko and #jeb provided, I gained understanding into the cause of this problem and how I could tackle it. As both their answers were helpful and the solution I currently have is sort of a mixture of the two, I can't decide which of the two answers to accept, so instead I'll upvote both answers and keep this question open.
This is how I now implement MOTOR_GetCurrentTime:
unsigned long MOTOR_GetCurrentTime(void)
{
const unsigned long ticksPerMicrosecond = 3; // 24 MHZ / 8 (prescaler)
unsigned int countA;
unsigned int countB;
unsigned int timerOverflowsA;
unsigned int timerOverflowsB;
unsigned long ticks;
unsigned long microseconds;
// Loops until TCNT and the timer overflow count can be reliably determined.
do
{
timerOverflowsA = _timerOverflowsNoReset;
countA = TCNT;
timerOverflowsB = _timerOverflowsNoReset;
countB = TCNT;
} while (timerOverflowsA != timerOverflowsB || countA >= countB);
ticks = ((unsigned long)timerOverflowsA << 16) + countA;
microseconds = ticks / ticksPerMicrosecond;
return microseconds;
}
This function might not be as efficient as other proposed answers, but it gives me confidence that it will avoid some of the pitfalls that have been brought to light. It works by repeatedly reading both the timer overflow count and TCNT register twice, and only exiting the loop when the following two conditions are satisfied:
the timer overflow count hasn't changed while reading TCNT for the first time in the loop
the second count is greater than the first count
This basically means that if MOTOR_GetCurrentTime is called around the time that a timer overflow occurs, we wait until we've safely moved on to the next cycle, indicated by the second TCNT read being greater than the first (e.g. 0x0001 > 0x0000).
This does mean that the function blocks until TCNT increments at least once, but since that occurs every 333 nanoseconds I don't see it being problematic.
I've tried running my test 20 times in a row and haven't noticed any tearing, so I believe this works. I'll continue to test and update this answer if I'm wrong and the issue persists.
Edit: As Vroomfondel points out in the comments below, the check I do involving countA and countB also incidentally works for me and can potentially cause the loop to repeat indefinitely if _timerOverflowsNoReset is read fast enough. I'll update this answer when I've come up with something to address this.
The atomic reads are not the main problem here.
It's the problem that the overflow-ISR and TCNT are highly related.
And you get problems when you read first TCNT and then the overflow counter.
Three sample situations:
TCNT=0x0000, Overflow=0 --- okay
TCNT=0xFFFF, Overflow=1 --- fails
TCNT=0x0001, Overflow=1 --- okay again
You got the same problems, when you change the order to: First read overflow, then TCNT.
You could solve it with reading twice the totalOverflow counter.
disable_ints();
uint16_t overflowsA=totalOverflows;
uint16_t cnt = TCNT;
uint16_t overflowsB=totalOverflows;
enable_ints();
uint32_t totalCnt = cnt;
if ( overflowsA != overflowsB )
{
if (cnt < 0x4000)
totalCnt += 0x10000;
}
totalCnt += (uint32_t)overflowsA << 16;
If the totalOverflowCounter changed while reading the TCNT, then it's necessary to check if the value in tcnt is already greater 0 (but below ex. 0x4000) or if tcnt is just before the overflow.
One technique that can be helpful is to maintain two or three values that, collectively, hold overlapping portions of a larger value.
If one knows that a value will be monotonically increasing, and one will never go more than 65,280 counts between calls to "update timer" function, one could use something like:
// Note: Assuming a platform where 16-bit loads and stores are atomic
uint16_t volatile timerHi, timerMed, timerLow;
void updateTimer(void) // Must be only thing that writes timers!
{
timerLow = HARDWARE_TIMER;
timerMed += (uint8_t)((timerLow >> 8) - timerMed);
timerHi += (uint8_t)((timerMed >> 8) - timerHi);
}
uint32_t readTimer(void)
{
uint16_t tempTimerHi = timerHi;
uint16_t tempTimerMed = timerMed;
uint16_t tempTimerLow = timerLow;
tempTimerMed += (uint8_t)((tempTimerLow >> 8) - tempTimerMed);
tempTimerHi += (uint8_t)((tempTimerMed >> 8) - tempTimerHi);
return ((uint32_t)tempTimerHi) << 16) | tempTimerLow;
}
Note that readTimer reads timerHi before it reads timerLow. It's possible that updateTimer might update timerLow or timerMed between the time readTimer reads
timerHi and the time it reads those other values, but if that occurs, it will
notice that the lower part of timerHi needs to be incremented to match the upper
part of the value that got updated later.
This approach can be cascaded to arbitrary length, and need not use a full 8 bits
of overlap. Using 8 bits of overlap, however, makes it possible to form a 32-bit
value by using the upper and lower values while simply ignoring the middle one.
If less overlap were used, all three values would need to take part in the
final computation.
The problem is that the writes to _timerOverflowsNoReset isn't atomic and you don't protect them. This is a bug. Writing atomic from the ISR isn't very important, as the HCS12 blocks the background program during interrupt. But reading atomic in the background program is absolutely necessary.
Also, have in mind that Codewarrior/HCS12 generates somewhat ineffective code for 32 bit arithmetic.
Here is how you can fix it:
Drop unsigned long for the shared variable. In fact you don't need a counter at all, given that your background program can service the variable within 22ms real-time - should be very easy requirement. Keep your 32 bit counter local and away from the ISR.
Ensure that reads of the shared variable are atomic. Disassemble! It must be a single MOV instruction or similar; otherwise you must implement semaphores.
Don't read any volatile variable inside complex expressions. Not only the shared variable but also the TCNT. Your program as it stands has a tight coupling between the slow 32 bit arithmetic algorithm's speed and the timer, which is very bad. You won't be able to reliably read TCNT with any accuracy, and to make things worse you call this function from other complex code.
Your code should be changed to something like this:
static volatile bool overflow;
void timovf_isr(void)
{
// Clear the interrupt.
TFLG2_TOF = 1;
// TEMP
overflow = true;
// ...
}
unsigned long MOTOR_GetCurrentTime(void)
{
bool of = overflow; // read this on a line of its own, ensure this is atomic!
uint16_t tcnt = TCNT; // read this on a line of its own
overflow = false; // ensure this is atomic too
if(of)
{
_timerOverflowsNoReset++;
}
/* calculations here */
return microseconds;
}
If you don't end up with atomic reads, you will have to implement semaphores, block the timer interrupt or write the reading code in inline assembler (my recommendation).
Overall I would say that your design relying on TOF is somewhat questionable. I think it would be better to set up a dedicated timer channel and let it count up a known time unit (10ms?). Any reason why you can't use one of the 8 timer channels for this?
It all boils down to the question of how often you do read the timer and how long the maximum interrupt sequence will be in your system (i.e. the maximum time the timer code can be stopped without making "substantial" progress).
Iff you test for time stamps more often than the cycle time of your hardware timer AND those tests have the guarantee that the end of one test is no further apart from the start of its predecessor than one interval (in your case 22ms), all is well. In the case your code is held up for so long that these preconditions don't hold, the following solution will not work - the question then however is whether the time information coming from such a system has any value at all.
The good thing is that you don't need an interrupt at all - any try to compensate for the inability of the system to satisfy two equally hard RT problems - updating your overflow timer and delivering the hardware time is either futile or ugly plus not meeting the basic system properties.
unsigned long MOTOR_GetCurrentTime(void)
{
static uint16_t last;
static uint16_t hi;
volatile uint16_t now = TCNT;
if (now < last)
{
hi++;
}
last = now;
return now + (hi * 65536UL);
}
BTW: I return ticks, not microseconds. Don't mix concerns.
PS: the caveat is that such a function is not reentrant and in a sense a true singleton.

Check if time_t is zero

I have written a timer eventloop with epoll and the timerfd linux API. The magpage of timerfd_gettime states the following:
The it_value field returns the amount of time until the timer will
next expire. If both fields of this structure are zero, then the
timer is currently disarmed.
So to check if a timer is currently armed or disarmed I had written the following code:
bool timer_is_running(struct timer *timer)
{
struct itimerspec timerspec;
if(timerfd_gettime(timer->_timer_fd, &timerspec) == -1) {
printf("[TIMER] Could not get timer '%s' running status\n", timer->name);
return false;
}
printf("[TIMER] Checking running state of timer '%s' it_value.tv_sec = %"PRIu64", it_value.tv_nsec = %"PRIu64"\n", timer->name, (uint64_t) timerspec.it_value.tv_sec, (uint64_t) timerspec.it_value.tv_nsec == 0);
return timerspec.it_value.tv_sec != 0 && timerspec.it_value.tv_nsec != 0;
}
This wasn't working and all timers were reported as disarmed. when I looked at the output I saw the following on a currently disarmed timer:
[TIMER] Checking running state of timer 'test' it_value.tv_sec = 0, it_value.tv_nsec = 4302591840
After further investigation it seems only the tv_sec field is set to 0 on disarmed timers.
This is program runs on kernel 3.18.23 on MIPS architecture (OpenWRT).
Before I flag this as a bug in the kernel implementation I would like to know if it's correct to check if a time_t is 0 by doing time_t == 0. Can anyone confirm this?
Kind regards,
Daan
This is not a bug in the kernel implementation. It is your code that is flawed.
The it_value field returns the amount of time until the timer will
next expire. If both fields of this structure are zero, then the
timer is currently disarmed.
The converse of this is that (assuming the call timerfd_gettime() succeeds) the timer is armed if ONE or BOTH of the fields of the structure are non-zero.
The last return statement of your function is
return timerspec.it_value.tv_sec != 0 && timerspec.it_value.tv_nsec != 0;
which returns true only if BOTH the fields are non-zero. Instead, you need to use
return timerspec.it_value.tv_sec != 0 || timerspec.it_value.tv_nsec != 0;
The time_t type alias is an arithmetic or real type. Both arithmetic and real types can by implicitly compared with the integer value zero.
Furthermore, on POSIX systems (like Linux) time_t is defined as an integer (see e.g. this <sys/types.h> reference).
While the C standard doesn't explicitly specify the type of time_t just about all implementations use integers for time_t for compatibility reasons. I don't know any implementation where it's not an integer.
So the answer to your question is that the comparison is correct.
It should be noted that it's only the tv_sec member that is of type time_t. The tv_nsec member is a long.

Why udelay and ndelay is not accurate in linux kernel?

I make a function like this
trace_printk("111111");
udelay(4000);
trace_printk("222222");
and the log shows it's 4.01 ms , it'OK
But when i call like this
trace_printk("111111");
ndelay(10000);
ndelay(10000);
ndelay(10000);
ndelay(10000);
....
....//totally 400 ndelay calls
trace_printk("222222");
the log will shows 4.7 ms. It's not acceptable.
Why the error of ndelay is so huge like this?
Look deep in the kernel code i found the implemention of this two functions
void __udelay(unsigned long usecs)
{
__const_udelay(usecs * 0x10C7UL); /* 2**32 / 1000000 (rounded up) */
}
void __ndelay(unsigned long nsecs)
{
__const_udelay(nsecs * 0x5UL); /* 2**32 / 1000000000 (rounded up) */
}
I thought udelay will be 1000 times than ndelay, but it's not, why?
As you've already noticed, the nanosecond delay implementation is quite a coarse approximation compared to the millisecond delay, because of the 0x5 constant factor used. 0x10c7 / 0x5 is approximately 859. Using 0x4 would be closer to 1000 (approximately 1073).
However, using 0x4 would cause the ndelay to be less than the number of nanoseconds requested. In general, delay functions aim to provide a delay at least as long as requested by the user (see here: http://practicepeople.blogspot.jp/2013/08/kernel-programming-busy-waiting-delay.html).
Every time you call it, a rounding error is added. Note the comment 2**32 / 1000000000. That value is really ~4.29, but it was rounded up to 5. That's a pretty hefty error.
By contrast the udelay error is small: (~4294.97 versus 4295 [0x10c7]).
You can use ktime_get_ns() to get high precision time since boot. So you can use it not only as high precision delay but also as high precision timer. There is example:
u64 t;
t = ktime_get_ns(); // Get current nanoseconds since boot
for (i = 0; i < 24; i++) // Send 24 1200ns-1300ns pulses via GPIO
{
gpio_set_value(pin, 1); // Drive GPIO or do something else
t += 1200; // Now we have absolute time of the next step
while (ktime_get_ns() < t); // Wait for it
gpio_set_value(pin, 0); // Do something, again
t += 1300; // Now we have time of the next step, again
while (ktime_get_ns() < t); // Wait for it, again
}

proper use of time_is_before_jiffies()

My Linux device driver has some obstinate logic which twiddles with some hardware and then waits for a signal to appear. The seemingly proper way is:
ulong timeout, waitcnt = 0;
...
/* 2. Establish programming mode */
gpio_bit_write (MPP_CFG_PROGRAM, 0); /* assert */
udelay (3); /* one microsecond should be long enough */
gpio_bit_write (MPP_CFG_PROGRAM, 1); /* de-assert */
/* 3. Wait for the FPGA to initialize. */
/* 100 ms timeout should be nearly 100 times too long */
timeout = jiffies + msecs_to_jiffies(100);
while (gpio_bit_read (MPP_CFG_INIT) == 0 &&
time_is_before_jiffies (timeout))
++waitcnt; /* do nothing */
if (!time_is_before_jiffies (timeout)) /* timed out? */
{
/* timeout error */
}
This always exercises the "timeout error" path and doesn't increment waitcnt at all. Perhaps I don't understand the meaning of time_is_before_jiffies(), or it is broken. When I replace it with the much more understandable direct comparison of jiffies:
while (gpio_bit_read (MPP_CFG_INIT) == 0 &&
jiffies <= timeout)
++waitcnt; /* do nothing */
It works just fine: it loops for awhile (1600 µS), sees the INIT bit come on, and then proceeds without triggering a timeout error.
The comment for time_is_before_jiffies() is:
/* time_is_before_jiffies(a) return true if a is before jiffies */
#define time_is_before_jiffies(a) time_after(jiffies, a)
As the sense of the comparison seemed nonsensically backward, I replaced both with time_is_after_jiffies(), but that doesn't work either.
What am I doing wrong? Maybe I should replace use of this confusing macro with the straightforward jiffies <= timeout logic, though that seems less portable.
The jiffies <= timeout comparison does not work when the jiffies are wrapping around, so you must use it.
The condition you want to use can be described as "has not yet timed out".
This means that the current time (jiffies) has not yet reached the timeout time (timeout), i.e., jiffies is before the variable you are comparing it to, which means that your variable is after jiffies.
(All the time_is_ functions have jiffies on the right side of the comparison.)
So you have to use timer_is_after_jiffies() in the while loop.
(And the <= implies that you actually want to use time_is_after_eq_jiffies().)
The timeout check should be better done by reading the GPIO bit, because it would be a shame if your code times out although it got the signal right at the end.
Furthermore, busy-looping for a hundred milliseconds is extremly evil; you should release the CPU if you don't need it:
unsigned long timeout = jiffies + msecs_to_jiffies(100);
bool ok = false;
for (;;) {
ok = gpio_bit_read(MPP_CFG_INIT) != 0;
if (ok || time_is_before_eq_jiffies(timeout))
break;
/* you should do msleep(...) or cond_resched() here, if possible */
}
if (!ok) /* timed out? */
...
(This loop uses time_is_before_eq_jiffies() because the condition is reversed.)

Resources