lflash.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. /*
  2. ** $Id: lflash.c
  3. ** See Copyright Notice in lua.h
  4. */
  5. #define lflash_c
  6. #define LUA_CORE
  7. #define LUAC_CROSS_FILE
  8. #include "lua.h"
  9. #include "lobject.h"
  10. #include "lauxlib.h"
  11. #include "lstate.h"
  12. #include "lfunc.h"
  13. #include "lflash.h"
  14. #include "platform.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 %1s %s\n",
  81. i, j, (size_t) ts, ts->tsv.hash, ts->tsv.len,
  82. ts_isreadonly(ts) ? "R" : " ", getstr(ts));
  83. }
  84. }
  85. LUA_API void dumpStrings(lua_State *L) {
  86. dumpStrt(&G(L)->strt, "RAM");
  87. if (G(L)->ROstrt.hash)
  88. dumpStrt(&G(L)->ROstrt, "ROM");
  89. }
  90. #endif
  91. /* =====================================================================================
  92. * The next 4 functions: flashPosition, flashSetPosition, flashBlock and flashErase
  93. * wrap writing to flash. The last two are platform dependent. Also note that any
  94. * writes are suppressed if the global writeToFlash is false. This is used in
  95. * phase I where the pass is used to size the structures in flash.
  96. */
  97. static char *flashPosition(void){
  98. return flashAddr + curOffset;
  99. }
  100. static char *flashSetPosition(uint32_t offset){
  101. NODE_DBG("flashSetPosition(%04x)\n", offset);
  102. curOffset = offset;
  103. return flashPosition();
  104. }
  105. static char *flashBlock(const void* b, size_t size) {
  106. void *cur = flashPosition();
  107. NODE_DBG("flashBlock((%04x),%08x,%04x)\n", curOffset,b,size);
  108. lua_assert(ALIGN_BITS(b) == 0 && ALIGN_BITS(size) == 0);
  109. platform_flash_write(b, flashAddrPhys+curOffset, size);
  110. curOffset += size;
  111. return cur;
  112. }
  113. static void flashErase(uint32_t start, uint32_t end){
  114. int i;
  115. if (start == -1) start = FLASH_PAGES - 1;
  116. if (end == -1) end = FLASH_PAGES - 1;
  117. NODE_DBG("flashErase(%04x,%04x)\n", flashSector+start, flashSector+end);
  118. for (i = start; i<=end; i++)
  119. platform_flash_erase_sector( flashSector + i );
  120. }
  121. /* =====================================================================================
  122. * luaN_init(), luaN_reload_reboot() and luaN_index() are exported via lflash.h.
  123. * The first is the startup hook used in lstate.c and the last two are
  124. * implementations of the node.flash API calls.
  125. */
  126. /*
  127. * Hook in lstate.c:f_luaopen() to set up ROstrt and ROpvmain if needed
  128. */
  129. LUAI_FUNC void luaN_init (lua_State *L) {
  130. flashSize = platform_flash_get_partition (NODEMCU_LFS0_PARTITION, &flashAddrPhys);
  131. if (flashSize == 0) {
  132. return; // Nothing to do if the size is zero
  133. }
  134. G(L)->LFSsize = flashSize;
  135. flashAddr = cast(char *, platform_flash_phys2mapped(flashAddrPhys));
  136. flashSector = platform_flash_get_sector_of_address(flashAddrPhys);
  137. FlashHeader *fh = cast(FlashHeader *, flashAddr);
  138. curOffset = 0;
  139. /*
  140. * For the LFS to be valid, its signature has to be correct for this build
  141. * variant, the ROhash and main proto fields must be defined and the main proto
  142. * address be within the LFS address bounds. (This last check is primarily to
  143. * detect the direct imaging of an absolute LFS with the wrong base address.
  144. */
  145. if (fh->flash_sig == 0 || fh->flash_sig == ~0 ) {
  146. NODE_ERR("No LFS image loaded\n");
  147. return;
  148. }
  149. if ((fh->flash_sig & (~FLASH_SIG_ABSOLUTE)) != FLASH_SIG ) {
  150. NODE_ERR("Flash sig not correct: 0x%08x vs 0x%08x\n",
  151. fh->flash_sig & (~FLASH_SIG_ABSOLUTE), FLASH_SIG);
  152. return;
  153. }
  154. if (fh->pROhash == ALL_SET ||
  155. ((fh->mainProto - cast(FlashAddr, fh)) >= fh->flash_size)) {
  156. NODE_ERR("Flash size check failed: 0x%08x vs 0xFFFFFFFF; 0x%08x >= 0x%08x\n",
  157. fh->pROhash, fh->mainProto - cast(FlashAddr, fh), fh->flash_size);
  158. return;
  159. }
  160. G(L)->ROstrt.hash = cast(GCObject **, fh->pROhash);
  161. G(L)->ROstrt.nuse = fh->nROuse ;
  162. G(L)->ROstrt.size = fh->nROsize;
  163. G(L)->ROpvmain = cast(Proto *,fh->mainProto);
  164. }
  165. //extern void software_reset(void);
  166. static int loadLFS (lua_State *L);
  167. static int loadLFSgc (lua_State *L);
  168. static void procFirstPass (void);
  169. /*
  170. * Library function called by node.flashreload(filename).
  171. */
  172. LUALIB_API int luaN_reload_reboot (lua_State *L) {
  173. // luaL_dbgbreak();
  174. const char *fn = lua_tostring(L, 1), *msg = "";
  175. int status;
  176. if (G(L)->LFSsize == 0) {
  177. lua_pushstring(L, "No LFS partition allocated");
  178. return 1;
  179. }
  180. /*
  181. * Do a protected call of loadLFS.
  182. *
  183. * - This will normally rewrite the LFS and reboot, with no return.
  184. * - If an error occurs then it is sent to the UART.
  185. * - If this occured in the 1st pass, the previous LFS is unchanged so it is
  186. * safe to return to the calling Lua.
  187. * - If in the 1st pass, then the ESP is rebooted.
  188. */
  189. status = lua_cpcall(L, &loadLFS, cast(void *,fn));
  190. if (!out || out->fullBlkCB == procFirstPass) {
  191. /*
  192. * Never entered the 2nd pass, so it is safe to return the error. Note
  193. * that I've gone to some trouble to ensure that all dynamically allocated
  194. * working areas have been freed, so that we have no memory leaks.
  195. */
  196. if (status == LUA_ERRMEM)
  197. msg = "Memory allocation error";
  198. else if (out && out->error)
  199. msg = out->error;
  200. else
  201. msg = "Unknown Error";
  202. /* We can clean up and return error */
  203. lua_cpcall(L, &loadLFSgc, NULL);
  204. lua_settop(L, 0);
  205. lua_pushstring(L, msg);
  206. return 1;
  207. }
  208. if (status == 0) {
  209. /* Successful LFS rewrite */
  210. msg = "LFS region updated. Restarting.";
  211. } else {
  212. /* We have errored during the second pass so clear the LFS and reboot */
  213. if (status == LUA_ERRMEM)
  214. msg = "Memory allocation error";
  215. else if (out->error)
  216. msg = out->error;
  217. else
  218. msg = "Unknown Error";
  219. flashErase(0,-1);
  220. }
  221. NODE_ERR(msg);
  222. while (1) {} // Force WDT as the ROM software_reset() doesn't seem to work
  223. return 0;
  224. }
  225. /*
  226. * If the arg is a valid LFS module name then return the LClosure
  227. * pointing to it. Otherwise return:
  228. * - The Unix time that the LFS was built
  229. * - The base address and length of the LFS
  230. * - An array of the module names in the LFS
  231. */
  232. LUAI_FUNC int luaN_index (lua_State *L) {
  233. int n = lua_gettop(L);
  234. /* Return nil + the LFS base address if the LFS size > 0 and it isn't loaded */
  235. if (!(G(L)->ROpvmain)) {
  236. lua_settop(L, 0);
  237. lua_pushnil(L);
  238. if (G(L)->LFSsize) {
  239. lua_pushinteger(L, (lua_Integer) flashAddr);
  240. lua_pushinteger(L, flashAddrPhys);
  241. lua_pushinteger(L, G(L)->LFSsize);
  242. return 4;
  243. } else {
  244. return 1;
  245. }
  246. }
  247. /* Push the LClosure of the LFS index function */
  248. Closure *cl = luaF_newLclosure(L, 0, hvalue(gt(L)));
  249. cl->l.p = G(L)->ROpvmain;
  250. lua_settop(L, n+1);
  251. setclvalue(L, L->top-1, cl);
  252. /* Move it infront of the arguments and call the index function */
  253. lua_insert(L, 1);
  254. lua_call(L, n, LUA_MULTRET);
  255. /* Return it if the response if a single value (the function) */
  256. if (lua_gettop(L) == 1)
  257. return 1;
  258. lua_assert(lua_gettop(L) == 2);
  259. /* Otherwise add the base address of the LFS, and its size bewteen the */
  260. /* Unix time and the module list, then return all 4 params. */
  261. lua_pushinteger(L, (lua_Integer) flashAddr);
  262. lua_insert(L, 2);
  263. lua_pushinteger(L, flashAddrPhys);
  264. lua_insert(L, 3);
  265. lua_pushinteger(L, cast(FlashHeader *, flashAddr)->flash_size);
  266. lua_insert(L, 4);
  267. return 5;
  268. }
  269. /* =====================================================================================
  270. * The following routines use my uzlib which was based on pfalcon's inflate and
  271. * deflate routines. The standard NodeMCU make also makes two host tools uz_zip
  272. * and uz_unzip which also use these and luac.cross uses the deflate. As discussed
  273. * below, The main action routine loadLFS() calls uzlib_inflate() to do the actual
  274. * stream inflation but uses three supplied CBs to abstract input and output
  275. * stream handling.
  276. *
  277. * ESP8266 RAM limitations and heap fragmentation are a key implementation
  278. * constraint and hence these routines use a number of ~2K buffers (11) as
  279. * working storage.
  280. *
  281. * The inflate is done twice, in order to limit storage use and avoid forward /
  282. * backward reference issues. However this has a major advantage that the LFS
  283. * is scanned with the headers, CRC, etc. validated BEFORE the write to flash
  284. * is started, so the only real chance of failure during the second pass
  285. * write is if a power fail occurs during the pass.
  286. */
  287. static void flash_error(const char *err) {
  288. if (out)
  289. out->error = err;
  290. if (in && in->inflate_state)
  291. uz_free(in->inflate_state);
  292. lua_pushnil(out->L); /* can't use it on a cpcall anyway */
  293. lua_error(out->L);
  294. }
  295. /*
  296. * uzlib_inflate does a stream inflate on an RFC 1951 encoded data stream.
  297. * It uses three application-specific CBs passed in the call to do the work:
  298. *
  299. * - get_byte() CB to return next byte in input stream
  300. * - put_byte() CB to output byte to output buffer
  301. * - recall_byte() CB to output byte to retrieve a historic byte from
  302. * the output buffer.
  303. *
  304. * Note that put_byte() also triggers secondary CBs to do further processing.
  305. */
  306. static uint8_t get_byte (void) {
  307. if (--in->left < 0) {
  308. /* Read next input block */
  309. int remaining = in->len - in->bytesRead;
  310. int wanted = remaining >= READ_BLOCKSIZE ? READ_BLOCKSIZE : remaining;
  311. if (vfs_read(in->fd, in->block, wanted) != wanted)
  312. flash_error("read error on LFS image file");
  313. system_soft_wdt_feed();
  314. in->bytesRead += wanted;
  315. in->inPtr = in->block;
  316. in->left = wanted-1;
  317. }
  318. return *in->inPtr++;
  319. }
  320. static void put_byte (uint8_t value) {
  321. int offset = out->ndx % WRITE_BLOCKSIZE; /* counts from 0 */
  322. out->block[0]->byte[offset++] = value;
  323. out->ndx++;
  324. if (offset == WRITE_BLOCKSIZE || out->ndx == out->len) {
  325. if (out->fullBlkCB)
  326. out->fullBlkCB();
  327. /* circular shift the block pointers (redundant on last block, but so what) */
  328. outBlock *nextBlock = out->block[WRITE_BLOCKS - 1];
  329. memmove(out->block+1, out->block, (WRITE_BLOCKS-1)*sizeof(void*));
  330. out->block[0] = nextBlock ;
  331. }
  332. }
  333. static uint8_t recall_byte (unsigned offset) {
  334. if(offset > DICTIONARY_WINDOW || offset >= out->ndx)
  335. flash_error("invalid dictionary offset on inflate");
  336. /* ndx starts at 1. Need relative to 0 */
  337. unsigned n = out->ndx - offset;
  338. unsigned pos = n % WRITE_BLOCKSIZE;
  339. unsigned blockNo = out->ndx / WRITE_BLOCKSIZE - n / WRITE_BLOCKSIZE;
  340. return out->block[blockNo]->byte[pos];
  341. }
  342. /*
  343. * On the first pass the break index is set to call this process at the end
  344. * of each completed output buffer.
  345. * - On the first call, the Flash Header is checked.
  346. * - On each call the CRC is rolled up for that buffer.
  347. * - Once the flags array is in-buffer this is also captured.
  348. * This logic is slightly complicated by the last buffer is typically short.
  349. */
  350. void procFirstPass (void) {
  351. int len = (out->ndx % WRITE_BLOCKSIZE) ?
  352. out->ndx % WRITE_BLOCKSIZE : WRITE_BLOCKSIZE;
  353. if (out->ndx <= WRITE_BLOCKSIZE) {
  354. /* Process the flash header and cache the FlashHeader fields we need */
  355. FlashHeader *fh = cast(FlashHeader *, out->block[0]);
  356. out->flashLen = fh->flash_size; /* in bytes */
  357. out->flagsLen = (out->len-fh->flash_size)/WORDSIZE; /* in words */
  358. out->flash_sig = fh->flash_sig;
  359. if ((fh->flash_sig & FLASH_FORMAT_MASK) != FLASH_FORMAT_VERSION)
  360. flash_error("Incorrect LFS header version");
  361. if ((fh->flash_sig & FLASH_SIG_B2_MASK) != FLASH_SIG_B2)
  362. flash_error("Incorrect LFS build type");
  363. if ((fh->flash_sig & ~FLASH_SIG_ABSOLUTE) != FLASH_SIG)
  364. flash_error("incorrect LFS header signature");
  365. if (fh->flash_size > flashSize)
  366. flash_error("LFS Image too big for configured LFS region");
  367. if ((fh->flash_size & 0x3) ||
  368. fh->flash_size > flashSize ||
  369. out->flagsLen != 1 + (out->flashLen/WORDSIZE - 1) / BITS_PER_WORD)
  370. flash_error("LFS length mismatch");
  371. out->flags = luaM_newvector(out->L, out->flagsLen, unsigned);
  372. }
  373. /* update running CRC */
  374. out->crc = uzlib_crc32(out->block[0], len, out->crc);
  375. /* copy out any flag vector */
  376. if (out->ndx > out->flashLen) {
  377. int start = out->flashLen - (out->ndx - len);
  378. if (start < 0) start = 0;
  379. memcpy(out->flags + out->flagsNdx, out->block[0]->byte + start, len - start);
  380. out->flagsNdx += (len -start) / WORDSIZE; /* flashLen and len are word aligned */
  381. }
  382. }
  383. void procSecondPass (void) {
  384. /*
  385. * The length rules are different for the second pass since this only processes
  386. * upto the flashLen and not the full image. This also works in word units.
  387. * (We've already validated these are word multiples.)
  388. */
  389. int i, len = (out->ndx > out->flashLen) ?
  390. (out->flashLen % WRITE_BLOCKSIZE) / WORDSIZE :
  391. WRITE_BLOCKSIZE / WORDSIZE;
  392. uint32_t *buf = (uint32_t *) out->buffer.byte, 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_OK) {
  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. }