Merge pull request #11494 from haslinghuis/dshot_gpio
[betaflight.git] / src / main / config / config_eeprom.c
blob4f4055a4bb44778b757e438252db30f9c16ae14c
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.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)
87 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;
99 do {
100 bytesRead = flashReadBytes(flashStartAddress + totalBytesRead, &eepromData[totalBytesRead], EEPROM_SIZE - totalBytesRead);
101 if (bytesRead > 0) {
102 totalBytesRead += bytesRead;
103 success = (totalBytesRead == EEPROM_SIZE);
105 } while (!success && bytesRead > 0);
107 return success;
109 #elif defined(CONFIG_IN_SDCARD)
111 enum {
112 FILE_STATE_NONE = 0,
113 FILE_STATE_BUSY = 1,
114 FILE_STATE_FAILED,
115 FILE_STATE_COMPLETE,
118 uint8_t fileState = FILE_STATE_NONE;
120 const char *defaultSDCardConfigFilename = "CONFIG.BIN";
122 void saveEEPROMToSDCardCloseContinue(void)
124 if (fileState != FILE_STATE_FAILED) {
125 fileState = FILE_STATE_COMPLETE;
129 void saveEEPROMToSDCardWriteContinue(afatfsFilePtr_t file)
131 if (!file) {
132 fileState = FILE_STATE_FAILED;
133 return;
136 uint32_t totalBytesWritten = 0;
137 uint32_t bytesWritten = 0;
138 bool success;
140 do {
141 bytesWritten = afatfs_fwrite(file, &eepromData[totalBytesWritten], EEPROM_SIZE - totalBytesWritten);
142 totalBytesWritten += bytesWritten;
143 success = (totalBytesWritten == EEPROM_SIZE);
145 afatfs_poll();
146 } while (!success && afatfs_getLastError() == AFATFS_ERROR_NONE);
148 if (!success) {
149 fileState = FILE_STATE_FAILED;
152 while (!afatfs_fclose(file, saveEEPROMToSDCardCloseContinue)) {
153 afatfs_poll();
157 bool saveEEPROMToSDCard(void)
159 fileState = FILE_STATE_BUSY;
160 bool result = afatfs_fopen(defaultSDCardConfigFilename, "w+", saveEEPROMToSDCardWriteContinue);
161 if (!result) {
162 return false;
165 while (fileState == FILE_STATE_BUSY) {
166 afatfs_poll();
169 while (!afatfs_flush()) {
170 afatfs_poll();
173 return (fileState == FILE_STATE_COMPLETE);
176 void loadEEPROMFromSDCardCloseContinue(void)
178 if (fileState != FILE_STATE_FAILED) {
179 fileState = FILE_STATE_COMPLETE;
183 void loadEEPROMFromSDCardReadContinue(afatfsFilePtr_t file)
185 if (!file) {
186 fileState = FILE_STATE_FAILED;
187 return;
190 fileState = FILE_STATE_BUSY;
192 uint32_t totalBytesRead = 0;
193 uint32_t bytesRead = 0;
194 bool success;
196 if (afatfs_feof(file)) {
197 // empty file, nothing to load.
198 memset(eepromData, 0x00, EEPROM_SIZE);
199 success = true;
200 } else {
202 do {
203 bytesRead = afatfs_fread(file, &eepromData[totalBytesRead], EEPROM_SIZE - totalBytesRead);
204 totalBytesRead += bytesRead;
205 success = (totalBytesRead == EEPROM_SIZE);
207 afatfs_poll();
208 } while (!success && afatfs_getLastError() == AFATFS_ERROR_NONE);
211 if (!success) {
212 fileState = FILE_STATE_FAILED;
215 while (!afatfs_fclose(file, loadEEPROMFromSDCardCloseContinue)) {
216 afatfs_poll();
219 return;
222 bool loadEEPROMFromSDCard(void)
224 fileState = FILE_STATE_BUSY;
225 // 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.
226 bool result = afatfs_fopen(defaultSDCardConfigFilename, "w+", loadEEPROMFromSDCardReadContinue);
227 if (!result) {
228 return false;
231 while (fileState == FILE_STATE_BUSY) {
232 afatfs_poll();
235 return (fileState == FILE_STATE_COMPLETE);
237 #endif
239 #ifdef CONFIG_IN_FILE
240 void loadEEPROMFromFile(void) {
241 FLASH_Unlock(); // load existing config file into eepromData
243 #endif
245 void initEEPROM(void)
247 // Verify that this architecture packs as expected.
248 STATIC_ASSERT(offsetof(packingTest_t, byte) == 0, byte_packing_test_failed);
249 STATIC_ASSERT(offsetof(packingTest_t, word) == 1, word_packing_test_failed);
250 STATIC_ASSERT(sizeof(packingTest_t) == 5, overall_packing_test_failed);
252 STATIC_ASSERT(sizeof(configFooter_t) == 2, footer_size_failed);
253 STATIC_ASSERT(sizeof(configRecord_t) == 6, record_size_failed);
255 #if defined(CONFIG_IN_FILE)
256 loadEEPROMFromFile();
257 #elif defined(CONFIG_IN_EXTERNAL_FLASH)
258 bool eepromLoaded = loadEEPROMFromExternalFlash();
259 if (!eepromLoaded) {
260 // Flash read failed - just die now
261 failureMode(FAILURE_FLASH_READ_FAILED);
263 #elif defined(CONFIG_IN_SDCARD)
264 bool eepromLoaded = loadEEPROMFromSDCard();
265 if (!eepromLoaded) {
266 // SDCard read failed - just die now
267 failureMode(FAILURE_SDCARD_READ_FAILED);
269 #endif
272 bool isEEPROMVersionValid(void)
274 const uint8_t *p = &__config_start;
275 const configHeader_t *header = (const configHeader_t *)p;
277 if (header->eepromConfigVersion != EEPROM_CONF_VERSION) {
278 return false;
281 return true;
284 // Scan the EEPROM config. Returns true if the config is valid.
285 bool isEEPROMStructureValid(void)
287 const uint8_t *p = &__config_start;
288 const configHeader_t *header = (const configHeader_t *)p;
290 if (header->magic_be != 0xBE) {
291 return false;
294 uint16_t crc = CRC_START_VALUE;
295 crc = crc16_ccitt_update(crc, header, sizeof(*header));
296 p += sizeof(*header);
298 for (;;) {
299 const configRecord_t *record = (const configRecord_t *)p;
301 if (record->size == 0) {
302 // Found the end. Stop scanning.
303 break;
305 if (p + record->size >= &__config_end
306 || record->size < sizeof(*record)) {
307 // Too big or too small.
308 return false;
311 crc = crc16_ccitt_update(crc, p, record->size);
313 p += record->size;
316 const configFooter_t *footer = (const configFooter_t *)p;
317 crc = crc16_ccitt_update(crc, footer, sizeof(*footer));
318 p += sizeof(*footer);
320 // include stored CRC in the CRC calculation
321 const uint16_t *storedCrc = (const uint16_t *)p;
322 crc = crc16_ccitt_update(crc, storedCrc, sizeof(*storedCrc));
323 p += sizeof(storedCrc);
325 eepromConfigSize = p - &__config_start;
327 // CRC has the property that if the CRC itself is included in the calculation the resulting CRC will have constant value
328 return crc == CRC_CHECK_VALUE;
331 uint16_t getEEPROMConfigSize(void)
333 return eepromConfigSize;
336 size_t getEEPROMStorageSize(void)
338 #if defined(CONFIG_IN_EXTERNAL_FLASH)
340 const flashPartition_t *flashPartition = flashPartitionFindByType(FLASH_PARTITION_TYPE_CONFIG);
341 return FLASH_PARTITION_SECTOR_COUNT(flashPartition) * flashGetGeometry()->sectorSize;
342 #endif
343 #ifdef CONFIG_IN_RAM
344 return EEPROM_SIZE;
345 #else
346 return &__config_end - &__config_start;
347 #endif
350 // find config record for reg + classification (profile info) in EEPROM
351 // return NULL when record is not found
352 // this function assumes that EEPROM content is valid
353 static const configRecord_t *findEEPROM(const pgRegistry_t *reg, configRecordFlags_e classification)
355 const uint8_t *p = &__config_start;
356 p += sizeof(configHeader_t); // skip header
357 while (true) {
358 const configRecord_t *record = (const configRecord_t *)p;
359 if (record->size == 0
360 || p + record->size >= &__config_end
361 || record->size < sizeof(*record))
362 break;
363 if (pgN(reg) == record->pgn
364 && (record->flags & CR_CLASSIFICATION_MASK) == classification)
365 return record;
366 p += record->size;
368 // record not found
369 return NULL;
372 // Initialize all PG records from EEPROM.
373 // This functions processes all PGs sequentially, scanning EEPROM for each one. This is suboptimal,
374 // but each PG is loaded/initialized exactly once and in defined order.
375 bool loadEEPROM(void)
377 bool success = true;
379 PG_FOREACH(reg) {
380 const configRecord_t *rec = findEEPROM(reg, CR_CLASSICATION_SYSTEM);
381 if (rec) {
382 // config from EEPROM is available, use it to initialize PG. pgLoad will handle version mismatch
383 if (!pgLoad(reg, rec->pg, rec->size - offsetof(configRecord_t, pg), rec->version)) {
384 success = false;
386 } else {
387 pgReset(reg);
389 success = false;
393 return success;
396 static bool writeSettingsToEEPROM(void)
398 config_streamer_t streamer;
399 config_streamer_init(&streamer);
401 config_streamer_start(&streamer, (uintptr_t)&__config_start, &__config_end - &__config_start);
403 configHeader_t header = {
404 .eepromConfigVersion = EEPROM_CONF_VERSION,
405 .magic_be = 0xBE,
408 config_streamer_write(&streamer, (uint8_t *)&header, sizeof(header));
409 uint16_t crc = CRC_START_VALUE;
410 crc = crc16_ccitt_update(crc, (uint8_t *)&header, sizeof(header));
411 PG_FOREACH(reg) {
412 const uint16_t regSize = pgSize(reg);
413 configRecord_t record = {
414 .size = sizeof(configRecord_t) + regSize,
415 .pgn = pgN(reg),
416 .version = pgVersion(reg),
417 .flags = 0
420 record.flags |= CR_CLASSICATION_SYSTEM;
421 config_streamer_write(&streamer, (uint8_t *)&record, sizeof(record));
422 crc = crc16_ccitt_update(crc, (uint8_t *)&record, sizeof(record));
423 config_streamer_write(&streamer, reg->address, regSize);
424 crc = crc16_ccitt_update(crc, reg->address, regSize);
427 configFooter_t footer = {
428 .terminator = 0,
431 config_streamer_write(&streamer, (uint8_t *)&footer, sizeof(footer));
432 crc = crc16_ccitt_update(crc, (uint8_t *)&footer, sizeof(footer));
434 // include inverted CRC in big endian format in the CRC
435 const uint16_t invertedBigEndianCrc = ~(((crc & 0xFF) << 8) | (crc >> 8));
436 config_streamer_write(&streamer, (uint8_t *)&invertedBigEndianCrc, sizeof(crc));
438 config_streamer_flush(&streamer);
440 const bool success = config_streamer_finish(&streamer) == 0;
442 return success;
445 void writeConfigToEEPROM(void)
447 bool success = false;
448 // write it
449 for (int attempt = 0; attempt < 3 && !success; attempt++) {
450 if (writeSettingsToEEPROM()) {
451 success = true;
453 #ifdef CONFIG_IN_EXTERNAL_FLASH
454 // copy it back from flash to the in-memory buffer.
455 success = loadEEPROMFromExternalFlash();
456 #endif
457 #ifdef CONFIG_IN_SDCARD
458 // copy it back from flash to the in-memory buffer.
459 success = loadEEPROMFromSDCard();
460 #endif
465 if (success && isEEPROMVersionValid() && isEEPROMStructureValid()) {
466 return;
469 // Flash write failed - just die now
470 failureMode(FAILURE_CONFIG_STORE_FAILURE);