-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMPU.hpp
More file actions
587 lines (523 loc) · 22.4 KB
/
MPU.hpp
File metadata and controls
587 lines (523 loc) · 22.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
/*
* MPU.hpp
*
* Created on: 10 dic. 2025
* Author: Boris
*
* Memory Allocation Strategies:
* ==============================
* This system supports three distinct memory allocation methods that can coexist:
*
* 1. MANUAL ALLOCATION (via macros):
* Use D1_NC, D2_NC, D3_NC, D1_C, D2_C, D3_C macros for static/global variables.
* Example: D1_NC uint8_t my_buffer[100];
* Placed in: .mpu_ram_dX_nc.user or .ram_dX.user sections
*
* 2. NEW MPU SYSTEM (compile-time allocation):
* Use MPUDomain::Buffer<T> with compile-time buffer management.
* Automatically placed and sized by the Domain system.
* Placed in: .mpu_ram_dX_nc.buffer or .ram_dX.buffer sections
*
* 3. LEGACY MPUManager (runtime allocation):
* Use MPUManager::allocate_non_cached_memory() for dynamic allocation.
* Currently uses a 2KB pool in D3 non-cached memory.
* Placed in: .mpu_ram_d3_nc.legacy section
*
* These three methods are separated in the linker script to prevent overlap.
* All memory is properly configured by MPU regions as non-cached or cached.
*/
#ifndef MPU_HPP
#define MPU_HPP
#ifndef HALAL_MPUBUFFERS_MAX_INSTANCES // Define this in your build system if you need a different
// value
#define HALAL_MPUBUFFERS_MAX_INSTANCES 100
#endif
#include "C++Utilities/CppUtils.hpp"
#include "C++Utilities/CppImports.hpp"
#include "ErrorHandler/ErrorHandler.hpp"
#include "stm32h7xx_hal.h"
#include "HALAL/Models/MPUManager/MPUManager.hpp"
// Defines for attributes
// Note1: Variables declared with these attributes will likely not be initialized by the startup
// Note2: These attributes can only be used for static/global variables
#ifdef SIM_ON
#define D1_NC
#define D2_NC
#define D3_NC
#define D1_C
#define D2_C
#define D3_C
#define RAM_CODE
#else
#define D1_NC __attribute__((section(".mpu_ram_d1_nc.user")))
#define D2_NC __attribute__((section(".mpu_ram_d2_nc.user")))
#define D3_NC __attribute__((section(".mpu_ram_d3_nc.user")))
#define D1_C __attribute__((section(".ram_d1.user")))
#define D2_C __attribute__((section(".ram_d2.user")))
#define D3_C __attribute__((section(".ram_d3.user")))
// Define for RAM code
#define RAM_CODE __attribute__((section(".ram_code")))
#endif
// Memory Bank Symbols from Linker
extern "C" const char __itcm_base;
extern "C" const char __itcm_size;
extern "C" const char __dtcm_base;
extern "C" const char __dtcm_size;
extern "C" const char __flash_base;
extern "C" const char __flash_size;
extern "C" const char __ram_d1_base;
extern "C" const char __ram_d1_size;
extern "C" const char __ram_d2_base;
extern "C" const char __ram_d2_size;
extern "C" const char __ram_d3_base;
extern "C" const char __ram_d3_size;
extern "C" const char __peripheral_base;
extern "C" const char __peripheral_size;
// MPU Non-Cached Section Symbols from Linker
extern "C" const char __mpu_d1_nc_start;
extern "C" const char __mpu_d1_nc_end;
extern "C" const char __mpu_d2_nc_start;
extern "C" const char __mpu_d2_nc_end;
extern "C" const char __mpu_d3_nc_start;
extern "C" const char __mpu_d3_nc_end;
inline constexpr std::array<std::size_t, 6> mpu_supported_alignments = {32, 16, 8, 4, 2, 1};
consteval bool is_supported_mpu_alignment(std::size_t alignment) {
for (std::size_t candidate : mpu_supported_alignments) {
if (candidate == alignment) {
return true;
}
}
return false;
}
template <typename T>
concept mpu_buffer_request = requires(typename T::domain d) {
typename T::buffer_type;
{ T{} } -> std::same_as<T>;
};
// POD-like buffers that can safely live in static storage without custom destruction.
template <typename T>
concept mpu_buffer_payload = std::is_standard_layout_v<T> && std::is_trivially_destructible_v<T>;
extern void compile_error(const char* msg);
struct MPUDomain {
enum class MemoryDomain : uint8_t {
D1 = 1, // AXI SRAM (0x24000000)
D2 = 2, // SRAM 1/2/3 (0x30000000)
D3 = 3 // SRAM 4 (0x38000000)
};
enum class MemoryType : bool { Cached = true, NonCached = false };
// Buffer Request
struct Entry {
MemoryDomain memory_domain;
MemoryType memory_type;
std::size_t alignment;
std::size_t size_in_bytes;
};
// Buffer Request Wrapper
template <mpu_buffer_payload T> struct Buffer {
using domain = MPUDomain;
using buffer_type = T;
Entry e;
/**
* @brief Constructs a Buffer entry for a type T with explicit parameter.
* @tparam T The type for which the buffer is requested. Must be a POD type.
* @param type The memory type (Cached or NonCached).
* @param domain The memory domain where the buffer should be allocated (Defaults to D1,
* since it is the largest and fastest).
* @param force_cache_alignment If true, forces the buffer to be cache line aligned (32
* bytes, takes the rest as padding).
*/
consteval Buffer(
MemoryType type = MemoryType::NonCached,
MemoryDomain mem_domain = MemoryDomain::D1,
bool force_cache_alignment = false
)
: e{mem_domain, type, force_cache_alignment ? 32 : alignof(T), sizeof(T)} {
static_assert(
alignof(T) <= 32,
"Requested type has alignment greater than cache line size (32 bytes)."
);
static_assert(
is_supported_mpu_alignment(alignof(T)),
"Requested type has alignment not supported by MPU buffer system."
);
}
/**
* @brief Constructs a Buffer from an Entry struct (allows named parameter syntax).
* @param entry The Entry with all buffer requirements specified.
*/
consteval Buffer(Entry entry) : e(entry) {
if (entry.alignment > 32) {
compile_error("Requested alignment greater than cache line size (32 bytes).");
}
if (!is_supported_mpu_alignment(entry.alignment)) {
compile_error("Requested alignment not supported by MPU buffer system.");
}
// Verify size matches sizeof(T)
if (entry.size_in_bytes != sizeof(T)) {
compile_error("Entry size_in_bytes must match sizeof(T)");
}
}
template <class Ctx> consteval std::size_t inscribe(Ctx& ctx) const {
return ctx.template add<MPUDomain>(e, this);
}
};
static constexpr std::size_t max_instances = HALAL_MPUBUFFERS_MAX_INSTANCES;
struct Config {
uint32_t offset; // Offset relative to the start of the domain buffer
std::size_t size;
MemoryDomain domain;
MemoryType type;
};
// Helper to calculate sizes needed for static arrays
struct DomainSizes {
size_t d1_nc_total = 0;
size_t d1_c_total = 0;
size_t d2_nc_total = 0;
size_t d2_c_total = 0;
size_t d3_nc_total = 0;
size_t d3_c_total = 0;
};
static consteval uint32_t align_up(uint32_t val, size_t align) {
return (val + align - 1) & ~(align - 1); // Align up to 'align' leaving the minimum padding
}
static consteval DomainSizes calculate_total_sizes(std::span<const Config> configs) {
DomainSizes sizes;
for (const auto& cfg : configs) {
size_t end = cfg.offset + cfg.size;
if (cfg.domain == MemoryDomain::D1) {
if (cfg.type == MemoryType::NonCached)
sizes.d1_nc_total = std::max(sizes.d1_nc_total, end);
else
sizes.d1_c_total = std::max(sizes.d1_c_total, end);
} else if (cfg.domain == MemoryDomain::D2) {
if (cfg.type == MemoryType::NonCached)
sizes.d2_nc_total = std::max(sizes.d2_nc_total, end);
else
sizes.d2_c_total = std::max(sizes.d2_c_total, end);
} else if (cfg.domain == MemoryDomain::D3) {
if (cfg.type == MemoryType::NonCached)
sizes.d3_nc_total = std::max(sizes.d3_nc_total, end);
else
sizes.d3_c_total = std::max(sizes.d3_c_total, end);
}
}
// Align totals to 32 bytes, just in case
sizes.d1_nc_total = align_up(sizes.d1_nc_total, 32);
sizes.d1_c_total = align_up(sizes.d1_c_total, 32);
sizes.d2_nc_total = align_up(sizes.d2_nc_total, 32);
sizes.d2_c_total = align_up(sizes.d2_c_total, 32);
sizes.d3_nc_total = align_up(sizes.d3_nc_total, 32);
sizes.d3_c_total = align_up(sizes.d3_c_total, 32);
return sizes;
}
template <std::size_t N>
static consteval std::array<Config, N> build(std::span<const Entry> entries) {
if constexpr (N == 0) {
return {};
} else {
std::array<Config, N> cfgs{};
uint32_t offsets_nc[3] = {}; // D1, D2, D3
uint32_t offsets_c[3] = {}; // D1, D2, D3
uint32_t assigned_offsets[N];
for (size_t align : mpu_supported_alignments) {
for (size_t i = 0; i < N; i++) {
if (entries[i].alignment == align) {
size_t d_idx = static_cast<size_t>(entries[i].memory_domain) - 1;
if (entries[i].memory_type == MemoryType::NonCached) {
offsets_nc[d_idx] = align_up(offsets_nc[d_idx], align);
assigned_offsets[i] = offsets_nc[d_idx];
offsets_nc[d_idx] += entries[i].size_in_bytes;
} else {
offsets_c[d_idx] = align_up(offsets_c[d_idx], align);
assigned_offsets[i] = offsets_c[d_idx];
offsets_c[d_idx] += entries[i].size_in_bytes;
}
}
}
}
/* Build Configs */
for (std::size_t i = 0; i < N; i++) {
cfgs[i].size = entries[i].size_in_bytes;
cfgs[i].domain = entries[i].memory_domain;
cfgs[i].type = entries[i].memory_type;
cfgs[i].offset = assigned_offsets[i];
}
return cfgs;
}
}
struct Instance {
void* ptr;
std::size_t size;
template <auto& Target, typename... Args> auto& construct(Args&&... args) {
using Request = std::remove_cvref_t<decltype(Target)>;
static_assert(mpu_buffer_request<Request>, "Target must be a valid MPUDomain buffer");
using T = typename Request::buffer_type;
return *new (ptr) T(std::forward<Args>(args)...);
}
template <auto& Target> auto* as() {
using Request = std::remove_cvref_t<decltype(Target)>;
static_assert(mpu_buffer_request<Request>, "Target must be a valid MPUDomain buffer");
using T = typename Request::buffer_type;
return static_cast<T*>(ptr);
}
};
template <typename Board, auto& Target, typename... Args>
static auto& construct(Args&&... args) {
using Request = std::remove_cvref_t<decltype(Target)>;
static_assert(mpu_buffer_request<Request>, "Target must be a valid MPUDomain buffer");
return Board::template instance_of<Target>().template construct<Target>(
std::forward<Args>(args)...
);
}
template <typename Board, auto& Target> static auto* as() {
using Request = std::remove_cvref_t<decltype(Target)>;
static_assert(mpu_buffer_request<Request>, "Target must be a valid MPUDomain buffer");
return Board::template instance_of<Target>().template as<Target>();
}
template <std::size_t N, std::array<Config, N> cfgs> struct Init {
static inline std::array<Instance, N> instances{};
static constexpr auto Sizes = calculate_total_sizes(cfgs);
// Sections defined in Linker Script (aligned to 32 bytes just in case)
#ifdef SIM_ON
alignas(32
) static inline uint8_t d1_nc_buffer[Sizes.d1_nc_total > 0 ? Sizes.d1_nc_total : 1];
alignas(32) static inline uint8_t d1_c_buffer[Sizes.d1_c_total > 0 ? Sizes.d1_c_total : 1];
alignas(32
) static inline uint8_t d2_nc_buffer[Sizes.d2_nc_total > 0 ? Sizes.d2_nc_total : 1];
alignas(32) static inline uint8_t d2_c_buffer[Sizes.d2_c_total > 0 ? Sizes.d2_c_total : 1];
alignas(32
) static inline uint8_t d3_nc_buffer[Sizes.d3_nc_total > 0 ? Sizes.d3_nc_total : 1];
alignas(32) static inline uint8_t d3_c_buffer[Sizes.d3_c_total > 0 ? Sizes.d3_c_total : 1];
#else
__attribute__((section(".mpu_ram_d1_nc.buffer"))) alignas(32
) static inline uint8_t d1_nc_buffer[Sizes.d1_nc_total > 0 ? Sizes.d1_nc_total : 1];
__attribute__((section(".ram_d1.buffer"))) alignas(32
) static inline uint8_t d1_c_buffer[Sizes.d1_c_total > 0 ? Sizes.d1_c_total : 1];
__attribute__((section(".mpu_ram_d2_nc.buffer"))) alignas(32
) static inline uint8_t d2_nc_buffer[Sizes.d2_nc_total > 0 ? Sizes.d2_nc_total : 1];
__attribute__((section(".ram_d2.buffer"))) alignas(32
) static inline uint8_t d2_c_buffer[Sizes.d2_c_total > 0 ? Sizes.d2_c_total : 1];
__attribute__((section(".mpu_ram_d3_nc.buffer"))) alignas(32
) static inline uint8_t d3_nc_buffer[Sizes.d3_nc_total > 0 ? Sizes.d3_nc_total : 1];
__attribute__((section(".ram_d3.buffer"))) alignas(32
) static inline uint8_t d3_c_buffer[Sizes.d3_c_total > 0 ? Sizes.d3_c_total : 1];
#endif
static void init() {
HAL_MPU_Disable();
configure_static_regions();
// Dynamic Configuration based on Linker Symbols
configure_dynamic_region(
(uintptr_t)__mpu_d1_nc_start,
(uintptr_t)__mpu_d1_nc_end,
MPU_REGION_NUMBER3
);
configure_dynamic_region(
(uintptr_t)__mpu_d2_nc_start,
(uintptr_t)__mpu_d2_nc_end,
MPU_REGION_NUMBER5
);
configure_dynamic_region(
(uintptr_t)__mpu_d3_nc_start,
(uintptr_t)__mpu_d3_nc_end,
MPU_REGION_NUMBER7
);
// Assign pointers
uint8_t* bases_nc[3] = {&d1_nc_buffer[0], &d2_nc_buffer[0], &d3_nc_buffer[0]};
uint8_t* bases_c[3] = {&d1_c_buffer[0], &d2_c_buffer[0], &d3_c_buffer[0]};
for (std::size_t i = 0; i < N; i++) {
const auto& cfg = cfgs[i];
auto& inst = instances[i];
if (cfg.domain == MemoryDomain::D1 || cfg.domain == MemoryDomain::D2 ||
cfg.domain == MemoryDomain::D3) {
size_t d_idx = static_cast<size_t>(cfg.domain) - 1;
if (cfg.type == MemoryType::NonCached) {
inst.ptr = bases_nc[d_idx] + cfg.offset;
} else {
inst.ptr = bases_c[d_idx] + cfg.offset;
}
inst.size = cfg.size;
}
}
HAL_MPU_Enable(MPU_PRIVILEGED_DEFAULT);
SCB_EnableICache();
SCB_EnableDCache();
}
};
private:
static void configure_dynamic_region(uintptr_t start, uintptr_t end, uint8_t region_num) {
if (end <= start)
return;
// Dx NC (Normal, Non-Cacheable)
// TEX=1, C=0, B=0: Normal, Non-Cacheable
// Shareable since it can be accessed by multiple masters (CPU, DMA, etc)
configure_region(
start,
end - start,
region_num,
MPU_TEX_LEVEL1,
MPU_REGION_FULL_ACCESS,
MPU_INSTRUCTION_ACCESS_DISABLE,
MPU_ACCESS_SHAREABLE,
MPU_ACCESS_NOT_CACHEABLE,
MPU_ACCESS_NOT_BUFFERABLE
);
}
static void configure_static_regions() {
MPU_Region_InitTypeDef MPU_InitStruct = {0};
// Background (No Access) - Covers all memory not explicitly defined by a further region
// Doesn't use configure_region helper since that uses an uint32_t size, we need 4GB here...
MPU_InitStruct.Enable = MPU_REGION_ENABLE;
MPU_InitStruct.Number = MPU_REGION_NUMBER0;
MPU_InitStruct.BaseAddress = 0x00;
MPU_InitStruct.Size = MPU_REGION_SIZE_4GB;
MPU_InitStruct.SubRegionDisable = 0x00;
MPU_InitStruct.TypeExtField = MPU_TEX_LEVEL0;
MPU_InitStruct.AccessPermission = MPU_REGION_NO_ACCESS;
MPU_InitStruct.DisableExec = MPU_INSTRUCTION_ACCESS_DISABLE;
MPU_InitStruct.IsShareable = MPU_ACCESS_NOT_SHAREABLE;
MPU_InitStruct.IsCacheable = MPU_ACCESS_NOT_CACHEABLE;
MPU_InitStruct.IsBufferable = MPU_ACCESS_NOT_BUFFERABLE;
HAL_MPU_ConfigRegion(&MPU_InitStruct);
// Peripherals (Device, Buffered)
// Guarded against speculative execution and cache
configure_region(
reinterpret_cast<uintptr_t>(&__peripheral_base),
reinterpret_cast<size_t>(&__peripheral_size),
MPU_REGION_NUMBER8,
MPU_TEX_LEVEL0,
MPU_REGION_FULL_ACCESS,
MPU_INSTRUCTION_ACCESS_DISABLE,
MPU_ACCESS_SHAREABLE,
MPU_ACCESS_NOT_CACHEABLE,
MPU_ACCESS_BUFFERABLE
);
// Flash (Normal, Cacheable)
// TEX=0, C=1, B=0: Normal, Write-Through, No Read-Allocate (Read optimized)
// Not Shareable to allow full caching
configure_region(
reinterpret_cast<uintptr_t>(&__flash_base),
reinterpret_cast<size_t>(&__flash_size),
MPU_REGION_NUMBER1,
MPU_TEX_LEVEL0,
MPU_REGION_FULL_ACCESS,
MPU_INSTRUCTION_ACCESS_ENABLE,
MPU_ACCESS_NOT_SHAREABLE,
MPU_ACCESS_CACHEABLE,
MPU_ACCESS_NOT_BUFFERABLE
);
// DTCM (Normal, Cacheable)
// TEX=1, C=1, B=1: Normal, Write-Back, Write and Read Allocate
// TCMs are like Cache, so they are not really cacheable, and the MPU settings are ignored
configure_region(
reinterpret_cast<uintptr_t>(&__dtcm_base),
reinterpret_cast<size_t>(&__dtcm_size),
MPU_REGION_NUMBER10,
MPU_TEX_LEVEL1,
MPU_REGION_FULL_ACCESS,
MPU_INSTRUCTION_ACCESS_DISABLE,
MPU_ACCESS_NOT_SHAREABLE,
MPU_ACCESS_CACHEABLE,
MPU_ACCESS_BUFFERABLE
);
// ITCM (Normal, Cacheable)
// TEX=0, C=1, B=0: Normal, Write-Through, No Read-Allocate (Read optimized)
// TCMs are like Cache, so they are not really cacheable, and the MPU settings are ignored
configure_region(
reinterpret_cast<uintptr_t>(&__itcm_base),
reinterpret_cast<size_t>(&__itcm_size),
MPU_REGION_NUMBER11,
MPU_TEX_LEVEL0,
MPU_REGION_FULL_ACCESS,
MPU_INSTRUCTION_ACCESS_ENABLE,
MPU_ACCESS_NOT_SHAREABLE,
MPU_ACCESS_CACHEABLE,
MPU_ACCESS_NOT_BUFFERABLE
);
// D1 RAM Cached (Normal, WBWA)
// TEX=1, C=1, B=1: Normal, Write-Back, Write-Allocate
// Shareable since it can be accessed by multiple masters (CPU, DMA, etc)
configure_region(
reinterpret_cast<uintptr_t>(&__ram_d1_base),
reinterpret_cast<size_t>(&__ram_d1_size),
MPU_REGION_NUMBER2,
MPU_TEX_LEVEL1,
MPU_REGION_FULL_ACCESS,
MPU_INSTRUCTION_ACCESS_DISABLE,
MPU_ACCESS_SHAREABLE,
MPU_ACCESS_CACHEABLE,
MPU_ACCESS_BUFFERABLE
);
// D2 RAM Cached (Normal, WBWA)
// TEX=1, C=1, B=1: Normal, Write-Back, Write-Allocate
// Shareable since it can be accessed by multiple masters (CPU, DMA, etc)
configure_region(
reinterpret_cast<uintptr_t>(&__ram_d2_base),
reinterpret_cast<size_t>(&__ram_d2_size),
MPU_REGION_NUMBER4,
MPU_TEX_LEVEL1,
MPU_REGION_FULL_ACCESS,
MPU_INSTRUCTION_ACCESS_DISABLE,
MPU_ACCESS_SHAREABLE,
MPU_ACCESS_CACHEABLE,
MPU_ACCESS_BUFFERABLE
);
// D3 RAM Cached (Normal, WBWA)
// TEX=1, C=1, B=1: Normal, Write-Back, Write-Allocate
// Shareable since it can be accessed by multiple masters (CPU, DMA, etc)
configure_region(
reinterpret_cast<uintptr_t>(&__ram_d3_base),
reinterpret_cast<size_t>(&__ram_d3_size),
MPU_REGION_NUMBER6,
MPU_TEX_LEVEL1,
MPU_REGION_FULL_ACCESS,
MPU_INSTRUCTION_ACCESS_DISABLE,
MPU_ACCESS_SHAREABLE,
MPU_ACCESS_CACHEABLE,
MPU_ACCESS_BUFFERABLE
);
}
static void configure_region(
uintptr_t base,
size_t size,
uint8_t region_num,
uint8_t tex,
uint8_t access,
uint8_t no_exec,
uint8_t shareable,
uint8_t cacheable,
uint8_t bufferable
) {
if (size == 0)
return;
// Find smallest power of 2 >= size, starting at 32 bytes (MPU minimum)
// Enforce MPU minimum (32 bytes = 2^(4+1))
uint8_t mpu_size = 4;
if (size > 32) {
// Calculate ceil(log2(size)) - 1
// __builtin_clz(x) returns leading zeros. For 32, it's 26: 31 - 26 = 5
mpu_size = (sizeof(size) * 8 - 1) - __builtin_clz(size - 1);
}
// Calculate SubRegion Disable (SRD)
uint32_t sub_size = (1 << (mpu_size + 1)) / 8;
// Number of subregions needed to cover 'size'
uint8_t needed_subs = (size + sub_size - 1) / sub_size;
// We want first 'needed_subs' enabled (0), rest disabled (1)
uint8_t srd = 0xFF << needed_subs;
MPU_Region_InitTypeDef MPU_InitStruct = {0};
MPU_InitStruct.Enable = MPU_REGION_ENABLE;
MPU_InitStruct.Number = region_num;
MPU_InitStruct.BaseAddress = static_cast<decltype(MPU_InitStruct.BaseAddress)>(base
); // Should be uint32_t, but may be different when mocking, so this is just to make sure it
// accepts it
MPU_InitStruct.Size = mpu_size;
MPU_InitStruct.SubRegionDisable = srd;
MPU_InitStruct.TypeExtField = tex;
MPU_InitStruct.AccessPermission = access;
MPU_InitStruct.DisableExec = no_exec;
MPU_InitStruct.IsShareable = shareable;
MPU_InitStruct.IsCacheable = cacheable;
MPU_InitStruct.IsBufferable = bufferable;
HAL_MPU_ConfigRegion(&MPU_InitStruct);
}
};
#endif // MPU_HPP