lflash.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. /*
  2. ** $Id: lflash.c
  3. ** See Copyright Notice in lua.h
  4. */
  5. #define lflash_c
  6. #define LUA_CORE
  7. #include "lua.h"
  8. #include "lobject.h"
  9. #include "lauxlib.h"
  10. #include "lstate.h"
  11. #include "lfunc.h"
  12. #include "lflash.h"
  13. #include "platform.h"
  14. #include "user_interface.h"
  15. #include "vfs.h"
  16. #include "uzlib.h"
  17. #include <fcntl.h>
  18. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <string.h>
  21. /*
  22. * Flash memory is a fixed memory addressable block that is serially allocated by the
  23. * luac build process and the out image can be downloaded into SPIFSS and loaded into
  24. * flash with a node.flash.load() command. See luac_cross/lflashimg.c for the build
  25. * process.
  26. */
  27. static char *flashAddr;
  28. static uint32_t flashSize;
  29. static uint32_t flashAddrPhys;
  30. static uint32_t flashSector;
  31. static uint32_t curOffset;
  32. #define ALIGN(s) (((s)+sizeof(size_t)-1) & ((size_t) (- (signed) sizeof(size_t))))
  33. #define ALIGN_BITS(s) (((uint32_t)s) & (sizeof(size_t)-1))
  34. #define ALL_SET (~0)
  35. #define FLASH_PAGE_SIZE INTERNAL_FLASH_SECTOR_SIZE
  36. #define FLASH_PAGES (flashSize/FLASH_PAGE_SIZE)
  37. #define READ_BLOCKSIZE 1024
  38. #define WRITE_BLOCKSIZE 2048
  39. #define DICTIONARY_WINDOW 16384
  40. #define WORDSIZE (sizeof(int))
  41. #define BITS_PER_WORD 32
  42. #define WRITE_BLOCKS ((DICTIONARY_WINDOW/WRITE_BLOCKSIZE)+1)
  43. #define WRITE_BLOCK_WORDS (WRITE_BLOCKSIZE/WORDSIZE)
  44. struct INPUT {
  45. int fd;
  46. int len;
  47. uint8_t block[READ_BLOCKSIZE];
  48. uint8_t *inPtr;
  49. int bytesRead;
  50. int left;
  51. void *inflate_state;
  52. } *in;
  53. typedef struct {
  54. uint8_t byte[WRITE_BLOCKSIZE];
  55. } outBlock;
  56. struct OUTPUT {
  57. lua_State *L;
  58. lu_int32 flash_sig;
  59. int len;
  60. outBlock *block[WRITE_BLOCKS];
  61. outBlock buffer;
  62. int ndx;
  63. uint32_t crc;
  64. void (*fullBlkCB) (void);
  65. int flashLen;
  66. int flagsLen;
  67. int flagsNdx;
  68. uint32_t *flags;
  69. const char *error;
  70. } *out;
  71. #ifdef NODE_DEBUG
  72. void dumpStrt(stringtable *tb, const char *type) {
  73. int i,j;
  74. GCObject *o;
  75. NODE_DBG("\nDumping %s String table\n\n========================\n", type);
  76. NODE_DBG("No of elements: %d\nSize of table: %d\n", tb->nuse, tb->size);
  77. for (i=0; i<tb->size; i++)
  78. for(o = tb->hash[i], j=0; o; (o=o->gch.next), j++ ) {
  79. TString *ts =cast(TString *, o);
  80. NODE_DBG("%5d %5d %08x %08x %5d %s\n",
  81. i, j, (size_t) ts, ts->tsv.hash, ts->tsv.len, getstr(ts));
  82. }
  83. }
  84. LUA_API void dumpStrings(lua_State *L) {
  85. dumpStrt(&G(L)->strt, "RAM");
  86. if (G(L)->ROstrt.hash)
  87. dumpStrt(&G(L)->ROstrt, "ROM");
  88. }
  89. #endif
  90. /* =====================================================================================
  91. * The next 4 functions: flashPosition, flashSetPosition, flashBlock and flashErase
  92. * wrap writing to flash. The last two are platform dependent. Also note that any
  93. * writes are suppressed if the global writeToFlash is false. This is used in
  94. * phase I where the pass is used to size the structures in flash.
  95. */
  96. static char *flashPosition(void){
  97. return flashAddr + curOffset;
  98. }
  99. static char *flashSetPosition(uint32_t offset){
  100. NODE_DBG("flashSetPosition(%04x)\n", offset);
  101. curOffset = offset;
  102. return flashPosition();
  103. }
  104. static char *flashBlock(const void* b, size_t size) {
  105. void *cur = flashPosition();
  106. NODE_DBG("flashBlock((%04x),%p,%04x)\n", curOffset,b,size);
  107. lua_assert(ALIGN_BITS(b) == 0 && ALIGN_BITS(size) == 0);
  108. platform_flash_write(b, flashAddrPhys+curOffset, size);
  109. curOffset += size;
  110. return cur;
  111. }
  112. static void flashErase(uint32_t start, uint32_t end){
  113. int i;
  114. if (start == -1) start = FLASH_PAGES - 1;
  115. if (end == -1) end = FLASH_PAGES - 1;
  116. NODE_DBG("flashErase(%04x,%04x)\n", flashSector+start, flashSector+end);
  117. for (i = start; i<=end; i++)
  118. platform_flash_erase_sector( flashSector + i );
  119. }
  120. /* =====================================================================================
  121. * luaN_init() is exported via lflash.h.
  122. * The first is the startup hook used in lstate.c and the last two are
  123. * implementations of the node.flash API calls.
  124. */
  125. /*
  126. * Hook in lstate.c:f_luaopen() to set up ROstrt and ROpvmain if needed
  127. */
  128. LUAI_FUNC void luaN_init (lua_State *L) {
  129. flashSize = platform_flash_get_partition (NODEMCU_LFS0_PARTITION, &flashAddrPhys);
  130. if (flashSize == 0) {
  131. return; // Nothing to do if the size is zero
  132. }
  133. G(L)->LFSsize = flashSize;
  134. flashAddr = cast(char *, platform_flash_phys2mapped(flashAddrPhys));
  135. flashSector = platform_flash_get_sector_of_address(flashAddrPhys);
  136. FlashHeader *fh = cast(FlashHeader *, flashAddr);
  137. curOffset = 0;
  138. /*
  139. * For the LFS to be valid, its signature has to be correct for this build
  140. * variant, the ROhash and main proto fields must be defined and the main proto
  141. * address be within the LFS address bounds. (This last check is primarily to
  142. * detect the direct imaging of an absolute LFS with the wrong base address.
  143. */
  144. if (fh->flash_sig == 0 || fh->flash_sig == ~0 ) {
  145. NODE_ERR("No LFS image loaded\n");
  146. return;
  147. }
  148. if ((fh->flash_sig & (~FLASH_SIG_ABSOLUTE)) != FLASH_SIG ) {
  149. NODE_ERR("Flash sig not correct: 0x%08x vs 0x%08x\n",
  150. fh->flash_sig & (~FLASH_SIG_ABSOLUTE), FLASH_SIG);
  151. return;
  152. }
  153. if (fh->pROhash == ALL_SET ||
  154. ((fh->mainProto - cast(FlashAddr, fh)) >= fh->flash_size)) {
  155. NODE_ERR("Flash size check failed: 0x%08x vs 0xFFFFFFFF; 0x%08x >= 0x%08x\n",
  156. fh->pROhash, fh->mainProto - cast(FlashAddr, fh), fh->flash_size);
  157. return;
  158. }
  159. G(L)->ROstrt.hash = cast(GCObject **, fh->pROhash);
  160. G(L)->ROstrt.nuse = fh->nROuse ;
  161. G(L)->ROstrt.size = fh->nROsize;
  162. G(L)->ROpvmain = cast(Proto *,fh->mainProto);
  163. }
  164. //extern void software_reset(void);
  165. static int loadLFS (lua_State *L);
  166. static int loadLFSgc (lua_State *L);
  167. static void procFirstPass (void);
  168. /* lua_lfsreload() and lua_lfsindex() are exported via lua.h */
  169. /*
  170. * Library function called by node.flashreload(filename).
  171. */
  172. LUALIB_API int lua_lfsreload (lua_State *L) {
  173. const char *fn = lua_tostring(L, 1), *msg = "";
  174. int status;
  175. if (G(L)->LFSsize == 0) {
  176. lua_pushstring(L, "No LFS partition allocated");
  177. return 1;
  178. }
  179. /*
  180. * Do a protected call of loadLFS.
  181. *
  182. * - This will normally rewrite the LFS and reboot, with no return.
  183. * - If an error occurs then it is sent to the UART.
  184. * - If this occured in the 1st pass, the previous LFS is unchanged so it is
  185. * safe to return to the calling Lua.
  186. * - If in the 1st pass, then the ESP is rebooted.
  187. */
  188. status = lua_cpcall(L, &loadLFS, cast(void *,fn));
  189. if (!out || out->fullBlkCB == procFirstPass) {
  190. /*
  191. * Never entered the 2nd pass, so it is safe to return the error. Note
  192. * that I've gone to some trouble to ensure that all dynamically allocated
  193. * working areas have been freed, so that we have no memory leaks.
  194. */
  195. if (status == LUA_ERRMEM)
  196. msg = "Memory allocation error";
  197. else if (out && out->error)
  198. msg = out->error;
  199. else
  200. msg = "Unknown Error";
  201. /* We can clean up and return error */
  202. lua_cpcall(L, &loadLFSgc, NULL);
  203. lua_settop(L, 0);
  204. lua_pushstring(L, msg);
  205. return 1;
  206. }
  207. if (status == 0) {
  208. /* Successful LFS rewrite */
  209. msg = "LFS region updated. Restarting.";
  210. } else {
  211. /* We have errored during the second pass so clear the LFS and reboot */
  212. if (status == LUA_ERRMEM)
  213. msg = "Memory allocation error";
  214. else if (out->error)
  215. msg = out->error;
  216. else
  217. msg = "Unknown Error";
  218. flashErase(0,-1);
  219. }
  220. NODE_ERR(msg);
  221. while (1) {} // Force WDT as the ROM software_reset() doesn't seem to work
  222. return 0;
  223. }
  224. /*
  225. * If the arg is a valid LFS module name then return the LClosure
  226. * pointing to it. Otherwise return:
  227. * - The Unix time that the LFS was built
  228. * - The base address and length of the LFS
  229. * - An array of the module names in the LFS
  230. */
  231. LUAI_FUNC int lua_lfsindex (lua_State *L) {
  232. int n = lua_gettop(L);
  233. /* Return nil + the LFS base address if the LFS size > 0 and it isn't loaded */
  234. if (!(G(L)->ROpvmain)) {
  235. lua_settop(L, 0);
  236. lua_pushnil(L);
  237. if (G(L)->LFSsize) {
  238. lua_pushinteger(L, (lua_Integer) flashAddr);
  239. lua_pushinteger(L, flashAddrPhys);
  240. lua_pushinteger(L, G(L)->LFSsize);
  241. return 4;
  242. } else {
  243. return 1;
  244. }
  245. }
  246. /* Push the LClosure of the LFS index function */
  247. Closure *cl = luaF_newLclosure(L, 0, hvalue(gt(L)));
  248. cl->l.p = G(L)->ROpvmain;
  249. lua_settop(L, n+1);
  250. setclvalue(L, L->top-1, cl);
  251. /* Move it infront of the arguments and call the index function */
  252. lua_insert(L, 1);
  253. lua_call(L, n, LUA_MULTRET);
  254. /* Return it if the response if a single value (the function) */
  255. if (lua_gettop(L) == 1)
  256. return 1;
  257. lua_assert(lua_gettop(L) == 2);
  258. /* Otherwise add the base address of the LFS, and its size bewteen the */
  259. /* Unix time and the module list, then return all 4 params. */
  260. lua_pushinteger(L, (lua_Integer) flashAddr);
  261. lua_insert(L, 2);
  262. lua_pushinteger(L, flashAddrPhys);
  263. lua_insert(L, 3);
  264. lua_pushinteger(L, cast(FlashHeader *, flashAddr)->flash_size);
  265. lua_insert(L, 4);
  266. return 5;
  267. }
  268. /* =====================================================================================
  269. * The following routines use my uzlib which was based on pfalcon's inflate and
  270. * deflate routines. The standard NodeMCU make also makes two host tools uz_zip
  271. * and uz_unzip which also use these and luac.cross uses the deflate. As discussed
  272. * below, The main action routine loadLFS() calls uzlib_inflate() to do the actual
  273. * stream inflation but uses three supplied CBs to abstract input and output
  274. * stream handling.
  275. *
  276. * ESP8266 RAM limitations and heap fragmentation are a key implementation
  277. * constraint and hence these routines use a number of ~2K buffers (11) as
  278. * working storage.
  279. *
  280. * The inflate is done twice, in order to limit storage use and avoid forward /
  281. * backward reference issues. However this has a major advantage that the LFS
  282. * is scanned with the headers, CRC, etc. validated BEFORE the write to flash
  283. * is started, so the only real chance of failure during the second pass
  284. * write is if a power fail occurs during the pass.
  285. */
  286. static void flash_error(const char *err) {
  287. if (out)
  288. out->error = err;
  289. if (in && in->inflate_state)
  290. uz_free(in->inflate_state);
  291. lua_pushnil(out->L); /* can't use it on a cpcall anyway */
  292. lua_error(out->L);
  293. }
  294. /*
  295. * uzlib_inflate does a stream inflate on an RFC 1951 encoded data stream.
  296. * It uses three application-specific CBs passed in the call to do the work:
  297. *
  298. * - get_byte() CB to return next byte in input stream
  299. * - put_byte() CB to output byte to output buffer
  300. * - recall_byte() CB to output byte to retrieve a historic byte from
  301. * the output buffer.
  302. *
  303. * Note that put_byte() also triggers secondary CBs to do further processing.
  304. */
  305. static uint8_t get_byte (void) {
  306. if (--in->left < 0) {
  307. /* Read next input block */
  308. int remaining = in->len - in->bytesRead;
  309. int wanted = remaining >= READ_BLOCKSIZE ? READ_BLOCKSIZE : remaining;
  310. if (vfs_read(in->fd, in->block, wanted) != wanted)
  311. flash_error("read error on LFS image file");
  312. system_soft_wdt_feed();
  313. in->bytesRead += wanted;
  314. in->inPtr = in->block;
  315. in->left = wanted-1;
  316. }
  317. return *in->inPtr++;
  318. }
  319. static void put_byte (uint8_t value) {
  320. int offset = out->ndx % WRITE_BLOCKSIZE; /* counts from 0 */
  321. out->block[0]->byte[offset++] = value;
  322. out->ndx++;
  323. if (offset == WRITE_BLOCKSIZE || out->ndx == out->len) {
  324. if (out->fullBlkCB)
  325. out->fullBlkCB();
  326. /* circular shift the block pointers (redundant on last block, but so what) */
  327. outBlock *nextBlock = out->block[WRITE_BLOCKS - 1];
  328. memmove(out->block+1, out->block, (WRITE_BLOCKS-1)*sizeof(void*));
  329. out->block[0] = nextBlock ;
  330. }
  331. }
  332. static uint8_t recall_byte (unsigned offset) {
  333. if(offset > DICTIONARY_WINDOW || offset >= out->ndx)
  334. flash_error("invalid dictionary offset on inflate");
  335. /* ndx starts at 1. Need relative to 0 */
  336. unsigned n = out->ndx - offset;
  337. unsigned pos = n % WRITE_BLOCKSIZE;
  338. unsigned blockNo = out->ndx / WRITE_BLOCKSIZE - n / WRITE_BLOCKSIZE;
  339. return out->block[blockNo]->byte[pos];
  340. }
  341. /*
  342. * On the first pass the break index is set to call this process at the end
  343. * of each completed output buffer.
  344. * - On the first call, the Flash Header is checked.
  345. * - On each call the CRC is rolled up for that buffer.
  346. * - Once the flags array is in-buffer this is also captured.
  347. * This logic is slightly complicated by the last buffer is typically short.
  348. */
  349. void procFirstPass (void) {
  350. int len = (out->ndx % WRITE_BLOCKSIZE) ?
  351. out->ndx % WRITE_BLOCKSIZE : WRITE_BLOCKSIZE;
  352. if (out->ndx <= WRITE_BLOCKSIZE) {
  353. /* Process the flash header and cache the FlashHeader fields we need */
  354. FlashHeader *fh = cast(FlashHeader *, out->block[0]);
  355. out->flashLen = fh->flash_size; /* in bytes */
  356. out->flagsLen = (out->len-fh->flash_size)/WORDSIZE; /* in words */
  357. out->flash_sig = fh->flash_sig;
  358. if ((fh->flash_sig & FLASH_FORMAT_MASK) != FLASH_FORMAT_VERSION)
  359. flash_error("Incorrect LFS header version");
  360. if ((fh->flash_sig & FLASH_SIG_B2_MASK) != FLASH_SIG_B2)
  361. flash_error("Incorrect LFS build type");
  362. if ((fh->flash_sig & ~FLASH_SIG_ABSOLUTE) != FLASH_SIG)
  363. flash_error("incorrect LFS header signature");
  364. if (fh->flash_size > flashSize)
  365. flash_error("LFS Image too big for configured LFS region");
  366. if ((fh->flash_size & 0x3) ||
  367. fh->flash_size > flashSize ||
  368. out->flagsLen != 1 + (out->flashLen/WORDSIZE - 1) / BITS_PER_WORD)
  369. flash_error("LFS length mismatch");
  370. out->flags = luaM_newvector(out->L, out->flagsLen, unsigned);
  371. }
  372. /* update running CRC */
  373. out->crc = uzlib_crc32(out->block[0], len, out->crc);
  374. /* copy out any flag vector */
  375. if (out->ndx > out->flashLen) {
  376. int start = out->flashLen - (out->ndx - len);
  377. if (start < 0) start = 0;
  378. memcpy(out->flags + out->flagsNdx, out->block[0]->byte + start, len - start);
  379. out->flagsNdx += (len -start) / WORDSIZE; /* flashLen and len are word aligned */
  380. }
  381. }
  382. void procSecondPass (void) {
  383. /*
  384. * The length rules are different for the second pass since this only processes
  385. * upto the flashLen and not the full image. This also works in word units.
  386. * (We've already validated these are word multiples.)
  387. */
  388. int i, len = (out->ndx > out->flashLen) ?
  389. (out->flashLen % WRITE_BLOCKSIZE) / WORDSIZE :
  390. WRITE_BLOCKSIZE / WORDSIZE;
  391. uint32_t *buf = (uint32_t *) out->buffer.byte;
  392. uint32_t flags = 0;
  393. /*
  394. * Relocate all the addresses tagged in out->flags. This can't be done in
  395. * place because the out->blocks are still in use as dictionary content so
  396. * first copy the block to a working buffer and do the relocation in this.
  397. */
  398. memcpy(out->buffer.byte, out->block[0]->byte, WRITE_BLOCKSIZE);
  399. for (i=0; i<len; i++,flags>>=1 ) {
  400. if ((i&31)==0)
  401. flags = out->flags[out->flagsNdx++];
  402. if (flags&1)
  403. buf[i] = WORDSIZE*buf[i] + cast(uint32_t, flashAddr);
  404. }
  405. /*
  406. * On first block, set the flash_sig has the in progress bit set and this
  407. * is not cleared until end.
  408. */
  409. if (out->ndx <= WRITE_BLOCKSIZE)
  410. buf[0] = out->flash_sig | FLASH_SIG_IN_PROGRESS;
  411. flashBlock(buf, len*WORDSIZE);
  412. if (out->ndx >= out->flashLen) {
  413. /* we're done so disable CB and rewrite flash sig to complete flash */
  414. flashSetPosition(0);
  415. flashBlock(&out->flash_sig, WORDSIZE);
  416. out->fullBlkCB = NULL;
  417. }
  418. }
  419. /*
  420. * loadLFS)() is protected called from luaN_reload_reboot so that it can recover
  421. * from out of memory and other thrown errors. loadLFSgc() GCs any resources.
  422. */
  423. static int loadLFS (lua_State *L) {
  424. const char *fn = cast(const char *, lua_touserdata(L, 1));
  425. int i, res;
  426. uint32_t crc;
  427. /* Allocate and zero in and out structures */
  428. in = NULL; out = NULL;
  429. in = luaM_new(L, struct INPUT);
  430. memset(in, 0, sizeof(*in));
  431. out = luaM_new(L, struct OUTPUT);
  432. memset(out, 0, sizeof(*out));
  433. out->L = L;
  434. out->fullBlkCB = procFirstPass;
  435. out->crc = ~0;
  436. /* Open LFS image/ file, read unpacked length from last 4 byte and rewind */
  437. if (!(in->fd = vfs_open(fn, "r")))
  438. flash_error("LFS image file not found");
  439. in->len = vfs_size(in->fd);
  440. if (in->len <= 200 || /* size of an empty luac output */
  441. vfs_lseek(in->fd, in->len-4, VFS_SEEK_SET) != in->len-4 ||
  442. vfs_read(in->fd, &out->len, sizeof(unsigned)) != sizeof(unsigned))
  443. flash_error("read error on LFS image file");
  444. vfs_lseek(in->fd, 0, VFS_SEEK_SET);
  445. /* Allocate the out buffers */
  446. for(i = 0; i <= WRITE_BLOCKS; i++)
  447. out->block[i] = luaM_new(L, outBlock);
  448. /* first inflate pass */
  449. if (uzlib_inflate (get_byte, put_byte, recall_byte,
  450. in->len, &crc, &in->inflate_state) < 0)
  451. flash_error("read error on LFS image file");
  452. if (crc != ~out->crc)
  453. flash_error("checksum error on LFS image file");
  454. out->fullBlkCB = procSecondPass;
  455. out->flagsNdx = 0;
  456. out->ndx = 0;
  457. in->bytesRead = in->left = 0;
  458. /*
  459. * Once we have completed the 1st pass then the LFS image has passed the
  460. * basic signature, crc and length checks, so now we can reset the counts
  461. * to do the actual write to flash on the second pass.
  462. */
  463. vfs_lseek(in->fd, 0, VFS_SEEK_SET);
  464. flashErase(0,(out->flashLen - 1)/FLASH_PAGE_SIZE);
  465. flashSetPosition(0);
  466. if ((res = uzlib_inflate(get_byte, put_byte, recall_byte,
  467. in->len, &crc, &in->inflate_state)) != UZLIB_DONE) {
  468. const char *err[] = {"Data_error during decompression",
  469. "Chksum_error during decompression",
  470. "Dictionary error during decompression",
  471. "Memory_error during decompression"};
  472. flash_error(err[UZLIB_DATA_ERROR - res]);
  473. }
  474. return 0;
  475. }
  476. static int loadLFSgc (lua_State *L) {
  477. int i;
  478. if (out) {
  479. for (i = 0; i < WRITE_BLOCKS; i++)
  480. if (out->block[i])
  481. luaM_free(L, out->block[i]);
  482. if (out->flags)
  483. luaM_freearray(L, out->flags, out->flagsLen, uint32_t);
  484. luaM_free(L, out);
  485. }
  486. if (in) {
  487. if (in->fd)
  488. vfs_close(in->fd);
  489. luaM_free(L, in);
  490. }
  491. return 0;
  492. }