Update cloud build defines (#14080)
[betaflight.git] / src / main / config / config_eeprom.c
blobf77586d3d8bfc9db8981d06d1e01f290cf80aa35
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 <stdbool.h>
22 #include <stdint.h>
23 #include <string.h>
25 #include "platform.h"
27 #include "build/build_config.h"
29 #include "common/crc.h"
30 #include "common/utils.h"
32 #include "config/config_eeprom.h"
33 #include "config/config_streamer.h"
34 #include "pg/pg.h"
35 #include "config/config.h"
37 #ifdef CONFIG_IN_SDCARD
38 #include "io/asyncfatfs/asyncfatfs.h"
39 #endif
41 #include "drivers/flash/flash.h"
42 #include "drivers/system.h"
44 static uint16_t eepromConfigSize;
46 typedef enum {
47 CR_CLASSICATION_SYSTEM = 0,
48 CR_CLASSICATION_PROFILE_LAST = CR_CLASSICATION_SYSTEM,
49 } configRecordFlags_e;
51 #define CR_CLASSIFICATION_MASK (0x3)
52 #define CRC_START_VALUE 0xFFFF
53 #define CRC_CHECK_VALUE 0x1D0F // pre-calculated value of CRC that includes the CRC itself
55 // Header for the saved copy.
56 typedef struct {
57 uint8_t eepromConfigVersion;
58 uint8_t magic_be; // magic number, should be 0xBE
59 } PG_PACKED configHeader_t;
61 // Header for each stored PG.
62 typedef struct {
63 // split up.
64 uint16_t size;
65 pgn_t pgn;
66 uint8_t version;
68 // lower 2 bits used to indicate system or profile number, see CR_CLASSIFICATION_MASK
69 uint8_t flags;
71 uint8_t pg[];
72 } PG_PACKED configRecord_t;
74 // Footer for the saved copy.
75 typedef struct {
76 uint16_t terminator;
77 } PG_PACKED configFooter_t;
78 // checksum is appended just after footer. It is not included in footer to make checksum calculation consistent
80 // Used to check the compiler packing at build time.
81 typedef struct {
82 uint8_t byte;
83 uint32_t word;
84 } PG_PACKED packingTest_t;
86 #if defined(CONFIG_IN_EXTERNAL_FLASH) || defined(CONFIG_IN_MEMORY_MAPPED_FLASH)
87 MMFLASH_CODE bool loadEEPROMFromExternalFlash(void)
89 const flashPartition_t *flashPartition = flashPartitionFindByType(FLASH_PARTITION_TYPE_CONFIG);
90 const flashGeometry_t *flashGeometry = flashGetGeometry();
92 uint32_t flashStartAddress = flashPartition->startSector * flashGeometry->sectorSize;
94 uint32_t totalBytesRead = 0;
95 int bytesRead = 0;
97 bool success = false;
98 #ifdef CONFIG_IN_MEMORY_MAPPED_FLASH
99 flashMemoryMappedModeDisable();
100 #endif
101 do {
102 bytesRead = flashReadBytes(flashStartAddress + totalBytesRead, &eepromData[totalBytesRead], EEPROM_SIZE - totalBytesRead);
103 if (bytesRead > 0) {
104 totalBytesRead += bytesRead;
105 success = (totalBytesRead == EEPROM_SIZE);
107 } while (!success && bytesRead > 0);
108 #ifdef CONFIG_IN_MEMORY_MAPPED_FLASH
109 flashMemoryMappedModeEnable();
110 #endif
112 return success;
115 #ifdef CONFIG_IN_MEMORY_MAPPED_FLASH
116 MMFLASH_CODE_NOINLINE void saveEEPROMToMemoryMappedFlash(void)
118 const flashPartition_t *flashPartition = flashPartitionFindByType(FLASH_PARTITION_TYPE_CONFIG);
119 const flashGeometry_t *flashGeometry = flashGetGeometry();
121 uint32_t flashSectorSize = flashGeometry->sectorSize;
122 uint32_t flashPageSize = flashGeometry->pageSize;
124 uint32_t flashStartAddress = flashPartition->startSector * flashGeometry->sectorSize;
126 uint32_t bytesRemaining = EEPROM_SIZE;
127 uint32_t offset = 0;
129 flashMemoryMappedModeDisable();
131 do {
132 uint32_t flashAddress = flashStartAddress + offset;
134 uint32_t bytesToWrite = bytesRemaining;
135 if (bytesToWrite > flashPageSize) {
136 bytesToWrite = flashPageSize;
139 bool onSectorBoundary = flashAddress % flashSectorSize == 0;
140 if (onSectorBoundary) {
141 flashEraseSector(flashAddress);
144 flashPageProgram(flashAddress, (uint8_t *)&eepromData[offset], bytesToWrite, NULL);
146 bytesRemaining -= bytesToWrite;
147 offset += bytesToWrite;
148 } while (bytesRemaining > 0);
150 flashWaitForReady();
152 flashMemoryMappedModeEnable();
154 #endif
156 #elif defined(CONFIG_IN_SDCARD)
158 enum {
159 FILE_STATE_NONE = 0,
160 FILE_STATE_BUSY = 1,
161 FILE_STATE_FAILED,
162 FILE_STATE_COMPLETE,
165 uint8_t fileState = FILE_STATE_NONE;
167 const char *defaultSDCardConfigFilename = "CONFIG.BIN";
169 void saveEEPROMToSDCardCloseContinue(void)
171 if (fileState != FILE_STATE_FAILED) {
172 fileState = FILE_STATE_COMPLETE;
176 void saveEEPROMToSDCardWriteContinue(afatfsFilePtr_t file)
178 if (!file) {
179 fileState = FILE_STATE_FAILED;
180 return;
183 uint32_t totalBytesWritten = 0;
184 uint32_t bytesWritten = 0;
185 bool success;
187 do {
188 bytesWritten = afatfs_fwrite(file, &eepromData[totalBytesWritten], EEPROM_SIZE - totalBytesWritten);
189 totalBytesWritten += bytesWritten;
190 success = (totalBytesWritten == EEPROM_SIZE);
192 afatfs_poll();
193 } while (!success && afatfs_getLastError() == AFATFS_ERROR_NONE);
195 if (!success) {
196 fileState = FILE_STATE_FAILED;
199 while (!afatfs_fclose(file, saveEEPROMToSDCardCloseContinue)) {
200 afatfs_poll();
204 bool saveEEPROMToSDCard(void)
206 fileState = FILE_STATE_BUSY;
207 bool result = afatfs_fopen(defaultSDCardConfigFilename, "w+", saveEEPROMToSDCardWriteContinue);
208 if (!result) {
209 return false;
212 while (fileState == FILE_STATE_BUSY) {
213 afatfs_poll();
216 while (!afatfs_flush()) {
217 afatfs_poll();
220 return (fileState == FILE_STATE_COMPLETE);
223 void loadEEPROMFromSDCardCloseContinue(void)
225 if (fileState != FILE_STATE_FAILED) {
226 fileState = FILE_STATE_COMPLETE;
230 void loadEEPROMFromSDCardReadContinue(afatfsFilePtr_t file)
232 if (!file) {
233 fileState = FILE_STATE_FAILED;
234 return;
237 fileState = FILE_STATE_BUSY;
239 uint32_t totalBytesRead = 0;
240 uint32_t bytesRead = 0;
241 bool success;
243 if (afatfs_feof(file)) {
244 // empty file, nothing to load.
245 memset(eepromData, 0x00, EEPROM_SIZE);
246 success = true;
247 } else {
249 do {
250 bytesRead = afatfs_fread(file, &eepromData[totalBytesRead], EEPROM_SIZE - totalBytesRead);
251 totalBytesRead += bytesRead;
252 success = (totalBytesRead == EEPROM_SIZE);
254 afatfs_poll();
255 } while (!success && afatfs_getLastError() == AFATFS_ERROR_NONE);
258 if (!success) {
259 fileState = FILE_STATE_FAILED;
262 while (!afatfs_fclose(file, loadEEPROMFromSDCardCloseContinue)) {
263 afatfs_poll();
266 return;
269 bool loadEEPROMFromSDCard(void)
271 fileState = FILE_STATE_BUSY;
272 // use "w+" mode here to ensure the file is created now - in w+ mode we can read and write and the seek position is 0 on existing files, ready for reading.
273 bool result = afatfs_fopen(defaultSDCardConfigFilename, "w+", loadEEPROMFromSDCardReadContinue);
274 if (!result) {
275 return false;
278 while (fileState == FILE_STATE_BUSY) {
279 afatfs_poll();
282 return (fileState == FILE_STATE_COMPLETE);
284 #endif
286 #ifdef CONFIG_IN_FILE
287 void loadEEPROMFromFile(void)
289 FLASH_Unlock(); // load existing config file into eepromData
291 #endif
293 void initEEPROM(void)
295 // Verify that this architecture packs as expected.
296 STATIC_ASSERT(offsetof(packingTest_t, byte) == 0, byte_packing_test_failed);
297 STATIC_ASSERT(offsetof(packingTest_t, word) == 1, word_packing_test_failed);
298 STATIC_ASSERT(sizeof(packingTest_t) == 5, overall_packing_test_failed);
300 STATIC_ASSERT(sizeof(configFooter_t) == 2, footer_size_failed);
301 STATIC_ASSERT(sizeof(configRecord_t) == 6, record_size_failed);
303 #if defined(CONFIG_IN_FILE)
304 loadEEPROMFromFile();
305 #elif defined(CONFIG_IN_EXTERNAL_FLASH) || defined(CONFIG_IN_MEMORY_MAPPED_FLASH)
306 bool eepromLoaded = loadEEPROMFromExternalFlash();
307 if (!eepromLoaded) {
308 // Flash read failed - just die now
309 failureMode(FAILURE_FLASH_READ_FAILED);
311 #elif defined(CONFIG_IN_SDCARD)
312 bool eepromLoaded = loadEEPROMFromSDCard();
313 if (!eepromLoaded) {
314 // SDCard read failed - just die now
315 failureMode(FAILURE_SDCARD_READ_FAILED);
317 #endif
320 bool isEEPROMVersionValid(void)
322 const uint8_t *p = &__config_start;
323 const configHeader_t *header = (const configHeader_t *)p;
325 if (header->eepromConfigVersion != EEPROM_CONF_VERSION) {
326 return false;
329 return true;
332 // Scan the EEPROM config. Returns true if the config is valid.
333 bool isEEPROMStructureValid(void)
335 const uint8_t *p = &__config_start;
336 const configHeader_t *header = (const configHeader_t *)p;
338 if (header->magic_be != 0xBE) {
339 return false;
342 uint16_t crc = CRC_START_VALUE;
343 crc = crc16_ccitt_update(crc, header, sizeof(*header));
344 p += sizeof(*header);
346 for (;;) {
347 const configRecord_t *record = (const configRecord_t *)p;
349 if (record->size == 0) {
350 // Found the end. Stop scanning.
351 break;
353 if (p + record->size >= &__config_end
354 || record->size < sizeof(*record)) {
355 // Too big or too small.
356 return false;
359 crc = crc16_ccitt_update(crc, p, record->size);
361 p += record->size;
364 const configFooter_t *footer = (const configFooter_t *)p;
365 crc = crc16_ccitt_update(crc, footer, sizeof(*footer));
366 p += sizeof(*footer);
368 // include stored CRC in the CRC calculation
369 const uint16_t *storedCrc = (const uint16_t *)p;
370 crc = crc16_ccitt_update(crc, storedCrc, sizeof(*storedCrc));
371 p += sizeof(storedCrc);
373 eepromConfigSize = p - &__config_start;
375 // CRC has the property that if the CRC itself is included in the calculation the resulting CRC will have constant value
376 return crc == CRC_CHECK_VALUE;
379 uint16_t getEEPROMConfigSize(void)
381 return eepromConfigSize;
384 size_t getEEPROMStorageSize(void)
386 #if defined(CONFIG_IN_EXTERNAL_FLASH) || defined(CONFIG_IN_MEMORY_MAPPED_FLASH)
388 const flashPartition_t *flashPartition = flashPartitionFindByType(FLASH_PARTITION_TYPE_CONFIG);
389 return FLASH_PARTITION_SECTOR_COUNT(flashPartition) * flashGetGeometry()->sectorSize;
390 #endif
391 #ifdef CONFIG_IN_RAM
392 return EEPROM_SIZE;
393 #else
394 return &__config_end - &__config_start;
395 #endif
398 // find config record for reg + classification (profile info) in EEPROM
399 // return NULL when record is not found
400 // this function assumes that EEPROM content is valid
401 static const configRecord_t *findEEPROM(const pgRegistry_t *reg, configRecordFlags_e classification)
403 const uint8_t *p = &__config_start;
404 p += sizeof(configHeader_t); // skip header
405 while (true) {
406 const configRecord_t *record = (const configRecord_t *)p;
407 if (record->size == 0
408 || p + record->size >= &__config_end
409 || record->size < sizeof(*record))
410 break;
411 if (pgN(reg) == record->pgn
412 && (record->flags & CR_CLASSIFICATION_MASK) == classification)
413 return record;
414 p += record->size;
416 // record not found
417 return NULL;
420 // Initialize all PG records from EEPROM.
421 // This functions processes all PGs sequentially, scanning EEPROM for each one. This is suboptimal,
422 // but each PG is loaded/initialized exactly once and in defined order.
423 bool loadEEPROM(void)
425 bool success = true;
427 PG_FOREACH(reg) {
428 const configRecord_t *rec = findEEPROM(reg, CR_CLASSICATION_SYSTEM);
429 if (rec) {
430 // config from EEPROM is available, use it to initialize PG. pgLoad will handle version mismatch
431 if (!pgLoad(reg, rec->pg, rec->size - offsetof(configRecord_t, pg), rec->version)) {
432 success = false;
434 } else {
435 pgReset(reg);
437 success = false;
439 *reg->fnv_hash = fnv_update(FNV_OFFSET_BASIS, reg->address, pgSize(reg));
442 return success;
445 static bool writeSettingsToEEPROM(void)
447 bool dirtyConfig = !isEEPROMVersionValid() || !isEEPROMStructureValid();
449 configHeader_t header = {
450 .eepromConfigVersion = EEPROM_CONF_VERSION,
451 .magic_be = 0xBE,
454 PG_FOREACH(reg) {
455 if (*reg->fnv_hash != fnv_update(FNV_OFFSET_BASIS, reg->address, pgSize(reg))) {
456 dirtyConfig = true;
460 // Only write the config if it has changed
461 if (dirtyConfig) {
462 config_streamer_t streamer;
463 config_streamer_init(&streamer);
465 config_streamer_start(&streamer, (uintptr_t)&__config_start, &__config_end - &__config_start);
467 config_streamer_write(&streamer, (uint8_t *)&header, sizeof(header));
468 uint16_t crc = CRC_START_VALUE;
469 crc = crc16_ccitt_update(crc, (uint8_t *)&header, sizeof(header));
470 PG_FOREACH(reg) {
471 const uint16_t regSize = pgSize(reg);
472 configRecord_t record = {
473 .size = sizeof(configRecord_t) + regSize,
474 .pgn = pgN(reg),
475 .version = pgVersion(reg),
476 .flags = 0,
479 record.flags |= CR_CLASSICATION_SYSTEM;
480 config_streamer_write(&streamer, (uint8_t *)&record, sizeof(record));
481 crc = crc16_ccitt_update(crc, (uint8_t *)&record, sizeof(record));
482 config_streamer_write(&streamer, reg->address, regSize);
483 crc = crc16_ccitt_update(crc, reg->address, regSize);
486 configFooter_t footer = {
487 .terminator = 0,
490 config_streamer_write(&streamer, (uint8_t *)&footer, sizeof(footer));
491 crc = crc16_ccitt_update(crc, (uint8_t *)&footer, sizeof(footer));
493 // include inverted CRC in big endian format in the CRC
494 const uint16_t invertedBigEndianCrc = ~(((crc & 0xFF) << 8) | (crc >> 8));
495 config_streamer_write(&streamer, (uint8_t *)&invertedBigEndianCrc, sizeof(crc));
497 config_streamer_flush(&streamer);
499 return (config_streamer_finish(&streamer) == 0);
500 } else {
501 return true;
505 void writeConfigToEEPROM(void)
507 bool success = false;
508 // write it
509 for (int attempt = 0; attempt < 3 && !success; attempt++) {
510 if (writeSettingsToEEPROM() && isEEPROMVersionValid() && isEEPROMStructureValid()) {
511 success = true;
513 #if defined(CONFIG_IN_EXTERNAL_FLASH) || defined(CONFIG_IN_MEMORY_MAPPED_FLASH)
514 // copy it back from flash to the in-memory buffer.
515 success = loadEEPROMFromExternalFlash();
516 #endif
517 #ifdef CONFIG_IN_SDCARD
518 // copy it back from flash to the in-memory buffer.
519 success = loadEEPROMFromSDCard();
520 #endif
524 if (success) {
525 return;
528 // Flash write failed - just die now
529 failureMode(FAILURE_CONFIG_STORE_FAILURE);