lflash.c 18 KB

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