rt_fota.c 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252
  1. /*
  2. * Copyright (c) 2006-2018, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2019-09-22 Warfalcon first version
  9. */
  10. #include <stdint.h>
  11. #include <stdio.h>
  12. #include <string.h>
  13. #include <rtthread.h>
  14. #include <rtdevice.h>
  15. #include <board.h>
  16. #include <fal.h>
  17. #include <tinycrypt.h>
  18. #include <fastlz.h>
  19. #include <quicklz.h>
  20. #include <rt_fota.h>
  21. #include <signal_led.h>
  22. #include "sys_config.h"
  23. #include "easyflash.h"
  24. #if defined(RT_USING_FINSH) && defined(FINSH_USING_MSH)
  25. #include <finsh.h>
  26. #include <shell.h>
  27. #endif
  28. #include <rt_fota.h>
  29. extern void HMI_WRITE(char *fmt,...);
  30. #define DBG_ENABLE
  31. #define DBG_SECTION_NAME "fota"
  32. #ifdef RT_FOTA_DEBUG
  33. #define DBG_LEVEL DBG_LOG
  34. #else
  35. #define DBG_LEVEL DBG_INFO
  36. #endif
  37. #define DBG_COLOR
  38. #include <rtdbg.h>
  39. #ifndef RT_FOTA_THREAD_STACK_SIZE
  40. #define RT_FOTA_THREAD_STACK_SIZE 4096
  41. #endif
  42. #ifndef RT_FOTA_THREAD_PRIORITY
  43. #define RT_FOTA_THREAD_PRIORITY (RT_THREAD_PRIORITY_MAX - 3)
  44. #endif
  45. #ifndef RT_FOTA_ALGO_BUFF_SIZE
  46. #define RT_FOTA_ALGO_BUFF_SIZE 2048 //2025-0428 CHANGE 2048
  47. #endif
  48. /**
  49. * AES256 encryption algorithm option
  50. */
  51. #ifndef RT_FOTA_ALGO_AES_IV
  52. #define RT_FOTA_ALGO_AES_IV "0123456789ABCDEF"
  53. #endif
  54. #ifndef RT_FOTA_ALGO_AES_KEY
  55. #define RT_FOTA_ALGO_AES_KEY "0123456789ABCDEF0123456789ABCDEF"
  56. #endif
  57. #ifndef RT_FOTA_BLOCK_HEADER_SIZE
  58. #define RT_FOTA_BLOCK_HEADER_SIZE 4
  59. #endif
  60. #ifndef RT_FOTA_CMPRS_BUFFER_SIZE
  61. #define RT_FOTA_CMPRS_BUFFER_SIZE 4096
  62. #endif
  63. #ifndef RT_FOTA_FASTLZ_BUFFER_PADDING
  64. #define RT_FOTA_FASTLZ_BUFFER_PADDING FASTLZ_BUFFER_PADDING(RT_FOTA_CMPRS_BUFFER_SIZE)
  65. #endif
  66. #ifndef RT_FOTA_QUICKLZ_BUFFER_PADDING
  67. #define RT_FOTA_QUICKLZ_BUFFER_PADDING QLZ_BUFFER_PADDING
  68. #endif
  69. #ifndef RT_FOTA_ENTER_SHELL_KEY
  70. #define RT_FOTA_ENTER_SHELL_KEY 0x0d
  71. #endif
  72. #ifndef RT_FOTA_GET_CHAR_WAITTIGN
  73. #define RT_FOTA_GET_CHAR_WAITTIGN (RT_TICK_PER_SECOND * 5)
  74. #endif
  75. #ifndef RT_FOTA_SIGNAL_LED_PIN
  76. #define RT_FOTA_SIGNAL_LED_PIN GET_PIN(B, 3)
  77. #endif
  78. #ifndef RT_FOTA_SIGNAL_LED_THREAD_STACK_SIZE
  79. #define RT_FOTA_SIGNAL_LED_THREAD_STACK_SIZE 1024
  80. #endif
  81. #ifndef RT_FOTA_SIGNAL_LED_THREAD_PRIORITY
  82. #define RT_FOTA_SIGNAL_LED_THREAD_PRIORITY (RT_THREAD_PRIORITY_MAX - 4)
  83. #endif
  84. /* For signal led */
  85. static led_t *signal_led = NULL;
  86. static led_mem_opreation_t signal_led_mem_op;
  87. const char *led_shell_mode = "500,500,"; /* 1Hz ��˸ */
  88. const char *led_upgrade_mode = "50,50,"; /* 10Hz ��˸ */
  89. const char *led_off_mode = "0,100,"; /* ���� */
  90. const char *led_on_mode = "100,0,"; /* ���� */
  91. static int stop_in_bootloader=0;
  92. /* ===================== v1.3.0 升级回滚机制 ===================== */
  93. /* RTC 备份寄存器 DR2 状态约定:
  94. * 0x0000 —— APP 启动成功:Application_CBD 的 main() 启动后立即写入,
  95. * 表示 bootloader 本次"启动尝试"已被 APP 确认;
  96. * 0x5AA5 —— 升级请求:应用侧 JSONRPC "update" 指令写入,bootloader
  97. * 读取后清 0 并停留执行 ymodem 升级;
  98. * 0xDEAD —— 启动尝试标记:bootloader 跳转 APP 前写入;若复位进入
  99. * bootloader 后该值仍在(或为其它非 0 值),说明 APP 未运行
  100. * 到清零处(未正常启动),将从 df_area 备份回滚 APP 固件。
  101. * 说明:DR2 为 16 位,位于 BKP_BASE + 4*2,与 Application_CBD 的
  102. * main.c / dtu_uart2.c 访问方式配对。 */
  103. #define RT_FOTA_YMODEM_REQ_BKP_MAGIC 0x5AA5
  104. #define RT_FOTA_BOOT_TRY_BKP_MAGIC 0xDEAD
  105. /* df_area 备份格式:
  106. * [0, 4KB) —— rt_fota_backup_head_t 头(magic + 长度 + CRC32),
  107. * 头部有效即代表存在有效备份;
  108. * [4KB, 4KB + data_len) —— APP 分区镜像(裸数据,恢复时原样写回)。
  109. * 写入顺序:先失效旧头 -> 写数据 -> 最后写头,任一步骤掉电都不会残留
  110. * 半新半旧的"有效备份"。 */
  111. #define RT_FOTA_BACKUP_MAGIC 0x46424B31 /* "FBK1" */
  112. #define RT_FOTA_BACKUP_HEAD_RSV 4096 /* 头部预留(独占首扇区) */
  113. #define RT_FOTA_BACKUP_BLK_SIZE 4096
  114. typedef struct
  115. {
  116. rt_uint32_t magic; /* RT_FOTA_BACKUP_MAGIC */
  117. rt_uint32_t data_len; /* 备份数据长度(字节) */
  118. rt_uint32_t data_crc; /* 备份数据 CRC32(rt_fota_crc 语义) */
  119. rt_uint32_t head_crc; /* 头部前 12 字节 CRC32 */
  120. } rt_fota_backup_head_t;
  121. /* 使能 PWR/BKP 时钟并解除备份域写访问保护(幂等,可重复调用) */
  122. static void rt_fota_bkp_access_enable(void)
  123. {
  124. __HAL_RCC_PWR_CLK_ENABLE();
  125. __HAL_RCC_BKP_CLK_ENABLE();
  126. HAL_PWR_EnableBkUpAccess();
  127. }
  128. static rt_uint16_t rt_fota_bkp_dr2_read(void)
  129. {
  130. rt_fota_bkp_access_enable();
  131. return *(__IO uint16_t *)(BKP_BASE + 4 * 2);
  132. }
  133. static void rt_fota_bkp_dr2_write(rt_uint16_t value)
  134. {
  135. rt_fota_bkp_access_enable();
  136. *(__IO uint16_t *)(BKP_BASE + 4 * 2) = value;
  137. }
  138. /* ===================== 长耗时 Flash 操作的看门狗喂狗 =====================
  139. * 背景:IWDG 由 syswatch 在启动阶段开启(SYSWATCH_WDT_TIMEOUT=10s、LSI/256 分频),
  140. * 一旦启动就无法停止,只能靠喂狗续命。而备份/恢复/擦除原来都是"整块"交给 FAL:
  141. * fal_partition_erase(df_area, 4KB, 312KB) 在 NOR 上要逐 4KB 扇区擦 78 次,
  142. * W25Q 单扇区擦除典型 45ms、最坏 400ms —— 一次调用可能 3.5s(典型)/ 31s(最坏),
  143. * 中途没有任何喂狗机会,10s 超时必然复位(现象:备份/擦除做到一半板子重启,
  144. * 重启后 DR2 残留 0xDEAD 还会触发回滚,进一步放大问题)。
  145. * 对策:① rt_fota_wdt_feed() 供所有长耗时循环调用;
  146. * ② 大块擦除拆成 RT_FOTA_BACKUP_BLK_SIZE(4KB) 分块,每块后喂一次;
  147. * ③ 读/写循环每块喂一次。
  148. *
  149. * 安全:只有确认 IWDG 已启动(PR/RLR 非复位值 0)时才喂。IWDG 只要写入一次 KR
  150. * (0xAAAA)就会启动且无法停止,若在 bootloader 里误喂一个"未启动"的 IWDG,
  151. * 会把一个 10s 看门狗凭空带进 APP 运行期,造成随机复位。
  152. */
  153. #define RT_FOTA_WDT_DEV_NAME "wdt"
  154. void rt_fota_wdt_feed(void)
  155. {
  156. static rt_device_t wdt_dev = RT_NULL;
  157. /* IWDG 未启动时 PR/RLR 保持复位值 0,直接返回:只要写一次 KR(0xAAAA)
  158. * 就会启动看门狗且无法停止,绝不能对"未启动"的 IWDG 喂狗。
  159. * 每次读两个寄存器(单周期访问)比缓存判断更稳,不受调用时机影响。 */
  160. if ((IWDG->PR == 0) && (IWDG->RLR == 0))
  161. return;
  162. if (wdt_dev == RT_NULL)
  163. wdt_dev = rt_device_find(RT_FOTA_WDT_DEV_NAME);
  164. if (wdt_dev != RT_NULL)
  165. rt_device_control(wdt_dev, RT_DEVICE_CTRL_WDT_KEEPALIVE, RT_NULL);
  166. }
  167. /* 分块擦除:把一次大块擦除拆成 chunk 大小的多次调用,块间喂狗。
  168. * chunk 取 RT_FOTA_BACKUP_BLK_SIZE(4KB) = NOR 扇区粒度,对 onchip flash 亦按页对齐,
  169. * 两种介质都安全。返回 0 成功,-1 失败(与 fal_partition_erase 语义一致)。 */
  170. static int rt_fota_erase_chunked(const struct fal_partition *part, rt_uint32_t addr, rt_size_t size)
  171. {
  172. rt_uint32_t done = 0;
  173. rt_size_t len;
  174. while (done < size)
  175. {
  176. len = size - done;
  177. if (len > RT_FOTA_BACKUP_BLK_SIZE)
  178. len = RT_FOTA_BACKUP_BLK_SIZE;
  179. if (fal_partition_erase(part, addr + done, len) < 0)
  180. return -1;
  181. done += len;
  182. rt_fota_wdt_feed();
  183. }
  184. return 0;
  185. }
  186. /* For shell */
  187. static rt_sem_t shell_sem = RT_NULL;
  188. static rt_device_t shell_dev = RT_NULL;
  189. typedef struct {
  190. char type[4];
  191. rt_uint16_t fota_algo;
  192. rt_uint8_t fm_time[6];
  193. char app_part_name[16];
  194. char download_version[24];
  195. char current_version[24];
  196. rt_uint32_t code_crc;
  197. rt_uint32_t hash_val;
  198. rt_uint32_t raw_size;
  199. rt_uint32_t com_size;
  200. rt_uint32_t head_crc;
  201. } rt_fota_part_head, *rt_fota_part_head_t;
  202. typedef void (*rt_fota_app_func)(void);
  203. static rt_fota_app_func app_func = RT_NULL;
  204. static rt_fota_part_head fota_part_head;
  205. static void rt_fota_signal_led_on(void)
  206. {
  207. rt_pin_write(RT_FOTA_SIGNAL_LED_PIN, PIN_LOW);
  208. }
  209. static void rt_fota_signal_led_off(void)
  210. {
  211. rt_pin_write(RT_FOTA_SIGNAL_LED_PIN, PIN_HIGH);
  212. }
  213. static void rt_fota_signal_led_entry(void *arg)
  214. {
  215. while(1)
  216. {
  217. led_ticks();
  218. rt_thread_mdelay(LED_TICK_TIME);
  219. }
  220. }
  221. static void rt_fota_signal_led_init(void)
  222. {
  223. rt_pin_mode(RT_FOTA_SIGNAL_LED_PIN, PIN_MODE_OUTPUT);
  224. signal_led_mem_op.malloc_fn = (void* (*)(size_t))rt_malloc;
  225. signal_led_mem_op.free_fn = rt_free;
  226. led_set_mem_operation(&signal_led_mem_op);
  227. signal_led = led_create(rt_fota_signal_led_on, rt_fota_signal_led_off);
  228. /* Config signal led mode */
  229. led_set_mode(signal_led, LOOP_PERMANENT, (char *)led_on_mode);
  230. led_set_blink_over_callback(signal_led, RT_NULL);
  231. led_start(signal_led);
  232. rt_thread_t tid;
  233. tid = rt_thread_create("sig_led", rt_fota_signal_led_entry, RT_NULL, RT_FOTA_SIGNAL_LED_THREAD_STACK_SIZE, RT_FOTA_SIGNAL_LED_THREAD_PRIORITY, 10);
  234. if (tid)
  235. rt_thread_startup(tid);
  236. }
  237. static void rt_fota_signal_led_mode(const char *led_cfg)
  238. {
  239. RT_ASSERT(led_cfg != RT_NULL);
  240. led_set_mode(signal_led, LOOP_PERMANENT, (char *)led_cfg);
  241. }
  242. static int rt_fota_boot_verify(void)
  243. {
  244. int fota_res = RT_FOTA_NO_ERR;
  245. rt_memset(&fota_part_head, 0x0, sizeof(rt_fota_part_head));
  246. /* partition initial */
  247. fal_init();
  248. extern int fal_init_check(void);
  249. /* verify partition */
  250. if (fal_init_check() != 1)
  251. {
  252. LOG_D("Partition initialized failed!");
  253. fota_res = RT_FOTA_GENERAL_ERR;
  254. goto __exit_boot_verify;
  255. }
  256. __exit_boot_verify:
  257. return fota_res;
  258. }
  259. int rt_fota_part_fw_verify(const char *part_name)
  260. {
  261. #define RT_FOTA_CRC_BUFF_SIZE 4096
  262. #define RT_FOTA_CRC_INIT_VAL 0xffffffff
  263. int fota_res = RT_FOTA_NO_ERR;
  264. const struct fal_partition *part;
  265. rt_fota_part_head part_head;
  266. rt_uint8_t *body_buf = RT_NULL;
  267. rt_uint32_t body_crc = RT_FOTA_CRC_INIT_VAL;
  268. rt_uint32_t hdr_crc;
  269. if (part_name == RT_NULL)
  270. {
  271. LOG_D("Invaild paramenter input!");
  272. fota_res = RT_FOTA_GENERAL_ERR;
  273. goto __exit_partition_verify;
  274. }
  275. part = fal_partition_find(part_name);
  276. if (part == RT_NULL)
  277. {
  278. LOG_D("Partition[%s] not found.", part_name);
  279. fota_res = RT_FOTA_GENERAL_ERR;
  280. goto __exit_partition_verify;
  281. }
  282. /* read the head of RBL files */
  283. if (fal_partition_read(part, 0, (rt_uint8_t *)&part_head, sizeof(rt_fota_part_head)) < 0)
  284. {
  285. LOG_D("Partition[%s] read error!", part->name);
  286. fota_res = RT_FOTA_PART_READ_ERR;
  287. goto __exit_partition_verify;
  288. }
  289. extern rt_uint32_t rt_fota_crc(rt_uint8_t *buf, rt_uint32_t len);
  290. hdr_crc = rt_fota_crc((rt_uint8_t *)&part_head, sizeof(rt_fota_part_head) - 4);
  291. if (hdr_crc != part_head.head_crc)
  292. {
  293. LOG_D("Partition[%s] head CRC32 error!", part->name);
  294. fota_res = RT_FOTA_FW_VERIFY_FAILED;
  295. goto __exit_partition_verify;
  296. }
  297. if (rt_strcmp(part_head.type, "RBL") != 0)
  298. {
  299. LOG_D("Partition[%s] type[%s] not surport.", part->name, part_head.type);
  300. fota_res = RT_FOTA_CHECK_FAILED;
  301. goto __exit_partition_verify;
  302. }
  303. if (fal_partition_find(part_head.app_part_name) == RT_NULL)
  304. {
  305. LOG_D("Partition[%s] not found.", part_head.app_part_name);
  306. fota_res = RT_FOTA_FW_VERIFY_FAILED;
  307. goto __exit_partition_verify;
  308. }
  309. body_buf = rt_malloc(RT_FOTA_CRC_BUFF_SIZE);
  310. if (body_buf == RT_NULL)
  311. {
  312. LOG_D("Not enough memory for body CRC32 verify.");
  313. fota_res = RT_FOTA_NO_MEM_ERR;
  314. goto __exit_partition_verify;
  315. }
  316. for (int body_pos = 0; body_pos < part_head.com_size;)
  317. {
  318. int body_read_len = fal_partition_read(part, sizeof(rt_fota_part_head) + body_pos, body_buf, RT_FOTA_CRC_BUFF_SIZE);
  319. if (body_read_len > 0)
  320. {
  321. if ((body_pos + body_read_len) > part_head.com_size)
  322. {
  323. body_read_len = part_head.com_size - body_pos;
  324. }
  325. extern rt_uint32_t rt_fota_step_crc(rt_uint32_t crc, rt_uint8_t *buf, rt_uint32_t len);
  326. body_crc = rt_fota_step_crc(body_crc, body_buf, body_read_len);
  327. body_pos = body_pos + body_read_len;
  328. }
  329. else
  330. {
  331. LOG_D("Partition[%s] read error!", part->name);
  332. fota_res = RT_FOTA_PART_READ_ERR;
  333. goto __exit_partition_verify;
  334. }
  335. }
  336. body_crc = body_crc ^ RT_FOTA_CRC_INIT_VAL;
  337. if (body_crc != part_head.code_crc)
  338. {
  339. LOG_D("Partition[%s] firmware integrity verify failed.", part->name);
  340. fota_res = RT_FOTA_FW_VERIFY_FAILED;
  341. goto __exit_partition_verify;
  342. }
  343. __exit_partition_verify:
  344. if (fota_res == RT_FOTA_NO_ERR)
  345. {
  346. rt_enter_critical();
  347. rt_memcpy(&fota_part_head, &part_head, sizeof(rt_fota_part_head));
  348. rt_exit_critical();
  349. LOG_D("partition[%s] verify success!", part->name);
  350. }
  351. else
  352. {
  353. rt_enter_critical();
  354. rt_memset(&fota_part_head, 0x0, sizeof(rt_fota_part_head));
  355. rt_exit_critical();
  356. LOG_D("Partition[%s] verify failed!", part->name);
  357. }
  358. if (body_buf)
  359. rt_free(body_buf);
  360. return fota_res;
  361. }
  362. int rt_fota_check_upgrade(void)
  363. {
  364. int is_upgrade = 0;
  365. if (rt_strcmp(fota_part_head.download_version, fota_part_head.current_version) != 0)
  366. {
  367. is_upgrade = 1;
  368. /* v1.3.4:原为 LOG_D(DBG_LEVEL=DBG_INFO 时不输出),导致现场完全看不到
  369. * "为什么会跑升级/备份"。改为 LOG_I 并把两侧版本都打出来,一眼可判 */
  370. LOG_I("Application need upgrade: fm_area[%s] != app[%s].",
  371. fota_part_head.download_version, fota_part_head.current_version);
  372. goto __exit_check_upgrade;
  373. }
  374. LOG_I("No upgrade: fm_area[%s] == app[%s].",
  375. fota_part_head.download_version, fota_part_head.current_version);
  376. __exit_check_upgrade:
  377. return is_upgrade;
  378. }
  379. /* ===================== v1.3.4:升级重试熔断 =====================
  380. * 为什么需要(现场问题:没有下发升级包,断电重启却反复执行 backup):
  381. * rt_fota_check_upgrade() 只比较 fm_area 里 RBL 头的 download_version 与
  382. * current_version;而把 current_version 对齐成 download_version 的
  383. * rt_fota_copy_version() 位于 rt_fota_upgrade() **之后**。所以只要 upgrade
  384. * 失败(擦写途中被 IWDG 复位、NOR 读写异常等),copy_version 就不会执行,
  385. * fm_area 里那个包始终"待升级"——
  386. * 于是每次上电都重跑完整升级流程:先 rt_fota_backup_app_to_df() 备份 312KB
  387. * (读一遍 + 擦 78 扇区 + 写一遍),再擦写 312KB。表现为:
  388. * "没触发升级却每次启动都打印 rt_fota_backup_app_to_df!
  389. * 并伴随长时间 # 输出、断电重启反复发生"。
  390. * 对策:按"版本"记录连续失败次数。同一版本连续失败达到
  391. * RT_FOTA_UPGRADE_MAX_RETRY 次后不再自动升级,直接跳转 APP 并打印原因;
  392. * 用户重新下发新包(版本变化)时计数自动归零,无需人工清标志。
  393. * 记录存 EasyFlash(NOR,掉电保持);EF 不可用时退化为本次上电内计数。
  394. */
  395. #define RT_FOTA_RETRY_EF_KEY "fota_retry"
  396. #define RT_FOTA_UPGRADE_MAX_RETRY 3
  397. typedef struct
  398. {
  399. rt_uint32_t cnt; /* 同一版本连续失败次数 */
  400. char ver[24]; /* 上次尝试的 download_version */
  401. } rt_fota_retry_t;
  402. static rt_fota_retry_t fota_retry;
  403. static rt_bool_t fota_retry_loaded = RT_FALSE;
  404. static void rt_fota_retry_load(void)
  405. {
  406. size_t saved_len = 0;
  407. if (fota_retry_loaded)
  408. return;
  409. rt_memset(&fota_retry, 0, sizeof(fota_retry));
  410. if (ef_get_env_blob(RT_FOTA_RETRY_EF_KEY, &fota_retry, sizeof(fota_retry), &saved_len) == 0)
  411. {
  412. /* 没有记录 or 读取失败:从头计数 */
  413. rt_memset(&fota_retry, 0, sizeof(fota_retry));
  414. }
  415. /* EF 记录被擦成 0xFF 等异常时 cnt 可能是垃圾值(0xFFFFFFFF),
  416. * 直接判"已达上限"会把升级永久禁用,这里按无效记录重置。
  417. * 注意 ver 是空/0xFF 时必然与 download_version 不等,会走"新版本"分支归零,
  418. * 所以只需兜住 cnt 本身。 */
  419. if (fota_retry.cnt > 100)
  420. {
  421. LOG_I("Retry: invalid record(cnt=0x%08X), reset.", fota_retry.cnt);
  422. rt_memset(&fota_retry, 0, sizeof(fota_retry));
  423. }
  424. fota_retry_loaded = RT_TRUE;
  425. }
  426. static void rt_fota_retry_save(void)
  427. {
  428. if (ef_set_env_blob(RT_FOTA_RETRY_EF_KEY, &fota_retry, sizeof(fota_retry)) != EF_NO_ERR)
  429. {
  430. LOG_I("Retry: save retry record failed (fallback to RAM only).");
  431. }
  432. }
  433. /* 升级前的熔断检查:新版本自动清零;返回 RT_TRUE 表示"可以升级" */
  434. static rt_bool_t rt_fota_retry_allow(void)
  435. {
  436. rt_fota_retry_load();
  437. /* 版本不同 = 用户下发了新包,重新给满次数 */
  438. if (rt_strcmp(fota_retry.ver, fota_part_head.download_version) != 0)
  439. {
  440. rt_strncpy(fota_retry.ver, fota_part_head.download_version, sizeof(fota_retry.ver) - 1);
  441. fota_retry.ver[sizeof(fota_retry.ver) - 1] = '\0';
  442. fota_retry.cnt = 0;
  443. }
  444. if (fota_retry.cnt >= RT_FOTA_UPGRADE_MAX_RETRY)
  445. {
  446. /* 达到上限:不再动 flash,保留现场供人工处理(msh: fota probe / dr2 0) */
  447. rt_kprintf("Upgrade of version [%s] failed %d times, auto upgrade disabled.\n",
  448. fota_retry.ver, (int)fota_retry.cnt);
  449. rt_kprintf("Fix the image or erase fm_area; a new version will re-enable it.\n");
  450. rt_fota_signal_led_mode(led_shell_mode);
  451. return RT_FALSE;
  452. }
  453. fota_retry.cnt++;
  454. rt_fota_wdt_feed();
  455. rt_fota_retry_save();
  456. return RT_TRUE;
  457. }
  458. /* 升级完全成功(含版本对齐)后清零 */
  459. static void rt_fota_retry_clear(void)
  460. {
  461. rt_fota_retry_load();
  462. if (fota_retry.cnt == 0)
  463. return;
  464. fota_retry.cnt = 0;
  465. rt_memset(fota_retry.ver, 0, sizeof(fota_retry.ver));
  466. rt_fota_wdt_feed();
  467. rt_fota_retry_save();
  468. }
  469. int rt_fota_copy_version(const char *part_name)
  470. {
  471. #define THE_NOR_FLASH_GRANULARITY 4096
  472. int fota_res = RT_FOTA_NO_ERR;
  473. const struct fal_partition *part;
  474. rt_fota_part_head_t part_head = RT_NULL;
  475. rt_uint8_t *cache_buf = RT_NULL;
  476. part = fal_partition_find(part_name);
  477. if (part == RT_NULL)
  478. {
  479. LOG_D("Find partition[%s] not found.", part_name);
  480. fota_res = RT_FOTA_FW_VERIFY_FAILED;
  481. goto __exit_copy_version;
  482. }
  483. cache_buf = rt_malloc(THE_NOR_FLASH_GRANULARITY);
  484. if (cache_buf == RT_NULL)
  485. {
  486. LOG_D("Not enough memory for head erase.");
  487. fota_res = RT_FOTA_NO_MEM_ERR;
  488. goto __exit_copy_version;
  489. }
  490. part_head = (rt_fota_part_head_t)cache_buf;
  491. if (fal_partition_read(part, 0, cache_buf, THE_NOR_FLASH_GRANULARITY) < 0)
  492. {
  493. LOG_I("Read partition[%s] failed.", part_name);
  494. fota_res = RT_FOTA_PART_READ_ERR;
  495. goto __exit_copy_version;
  496. }
  497. rt_memcpy(part_head->current_version, part_head->download_version, sizeof(part_head->current_version));
  498. extern rt_uint32_t rt_fota_crc(rt_uint8_t *buf, rt_uint32_t len);
  499. part_head->head_crc = rt_fota_crc((rt_uint8_t *)part_head, sizeof(rt_fota_part_head) - 4);
  500. if (fal_partition_erase(part, 0, THE_NOR_FLASH_GRANULARITY) < 0)
  501. {
  502. LOG_D("Erase partition[%s] failed.", part_name);
  503. fota_res = RT_FOTA_PART_ERASE_ERR;
  504. goto __exit_copy_version;
  505. }
  506. if (fal_partition_write(part, 0, (const rt_uint8_t *)cache_buf, THE_NOR_FLASH_GRANULARITY) < 0)
  507. {
  508. LOG_I("Write partition[%s] failed.", part_name);
  509. fota_res = RT_FOTA_PART_WRITE_ERR;
  510. goto __exit_copy_version;
  511. }
  512. __exit_copy_version:
  513. if (cache_buf)
  514. rt_free(cache_buf);
  515. if (fota_res != RT_FOTA_NO_ERR)
  516. LOG_I("Copy firmware version failed!");
  517. else
  518. LOG_I("Copy firmware version Success!");
  519. return fota_res;
  520. }
  521. int rt_fota_erase_app_part(void)
  522. {
  523. int fota_res = RT_FOTA_NO_ERR;
  524. const struct fal_partition *part;
  525. part = fal_partition_find(fota_part_head.app_part_name);
  526. if (part == RT_NULL)
  527. {
  528. LOG_D("Erase partition[%s] not found.", fota_part_head.app_part_name);
  529. fota_res = RT_FOTA_FW_VERIFY_FAILED;
  530. goto __exit_partition_erase;
  531. }
  532. LOG_I("Partition[%s] erase start:", part->name);
  533. /* 分块擦除 + 逐块喂狗:312KB 的 onchip 擦除按页进行(16 页一批关中断),
  534. * 单次调用可达数秒,与前面的 df_area 备份累加后容易撞 IWDG 10s 超时 */
  535. if (rt_fota_erase_chunked(part, 0, fota_part_head.raw_size) < 0)
  536. {
  537. LOG_D("Partition[%s] erase failed!", part->name);
  538. fota_res = RT_FOTA_PART_ERASE_ERR;
  539. goto __exit_partition_erase;
  540. }
  541. __exit_partition_erase:
  542. if (fota_res == RT_FOTA_NO_ERR)
  543. {
  544. LOG_D("Partition[%s] erase %d bytes success!", part->name, fota_part_head.raw_size);
  545. }
  546. return fota_res;
  547. }
  548. int rt_fota_write_app_part(int fw_pos, rt_uint8_t *fw_buf, int fw_len)
  549. {
  550. int rt_fota_res = RT_FOTA_NO_ERR;
  551. const struct fal_partition *part;
  552. part = fal_partition_find(fota_part_head.app_part_name);
  553. if (part == RT_NULL)
  554. {
  555. LOG_D("Erase partition[%s] not found.", fota_part_head.app_part_name);
  556. rt_fota_res = RT_FOTA_FW_VERIFY_FAILED;
  557. goto __partition_write_exit;
  558. }
  559. if (fal_partition_write(part, fw_pos, fw_buf, fw_len) < 0)
  560. {
  561. LOG_D("Partition[%s] write failed!", part->name);
  562. rt_fota_res = RT_FOTA_PART_WRITE_ERR;
  563. goto __partition_write_exit;
  564. }
  565. /* 搬运循环里每块都写一次 app 分区,逐块喂狗(onchip 写 2KB/页,整包累计数秒) */
  566. rt_fota_wdt_feed();
  567. __partition_write_exit:
  568. if (rt_fota_res == RT_FOTA_NO_ERR)
  569. {
  570. LOG_D("Partition[%s] write %d bytes success!", part->name, fw_len);
  571. }
  572. return rt_fota_res;
  573. }
  574. static int rt_fota_read_part(const struct fal_partition *part, int read_pos, tiny_aes_context *aes_ctx, rt_uint8_t *aes_iv, rt_uint8_t *decrypt_buf, rt_uint32_t decrypt_len)
  575. {
  576. int fota_err = RT_FOTA_NO_ERR;
  577. rt_uint8_t *encrypt_buf = RT_NULL;
  578. if ((part == RT_NULL) || (decrypt_buf == RT_NULL)
  579. || (decrypt_len % 16 != 0) || (decrypt_len > RT_FOTA_ALGO_BUFF_SIZE))
  580. {
  581. fota_err = RT_FOTA_GENERAL_ERR;
  582. goto __exit_read_decrypt;
  583. }
  584. rt_memset(decrypt_buf, 0x0, decrypt_len);
  585. /* Not use AES256 algorithm */
  586. if (aes_ctx == RT_NULL || aes_iv == RT_NULL)
  587. {
  588. fota_err = fal_partition_read(part, sizeof(rt_fota_part_head) + read_pos, decrypt_buf, decrypt_len);
  589. if (fota_err <= 0)
  590. {
  591. fota_err = RT_FOTA_PART_READ_ERR;
  592. }
  593. goto __exit_read_decrypt;
  594. }
  595. encrypt_buf = rt_malloc(decrypt_len);
  596. if (encrypt_buf == RT_NULL)
  597. {
  598. fota_err = RT_FOTA_GENERAL_ERR;
  599. goto __exit_read_decrypt;
  600. }
  601. rt_memset(encrypt_buf, 0x0, decrypt_len);
  602. fota_err = fal_partition_read(part, sizeof(rt_fota_part_head) + read_pos, encrypt_buf, decrypt_len);
  603. if (fota_err <= 0 || fota_err % 16 != 0)
  604. {
  605. fota_err = RT_FOTA_PART_READ_ERR;
  606. goto __exit_read_decrypt;
  607. }
  608. tiny_aes_crypt_cbc(aes_ctx, AES_DECRYPT, fota_err, aes_iv, encrypt_buf, decrypt_buf);
  609. __exit_read_decrypt:
  610. if (encrypt_buf)
  611. rt_free(encrypt_buf);
  612. return fota_err;
  613. }
  614. int rt_fota_upgrade(const char *part_name)
  615. {
  616. rt_kprintf("rt_fota_upgrade:%s",part_name);
  617. int fota_err = RT_FOTA_NO_ERR;
  618. const struct fal_partition *part;
  619. rt_fota_part_head_t part_head = RT_NULL;
  620. tiny_aes_context *aes_ctx = RT_NULL;
  621. rt_uint8_t *aes_iv = RT_NULL;
  622. rt_uint8_t *crypt_buf = RT_NULL;
  623. int fw_raw_pos = 0;
  624. int fw_raw_len = 0;
  625. rt_uint32_t total_copy_size = 0;
  626. rt_uint8_t block_hdr_buf[RT_FOTA_BLOCK_HEADER_SIZE];
  627. rt_uint32_t block_hdr_pos = RT_FOTA_ALGO_BUFF_SIZE;
  628. rt_uint32_t block_size = 0;
  629. rt_uint32_t dcprs_size = 0;
  630. qlz_state_decompress *dcprs_state = RT_NULL;
  631. rt_uint8_t *cmprs_buff = RT_NULL;
  632. rt_uint8_t *dcprs_buff = RT_NULL;
  633. rt_uint32_t padding_size = 0;
  634. if (part_name == RT_NULL)
  635. {
  636. LOG_D("Invaild paramenter input!");
  637. fota_err = RT_FOTA_GENERAL_ERR;
  638. goto __exit_upgrade;
  639. }
  640. part = fal_partition_find(part_name);
  641. if (part == RT_NULL)
  642. {
  643. LOG_D("Upgrade partition[%s] not found.", part_name);
  644. fota_err = RT_FOTA_GENERAL_ERR;
  645. goto __exit_upgrade;
  646. }
  647. /* Application partition erase */
  648. fota_err = rt_fota_erase_app_part();
  649. if (fota_err != RT_FOTA_NO_ERR)
  650. {
  651. goto __exit_upgrade;
  652. }
  653. /* rt_fota_erase_app_part() has check fota_part_head vaild already */
  654. part_head = &fota_part_head;
  655. crypt_buf = rt_malloc(RT_FOTA_ALGO_BUFF_SIZE);
  656. if (crypt_buf == RT_NULL)
  657. {
  658. LOG_D("Not enough memory for firmware buffer.");
  659. fota_err = RT_FOTA_NO_MEM_ERR;
  660. goto __exit_upgrade;
  661. }
  662. /* AES256 algorithm enable */
  663. if ((part_head->fota_algo & RT_FOTA_CRYPT_STAT_MASK) == RT_FOTA_CRYPT_ALGO_AES256)
  664. {
  665. aes_ctx = rt_malloc(sizeof(tiny_aes_context));
  666. aes_iv = rt_malloc(rt_strlen(RT_FOTA_ALGO_AES_IV) + 1);
  667. if (aes_ctx == RT_NULL || aes_iv == RT_NULL)
  668. {
  669. LOG_D("Not enough memory for firmware hash verify.");
  670. fota_err = RT_FOTA_NO_MEM_ERR;
  671. goto __exit_upgrade;
  672. }
  673. rt_memset(aes_iv, 0x0, rt_strlen(RT_FOTA_ALGO_AES_IV) + 1);
  674. rt_memcpy(aes_iv, RT_FOTA_ALGO_AES_IV, rt_strlen(RT_FOTA_ALGO_AES_IV));
  675. tiny_aes_setkey_dec(aes_ctx, (rt_uint8_t *)RT_FOTA_ALGO_AES_KEY, 256);
  676. }
  677. else if ((part_head->fota_algo & RT_FOTA_CRYPT_STAT_MASK) == RT_FOTA_CRYPT_ALGO_XOR)
  678. {
  679. LOG_I("Not surpport XOR.");
  680. fota_err = RT_FOTA_GENERAL_ERR;
  681. goto __exit_upgrade;
  682. }
  683. /* If enable fastlz compress function */
  684. if ((part_head->fota_algo & RT_FOTA_CMPRS_STAT_MASK) == RT_FOTA_CMPRS_ALGO_FASTLZ)
  685. {
  686. cmprs_buff = rt_malloc(RT_FOTA_CMPRS_BUFFER_SIZE + RT_FOTA_FASTLZ_BUFFER_PADDING);
  687. dcprs_buff = rt_malloc(RT_FOTA_CMPRS_BUFFER_SIZE);
  688. if (cmprs_buff == RT_NULL || dcprs_buff == RT_NULL)
  689. {
  690. LOG_D("Not enough memory for firmware hash verify.");
  691. fota_err = RT_FOTA_NO_MEM_ERR;
  692. goto __exit_upgrade;
  693. }
  694. padding_size = RT_FOTA_FASTLZ_BUFFER_PADDING;
  695. }
  696. else if ((part_head->fota_algo & RT_FOTA_CMPRS_STAT_MASK) == RT_FOTA_CMPRS_ALGO_QUICKLZ)
  697. {
  698. cmprs_buff = rt_malloc(RT_FOTA_CMPRS_BUFFER_SIZE + RT_FOTA_QUICKLZ_BUFFER_PADDING);
  699. dcprs_buff = rt_malloc(RT_FOTA_CMPRS_BUFFER_SIZE);
  700. dcprs_state = rt_malloc(sizeof(qlz_state_decompress));
  701. if (cmprs_buff == RT_NULL || dcprs_buff == RT_NULL || dcprs_state == RT_NULL)
  702. {
  703. LOG_D("Not enough memory for firmware hash verify.");
  704. fota_err = RT_FOTA_NO_MEM_ERR;
  705. goto __exit_upgrade;
  706. }
  707. padding_size = RT_FOTA_QUICKLZ_BUFFER_PADDING;
  708. rt_memset(dcprs_state, 0x0, sizeof(qlz_state_decompress));
  709. }
  710. else if ((part_head->fota_algo & RT_FOTA_CMPRS_STAT_MASK) == RT_FOTA_CMPRS_ALGO_GZIP)
  711. {
  712. LOG_I("Not surpport GZIP.");
  713. fota_err = RT_FOTA_GENERAL_ERR;
  714. goto __exit_upgrade;
  715. }
  716. LOG_I("Start to copy firmware from %s to %s partition:", part->name, part_head->app_part_name);
  717. while (fw_raw_pos < part_head->com_size)
  718. {
  719. if ((part_head->fota_algo & RT_FOTA_CMPRS_STAT_MASK) != RT_FOTA_CRYPT_ALGO_NONE)
  720. {
  721. if (block_hdr_pos >= RT_FOTA_ALGO_BUFF_SIZE)
  722. {
  723. fw_raw_len = rt_fota_read_part(part, fw_raw_pos, aes_ctx, aes_iv, crypt_buf, RT_FOTA_ALGO_BUFF_SIZE);
  724. if (fw_raw_len < 0)
  725. {
  726. LOG_D("AES256 algorithm failed.");
  727. fota_err = RT_FOTA_PART_READ_ERR;
  728. goto __exit_upgrade;
  729. }
  730. fw_raw_pos += fw_raw_len;
  731. rt_memcpy(block_hdr_buf, crypt_buf, RT_FOTA_BLOCK_HEADER_SIZE);
  732. block_size = block_hdr_buf[0] * (1 << 24) + block_hdr_buf[1] * (1 << 16) + block_hdr_buf[2] * (1 << 8) + block_hdr_buf[3];
  733. /* 校验块长:防止损坏/伪造的升级包造成缓冲区越界 */
  734. if ((fw_raw_len < RT_FOTA_BLOCK_HEADER_SIZE) ||
  735. (block_size > (rt_uint32_t)(fw_raw_len - RT_FOTA_BLOCK_HEADER_SIZE)) ||
  736. (block_size > (RT_FOTA_CMPRS_BUFFER_SIZE + padding_size)))
  737. {
  738. LOG_D("Invalid compressed block size(%d).", block_size);
  739. fota_err = RT_FOTA_GENERAL_ERR;
  740. goto __exit_upgrade;
  741. }
  742. rt_memset(cmprs_buff, 0x0, RT_FOTA_CMPRS_BUFFER_SIZE + padding_size);
  743. rt_memcpy(cmprs_buff, &crypt_buf[RT_FOTA_BLOCK_HEADER_SIZE], block_size);
  744. block_hdr_pos = RT_FOTA_BLOCK_HEADER_SIZE + block_size;
  745. }
  746. else
  747. {
  748. rt_uint8_t hdr_tmp_pos = 0;
  749. while (block_hdr_pos < RT_FOTA_ALGO_BUFF_SIZE)
  750. {
  751. if (hdr_tmp_pos < RT_FOTA_BLOCK_HEADER_SIZE)
  752. {
  753. block_hdr_buf[hdr_tmp_pos++] = crypt_buf[block_hdr_pos++];
  754. }
  755. else
  756. {
  757. block_size = block_hdr_buf[0] * (1 << 24) + block_hdr_buf[1] * (1 << 16) + block_hdr_buf[2] * (1 << 8) + block_hdr_buf[3];
  758. /* 校验块长:防止损坏/伪造的升级包造成缓冲区越界 */
  759. if (block_size > (RT_FOTA_CMPRS_BUFFER_SIZE + padding_size))
  760. {
  761. LOG_D("Invalid compressed block size(%d).", block_size);
  762. fota_err = RT_FOTA_GENERAL_ERR;
  763. goto __exit_upgrade;
  764. }
  765. rt_memset(cmprs_buff, 0x0, RT_FOTA_CMPRS_BUFFER_SIZE + padding_size);
  766. if (block_size > (RT_FOTA_ALGO_BUFF_SIZE - block_hdr_pos))
  767. {
  768. rt_memcpy(cmprs_buff, &crypt_buf[block_hdr_pos], (RT_FOTA_ALGO_BUFF_SIZE - block_hdr_pos));
  769. fw_raw_len = rt_fota_read_part(part, fw_raw_pos, aes_ctx, aes_iv, crypt_buf, RT_FOTA_ALGO_BUFF_SIZE);
  770. if (fw_raw_len < 0)
  771. {
  772. LOG_D("AES256 algorithm failed.");
  773. fota_err = RT_FOTA_PART_READ_ERR;
  774. goto __exit_upgrade;
  775. }
  776. fw_raw_pos += fw_raw_len;
  777. /* 校验跨缓冲块的剩余长度不超过本次读取的字节数 */
  778. if (((block_size + block_hdr_pos) - RT_FOTA_ALGO_BUFF_SIZE) > (rt_uint32_t)fw_raw_len)
  779. {
  780. LOG_D("Invalid compressed block size(%d).", block_size);
  781. fota_err = RT_FOTA_GENERAL_ERR;
  782. goto __exit_upgrade;
  783. }
  784. rt_memcpy(&cmprs_buff[RT_FOTA_ALGO_BUFF_SIZE - block_hdr_pos], &crypt_buf[0], (block_size + block_hdr_pos) - RT_FOTA_ALGO_BUFF_SIZE);
  785. block_hdr_pos = (block_size + block_hdr_pos) - RT_FOTA_ALGO_BUFF_SIZE;
  786. }
  787. else
  788. {
  789. rt_memcpy(cmprs_buff, &crypt_buf[block_hdr_pos], block_size);
  790. block_hdr_pos = block_hdr_pos + block_size;
  791. }
  792. break;
  793. }
  794. }
  795. if (hdr_tmp_pos < RT_FOTA_BLOCK_HEADER_SIZE)
  796. {
  797. fw_raw_len = rt_fota_read_part(part, fw_raw_pos, aes_ctx, aes_iv, crypt_buf, RT_FOTA_ALGO_BUFF_SIZE);
  798. if (fw_raw_len < 0)
  799. {
  800. LOG_D("AES256 algorithm failed.");
  801. fota_err = RT_FOTA_PART_READ_ERR;
  802. goto __exit_upgrade;
  803. }
  804. fw_raw_pos += fw_raw_len;
  805. block_hdr_pos = 0;
  806. while (hdr_tmp_pos < RT_FOTA_BLOCK_HEADER_SIZE)
  807. {
  808. block_hdr_buf[hdr_tmp_pos++] = crypt_buf[block_hdr_pos++];
  809. }
  810. block_size = block_hdr_buf[0] * (1 << 24) + block_hdr_buf[1] * (1 << 16) + block_hdr_buf[2] * (1 << 8) + block_hdr_buf[3];
  811. /* 校验块长:防止损坏/伪造的升级包造成缓冲区越界 */
  812. if ((fw_raw_len < (int)block_hdr_pos) ||
  813. (block_size > (rt_uint32_t)(fw_raw_len - block_hdr_pos)) ||
  814. (block_size > (RT_FOTA_CMPRS_BUFFER_SIZE + padding_size)))
  815. {
  816. LOG_D("Invalid compressed block size(%d).", block_size);
  817. fota_err = RT_FOTA_GENERAL_ERR;
  818. goto __exit_upgrade;
  819. }
  820. rt_memset(cmprs_buff, 0x0, RT_FOTA_CMPRS_BUFFER_SIZE + padding_size);
  821. rt_memcpy(cmprs_buff, &crypt_buf[block_hdr_pos], block_size);
  822. block_hdr_pos = (block_hdr_pos + block_size) % RT_FOTA_ALGO_BUFF_SIZE;
  823. }
  824. }
  825. rt_memset(dcprs_buff, 0x0, RT_FOTA_CMPRS_BUFFER_SIZE);
  826. if ((part_head->fota_algo & RT_FOTA_CMPRS_STAT_MASK) == RT_FOTA_CMPRS_ALGO_FASTLZ)
  827. {
  828. dcprs_size = fastlz_decompress((const void *)&cmprs_buff[0], block_size, &dcprs_buff[0], RT_FOTA_CMPRS_BUFFER_SIZE);
  829. }
  830. else if ((part_head->fota_algo & RT_FOTA_CMPRS_STAT_MASK) == RT_FOTA_CMPRS_ALGO_QUICKLZ)
  831. {
  832. /* 校验解压长度:qlz 解压长度由流头自报,必须在目标缓冲区容量内 */
  833. if (qlz_size_decompressed((const char *)&cmprs_buff[0]) > RT_FOTA_CMPRS_BUFFER_SIZE)
  834. {
  835. LOG_D("Invalid quicklz decompressed size in upgrade package.");
  836. fota_err = RT_FOTA_GENERAL_ERR;
  837. goto __exit_upgrade;
  838. }
  839. dcprs_size = qlz_decompress((const char *)&cmprs_buff[0], &dcprs_buff[0], dcprs_state);
  840. }
  841. if (dcprs_size <= 0)
  842. {
  843. LOG_D("Decompress failed: %d.", dcprs_size);
  844. fota_err = RT_FOTA_GENERAL_ERR;
  845. goto __exit_upgrade;
  846. }
  847. if (rt_fota_write_app_part(total_copy_size, dcprs_buff, dcprs_size) < 0)
  848. {
  849. fota_err = RT_FOTA_COPY_FAILED;
  850. goto __exit_upgrade;
  851. }
  852. total_copy_size += dcprs_size;
  853. rt_kprintf("#");
  854. }
  855. /* no compress option */
  856. else
  857. {
  858. fw_raw_len = rt_fota_read_part(part, fw_raw_pos, aes_ctx, aes_iv, crypt_buf, RT_FOTA_ALGO_BUFF_SIZE);
  859. if (fw_raw_len < 0)
  860. {
  861. LOG_D("AES256 algorithm failed.");
  862. fota_err = RT_FOTA_PART_READ_ERR;
  863. goto __exit_upgrade;
  864. }
  865. fw_raw_pos += fw_raw_len;
  866. if (rt_fota_write_app_part(total_copy_size, crypt_buf, fw_raw_len) < 0)
  867. {
  868. fota_err = RT_FOTA_COPY_FAILED;
  869. goto __exit_upgrade;
  870. }
  871. total_copy_size += fw_raw_len;
  872. rt_kprintf("#");
  873. }
  874. }
  875. /* it has compress option */
  876. if ((part_head->fota_algo & RT_FOTA_CMPRS_STAT_MASK) != RT_FOTA_CRYPT_ALGO_NONE)
  877. {
  878. while (total_copy_size < part_head->raw_size)
  879. {
  880. if ((block_hdr_pos < fw_raw_len) && ((fw_raw_len - block_hdr_pos) > RT_FOTA_BLOCK_HEADER_SIZE))
  881. {
  882. rt_memcpy(block_hdr_buf, &crypt_buf[block_hdr_pos], RT_FOTA_BLOCK_HEADER_SIZE);
  883. block_size = block_hdr_buf[0] * (1 << 24) + block_hdr_buf[1] * (1 << 16) + block_hdr_buf[2] * (1 << 8) + block_hdr_buf[3];
  884. if ((fw_raw_len - block_hdr_pos - RT_FOTA_BLOCK_HEADER_SIZE) >= block_size)
  885. {
  886. rt_memset(cmprs_buff, 0x0, RT_FOTA_CMPRS_BUFFER_SIZE + padding_size);
  887. rt_memcpy(cmprs_buff, &crypt_buf[block_hdr_pos + RT_FOTA_BLOCK_HEADER_SIZE], block_size);
  888. rt_memset(dcprs_buff, 0x0, RT_FOTA_CMPRS_BUFFER_SIZE);
  889. block_hdr_pos += (block_size + RT_FOTA_BLOCK_HEADER_SIZE);
  890. if ((part_head->fota_algo & RT_FOTA_CMPRS_STAT_MASK) == RT_FOTA_CMPRS_ALGO_FASTLZ)
  891. {
  892. dcprs_size = fastlz_decompress((const void *)&cmprs_buff[0], block_size, &dcprs_buff[0], RT_FOTA_CMPRS_BUFFER_SIZE);
  893. }
  894. else if ((part_head->fota_algo & RT_FOTA_CMPRS_STAT_MASK) == RT_FOTA_CMPRS_ALGO_QUICKLZ)
  895. {
  896. /* 校验解压长度:qlz 解压长度由流头自报,必须在目标缓冲区容量内 */
  897. if (qlz_size_decompressed((const char *)&cmprs_buff[0]) > RT_FOTA_CMPRS_BUFFER_SIZE)
  898. {
  899. LOG_D("Invalid quicklz decompressed size in upgrade package.");
  900. fota_err = RT_FOTA_GENERAL_ERR;
  901. goto __exit_upgrade;
  902. }
  903. dcprs_size = qlz_decompress((const char *)&cmprs_buff[0], &dcprs_buff[0], dcprs_state);
  904. }
  905. if (dcprs_size <= 0)
  906. {
  907. LOG_D("Decompress failed: %d.", dcprs_size);
  908. fota_err = RT_FOTA_GENERAL_ERR;
  909. goto __exit_upgrade;
  910. }
  911. if (rt_fota_write_app_part(total_copy_size, dcprs_buff, dcprs_size) < 0)
  912. {
  913. fota_err = RT_FOTA_COPY_FAILED;
  914. goto __exit_upgrade;
  915. }
  916. total_copy_size += dcprs_size;
  917. rt_kprintf("#");
  918. }
  919. else
  920. {
  921. break;
  922. }
  923. }
  924. else
  925. {
  926. break;
  927. }
  928. }
  929. }
  930. rt_kprintf("\r\n");
  931. /* �п�������ֵ�����,��ΪAES��Ҫ���16�ֽ�����,�����Ľ��ܽ�ѹֵ�Ĵ������������Ǵ��ڵ���raw_size */
  932. /* �ȽϺõķ�������һ��У��,Ŀǰ��������HASH_CODE�㷨��֪�� */
  933. if (total_copy_size < part_head->raw_size)
  934. {
  935. LOG_D("Decompress check failed.");
  936. fota_err = RT_FOTA_GENERAL_ERR;
  937. }
  938. __exit_upgrade:
  939. if (aes_ctx)
  940. rt_free(aes_ctx);
  941. if (aes_iv)
  942. rt_free(aes_iv);
  943. if (crypt_buf)
  944. rt_free(crypt_buf);
  945. if (cmprs_buff)
  946. rt_free(cmprs_buff);
  947. if (dcprs_buff)
  948. rt_free(dcprs_buff);
  949. if (dcprs_state)
  950. rt_free(dcprs_state);
  951. if (fota_err == RT_FOTA_NO_ERR)
  952. {
  953. LOG_I("Upgrade success, total %d bytes.", total_copy_size);
  954. }
  955. return fota_err;
  956. }
  957. /* ================== v1.3.2:跳转 APP 前的 SPI Flash 交接处理 ==================
  958. * 现象:bootloader 内 SFUD 正常(打印 "Find a Winbond flash chip"),跳转后 APP 的
  959. * SFUD 探测失败("Read SFDP parameter header information failed" /
  960. * "This flash device is not found or not support"),FAL 里 w25q16m 设备为空,
  961. * EasyFlash 于是逐个 4KB 扇区做"检查-格式化",启动被拖死(表现为"读参数很慢")。
  962. *
  963. * 原因:原跳转序列里的 HAL_DeInit()/HAL_RCC_DeInit() 会复位 APB2(含 GPIOA、SPI1、
  964. * AFIO),/CS(PA4)、SCK(PA5)、MOSI(PA7) 变成浮空输入;从这一刻到 APP 里
  965. * HAL_SPI_MspInit 重新配置引脚,中间有几十毫秒"悬空窗口"。悬空的 /CS 一旦被
  966. * 噪声拉低,悬空时钟线上的毛刺就会被 Flash 当成指令时打入(0xB9 = 深度掉电、
  967. * 0x38 = QPI 等),此后标准 SPI 读只能得到 0xFF/0x00 —— 与 APP 侧现象完全一致。
  968. *
  969. * 对策(两步,缺一不可):
  970. * 1) 跳转前让芯片回到"标准 SPI + 空闲"态:等 BUSY 清零 → 0xAB 释放深度掉电 →
  971. * 0xFF 逃逸 QPI/连续读 → 0x66/0x99 复位器件;
  972. * 2) 外设复位之后再固定引脚电平:/CS 推挽输出高(不选中),SCK/MOSI/MISO 上拉输入。
  973. * 注意必须在 HAL_DeInit() 之后做,否则会被 APB2 复位冲掉。
  974. * 另外顺手读一次 JEDEC ID 打印出来,交接是否健康一眼可见(读不到 = 总线/芯片已异常)。
  975. */
  976. #define RT_FOTA_SPI_FLASH_DEV_NAME "spi10"
  977. #define RT_FOTA_FLASH_CMD_READ_SR 0x05 /* 读状态寄存器 */
  978. #define RT_FOTA_FLASH_CMD_RELEASE_PD 0xAB /* 释放深度掉电 / 读器件 ID */
  979. #define RT_FOTA_FLASH_CMD_READ_ID 0x9F /* JEDEC ID */
  980. #define RT_FOTA_FLASH_CMD_RESET_EN 0x66 /* 复位使能 */
  981. #define RT_FOTA_FLASH_CMD_RESET 0x99 /* 复位器件 */
  982. static struct rt_spi_device *rt_fota_spi_flash_dev(void)
  983. {
  984. return (struct rt_spi_device *)rt_device_find(RT_FOTA_SPI_FLASH_DEV_NAME);
  985. }
  986. /* 发 1 字节命令 + 读回数据(CS 由 SPI 框架自动拉低/释放) */
  987. static void rt_fota_spi_flash_cmd_recv(rt_uint8_t cmd, rt_uint8_t *rx, rt_size_t rx_len)
  988. {
  989. struct rt_spi_device *dev = rt_fota_spi_flash_dev();
  990. if ((dev == RT_NULL) || (rx == RT_NULL) || (rx_len == 0))
  991. return;
  992. rt_spi_send_then_recv(dev, &cmd, 1, rx, rx_len);
  993. }
  994. /* 只发 1 字节命令 */
  995. static void rt_fota_spi_flash_cmd(rt_uint8_t cmd)
  996. {
  997. struct rt_spi_device *dev = rt_fota_spi_flash_dev();
  998. if (dev == RT_NULL)
  999. return;
  1000. rt_spi_send(dev, &cmd, 1);
  1001. }
  1002. /* 跳转前:把 SPI Flash 恢复到"标准 SPI + 空闲"状态 */
  1003. static void rt_fota_spi_flash_quiesce(void)
  1004. {
  1005. struct rt_spi_device *dev = rt_fota_spi_flash_dev();
  1006. rt_uint8_t status = 0xFF;
  1007. rt_uint8_t id[3] = {0, 0, 0};
  1008. rt_uint32_t start;
  1009. int i;
  1010. if (dev == RT_NULL)
  1011. {
  1012. rt_kprintf("SPI flash handover: %s not found, skip quiesce.\n", RT_FOTA_SPI_FLASH_DEV_NAME);
  1013. return;
  1014. }
  1015. /* 1) 等上一次写/擦除结束(BUSY=0),最长等 1s,避免复位指令打断写入 */
  1016. start = rt_tick_get();
  1017. do
  1018. {
  1019. status = 0xFF;
  1020. rt_fota_spi_flash_cmd_recv(RT_FOTA_FLASH_CMD_READ_SR, &status, 1);
  1021. if ((status & 0x01) == 0)
  1022. break;
  1023. } while ((rt_tick_get() - start) < rt_tick_from_millisecond(1000));
  1024. /* 2) 0xFF 逃逸(尽力而为):若芯片被噪声带入 QPI/连续读模式,需 0xFF 才能退出;
  1025. * 标准 SPI 模式下 0xFF 是空操作,无副作用。真正的兜底是后面的 0x66/0x99 复位
  1026. * 与"跳转后 /CS 保持高电平"(见 rt_fota_spi_pins_safe_state) */
  1027. for (i = 0; i < 8; i++)
  1028. rt_fota_spi_flash_cmd(0xFF);
  1029. /* 3) 释放深度掉电(0xB9 之后只有 0xAB 能被响应) */
  1030. rt_fota_spi_flash_cmd(RT_FOTA_FLASH_CMD_RELEASE_PD);
  1031. rt_thread_mdelay(1); /* tRES1,留足余量 */
  1032. /* 4) 器件复位(不支持的型号会忽略,无副作用) */
  1033. rt_fota_spi_flash_cmd(RT_FOTA_FLASH_CMD_RESET_EN);
  1034. rt_fota_spi_flash_cmd(RT_FOTA_FLASH_CMD_RESET);
  1035. rt_thread_mdelay(1); /* tRST */
  1036. /* 5) 交接自检:读 JEDEC ID,异常时提前暴露(正常应为 0xEF4015/0xEF4016 之类) */
  1037. rt_fota_spi_flash_cmd_recv(RT_FOTA_FLASH_CMD_READ_ID, id, 3);
  1038. rt_kprintf("SPI flash handover: SR=0x%02X JEDEC ID=0x%02X%02X%02X\n",
  1039. status, id[0], id[1], id[2]);
  1040. }
  1041. /* 外设复位后:把 SPI 引脚固定为安全电平,杜绝 APP 启动前的悬空窗口 */
  1042. static void rt_fota_spi_pins_safe_state(void)
  1043. {
  1044. rt_uint32_t crl;
  1045. __HAL_RCC_GPIOA_CLK_ENABLE();
  1046. /* 先置 ODR 再改模式:切换成输出的瞬间即为高电平,不会把 Flash 选中一下 */
  1047. GPIOA->BSRR = GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7;
  1048. crl = GPIOA->CRL;
  1049. crl &= ~(0xFUL << 16); /* PA4:/CS */
  1050. crl |= (0x3UL << 16); /* 推挽输出 50MHz,ODR=1 → 不选中 */
  1051. crl &= ~(0xFFFUL << 20); /* PA5/PA6/PA7:SCK/MISO/MOSI */
  1052. crl |= (0x888UL << 20); /* 上拉输入,杜绝悬空引入毛刺 */
  1053. GPIOA->CRL = crl;
  1054. }
  1055. /* ============== v1.3.5:NOR 可用性快速检查(EasyFlash 初始化前置门禁) ==============
  1056. * 现场问题:SPI Flash 不可用时(SFUD 探测失败),EasyFlash 仍会对 3MB 环境区
  1057. * (768 个 4KB 扇区)逐个扇区执行"读头 → 判定无效 → 擦除 → 写头"的格式化尝试:
  1058. * - 每次读/擦/写都撞上 FAL 的 assert,各打一条日志;
  1059. * - 加上 EasyFlash 自己的 "Sector header check failed" 提示,
  1060. * 单个扇区产生约 4~5 条串口输出,768 个扇区合计近 4000 条;
  1061. * - @115200 下纯阻塞输出即达 20~30 秒,表现为"加载参数极慢、启动像卡死"。
  1062. * 更危险的是:一旦总线只是间歇异常,format_sector 有可能真的擦掉用户环境变量。
  1063. *
  1064. * 对策:在 easyflash_init() 之前先确认 NOR 真的能应答——读 JEDEC ID,
  1065. * 全 0x00 / 全 0xFF 视为不可用,直接跳过 EasyFlash 初始化并给出单条明确提示。
  1066. * 效果:故障时启动从数十秒降到毫秒级,且不会产生任何破坏性写入。
  1067. * 安全性:EasyFlash 未初始化时 ef_get_env_blob / ef_set_env_blob 内部有 init_ok
  1068. * 判据,会安全返回失败而不是崩溃(已核对 ef_env.c)。
  1069. */
  1070. int rt_fota_nor_ready(void)
  1071. {
  1072. rt_uint8_t id[3] = {0, 0, 0};
  1073. rt_fota_spi_flash_cmd_recv(RT_FOTA_FLASH_CMD_READ_ID, id, 3);
  1074. /* 全 0x00(MISO 被拉低/设备未接)或全 0xFF(MISO 悬空/设备无响应)均判不可用 */
  1075. if (((id[0] == 0x00) && (id[1] == 0x00) && (id[2] == 0x00)) ||
  1076. ((id[0] == 0xFF) && (id[1] == 0xFF) && (id[2] == 0xFF)))
  1077. {
  1078. rt_kprintf("NOR flash not responding (JEDEC ID=0x%02X%02X%02X).\n", id[0], id[1], id[2]);
  1079. return 0;
  1080. }
  1081. return 1;
  1082. }
  1083. int rt_fota_start_application(void)
  1084. {
  1085. int fota_res = RT_FOTA_NO_ERR;
  1086. const struct fal_partition *part;
  1087. rt_uint32_t app_addr;
  1088. part = fal_partition_find(RT_FOTA_APP_PART_NAME);
  1089. if (part == RT_NULL)
  1090. {
  1091. LOG_D("Partition[%s] not found.", fota_part_head.app_part_name);
  1092. fota_res = RT_FOTA_GENERAL_ERR;
  1093. goto __exit_start_application;
  1094. }
  1095. app_addr = part->offset + 0x08000000;
  1096. //�ж��Ƿ�Ϊ0x08XXXXXX.
  1097. if (((*(__IO uint32_t *)(app_addr + 4)) & 0xff000000) != 0x08000000)
  1098. {
  1099. LOG_I("Illegal Flash code.");
  1100. fota_res = RT_FOTA_GENERAL_ERR;
  1101. goto __exit_start_application;
  1102. }
  1103. // ���ջ����ַ�Ƿ�Ϸ�.
  1104. if (((*(__IO uint32_t *)app_addr) & 0x2ffe0000) != 0x20000000)
  1105. {
  1106. LOG_I("Illegal Stack code.");
  1107. fota_res = RT_FOTA_GENERAL_ERR;
  1108. goto __exit_start_application;
  1109. }
  1110. /* v1.3.0:写"启动尝试"标记(0xDEAD)——APP 启动后(main 开头)会清零;
  1111. * 若复位后仍残留,说明 APP 未正常启动,由 rt_fota_check_boot_state() 触发回滚 */
  1112. rt_fota_bkp_dr2_write(RT_FOTA_BOOT_TRY_BKP_MAGIC);
  1113. LOG_I("Implement application now.");
  1114. /* v1.3.2:把 SPI Flash 恢复到标准 SPI 空闲态(必须放在关中断之前,
  1115. * 因为 rt_spi_* 走总线互斥量/延时,关中断后会失去调度) */
  1116. rt_fota_spi_flash_quiesce();
  1117. __disable_irq();
  1118. /* 禁用并清除全部 NVIC 中断(原循环因 F1 无 FPU_IRQn 被注释,改用寄存器遍历),
  1119. * 防止 APP 启动初期残留/挂起中断使用旧向量表或未初始化外设 */
  1120. for (int nvic_idx = 0; nvic_idx < 8; nvic_idx++)
  1121. {
  1122. NVIC->ICER[nvic_idx] = 0xFFFFFFFF;
  1123. NVIC->ICPR[nvic_idx] = 0xFFFFFFFF;
  1124. }
  1125. /* 清除可能挂起的系统异常(PendSV/SysTick) */
  1126. SCB->ICSR |= SCB_ICSR_PENDSVCLR_Msk;
  1127. SCB->ICSR |= SCB_ICSR_PENDSTCLR_Msk;
  1128. /* 停止 SysTick */
  1129. SysTick->CTRL = 0;
  1130. SysTick->LOAD = 0;
  1131. SysTick->VAL = 0;
  1132. /* 外设与时钟恢复到默认状态 */
  1133. HAL_DeInit();
  1134. HAL_RCC_DeInit();
  1135. /* v1.3.2:上面的 APB2 复位会把 GPIOA 打回浮空输入,这里重新固定 SPI 引脚电平,
  1136. * 保证从此刻到 APP 配好引脚之间 /CS 始终为高、时钟/数据线不被噪声干扰 */
  1137. rt_fota_spi_pins_safe_state();
  1138. /* 向量表预先指向 APP(其 SystemInit 会先写回 0x08000000,此步保证交接窗口安全) */
  1139. SCB->VTOR = app_addr;
  1140. __DSB();
  1141. __ISB();
  1142. //用户代码区第二个字为程序开始地址(复位地址)
  1143. app_func = (rt_fota_app_func)*(__IO uint32_t *)(app_addr + 4);
  1144. /* Configure main stack */
  1145. __set_MSP(*(__IO uint32_t *)app_addr);
  1146. /* 由线程(PSP)切回 MSP:APP 以复位状态(CONTROL=0)运行 */
  1147. __set_CONTROL(0);
  1148. /* 恢复中断屏蔽(PRIMASK=0),以接近复位后的状态进入 APP */
  1149. __enable_irq();
  1150. /* jump to application */
  1151. app_func();
  1152. __exit_start_application:
  1153. LOG_I("Implement application failed.");
  1154. HMI_WRITE("Implement application failed.");
  1155. return fota_res;
  1156. }
  1157. static rt_err_t rt_fota_get_shell_key(void)
  1158. {
  1159. char ch;
  1160. rt_err_t res = RT_EOK;
  1161. rt_uint32_t timeout = RT_FOTA_GET_CHAR_WAITTIGN;
  1162. rt_tick_t tick_start, tick_stop;
  1163. RT_ASSERT(shell_dev != RT_NULL);
  1164. RT_ASSERT(shell_sem != RT_NULL);
  1165. rt_tick_set(0);
  1166. tick_start = rt_tick_get();
  1167. while (1)
  1168. {
  1169. if (rt_device_read(shell_dev, -1, &ch, 1) != 1)
  1170. {
  1171. if (rt_sem_take(shell_sem, timeout) != RT_EOK)
  1172. {
  1173. res = RT_ERROR;
  1174. goto __exit_get_shell_key;
  1175. }
  1176. }
  1177. if (ch == 0x0d)
  1178. goto __exit_get_shell_key;
  1179. tick_stop = rt_tick_get();
  1180. if ((tick_stop - tick_start) > RT_FOTA_GET_CHAR_WAITTIGN)
  1181. {
  1182. res = RT_ERROR;
  1183. goto __exit_get_shell_key;
  1184. }
  1185. timeout = RT_FOTA_GET_CHAR_WAITTIGN - tick_stop + tick_start;
  1186. }
  1187. __exit_get_shell_key:
  1188. if(stop_in_bootloader!=0)
  1189. {
  1190. res = RT_EOK;
  1191. }
  1192. return res;
  1193. }
  1194. static rt_err_t rt_fota_rx_ind(rt_device_t dev, rt_size_t size)
  1195. {
  1196. RT_ASSERT(shell_sem != RT_NULL);
  1197. /* release semaphore to let fota thread rx data */
  1198. rt_sem_release(shell_sem);
  1199. return RT_EOK;
  1200. }
  1201. static rt_err_t rt_fota_set_device(const char *device_name)
  1202. {
  1203. rt_device_t dev;
  1204. RT_ASSERT(device_name != RT_NULL);
  1205. dev = rt_device_find(device_name);
  1206. if (dev == RT_NULL)
  1207. {
  1208. LOG_D("Can not find device: %s.", device_name);
  1209. return RT_ERROR;
  1210. }
  1211. if (shell_sem)
  1212. rt_sem_delete(shell_sem);
  1213. shell_sem = rt_sem_create("shell_sem", 0, RT_IPC_FLAG_FIFO);
  1214. if (shell_sem == RT_NULL)
  1215. return RT_ERROR;
  1216. if (dev == shell_dev)
  1217. return RT_EOK;
  1218. if (rt_device_open(dev, RT_DEVICE_OFLAG_RDWR | RT_DEVICE_FLAG_INT_RX | RT_DEVICE_FLAG_STREAM) == RT_EOK)
  1219. {
  1220. if (shell_dev != RT_NULL)
  1221. {
  1222. /* close old finsh device */
  1223. rt_device_close(shell_dev);
  1224. rt_device_set_rx_indicate(shell_dev, RT_NULL);
  1225. }
  1226. shell_dev = dev;
  1227. rt_device_set_rx_indicate(dev, rt_fota_rx_ind);
  1228. LOG_D("Shell device %s open success.", device_name);
  1229. return RT_EOK;
  1230. }
  1231. LOG_D("Shell device %s open failed.", device_name);
  1232. return RT_ERROR;
  1233. }
  1234. #if defined(RT_FOTA_DEFAULT_KEY_PIN) && defined(RT_FOTA_DEFAULT_KEY_CHK_TIME)
  1235. static rt_err_t rt_fota_check_defalut_key(void)
  1236. {
  1237. int chk_idx;
  1238. /* GPIO initialized */
  1239. rt_pin_mode(RT_FOTA_DEFAULT_KEY_PIN, PIN_MODE_INPUT_PULLUP);
  1240. /* Delay for power up */
  1241. rt_thread_mdelay(500);
  1242. if (rt_pin_read(RT_FOTA_DEFAULT_KEY_PIN) == PIN_LOW)
  1243. rt_kprintf("Default firmware key pressed:\n");
  1244. /* Check GPIO status */
  1245. for (chk_idx = 0; (rt_pin_read(RT_FOTA_DEFAULT_KEY_PIN) == PIN_LOW) && (chk_idx < RT_FOTA_DEFAULT_KEY_CHK_TIME); chk_idx++)
  1246. {
  1247. rt_thread_mdelay(RT_TICK_PER_SECOND);
  1248. rt_kprintf(">");
  1249. }
  1250. if (chk_idx < RT_FOTA_DEFAULT_KEY_CHK_TIME)
  1251. return RT_ERROR;
  1252. else
  1253. return RT_EOK;
  1254. }
  1255. #endif
  1256. /* 检测应用侧写入的 RTC_BKP_DR2 升级请求(值约定见文件头 v1.3.0 区块):
  1257. * 命中 0x5AA5 时清除标志并返回 RT_EOK(请求 ymodem 升级) */
  1258. static rt_err_t rt_fota_check_ymodem_request(void)
  1259. {
  1260. rt_uint16_t boot_flag;
  1261. boot_flag = rt_fota_bkp_dr2_read();
  1262. if (boot_flag != RT_FOTA_YMODEM_REQ_BKP_MAGIC)
  1263. {
  1264. return RT_ERROR;
  1265. }
  1266. /* 先清除标志:避免 ymodem 完成复位后再次进入升级模式(app 启动时也会清除) */
  1267. rt_fota_bkp_dr2_write(0x0000);
  1268. return RT_EOK;
  1269. }
  1270. /* ===================== v1.3.0 APP 固件备份 / 回滚 ===================== */
  1271. /* 将当前 APP 分区固件备份到 df_area(升级搬运前自动调用;uart4 "backupapp" 手动触发)。
  1272. * 流程:失效旧头 -> 读 APP 计算 CRC -> 擦数据区 -> 回写数据 -> 最后写头。
  1273. * 返回 RT_FOTA_NO_ERR 表示备份有效。 */
  1274. int rt_fota_backup_app_to_df(void)
  1275. {
  1276. rt_kprintf("rt_fota_backup_app_to_df!");
  1277. rt_fota_backup_head_t head;
  1278. const struct fal_partition *app_part;
  1279. const struct fal_partition *df_part;
  1280. rt_uint8_t *buf = RT_NULL;
  1281. rt_uint32_t data_len = 0, pos, read_need, read_len, crc, erase_len;
  1282. int fota_res = RT_FOTA_NO_ERR;
  1283. app_part = fal_partition_find(RT_FOTA_APP_PART_NAME);
  1284. df_part = fal_partition_find(RT_FOTA_DF_PART_NAME);
  1285. if ((app_part == RT_NULL) || (df_part == RT_NULL))
  1286. {
  1287. LOG_I("Backup: partition not found.");
  1288. fota_res = RT_FOTA_GENERAL_ERR;
  1289. goto __exit_backup;
  1290. }
  1291. /* 数据区(头部预留 + APP 大小)必须容得下 */
  1292. data_len = app_part->len;
  1293. erase_len = RT_ALIGN(data_len, RT_FOTA_BACKUP_BLK_SIZE);
  1294. if ((RT_FOTA_BACKUP_HEAD_RSV + erase_len) > df_part->len)
  1295. {
  1296. LOG_I("Backup: no enough space in [%s].", df_part->name);
  1297. fota_res = RT_FOTA_GENERAL_ERR;
  1298. goto __exit_backup;
  1299. }
  1300. buf = rt_malloc(RT_FOTA_BACKUP_BLK_SIZE);
  1301. if (buf == RT_NULL)
  1302. {
  1303. LOG_I("Backup: no memory.");
  1304. fota_res = RT_FOTA_NO_MEM_ERR;
  1305. goto __exit_backup;
  1306. }
  1307. /* 1. 先擦除备份头:旧备份即刻失效,中途掉电不会残留旧的"有效"magic */
  1308. if (fal_partition_erase(df_part, 0, RT_FOTA_BACKUP_HEAD_RSV) < 0)
  1309. {
  1310. LOG_I("Backup: erase backup head failed.");
  1311. fota_res = RT_FOTA_PART_ERASE_ERR;
  1312. goto __exit_backup;
  1313. }
  1314. rt_fota_wdt_feed();
  1315. /* 2. 读取 APP 分区并计算数据 CRC32 */
  1316. extern rt_uint32_t rt_fota_step_crc(rt_uint32_t crc, rt_uint8_t *buf, rt_uint32_t len);
  1317. crc = 0xffffffff;
  1318. for (pos = 0; pos < data_len;)
  1319. {
  1320. read_need = data_len - pos;
  1321. if (read_need > RT_FOTA_BACKUP_BLK_SIZE)
  1322. read_need = RT_FOTA_BACKUP_BLK_SIZE;
  1323. read_len = fal_partition_read(app_part, pos, buf, read_need);
  1324. if (read_len <= 0)
  1325. {
  1326. LOG_I("Backup: read [%s] failed.", app_part->name);
  1327. fota_res = RT_FOTA_PART_READ_ERR;
  1328. goto __exit_backup;
  1329. }
  1330. crc = rt_fota_step_crc(crc, buf, read_len);
  1331. pos += read_len;
  1332. rt_fota_wdt_feed();
  1333. rt_kprintf("#");
  1334. }
  1335. crc ^= 0xffffffff;
  1336. /* 3. 擦除数据区:分块擦除并逐块喂狗(整块 312KB 在 NOR 上最坏要擦 30s 以上,
  1337. * 一次性调用必然触发 IWDG 10s 超时复位) */
  1338. if (rt_fota_erase_chunked(df_part, RT_FOTA_BACKUP_HEAD_RSV, erase_len) < 0)
  1339. {
  1340. LOG_I("Backup: erase data area failed.");
  1341. fota_res = RT_FOTA_PART_ERASE_ERR;
  1342. goto __exit_backup;
  1343. }
  1344. /* 4. 回写 APP 数据到 df_area */
  1345. for (pos = 0; pos < data_len;)
  1346. {
  1347. read_need = data_len - pos;
  1348. if (read_need > RT_FOTA_BACKUP_BLK_SIZE)
  1349. read_need = RT_FOTA_BACKUP_BLK_SIZE;
  1350. read_len = fal_partition_read(app_part, pos, buf, read_need);
  1351. if (read_len <= 0)
  1352. {
  1353. LOG_I("Backup: read [%s] failed.", app_part->name);
  1354. fota_res = RT_FOTA_PART_READ_ERR;
  1355. goto __exit_backup;
  1356. }
  1357. if (fal_partition_write(df_part, RT_FOTA_BACKUP_HEAD_RSV + pos, buf, read_len) < 0)
  1358. {
  1359. LOG_I("Backup: write [%s] failed.", df_part->name);
  1360. fota_res = RT_FOTA_PART_WRITE_ERR;
  1361. goto __exit_backup;
  1362. }
  1363. pos += read_len;
  1364. /* 喂狗放在 HMI_WRITE 之前:串口屏是阻塞发送(每次十几 ms),
  1365. * 78 块累计也有秒级,先确保看门狗被喂过 */
  1366. rt_fota_wdt_feed();
  1367. HMI_WRITE("debug.update.val=%d", (int)(pos * 100 / data_len));
  1368. rt_kprintf("#");
  1369. }
  1370. rt_kprintf("\r\n");
  1371. /* 5. 最后写头部:备份自此生效 */
  1372. head.magic = RT_FOTA_BACKUP_MAGIC;
  1373. head.data_len = data_len;
  1374. head.data_crc = crc;
  1375. extern rt_uint32_t rt_fota_crc(rt_uint8_t *buf, rt_uint32_t len);
  1376. head.head_crc = rt_fota_crc((rt_uint8_t *)&head, sizeof(head) - 4);
  1377. if (fal_partition_write(df_part, 0, (const rt_uint8_t *)&head, sizeof(head)) < 0)
  1378. {
  1379. LOG_I("Backup: write backup head failed.");
  1380. fota_res = RT_FOTA_PART_WRITE_ERR;
  1381. goto __exit_backup;
  1382. }
  1383. __exit_backup:
  1384. if (buf)
  1385. rt_free(buf);
  1386. if (fota_res == RT_FOTA_NO_ERR)
  1387. LOG_I("Backup app to df_area success, %d bytes.", data_len);
  1388. return fota_res;
  1389. }
  1390. /* 将 df_area 中的有效备份固件恢复到 APP 分区(带完整性校验;供启动失败自动
  1391. * 回滚、uart4 的 "dbg_restore" / "resetapp" 命令共用)。
  1392. * consume_backup:恢复成功后是否消费(擦除)备份头——自动回滚置 1,防止"恢复
  1393. * 的固件也无法启动"时反复恢复擦写 flash;手动命令置 0,保留备份便于重复调试。
  1394. * 返回 RT_FOTA_NO_ERR 表示恢复完成。 */
  1395. int rt_fota_restore_app_from_df(int consume_backup)
  1396. {
  1397. LOG_I("rt_fota_restore_app_from_df:%d", consume_backup);
  1398. rt_fota_backup_head_t head;
  1399. const struct fal_partition *app_part;
  1400. const struct fal_partition *df_part;
  1401. rt_uint8_t *buf = RT_NULL;
  1402. rt_uint32_t pos, read_need, read_len, crc;
  1403. int fota_res = RT_FOTA_NO_ERR;
  1404. rt_memset(&head, 0, sizeof(head));
  1405. app_part = fal_partition_find(RT_FOTA_APP_PART_NAME);
  1406. df_part = fal_partition_find(RT_FOTA_DF_PART_NAME);
  1407. if ((app_part == RT_NULL) || (df_part == RT_NULL))
  1408. {
  1409. LOG_I("Restore: partition not found.");
  1410. fota_res = RT_FOTA_GENERAL_ERR;
  1411. goto __exit_restore;
  1412. }
  1413. /* 1. 读备份头并校验(magic + 头 CRC32 + 长度合法性) */
  1414. if (fal_partition_read(df_part, 0, (rt_uint8_t *)&head, sizeof(head)) < 0)
  1415. {
  1416. LOG_I("Restore: read backup head failed.");
  1417. fota_res = RT_FOTA_PART_READ_ERR;
  1418. goto __exit_restore;
  1419. }
  1420. extern rt_uint32_t rt_fota_crc(rt_uint8_t *buf, rt_uint32_t len);
  1421. if ((head.magic != RT_FOTA_BACKUP_MAGIC) ||
  1422. (rt_fota_crc((rt_uint8_t *)&head, sizeof(head) - 4) != head.head_crc))
  1423. {
  1424. LOG_I("Restore: no valid backup in [%s].", df_part->name);
  1425. fota_res = RT_FOTA_FW_VERIFY_FAILED;
  1426. goto __exit_restore;
  1427. }
  1428. if ((head.data_len == 0) ||
  1429. (head.data_len > app_part->len) ||
  1430. ((RT_FOTA_BACKUP_HEAD_RSV + head.data_len) > df_part->len))
  1431. {
  1432. LOG_I("Restore: invalid backup length(%d).", head.data_len);
  1433. fota_res = RT_FOTA_FW_VERIFY_FAILED;
  1434. goto __exit_restore;
  1435. }
  1436. buf = rt_malloc(RT_FOTA_BACKUP_BLK_SIZE);
  1437. if (buf == RT_NULL)
  1438. {
  1439. LOG_I("Restore: no memory.");
  1440. fota_res = RT_FOTA_NO_MEM_ERR;
  1441. goto __exit_restore;
  1442. }
  1443. /* 2. 备份数据 CRC32 校验(先校验后擦写,避免把无效数据写入 APP 分区) */
  1444. extern rt_uint32_t rt_fota_step_crc(rt_uint32_t crc, rt_uint8_t *buf, rt_uint32_t len);
  1445. crc = 0xffffffff;
  1446. for (pos = 0; pos < head.data_len;)
  1447. {
  1448. read_need = head.data_len - pos;
  1449. if (read_need > RT_FOTA_BACKUP_BLK_SIZE)
  1450. read_need = RT_FOTA_BACKUP_BLK_SIZE;
  1451. read_len = fal_partition_read(df_part, RT_FOTA_BACKUP_HEAD_RSV + pos, buf, read_need);
  1452. if (read_len <= 0)
  1453. {
  1454. LOG_I("Restore: read [%s] failed.", df_part->name);
  1455. fota_res = RT_FOTA_PART_READ_ERR;
  1456. goto __exit_restore;
  1457. }
  1458. crc = rt_fota_step_crc(crc, buf, read_len);
  1459. pos += read_len;
  1460. rt_fota_wdt_feed();
  1461. rt_kprintf("#");
  1462. }
  1463. crc ^= 0xffffffff;
  1464. if (crc != head.data_crc)
  1465. {
  1466. LOG_I("Restore: backup data CRC32 error (0x%08X != 0x%08X).", crc, head.data_crc);
  1467. fota_res = RT_FOTA_FW_VERIFY_FAILED;
  1468. goto __exit_restore;
  1469. }
  1470. /* 3. 擦除 APP 分区并回写备份数据:分块擦除 + 逐块喂狗
  1471. * (自动回滚路径尤其关键:擦到一半被看门狗复位,会变成"回滚-复位"死循环) */
  1472. if (rt_fota_erase_chunked(app_part, 0, app_part->len) < 0)
  1473. {
  1474. LOG_I("Restore: erase [%s] failed.", app_part->name);
  1475. fota_res = RT_FOTA_PART_ERASE_ERR;
  1476. goto __exit_restore;
  1477. }
  1478. for (pos = 0; pos < head.data_len;)
  1479. {
  1480. read_need = head.data_len - pos;
  1481. if (read_need > RT_FOTA_BACKUP_BLK_SIZE)
  1482. read_need = RT_FOTA_BACKUP_BLK_SIZE;
  1483. read_len = fal_partition_read(df_part, RT_FOTA_BACKUP_HEAD_RSV + pos, buf, read_need);
  1484. if (read_len <= 0)
  1485. {
  1486. LOG_I("Restore: read [%s] failed.", df_part->name);
  1487. fota_res = RT_FOTA_PART_READ_ERR;
  1488. goto __exit_restore;
  1489. }
  1490. if (fal_partition_write(app_part, pos, buf, read_len) < 0)
  1491. {
  1492. LOG_I("Restore: write [%s] failed.", app_part->name);
  1493. fota_res = RT_FOTA_PART_WRITE_ERR;
  1494. goto __exit_restore;
  1495. }
  1496. pos += read_len;
  1497. rt_fota_wdt_feed();
  1498. HMI_WRITE("debug.update.val=%d", (int)(pos * 100 / head.data_len));
  1499. rt_kprintf("#");
  1500. }
  1501. rt_kprintf("\r\n");
  1502. /* 4. 自动回滚场景消费备份,防止"恢复的固件仍无法启动"反复恢复 */
  1503. if (consume_backup)
  1504. {
  1505. if (fal_partition_erase(df_part, 0, RT_FOTA_BACKUP_HEAD_RSV) < 0)
  1506. LOG_I("Restore: consume backup head failed.");
  1507. else
  1508. LOG_I("Restore: backup consumed.");
  1509. }
  1510. __exit_restore:
  1511. if (buf)
  1512. rt_free(buf);
  1513. if (fota_res == RT_FOTA_NO_ERR)
  1514. LOG_I("Restore app from df_area success, %d bytes.", head.data_len);
  1515. else
  1516. LOG_I("Restore app from df_area failed(%d).", fota_res);
  1517. return fota_res;
  1518. }
  1519. /* 启动失败检测与自动回滚:进入 bootloader 后读取 RTC_BKP_DR2——
  1520. * 0 / 0x5AA5 分别表示上次启动正常 / 升级请求(由 ymodem 检测处理),跳过;
  1521. * 其它非 0 值(跳转前写入的 0xDEAD 未被 APP 清零)说明 APP 未正常启动:
  1522. * 标记 0xDEAD -> 有有效备份则回滚 APP -> 对齐 fm_area 版本,防止同一升级包
  1523. * 在回滚后再次被自动应用(用户重新下发升级包会重写 fm_area,不受影响)。 */
  1524. static void rt_fota_check_boot_state(void)
  1525. {
  1526. rt_uint16_t boot_flag = rt_fota_bkp_dr2_read();
  1527. if ((boot_flag == 0x0000) || (boot_flag == RT_FOTA_YMODEM_REQ_BKP_MAGIC))
  1528. {
  1529. return;
  1530. }
  1531. LOG_I("RTC_BKP_DR2 = 0x%04X: application boot failed, try restore.", boot_flag);
  1532. rt_fota_signal_led_mode(led_upgrade_mode);
  1533. /* 约定:检测到启动失败先标记 0xDEAD */
  1534. rt_fota_bkp_dr2_write(RT_FOTA_BOOT_TRY_BKP_MAGIC);
  1535. if (rt_fota_restore_app_from_df(1) == RT_FOTA_NO_ERR)
  1536. {
  1537. /* 对齐 fm_area 版本:本次升级包视为已处理,避免回滚后再次自动升级 */
  1538. rt_fota_copy_version(RT_FOTA_FM_PART_NAME);
  1539. }
  1540. else
  1541. {
  1542. LOG_I("No valid backup in df_area, skip restore.");
  1543. }
  1544. }
  1545. void rt_fota_thread_entry(void *arg)
  1546. {
  1547. int fota_err = RT_FOTA_NO_ERR;
  1548. extern int finsh_system_init(void);
  1549. /* Signal led initialized */
  1550. rt_fota_signal_led_init();
  1551. /* Partition initialized */
  1552. fota_err = rt_fota_boot_verify();
  1553. if (fota_err != RT_FOTA_NO_ERR)
  1554. {
  1555. LOG_I("Partition initialized failed.");
  1556. }
  1557. #if defined(RT_FOTA_DEFAULT_KEY_PIN) && defined(RT_FOTA_DEFAULT_KEY_CHK_TIME)
  1558. /* Default key check */
  1559. if (rt_fota_check_defalut_key() == RT_EOK)
  1560. {
  1561. /* enter to defalut key mode */
  1562. rt_fota_signal_led_mode(led_upgrade_mode);
  1563. goto __exit_default_entry;
  1564. }
  1565. #endif
  1566. /* RTC 备份寄存器 DR2 升级请求检测:命中 0x5AA5 → 停留 bootloader 执行 ymodem 升级 */
  1567. if (rt_fota_check_ymodem_request() == RT_EOK)
  1568. {
  1569. extern void ymodem_ota(uint8_t argc, char **argv);
  1570. LOG_I("RTC_BKP_DR2 = 0x5AA5, stay in bootloader, start ymodem ota.");
  1571. rt_fota_signal_led_mode(led_upgrade_mode);
  1572. /* 下载分区默认 fm_area;ymodem 完成后内部复位,正常不返回 */
  1573. ymodem_ota(1, RT_NULL);
  1574. }
  1575. /* v1.3.0:启动失败检测与自动回滚(详见函数注释),需在 shell 交互前处理 */
  1576. rt_fota_check_boot_state();
  1577. /* Shell initialized */
  1578. if (rt_fota_set_device(RT_CONSOLE_DEVICE_NAME) == RT_EOK)
  1579. {
  1580. /* v1.3.5:EasyFlash 前置门禁——NOR 不响应时不要进去,
  1581. * 否则会对 768 个扇区逐一做无效的格式化尝试(近 4000 条日志、
  1582. * 阻塞启动 20~30 秒),且存在误擦用户环境变量的风险 */
  1583. if ((rt_fota_nor_ready() != 0) && (easyflash_init() == EF_NO_ERR)) //初始化成功
  1584. {
  1585. rt_uint8_t boot_flag_buf[4] = {0, 0, 0, 0};
  1586. ef_get_env_blob("stop_in_bootloader", boot_flag_buf, sizeof(boot_flag_buf), NULL);
  1587. /* 兼容三种历史存储格式:字符串 "0"/"1"(EasyFlash 默认值)与二进制 0/1。
  1588. * 历史缺陷:默认值 "0" 按二进制读为 0x30(非零),会误判为停留引导模式 */
  1589. if (boot_flag_buf[0] == '0')
  1590. stop_in_bootloader = 0;
  1591. else if (boot_flag_buf[0] == '1')
  1592. stop_in_bootloader = 1;
  1593. else
  1594. stop_in_bootloader = (boot_flag_buf[0] != 0) ? 1 : 0;
  1595. rt_kprintf("stop_in_bootloader:%d\n", stop_in_bootloader);
  1596. }
  1597. rt_kprintf("Please press [Enter] key into shell mode in %d secs:\r\n", RT_FOTA_GET_CHAR_WAITTIGN / RT_TICK_PER_SECOND);
  1598. if (rt_fota_get_shell_key() == RT_EOK)
  1599. {
  1600. if(stop_in_bootloader!=0)
  1601. {
  1602. stop_in_bootloader = 0;
  1603. ef_set_env_blob("stop_in_bootloader", &stop_in_bootloader, sizeof(stop_in_bootloader));
  1604. }
  1605. goto __exit_shell_entry;
  1606. }
  1607. }
  1608. else
  1609. {
  1610. LOG_I("Shell device config failed.");
  1611. }
  1612. /* Firmware partition verify */
  1613. fota_err = rt_fota_part_fw_verify(RT_FOTA_FM_PART_NAME);
  1614. if (fota_err != RT_FOTA_NO_ERR)
  1615. goto __exit_boot_entry;
  1616. /* Check upgrade status */
  1617. if (rt_fota_check_upgrade() <= 0)
  1618. goto __exit_boot_entry;
  1619. /* v1.3.4:重试熔断——同一版本连续失败到上限后不再动 flash,直接跳 APP。
  1620. * 否则 upgrade 失败会让 fm_area 永远处于"待升级"状态,每次上电都重跑
  1621. * backup(312KB 读+擦+写) + 升级,形成"重启-升级-失败"循环 */
  1622. if (rt_fota_retry_allow() != RT_TRUE)
  1623. goto __exit_boot_entry;
  1624. /* enter to upgrade mode */
  1625. rt_fota_signal_led_mode(led_upgrade_mode);
  1626. /* v1.3.0:搬运前先把当前 APP 固件备份到 df_area(新固件启动失败时回滚用)。
  1627. * 备份失败不阻断升级(极端情况 df_area 异常;升级包读自 fm_area) */
  1628. if (rt_fota_backup_app_to_df() != RT_FOTA_NO_ERR)
  1629. {
  1630. LOG_I("Backup app to df_area failed, continue upgrade.");
  1631. }
  1632. /* Implement upgrade, copy firmware partition to app partition */
  1633. fota_err = rt_fota_upgrade(RT_FOTA_FM_PART_NAME);
  1634. if (fota_err != RT_FOTA_NO_ERR)
  1635. {
  1636. LOG_I("Upgrade failed(%d), fm_area image kept for retry.", fota_err);
  1637. goto __exit_boot_entry;
  1638. }
  1639. /* Update new application verison in RBL file of firmware partition */
  1640. fota_err = rt_fota_copy_version(RT_FOTA_FM_PART_NAME);
  1641. if (fota_err != RT_FOTA_NO_ERR)
  1642. {
  1643. LOG_I("Copy version failed(%d), fm_area stays pending upgrade.", fota_err);
  1644. goto __exit_boot_entry;
  1645. }
  1646. /* 升级 + 版本对齐都成功:清零熔断计数,下次上电不会再走升级分支 */
  1647. rt_fota_retry_clear();
  1648. rt_kprintf("Upgrade done, version[%s] applied.\n", fota_part_head.download_version);
  1649. __exit_boot_entry:
  1650. /* Implement application */
  1651. rt_fota_start_application();
  1652. #if defined(RT_FOTA_DEFAULT_KEY_PIN) && defined(RT_FOTA_DEFAULT_KEY_CHK_TIME)
  1653. __exit_default_entry:
  1654. #endif
  1655. /* Implement upgrade, copy default partition to app partition */
  1656. if (rt_fota_part_fw_verify(RT_FOTA_DF_PART_NAME) == RT_FOTA_NO_ERR)
  1657. {
  1658. if (rt_fota_upgrade(RT_FOTA_DF_PART_NAME) == RT_FOTA_NO_ERR)
  1659. {
  1660. rt_fota_start_application();
  1661. }
  1662. }
  1663. LOG_I("Boot application failed, entry shell mode.");
  1664. __exit_shell_entry:
  1665. /* enter to shell mode */
  1666. rt_fota_signal_led_mode(led_shell_mode);
  1667. /* Implement shell */
  1668. finsh_system_init();
  1669. }
  1670. void rt_fota_init(void)
  1671. {
  1672. rt_thread_t tid;
  1673. tid = rt_thread_create("rt-boot", rt_fota_thread_entry, RT_NULL, RT_FOTA_THREAD_STACK_SIZE, RT_FOTA_THREAD_PRIORITY, 10);
  1674. if (tid != RT_NULL)
  1675. {
  1676. rt_thread_startup(tid);
  1677. }
  1678. else
  1679. {
  1680. LOG_I("rt-fota thread create failed.");
  1681. }
  1682. }
  1683. void rt_fota_info(rt_uint8_t argc, char **argv)
  1684. {
  1685. char put_buf[24];
  1686. char part_name[2][FAL_DEV_NAME_MAX] =
  1687. {
  1688. {RT_FOTA_FM_PART_NAME},
  1689. {RT_FOTA_DF_PART_NAME}
  1690. };
  1691. const char* help_info[] =
  1692. {
  1693. [0] = "fota probe - probe RBL file of partiton",
  1694. [1] = "fota show partition addr size - show 'size' bytes starting at 'addr'",
  1695. [2] = "fota retry [0] - show or clear upgrade retry counter",
  1696. [3] = "fota clone des_part src_part - clone src partition to des partiton",
  1697. [4] = "fota exec - execute application program",
  1698. };
  1699. if (argc < 2)
  1700. {
  1701. rt_kprintf("Usage:\n");
  1702. for (int i = 0; i < sizeof(help_info) / sizeof(char*); i++)
  1703. {
  1704. rt_kprintf("%s\n", help_info[i]);
  1705. }
  1706. rt_kprintf("\n");
  1707. }
  1708. else
  1709. {
  1710. const char *operator = argv[1];
  1711. if (!rt_strcmp(operator, "probe"))
  1712. {
  1713. for (int i = 0; i < 2; i++)
  1714. {
  1715. if (rt_fota_part_fw_verify(&part_name[i][0]) == RT_FOTA_NO_ERR)
  1716. {
  1717. LOG_I("===== RBL of %s partition =====", &part_name[i][0]);
  1718. LOG_I("| App partition name | %*.s |", 11, fota_part_head.app_part_name);
  1719. rt_memset(put_buf, 0x0, sizeof(put_buf));
  1720. if ((fota_part_head.fota_algo & RT_FOTA_CRYPT_STAT_MASK) == RT_FOTA_CRYPT_ALGO_AES256)
  1721. {
  1722. rt_strncpy(put_buf, " AES", 4);
  1723. }
  1724. else if ((fota_part_head.fota_algo & RT_FOTA_CRYPT_STAT_MASK) == RT_FOTA_CRYPT_ALGO_XOR)
  1725. {
  1726. rt_strncpy(put_buf, " XOR", 4);
  1727. }
  1728. else
  1729. {
  1730. rt_strncpy(put_buf, "NONE", 4);
  1731. }
  1732. if ((fota_part_head.fota_algo & RT_FOTA_CMPRS_STAT_MASK) == RT_FOTA_CMPRS_ALGO_GZIP)
  1733. {
  1734. rt_strncpy(&put_buf[rt_strlen(put_buf)], " && GLZ", 7);
  1735. }
  1736. else if ((fota_part_head.fota_algo & RT_FOTA_CMPRS_STAT_MASK) == RT_FOTA_CMPRS_ALGO_QUICKLZ)
  1737. {
  1738. rt_strncpy(&put_buf[rt_strlen(put_buf)], " && QLZ", 7);
  1739. }
  1740. else if ((fota_part_head.fota_algo & RT_FOTA_CMPRS_STAT_MASK) == RT_FOTA_CMPRS_ALGO_FASTLZ)
  1741. {
  1742. rt_strncpy(&put_buf[rt_strlen(put_buf)], " && FLZ", 7);
  1743. }
  1744. if (rt_strlen(put_buf) <= 0)
  1745. {
  1746. rt_strncpy(put_buf, "None", 4);
  1747. }
  1748. LOG_I("| Algorithm mode | %*.s |", 11, put_buf);
  1749. LOG_I("| Firmware version | %*.s |", 11, fota_part_head.download_version);
  1750. /* v1.3.4:把 current_version 和"是否需升级"一并打出来。
  1751. * 这两个字段不等就会在每次上电触发升级+备份,原来完全看不到 */
  1752. LOG_I("| Applied version | %*.s |", 11, fota_part_head.current_version);
  1753. LOG_I("| Upgrade pending | %11s |",
  1754. (rt_strcmp(fota_part_head.download_version, fota_part_head.current_version) != 0)
  1755. ? "YES" : "NO");
  1756. LOG_I("| Code raw size | %11d |", fota_part_head.raw_size);
  1757. LOG_I("| Code package size | %11d |", fota_part_head.com_size);
  1758. LOG_I("| Build Timestamp | %11d |", *((rt_uint32_t *)(&fota_part_head.fm_time[2])));
  1759. }
  1760. }
  1761. }
  1762. else if (!rt_strcmp(operator, "show"))
  1763. {
  1764. const struct fal_partition *part;
  1765. const char *part_name = argv[2];
  1766. rt_uint32_t addr = strtol(argv[3], NULL, 0);
  1767. rt_uint32_t size = strtol(argv[4], NULL, 0);
  1768. rt_uint8_t buf[16];
  1769. part = fal_partition_find(part_name);
  1770. if (part != RT_NULL)
  1771. {
  1772. while (size > 16)
  1773. {
  1774. fal_partition_read(part, addr, buf, 16);
  1775. rt_kprintf("%08X: ", addr);
  1776. for (int i = 0; i < 16; i++)
  1777. {
  1778. rt_kprintf("%02X ", buf[i]);
  1779. }
  1780. rt_kprintf("\n");
  1781. size -= 16;
  1782. addr += 16;
  1783. }
  1784. fal_partition_read(part, addr, buf, size);
  1785. rt_kprintf("%08X: ", addr);
  1786. for (int i = 0; i < size; i++)
  1787. {
  1788. rt_kprintf("%02X ", buf[i]);
  1789. }
  1790. rt_kprintf("\n");
  1791. }
  1792. else
  1793. {
  1794. rt_kprintf("%s partition is not exist!\n", part_name);
  1795. }
  1796. }
  1797. else if (!rt_strcmp(operator, "retry"))
  1798. {
  1799. /* v1.3.4:查看/清除升级重试熔断记录。
  1800. * fota retry - 查看连续失败次数与上次尝试的版本
  1801. * fota retry 0 - 清零(熔断后想再试一次、或定位问题后强制重试) */
  1802. rt_fota_retry_load();
  1803. if (argc < 3)
  1804. {
  1805. rt_kprintf("Upgrade retry: cnt=%d/%d, last version=[%s]\n",
  1806. (int)fota_retry.cnt, RT_FOTA_UPGRADE_MAX_RETRY, fota_retry.ver);
  1807. rt_kprintf("Auto upgrade is %s.\n",
  1808. (fota_retry.cnt >= RT_FOTA_UPGRADE_MAX_RETRY) ? "DISABLED" : "enabled");
  1809. }
  1810. else
  1811. {
  1812. fota_retry.cnt = 0;
  1813. rt_memset(fota_retry.ver, 0, sizeof(fota_retry.ver));
  1814. rt_fota_wdt_feed();
  1815. rt_fota_retry_save();
  1816. rt_kprintf("Upgrade retry record cleared.\n");
  1817. }
  1818. }
  1819. else if (!rt_strcmp(operator, "clone"))
  1820. {
  1821. const char *dst_part_name = argv[2];
  1822. const char *src_part_name = argv[3];
  1823. const struct fal_partition *dst_part;
  1824. const struct fal_partition *src_part;
  1825. dst_part = fal_partition_find(dst_part_name);
  1826. src_part = fal_partition_find(src_part_name);
  1827. if (dst_part == RT_NULL || src_part == RT_NULL)
  1828. {
  1829. if (dst_part == RT_NULL)
  1830. rt_kprintf("%s partition is not exist!\n", dst_part_name);
  1831. if (src_part == RT_NULL)
  1832. rt_kprintf("%s partition is not exist!\n", src_part_name);
  1833. }
  1834. else
  1835. {
  1836. rt_kprintf("Clone %s partition to %s partition:\n", src_part_name, dst_part_name);
  1837. /* 分块擦除 + 逐块喂狗(dst 可能是 512KB NOR,整块擦会撞 IWDG 超时) */
  1838. if (rt_fota_erase_chunked(dst_part, 0, dst_part->len) >= 0)
  1839. {
  1840. int clone_pos = 0;
  1841. int clone_len = 0, clone_tol_len;
  1842. rt_uint8_t *buf = rt_malloc(4096);
  1843. if (dst_part->len < src_part->len)
  1844. clone_tol_len = dst_part->len;
  1845. else
  1846. clone_tol_len = src_part->len;
  1847. while ((clone_pos < clone_tol_len) && (buf != RT_NULL))
  1848. {
  1849. clone_len = fal_partition_read(src_part, clone_pos, buf, 4096);
  1850. if (clone_len < 0)
  1851. {
  1852. rt_kprintf("\nread %s partition failed, clone stop!\n", src_part_name);
  1853. break;
  1854. }
  1855. if (fal_partition_write(dst_part, clone_pos, buf, clone_len) < 0)
  1856. {
  1857. rt_kprintf("\nwrite %s partition failed, clone stop!\n", dst_part_name);
  1858. break;
  1859. }
  1860. rt_fota_wdt_feed();
  1861. rt_kprintf("#");
  1862. clone_pos += clone_len;
  1863. }
  1864. if (clone_pos >= clone_tol_len)
  1865. rt_kprintf("\nClone partition success, total %d bytes!\n", clone_tol_len);
  1866. else
  1867. rt_kprintf("\nClone partition failed!\n");
  1868. if (buf)
  1869. rt_free(buf);
  1870. }
  1871. }
  1872. }
  1873. else if (!rt_strcmp(operator, "exec"))
  1874. {
  1875. rt_fota_start_application();
  1876. }
  1877. else
  1878. {
  1879. rt_kprintf("Usage:\n");
  1880. for (int i = 0; i < sizeof(help_info) / sizeof(char*); i++)
  1881. {
  1882. rt_kprintf("%s\n", help_info[i]);
  1883. }
  1884. rt_kprintf("\n");
  1885. }
  1886. }
  1887. }
  1888. /**
  1889. * rt-fota />ymodem_ota
  1890. */
  1891. MSH_CMD_EXPORT_ALIAS(rt_fota_info, fota, Check RBL file of partition);
  1892. /* msh 命令:查看/设置 RTC_BKP_DR2 启动标志(取值约定见文件头 v1.3.0 区块)。
  1893. * 典型用途:手动进入 bootloader 维护后、重新上电前执行 `dr2 0` 清除标志,
  1894. * 避免残留非 0 值(如启动失败检测写入的 0xDEAD)在下次上电被
  1895. * rt_fota_check_boot_state() 误判为“APP 未正常启动”而触发 df_area→app 回滚;
  1896. * 也可写入 0x5AA5 / 0xDEAD 分别验证 ymodem 升级入口 / 启动失败回滚路径。 */
  1897. void rt_fota_dr2(int argc, char **argv)
  1898. {
  1899. rt_uint16_t boot_flag;
  1900. char *endp = NULL;
  1901. if (argc < 2)
  1902. {
  1903. boot_flag = rt_fota_bkp_dr2_read();
  1904. rt_kprintf("RTC_BKP_DR2 = 0x%04X", boot_flag);
  1905. if (boot_flag == 0x0000)
  1906. rt_kprintf(" (normal)\n");
  1907. else if (boot_flag == RT_FOTA_YMODEM_REQ_BKP_MAGIC)
  1908. rt_kprintf(" (ymodem upgrade request)\n");
  1909. else if (boot_flag == RT_FOTA_BOOT_TRY_BKP_MAGIC)
  1910. rt_kprintf(" (boot-fail marker, restore pending)\n");
  1911. else
  1912. rt_kprintf(" (unknown, restore pending)\n");
  1913. return;
  1914. }
  1915. boot_flag = (rt_uint16_t)strtol(argv[1], &endp, 0);
  1916. if (endp == argv[1])
  1917. {
  1918. rt_kprintf("usage: dr2 - show boot flag\n");
  1919. rt_kprintf(" dr2 0 - clear flag (avoid false restore)\n");
  1920. rt_kprintf(" dr2 <value> - set value (0x5AA5 / 0xDEAD for test)\n");
  1921. return;
  1922. }
  1923. rt_fota_bkp_dr2_write(boot_flag);
  1924. rt_kprintf("RTC_BKP_DR2 set to 0x%04X\n", rt_fota_bkp_dr2_read());
  1925. }
  1926. MSH_CMD_EXPORT_ALIAS(rt_fota_dr2, dr2, Show or set RTC_BKP_DR2 boot flag);