Merge pull request #11297 from SteveCEvans/baro_state
[betaflight.git] / src / main / drivers / memprot_hal.c
blob07cfac5bdc3654720620489a2123fa36ccc22469
1 /*
2 * This file is part of Cleanflight and Betaflight.
4 * Cleanflight and Betaflight are free software. You can redistribute
5 * this software and/or modify this software under the terms of the
6 * GNU General Public License as published by the Free Software
7 * Foundation, either version 3 of the License, or (at your option)
8 * any later version.
10 * Cleanflight and Betaflight are distributed in the hope that they
11 * will be useful, but WITHOUT ANY WARRANTY; without even the implied
12 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 * See the GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this software.
18 * If not, see <http://www.gnu.org/licenses/>.
21 #include <string.h>
23 #include "platform.h"
25 #include "memprot.h"
27 static void memProtConfigError(void)
29 for (;;) {}
32 void memProtConfigure(mpuRegion_t *regions, unsigned regionCount)
34 MPU_Region_InitTypeDef MPU_InitStruct;
36 if (regionCount > MAX_MPU_REGIONS) {
37 memProtConfigError();
40 HAL_MPU_Disable();
42 // Setup common members
43 MPU_InitStruct.Enable = MPU_REGION_ENABLE;
44 MPU_InitStruct.SubRegionDisable = 0x00;
45 MPU_InitStruct.TypeExtField = MPU_TEX_LEVEL0;
47 for (unsigned number = 0; number < regionCount; number++) {
48 mpuRegion_t *region = &regions[number];
50 if (region->end == 0 && region->size == 0) {
51 memProtConfigError();
54 MPU_InitStruct.Number = number;
55 MPU_InitStruct.BaseAddress = region->start;
57 if (region->size) {
58 MPU_InitStruct.Size = region->size;
59 } else {
60 // Adjust start of the region to align with cache line size.
61 uint32_t start = region->start & ~0x1F;
62 uint32_t length = region->end - start;
64 if (length < 32) {
65 // This will also prevent flsl from returning negative (case length == 0)
66 length = 32;
69 int msbpos = flsl(length) - 1;
71 if (length != (1U << msbpos)) {
72 msbpos += 1;
75 MPU_InitStruct.Size = msbpos;
78 // Copy per region attributes
79 MPU_InitStruct.AccessPermission = region->perm;
80 MPU_InitStruct.DisableExec = region->exec;
81 MPU_InitStruct.IsShareable = region->shareable;
82 MPU_InitStruct.IsCacheable = region->cacheable;
83 MPU_InitStruct.IsBufferable = region->bufferable;
85 HAL_MPU_ConfigRegion(&MPU_InitStruct);
88 HAL_MPU_Enable(MPU_PRIVILEGED_DEFAULT);
91 void memProtReset(void)
93 MPU_Region_InitTypeDef MPU_InitStruct;
95 /* Disable the MPU */
96 HAL_MPU_Disable();
98 // Disable existing regions
100 for (uint8_t region = 0; region <= MAX_MPU_REGIONS; region++) {
101 MPU_InitStruct.Enable = MPU_REGION_DISABLE;
102 MPU_InitStruct.Number = region;
103 HAL_MPU_ConfigRegion(&MPU_InitStruct);
106 HAL_MPU_Enable(MPU_PRIVILEGED_DEFAULT);