Skip to content

os/kernel/semaphore: fix timeout+post race in sem_timedwait - #7487

Open
rish-sg wants to merge 1 commit into
Samsung:masterfrom
rish-sg:sem_timedwait_fix
Open

os/kernel/semaphore: fix timeout+post race in sem_timedwait#7487
rish-sg wants to merge 1 commit into
Samsung:masterfrom
rish-sg:sem_timedwait_fix

Conversation

@rish-sg

@rish-sg rish-sg commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

Fix a race condition between timeout and sem_post that causes spurious wakeups on subsequent semaphore waits.

Root Cause:
When timeout fires, sem_waitirq() increments semcount to restore the count that was decremented when the thread blocked. If a concurrent sem_post() also increments semcount before the thread gets CPU, there will be a leftover semcount (double increment).

This leftover causes the next sem_wait() on the same semaphore to return immediately without actually waiting (spurious wakeup).

Fix:
In the error path after sem_wait() returns, check if:

  • errno is ETIMEDOUT (timeout fired)
  • semcount > 0 (concurrent post happened)

If both conditions are true, consume the leftover semcount and return OK since the semaphore was successfully acquired.

This is POSIX-compliant per:
"Under no circumstance shall the function fail with a timeout if the semaphore can be locked immediately."

Fix a race condition between timeout and sem_post that causes
spurious wakeups on subsequent semaphore waits.

Root Cause:
When timeout fires, sem_waitirq() increments semcount to restore the
count that was decremented when the thread blocked. If a concurrent
sem_post() also increments semcount before the thread gets CPU,
there will be a leftover semcount (double increment).

This leftover causes the next sem_wait() on the same semaphore to
return immediately without actually waiting (spurious wakeup).

Fix:
In the error path after sem_wait() returns, check if:
- errno is ETIMEDOUT (timeout fired)
- semcount > 0 (concurrent post happened)

If both conditions are true, consume the leftover semcount and
return OK since the semaphore was successfully acquired.

This is POSIX-compliant per:
"Under no circumstance shall the function fail with a timeout if
the semaphore can be locked immediately."

Co-authored-by: Aashish Lakhwara <aashish.l@samsung.com>
Signed-off-by: Rishabh Singh <ris.singh@samsung.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant