eeprom_stm32.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  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_DENSITY_PAGES # 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_DENSITY_PAGES)
  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_DENSITY_PAGES * 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. /* These bits are used for optimizing encoding of bytes, 0 and 1 */
  133. #define FEE_WORD_ENCODING 0x8000
  134. #define FEE_VALUE_NEXT 0x6000
  135. #define FEE_VALUE_RESERVED 0x4000
  136. #define FEE_VALUE_ENCODED 0x2000
  137. #define FEE_BYTE_RANGE 0x80
  138. // HACK ALERT. This definition may not match your processor
  139. // To Do. Work out correct value for EEPROM_PAGE_SIZE on the STM32F103CT6 etc
  140. #if defined(EEPROM_EMU_STM32F303xC)
  141. # define MCU_STM32F303CC
  142. #elif defined(EEPROM_EMU_STM32F103xB)
  143. # define MCU_STM32F103RB
  144. #elif defined(EEPROM_EMU_STM32F072xB)
  145. # define MCU_STM32F072CB
  146. #elif defined(EEPROM_EMU_STM32F042x6)
  147. # define MCU_STM32F042K6
  148. #elif !defined(FEE_PAGE_SIZE) || !defined(FEE_DENSITY_PAGES) || !defined(FEE_MCU_FLASH_SIZE)
  149. # error "not implemented."
  150. #endif
  151. #if !defined(FEE_PAGE_SIZE) || !defined(FEE_DENSITY_PAGES)
  152. # if defined(MCU_STM32F103RB) || defined(MCU_STM32F042K6)
  153. # ifndef FEE_PAGE_SIZE
  154. # define FEE_PAGE_SIZE 0x400 // Page size = 1KByte
  155. # endif
  156. # ifndef FEE_DENSITY_PAGES
  157. # define FEE_DENSITY_PAGES 2 // How many pages are used
  158. # endif
  159. # elif defined(MCU_STM32F103ZE) || defined(MCU_STM32F103RE) || defined(MCU_STM32F103RD) || defined(MCU_STM32F303CC) || defined(MCU_STM32F072CB)
  160. # ifndef FEE_PAGE_SIZE
  161. # define FEE_PAGE_SIZE 0x800 // Page size = 2KByte
  162. # endif
  163. # ifndef FEE_DENSITY_PAGES
  164. # define FEE_DENSITY_PAGES 4 // How many pages are used
  165. # endif
  166. # else
  167. # error "No MCU type specified. Add something like -DMCU_STM32F103RB to your compiler arguments (probably in a Makefile)."
  168. # endif
  169. #endif
  170. #ifndef FEE_MCU_FLASH_SIZE
  171. # if defined(MCU_STM32F103RB) || defined(MCU_STM32F072CB)
  172. # define FEE_MCU_FLASH_SIZE 128 // Size in Kb
  173. # elif defined(MCU_STM32F042K6)
  174. # define FEE_MCU_FLASH_SIZE 32 // Size in Kb
  175. # elif defined(MCU_STM32F103ZE) || defined(MCU_STM32F103RE)
  176. # define FEE_MCU_FLASH_SIZE 512 // Size in Kb
  177. # elif defined(MCU_STM32F103RD)
  178. # define FEE_MCU_FLASH_SIZE 384 // Size in Kb
  179. # elif defined(MCU_STM32F303CC)
  180. # define FEE_MCU_FLASH_SIZE 256 // Size in Kb
  181. # else
  182. # error "No MCU type specified. Add something like -DMCU_STM32F103RB to your compiler arguments (probably in a Makefile)."
  183. # endif
  184. #endif
  185. /* Size of combined compacted eeprom and write log pages */
  186. #define FEE_DENSITY_MAX_SIZE (FEE_DENSITY_PAGES * FEE_PAGE_SIZE)
  187. /* Addressable range 16KByte: 0 <-> (0x1FFF << 1) */
  188. #define FEE_ADDRESS_MAX_SIZE 0x4000
  189. #ifndef EEPROM_START_ADDRESS /* *TODO: Get rid of this check */
  190. # if FEE_DENSITY_MAX_SIZE > (FEE_MCU_FLASH_SIZE * 1024)
  191. # pragma message STR(FEE_DENSITY_MAX_SIZE) " > " STR(FEE_MCU_FLASH_SIZE * 1024)
  192. # error emulated eeprom: FEE_DENSITY_PAGES is greater than available flash size
  193. # endif
  194. #endif
  195. /* Size of emulated eeprom */
  196. #ifdef FEE_DENSITY_BYTES
  197. # if (FEE_DENSITY_BYTES > FEE_DENSITY_MAX_SIZE)
  198. # pragma message STR(FEE_DENSITY_BYTES) " > " STR(FEE_DENSITY_MAX_SIZE)
  199. # error emulated eeprom: FEE_DENSITY_BYTES exceeds FEE_DENSITY_MAX_SIZE
  200. # endif
  201. # if (FEE_DENSITY_BYTES == FEE_DENSITY_MAX_SIZE)
  202. # pragma message STR(FEE_DENSITY_BYTES) " == " STR(FEE_DENSITY_MAX_SIZE)
  203. # warning emulated eeprom: FEE_DENSITY_BYTES leaves no room for a write log. This will greatly increase the flash wear rate!
  204. # endif
  205. # if FEE_DENSITY_BYTES > FEE_ADDRESS_MAX_SIZE
  206. # pragma message STR(FEE_DENSITY_BYTES) " > " STR(FEE_ADDRESS_MAX_SIZE)
  207. # error emulated eeprom: FEE_DENSITY_BYTES is greater than FEE_ADDRESS_MAX_SIZE allows
  208. # endif
  209. # if ((FEE_DENSITY_BYTES) % 2) == 1
  210. # error emulated eeprom: FEE_DENSITY_BYTES must be even
  211. # endif
  212. #else
  213. /* Default to half of allocated space used for emulated eeprom, half for write log */
  214. # define FEE_DENSITY_BYTES (FEE_DENSITY_PAGES * FEE_PAGE_SIZE / 2)
  215. #endif
  216. /* Size of write log */
  217. #define FEE_WRITE_LOG_BYTES (FEE_DENSITY_PAGES * FEE_PAGE_SIZE - FEE_DENSITY_BYTES)
  218. /* Start of the emulated eeprom compacted flash area */
  219. #ifndef FEE_FLASH_BASE
  220. # define FEE_FLASH_BASE 0x8000000
  221. #endif
  222. #define FEE_PAGE_BASE_ADDRESS ((uintptr_t)(FEE_FLASH_BASE) + FEE_MCU_FLASH_SIZE * 1024 - FEE_WRITE_LOG_BYTES - FEE_DENSITY_BYTES)
  223. /* End of the emulated eeprom compacted flash area */
  224. #define FEE_PAGE_LAST_ADDRESS (FEE_PAGE_BASE_ADDRESS + FEE_DENSITY_BYTES)
  225. /* Start of the emulated eeprom write log */
  226. #define FEE_WRITE_LOG_BASE_ADDRESS FEE_PAGE_LAST_ADDRESS
  227. /* End of the emulated eeprom write log */
  228. #define FEE_WRITE_LOG_LAST_ADDRESS (FEE_WRITE_LOG_BASE_ADDRESS + FEE_WRITE_LOG_BYTES)
  229. /* Flash word value after erase */
  230. #define FEE_EMPTY_WORD ((uint16_t)0xFFFF)
  231. #if defined(DYNAMIC_KEYMAP_EEPROM_MAX_ADDR) && (DYNAMIC_KEYMAP_EEPROM_MAX_ADDR >= FEE_DENSITY_BYTES)
  232. # error emulated eeprom: DYNAMIC_KEYMAP_EEPROM_MAX_ADDR is greater than the FEE_DENSITY_BYTES available
  233. #endif
  234. /* In-memory contents of emulated eeprom for faster access */
  235. /* *TODO: Implement page swapping */
  236. static uint16_t WordBuf[FEE_DENSITY_BYTES / 2];
  237. static uint8_t *DataBuf = (uint8_t *)WordBuf;
  238. /* Pointer to the first available slot within the write log */
  239. static uint16_t *empty_slot;
  240. // #define DEBUG_EEPROM_OUTPUT
  241. /*
  242. * Debug print utils
  243. */
  244. #if defined(DEBUG_EEPROM_OUTPUT)
  245. # define debug_eeprom debug_enable
  246. # define eeprom_println(s) println(s)
  247. # define eeprom_printf(fmt, ...) xprintf(fmt, ##__VA_ARGS__);
  248. #else /* NO_DEBUG */
  249. # define debug_eeprom false
  250. # define eeprom_println(s)
  251. # define eeprom_printf(fmt, ...)
  252. #endif /* NO_DEBUG */
  253. void print_eeprom(void) {
  254. #ifndef NO_DEBUG
  255. int empty_rows = 0;
  256. for (uint16_t i = 0; i < FEE_DENSITY_BYTES; i++) {
  257. if (i % 16 == 0) {
  258. if (i >= FEE_DENSITY_BYTES - 16) {
  259. /* Make sure we display the last row */
  260. empty_rows = 0;
  261. }
  262. /* Check if this row is uninitialized */
  263. ++empty_rows;
  264. for (uint16_t j = 0; j < 16; j++) {
  265. if (DataBuf[i + j]) {
  266. empty_rows = 0;
  267. break;
  268. }
  269. }
  270. if (empty_rows > 1) {
  271. /* Repeat empty row */
  272. if (empty_rows == 2) {
  273. /* Only display the first repeat empty row */
  274. println("*");
  275. }
  276. i += 15;
  277. continue;
  278. }
  279. xprintf("%04x", i);
  280. }
  281. if (i % 8 == 0) print(" ");
  282. xprintf(" %02x", DataBuf[i]);
  283. if ((i + 1) % 16 == 0) {
  284. println("");
  285. }
  286. }
  287. #endif
  288. }
  289. uint16_t EEPROM_Init(void) {
  290. /* Load emulated eeprom contents from compacted flash into memory */
  291. uint16_t *src = (uint16_t *)FEE_PAGE_BASE_ADDRESS;
  292. uint16_t *dest = (uint16_t *)DataBuf;
  293. for (; src < (uint16_t *)FEE_PAGE_LAST_ADDRESS; ++src, ++dest) {
  294. *dest = ~*src;
  295. }
  296. if (debug_eeprom) {
  297. println("EEPROM_Init Compacted Pages:");
  298. print_eeprom();
  299. println("EEPROM_Init Write Log:");
  300. }
  301. /* Replay write log */
  302. uint16_t *log_addr;
  303. for (log_addr = (uint16_t *)FEE_WRITE_LOG_BASE_ADDRESS; log_addr < (uint16_t *)FEE_WRITE_LOG_LAST_ADDRESS; ++log_addr) {
  304. uint16_t address = *log_addr;
  305. if (address == FEE_EMPTY_WORD) {
  306. break;
  307. }
  308. /* Check for lowest 128-bytes optimization */
  309. if (!(address & FEE_WORD_ENCODING)) {
  310. uint8_t bvalue = (uint8_t)address;
  311. address >>= 8;
  312. DataBuf[address] = bvalue;
  313. eeprom_printf("DataBuf[0x%02x] = 0x%02x;\n", address, bvalue);
  314. } else {
  315. uint16_t wvalue;
  316. /* Check if value is in next word */
  317. if ((address & FEE_VALUE_NEXT) == FEE_VALUE_NEXT) {
  318. /* Read value from next word */
  319. if (++log_addr >= (uint16_t *)FEE_WRITE_LOG_LAST_ADDRESS) {
  320. break;
  321. }
  322. wvalue = ~*log_addr;
  323. if (!wvalue) {
  324. eeprom_printf("Incomplete write at log_addr: 0x%04x;\n", (uint32_t)log_addr);
  325. /* Possibly incomplete write. Ignore and continue */
  326. continue;
  327. }
  328. address &= 0x1FFF;
  329. address <<= 1;
  330. /* Writes to addresses less than 128 are byte log entries */
  331. address += FEE_BYTE_RANGE;
  332. } else {
  333. /* Reserved for future use */
  334. if (address & FEE_VALUE_RESERVED) {
  335. eeprom_printf("Reserved encoded value at log_addr: 0x%04x;\n", (uint32_t)log_addr);
  336. continue;
  337. }
  338. /* Optimization for 0 or 1 values. */
  339. wvalue = (address & FEE_VALUE_ENCODED) >> 13;
  340. address &= 0x1FFF;
  341. address <<= 1;
  342. }
  343. if (address < FEE_DENSITY_BYTES) {
  344. eeprom_printf("DataBuf[0x%04x] = 0x%04x;\n", address, wvalue);
  345. *(uint16_t *)(&DataBuf[address]) = wvalue;
  346. } else {
  347. eeprom_printf("DataBuf[0x%04x] cannot be set to 0x%04x [BAD ADDRESS]\n", address, wvalue);
  348. }
  349. }
  350. }
  351. empty_slot = log_addr;
  352. if (debug_eeprom) {
  353. println("EEPROM_Init Final DataBuf:");
  354. print_eeprom();
  355. }
  356. return FEE_DENSITY_BYTES;
  357. }
  358. /* Clear flash contents (doesn't touch in-memory DataBuf) */
  359. static void eeprom_clear(void) {
  360. FLASH_Unlock();
  361. for (uint16_t page_num = 0; page_num < FEE_DENSITY_PAGES; ++page_num) {
  362. eeprom_printf("FLASH_ErasePage(0x%04x)\n", (uint32_t)(FEE_PAGE_BASE_ADDRESS + (page_num * FEE_PAGE_SIZE)));
  363. FLASH_ErasePage(FEE_PAGE_BASE_ADDRESS + (page_num * FEE_PAGE_SIZE));
  364. }
  365. FLASH_Lock();
  366. empty_slot = (uint16_t *)FEE_WRITE_LOG_BASE_ADDRESS;
  367. eeprom_printf("eeprom_clear empty_slot: 0x%08x\n", (uint32_t)empty_slot);
  368. }
  369. /* Erase emulated eeprom */
  370. void EEPROM_Erase(void) {
  371. eeprom_println("EEPROM_Erase");
  372. /* Erase compacted pages and write log */
  373. eeprom_clear();
  374. /* re-initialize to reset DataBuf */
  375. EEPROM_Init();
  376. }
  377. /* Compact write log */
  378. static uint8_t eeprom_compact(void) {
  379. /* Erase compacted pages and write log */
  380. eeprom_clear();
  381. FLASH_Unlock();
  382. FLASH_Status final_status = FLASH_COMPLETE;
  383. /* Write emulated eeprom contents from memory to compacted flash */
  384. uint16_t *src = (uint16_t *)DataBuf;
  385. uintptr_t dest = FEE_PAGE_BASE_ADDRESS;
  386. uint16_t value;
  387. for (; dest < FEE_PAGE_LAST_ADDRESS; ++src, dest += 2) {
  388. value = *src;
  389. if (value) {
  390. eeprom_printf("FLASH_ProgramHalfWord(0x%04x, 0x%04x)\n", (uint32_t)dest, ~value);
  391. FLASH_Status status = FLASH_ProgramHalfWord(dest, ~value);
  392. if (status != FLASH_COMPLETE) final_status = status;
  393. }
  394. }
  395. FLASH_Lock();
  396. if (debug_eeprom) {
  397. println("eeprom_compacted:");
  398. print_eeprom();
  399. }
  400. return final_status;
  401. }
  402. static uint8_t eeprom_write_direct_entry(uint16_t Address) {
  403. /* Check if we can just write this directly to the compacted flash area */
  404. uintptr_t directAddress = FEE_PAGE_BASE_ADDRESS + (Address & 0xFFFE);
  405. if (*(uint16_t *)directAddress == FEE_EMPTY_WORD) {
  406. /* Write the value directly to the compacted area without a log entry */
  407. uint16_t value = ~*(uint16_t *)(&DataBuf[Address & 0xFFFE]);
  408. /* Early exit if a write isn't needed */
  409. if (value == FEE_EMPTY_WORD) return FLASH_COMPLETE;
  410. FLASH_Unlock();
  411. eeprom_printf("FLASH_ProgramHalfWord(0x%08x, 0x%04x) [DIRECT]\n", (uint32_t)directAddress, value);
  412. FLASH_Status status = FLASH_ProgramHalfWord(directAddress, value);
  413. FLASH_Lock();
  414. return status;
  415. }
  416. return 0;
  417. }
  418. static uint8_t eeprom_write_log_word_entry(uint16_t Address) {
  419. FLASH_Status final_status = FLASH_COMPLETE;
  420. uint16_t value = *(uint16_t *)(&DataBuf[Address]);
  421. eeprom_printf("eeprom_write_log_word_entry(0x%04x): 0x%04x\n", Address, value);
  422. /* MSB signifies the lowest 128-byte optimization is not in effect */
  423. uint16_t encoding = FEE_WORD_ENCODING;
  424. uint8_t entry_size;
  425. if (value <= 1) {
  426. encoding |= value << 13;
  427. entry_size = 2;
  428. } else {
  429. encoding |= FEE_VALUE_NEXT;
  430. entry_size = 4;
  431. /* Writes to addresses less than 128 are byte log entries */
  432. Address -= FEE_BYTE_RANGE;
  433. }
  434. /* if we can't find an empty spot, we must compact emulated eeprom */
  435. if (empty_slot > (uint16_t *)(FEE_WRITE_LOG_LAST_ADDRESS - entry_size)) {
  436. /* compact the write log into the compacted flash area */
  437. return eeprom_compact();
  438. }
  439. /* Word log writes should be word-aligned. Take back a bit */
  440. Address >>= 1;
  441. Address |= encoding;
  442. /* ok we found a place let's write our data */
  443. FLASH_Unlock();
  444. /* address */
  445. eeprom_printf("FLASH_ProgramHalfWord(0x%08x, 0x%04x)\n", (uint32_t)empty_slot, Address);
  446. final_status = FLASH_ProgramHalfWord((uintptr_t)empty_slot++, Address);
  447. /* value */
  448. if (encoding == (FEE_WORD_ENCODING | FEE_VALUE_NEXT)) {
  449. eeprom_printf("FLASH_ProgramHalfWord(0x%08x, 0x%04x)\n", (uint32_t)empty_slot, ~value);
  450. FLASH_Status status = FLASH_ProgramHalfWord((uintptr_t)empty_slot++, ~value);
  451. if (status != FLASH_COMPLETE) final_status = status;
  452. }
  453. FLASH_Lock();
  454. return final_status;
  455. }
  456. static uint8_t eeprom_write_log_byte_entry(uint16_t Address) {
  457. eeprom_printf("eeprom_write_log_byte_entry(0x%04x): 0x%02x\n", Address, DataBuf[Address]);
  458. /* if couldn't find an empty spot, we must compact emulated eeprom */
  459. if (empty_slot >= (uint16_t *)FEE_WRITE_LOG_LAST_ADDRESS) {
  460. /* compact the write log into the compacted flash area */
  461. return eeprom_compact();
  462. }
  463. /* ok we found a place let's write our data */
  464. FLASH_Unlock();
  465. /* Pack address and value into the same word */
  466. uint16_t value = (Address << 8) | DataBuf[Address];
  467. /* write to flash */
  468. eeprom_printf("FLASH_ProgramHalfWord(0x%08x, 0x%04x)\n", (uint32_t)empty_slot, value);
  469. FLASH_Status status = FLASH_ProgramHalfWord((uintptr_t)empty_slot++, value);
  470. FLASH_Lock();
  471. return status;
  472. }
  473. uint8_t EEPROM_WriteDataByte(uint16_t Address, uint8_t DataByte) {
  474. /* if the address is out-of-bounds, do nothing */
  475. if (Address >= FEE_DENSITY_BYTES) {
  476. eeprom_printf("EEPROM_WriteDataByte(0x%04x, 0x%02x) [BAD ADDRESS]\n", Address, DataByte);
  477. return FLASH_BAD_ADDRESS;
  478. }
  479. /* if the value is the same, don't bother writing it */
  480. if (DataBuf[Address] == DataByte) {
  481. eeprom_printf("EEPROM_WriteDataByte(0x%04x, 0x%02x) [SKIP SAME]\n", Address, DataByte);
  482. return 0;
  483. }
  484. /* keep DataBuf cache in sync */
  485. DataBuf[Address] = DataByte;
  486. eeprom_printf("EEPROM_WriteDataByte DataBuf[0x%04x] = 0x%02x\n", Address, DataBuf[Address]);
  487. /* perform the write into flash memory */
  488. /* First, attempt to write directly into the compacted flash area */
  489. FLASH_Status status = eeprom_write_direct_entry(Address);
  490. if (!status) {
  491. /* Otherwise append to the write log */
  492. if (Address < FEE_BYTE_RANGE) {
  493. status = eeprom_write_log_byte_entry(Address);
  494. } else {
  495. status = eeprom_write_log_word_entry(Address & 0xFFFE);
  496. }
  497. }
  498. if (status != 0 && status != FLASH_COMPLETE) {
  499. eeprom_printf("EEPROM_WriteDataByte [STATUS == %d]\n", status);
  500. }
  501. return status;
  502. }
  503. uint8_t EEPROM_WriteDataWord(uint16_t Address, uint16_t DataWord) {
  504. /* if the address is out-of-bounds, do nothing */
  505. if (Address >= FEE_DENSITY_BYTES) {
  506. eeprom_printf("EEPROM_WriteDataWord(0x%04x, 0x%04x) [BAD ADDRESS]\n", Address, DataWord);
  507. return FLASH_BAD_ADDRESS;
  508. }
  509. /* Check for word alignment */
  510. FLASH_Status final_status = FLASH_COMPLETE;
  511. if (Address % 2) {
  512. final_status = EEPROM_WriteDataByte(Address, DataWord);
  513. FLASH_Status status = EEPROM_WriteDataByte(Address + 1, DataWord >> 8);
  514. if (status != FLASH_COMPLETE) final_status = status;
  515. if (final_status != 0 && final_status != FLASH_COMPLETE) {
  516. eeprom_printf("EEPROM_WriteDataWord [STATUS == %d]\n", final_status);
  517. }
  518. return final_status;
  519. }
  520. /* if the value is the same, don't bother writing it */
  521. uint16_t oldValue = *(uint16_t *)(&DataBuf[Address]);
  522. if (oldValue == DataWord) {
  523. eeprom_printf("EEPROM_WriteDataWord(0x%04x, 0x%04x) [SKIP SAME]\n", Address, DataWord);
  524. return 0;
  525. }
  526. /* keep DataBuf cache in sync */
  527. *(uint16_t *)(&DataBuf[Address]) = DataWord;
  528. eeprom_printf("EEPROM_WriteDataWord DataBuf[0x%04x] = 0x%04x\n", Address, *(uint16_t *)(&DataBuf[Address]));
  529. /* perform the write into flash memory */
  530. /* First, attempt to write directly into the compacted flash area */
  531. final_status = eeprom_write_direct_entry(Address);
  532. if (!final_status) {
  533. /* Otherwise append to the write log */
  534. /* Check if we need to fall back to byte write */
  535. if (Address < FEE_BYTE_RANGE) {
  536. final_status = FLASH_COMPLETE;
  537. /* Only write a byte if it has changed */
  538. if ((uint8_t)oldValue != (uint8_t)DataWord) {
  539. final_status = eeprom_write_log_byte_entry(Address);
  540. }
  541. FLASH_Status status = FLASH_COMPLETE;
  542. /* Only write a byte if it has changed */
  543. if ((oldValue >> 8) != (DataWord >> 8)) {
  544. status = eeprom_write_log_byte_entry(Address + 1);
  545. }
  546. if (status != FLASH_COMPLETE) final_status = status;
  547. } else {
  548. final_status = eeprom_write_log_word_entry(Address);
  549. }
  550. }
  551. if (final_status != 0 && final_status != FLASH_COMPLETE) {
  552. eeprom_printf("EEPROM_WriteDataWord [STATUS == %d]\n", final_status);
  553. }
  554. return final_status;
  555. }
  556. uint8_t EEPROM_ReadDataByte(uint16_t Address) {
  557. uint8_t DataByte = 0xFF;
  558. if (Address < FEE_DENSITY_BYTES) {
  559. DataByte = DataBuf[Address];
  560. }
  561. eeprom_printf("EEPROM_ReadDataByte(0x%04x): 0x%02x\n", Address, DataByte);
  562. return DataByte;
  563. }
  564. uint16_t EEPROM_ReadDataWord(uint16_t Address) {
  565. uint16_t DataWord = 0xFFFF;
  566. if (Address < FEE_DENSITY_BYTES - 1) {
  567. /* Check word alignment */
  568. if (Address % 2) {
  569. DataWord = DataBuf[Address] | (DataBuf[Address + 1] << 8);
  570. } else {
  571. DataWord = *(uint16_t *)(&DataBuf[Address]);
  572. }
  573. }
  574. eeprom_printf("EEPROM_ReadDataWord(0x%04x): 0x%04x\n", Address, DataWord);
  575. return DataWord;
  576. }
  577. /*****************************************************************************
  578. * Wrap library in AVR style functions.
  579. *******************************************************************************/
  580. uint8_t eeprom_read_byte(const uint8_t *Address) { return EEPROM_ReadDataByte((const uintptr_t)Address); }
  581. void eeprom_write_byte(uint8_t *Address, uint8_t Value) { EEPROM_WriteDataByte((uintptr_t)Address, Value); }
  582. void eeprom_update_byte(uint8_t *Address, uint8_t Value) { EEPROM_WriteDataByte((uintptr_t)Address, Value); }
  583. uint16_t eeprom_read_word(const uint16_t *Address) { return EEPROM_ReadDataWord((const uintptr_t)Address); }
  584. void eeprom_write_word(uint16_t *Address, uint16_t Value) { EEPROM_WriteDataWord((uintptr_t)Address, Value); }
  585. void eeprom_update_word(uint16_t *Address, uint16_t Value) { EEPROM_WriteDataWord((uintptr_t)Address, Value); }
  586. uint32_t eeprom_read_dword(const uint32_t *Address) {
  587. const uint16_t p = (const uintptr_t)Address;
  588. /* Check word alignment */
  589. if (p % 2) {
  590. /* Not aligned */
  591. return (uint32_t)EEPROM_ReadDataByte(p) | (uint32_t)(EEPROM_ReadDataWord(p + 1) << 8) | (uint32_t)(EEPROM_ReadDataByte(p + 3) << 24);
  592. } else {
  593. /* Aligned */
  594. return EEPROM_ReadDataWord(p) | (EEPROM_ReadDataWord(p + 2) << 16);
  595. }
  596. }
  597. void eeprom_write_dword(uint32_t *Address, uint32_t Value) {
  598. uint16_t p = (const uintptr_t)Address;
  599. /* Check word alignment */
  600. if (p % 2) {
  601. /* Not aligned */
  602. EEPROM_WriteDataByte(p, (uint8_t)Value);
  603. EEPROM_WriteDataWord(p + 1, (uint16_t)(Value >> 8));
  604. EEPROM_WriteDataByte(p + 3, (uint8_t)(Value >> 24));
  605. } else {
  606. /* Aligned */
  607. EEPROM_WriteDataWord(p, (uint16_t)Value);
  608. EEPROM_WriteDataWord(p + 2, (uint16_t)(Value >> 16));
  609. }
  610. }
  611. void eeprom_update_dword(uint32_t *Address, uint32_t Value) { eeprom_write_dword(Address, Value); }
  612. void eeprom_read_block(void *buf, const void *addr, size_t len) {
  613. const uint8_t *src = (const uint8_t *)addr;
  614. uint8_t * dest = (uint8_t *)buf;
  615. /* Check word alignment */
  616. if (len && (uintptr_t)src % 2) {
  617. /* Read the unaligned first byte */
  618. *dest++ = eeprom_read_byte(src++);
  619. --len;
  620. }
  621. uint16_t value;
  622. bool aligned = ((uintptr_t)dest % 2 == 0);
  623. while (len > 1) {
  624. value = eeprom_read_word((uint16_t *)src);
  625. if (aligned) {
  626. *(uint16_t *)dest = value;
  627. dest += 2;
  628. } else {
  629. *dest++ = value;
  630. *dest++ = value >> 8;
  631. }
  632. src += 2;
  633. len -= 2;
  634. }
  635. if (len) {
  636. *dest = eeprom_read_byte(src);
  637. }
  638. }
  639. void eeprom_write_block(const void *buf, void *addr, size_t len) {
  640. uint8_t * dest = (uint8_t *)addr;
  641. const uint8_t *src = (const uint8_t *)buf;
  642. /* Check word alignment */
  643. if (len && (uintptr_t)dest % 2) {
  644. /* Write the unaligned first byte */
  645. eeprom_write_byte(dest++, *src++);
  646. --len;
  647. }
  648. uint16_t value;
  649. bool aligned = ((uintptr_t)src % 2 == 0);
  650. while (len > 1) {
  651. if (aligned) {
  652. value = *(uint16_t *)src;
  653. } else {
  654. value = *(uint8_t *)src | (*(uint8_t *)(src + 1) << 8);
  655. }
  656. eeprom_write_word((uint16_t *)dest, value);
  657. dest += 2;
  658. src += 2;
  659. len -= 2;
  660. }
  661. if (len) {
  662. eeprom_write_byte(dest, *src);
  663. }
  664. }
  665. void eeprom_update_block(const void *buf, void *addr, size_t len) { eeprom_write_block(buf, addr, len); }