eeprom_legacy_emulated_flash.c 22 KB

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