SuperTinyKernel™ RTOS 1.08.x
Lightweight, high-performance, deterministic, bare-metal C++ RTOS for resource-constrained embedded systems. MIT Open Source License.
Loading...
Searching...
No Matches
blinky_mpu-trustzone-sc/example.cpp
Go to the documentation of this file.
1/*
2 * SuperTinyKernel(TM) RTOS: Lightweight High-Performance Deterministic C++ RTOS for Embedded Systems.
3 *
4 * Source: https://github.com/SuperTinyKernel-RTOS
5 *
6 * Copyright (c) 2022-2026 Neutron Code Limited <stk@neutroncode.com>. All Rights Reserved.
7 * License: MIT License, see LICENSE for a full text.
8 *
9 * -----------------------------------------------------------------------------------------------
10 * TrustZone + per-task MPU sandboxing example (Secure side).
11 *
12 * Builds on the plain TrustZone example: on top of the SAU split (Secure/Non-Secure/NSC), this
13 * adds a second, independent layer of defense using the Secure world's own MPU:
14 *
15 * 1. IPlatform::IEventOverrider::OnConfigureMpu() installs system-wide "background" regions
16 * (Flash: RO+exec, general RAM: RW+no-exec, and a Privileged-only "secrets" partition) that
17 * apply underneath every task's own regions -- so even a task with no GetMpuRegions() of its
18 * own gets sane W^X defaults, and nothing (Secure or Non-Secure, any privilege) can reach the
19 * secrets partition except Secure Privileged code.
20 *
21 * 2. SecureHwCommandQueueTask sandboxes *itself* to just its own HW command queue via
22 * ITask::GetMpuRegions() -- defense-in-depth: even though this Secure task is Privileged and
23 * could otherwise touch all of Secure RAM, a bug in its own Run() can't stray outside the
24 * queue it actually needs.
25 *
26 * 3. The existing PlatformEventHandler::OnException() (unchanged) is what reports any MemManage
27 * fault raised by either of the above -- e.g. from the Non-Secure side's deliberately-disabled
28 * TryBreakoutDemo() in example_ns_mpu.cpp -- including the MPU region table active at fault
29 * time, which now tells you exactly which region did (or didn't) permit the access.
30 *
31 * Required stk_config.h settings for this example:
32 * #define STK_MPU 1
33 * #define STK_MPU_STACK_GUARD 1
34 * #define STK_MPU_TASK_REGIONS 2
35 * -----------------------------------------------------------------------------------------------
36 */
37
43
44#include <setjmp.h>
45#include <stdio.h>
46#include <pico/runtime.h>
47#include <pico/stdio.h>
48#include <pico/unique_id.h>
49
50#include <stk.h>
51#include <time/stk_time.h>
52#include <sync/stk_sync.h>
53#include <arch/arm/cortex-m/stk_arch_arm-tz.h> // for Secure/Non-Secure-specific TrustZone API
54
55#include "example.h"
56
57#if (__ARM_FEATURE_CMSE & 1) == 0
58#error "Need ARMv8-M security extensions"
59#elif (__ARM_FEATURE_CMSE & 2) == 0
60#error "Compile with --mcmse"
61#endif
62
63#if !STK_MPU || !STK_MPU_STACK_GUARD
64#error "This example requires STK_MPU=1 and STK_MPU_STACK_GUARD=1 in stk_config.h"
65#endif
66
67// Size of the task's stack (number of stk::Word)
68// R2350 requires larger stack due to stack-memory heavy SDK API
69#ifdef _PICO_H
70static constexpr size_t TASK_STACK_SIZE = 1024U;
71#else
72static constexpr size_t TASK_STACK_SIZE = 256U;
73#endif
74
75// Tasks count.
76#define TASK_NS_COUNT (4U)
77#define TASK_S_COUNT (1U)
78#define TASK_COUNT (TASK_NS_COUNT + TASK_S_COUNT)
79
80// Kernel type.
81#define KERNEL_TYPE KERNEL_STATIC
82
83using namespace bsp;
84using namespace stk;
85
86// Allocate a global jump buffer in Secure memory.
87static jmp_buf s_NsExitEnv;
88
89// Counter located in a secure_data section.
90__attribute__((section(".secure_data"))) uint32_t s_Counter = 0U;
91
92// Hw commands.
93struct HwCommand
94{
95 enum EId
96 {
97 CMD_NONE = 0,
98 CMD_LED_ON = 1
99 };
100
101 EId id;
102 Word param_0;
103};
106
107// This is your NSC exit function.
109{
110 // Jump back to the point right before BLXNS happened,
111 // passing '1' as the return value for setjmp.
112 longjmp(s_NsExitEnv, 1);
113}
114
115// A demo function for exposing SDK functions to Non-Secure side of the binary.
116__stk_tz_nsc_entry void NSC_GetBoardUID(pico_unique_board_id_t *id_out)
117{
119}
120
121// A demo function for exposing some sensible data to Non-Secure side of the binary.
122__stk_tz_nsc_entry uint32_t NSC_GetKey(uint8_t key[], uint32_t size)
123{
124 uint32_t result = 0;
125
126 // Verify the entire buffer lies in Non-Secure memory and is writable
127 if (cmse_check_address_range(key, size, CMSE_NONSECURE | CMSE_MPU_READWRITE) != nullptr)
128 {
129 if (size == 4)
130 {
131 key[0] = 1;
132 key[1] = 2;
133 key[2] = 3;
134 key[3] = 4;
135
136 result = 4;
137 }
138 }
139
140 return result;
141}
142
143// A demo function for exposing some sensible data to Non-Secure state.
145{
146 // You can call hardware directly now, because execution is happening in a
147 // Secure world and Non-Secure task is Privileged.
149 {
151 }
152 else
153 {
154 // If Non-Secure task is not Privileged - direct hw calls are not possible, let Secure
155 // Privileged task handle all hw calls for such calling contexts.
156 s_HwCmdQueue.Write({ .id = HwCommand::CMD_LED_ON, led });
157 }
158}
159
160// Init mpu_shared_data: the Pico SDK's default linker script/runtime does not know
161// about STK's custom .stk_mpu_shared_data/.stk_mpu_shared_bss sections, so their
162// FLASH->RAM copy and zero-fill has to be done manually, and it must happen before
163// any C++ static constructor runs (globals living in those sections - like
164// g_TaskFlags and g_Timeline below - would otherwise be constructed on top of
165// uninitialized/stale memory).
166//
167// Two ways to guarantee that ordering are shown here; this example uses the second:
168// 1. __attribute__((constructor(101))) - 101 is the highest priority available to
169// user code, forcing the function to the very start of the __init_array loop
170// (kept below, commented out, for reference).
171// 2. PICO_RUNTIME_INIT_FUNC(..., "00100") - registers the function in the Pico
172// SDK's preinit_array section, which the SDK's runtime guarantees to run
173// before init_array (and therefore before any static constructor).
174//__attribute__((constructor(101)))
175static void InitMpuSharedData()
176{
177 extern char __stk_mpu_shared_data_start[];
178 extern char __stk_mpu_shared_data_end[];
179 extern char __stk_mpu_shared_data_source__[];
180 extern char __stk_mpu_shared_bss_start[];
181 extern char __stk_mpu_shared_bss_end[];
182
183 // copy initialized variables from FLASH to RAM
184 const size_t data_size = __stk_mpu_shared_data_end - __stk_mpu_shared_data_start;
185 if (data_size > 0)
186 {
187 STK_MEMCPY(__stk_mpu_shared_data_start, __stk_mpu_shared_data_source__, data_size);
188 }
189
190 // zero-fill the BSS region
191 const size_t bss_size = __stk_mpu_shared_bss_end - __stk_mpu_shared_bss_start;
192 if (bss_size > 0)
193 {
194 STK_MEMSET(__stk_mpu_shared_bss_start, 0, bss_size);
195 }
196}
198
199static void InitSecureData()
200{
201 extern char __secure_data_start[];
202 extern char __secure_data_end[];
203 extern char __secure_data_source__[];
204
205 // copy initialized variables from FLASH to RAM
206 const size_t data_size = __secure_data_end - __secure_data_start;
207 if (data_size > 0)
208 {
209 STK_MEMCPY(__secure_data_start, __secure_data_source__, data_size);
210 }
211}
213
214static void Configure_SAU(void)
215{
216 extern char __nsc_start[]; // = ORIGIN(FLASH_NSC)
217 extern char __nsc_end[]; // = ORIGIN(FLASH_NSC) + LENGTH(FLASH_NSC)
218 extern char __ns_ram_start[]; // = ORIGIN(RAM_NS)
219 //extern char __ns_ram_end[]; // = ORIGIN(RAM_NS) + LENGTH(RAM_NS)
220 extern char __ns_flash_start[]; // = __nsc_end
221 extern char __ns_flash_end[]; // = ORIGIN(FLASH_NS) + LENGTH(FLASH_NS)
222 extern char __ns_scratch_start[]; // = ORIGIN = 0x2007E000
223 extern char __ns_scratch_end[]; // = ORIGIN = 0x2007F000
224
225 // Disable SAU while programming regions.
226 SAU->CTRL = 0U;
227
228 // Region 0: NSC Gateway.
229 SAU->RNR = 0U;
230 SAU->RBAR = (uintptr_t)__nsc_start;
231 SAU->RLAR = (((uintptr_t)__nsc_end - 1U) & ~0x1FU) | 2U | 1U; // NSC + ENABLE
232
233 // Region 1: Non-Secure Flash (code + vector table).
234 SAU->RNR = 1U;
235 SAU->RBAR = (uintptr_t)__ns_flash_start;
236 SAU->RLAR = (((uintptr_t)__ns_flash_end - 1U) & ~0x1FU) | 0U | 1U; // NS + ENABLE
237
238 // Region 2: Non-Secure RAM (TASK STACKS ONLY).
239 SAU->RNR = 2U;
240 SAU->RBAR = (uintptr_t)__ns_ram_start; // 0x20040000
241 SAU->RLAR = (((uintptr_t)__ns_scratch_start - 1U) & ~0x1FU) | 0U | 1U; // NS + ENABLE
242
243 // Region 3: SCRATCH RAM (core stacks / special buffers).
244 SAU->RNR = 3U;
245 SAU->RBAR = (uintptr_t)__ns_scratch_start;
246 SAU->RLAR = (((uintptr_t)__ns_scratch_end - 1U) & ~0x1FU) | 0U | 1U; // NS + ENABLE
247
248 // Clear remaining SAU regions.
249 for (uint32_t i = 4U; i < 8U; ++i)
250 {
251 SAU->RNR = i;
252 SAU->RBAR = 0U;
253 SAU->RLAR = 0U;
254 }
255
256 // Enable SAU (default = Secure).
257 SAU->CTRL = 1U;
258
259 __DSB();
260 __ISB();
261}
262
264{
265 // Enable secure fault reporting.
266 SCB->SHCSR |= SCB_SHCSR_SECUREFAULTENA_Msk |
267 SCB_SHCSR_BUSFAULTENA_Msk |
268 SCB_SHCSR_USGFAULTENA_Msk |
269 SCB_SHCSR_MEMFAULTENA_Msk;
270
271 // 1. Configure SAU boundaries before any peripheral writes.
273
274 // 2. Do other initializations...
275}
276
278{
279 typedef __stk_tz_ns_call void (* NSFuncT)(void);
280
281 extern char __ns_flash_start[]; // = __nsc_end
282
283 // 1. Init PSP to 0.
284 __TZ_set_PSP_NS(0);
285 __set_PSP(0);
286
287 // 2. Read the initial Stack Pointer dynamically from Word 0 of the NS vector table
288 // (Instead of hardcoding to the start of RAM, this ensures it uses the stack top your NS app expects)
289 uint32_t *ns_vector_table = reinterpret_cast<uint32_t *>(__ns_flash_start);
290 uint32_t initial_msp_ns = ns_vector_table[0];
291 __TZ_set_MSP_NS(initial_msp_ns);
292
293 // 3. Point the NON-SECURE VTOR to the Non-Secure vector table
294 SCB_NS->VTOR = reinterpret_cast<uintptr_t>(__ns_flash_start);
295 __DSB();
296 __ISB();
297
298 // 4. Extract the Reset Handler address (Word 1 of the NS vector table)
299 uint32_t reset_handler_address = ns_vector_table[1];
300
301 // 5. Clear Bit 0 (LSB): required by BLXNS — signals Secure-to-NonSecure transition.
302 // The vector table stores Thumb addresses (LSB=1), but BLXNS needs LSB=0.
303 NSFuncT ResetHandler_ns = reinterpret_cast<NSFuncT>(reset_handler_address & ~1UL);
304
305 // Save the current Secure CPU state.
306 // The first time setjmp executes, it returns 0.
307 if (setjmp(s_NsExitEnv) == 0)
308 {
309 // 6. Jump into the Non-Secure World.
310 ResetHandler_ns();
311 }
312 else
313 {
314 // --- WE ARE BACK IN SECURE MODE PERMANENTLY ---
315
316 // The Non-Secure binary called NSC_Secure_HandleNSExit(), which triggered longjmp(),
317 // bypassing the standard C function return mechanism.
318
319 // Continue your Secure-only main loop or application logic here.
320
321 // Reset PSP_NS.
322 __TZ_set_PSP_NS(0);
323 }
324}
325
326// Secure task's core.
327template <stk::EAccessMode _AccessMode>
328class SecureHwCommandQueueTask : public stk::Task<TASK_STACK_SIZE, _AccessMode>
329{
330 void Run() override
331 {
332 while (true)
333 {
334 HwCommand cmd;
335 if (s_HwCmdQueue.Read(cmd))
336 {
337 switch (cmd.id)
338 {
341 ++s_Counter;
342 break; }
343 default:
344 STK_ASSERT(false);
345 break;
346 }
347 }
348 }
349 }
350};
351
353{
354 const stk::MpuConfig *OnConfigureMpu() const override
355 {
356 using namespace stk;
357
358 // RP2350 memory map constants. Adjust FLASH_SIZE_BYTES / SRAM_SIZE_BYTES to
359 // match your exact board/flash chip if it differs from the Pico 2 default.
360 // MPU region sizes must be a power of two, so pick the next power-of-two
361 // that covers your actual flash/RAM size when changing these.
362 enum EMemPartition : uint32_t
363 {
364 // Reserved for a future revision that maps the BOOTROM window as a global
365 // region (see Region 5 note above) - not yet referenced by mpu_table below.
366 BOOTROM_BASE_ADDR = 0x00000000UL,
367 BOOTROM_SIZE = 32 * 1024, // 32 KB internal boot ROM
368
369 FLASH_BASE_ADDR = 0x10000000UL, // start of external QSPI flash (XIP window)
370 FLASH_SIZE_BYTES = 4 * 1024 * 1024, // 4 MB -> matches Pico 2 / RP2350 default flash
371
372 SRAM_BASE_ADDR = 0x20000000UL,
373 SRAM_SIZE_BYTES = 512 * 1024, // 512 KB on-chip SRAM (banks 0-9 + scratch X/Y)
374 };
375
376 extern char __stk_mpu_shared_code_start[];
377 extern char __stk_mpu_shared_code_end[];
378 extern char __stk_mpu_shared_data_start[];
379 extern char __stk_mpu_shared_data_end[];
380 extern char __stk_mpu_shared_bss_start[];
381 extern char __stk_mpu_shared_bss_end[];
382
383 // Pico SDK places __aeabi_ldivmod, __aeabi_uldivmod, __aeabi_idiv0 into RAM for a
384 // faster execution. We must allow this memory region for access by non-priviliged
385 // tasks to support basic math operations.
386 extern char __stk_mpu_ram_text_start[];
387 extern char __stk_mpu_ram_text_end[];
388
389 // Convert pointers once to avoid long calculations in the table
390 const Word shared_code_start = hw::PtrToWord(__stk_mpu_shared_code_start);
391 const Word shared_code_end = hw::PtrToWord(__stk_mpu_shared_code_end);
392 const Word flash_end = FLASH_BASE_ADDR + FLASH_SIZE_BYTES;
393
394 const Word ram_text_start = hw::PtrToWord(__stk_mpu_ram_text_start);
395 const Word ram_text_end = hw::PtrToWord(__stk_mpu_ram_text_end);
396 const size_t ram_text_size = stk::Align<size_t>(static_cast<size_t>(ram_text_end - ram_text_start), 32U);
397
398 // Static region table mapped to RP2350 hardware layout without overlapping windows.
399 // Table position == hardware region index (entry 0 -> region 0, etc).
400 static const stk::MpuRegionConfig mpu_table[] =
401 {
402 { // REGION 0: LOWER FLASH - Everything from start up to the shared code window
403 .addr = FLASH_BASE_ADDR,
404 .size = shared_code_start - FLASH_BASE_ADDR,
405 .access_perm = hw::mpu::ACCESS_PRIV_RO_USER_RO,
406 .mem_type = hw::mpu::TYPE_NORMAL_CACHEABLE,
407 .share = hw::mpu::SHARE_NON,
408 .exec = hw::mpu::EXEC_ALLOWED
409 },
410 { // REGION 1: UPPER FLASH - Everything after the shared code window to the end of Flash
411 .addr = shared_code_end,
412 .size = flash_end - shared_code_end,
413 .access_perm = hw::mpu::ACCESS_PRIV_RO_USER_RO,
414 .mem_type = hw::mpu::TYPE_NORMAL_CACHEABLE,
415 .share = hw::mpu::SHARE_NON,
416 .exec = hw::mpu::EXEC_ALLOWED
417 },
418 { // REGION 2: SHARED CODE WINDOW - Explicitly mapped with user execution permissions
419 .addr = shared_code_start,
420 .size = shared_code_end - shared_code_start,
421 .access_perm = hw::mpu::ACCESS_PRIV_RO_USER_RO,
422 .mem_type = hw::mpu::TYPE_NORMAL_CACHEABLE,
423 .share = hw::mpu::SHARE_NON,
424 .exec = hw::mpu::EXEC_ALLOWED
425 },
426 { // REGION 3: RAM DATA / BSS WINDOW
427 .addr = hw::PtrToWord(__stk_mpu_shared_data_start),
428 .size = hw::PtrToWord(__stk_mpu_shared_bss_end) - hw::PtrToWord(__stk_mpu_shared_data_start),
429 .access_perm = hw::mpu::ACCESS_FULL,
430 .mem_type = hw::mpu::TYPE_NORMAL_CACHEABLE,
431 .share = hw::mpu::SHARE_NON,
432 .exec = hw::mpu::EXEC_NEVER
433 },
434 { // REGION 4: RAM TEXT WINDOW - Pico SDK division routines, RO+exec for every task
435 .addr = ram_text_start,
436 .size = ram_text_size,
437 .access_perm = hw::mpu::ACCESS_PRIV_RO_USER_RO,
438 .mem_type = hw::mpu::TYPE_NORMAL_CACHEABLE,
439 .share = hw::mpu::SHARE_NON,
440 .exec = hw::mpu::EXEC_ALLOWED
441 }
442
443 // Region 5 is left unconfigured here on purpose: ConfigureTable() disables
444 // any static-region slot beyond out_count automatically, so it's already
445 // free for future use without a placeholder entry.
446 };
447
448 STK_UNUSED(__stk_mpu_shared_data_end);
449 STK_UNUSED(__stk_mpu_shared_bss_start);
450
451 // set MPU regions and notify driver that we want to enable MPU
452 static const stk::MpuConfig mpu_config
453 (
454 stk::MpuRegionList(mpu_table, STK_STATIC_ARRAY_SIZE(mpu_table)),
455 (hw::mpu::MPU_CFG_PRIVILEGED_BG_MEM |
456 hw::mpu::MPU_CFG_CLEAR_ON_INIT)
457 );
458
459 return &mpu_config;
460 }
461
462#if STK_MPU
463 static void PrintMpuConfig(const char *label, const stk::FaultContext::Mpu &mpu)
464 {
465 printf("--- %s MPU Status & Config ---\r\n", label);
466 printf("CTRL: 0x%08X\r\n", (unsigned int)mpu.CTRL);
467 #if STK_ARCH_ARMV8_M
468 printf("MAIR0: 0x%08X MAIR1: 0x%08X\r\n", (unsigned int)mpu.MAIR0, (unsigned int)mpu.MAIR1);
469 #endif
470
471 printf("--- %s MPU Regions Configuration ---\r\n", label);
472 for (size_t i = 0U; i < STK_STATIC_ARRAY_SIZE(mpu.regions); i++)
473 {
474 printf(" Region %u -> RBAR: 0x%08X R%s: 0x%08X\r\n",
475 (unsigned int)i,
476 (unsigned int)mpu.regions[i].RBAR,
477 STK_ARCH_ARMV8_M ? "LAR" : "ASR",
478 (unsigned int)mpu.regions[i].ATTR);
479 }
480 }
481#endif
482
483 // Kernel-invoked fault handler: fires on MemManage faults (e.g. the Non-Secure LED
484 // tasks touching g_SecureCounter, or a stack-guard violation) and on generic hard
485 // faults. Dumps CPU/MPU state for diagnostics and halts via a debug breakpoint -
486 // this is intentionally non-recoverable diagnostic code, not a fault-recovery example.
487#ifdef DEBUG
488 bool OnException(stk::EHwException exc_id, stk::TId tid, const struct stk::FaultContext *const ctx) override
489 {
490 if (exc_id == stk::HW_EXCEPT_MEMACCESS)
491 {
492 printf("\r\n================ MEMMANAGE FAULT DETECTED ================\r\n");
493 printf("(Sandbox Violation: a task's Run() reached outside the MPU\r\n");
494 printf(" regions granted to it - see region dump below for what\r\n");
495 printf(" WAS active for this task at fault time)\r\n");
496 }
497 else
498 {
499 printf("\r\n================== HARD FAULT DETECTED ===================\r\n");
500 }
501
502 printf("ITask *: 0x%08X:\r\n", (unsigned int)tid);
503
504 printf("EXC_RETURN: 0x%08X\r\n\r\n", (unsigned int)ctx->EXC_RETURN);
505
506 printf("--- Stacked CPU Registers ---\r\n");
507 printf("R0: 0x%08X R1: 0x%08X R2: 0x%08X\r\n", (unsigned int)ctx->frame.R0, (unsigned int)ctx->frame.R1, (unsigned int)ctx->frame.R2);
508 printf("R3: 0x%08X R12: 0x%08X LR: 0x%08X\r\n", (unsigned int)ctx->frame.R3, (unsigned int)ctx->frame.R12, (unsigned int)ctx->frame.LR);
509 printf("PC: 0x%08X xPSR: 0x%08X\r\n\r\n", (unsigned int)ctx->frame.PC, (unsigned int)ctx->frame.xPSR);
510
511 printf("--- System Control Registers ---\r\n");
512 printf("CFSR: 0x%08X HFSR: 0x%08X AFSR: 0x%08X\r\n", (unsigned int)ctx->CFSR, (unsigned int)ctx->HFSR, (unsigned int)ctx->AFSR);
513 printf("MMFAR: 0x%08X (%s)\r\n", (unsigned int)ctx->MMFAR, ctx->mmfar_valid ? "VALID" : "INVALID");
514 printf("BFAR: 0x%08X (%s)\r\n\r\n", (unsigned int)ctx->BFAR, ctx->bfar_valid ? "VALID" : "INVALID");
515 printf("CONTROL: 0x%08X (nPRIV=%u)\r\n", (unsigned int)ctx->CONTROL, (unsigned int)(ctx->CONTROL & 1U));
516
517#if STK_MPU
518 PrintMpuConfig((STK_ARCH_ARMV8_M && STK_TZ_SECURE) ? "Secure" : "Primary", ctx->mpu);
519
520 #if STK_ARCH_ARMV8_M && STK_TZ_SECURE
521 printf("\r\n");
522 PrintMpuConfig("Non-Secure", ctx->mpu_ns);
523 #endif
524#endif
525
526 printf("=====================================================\r\n");
527
529 return false; // allow default handling by the platform driver
530 }
531#endif // DEBUG
532};
533
534static void CreateKernel()
535{
536 Led::InitAll(false);
537
538 // Operating in Static + Sync mode (EventFlags requires KERNEL_SYNC) and optionally tickless.
539 const uint8_t KernelMode = KERNEL_TYPE | KERNEL_SYNC | (STK_TICKLESS_IDLE ? KERNEL_TICKLESS : 0);
540
541 // Allocate scheduling kernel for 3 threads (tasks) with Round-Robin scheduling strategy.
543
544 // for MPU configuration and MemFault/HardFault exceptions processing (also supplies the
545 // system-wide background MPU regions via OnConfigureMpu(), see above).
546 static PlatformEventHandler event_overrider;
547 kernel.GetPlatform()->SetEventOverrider(&event_overrider);
548
549 // Init scheduling kernel.
550 kernel.Initialize();
551
552 // Register kernel instance with TrustZone interface.
553 tz::sec::SetKernel(0, &kernel);
554
555 // Add Secure tasks:
557 kernel.AddTask(&hw_cmd_task);
558}
559
561{
562 // For semihosting and logging to console.
563#ifdef DEBUG
564 stdio_init_all();
565#endif
566
567 // Init BSP.
568 Led::InitAll(false);
569
570 // Configure Secure state by partitioning FLASH and RAM via SAU. STK does not wrap this functionality
571 // to give more freedom and be less noisy in its API.
573
574 // Create scheduler and add Secure tasks.
575 CreateKernel();
576
577 // Invoke Non-Secure state which will drive logic further.
579
580 // CPU is now executing your Non-Secure application, execution will never return here.
581 while (true)
582 {
583 // KERNEL_STATIC does not support exit from scheduling, while it is possible with KERNEL_DYNAMIC
584 // when all tasks exit on both sides Non-secure and Secure.
585 #if (KERNEL_TYPE == KERNEL_STATIC)
586 STK_ASSERT(false);
587 #endif
588 }
589}
#define __stk_tz_ns_call
ARM TrustZone: attribute for calling Non-Secure functions from Secure state.
#define __stk_tz_nsc_entry
ARM TrustZone: attribute for Non-Secure callable gateway functions.
#define STK_ARCH_ARMV8_M
ARMv8-M platform (Cortex-M23, Cortex-M33, Cortex-M55, Cortex-M85).
Top-level STK include. Provides the Kernel class template and all built-in task-switching strategies.
#define STK_MPU_SHARED_DATA_SECTION
Definition stk_arch.h:158
#define STK_UNUSED(X)
Explicitly marks a variable as unused to suppress compiler warnings.
Definition stk_defs.h:715
#define __stk_aligned(x)
Specifies minimum alignment in bytes for the decorated variable or struct member (data instance prefi...
Definition stk_defs.h:282
#define STK_TZ_SECURE
ARM TrustZone: Defines Secure (1) build.
Definition stk_defs.h:180
#define STK_ASSERT(e)
Runtime assertion. Halts execution if the expression e evaluates to false.
Definition stk_defs.h:532
static void __stk_debug_break()
Definition stk_defs.h:495
#define STK_STATIC_ARRAY_SIZE(ARRAY)
Get size of the static array.
Definition stk_defs.h:742
Collection of synchronization primitives (stk::sync namespace).
Collection of time-related primitives (stk::time namespace).
Namespace of STK package.
uintptr_t Word
Native processor word type.
Definition stk_common.h:206
void STK_MEMCPY(void *const dest, const void *const src, size_t size)
Implementation of STK_MEMCPY.
Definition stk_arch.h:788
void STK_MEMSET(void *const dest, uint8_t value, size_t size)
Implementation of STK_MEMSET.
Definition stk_arch.h:823
constexpr T Align(T v, T align) noexcept
Aligns a value towards the next larger size multiple.
Definition stk_defs.h:764
EHwException
Hardware exception id (see IPlatform::IEventOverrider::OnException).
Definition stk_common.h:194
@ HW_EXCEPT_MEMACCESS
MemManage on ARM / Page Fault or PMP violation on RISC-V.
Definition stk_common.h:196
Word TId
Task (thread) id.
Definition stk_common.h:211
@ KERNEL_TICKLESS
Tickless mode. To use this mode STK_TICKLESS_IDLE must be defined to 1 in stk_config....
Definition stk_common.h:51
@ KERNEL_SYNC
Synchronization support (see Event).
Definition stk_common.h:50
bool IsPrivilegedContext()
Check if caller context is Privileged.
static Word PtrToWord(T *const ptr) noexcept
Cast a pointer to a CPU register-width integer.
Definition stk_arch.h:215
Definition cpu.h:17
Word BFAR
BusFault Address Register (BFAR).
Word AFSR
Auxiliary Fault Status Register (AFSR).
Word HFSR
HardFault Status Register (HFSR).
hw::ExceptionFrame frame
Saved hardware exception stack frame.
Word MMFAR
Memory Management Fault Address Register (MMFAR).
Word CFSR
Configurable Fault Status Register (CFSR: MemManage, BusFault, UsageFault).
Word CONTROL
Core CONTROL register state snapshot.
bool mmfar_valid
Flag indicating validity of MMFAR address value (derived from CFSR.MMARVALID).
Word EXC_RETURN
Exception return magic value (EXC_RETURN).
bool bfar_valid
Flag indicating validity of BFAR address value (derived from CFSR.BFARVALID).
Hardware Memory Protection Unit (MPU) status register snapshot.
Region regions[(8U)]
Active hardware MPU region register state table.
Word CTRL
MPU Control Register (MPU_CTRL).
Word ATTR
Region Attribute and Size Register (RASR / RLAR / MPU_RLAR).
Word RBAR
Region Base Address Register (RBAR).
Concrete implementation of IKernel.
Definition stk.h:102
EAddResult AddTask(ITask *user_task) override
Register task for a soft real-time (SRT) scheduling.
Definition stk.h:1465
IPlatform * GetPlatform() override
Get platform driver instance owned by this kernel.
Definition stk.h:2034
void Initialize(uint32_t resolution_us=PERIODICITY_DEFAULT) override
Initialize kernel.
Definition stk.h:1425
virtual void SetEventOverrider(IEventOverrider *overrider, bool non_secure=false)=0
Set platform event overrider.
Interface for a platform event overrider.
Partial implementation of the user task.
Definition stk_helper.h:98
Thread-safe, type-safe FIFO communication pipe with internal storage.
void Run() override
Entry point of the user task.
bool OnException(stk::EHwException exc_id, stk::TId tid, const struct stk::FaultContext *const ctx) override
const stk::MpuConfig * OnConfigureMpu() const override
LedId Id
Definition led.h:32
static void InitAll(bool init_state)
Definition led.h:40
static void SwitchOnExclusive(Id led)
Definition led.h:48
void pico_get_unique_board_id(pico_unique_board_id_t *id_out)
static jmp_buf s_NsExitEnv
#define KERNEL_TYPE
static sync::PipeT< HwCommand, 4 > s_HwCmdQueue
static void InitMpuSharedData()
static void InitMpuSharedData()
__stk_tz_nsc_entry uint32_t NSC_GetKey(uint8_t key[], uint32_t size)
PICO_RUNTIME_INIT_FUNC(InitMpuSharedData, "00100")
static void CreateKernel()
__stk_tz_nsc_entry void NSC_GetBoardUID(pico_unique_board_id_t *id_out)
static void InvokeNonSecureState()
static void Configure_SAU(void)
__stk_tz_nsc_entry void NSC_OnExitNs(void)
__attribute__((section(".secure_data"))) uint32_t s_Counter=0U
static void InitSecureData()
static void ConfigureSecureState()
__stk_tz_nsc_entry void NSC_bsp_Led_SwitchOnExclusive(bsp::Led::Id led)
static STK_MPU_SHARED_DATA_SECTION stk::sync::PipeT< HwCommand, 4 > s_HwCmdQueue
#define TASK_STACK_SIZE