Issue created by Christian Mauderer: 
https://gitlab.rtems.org/rtems/rtos/rtems/-/work_items/5825

Assignee: Christian Mauderer

# Summary for Backport to 6

Like mentioned in the original issue, this bug can happen on 6 too. It took me 
a bit of time to understand the original description, therefore here is a short 
summary of the sequence of events that can trigger this bug on a SMP system:

1. Task T waits for a semaphore with a timeout.
2. CPU 0 sees that the timeout expired and starts to handle it.
3. CPU 1 releases the semaphore before CPU 0 finishes. T wakes up with success.
4. Task T starts a new wait for something else.
5. CPU 0 finishes the timeout of the old wait. It cannot tell that this wait is 
over, so it ends the new wait with a timeout.

The problem has been solved with 
https://gitlab.rtems.org/rtems/rtos/rtems/-/merge_requests/1481 on `main`. It 
should be backported to 6. **Note that this means an API change.**


# Original #5733 description

## Summary

This is a severe bug which should be fixed in all production systems.

A thread timeout can cancel a wait which the thread started after that
timeout expired. The score has no way to name the wait which a timeout
belongs to. The thread then gets a wrong `STATUS_TIMEOUT` for an
unrelated wait, or the watchdog tree of a processor becomes corrupt and a
later clock tick stops every processor.

## The mechanism

`_Watchdog_Do_tickle()` extracts the node from the tree, sets it inactive
and releases the lock of the header. It calls the service routine after
that. It never acquires the `Timer.Lock` of the thread, which is the lock
the arm and the removal of a thread timer use.

For a thread timer the routine is `_Thread_Timeout()`. That routine calls
`_Thread_Continue()` with `STATUS_TIMEOUT`.

Between the release of the header lock and the call, another party can
satisfy the wait. The `_Thread_Timer_remove()` of that party finds an
inactive node and reports success, although the routine is still in
flight. The score has no cancel and drain for a thread timer. The thread
leaves its wait, continues, and enters a new wait.

`_Thread_Continue()` then acquires the wait lock of the new wait. It
tests `wait_flags != THREAD_WAIT_STATE_READY` and derives the wait class
from the value it reads. Both tests pass for any wait, so it cancels the
new one.

The thread wait flags cannot separate one wait of a thread from the next.
The state runs `READY`, `INTEND_TO_BLOCK`, `BLOCKED`, `READY` and starts
again. It is a generation counter of three values which resets at every
wait.

## What the cancel leaves behind

| The new wait of the thread | Result                                 |
| -------------------------- | -------------------------------------- |
| carries a timeout          | the watchdog it armed, still scheduled |
| carries no timeout         | a report of a timeout which never ran  |

A leaked watchdog stays in the tree of a processor. The next timed wait
of that thread inserts the same node a second time. The red-black tree of
that processor is then corrupt. A later clock tick either traps in
`_RBTree_Extract()` or turns in an endless loop with the lock of the tree
held. The second case stops every processor.

## Exposure

Every wait which `_Thread_Continue()` ends is exposed. That covers each
call which blocks on a thread queue, `rtems_event_receive()`,
`rtems_task_wake_after()`, `rtems_task_wake_when()` and the POSIX
counterparts of these calls.

On an SMP configuration the party which satisfies the wait is an
interrupt handler or a thread on another processor. The window is open on
every timed wait.

On a uniprocessor configuration the window opens through `_TOD_Set()`.
That routine tickles the realtime header of each processor in task
context. `rtems_clock_set()` holds a mutex and an ISR lock, and
`_Timecounter_Set_clock()` releases that ISR lock before the loop.
Interrupts and thread dispatch are both enabled while the loop calls
`_Thread_Timeout()`.

A uniprocessor configuration which never moves the time of day past an
armed timeout does not reach this defect. A system which calls neither
`rtems_clock_set()` nor `clock_settime()` is therefore not exposed. The
same holds for a system which calls them only before the first timed wait
exists. An SMP configuration has no such condition and no workaround at
the application level.

## Affected versions

| Change                                        | Date       | Releases         
     |
| --------------------------------------------- | ---------- | 
--------------------- |
| `score: Add thread wait flags`                 | 2015-03-04 | 4.11 and later  
      |
| `score: Replace watchdog handler implementation` | 2016-02-18 | 5.1 and later 
        |
| `score: Add _Thread_Continue()`                | 2017-10-19 | 5.1 and later   
      |

The mechanism above is present in 5.1, 5.2, 5.3, 6.1, 6.2 and the
development head. Release 4.11 carries the thread wait flags but a
different watchdog handler. Nobody checked 4.11 against this defect.

## How to construct the defect without a race

The `_TOD_Set()` path makes the window deterministic on a single
processor.

1. A high priority task blocks on a semaphore with an absolute realtime
   timeout.
2. A low priority task calls `rtems_clock_set()` with a time past that
   expiry.
3. `_TOD_Set()` extracts the watchdog, releases the header lock and calls
   `_Thread_Timeout()`.
4. An interrupt releases the semaphore inside that window.
5. The high priority task preempts, returns from the wait and enters a
   second wait.
6. The low priority task resumes and cancels the second wait.

Without the defect the second wait stays intact. With the defect it
reports a timeout, and it leaks its watchdog when it carries one.

## The repair

The thread wait flags word is an `unsigned int`. The repair compresses
the state into bit 0 and the class into bits 1 to 5. It drops
`THREAD_WAIT_STATE_INTEND_TO_BLOCK`, so the class alone names a started
wait. It renames `THREAD_WAIT_CLASS_OBJECT` to `THREAD_WAIT_CLASS_QUEUE`
and adds `THREAD_WAIT_CLASS_TIME` for `rtems_task_wake_after()` and
`rtems_task_wake_when()`.

Bits 6 to 31 then hold a generation which steps at the end of every wait,
so the word names one wait of the thread. The watchdog carries an opaque
token which the party who schedules it writes. The arm of a thread timer
writes the wait flags of that wait into the token.
`_Watchdog_Do_tickle()` reads the token under the header lock and passes
it to the service routine. This is the only transport which survives a
second arm of the same node. The arm of the next wait overwrites every
field of the node.

`_Thread_Timeout()` compares the token against the wait flags of the
thread under the wait lock. On a mismatch it returns and touches nothing.
A tickle phase runs with thread dispatch disabled, so only another
processor can start the new wait. The comparison is therefore built in an
SMP configuration only.

Merge request !1481 carries this repair.

## Impact on the API and the ABI

The repair changes no user API. An application changes no source. It
changes the internal API of the score and the layout of four structures,
so every object which includes an affected header needs a rebuild.

### The internal API

| Change | Header |
| ------ | ------ |
| `Watchdog_Service_routine_entry` takes the token as a second parameter | 
`rtems/score/watchdog.h` |
| `Watchdog_Control` gains `unsigned int token` | `rtems/score/watchdog.h` |
| `Rate_monotonic_Control` gains `unsigned int timer_generation` | 
`rtems/rtems/ratemondata.h` |
| `Thread_queue_Context` gains `unsigned int timeout_token` | 
`rtems/score/threadq.h` |
| the wait state moves to bit 0, the class to bits 1 to 5 and the generation to 
bits 6 to 31 | `rtems/score/threadimpl.h` |
| `THREAD_WAIT_CLASS_OBJECT` becomes `THREAD_WAIT_CLASS_QUEUE` | 
`rtems/score/threadimpl.h` |
| `THREAD_WAIT_STATE_INTEND_TO_BLOCK` is gone | `rtems/score/threadimpl.h` |

The last two rows are a source break. Code outside the tree which names
either macro fails to compile.

### The object sizes

The numbers are bytes, measured with gcc 15.2.0 against the branch of
!1481.

| Structure | sparc, uniprocessor | sparc, SMP | aarch64, uniprocessor |
| --------- | ------------------- | ---------- | --------------------- |
| `Watchdog_Control` | 32, unchanged | 32 to 40 | 48 to 56 |
| `Rate_monotonic_Control` | 176, unchanged | 184 to 192 | 232 to 240 |
| `Thread_queue_Context` | 44 to 48 | 184 to 188 | 72 to 80 |
| `Thread_Control` | 392, unchanged | 576 to 584 | 672 to 680 |

`Thread_Control` follows because it embeds the watchdog of the thread
timer. The token fills existing padding only in the uniprocessor layout
of a 32 bit target. Every other layout grows by eight bytes.

### Why an application and not the kernel alone

`<rtems/confdefs.h>` puts these structures into the application.
`rtems/confdefs/threads.h` wraps `Thread_Control` in
`Thread_Configured_control` and computes `offsetof()` values into
`_Thread_Control_add_ons[]`. `rtems/confdefs/objectsclassic.h` allocates
the period objects with `RATE_MONOTONIC_INFORMATION_DEFINE()`. An
application which keeps its old configuration object hands the kernel
wrong offsets and undersized objects.

No symbol changes, so the linker reports nothing.

## Impact on RTEMS libbsd

The assessment covers `rtems-libbsd` at commit 5effd14be.

Two functions are watchdog service routines and have to take the token
parameter. Without that change the build stops, because
`Watchdog_Service_routine_entry` accepts them no longer.

| Function | File | How it reaches the watchdog |
| -------- | ---- | --------------------------- |
| `sleepq_timeout()` | `freebsd/sys/kern/subr_sleepqueue.c:1349` | the arm 
assigns it at line 488 |
| `epoch_watchdog()` | `rtemsbsd/rtems/rtems-kernel-epoch.c:106` | 
`_Watchdog_Preinitialize()` and `_Watchdog_Initialize()` at lines 178 and 179 |

`rtemsbsd/include/machine/rtems-bsd-muteximpl.h` puts a
`Thread_queue_Context` on the stack in three places. That structure grows
in every configuration measured above. These objects therefore need a
rebuild although their source stays the same.

libbsd uses none of the thread wait flag macros. The rename of
`THREAD_WAIT_CLASS_OBJECT` and the loss of
`THREAD_WAIT_STATE_INTEND_TO_BLOCK` cost it nothing.

### libbsd carries this defect in its own sleep queue

The port is not the whole work. `subr_sleepqueue.c` runs a timed sleep of
its own on `Thread_Control::Timer.Watchdog`. It uses `sleepq_timeout()`
as the service routine and `td_sq_state` as the state. The end of a sleep
calls `_Thread_Timer_remove()` at line 793, which removes nothing while a
tickle phase already holds the node. The thread returns and its caller
can start the next sleep, which sets `td_sq_state` to `TD_SQ_TIRED` at
line 420. The stale `sleepq_timeout()` reads that state and sets
`TD_SQ_NIGHTMARE`, so the next check at line 729 reports a timeout which
never happened.

This is SMP only. Line 486 arms the watchdog in
`Watchdog.Header[PER_CPU_WATCHDOG_TICKS]`, and only the clock tick
interrupt tickles that collection. A uniprocessor system runs no thread
inside the window. The tree corruption of this issue does not follow
either, because `sleepq_timeout()` arms no watchdog of its own.

The token of merge request !1481 is the means to close it, and the port
has to use the token, not only compile against it.

The bug report and the impact assessment were created using Claude Code.

-- 
View it on GitLab: https://gitlab.rtems.org/rtems/rtos/rtems/-/work_items/5825
You're receiving this email because of your account on gitlab.rtems.org. 
Unsubscribe from this thread: 
https://gitlab.rtems.org/-/namespace/49/sent_notifications/6-2pk21w7qnjccr06vfuijshhh0-1d/unsubscribe
 | Manage all notifications: https://gitlab.rtems.org/-/profile/notifications | 
Help: https://gitlab.rtems.org/help


_______________________________________________
bugs mailing list
[email protected]
http://lists.rtems.org/mailman/listinfo/bugs

Reply via email to