Skip to content

Commit

Permalink
kernel/sched: correct k_sleep() return value calculation
Browse files Browse the repository at this point in the history
Fix the issue: zephyrproject-rtos#79863

The expected_wakeup_ticks and sys_clock_tick_get_32() are uint32_t values,
and may wrap around individually.
If the expected_wakeup_ticks has a wraparound and sys_clock_tick_get_32()
doesn't, so expected_wakeup_ticks < sys_clock_tick_get_32(), the API return
value will be corrupted.

The API return value, that is the remaining time, should be calculated in
32bit-unsigned-integer manner, and any wraparound will be treated properly.

Signed-off-by: Akaiwa Wataru <akaiwa@sonas.co.jp>
  • Loading branch information
akasona authored and kartben committed Dec 3, 2024
1 parent 4fb6ce3 commit feefb7d
Showing 1 changed file with 5 additions and 1 deletion.
6 changes: 5 additions & 1 deletion kernel/sched.c
Original file line number Diff line number Diff line change
Expand Up @@ -1117,7 +1117,11 @@ static int32_t z_tick_sleep(k_ticks_t ticks)

__ASSERT(!z_is_thread_state_set(arch_current_thread(), _THREAD_SUSPENDED), "");

ticks = (k_ticks_t)expected_wakeup_ticks - sys_clock_tick_get_32();
/* We require a 32 bit unsigned subtraction to care a wraparound */
uint32_t left_ticks = expected_wakeup_ticks - sys_clock_tick_get_32();

/* To handle a negative value correctly, once type-cast it to signed 32 bit */
ticks = (k_ticks_t)(int32_t)left_ticks;
if (ticks > 0) {
return ticks;
}
Expand Down

0 comments on commit feefb7d

Please sign in to comment.