lflash.c 18 KB

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