Kleidos API Search

In development. It changes without notice.

Topic

RTOS Facade

Tasks and the core each runs on, queues, semaphores, critical sections, delays and the task watchdog.

The types of FreeRTOS stay inside. Core 1 runs the application's loop and the screen; core 0 runs Bluetooth, Wi-Fi, storage and crypto. A task of the application takes a priority from 1 to 6, below the radios'. The size of a stack is in bytes.

using namespace kleidos::platform;
rtos::TaskConfig cfg{ .name = "worker", .stackBytes = 8192,
.priority = rtos::kMinAppPriority,
.core = rtos::Core::AppCpu };
rtos::createPinnedTask( +[]( void* ) { }, cfg );

What more than one task may reach first (a queue, a mutex, a task) is built under kleidos::platform::rtos::Once: one caller builds it and the others wait for that, so it is never built twice.

The tick and the CPU clock. On the ESP32 boards the tick is counted in CPU cycles, by a number worked out for the clock the board started at. Each change of the CPU clock therefore writes that number again, in the one function that changes it; otherwise every delay and timeout would be wrong by the ratio of the two clocks. The interval already running on each core ends up to 2 ms late or early, once for each change. On the ESP32-S3 the tick comes from a timer of its own and none of this is needed. Where ESP-IDF's power management makes the changes, it does this itself.

See also
Monotonic Clock & Deadlines, Power, Sleep & System Control

Files

file src/platform/rtos/rtos.h
Umbrella include for the platform RTOS facade.
file src/platform/rtos/rtos_once.cpp
The wait step of the exactly-once guard.
file src/platform/rtos/rtos_once.h
Exactly-once creation of an object several tasks may reach first.
file src/platform/rtos/rtos_queue.cpp
Raw and typed FreeRTOS queue operations.
file src/platform/rtos/rtos_queue.h
Type-safe RTOS queue facade over FreeRTOS queues.
file src/platform/rtos/rtos_stack_scrub.cpp
Stack fill-pattern refill implementation.
file src/platform/rtos/rtos_stack_scrub.h
Debug-only refill of a task's FreeRTOS stack fill pattern.
file src/platform/rtos/rtos_sync.cpp
FreeRTOS semaphore, mutex, and critical-section implementations.
file src/platform/rtos/rtos_sync.h
RTOS synchronization primitives: semaphores, mutexes, critical locks.
file src/platform/rtos/rtos_task.cpp
FreeRTOS task lifecycle, introspection, and notification implementations.
file src/platform/rtos/rtos_task.h
RTOS task lifecycle, introspection, and notification facade.
file src/platform/rtos/rtos_time.cpp
FreeRTOS tick and delay implementations.
file src/platform/rtos/rtos_time.h
RTOS timing facade: tick conversions and task delays.
file src/platform/rtos/rtos_types.h
Shared types for the platform RTOS facade.
file src/platform/rtos/tick_base.h
Cycles-per-tick arithmetic for a tick generated from the CPU clock.
file src/platform/rtos/watchdog.cpp
Task watchdog (TWDT) configuration and subscription implementation.
file src/platform/rtos/watchdog.h
Task watchdog (TWDT) configuration and subscription facade.

Classes

class kleidos::platform::rtos::Once
One-time initialization guard shared between tasks on either core. More about kleidos::platform::rtos::Once
class kleidos::platform::rtos::Queue< T >
Owning, type-safe queue of trivially-copyable T. More about kleidos::platform::rtos::Queue< T >
class kleidos::platform::rtos::IsrYield
Tracks whether an ISR woke a higher-priority task and should yield on exit. More about kleidos::platform::rtos::IsrYield
struct kleidos::platform::rtos::CriticalMux
Storage for a critical-section spinlock. More about kleidos::platform::rtos::CriticalMux
class kleidos::platform::rtos::CriticalLock
RAII task-context critical section (enter on construct, exit on destroy). More about kleidos::platform::rtos::CriticalLock
class kleidos::platform::rtos::CriticalIsrLock
RAII ISR-context critical section (enter on construct, exit on destroy). More about kleidos::platform::rtos::CriticalIsrLock
class kleidos::platform::rtos::BinarySemaphore
Owning RAII wrapper around a binary semaphore. More about kleidos::platform::rtos::BinarySemaphore
class kleidos::platform::rtos::Mutex
Owning RAII wrapper around a mutex. More about kleidos::platform::rtos::Mutex
class kleidos::platform::rtos::MutexLock
Scoped lock guard for a Mutex (locks on construct, unlocks on destroy). More about kleidos::platform::rtos::MutexLock
struct kleidos::platform::rtos::TaskSnapshot
Point-in-time description of a task for diagnostics. More about kleidos::platform::rtos::TaskSnapshot
class kleidos::platform::rtos::Ticks
Type-safe relative tick duration. More about kleidos::platform::rtos::Ticks
class kleidos::platform::rtos::TickCount
Type-safe absolute tick timestamp. More about kleidos::platform::rtos::TickCount
struct kleidos::platform::rtos::TaskConfig
Parameters for creating a pinned task. More about kleidos::platform::rtos::TaskConfig
struct kleidos::platform::watchdog::Config
Task-watchdog configuration. More about kleidos::platform::watchdog::Config
class kleidos::platform::watchdog::ScopedTimeout
RAII guard that widens the task-watchdog timeout for a bounded block. More about kleidos::platform::watchdog::ScopedTimeout

Typedefs

usingkleidos::platform::rtos::Priority
Task priority value.
usingkleidos::platform::rtos::QueueDepth
Queue capacity in items.

Enumerations

enum class kleidos::platform::rtos::Core : int32_t { kleidos::platform::rtos::Core::ProCpu , kleidos::platform::rtos::Core::AppCpu , kleidos::platform::rtos::Core::NoAffinity }
CPU core affinity for pinned tasks. More about kleidos::platform::rtos::Core
enum class kleidos::platform::rtos::NotifyAction : uint8_t { kleidos::platform::rtos::NotifyAction::NoAction, kleidos::platform::rtos::NotifyAction::SetBits, kleidos::platform::rtos::NotifyAction::Increment, kleidos::platform::rtos::NotifyAction::SetValueWithOverwrite, kleidos::platform::rtos::NotifyAction::SetValueWithoutOverwrite }
enum class kleidos::platform::rtos::TaskState : uint8_t { kleidos::platform::rtos::TaskState::Running, kleidos::platform::rtos::TaskState::Ready, kleidos::platform::rtos::TaskState::Blocked, kleidos::platform::rtos::TaskState::Suspended, kleidos::platform::rtos::TaskState::Deleted, kleidos::platform::rtos::TaskState::Unknown }
The scheduling state of a task, as taskSnapshots reports it. More about kleidos::platform::rtos::TaskState
enum class kleidos::platform::watchdog::TaskSubscribeResult : uint8_t { kleidos::platform::watchdog::TaskSubscribeResult::Subscribed , kleidos::platform::watchdog::TaskSubscribeResult::AlreadySubscribed , kleidos::platform::watchdog::TaskSubscribeResult::InvalidTask , kleidos::platform::watchdog::TaskSubscribeResult::Failed }

Functions

template<typename T>
QueueHandlekleidos::platform::rtos::createStaticQueue (QueueDepth depth, uint8_t *itemStorage, StaticQueue &queueStorage)
Create a static queue for trivially-copyable type T.
template<typename T>
boolkleidos::platform::rtos::queueSend (QueueHandle handle, const T &item, Ticks waitTicks=noWait())
Send a typed item onto a queue.
template<typename T>
boolkleidos::platform::rtos::queueSendFromIsr (QueueHandle handle, const T &item, IsrYield &yield)
Send a typed item onto a queue from ISR context.
template<typename T>
boolkleidos::platform::rtos::queueReceive (QueueHandle handle, T &out, Ticks waitTicks=waitForever())
Receive a typed item from a queue.
template<typename T>
boolkleidos::platform::rtos::queueReceiveFromIsr (QueueHandle handle, T &out, IsrYield &yield)
Receive a typed item from a queue in ISR context.
template<size_t Capacity>
uint32_tkleidos::platform::rtos::taskSnapshots (TaskSnapshot(&out)[Capacity], uint32_t &totalRuntime)
Capture task snapshots into a fixed-size array (capacity deduced).
constexpr uint32_tkleidos::platform::rtos::tickBaseCyclesFor (uint32_t cpuMhz, uint32_t tickRateHz)
Cycles one tick lasts at a core frequency.
constexpr boolkleidos::platform::rtos::storeTickBaseCycles (unsigned &cachedCycles, uint32_t cpuMhz, uint32_t tickRateHz)
Store the cycles-per-tick a core frequency implies, or refuse.
constexpr Configkleidos::platform::watchdog::bootConfig ()
The configuration ESP-IDF's TWDT auto-init applies at boot.
boolkleidos::platform::watchdog::configure (const Config &config)
Reconfigure an already-initialized task watchdog.
Configkleidos::platform::watchdog::currentConfig ()
Return the task-watchdog configuration currently in force.
boolkleidos::platform::watchdog::configureOrInit (const Config &config)
Reconfigure the task watchdog, initializing it first if needed.
TaskSubscribeResultkleidos::platform::watchdog::subscribeTask (rtos::TaskHandle task)
Subscribe a task to the task watchdog.
boolkleidos::platform::watchdog::resetCurrentTask ()
Feed the task watchdog for the calling task.
const char *kleidos::platform::watchdog::taskSubscribeResultName (TaskSubscribeResult result)
Return a human-readable name for a subscribe result.
boolkleidos::platform::watchdog::taskWdtConfigured ()
Whether the task watchdog (TWDT) is compiled in and auto-initialized.
boolkleidos::platform::watchdog::intWdtConfigured ()
Whether the interrupt watchdog (IWDT) is compiled in.

Variables

constexpr Prioritykleidos::platform::rtos::kMinAppPriority
Lowest allowed application task priority.
constexpr Prioritykleidos::platform::rtos::kMaxAppPriority
Highest allowed application task priority.
constexpr uint32_tkleidos::platform::rtos::kTickBaseCyclesUnknown
constexpr uint32_tkleidos::platform::rtos::kHertzPerMegahertz
Hertz in one megahertz, so the conversion below is not a bare literal.
constexpr uint32_tkleidos::platform::rtos::kMaxConvertibleCpuMhz
constexpr uint32_tkleidos::platform::watchdog::kFallbackTimeoutMs
Timeout assumed when sdkconfig does not define the TWDT period.
constexpr uint32_tkleidos::platform::watchdog::kIdleCoreBit0
Idle-core mask bit of core 0.
constexpr uint32_tkleidos::platform::watchdog::kIdleCoreBit1
Idle-core mask bit of core 1.

FreeRTOS handle aliases

usingkleidos::platform::rtos::TaskEntry
Task entry-point function type.
usingkleidos::platform::rtos::TaskHandle
Opaque task handle.
usingkleidos::platform::rtos::QueueHandle
Opaque queue handle.
usingkleidos::platform::rtos::SemaphoreHandle
Opaque semaphore/mutex handle.
usingkleidos::platform::rtos::StackType
Stack storage word type.
usingkleidos::platform::rtos::StaticTask
Static task control block.
usingkleidos::platform::rtos::StaticQueue
Static queue control block.
usingkleidos::platform::rtos::StaticSemaphore
Static semaphore control block.

Diagnostics

constexpr uint32_tkleidos::platform::rtos::kMaxTaskSnapshots
Capacity of one task census: the largest snapshot this facade can take.
uint32_tkleidos::platform::rtos::stackHighWaterBytes (TaskHandle task)
Return the minimum free stack seen for a task (high-water mark).
uint32_tkleidos::platform::rtos::currentStackHighWaterBytes ()
Return the minimum free stack seen for the calling task.
uint32_tkleidos::platform::rtos::taskCount ()
Return the total number of tasks in the system.
uint32_tkleidos::platform::rtos::taskSnapshots (TaskSnapshot *out, uint32_t capacity, uint32_t &totalRuntime)
Capture a snapshot of all tasks into out.

Raw operations

QueueHandlekleidos::platform::rtos::createStaticQueueRaw (QueueDepth depth, size_t itemSize, uint8_t *itemStorage, StaticQueue &queueStorage)
Create a static queue backed by caller-provided storage.
QueueHandlekleidos::platform::rtos::createQueueRaw (QueueDepth depth, size_t itemSize)
Create a dynamically-allocated queue.
boolkleidos::platform::rtos::queueSendRaw (QueueHandle handle, const void *item, Ticks waitTicks)
Send raw bytes onto a queue.
boolkleidos::platform::rtos::queueSendFromIsrRaw (QueueHandle handle, const void *item, IsrYield &yield)
Send raw bytes onto a queue from ISR context.
boolkleidos::platform::rtos::queueReceiveRaw (QueueHandle handle, void *out, Ticks waitTicks)
Receive raw bytes from a queue.
boolkleidos::platform::rtos::queueReceiveFromIsrRaw (QueueHandle handle, void *out, IsrYield &yield)
Receive raw bytes from a queue in ISR context.
uint32_tkleidos::platform::rtos::queuePending (QueueHandle handle)
Return the number of items currently held in the queue.
voidkleidos::platform::rtos::deleteQueue (QueueHandle &handle)
Delete a queue and clear its handle.

Semaphore helpers

boolkleidos::platform::rtos::takeSemaphore (SemaphoreHandle handle, Ticks waitTicks=waitForever())
Take (wait for) a semaphore.
boolkleidos::platform::rtos::giveSemaphore (SemaphoreHandle handle)
Give (signal) a semaphore.
boolkleidos::platform::rtos::giveSemaphoreFromIsr (SemaphoreHandle handle, IsrYield &yield)
Give a semaphore from ISR context.
SemaphoreHandlekleidos::platform::rtos::createStaticMutex (StaticSemaphore &storage)
Create a statically-allocated mutex.
SemaphoreHandlekleidos::platform::rtos::createMutex ()
Create a dynamically-allocated mutex.
SemaphoreHandlekleidos::platform::rtos::createRecursiveMutex ()
Create a dynamically-allocated recursive mutex.
SemaphoreHandlekleidos::platform::rtos::createStaticBinarySemaphore (StaticSemaphore &storage)
Create a statically-allocated binary semaphore.
boolkleidos::platform::rtos::takeRecursiveMutex (SemaphoreHandle handle, Ticks waitTicks=waitForever())
Lock a recursive mutex.
boolkleidos::platform::rtos::giveRecursiveMutex (SemaphoreHandle handle)
Unlock a recursive mutex.
boolkleidos::platform::rtos::mutexHeldByCurrentTask (SemaphoreHandle handle)
True when the calling task holds the mutex handle.

Validation

boolkleidos::platform::rtos::isValidCore (Core core)
True when core is a real core selector (not NoAffinity).
boolkleidos::platform::rtos::isAppPriority (Priority priority)
True when priority falls within the application priority band.
intkleidos::platform::rtos::coreId (Core core)
Return the numeric core id for a Core value.

Current-context queries

TaskHandlekleidos::platform::rtos::currentTask ()
Return the handle of the calling task.
TaskHandlekleidos::platform::rtos::idleTask (Core core)
Return the idle-task handle for a core.
Corekleidos::platform::rtos::currentCore ()
Return the core the caller is currently running on.
intkleidos::platform::rtos::currentCoreId ()
Return the numeric core id the caller is running on.
Prioritykleidos::platform::rtos::currentTaskPriority ()
Return the priority of the calling task.

Lifecycle

voidkleidos::platform::rtos::deleteTask (TaskHandle task)
Delete a task by handle.
voidkleidos::platform::rtos::deleteCurrentTask ()
Delete the calling task (never returns to caller).
voidkleidos::platform::rtos::yield ()
Hand the core to another ready task of the caller's priority, if one waits.

Creation

boolkleidos::platform::rtos::createPinnedTask (TaskEntry entry, const TaskConfig &config, TaskHandle *outHandle=nullptr)
Create a dynamically-allocated task pinned to a specific core.
TaskHandlekleidos::platform::rtos::createStaticPinnedTask (TaskEntry entry, const TaskConfig &config, StackType *stackStorage, StaticTask *taskStorage)
Create a statically-allocated task pinned to a specific core.

Notifications

boolkleidos::platform::rtos::notify (TaskHandle task, uint32_t value, NotifyAction action)
Send a direct-to-task notification.
boolkleidos::platform::rtos::waitNotification (uint32_t clearOnEntry, uint32_t clearOnExit, uint32_t *value, Ticks waitTicks)
Block the calling task until a notification arrives.

Tick constructors

constexpr Tickskleidos::platform::rtos::ticksFromMs (uint32_t ms)
Convert a millisecond duration to RTOS ticks.
constexpr Tickskleidos::platform::rtos::milliseconds (uint32_t ms)
Alias of ticksFromMs(); preferred in call sites for readability.
constexpr Tickskleidos::platform::rtos::noWait ()
Return a zero-wait (non-blocking) duration.
constexpr Tickskleidos::platform::rtos::waitForever ()
Return an infinite-wait duration.

Delays

TickCountkleidos::platform::rtos::tickCount ()
Return the current absolute tick timestamp.
voidkleidos::platform::rtos::delay (Ticks ticks)
Block the caller for a relative tick duration.
voidkleidos::platform::rtos::delayMs (uint32_t ms)
Block the caller for a millisecond duration.
voidkleidos::platform::rtos::delayForever ()
Block the caller indefinitely.
voidkleidos::platform::rtos::delayUntil (TickCount &previousWake, Ticks period)
Drift-free periodic delay relative to a reference wake time.

Tick base

boolkleidos::platform::rtos::syncTickBase (uint32_t cpuMhz)
Rewrite the cached cycles-per-tick the Xtensa tick ISR adds to CCOMPARE.
uint32_tkleidos::platform::rtos::tickRateHz ()
Ticks the kernel counts in one second.
uint32_tkleidos::platform::rtos::tickBaseCycles ()
Cycles the tick source counts per tick.

Back to the top

Enumeration Type Documentation

Core #

enum class kleidos::platform::rtos::Core : int32_t

CPU core affinity for pinned tasks.

Enumerator
ProCpu 

Core 0 (services: BLE/WiFi/storage/crypto).

AppCpu 

Core 1 (UI / FSM / display).

NoAffinity 

No fixed core affinity.

NotifyAction #

enum class kleidos::platform::rtos::NotifyAction : uint8_t

Action applied by a task notification.

Value Meaning
NoAction Wake the target without modifying the notification value.
SetBits OR value into the current notification value.
Increment Add 1 to the notification value (the value argument is ignored).
SetValueWithOverwrite Replace the notification value unconditionally.
SetValueWithoutOverwrite Replace the value only if no notification is pending.
Enumerator
NoAction 

Wake only; do not modify the value.

SetBits 

OR bits into the notification value.

Increment 

Increment the notification value.

SetValueWithOverwrite 

Overwrite the value unconditionally.

SetValueWithoutOverwrite 

Set the value only if not pending.

TaskState #

enum class kleidos::platform::rtos::TaskState : uint8_t

The scheduling state of a task, as taskSnapshots reports it.

FreeRTOS's own states, with a raw value that has no name here reported as Unknown.

Enumerator
Running 

Currently executing.

Ready 

Ready to run.

Blocked 

Blocked on an event/timeout.

Suspended 

Suspended.

Deleted 

Awaiting cleanup.

Unknown 

State could not be determined.

TaskSubscribeResult #

enum class kleidos::platform::watchdog::TaskSubscribeResult : uint8_t

Result of subscribing a task to the watchdog.

Value Meaning
Subscribed Task is now monitored.
AlreadySubscribed Task was already in the watchdog's set; treated as success.
InvalidTask The task handle was nullptr.
Failed The TWDT reported a non-recoverable error.
Enumerator
Subscribed 

Task is now monitored.

AlreadySubscribed 

Task was already subscribed.

InvalidTask 

Null/invalid task handle.

Failed 

Underlying driver call failed.

Back to the top

Function Documentation

bootConfig() #

Config kleidos::platform::watchdog::bootConfig()
constexpr

The configuration ESP-IDF's TWDT auto-init applies at boot.

Read from the CONFIG_ESP_TASK_WDT_* sdkconfig values (the period, the idle cores watched and whether a timeout panics); the fallbacks above on the native build. A caller that must not change the idle mask at runtime checks it here at compile time.

Returns
The boot configuration.

configure() #

bool kleidos::platform::watchdog::configure(const Config & config)

Reconfigure an already-initialized task watchdog.

On success the new settings become the value reported by currentConfig().

Parameters
NameMeaning
configNew timeout and panic settings.
Return values
ValueMeaning
trueWatchdog reconfigured with the new settings.
falseTWDT was not yet initialized.

configureOrInit() #

bool kleidos::platform::watchdog::configureOrInit(const Config & config)

Reconfigure the task watchdog, initializing it first if needed.

Parameters
NameMeaning
configTimeout, idle-core mask, and panic settings.
Return values
ValueMeaning
trueWatchdog reconfigured (or initialized and configured).
falseDriver refused the configuration.

coreId() #

int kleidos::platform::rtos::coreId(Core core)

Return the numeric core id for a Core value.

Parameters
NameMeaning
coreCore enum value.
Returns
0 for ProCpu, 1 for AppCpu; -1 for NoAffinity.

createMutex() #

SemaphoreHandle kleidos::platform::rtos::createMutex()

Create a dynamically-allocated mutex.

Returns
Non-null handle on success, nullptr on allocation failure.

createPinnedTask() #

bool kleidos::platform::rtos::createPinnedTask(TaskEntry entry, const TaskConfig & config, TaskHandle * outHandle = nullptr)

Create a dynamically-allocated task pinned to a specific core.

Parameters
NameMeaning
entryTask entry function.
configName, stack size, priority, core, and argument.
outHandleOptional; set to the new task handle on success.
Return values
ValueMeaning
trueTask was created and pinned to the requested core.
falseAllocation or configuration failed.

createQueueRaw() #

QueueHandle kleidos::platform::rtos::createQueueRaw(QueueDepth depth, size_t itemSize)

Create a dynamically-allocated queue.

Parameters
NameMeaning
depthMaximum number of items the queue can hold.
itemSizeSize of each item in bytes.
Returns
Non-null handle on success, nullptr on allocation failure.

createRecursiveMutex() #

SemaphoreHandle kleidos::platform::rtos::createRecursiveMutex()

Create a dynamically-allocated recursive mutex.

Returns
Non-null handle on success, nullptr on allocation failure.

createStaticBinarySemaphore() #

SemaphoreHandle kleidos::platform::rtos::createStaticBinarySemaphore(StaticSemaphore & storage)

Create a statically-allocated binary semaphore.

Parameters
NameMeaning
storageCaller-provided static control block.
Returns
Non-null handle on success.

createStaticMutex() #

SemaphoreHandle kleidos::platform::rtos::createStaticMutex(StaticSemaphore & storage)

Create a statically-allocated mutex.

Parameters
NameMeaning
storageCaller-provided static control block.
Returns
Non-null handle on success.

createStaticPinnedTask() #

TaskHandle kleidos::platform::rtos::createStaticPinnedTask(TaskEntry entry, const TaskConfig & config, StackType * stackStorage, StaticTask * taskStorage)

Create a statically-allocated task pinned to a specific core.

Parameters
NameMeaning
entryTask entry function.
configName, stack size, priority, core, and argument.
stackStorageCaller-provided stack memory (config.stackBytes bytes).
taskStorageCaller-provided static task control block.
Returns
Task handle; never null (panics on invalid config).

createStaticQueue() #

template<typename T>
QueueHandle kleidos::platform::rtos::createStaticQueue(QueueDepth depth, uint8_t * itemStorage, StaticQueue & queueStorage)
inline

Create a static queue for trivially-copyable type T.

Template Parameters
NameMeaning
TElement type (must be trivially copyable).
Parameters
NameMeaning
depthMaximum number of items the queue can hold.
itemStorageCaller-provided storage (depth * sizeof(T) bytes).
queueStorageCaller-provided static queue control block.
Returns
Non-null handle on success.

createStaticQueueRaw() #

QueueHandle kleidos::platform::rtos::createStaticQueueRaw(QueueDepth depth, size_t itemSize, uint8_t * itemStorage, StaticQueue & queueStorage)

Create a static queue backed by caller-provided storage.

Parameters
NameMeaning
depthMaximum number of items the queue can hold.
itemSizeSize of each item in bytes.
itemStorageCaller-provided storage (depth * itemSize bytes).
queueStorageCaller-provided static queue control block.
Returns
Non-null handle on success.

currentConfig() #

Config kleidos::platform::watchdog::currentConfig()

Return the task-watchdog configuration currently in force.

ESP-IDF exposes no getter for the live TWDT settings, so this facade is the single source of truth: the returned value starts at the boot configuration IDF's auto-init applied (the CONFIG_ESP_TASK_WDT_* sdkconfig values) and tracks every later configure() / configureOrInit() that succeeded. Code that temporarily changes the watchdog restores this value instead of rebuilding one from compile-time constants, which would discard the runtime settings.

Returns
The live configuration; the sdkconfig boot values on the native build.
Note
Reconfiguration is not concurrency-safe (the same restriction ESP-IDF documents for esp_task_wdt_reconfigure): only one task at a time may change the watchdog.

currentCore() #

Core kleidos::platform::rtos::currentCore()

Return the core the caller is currently running on.

Returns
Core enum value for the calling task's current core.

currentCoreId() #

int kleidos::platform::rtos::currentCoreId()

Return the numeric core id the caller is running on.

Returns
0 or 1.

currentStackHighWaterBytes() #

uint32_t kleidos::platform::rtos::currentStackHighWaterBytes()

Return the minimum free stack seen for the calling task.

Returns
Minimum free stack in bytes observed since the calling task started.

currentTask() #

TaskHandle kleidos::platform::rtos::currentTask()

Return the handle of the calling task.

Returns
TaskHandle of the currently executing task.

currentTaskPriority() #

Priority kleidos::platform::rtos::currentTaskPriority()

Return the priority of the calling task.

Returns
Current task priority.

delay() #

void kleidos::platform::rtos::delay(Ticks ticks)

Block the caller for a relative tick duration.

Parameters
NameMeaning
ticksDuration to sleep.

delayMs() #

void kleidos::platform::rtos::delayMs(uint32_t ms)

Block the caller for a millisecond duration.

Parameters
NameMeaning
msMilliseconds to sleep.

delayUntil() #

void kleidos::platform::rtos::delayUntil(TickCount & previousWake, Ticks period)

Drift-free periodic delay relative to a reference wake time.

Parameters
NameMeaning
previousWakeReference wake tick updated on each call; set to tickCount() before the first call.
periodDesired period between wakes.

deleteQueue() #

void kleidos::platform::rtos::deleteQueue(QueueHandle & handle)

Delete a queue and clear its handle.

Parameters
NameMeaning
handleQueue handle; set to nullptr after deletion.

deleteTask() #

void kleidos::platform::rtos::deleteTask(TaskHandle task)

Delete a task by handle.

Parameters
NameMeaning
taskTask handle to delete; nullptr deletes the calling task.

giveRecursiveMutex() #

bool kleidos::platform::rtos::giveRecursiveMutex(SemaphoreHandle handle)

Unlock a recursive mutex.

Parameters
NameMeaning
handleRecursive mutex handle.
Return values
ValueMeaning
trueMutex was unlocked.
falseDriver refused the unlock.

giveSemaphore() #

bool kleidos::platform::rtos::giveSemaphore(SemaphoreHandle handle)

Give (signal) a semaphore.

Parameters
NameMeaning
handleSemaphore or mutex handle.
Return values
ValueMeaning
trueSemaphore was given.
falseDriver refused the give (e.g. invalid handle).

giveSemaphoreFromIsr() #

bool kleidos::platform::rtos::giveSemaphoreFromIsr(SemaphoreHandle handle, IsrYield & yield)

Give a semaphore from ISR context.

Parameters
NameMeaning
handleSemaphore handle.
yieldISR yield tracker; call yield.yieldIfNeeded() before leaving the ISR.
Return values
ValueMeaning
trueSemaphore was given from ISR.
falseDriver refused the give.

idleTask() #

TaskHandle kleidos::platform::rtos::idleTask(Core core)

Return the idle-task handle for a core.

Parameters
NameMeaning
coreCore selector.
Returns
TaskHandle of the idle task pinned to that core.

intWdtConfigured() #

bool kleidos::platform::watchdog::intWdtConfigured()

Whether the interrupt watchdog (IWDT) is compiled in.

Reflects the CONFIG_ESP_INT_WDT sdkconfig option. A read-only build-configuration query with no side effects.

Return values
ValueMeaning
trueInterrupt watchdog is configured.
falseInterrupt watchdog is disabled, or the native build.

isAppPriority() #

bool kleidos::platform::rtos::isAppPriority(Priority priority)

True when priority falls within the application priority band.

Parameters
NameMeaning
priorityPriority value to check.
Return values
ValueMeaning
truekMinAppPriority <= priority <= kMaxAppPriority.
falsepriority is below the app band (radio) or above it.

isValidCore() #

bool kleidos::platform::rtos::isValidCore(Core core)

True when core is a real core selector (not NoAffinity).

Parameters
NameMeaning
coreCore enum value to validate.
Return values
ValueMeaning
truecore maps to an existing core.
falsecore is NoAffinity or out of range.

milliseconds() #

Ticks kleidos::platform::rtos::milliseconds(uint32_t ms)
constexpr

Alias of ticksFromMs(); preferred in call sites for readability.

Parameters
NameDirectionMeaning
msinDuration in milliseconds.
Returns
Corresponding Ticks value.

mutexHeldByCurrentTask() #

bool kleidos::platform::rtos::mutexHeldByCurrentTask(SemaphoreHandle handle)

True when the calling task holds the mutex handle.

A mutex is not recursive: a second take from its holder waits for ever, so a caller that may re-enter asks this first.

Parameters
NameMeaning
handleMutex handle (from createMutex or createStaticMutex).
Return values
ValueMeaning
trueThe calling task is the holder.
falseAnother task holds it, nobody does, or handle is null.

notify() #

bool kleidos::platform::rtos::notify(TaskHandle task, uint32_t value, NotifyAction action)

Send a direct-to-task notification.

Parameters
NameMeaning
taskTarget task handle.
valueValue for the notification action.
actionHow to modify the notification value (SetBits, Increment, etc.).
Return values
ValueMeaning
trueNotification was posted to task.
falseDriver rejected the notification request.

noWait() #

Ticks kleidos::platform::rtos::noWait()
constexpr

Return a zero-wait (non-blocking) duration.

Returns
Ticks with value 0 — the call returns immediately if no item is available.

queuePending() #

uint32_t kleidos::platform::rtos::queuePending(QueueHandle handle)

Return the number of items currently held in the queue.

Parameters
NameMeaning
handleQueue handle.
Returns
Item count.

queueReceive() #

template<typename T>
bool kleidos::platform::rtos::queueReceive(QueueHandle handle, T & out, Ticks waitTicks = waitForever())
inline

Receive a typed item from a queue.

Template Parameters
NameMeaning
TElement type (must be trivially copyable).
Parameters
NameMeaning
handleQueue handle.
outReference to store the received item.
waitTicksMaximum time to block when the queue is empty.
Returns
True on success; false on timeout.

queueReceiveFromIsr() #

template<typename T>
bool kleidos::platform::rtos::queueReceiveFromIsr(QueueHandle handle, T & out, IsrYield & yield)
inline

Receive a typed item from a queue in ISR context.

Template Parameters
NameMeaning
TElement type (must be trivially copyable).
Parameters
NameMeaning
handleQueue handle.
outReference to store the received item.
yieldISR yield tracker; call yield.yieldIfNeeded() before leaving the ISR.
Returns
True on success.

queueReceiveFromIsrRaw() #

bool kleidos::platform::rtos::queueReceiveFromIsrRaw(QueueHandle handle, void * out, IsrYield & yield)

Receive raw bytes from a queue in ISR context.

Parameters
NameMeaning
handleQueue handle.
outDestination buffer; must be at least itemSize bytes.
yieldISR yield tracker; call yield.yieldIfNeeded() before leaving the ISR.
Return values
ValueMeaning
trueItem was received from ISR.
falseNo item was available.

queueReceiveRaw() #

bool kleidos::platform::rtos::queueReceiveRaw(QueueHandle handle, void * out, Ticks waitTicks)

Receive raw bytes from a queue.

Parameters
NameMeaning
handleQueue handle.
outDestination buffer; must be at least itemSize bytes.
waitTicksMaximum time to block when the queue is empty.
Return values
ValueMeaning
trueItem was received before waitTicks elapsed.
falseTimeout elapsed before an item arrived.

queueSend() #

template<typename T>
bool kleidos::platform::rtos::queueSend(QueueHandle handle, const T & item, Ticks waitTicks = noWait())
inline

Send a typed item onto a queue.

Template Parameters
NameMeaning
TElement type (must be trivially copyable).
Parameters
NameMeaning
handleQueue handle.
itemItem to send.
waitTicksMaximum time to block when the queue is full.
Returns
True on success; false on timeout.

queueSendFromIsr() #

template<typename T>
bool kleidos::platform::rtos::queueSendFromIsr(QueueHandle handle, const T & item, IsrYield & yield)
inline

Send a typed item onto a queue from ISR context.

Template Parameters
NameMeaning
TElement type (must be trivially copyable).
Parameters
NameMeaning
handleQueue handle.
itemItem to send.
yieldISR yield tracker; call yield.yieldIfNeeded() before leaving the ISR.
Returns
True on success.

queueSendFromIsrRaw() #

bool kleidos::platform::rtos::queueSendFromIsrRaw(QueueHandle handle, const void * item, IsrYield & yield)

Send raw bytes onto a queue from ISR context.

Parameters
NameMeaning
handleQueue handle.
itemPointer to the item to copy into the queue.
yieldISR yield tracker; call yield.yieldIfNeeded() before leaving the ISR.
Return values
ValueMeaning
trueItem was queued from ISR.
falseDriver refused the post.

queueSendRaw() #

bool kleidos::platform::rtos::queueSendRaw(QueueHandle handle, const void * item, Ticks waitTicks)

Send raw bytes onto a queue.

Parameters
NameMeaning
handleQueue handle.
itemPointer to the item to copy into the queue.
waitTicksMaximum time to block when the queue is full.
Return values
ValueMeaning
trueItem was queued successfully.
falseTimeout elapsed before the queue had space.

resetCurrentTask() #

bool kleidos::platform::watchdog::resetCurrentTask()

Feed the task watchdog for the calling task.

A silent no-op when the calling task is not subscribed, so shared code paths that run on both subscribed and unsubscribed tasks may feed unconditionally without producing driver error logs.

Return values
ValueMeaning
trueWatchdog was reset for the calling task.
falseCalling task was not subscribed to the watchdog.

stackHighWaterBytes() #

uint32_t kleidos::platform::rtos::stackHighWaterBytes(TaskHandle task)

Return the minimum free stack seen for a task (high-water mark).

Parameters
NameMeaning
taskTask handle to query.
Returns
Minimum free stack in bytes observed since task creation.

storeTickBaseCycles() #

bool kleidos::platform::rtos::storeTickBaseCycles(unsigned & cachedCycles, uint32_t cpuMhz, uint32_t tickRateHz)
constexpr

Store the cycles-per-tick a core frequency implies, or refuse.

The whole of the decision syncTickBase makes, with the one thing that cannot exist on the host — the name of the port's cached divisor — passed in instead of referenced. That split is what puts the store itself under host test: a change that computes the right number and never writes it, or writes it on the argument pair that has no answer, is visible here.

A refusal deliberately leaves cachedCycles as it was. Zero cycles per tick would make the tick interrupt re-arm the comparator on the value it just fired at, so the frequency it last described is a far better answer than a number that stops the tick.

Parameters
NameDirectionMeaning
cachedCyclesin, outCell the tick source reads its per-tick cycle count from; written only on success.
cpuMhzinCore frequency now in force, in MHz.
tickRateHzinTick rate in Hz.
Return values
ValueMeaning
truecachedCycles now describes cpuMhz.
falseThe pair does not convert (see tickBaseCyclesFor) and cachedCycles is untouched.

subscribeTask() #

TaskSubscribeResult kleidos::platform::watchdog::subscribeTask(rtos::TaskHandle task)

Subscribe a task to the task watchdog.

Parameters
NameMeaning
taskTask handle to monitor; nullptr results in InvalidTask.
Return values
ValueMeaning
TaskSubscribeResult::SubscribedTask is now monitored.
TaskSubscribeResult::AlreadySubscribedTask was already subscribed.
TaskSubscribeResult::InvalidTasktask was null.
TaskSubscribeResult::FailedUnderlying driver call failed.

syncTickBase() #

bool kleidos::platform::rtos::syncTickBase(uint32_t cpuMhz)

Rewrite the cached cycles-per-tick the Xtensa tick ISR adds to CCOMPARE.

Re-derive the tick period the kernel counts, for a new core frequency.

ESP-IDF computes _xt_tick_divisor once at boot from the frequency the SoC booted at (xtensa_init.c:53: esp_clk_cpu_freq() / XT_TICK_PER_SEC) and rewrites it in exactly one place afterwards — esp_pm's on_freq_update (esp_pm/pm_impl.c:590), which runs only on the boards built with ESP-IDF's power management (CONFIG_PM_ENABLE: the idle floor, or automatic light sleep). This is the firmware's substitute for that one place on every other board; on those, system::setCpuFrequencyMhz hands the clock to esp_pm and never calls this.

The intervals this cannot reach

The tick ISR arms the comparator for the NEXT interval before it services the current one: it reads CCOMPARE, adds the divisor as it stands at that instant, and writes the sum back (FreeRTOS-Kernel/portable/xtensa/portasm.S:326-331). The interval already in flight when this function runs was therefore sized in cycles against the old frequency, and writing the divisor cannot re-size it — only writing CCOMPARE can.

So one interval per core comes out wrong, and it is wrong by the frequency ratio rather than by a fixed amount: an interval armed at the old frequency and elapsed at the new one lasts (old / new) tick periods. CONFIG_FREERTOS_HZ is 1000 on every board (sdkconfig.defaults.kleidos_ble:87), so a tick period is 1 ms and the extremes are

  • a 240 -> 80 MHz drop: one interval of 3 ms, i.e. 2 ms late;
  • an 80 -> 240 MHz rise: one interval of 0.333 ms, i.e. 0.67 ms early.

Both cores pay it independently — each has its own CCOMPARE and its own interval in flight — and each re-arms from this value at its own next tick, after which every interval on both cores is a real tick again.

A tick that lands on either core in the few instructions between the frequency switch and this write arms one further interval from the stale divisor, so the honest worst case is two intervals per core, not one. Against a 1 kHz tick that window is about 10^-5 of the time between ticks.

The ISR's catch-up loop absorbs none of it. That loop re-enters only when the cycles elapsed at ISR entry already exceed the divisor (portasm.S:353-357), which is a tick serviced late; a comparator re-armed exactly one divisor ahead never produces that.

Removing the one-off means re-arming CCOMPARE on both cores, which is what esp_pm does: rescale the calling core's comparator under a spinlock, then send a cross-core interrupt and spin until the other core has rescaled its own. That machinery belongs to esp_pm and lives in IRAM. A bounded, self-correcting slip on one tick boundary per core per frequency change is the price of not having it; what it replaces is a permanent proportional error on every tick for as long as the clock stays moved.

Where the SoC has no SYSTIMER the Xtensa port generates the tick from the CPU's own CCOUNT/CCOMPARE pair, so the number of cycles in a tick is a cached constant that only describes the frequency it was computed at. ESP-IDF computes it once at boot and updates it nowhere this firmware reaches, so whoever changes the core clock owns it: without this call every tick-derived duration — delayMs, queue and semaphore timeouts, the task-watchdog period, the log timestamp — is wrong in real time by the ratio of the two frequencies, for as long as the clock stays there.

Which SoC family that applies to is the platform knowledge this facade exists to hold; when to call it is not. It is called from the one function that applies a core frequency, kleidos::platform::system::setCpuFrequencyMhz, with the frequency the silicon has just accepted — so no policy above that function can be the one that forgets, and a frequency that was refused never reaches it.

On a board built with ESP-IDF's power management (kleidos::platform::system::powerManagementBuilt: the idle floor, or automatic light sleep) ESP-IDF switches the clock instead (with the idle floor many times a second) and re-derives the period itself on every switch, rescaling the comparator already counting on both cores as well; that function then does not call this one. tickBaseCycles still reads the period back.

Parameters
NameDirectionMeaning
cpuMhzinCore frequency now in force, in MHz.
Return values
ValueMeaning
trueThe tick is CPU-derived on this SoC and the period was rewritten.
falseThe tick runs off a fixed timer and nothing needed doing, or cpuMhz does not convert (see tickBaseCyclesFor).

takeRecursiveMutex() #

bool kleidos::platform::rtos::takeRecursiveMutex(SemaphoreHandle handle, Ticks waitTicks = waitForever())

Lock a recursive mutex.

Parameters
NameMeaning
handleRecursive mutex handle.
waitTicksMaximum time to block.
Return values
ValueMeaning
trueRecursive mutex was locked.
falseTimeout elapsed before the mutex was available.

takeSemaphore() #

bool kleidos::platform::rtos::takeSemaphore(SemaphoreHandle handle, Ticks waitTicks = waitForever())

Take (wait for) a semaphore.

Parameters
NameMeaning
handleSemaphore or mutex handle.
waitTicksMaximum time to block.
Return values
ValueMeaning
trueSemaphore was taken before waitTicks elapsed.
falseTimeout elapsed before the semaphore was available.

taskCount() #

uint32_t kleidos::platform::rtos::taskCount()

Return the total number of tasks in the system.

Returns
Task count.

taskSnapshots() [1/2] #

uint32_t kleidos::platform::rtos::taskSnapshots(TaskSnapshot * out, uint32_t capacity, uint32_t & totalRuntime)

Capture a snapshot of all tasks into out.

The census is all-or-nothing: FreeRTOS's uxTaskGetSystemState fills the array only when it can hold every live task, and otherwise writes nothing and reports zero. A return of 0 with a non-zero taskCount() therefore means the census was truncated, not that the system has no tasks — callers must report that case distinctly instead of printing an empty table.

Parameters
NameMeaning
outDestination array of TaskSnapshot records.
capacityMaximum number of entries to write; effectively clamped to ::kMaxTaskSnapshots.
totalRuntimeSet to the total accumulated runtime counter; left at 0 when the census is truncated.
Returns
Number of entries written; 0 when the live task count exceeds the smaller of capacity and ::kMaxTaskSnapshots.
See also
taskCount

taskSnapshots() [2/2] #

template<size_t Capacity>
uint32_t kleidos::platform::rtos::taskSnapshots(TaskSnapshot(&) out[Capacity], uint32_t & totalRuntime)
inline

Capture task snapshots into a fixed-size array (capacity deduced).

Template Parameters
NameMeaning
CapacityCompile-time array capacity deduced from out; use ::kMaxTaskSnapshots so the array can hold a full census.
Parameters
NameMeaning
outFixed-size array of TaskSnapshot records.
totalRuntimeSet to the total accumulated runtime counter.
Returns
Number of entries written; 0 when the census was truncated.

taskSubscribeResultName() #

const char * kleidos::platform::watchdog::taskSubscribeResultName(TaskSubscribeResult result)

Return a human-readable name for a subscribe result.

Parameters
NameMeaning
resultEnum value to name.
Returns
Pointer to a static string.

taskWdtConfigured() #

bool kleidos::platform::watchdog::taskWdtConfigured()

Whether the task watchdog (TWDT) is compiled in and auto-initialized.

Reflects the CONFIG_ESP_TASK_WDT_INIT sdkconfig option: true when the bootloader starts the TWDT automatically. A read-only build-configuration query with no side effects.

Return values
ValueMeaning
trueTask watchdog is configured.
falseTask watchdog is disabled, or the native build.

tickBaseCycles() #

uint32_t kleidos::platform::rtos::tickBaseCycles()

Cycles the tick source counts per tick.

The readback that makes syncTickBase observable: on a CPU-derived tick this and the core frequency have to move together, and the debug console's clock snapshot prints them side by side — with the value they are required to agree on — so a board can be checked rather than assumed.

Returns
Cycles per tick, or ::kTickBaseCyclesUnknown where the tick is not CPU-derived and the count is therefore not a cycle count at all.

tickBaseCyclesFor() #

uint32_t kleidos::platform::rtos::tickBaseCyclesFor(uint32_t cpuMhz, uint32_t tickRateHz)
constexpr

Cycles one tick lasts at a core frequency.

Integer division, matching the tick interrupt: the comparator is advanced by a whole number of cycles, so a tick rate that does not divide the frequency exactly leaves the tick marginally short rather than accumulating a fraction. Every combination the boards use divides exactly — 80, 160 and 240 MHz against a 1 kHz tick give 80 000, 160 000 and 240 000 cycles.

Parameters
NameDirectionMeaning
cpuMhzinCore frequency in MHz.
tickRateHzinTick rate in Hz (configTICK_RATE_HZ on target).
Returns
Cycles per tick, or ::kTickBaseCyclesUnknown when either argument is zero or cpuMhz exceeds ::kMaxConvertibleCpuMhz.

tickCount() #

TickCount kleidos::platform::rtos::tickCount()

Return the current absolute tick timestamp.

Returns
Current TickCount value from xTaskGetTickCount().

tickRateHz() #

uint32_t kleidos::platform::rtos::tickRateHz()

Ticks the kernel counts in one second.

Returns
CONFIG_FREERTOS_HZ, the rate every tick-derived duration in this firmware is expressed against.

ticksFromMs() #

Ticks kleidos::platform::rtos::ticksFromMs(uint32_t ms)
constexpr

Convert a millisecond duration to RTOS ticks.

Parameters
NameDirectionMeaning
msinDuration in milliseconds.
Returns
Corresponding Ticks value.

waitForever() #

Ticks kleidos::platform::rtos::waitForever()
constexpr

Return an infinite-wait duration.

Returns
Ticks with sentinel value that causes the blocking call to wait forever (until an item becomes available or the task is deleted).

waitNotification() #

bool kleidos::platform::rtos::waitNotification(uint32_t clearOnEntry, uint32_t clearOnExit, uint32_t * value, Ticks waitTicks)

Block the calling task until a notification arrives.

Parameters
NameMeaning
clearOnEntryBits to clear in the notification value on entry.
clearOnExitBits to clear in the notification value on exit.
valueSet to the notification value when not nullptr.
waitTicksMaximum time to block.
Return values
ValueMeaning
trueA notification was received before waitTicks elapsed.
falseTimeout elapsed without a notification.

yield() #

void kleidos::platform::rtos::yield()

Hand the core to another ready task of the caller's priority, if one waits.

A task that keeps its core busy at a priority it shares with others (a load generator at kMinAppPriority, the loop task's own) calls this between stretches of work, so a task of its priority that became ready runs within one stretch rather than at the next tick's time slice. Returns at once when no such task is ready. It never lets a lower-priority task run: the core's idle task gets a turn only from a block (delayMs).

Back to the top

Variable Documentation

kMaxConvertibleCpuMhz #

uint32_t kleidos::platform::rtos::kMaxConvertibleCpuMhz
inlineconstexpr

Highest core frequency whose cycles-per-second still fits in a uint32_t. The top frequency of the boards is 240 MHz, so the bound is never approached; it exists so the multiplication cannot wrap for an argument nobody checked.

kMaxTaskSnapshots #

uint32_t kleidos::platform::rtos::kMaxTaskSnapshots
constexpr

Capacity of one task census: the largest snapshot this facade can take.

FreeRTOS fills a census array all-or-nothing, so this bound is shared by the facade's kernel-side scratch array and by every caller's destination array — declare caller arrays as TaskSnapshot[kMaxTaskSnapshots] so the two can never drift apart. Sized above the worst-case live task count (radio hosts, LittleFS, crypto/TOTP workers, logger, timers, idle tasks) with headroom.

kTickBaseCyclesUnknown #

uint32_t kleidos::platform::rtos::kTickBaseCyclesUnknown
inlineconstexpr

Reported where the tick is not counted in CPU cycles at all, and returned by tickBaseCyclesFor for an argument pair it cannot convert. Zero cycles per tick is not a frequency any caller could mean, so it is unambiguous.

Back to the top