eeprom_stm32.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. /*
  2. * This software is experimental and a work in progress.
  3. * Under no circumstances should these files be used in relation to any critical system(s).
  4. * Use of these files is at your own risk.
  5. *
  6. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  7. * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  8. * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  9. * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  10. * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  11. * DEALINGS IN THE SOFTWARE.
  12. *
  13. * This files are free to use from http://engsta.com/stm32-flash-memory-eeprom-emulator/ by
  14. * Artur F.
  15. *
  16. * Modifications for QMK and STM32F303 by Yiancar
  17. * Modifications to add flash wear leveling by Ilya Zhuravlev
  18. * Modifications to increase flash density by Don Kjer
  19. */
  20. #include <stdio.h>
  21. #include <stdbool.h>
  22. #include "util.h"
  23. #include "debug.h"
  24. #include "eeprom_stm32.h"
  25. #include "flash_stm32.h"
  26. /*
  27. * We emulate eeprom by writing a snapshot compacted view of eeprom contents,
  28. * followed by a write log of any change since that snapshot:
  29. *
  30. * === SIMULATED EEPROM CONTENTS ===
  31. *
  32. * ┌─ Compacted ┬ Write Log ─┐
  33. * │............│[BYTE][BYTE]│
  34. * │FFFF....FFFF│[WRD0][WRD1]│
  35. * │FFFFFFFFFFFF│[WORD][NEXT]│
  36. * │....FFFFFFFF│[BYTE][WRD0]│
  37. * ├────────────┼────────────┤
  38. * └──PAGE_BASE │ │
  39. * PAGE_LAST─┴─WRITE_BASE │
  40. * WRITE_LAST ┘
  41. *
  42. * Compacted contents are the 1's complement of the actual EEPROM contents.
  43. * e.g. An 'FFFF' represents a '0000' value.
  44. *
  45. * The size of the 'compacted' area is equal to the size of the 'emulated' eeprom.
  46. * The size of the compacted-area and write log are configurable, and the combined
  47. * size of Compacted + WriteLog is a multiple FEE_PAGE_SIZE, which is MCU dependent.
  48. * Simulated Eeprom contents are located at the end of available flash space.
  49. *
  50. * The following configuration defines can be set:
  51. *
  52. * FEE_PAGE_COUNT # Total number of pages to use for eeprom simulation (Compact + Write log)
  53. * FEE_DENSITY_BYTES # Size of simulated eeprom. (Defaults to half the space allocated by FEE_PAGE_COUNT)
  54. * NOTE: The current implementation does not include page swapping,
  55. * and FEE_DENSITY_BYTES will consume that amount of RAM as a cached view of actual EEPROM contents.
  56. *
  57. * The maximum size of FEE_DENSITY_BYTES is currently 16384. The write log size equals
  58. * FEE_PAGE_COUNT * FEE_PAGE_SIZE - FEE_DENSITY_BYTES.
  59. * The larger the write log, the less frequently the compacted area needs to be rewritten.
  60. *
  61. *
  62. * *** General Algorithm ***
  63. *
  64. * During initialization:
  65. * The contents of the Compacted-flash area are loaded and the 1's complement value
  66. * is cached into memory (e.g. 0xFFFF in Flash represents 0x0000 in cache).
  67. * Write log entries are processed until a 0xFFFF is reached.
  68. * Each log entry updates a byte or word in the cache.
  69. *
  70. * During reads:
  71. * EEPROM contents are given back directly from the cache in memory.
  72. *
  73. * During writes:
  74. * The contents of the cache is updated first.
  75. * If the Compacted-flash area corresponding to the write address is unprogrammed, the 1's complement of the value is written directly into Compacted-flash
  76. * Otherwise:
  77. * If the write log is full, erase both the Compacted-flash area and the Write log, then write cached contents to the Compacted-flash area.
  78. * Otherwise a Write log entry is constructed and appended to the next free position in the Write log.
  79. *
  80. *
  81. * *** Write Log Structure ***
  82. *
  83. * Write log entries allow for optimized byte writes to addresses below 128. Writing 0 or 1 words are also optimized when word-aligned.
  84. *
  85. * === WRITE LOG ENTRY FORMATS ===
  86. *
  87. * ╔═══ Byte-Entry ══╗
  88. * ║0XXXXXXX║YYYYYYYY║
  89. * ║ └──┬──┘║└──┬───┘║
  90. * ║ Address║ Value ║
  91. * ╚════════╩════════╝
  92. * 0 <= Address < 0x80 (128)
  93. *
  94. * ╔ Word-Encoded 0 ╗
  95. * ║100XXXXXXXXXXXXX║
  96. * ║ │└─────┬─────┘║
  97. * ║ │Address >> 1 ║
  98. * ║ └── Value: 0 ║
  99. * ╚════════════════╝
  100. * 0 <= Address <= 0x3FFE (16382)
  101. *
  102. * ╔ Word-Encoded 1 ╗
  103. * ║101XXXXXXXXXXXXX║
  104. * ║ │└─────┬─────┘║
  105. * ║ │Address >> 1 ║
  106. * ║ └── Value: 1 ║
  107. * ╚════════════════╝
  108. * 0 <= Address <= 0x3FFE (16382)
  109. *
  110. * ╔═══ Reserved ═══╗
  111. * ║110XXXXXXXXXXXXX║
  112. * ╚════════════════╝
  113. *
  114. * ╔═══════════ Word-Next ═══════════╗
  115. * ║111XXXXXXXXXXXXX║YYYYYYYYYYYYYYYY║
  116. * ║ └─────┬─────┘║└───────┬──────┘║
  117. * ║(Address-128)>>1║ ~Value ║
  118. * ╚════════════════╩════════════════╝
  119. * ( 0 <= Address < 0x0080 (128): Reserved)
  120. * 0x80 <= Address <= 0x3FFE (16382)
  121. *
  122. * Write Log entry ranges:
  123. * 0x0000 ... 0x7FFF - Byte-Entry; address is (Entry & 0x7F00) >> 4; value is (Entry & 0xFF)
  124. * 0x8000 ... 0x9FFF - Word-Encoded 0; address is (Entry & 0x1FFF) << 1; value is 0
  125. * 0xA000 ... 0xBFFF - Word-Encoded 1; address is (Entry & 0x1FFF) << 1; value is 1
  126. * 0xC000 ... 0xDFFF - Reserved
  127. * 0xE000 ... 0xFFBF - Word-Next; address is (Entry & 0x1FFF) << 1 + 0x80; value is ~(Next_Entry)
  128. * 0xFFC0 ... 0xFFFE - Reserved
  129. * 0xFFFF - Unprogrammed
  130. *
  131. */
  132. #include "eeprom_stm32_defs.h"
  133. #if !defined(FEE_PAGE_SIZE) || !defined(FEE_PAGE_COUNT) || !defined(FEE_MCU_FLASH_SIZE) || !defined(FEE_PAGE_BASE_ADDRESS)
  134. # error "not implemented."
  135. #endif
  136. /* These bits are used for optimizing encoding of bytes, 0 and 1 */
  137. #define FEE_WORD_ENCODING 0x8000
  138. #define FEE_VALUE_NEXT 0x6000
  139. #define FEE_VALUE_RESERVED 0x4000
  140. #define FEE_VALUE_ENCODED 0x2000
  141. #define FEE_BYTE_RANGE 0x80
  142. /* Addressable range 16KByte: 0 <-> (0x1FFF << 1) */
  143. #define FEE_ADDRESS_MAX_SIZE 0x4000
  144. /* Flash word value after erase */
  145. #define FEE_EMPTY_WORD ((uint16_t)0xFFFF)
  146. /* Size of combined compacted eeprom and write log pages */
  147. #define FEE_DENSITY_MAX_SIZE (FEE_PAGE_COUNT * FEE_PAGE_SIZE)
  148. #ifndef FEE_MCU_FLASH_SIZE_IGNORE_CHECK /* *TODO: Get rid of this check */
  149. # if FEE_DENSITY_MAX_SIZE > (FEE_MCU_FLASH_SIZE * 1024)
  150. # pragma message STR(FEE_DENSITY_MAX_SIZE) " > " STR(FEE_MCU_FLASH_SIZE * 1024)
  151. # error emulated eeprom: FEE_DENSITY_MAX_SIZE is greater than available flash size
  152. # endif
  153. #endif
  154. /* Size of emulated eeprom */
  155. #ifdef FEE_DENSITY_BYTES
  156. # if (FEE_DENSITY_BYTES > FEE_DENSITY_MAX_SIZE)
  157. # pragma message STR(FEE_DENSITY_BYTES) " > " STR(FEE_DENSITY_MAX_SIZE)
  158. # error emulated eeprom: FEE_DENSITY_BYTES exceeds FEE_DENSITY_MAX_SIZE
  159. # endif
  160. # if (FEE_DENSITY_BYTES == FEE_DENSITY_MAX_SIZE)
  161. # pragma message STR(FEE_DENSITY_BYTES) " == " STR(FEE_DENSITY_MAX_SIZE)
  162. # warning emulated eeprom: FEE_DENSITY_BYTES leaves no room for a write log. This will greatly increase the flash wear rate!
  163. # endif
  164. # if FEE_DENSITY_BYTES > FEE_ADDRESS_MAX_SIZE
  165. # pragma message STR(FEE_DENSITY_BYTES) " > " STR(FEE_ADDRESS_MAX_SIZE)
  166. # error emulated eeprom: FEE_DENSITY_BYTES is greater than FEE_ADDRESS_MAX_SIZE allows
  167. # endif
  168. # if ((FEE_DENSITY_BYTES) % 2) == 1
  169. # error emulated eeprom: FEE_DENSITY_BYTES must be even
  170. # endif
  171. #else
  172. /* Default to half of allocated space used for emulated eeprom, half for write log */
  173. # define FEE_DENSITY_BYTES (FEE_PAGE_COUNT * FEE_PAGE_SIZE / 2)
  174. #endif
  175. /* Size of write log */
  176. #ifdef FEE_WRITE_LOG_BYTES
  177. # if ((FEE_DENSITY_BYTES + FEE_WRITE_LOG_BYTES) > FEE_DENSITY_MAX_SIZE)
  178. # pragma message STR(FEE_DENSITY_BYTES) " + " STR(FEE_WRITE_LOG_BYTES) " > " STR(FEE_DENSITY_MAX_SIZE)
  179. # error emulated eeprom: FEE_WRITE_LOG_BYTES exceeds remaining FEE_DENSITY_MAX_SIZE
  180. # endif
  181. # if ((FEE_WRITE_LOG_BYTES) % 2) == 1
  182. # error emulated eeprom: FEE_WRITE_LOG_BYTES must be even
  183. # endif
  184. #else
  185. /* Default to use all remaining space */
  186. # define FEE_WRITE_LOG_BYTES (FEE_PAGE_COUNT * FEE_PAGE_SIZE - FEE_DENSITY_BYTES)
  187. #endif
  188. /* Start of the emulated eeprom compacted flash area */
  189. #define FEE_COMPACTED_BASE_ADDRESS FEE_PAGE_BASE_ADDRESS
  190. /* End of the emulated eeprom compacted flash area */
  191. #define FEE_COMPACTED_LAST_ADDRESS (FEE_COMPACTED_BASE_ADDRESS + FEE_DENSITY_BYTES)
  192. /* Start of the emulated eeprom write log */
  193. #define FEE_WRITE_LOG_BASE_ADDRESS FEE_COMPACTED_LAST_ADDRESS
  194. /* End of the emulated eeprom write log */
  195. #define FEE_WRITE_LOG_LAST_ADDRESS (FEE_WRITE_LOG_BASE_ADDRESS + FEE_WRITE_LOG_BYTES)
  196. #if defined(DYNAMIC_KEYMAP_EEPROM_MAX_ADDR) && (DYNAMIC_KEYMAP_EEPROM_MAX_ADDR >= FEE_DENSITY_BYTES)
  197. # error emulated eeprom: DYNAMIC_KEYMAP_EEPROM_MAX_ADDR is greater than the FEE_DENSITY_BYTES available
  198. #endif
  199. /* In-memory contents of emulated eeprom for faster access */
  200. /* *TODO: Implement page swapping */
  201. static uint16_t WordBuf[FEE_DENSITY_BYTES / 2];
  202. static uint8_t *DataBuf = (uint8_t *)WordBuf;
  203. /* Pointer to the first available slot within the write log */
  204. static uint16_t *empty_slot;
  205. // #define DEBUG_EEPROM_OUTPUT
  206. /*
  207. * Debug print utils
  208. */
  209. #if defined(DEBUG_EEPROM_OUTPUT)
  210. # define debug_eeprom debug_enable
  211. # define eeprom_println(s) println(s)
  212. # define eeprom_printf(fmt, ...) xprintf(fmt, ##__VA_ARGS__);
  213. #else /* NO_DEBUG */
  214. # define debug_eeprom false
  215. # define eeprom_println(s)
  216. # define eeprom_printf(fmt, ...)
  217. #endif /* NO_DEBUG */
  218. void print_eeprom(void) {
  219. #ifndef NO_DEBUG
  220. int empty_rows = 0;
  221. for (uint16_t i = 0; i < FEE_DENSITY_BYTES; i++) {
  222. if (i % 16 == 0) {
  223. if (i >= FEE_DENSITY_BYTES - 16) {
  224. /* Make sure we display the last row */
  225. empty_rows = 0;
  226. }
  227. /* Check if this row is uninitialized */
  228. ++empty_rows;
  229. for (uint16_t j = 0; j < 16; j++) {
  230. if (DataBuf[i + j]) {
  231. empty_rows = 0;
  232. break;
  233. }
  234. }
  235. if (empty_rows > 1) {
  236. /* Repeat empty row */
  237. if (empty_rows == 2) {
  238. /* Only display the first repeat empty row */
  239. println("*");
  240. }
  241. i += 15;
  242. continue;
  243. }
  244. xprintf("%04x", i);
  245. }
  246. if (i % 8 == 0) print(" ");
  247. xprintf(" %02x", DataBuf[i]);
  248. if ((i + 1) % 16 == 0) {
  249. println("");
  250. }
  251. }
  252. #endif
  253. }
  254. uint16_t EEPROM_Init(void) {
  255. /* Load emulated eeprom contents from compacted flash into memory */
  256. uint16_t *src = (uint16_t *)FEE_COMPACTED_BASE_ADDRESS;
  257. uint16_t *dest = (uint16_t *)DataBuf;
  258. for (; src < (uint16_t *)FEE_COMPACTED_LAST_ADDRESS; ++src, ++dest) {
  259. *dest = ~*src;
  260. }
  261. if (debug_eeprom) {
  262. println("EEPROM_Init Compacted Pages:");
  263. print_eeprom();
  264. println("EEPROM_Init Write Log:");
  265. }
  266. /* Replay write log */
  267. uint16_t *log_addr;
  268. for (log_addr = (uint16_t *)FEE_WRITE_LOG_BASE_ADDRESS; log_addr < (uint16_t *)FEE_WRITE_LOG_LAST_ADDRESS; ++log_addr) {
  269. uint16_t address = *log_addr;
  270. if (address == FEE_EMPTY_WORD) {
  271. break;
  272. }
  273. /* Check for lowest 128-bytes optimization */
  274. if (!(address & FEE_WORD_ENCODING)) {
  275. uint8_t bvalue = (uint8_t)address;
  276. address >>= 8;
  277. DataBuf[address] = bvalue;
  278. eeprom_printf("DataBuf[0x%02x] = 0x%02x;\n", address, bvalue);
  279. } else {
  280. uint16_t wvalue;
  281. /* Check if value is in next word */
  282. if ((address & FEE_VALUE_NEXT) == FEE_VALUE_NEXT) {
  283. /* Read value from next word */
  284. if (++log_addr >= (uint16_t *)FEE_WRITE_LOG_LAST_ADDRESS) {
  285. break;
  286. }
  287. wvalue = ~*log_addr;
  288. if (!wvalue) {
  289. eeprom_printf("Incomplete write at log_addr: 0x%04x;\n", (uint32_t)log_addr);
  290. /* Possibly incomplete write. Ignore and continue */
  291. continue;
  292. }
  293. address &= 0x1FFF;
  294. address <<= 1;
  295. /* Writes to addresses less than 128 are byte log entries */
  296. address += FEE_BYTE_RANGE;
  297. } else {
  298. /* Reserved for future use */
  299. if (address & FEE_VALUE_RESERVED) {
  300. eeprom_printf("Reserved encoded value at log_addr: 0x%04x;\n", (uint32_t)log_addr);
  301. continue;
  302. }
  303. /* Optimization for 0 or 1 values. */
  304. wvalue = (address & FEE_VALUE_ENCODED) >> 13;
  305. address &= 0x1FFF;
  306. address <<= 1;
  307. }
  308. if (address < FEE_DENSITY_BYTES) {
  309. eeprom_printf("DataBuf[0x%04x] = 0x%04x;\n", address, wvalue);
  310. *(uint16_t *)(&DataBuf[address]) = wvalue;
  311. } else {
  312. eeprom_printf("DataBuf[0x%04x] cannot be set to 0x%04x [BAD ADDRESS]\n", address, wvalue);
  313. }
  314. }
  315. }
  316. empty_slot = log_addr;
  317. if (debug_eeprom) {
  318. println("EEPROM_Init Final DataBuf:");
  319. print_eeprom();
  320. }
  321. return FEE_DENSITY_BYTES;
  322. }
  323. /* Clear flash contents (doesn't touch in-memory DataBuf) */
  324. static void eeprom_clear(void) {
  325. FLASH_Unlock();
  326. for (uint16_t page_num = 0; page_num < FEE_PAGE_COUNT; ++page_num) {
  327. eeprom_printf("FLASH_ErasePage(0x%04x)\n", (uint32_t)(FEE_PAGE_BASE_ADDRESS + (page_num * FEE_PAGE_SIZE)));
  328. FLASH_ErasePage(FEE_PAGE_BASE_ADDRESS + (page_num * FEE_PAGE_SIZE));
  329. }
  330. FLASH_Lock();
  331. empty_slot = (uint16_t *)FEE_WRITE_LOG_BASE_ADDRESS;
  332. eeprom_printf("eeprom_clear empty_slot: 0x%08x\n", (uint32_t)empty_slot);
  333. }
  334. /* Erase emulated eeprom */
  335. void EEPROM_Erase(void) {
  336. eeprom_println("EEPROM_Erase");
  337. /* Erase compacted pages and write log */
  338. eeprom_clear();
  339. /* re-initialize to reset DataBuf */
  340. EEPROM_Init();
  341. }
  342. /* Compact write log */
  343. static uint8_t eeprom_compact(void) {
  344. /* Erase compacted pages and write log */
  345. eeprom_clear();
  346. FLASH_Unlock();
  347. FLASH_Status final_status = FLASH_COMPLETE;
  348. /* Write emulated eeprom contents from memory to compacted flash */
  349. uint16_t *src = (uint16_t *)DataBuf;
  350. uintptr_t dest = FEE_COMPACTED_BASE_ADDRESS;
  351. uint16_t value;
  352. for (; dest < FEE_COMPACTED_LAST_ADDRESS; ++src, dest += 2) {
  353. value = *src;
  354. if (value) {
  355. eeprom_printf("FLASH_ProgramHalfWord(0x%04x, 0x%04x)\n", (uint32_t)dest, ~value);
  356. FLASH_Status status = FLASH_ProgramHalfWord(dest, ~value);
  357. if (status != FLASH_COMPLETE) final_status = status;
  358. }
  359. }
  360. FLASH_Lock();
  361. if (debug_eeprom) {
  362. println("eeprom_compacted:");
  363. print_eeprom();
  364. }
  365. return final_status;
  366. }
  367. static uint8_t eeprom_write_direct_entry(uint16_t Address) {
  368. /* Check if we can just write this directly to the compacted flash area */
  369. uintptr_t directAddress = FEE_COMPACTED_BASE_ADDRESS + (Address & 0xFFFE);
  370. if (*(uint16_t *)directAddress == FEE_EMPTY_WORD) {
  371. /* Write the value directly to the compacted area without a log entry */
  372. uint16_t value = ~*(uint16_t *)(&DataBuf[Address & 0xFFFE]);
  373. /* Early exit if a write isn't needed */
  374. if (value == FEE_EMPTY_WORD) return FLASH_COMPLETE;
  375. FLASH_Unlock();
  376. eeprom_printf("FLASH_ProgramHalfWord(0x%08x, 0x%04x) [DIRECT]\n", (uint32_t)directAddress, value);
  377. FLASH_Status status = FLASH_ProgramHalfWord(directAddress, value);
  378. FLASH_Lock();
  379. return status;
  380. }
  381. return 0;
  382. }
  383. static uint8_t eeprom_write_log_word_entry(uint16_t Address) {
  384. FLASH_Status final_status = FLASH_COMPLETE;
  385. uint16_t value = *(uint16_t *)(&DataBuf[Address]);
  386. eeprom_printf("eeprom_write_log_word_entry(0x%04x): 0x%04x\n", Address, value);
  387. /* MSB signifies the lowest 128-byte optimization is not in effect */
  388. uint16_t encoding = FEE_WORD_ENCODING;
  389. uint8_t entry_size;
  390. if (value <= 1) {
  391. encoding |= value << 13;
  392. entry_size = 2;
  393. } else {
  394. encoding |= FEE_VALUE_NEXT;
  395. entry_size = 4;
  396. /* Writes to addresses less than 128 are byte log entries */
  397. Address -= FEE_BYTE_RANGE;
  398. }
  399. /* if we can't find an empty spot, we must compact emulated eeprom */
  400. if (empty_slot > (uint16_t *)(FEE_WRITE_LOG_LAST_ADDRESS - entry_size)) {
  401. /* compact the write log into the compacted flash area */
  402. return eeprom_compact();
  403. }
  404. /* Word log writes should be word-aligned. Take back a bit */
  405. Address >>= 1;
  406. Address |= encoding;
  407. /* ok we found a place let's write our data */
  408. FLASH_Unlock();
  409. /* address */
  410. eeprom_printf("FLASH_ProgramHalfWord(0x%08x, 0x%04x)\n", (uint32_t)empty_slot, Address);
  411. final_status = FLASH_ProgramHalfWord((uintptr_t)empty_slot++, Address);
  412. /* value */
  413. if (encoding == (FEE_WORD_ENCODING | FEE_VALUE_NEXT)) {
  414. eeprom_printf("FLASH_ProgramHalfWord(0x%08x, 0x%04x)\n", (uint32_t)empty_slot, ~value);
  415. FLASH_Status status = FLASH_ProgramHalfWord((uintptr_t)empty_slot++, ~value);
  416. if (status != FLASH_COMPLETE) final_status = status;
  417. }
  418. FLASH_Lock();
  419. return final_status;
  420. }
  421. static uint8_t eeprom_write_log_byte_entry(uint16_t Address) {
  422. eeprom_printf("eeprom_write_log_byte_entry(0x%04x): 0x%02x\n", Address, DataBuf[Address]);
  423. /* if couldn't find an empty spot, we must compact emulated eeprom */
  424. if (empty_slot >= (uint16_t *)FEE_WRITE_LOG_LAST_ADDRESS) {
  425. /* compact the write log into the compacted flash area */
  426. return eeprom_compact();
  427. }
  428. /* ok we found a place let's write our data */
  429. FLASH_Unlock();
  430. /* Pack address and value into the same word */
  431. uint16_t value = (Address << 8) | DataBuf[Address];
  432. /* write to flash */
  433. eeprom_printf("FLASH_ProgramHalfWord(0x%08x, 0x%04x)\n", (uint32_t)empty_slot, value);
  434. FLASH_Status status = FLASH_ProgramHalfWord((uintptr_t)empty_slot++, value);
  435. FLASH_Lock();
  436. return status;
  437. }
  438. uint8_t EEPROM_WriteDataByte(uint16_t Address, uint8_t DataByte) {
  439. /* if the address is out-of-bounds, do nothing */
  440. if (Address >= FEE_DENSITY_BYTES) {
  441. eeprom_printf("EEPROM_WriteDataByte(0x%04x, 0x%02x) [BAD ADDRESS]\n", Address, DataByte);
  442. return FLASH_BAD_ADDRESS;
  443. }
  444. /* if the value is the same, don't bother writing it */
  445. if (DataBuf[Address] == DataByte) {
  446. eeprom_printf("EEPROM_WriteDataByte(0x%04x, 0x%02x) [SKIP SAME]\n", Address, DataByte);
  447. return 0;
  448. }
  449. /* keep DataBuf cache in sync */
  450. DataBuf[Address] = DataByte;
  451. eeprom_printf("EEPROM_WriteDataByte DataBuf[0x%04x] = 0x%02x\n", Address, DataBuf[Address]);
  452. /* perform the write into flash memory */
  453. /* First, attempt to write directly into the compacted flash area */
  454. FLASH_Status status = eeprom_write_direct_entry(Address);
  455. if (!status) {
  456. /* Otherwise append to the write log */
  457. if (Address < FEE_BYTE_RANGE) {
  458. status = eeprom_write_log_byte_entry(Address);
  459. } else {
  460. status = eeprom_write_log_word_entry(Address & 0xFFFE);
  461. }
  462. }
  463. if (status != 0 && status != FLASH_COMPLETE) {
  464. eeprom_printf("EEPROM_WriteDataByte [STATUS == %d]\n", status);
  465. }
  466. return status;
  467. }
  468. uint8_t EEPROM_WriteDataWord(uint16_t Address, uint16_t DataWord) {
  469. /* if the address is out-of-bounds, do nothing */
  470. if (Address >= FEE_DENSITY_BYTES) {
  471. eeprom_printf("EEPROM_WriteDataWord(0x%04x, 0x%04x) [BAD ADDRESS]\n", Address, DataWord);
  472. return FLASH_BAD_ADDRESS;
  473. }
  474. /* Check for word alignment */
  475. FLASH_Status final_status = FLASH_COMPLETE;
  476. if (Address % 2) {
  477. final_status = EEPROM_WriteDataByte(Address, DataWord);
  478. FLASH_Status status = EEPROM_WriteDataByte(Address + 1, DataWord >> 8);
  479. if (status != FLASH_COMPLETE) final_status = status;
  480. if (final_status != 0 && final_status != FLASH_COMPLETE) {
  481. eeprom_printf("EEPROM_WriteDataWord [STATUS == %d]\n", final_status);
  482. }
  483. return final_status;
  484. }
  485. /* if the value is the same, don't bother writing it */
  486. uint16_t oldValue = *(uint16_t *)(&DataBuf[Address]);
  487. if (oldValue == DataWord) {
  488. eeprom_printf("EEPROM_WriteDataWord(0x%04x, 0x%04x) [SKIP SAME]\n", Address, DataWord);
  489. return 0;
  490. }
  491. /* keep DataBuf cache in sync */
  492. *(uint16_t *)(&DataBuf[Address]) = DataWord;
  493. eeprom_printf("EEPROM_WriteDataWord DataBuf[0x%04x] = 0x%04x\n", Address, *(uint16_t *)(&DataBuf[Address]));
  494. /* perform the write into flash memory */
  495. /* First, attempt to write directly into the compacted flash area */
  496. final_status = eeprom_write_direct_entry(Address);
  497. if (!final_status) {
  498. /* Otherwise append to the write log */
  499. /* Check if we need to fall back to byte write */
  500. if (Address < FEE_BYTE_RANGE) {
  501. final_status = FLASH_COMPLETE;
  502. /* Only write a byte if it has changed */
  503. if ((uint8_t)oldValue != (uint8_t)DataWord) {
  504. final_status = eeprom_write_log_byte_entry(Address);
  505. }
  506. FLASH_Status status = FLASH_COMPLETE;
  507. /* Only write a byte if it has changed */
  508. if ((oldValue >> 8) != (DataWord >> 8)) {
  509. status = eeprom_write_log_byte_entry(Address + 1);
  510. }
  511. if (status != FLASH_COMPLETE) final_status = status;
  512. } else {
  513. final_status = eeprom_write_log_word_entry(Address);
  514. }
  515. }
  516. if (final_status != 0 && final_status != FLASH_COMPLETE) {
  517. eeprom_printf("EEPROM_WriteDataWord [STATUS == %d]\n", final_status);
  518. }
  519. return final_status;
  520. }
  521. uint8_t EEPROM_ReadDataByte(uint16_t Address) {
  522. uint8_t DataByte = 0xFF;
  523. if (Address < FEE_DENSITY_BYTES) {
  524. DataByte = DataBuf[Address];
  525. }
  526. eeprom_printf("EEPROM_ReadDataByte(0x%04x): 0x%02x\n", Address, DataByte);
  527. return DataByte;
  528. }
  529. uint16_t EEPROM_ReadDataWord(uint16_t Address) {
  530. uint16_t DataWord = 0xFFFF;
  531. if (Address < FEE_DENSITY_BYTES - 1) {
  532. /* Check word alignment */
  533. if (Address % 2) {
  534. DataWord = DataBuf[Address] | (DataBuf[Address + 1] << 8);
  535. } else {
  536. DataWord = *(uint16_t *)(&DataBuf[Address]);
  537. }
  538. }
  539. eeprom_printf("EEPROM_ReadDataWord(0x%04x): 0x%04x\n", Address, DataWord);
  540. return DataWord;
  541. }
  542. /*****************************************************************************
  543. * Bind to eeprom_driver.c
  544. *******************************************************************************/
  545. void eeprom_driver_init(void) { EEPROM_Init(); }
  546. void eeprom_driver_erase(void) { EEPROM_Erase(); }
  547. void eeprom_read_block(void *buf, const void *addr, size_t len) {
  548. const uint8_t *src = (const uint8_t *)addr;
  549. uint8_t * dest = (uint8_t *)buf;
  550. /* Check word alignment */
  551. if (len && (uintptr_t)src % 2) {
  552. /* Read the unaligned first byte */
  553. *dest++ = EEPROM_ReadDataByte((const uintptr_t)src++);
  554. --len;
  555. }
  556. uint16_t value;
  557. bool aligned = ((uintptr_t)dest % 2 == 0);
  558. while (len > 1) {
  559. value = EEPROM_ReadDataWord((const uintptr_t)((uint16_t *)src));
  560. if (aligned) {
  561. *(uint16_t *)dest = value;
  562. dest += 2;
  563. } else {
  564. *dest++ = value;
  565. *dest++ = value >> 8;
  566. }
  567. src += 2;
  568. len -= 2;
  569. }
  570. if (len) {
  571. *dest = EEPROM_ReadDataByte((const uintptr_t)src);
  572. }
  573. }
  574. void eeprom_write_block(const void *buf, void *addr, size_t len) {
  575. uint8_t * dest = (uint8_t *)addr;
  576. const uint8_t *src = (const uint8_t *)buf;
  577. /* Check word alignment */
  578. if (len && (uintptr_t)dest % 2) {
  579. /* Write the unaligned first byte */
  580. EEPROM_WriteDataByte((uintptr_t)dest++, *src++);
  581. --len;
  582. }
  583. uint16_t value;
  584. bool aligned = ((uintptr_t)src % 2 == 0);
  585. while (len > 1) {
  586. if (aligned) {
  587. value = *(uint16_t *)src;
  588. } else {
  589. value = *(uint8_t *)src | (*(uint8_t *)(src + 1) << 8);
  590. }
  591. EEPROM_WriteDataWord((uintptr_t)((uint16_t *)dest), value);
  592. dest += 2;
  593. src += 2;
  594. len -= 2;
  595. }
  596. if (len) {
  597. EEPROM_WriteDataByte((uintptr_t)dest, *src);
  598. }
  599. }