rt_fota.c 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227
  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 "ecode.h"
  24. #include "flash_ops.h"
  25. #include "main.h" // BSP_Write_RTC_Reg / App_Ver_Sync
  26. #include <easyflash.h>
  27. // 升级包目标分区名,打包时写入,APP 与 BL 强校验同一份白名单
  28. #define QXZ_APP_PKG_NAME "QXZAPP"
  29. #define QXZ_BL_PKG_NAME "QXZBL"
  30. void firstime_clone_df(void);
  31. // 定义在本文件后半段,drop_pkg 的退路判断要用
  32. static int rt_fota_app_image_ok(rt_uint32_t app_addr);
  33. static int rt_fota_part_head_ok(const char *part_name);
  34. void boot_auto_clone_df(void);
  35. static EfErrCode bl_env_set(const char *key, const void *val, size_t len);
  36. static void sync_bl_ver_env(void);
  37. void bl_publish_version(void);
  38. extern rt_uint32_t rt_fota_crc(rt_uint8_t *buf, rt_uint32_t len);
  39. extern rt_uint32_t rt_fota_step_crc(rt_uint32_t crc, rt_uint8_t *buf, rt_uint32_t len);
  40. // 定长字段整段比较,避免未终止字符串越界读
  41. static int rbl_pname_is(const char *field, rt_uint32_t size, const char *name)
  42. {
  43. rt_uint32_t n = rt_strlen(name);
  44. if (n >= size)
  45. {
  46. return 0;
  47. }
  48. if (rt_memcmp(field, name, n) != 0)
  49. {
  50. return 0;
  51. }
  52. return (field[n] == 0) ? 1 : 0;
  53. }
  54. // 擦掉 fm_area 包头让包彻底失效:只擦 4KB 头扇区,nor flash 擦除不会 stall CPU
  55. // 只对 fm_area 生效:df_area 是出厂备份,包头坏了只是"这个备份无效",
  56. // 主动擦掉等于自毁,一旦 app 也空了就彻底起不来
  57. // 而且擦之前必须有退路:系统里还得有一份能起来的固件,否则宁可不擦
  58. static void rt_fota_drop_pkg(const char *part_name)
  59. {
  60. const struct fal_partition *part;
  61. const struct fal_partition *app_part;
  62. int has_fallback;
  63. if (rt_strcmp(part_name, RT_FOTA_FM_PART_NAME) != 0)
  64. {
  65. return;
  66. }
  67. // 退路 = app 分区能启动,或 df 里有有效包头。
  68. // 两者都没有时,fm 里的坏包就是唯一"可能救回来"的东西,绝不擦。
  69. // 代价只是每次开机多算一次 64 字节包头 CRC —— 三个调用点都在 body CRC 之前
  70. app_part = fal_partition_find(RT_FOTA_APP_PART_NAME);
  71. has_fallback = ((app_part != RT_NULL)
  72. && rt_fota_app_image_ok(app_part->offset + 0x08000000))
  73. || rt_fota_part_head_ok(RT_FOTA_DF_PART_NAME);
  74. if (!has_fallback)
  75. {
  76. // 此处 rtdbg.h 还没 include,LOG_I 不可用,只能走 rt_kprintf
  77. rt_kprintf("no fallback firmware, keep broken %s pkg\n", part_name);
  78. return;
  79. }
  80. part = fal_partition_find(part_name);
  81. if (part != RT_NULL)
  82. {
  83. if (fal_partition_erase(part, 0, 4096) < 0)
  84. {
  85. rt_kprintf("drop pkg header failed\n");
  86. }
  87. wdg_feed_once();
  88. }
  89. }
  90. // 复位来源必须在这里抓:ports/fal/fal_flash_sfud_port.c 的 print_reset_cause()
  91. // 是 INIT_COMPONENT 级,它读完就把 RCC_CSR 清掉,等 rt_fota 跑到全是 0。
  92. // 这里只读不清,把清除留给它,否则它自己的日志会变成 Unknown。
  93. static uint16_t bl_reset_bits = 0;
  94. static int bl_capture_reset_cause(void)
  95. {
  96. uint32_t csr = RCC->CSR;
  97. if ((csr & RCC_CSR_PORRSTF) != 0u) bl_reset_bits |= 0x01;
  98. if ((csr & RCC_CSR_PINRSTF) != 0u) bl_reset_bits |= 0x02;
  99. if ((csr & RCC_CSR_SFTRSTF) != 0u) bl_reset_bits |= 0x04;
  100. if ((csr & RCC_CSR_IWDGRSTF) != 0u) bl_reset_bits |= 0x08;
  101. if ((csr & RCC_CSR_WWDGRSTF) != 0u) bl_reset_bits |= 0x10;
  102. if ((csr & RCC_CSR_LPWRRSTF) != 0u) bl_reset_bits |= 0x20;
  103. if ((csr & RCC_CSR_BORRSTF) != 0u) bl_reset_bits |= 0x40;
  104. // 主因文案由 ecode_detail 表按位的优先级决定(boot_desc),这里只采集位标志
  105. return 0;
  106. }
  107. INIT_BOARD_EXPORT(bl_capture_reset_cause);
  108. #define EXWATCHDOG_PIN GET_PIN(E, 11)
  109. void feed_watch(void)
  110. {
  111. if(rt_pin_read(EXWATCHDOG_PIN) == 0)rt_pin_write(EXWATCHDOG_PIN, PIN_HIGH);
  112. else if(rt_pin_read(EXWATCHDOG_PIN) == 1)rt_pin_write(EXWATCHDOG_PIN, PIN_LOW);
  113. }
  114. #if defined(RT_USING_FINSH) && defined(FINSH_USING_MSH)
  115. #include <finsh.h>
  116. #include <shell.h>
  117. #endif
  118. #define DBG_ENABLE
  119. #define DBG_SECTION_NAME "fota"
  120. #ifdef RT_FOTA_DEBUG
  121. #define DBG_LEVEL DBG_INFO
  122. #else
  123. #define DBG_LEVEL DBG_INFO
  124. #endif
  125. #define DBG_COLOR
  126. #include <rtdbg.h>
  127. // BL 停留上限:超过就强制离场,不允许无限停在 shell
  128. #define BL_STAY_TIMEOUT_S 120
  129. // 备份确认版本:老固件用 firstime 标记但写失败也置 1,升级后靠这个键自愈
  130. #define BL_DF_BAK_VER 1
  131. #ifndef RT_FOTA_THREAD_STACK_SIZE
  132. #define RT_FOTA_THREAD_STACK_SIZE 4096
  133. #endif
  134. #ifndef RT_FOTA_THREAD_PRIORITY
  135. #define RT_FOTA_THREAD_PRIORITY (RT_THREAD_PRIORITY_MAX - 3)
  136. #endif
  137. #ifndef RT_FOTA_ALGO_BUFF_SIZE
  138. #define RT_FOTA_ALGO_BUFF_SIZE 4096
  139. #endif
  140. /**
  141. * AES256 encryption algorithm option
  142. */
  143. #ifndef RT_FOTA_ALGO_AES_IV
  144. #define RT_FOTA_ALGO_AES_IV "0123456789ABCDEF"
  145. #endif
  146. #ifndef RT_FOTA_ALGO_AES_KEY
  147. #define RT_FOTA_ALGO_AES_KEY "0123456789ABCDEF0123456789ABCDEF"
  148. #endif
  149. #ifndef RT_FOTA_BLOCK_HEADER_SIZE
  150. #define RT_FOTA_BLOCK_HEADER_SIZE 4
  151. #endif
  152. #ifndef RT_FOTA_CMPRS_BUFFER_SIZE
  153. #define RT_FOTA_CMPRS_BUFFER_SIZE 4096
  154. #endif
  155. #ifndef RT_FOTA_FASTLZ_BUFFER_PADDING
  156. #define RT_FOTA_FASTLZ_BUFFER_PADDING FASTLZ_BUFFER_PADDING(RT_FOTA_CMPRS_BUFFER_SIZE)
  157. #endif
  158. //#ifndef RT_FOTA_QUICKLZ_BUFFER_PADDING
  159. //#define RT_FOTA_QUICKLZ_BUFFER_PADDING QLZ_BUFFER_PADDING
  160. //#endif
  161. #ifndef RT_FOTA_ENTER_SHELL_KEY
  162. #define RT_FOTA_ENTER_SHELL_KEY 0x0d
  163. #endif
  164. #ifndef RT_FOTA_GET_CHAR_WAITTIGN
  165. #define RT_FOTA_GET_CHAR_WAITTIGN (RT_TICK_PER_SECOND * 5)
  166. #endif
  167. // shell 等待分片:每片醒来喂一次外狗。
  168. // 这 5 秒 rt-boot 全程阻塞,原来一次 rt_sem_take 就睡满 5 秒,喂狗只靠 syswatch 单点。
  169. #ifndef RT_FOTA_SHELL_WAIT_SLICE
  170. #define RT_FOTA_SHELL_WAIT_SLICE (RT_TICK_PER_SECOND / 10)
  171. #endif
  172. #ifndef RT_FOTA_SIGNAL_LED_PIN
  173. #define RT_FOTA_SIGNAL_LED_PIN 76
  174. #endif
  175. #ifndef RT_FOTA_SIGNAL_LED_THREAD_STACK_SIZE
  176. #define RT_FOTA_SIGNAL_LED_THREAD_STACK_SIZE 1024
  177. #endif
  178. #ifndef RT_FOTA_SIGNAL_LED_THREAD_PRIORITY
  179. #define RT_FOTA_SIGNAL_LED_THREAD_PRIORITY (RT_THREAD_PRIORITY_MAX - 4)
  180. #endif
  181. /* For signal led */
  182. static led_t *signal_led = NULL;
  183. static led_mem_opreation_t signal_led_mem_op;
  184. const char *led_shell_mode = "500,500,"; /* 1Hz 闪烁 */
  185. const char *led_upgrade_mode = "50,50,"; /* 10Hz 闪烁 */
  186. const char *led_off_mode = "0,100,"; /* 常灭 */
  187. const char *led_on_mode = "100,0,"; /* 常亮 */
  188. /* For shell */
  189. static rt_sem_t shell_sem = RT_NULL;
  190. static rt_device_t shell_dev = RT_NULL;
  191. typedef struct {
  192. char type[4];
  193. rt_uint16_t fota_algo;
  194. rt_uint8_t fm_time[6];
  195. char app_part_name[16];
  196. char download_version[24];
  197. char current_version[24];
  198. rt_uint32_t code_crc;
  199. rt_uint32_t hash_val;
  200. rt_uint32_t raw_size;
  201. rt_uint32_t com_size;
  202. rt_uint32_t head_crc;
  203. } rt_fota_part_head, *rt_fota_part_head_t;
  204. typedef void (*rt_fota_app_func)(void);
  205. static rt_fota_app_func app_func = RT_NULL;
  206. static rt_fota_part_head fota_part_head;
  207. static void rt_fota_signal_led_on(void)
  208. {
  209. rt_pin_write(RT_FOTA_SIGNAL_LED_PIN, PIN_LOW);
  210. }
  211. static void rt_fota_signal_led_off(void)
  212. {
  213. rt_pin_write(RT_FOTA_SIGNAL_LED_PIN, PIN_HIGH);
  214. }
  215. static void rt_fota_signal_led_entry(void *arg)
  216. {
  217. while(1)
  218. {
  219. led_ticks();
  220. rt_thread_mdelay(LED_TICK_TIME);
  221. }
  222. }
  223. static void rt_fota_signal_led_init(void)
  224. {
  225. rt_pin_mode(RT_FOTA_SIGNAL_LED_PIN, PIN_MODE_OUTPUT);
  226. signal_led_mem_op.malloc_fn = (void* (*)(size_t))rt_malloc;
  227. signal_led_mem_op.free_fn = rt_free;
  228. led_set_mem_operation(&signal_led_mem_op);
  229. signal_led = led_create(rt_fota_signal_led_on, rt_fota_signal_led_off);
  230. /* Config signal led mode */
  231. led_set_mode(signal_led, LOOP_PERMANENT, (char *)led_on_mode);
  232. led_set_blink_over_callback(signal_led, RT_NULL);
  233. led_start(signal_led);
  234. rt_thread_t tid;
  235. 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);
  236. if (tid)
  237. rt_thread_startup(tid);
  238. }
  239. static void rt_fota_signal_led_mode(const char *led_cfg)
  240. {
  241. RT_ASSERT(led_cfg != RT_NULL);
  242. led_set_mode(signal_led, LOOP_PERMANENT, (char *)led_cfg);
  243. }
  244. static int rt_fota_boot_verify(void)
  245. {
  246. int fota_res = RT_FOTA_NO_ERR;
  247. rt_memset(&fota_part_head, 0x0, sizeof(rt_fota_part_head));
  248. /* partition initial */
  249. fal_init();
  250. extern int fal_init_check(void);
  251. /* verify partition */
  252. if (fal_init_check() != 1)
  253. {
  254. PartitionInitFail
  255. LOG_D("Partition initialized failed!");
  256. fota_res = RT_FOTA_GENERAL_ERR;
  257. goto __exit_boot_verify;
  258. }
  259. __exit_boot_verify:
  260. return fota_res;
  261. }
  262. int rt_fota_part_fw_verify(const char *part_name)
  263. {
  264. #define RT_FOTA_CRC_BUFF_SIZE 4096
  265. #define RT_FOTA_CRC_INIT_VAL 0xffffffff
  266. int fota_res = RT_FOTA_NO_ERR;
  267. const struct fal_partition *part;
  268. rt_fota_part_head part_head;
  269. rt_uint8_t *body_buf = RT_NULL;
  270. rt_uint32_t body_crc = RT_FOTA_CRC_INIT_VAL;
  271. rt_uint32_t hdr_crc;
  272. if (part_name == RT_NULL)
  273. {
  274. LOG_D("Invaild paramenter input!");
  275. fota_res = RT_FOTA_GENERAL_ERR;
  276. goto __exit_partition_verify;
  277. }
  278. part = fal_partition_find(part_name);
  279. if (part == RT_NULL)
  280. {
  281. PartitionNotFound
  282. LOG_D("Partition[%s] not found.", part_name);
  283. fota_res = RT_FOTA_GENERAL_ERR;
  284. goto __exit_partition_verify;
  285. }
  286. /* read the head of RBL files */
  287. if (fal_partition_read(part, 0, (rt_uint8_t *)&part_head, sizeof(rt_fota_part_head)) < 0)
  288. {
  289. PartitionReadError //分区读取错误
  290. // 读失败必须报:DBG_LEVEL=DBG_INFO 会把 LOG_D 整条编译掉,等于"读不到"和"读到了 FF"无法区分
  291. LOG_E("Partition[%s] head read failed!", part->name);
  292. fota_res = RT_FOTA_PART_READ_ERR;
  293. goto __exit_partition_verify;
  294. }
  295. // 空分区(全 0xFF)= 从没下过包。这是开机常态,静默返回,不打日志也不记事件
  296. {
  297. const rt_uint32_t *w = (const rt_uint32_t *)&part_head;
  298. rt_uint32_t n;
  299. int blank = 1;
  300. for (n = 0; n < (sizeof(rt_fota_part_head) / 4u); n++)
  301. {
  302. if (w[n] != 0xFFFFFFFFu)
  303. {
  304. blank = 0;
  305. break;
  306. }
  307. }
  308. if (blank)
  309. {
  310. fota_res = RT_FOTA_CHECK_FAILED;
  311. goto __exit_partition_verify;
  312. }
  313. }
  314. extern rt_uint32_t rt_fota_crc(rt_uint8_t *buf, rt_uint32_t len);
  315. hdr_crc = rt_fota_crc((rt_uint8_t *)&part_head, sizeof(rt_fota_part_head) - 4);
  316. if (hdr_crc != part_head.head_crc)
  317. {
  318. // 包头对不上就擦掉让它失效。但擦之前必须把实测值留下:
  319. // 这是唯一能看出"包到底写成什么样"的时刻,擦完就成了全 0xFF 的黑盒
  320. LOG_W("fm head crc: got %08X want %08X type=%02X%02X%02X%02X",
  321. (unsigned)part_head.head_crc, (unsigned)hdr_crc,
  322. (unsigned)(rt_uint8_t)part_head.type[0], (unsigned)(rt_uint8_t)part_head.type[1],
  323. (unsigned)(rt_uint8_t)part_head.type[2], (unsigned)(rt_uint8_t)part_head.type[3]);
  324. rt_fota_drop_pkg(part_name);
  325. fota_res = RT_FOTA_CHECK_FAILED;
  326. goto __exit_partition_verify;
  327. }
  328. if (rt_strcmp(part_head.type, "RBL") != 0)
  329. {
  330. // 不是 RBL 包,等同没有包。打出来是哪种类型,才看得出包是怎么来的
  331. LOG_W("fm type not RBL: %02X %02X %02X %02X",
  332. (unsigned)(rt_uint8_t)part_head.type[0], (unsigned)(rt_uint8_t)part_head.type[1],
  333. (unsigned)(rt_uint8_t)part_head.type[2], (unsigned)(rt_uint8_t)part_head.type[3]);
  334. rt_fota_drop_pkg(part_name);
  335. fota_res = RT_FOTA_CHECK_FAILED;
  336. goto __exit_partition_verify;
  337. }
  338. // 包只用一次:升级成功会把 partname 擦成 0xFF,这里第一道门就返回,
  339. // 384KB 整包 CRC 不再做(这是开机时外狗超时的主因之一)
  340. if (!rbl_pname_is(part_head.app_part_name, sizeof(part_head.app_part_name), QXZ_APP_PKG_NAME))
  341. {
  342. // 只有既不是"已用掉"(0xFF)、也不是旧格式("app")时才说明头在传输/落盘时被改了;
  343. // 前两种是开机常态,静默处理,否则每次开机都刷一条
  344. if ((!rbl_pname_is(part_head.app_part_name, sizeof(part_head.app_part_name), "app"))
  345. && ((rt_uint8_t)part_head.app_part_name[0] != 0xFFu))
  346. {
  347. LOG_W("fm part_name unexpected: %.16s", part_head.app_part_name);
  348. }
  349. if (rbl_pname_is(part_head.app_part_name, sizeof(part_head.app_part_name), "app"))
  350. {
  351. rt_fota_drop_pkg(part_name);
  352. }
  353. fota_res = RT_FOTA_CHECK_FAILED;
  354. goto __exit_partition_verify;
  355. }
  356. // 体积上限必须在擦除之前卡死:包头被篡改时 raw_size 会直接传给擦除,
  357. // 越界就会把 bl 分区抹掉(BL 自己就没代码可跑了)
  358. {
  359. const struct fal_partition *app_part = fal_partition_find(RT_FOTA_APP_PART_NAME);
  360. if ((app_part == RT_NULL) || (part_head.raw_size == 0) || (part_head.com_size == 0)
  361. || (part_head.raw_size > app_part->len) || (part_head.com_size > app_part->len))
  362. {
  363. LOG_W("pkg size out of range: raw=%u com=%u part=%u",
  364. part_head.raw_size, part_head.com_size,
  365. (app_part != RT_NULL) ? app_part->len : 0);
  366. PartitionIntegrityVerifyError
  367. fota_res = RT_FOTA_FW_VERIFY_FAILED;
  368. goto __exit_partition_verify;
  369. }
  370. }
  371. body_buf = rt_malloc(RT_FOTA_CRC_BUFF_SIZE);
  372. if (body_buf == RT_NULL)
  373. {
  374. LOG_W("Not enough memory for body CRC32 verify.");
  375. fota_res = RT_FOTA_NO_MEM_ERR;
  376. goto __exit_partition_verify;
  377. }
  378. // 分包递进:每读完一包(4KB)立刻校验并喂一次狗,包与包之间串行
  379. for (int body_pos = 0; body_pos < part_head.com_size;)
  380. {
  381. int body_read_len;
  382. body_read_len = fal_partition_read(part, sizeof(rt_fota_part_head) + body_pos, body_buf, RT_FOTA_CRC_BUFF_SIZE);
  383. if (body_read_len > 0)
  384. {
  385. if ((body_pos + body_read_len) > part_head.com_size)
  386. {
  387. body_read_len = part_head.com_size - body_pos;
  388. }
  389. extern rt_uint32_t rt_fota_step_crc(rt_uint32_t crc, rt_uint8_t *buf, rt_uint32_t len);
  390. body_crc = rt_fota_step_crc(body_crc, body_buf, body_read_len);
  391. body_pos = body_pos + body_read_len;
  392. wdg_feed_once(); // 每校验完一包立即喂一次,串行递进
  393. }
  394. else
  395. {
  396. LOG_W("Partition[%s] read error!", part->name);
  397. fota_res = RT_FOTA_PART_READ_ERR;
  398. goto __exit_partition_verify;
  399. }
  400. }
  401. body_crc = body_crc ^ RT_FOTA_CRC_INIT_VAL;
  402. if (body_crc != part_head.code_crc)
  403. {
  404. PartitionIntegrityVerifyError //固件完整性校验失败
  405. LOG_W("Partition[%s] firmware integrity verify failed.", part->name);
  406. fota_res = RT_FOTA_FW_VERIFY_FAILED;
  407. goto __exit_partition_verify;
  408. }
  409. char cache[32] = {0};
  410. __exit_partition_verify:
  411. if (fota_res == RT_FOTA_NO_ERR)
  412. {
  413. rt_enter_critical();
  414. rt_memcpy(&fota_part_head, &part_head, sizeof(rt_fota_part_head));
  415. rt_exit_critical();
  416. //PartitionVerifySuccess //固件校验成功
  417. sprintf(cache , "固件校验成功:%s" , part_name);
  418. fota_status_send( cache, strlen(cache));
  419. LOG_I("partition[%s] verify success!", part->name);
  420. }
  421. else
  422. {
  423. rt_enter_critical();
  424. rt_memset(&fota_part_head, 0x0, sizeof(rt_fota_part_head));
  425. rt_exit_critical();
  426. // RT_FOTA_CHECK_FAILED 表示"没有待升级包",是开机常态,不打印也不上屏;
  427. // 只有真有 QXZAPP 包头但体积/内容校验不过时才报,避免现场被无意义的失败刷屏
  428. if (fota_res != RT_FOTA_CHECK_FAILED)
  429. {
  430. LOG_W("fota_res:%d partition[%s] verify failed", fota_res, part_name);
  431. sprintf(cache , "固件校验失败:%s" , part_name);
  432. fota_status_send( cache, strlen(cache));
  433. }
  434. }
  435. if (body_buf)
  436. rt_free(body_buf);
  437. return fota_res;
  438. }
  439. int rt_fota_check_upgrade(void)
  440. {
  441. int is_upgrade = 0;
  442. rt_kprintf("download_version %s >> current_version %s \n" , fota_part_head.download_version, fota_part_head.current_version);
  443. // 一次性包:partname 合法就要装,不再比版本号(否则同版本重刷会被跳过)
  444. if (rbl_pname_is(fota_part_head.app_part_name, sizeof(fota_part_head.app_part_name), QXZ_APP_PKG_NAME))
  445. {
  446. is_upgrade = 1;
  447. LOG_D("Application need upgrade.");
  448. goto __exit_check_upgrade;
  449. }
  450. __exit_check_upgrade:
  451. return is_upgrade;
  452. }
  453. int rt_fota_copy_version(const char *part_name)
  454. {
  455. #define THE_NOR_FLASH_GRANULARITY 4096
  456. int fota_res = RT_FOTA_NO_ERR;
  457. const struct fal_partition *part;
  458. rt_fota_part_head_t part_head = RT_NULL;
  459. rt_uint8_t *cache_buf = RT_NULL;
  460. part = fal_partition_find(part_name);
  461. if (part == RT_NULL)
  462. {
  463. LOG_D("Find partition[%s] not found.", part_name);
  464. fota_res = RT_FOTA_FW_VERIFY_FAILED;
  465. goto __exit_copy_version;
  466. }
  467. cache_buf = rt_malloc(THE_NOR_FLASH_GRANULARITY);
  468. if (cache_buf == RT_NULL)
  469. {
  470. LOG_I("Not enough memory for head erase.");
  471. fota_res = RT_FOTA_NO_MEM_ERR;
  472. goto __exit_copy_version;
  473. }
  474. part_head = (rt_fota_part_head_t)cache_buf;
  475. if (fal_partition_read(part, 0, cache_buf, THE_NOR_FLASH_GRANULARITY) < 0)
  476. {
  477. LOG_I("Read partition[%s] failed.", part_name);
  478. fota_res = RT_FOTA_PART_READ_ERR;
  479. goto __exit_copy_version;
  480. }
  481. rt_memcpy(part_head->current_version, part_head->download_version, sizeof(part_head->current_version));
  482. // 一次性消耗:把目标分区名整段填 0xFF,下次开机 verify 第一道门就过不了
  483. rt_memset(part_head->app_part_name, 0xFF, sizeof(part_head->app_part_name));
  484. extern rt_uint32_t rt_fota_crc(rt_uint8_t *buf, rt_uint32_t len);
  485. part_head->head_crc = rt_fota_crc((rt_uint8_t *)part_head, sizeof(rt_fota_part_head) - 4);
  486. if (fal_partition_erase(part, 0, THE_NOR_FLASH_GRANULARITY) < 0)
  487. {
  488. LOG_I("Erase partition[%s] failed.", part_name);
  489. fota_res = RT_FOTA_PART_ERASE_ERR;
  490. goto __exit_copy_version;
  491. }
  492. if (fal_partition_write(part, 0, (const rt_uint8_t *)cache_buf, THE_NOR_FLASH_GRANULARITY) < 0)
  493. {
  494. LOG_I("Write partition[%s] failed.", part_name);
  495. fota_res = RT_FOTA_PART_WRITE_ERR;
  496. goto __exit_copy_version;
  497. }
  498. wdg_feed_once();
  499. __exit_copy_version:
  500. if (cache_buf)
  501. rt_free(cache_buf);
  502. if (fota_res != RT_FOTA_NO_ERR)
  503. LOG_I("Copy firmware version failed!");
  504. else
  505. LOG_I("Copy firmware version Success!");
  506. return fota_res;
  507. }
  508. int rt_fota_erase_app_part(void)
  509. {
  510. int fota_res = RT_FOTA_NO_ERR;
  511. const struct fal_partition *part;
  512. // 包头里的 QXZAPP 是产品级名字,fal 分区名仍是 app,不能用包里的名字去 find
  513. part = fal_partition_find(RT_FOTA_APP_PART_NAME);
  514. if (part == RT_NULL)
  515. {
  516. PartitionNotFound //分区未找到
  517. LOG_D("Erase partition[%s] not found.", fota_part_head.app_part_name);
  518. fota_res = RT_FOTA_FW_VERIFY_FAILED;
  519. goto __exit_partition_erase;
  520. }
  521. EraseStart //开始擦除分区
  522. // 128KB 扇区擦除是慢操作,最坏十几秒且全程无输出,先说明一句免得现场以为死机
  523. LOG_I("Erase %s %u bytes, may take 10s+...", part->name, fota_part_head.raw_size);
  524. // 128KB 扇区擦除期间 CPU 取指被 stall,必须走 SRAM 里的擦除循环持续喂狗
  525. if (flash_erase_range_hw(ONCHIP_FLASH_BASE + part->offset, fota_part_head.raw_size) != 0)
  526. {
  527. EraseFailed //擦除失败
  528. LOG_I("Partition[%s] erase failed!", part->name);
  529. fota_res = RT_FOTA_PART_ERASE_ERR;
  530. goto __exit_partition_erase;
  531. }
  532. __exit_partition_erase:
  533. if (fota_res == RT_FOTA_NO_ERR)
  534. {
  535. EraseSuccess //擦除成功
  536. LOG_D("Partition[%s] erase %d bytes success!", part->name, fota_part_head.raw_size);
  537. }
  538. return fota_res;
  539. }
  540. int rt_fota_write_app_part(int fw_pos, rt_uint8_t *fw_buf, int fw_len)
  541. {
  542. int rt_fota_res = RT_FOTA_NO_ERR;
  543. const struct fal_partition *part;
  544. // 包头里的 QXZAPP 是产品级名字,fal 分区名仍是 app,不能用包里的名字去 find
  545. part = fal_partition_find(RT_FOTA_APP_PART_NAME);
  546. if (part == RT_NULL)
  547. {
  548. PartitionNotFound
  549. LOG_D("Erase partition[%s] not found.", fota_part_head.app_part_name);
  550. rt_fota_res = RT_FOTA_FW_VERIFY_FAILED;
  551. goto __partition_write_exit;
  552. }
  553. if (fal_partition_write(part, fw_pos, fw_buf, fw_len) < 0)
  554. {
  555. WriteFailed //写入失败
  556. LOG_I("Partition[%s] write failed!", part->name);
  557. rt_fota_res = RT_FOTA_PART_WRITE_ERR;
  558. goto __partition_write_exit;
  559. }
  560. __partition_write_exit:
  561. if (rt_fota_res == RT_FOTA_NO_ERR)
  562. {
  563. LOG_D("Partition[%s] write %d bytes success!", part->name, fw_len);
  564. }
  565. return rt_fota_res;
  566. }
  567. 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)
  568. {
  569. int fota_err = RT_FOTA_NO_ERR;
  570. rt_uint8_t *encrypt_buf = RT_NULL;
  571. if ((part == RT_NULL) || (decrypt_buf == RT_NULL)
  572. || (decrypt_len % 16 != 0) || (decrypt_len > RT_FOTA_ALGO_BUFF_SIZE))
  573. {
  574. fota_err = RT_FOTA_GENERAL_ERR;
  575. goto __exit_read_decrypt;
  576. }
  577. rt_memset(decrypt_buf, 0x0, decrypt_len);
  578. /* Not use AES256 algorithm */
  579. if (aes_ctx == RT_NULL || aes_iv == RT_NULL)
  580. {
  581. fota_err = fal_partition_read(part, sizeof(rt_fota_part_head) + read_pos, decrypt_buf, decrypt_len);
  582. if (fota_err <= 0)
  583. {
  584. fota_err = RT_FOTA_PART_READ_ERR;
  585. }
  586. goto __exit_read_decrypt;
  587. }
  588. encrypt_buf = rt_malloc(decrypt_len);
  589. if (encrypt_buf == RT_NULL)
  590. {
  591. fota_err = RT_FOTA_GENERAL_ERR;
  592. goto __exit_read_decrypt;
  593. }
  594. rt_memset(encrypt_buf, 0x0, decrypt_len);
  595. fota_err = fal_partition_read(part, sizeof(rt_fota_part_head) + read_pos, encrypt_buf, decrypt_len);
  596. if (fota_err <= 0 || fota_err % 16 != 0)
  597. {
  598. fota_err = RT_FOTA_PART_READ_ERR;
  599. goto __exit_read_decrypt;
  600. }
  601. // tiny_aes_crypt_cbc(aes_ctx, AES_DECRYPT, fota_err, aes_iv, encrypt_buf, decrypt_buf);
  602. __exit_read_decrypt:
  603. if (encrypt_buf)
  604. rt_free(encrypt_buf);
  605. return fota_err;
  606. }
  607. int rt_fota_upgrade(const char *part_name)
  608. {
  609. int fota_err = RT_FOTA_NO_ERR;
  610. const struct fal_partition *part;
  611. rt_fota_part_head_t part_head = RT_NULL;
  612. tiny_aes_context *aes_ctx = RT_NULL;
  613. rt_uint8_t *aes_iv = RT_NULL;
  614. rt_uint8_t *crypt_buf = RT_NULL;
  615. int fw_raw_pos = 0;
  616. int fw_raw_len = 0;
  617. rt_uint32_t total_copy_size = 0;
  618. rt_uint8_t block_hdr_buf[RT_FOTA_BLOCK_HEADER_SIZE];
  619. rt_uint32_t block_hdr_pos = RT_FOTA_ALGO_BUFF_SIZE;
  620. rt_uint32_t block_size = 0;
  621. rt_uint32_t dcprs_size = 0;
  622. // qlz_state_decompress *dcprs_state = RT_NULL;
  623. rt_uint8_t *cmprs_buff = RT_NULL;
  624. rt_uint8_t *dcprs_buff = RT_NULL;
  625. rt_uint32_t padding_size = 0;
  626. if (part_name == RT_NULL)
  627. {
  628. LOG_D("Invaild paramenter input!");
  629. fota_err = RT_FOTA_GENERAL_ERR;
  630. goto __exit_upgrade;
  631. }
  632. part = fal_partition_find(part_name);
  633. if (part == RT_NULL)
  634. {PartitionNotFound
  635. LOG_I("Upgrade partition[%s] not found.", part_name);
  636. fota_err = RT_FOTA_GENERAL_ERR;
  637. goto __exit_upgrade;
  638. }
  639. /* Application partition erase */
  640. fota_err = rt_fota_erase_app_part();
  641. if (fota_err != RT_FOTA_NO_ERR)
  642. {
  643. goto __exit_upgrade;
  644. }
  645. /* rt_fota_erase_app_part() has check fota_part_head vaild already */
  646. part_head = &fota_part_head;
  647. crypt_buf = rt_malloc(RT_FOTA_ALGO_BUFF_SIZE);
  648. if (crypt_buf == RT_NULL)
  649. {
  650. LOG_I("Not enough memory for firmware buffer.");
  651. fota_err = RT_FOTA_NO_MEM_ERR;
  652. goto __exit_upgrade;
  653. }
  654. if ((part_head->fota_algo & RT_FOTA_CRYPT_STAT_MASK) == RT_FOTA_CRYPT_ALGO_XOR)
  655. {
  656. LOG_I("Not surpport XOR.");
  657. fota_err = RT_FOTA_GENERAL_ERR;
  658. goto __exit_upgrade;
  659. }
  660. else if ((part_head->fota_algo & RT_FOTA_CMPRS_STAT_MASK) == RT_FOTA_CMPRS_ALGO_GZIP)
  661. {
  662. LOG_I("Not surpport GZIP.");
  663. fota_err = RT_FOTA_GENERAL_ERR;
  664. goto __exit_upgrade;
  665. }
  666. //按照输入分区名称判断显示
  667. if(rt_strcmp(part_name,"fm_area") == 0)Flash_Fw //正在刷写固件
  668. else if(rt_strcmp(part_name,"df_area") == 0)Recove_Fw //正在恢复出厂固件
  669. LOG_I("Start to copy firmware from %s to %s partition:", part->name, part_head->app_part_name);
  670. while (fw_raw_pos < part_head->com_size)
  671. {
  672. fw_raw_len = rt_fota_read_part(part, fw_raw_pos, aes_ctx, aes_iv, crypt_buf, RT_FOTA_ALGO_BUFF_SIZE);
  673. if (fw_raw_len < 0)
  674. {
  675. LOG_I("AES256 algorithm failed.");
  676. fota_err = RT_FOTA_PART_READ_ERR;
  677. goto __exit_upgrade;
  678. }
  679. fw_raw_pos += fw_raw_len;
  680. if (rt_fota_write_app_part(total_copy_size, crypt_buf, fw_raw_len) < 0)
  681. {
  682. fota_err = RT_FOTA_COPY_FAILED;
  683. goto __exit_upgrade;
  684. }
  685. total_copy_size += fw_raw_len;
  686. wdg_feed_once();
  687. rt_kprintf("#");
  688. }
  689. /* it has compress option */
  690. if ((part_head->fota_algo & RT_FOTA_CMPRS_STAT_MASK) != RT_FOTA_CRYPT_ALGO_NONE)
  691. {
  692. while (total_copy_size < part_head->raw_size)
  693. {
  694. if ((block_hdr_pos < fw_raw_len) && ((fw_raw_len - block_hdr_pos) > RT_FOTA_BLOCK_HEADER_SIZE))
  695. {
  696. rt_memcpy(block_hdr_buf, &crypt_buf[block_hdr_pos], RT_FOTA_BLOCK_HEADER_SIZE);
  697. block_size = block_hdr_buf[0] * (1 << 24) + block_hdr_buf[1] * (1 << 16) + block_hdr_buf[2] * (1 << 8) + block_hdr_buf[3];
  698. if ((fw_raw_len - block_hdr_pos - RT_FOTA_BLOCK_HEADER_SIZE) >= block_size)
  699. {
  700. rt_memset(cmprs_buff, 0x0, RT_FOTA_CMPRS_BUFFER_SIZE + padding_size);
  701. rt_memcpy(cmprs_buff, &crypt_buf[block_hdr_pos + RT_FOTA_BLOCK_HEADER_SIZE], block_size);
  702. rt_memset(dcprs_buff, 0x0, RT_FOTA_CMPRS_BUFFER_SIZE);
  703. block_hdr_pos += (block_size + RT_FOTA_BLOCK_HEADER_SIZE);
  704. if (dcprs_size <= 0)
  705. {
  706. LOG_I("Decompress failed: %d.", dcprs_size);
  707. fota_err = RT_FOTA_GENERAL_ERR;
  708. goto __exit_upgrade;
  709. }
  710. if (rt_fota_write_app_part(total_copy_size, dcprs_buff, dcprs_size) < 0)
  711. {
  712. fota_err = RT_FOTA_COPY_FAILED;
  713. goto __exit_upgrade;
  714. }
  715. total_copy_size += dcprs_size;
  716. wdg_feed_once(); // 每写入一块立即喂一次
  717. rt_kprintf("#");
  718. }
  719. else
  720. {
  721. break;
  722. }
  723. }
  724. else
  725. {
  726. break;
  727. }
  728. }
  729. }
  730. rt_kprintf("\r\n");
  731. /* 有可能两个值不相等,因为AES需要填充16字节整数,但最后的解密解压值的代码数量必须是大于等于raw_size */
  732. /* 比较好的方法是做一个校验,目前打包软件的HASH_CODE算法不知道 */
  733. if (total_copy_size < part_head->raw_size)
  734. {
  735. LOG_I("Decompress check failed.");
  736. fota_err = RT_FOTA_GENERAL_ERR;
  737. }
  738. __exit_upgrade:
  739. if (aes_ctx)
  740. rt_free(aes_ctx);
  741. if (aes_iv)
  742. rt_free(aes_iv);
  743. if (crypt_buf)
  744. rt_free(crypt_buf);
  745. if (cmprs_buff)
  746. rt_free(cmprs_buff);
  747. if (dcprs_buff)
  748. rt_free(dcprs_buff);
  749. // if (dcprs_state)
  750. // rt_free(dcprs_state);
  751. if (fota_err == RT_FOTA_NO_ERR)
  752. { UpgradeSuccess //固件升级成功
  753. LOG_I("Upgrade success, total %d bytes.", total_copy_size);
  754. }
  755. else UpgradeFail //固件升级失败
  756. return fota_err;
  757. }
  758. // APP 区镜像自检:首字是 SRAM 栈顶,次字是 0x08XXXXXX 复位入口,缺一个都不能跳
  759. static int rt_fota_app_image_ok(rt_uint32_t app_addr)
  760. {
  761. //判断是否为0x08XXXXXX.
  762. if (((*(__IO uint32_t *)(app_addr + 4)) & 0xff000000) != 0x08000000)
  763. {
  764. return 0;
  765. }
  766. // 检查栈顶地址是否合法.
  767. if (((*(__IO uint32_t *)app_addr) & 0x2ffe0000) != 0x20000000)
  768. {
  769. return 0;
  770. }
  771. return 1;
  772. }
  773. int rt_fota_start_application(void)
  774. {
  775. int fota_res = RT_FOTA_NO_ERR;
  776. const struct fal_partition *part;
  777. rt_uint32_t app_addr;
  778. part = fal_partition_find(RT_FOTA_APP_PART_NAME);
  779. if (part == RT_NULL)
  780. {
  781. LOG_I("Partition[%s] not found.", RT_FOTA_APP_PART_NAME);
  782. fota_res = RT_FOTA_GENERAL_ERR;
  783. goto __exit_start_application;
  784. }
  785. app_addr = part->offset + 0x08000000;
  786. // APP 区没有可启动镜像时硬跳会跑飞,必须先拿出厂固件补一次,补不上就停在这里
  787. if (!rt_fota_app_image_ok(app_addr))
  788. {
  789. LOG_I("APP image invalid, boot refused.");
  790. Recode_e_code(e_boot_recover, 1);
  791. LOG_I("Recover APP from %s.", RT_FOTA_DF_PART_NAME);
  792. if (upgrade_df() != 0)
  793. {
  794. fota_res = RT_FOTA_GENERAL_ERR;
  795. goto __exit_start_application;
  796. }
  797. if (!rt_fota_app_image_ok(app_addr))
  798. {
  799. // 恢复后仍不可启动说明出厂包本身有问题,再补也是空转
  800. LOG_I("APP image still invalid after recover.");
  801. Recode_e_code(e_boot_recover, 4);
  802. fota_res = RT_FOTA_GENERAL_ERR;
  803. goto __exit_start_application;
  804. }
  805. LOG_I("Factory image restored, boot again.");
  806. }
  807. StartApp //正在启动应用……
  808. for (int i = 0; i < 10; i++)
  809. {
  810. wdg_feed_once();
  811. rt_thread_mdelay(100);
  812. }
  813. rt_pin_mode(GET_PIN(E, 0), PIN_MODE_OUTPUT);
  814. rt_pin_write(GET_PIN(E, 0), PIN_LOW);
  815. for (int i = 0; i < 10; i++)
  816. {
  817. wdg_feed_once();
  818. rt_thread_mdelay(100);
  819. }
  820. rt_pin_write(GET_PIN(E, 0), PIN_HIGH);
  821. LOG_I("Implement application now.");
  822. __disable_irq();
  823. // for (IRQn_Type irq = WWDG_IRQn; irq <= FPU_IRQn; irq++)
  824. // {
  825. // HAL_NVIC_DisableIRQ(irq);
  826. // HAL_NVIC_ClearPendingIRQ(irq);
  827. // }
  828. //Resets the RCC clock configuration to the default reset state.
  829. HAL_RCC_DeInit();
  830. SysTick->CTRL = 0;
  831. SysTick->LOAD = 0;
  832. SysTick->VAL = 0;
  833. HAL_DeInit();
  834. //用户代码区第二个字为程序开始地址(复位地址)
  835. app_func = (rt_fota_app_func)*(__IO uint32_t *)(app_addr + 4);
  836. /* Configure main stack */
  837. __set_MSP(*(__IO uint32_t *)app_addr);
  838. /* jump to application */
  839. app_func();
  840. __exit_start_application:
  841. LOG_I("Implement application failed.");
  842. return fota_res;
  843. }
  844. // 外狗约 2 秒没被翻转就拉 NRST。BL 里任何上千毫秒的等待都不能只靠
  845. // syswatch 一个线程喂狗,自己切片喂:每片醒来翻一次 WDI。
  846. #ifndef RT_FOTA_FEED_SLICE_MS
  847. #define RT_FOTA_FEED_SLICE_MS 200
  848. #endif
  849. static void bl_delay_fed(rt_int32_t ms)
  850. {
  851. while (ms > 0)
  852. {
  853. rt_int32_t step = (ms > RT_FOTA_FEED_SLICE_MS) ? RT_FOTA_FEED_SLICE_MS : ms;
  854. rt_thread_mdelay(step);
  855. wdg_feed_once();
  856. ms -= step;
  857. }
  858. }
  859. static rt_err_t rt_fota_get_shell_key(void)
  860. {
  861. char ch = 0;
  862. rt_err_t res = RT_EOK;
  863. rt_tick_t tick_start;
  864. RT_ASSERT(shell_dev != RT_NULL);
  865. RT_ASSERT(shell_sem != RT_NULL);
  866. // 计时一律用 tick 差值,绝不把全局 tick 归零:
  867. // 线程延时的 timeout_tick 是绝对值(timer.c: rt_tick_get() + init_tick),
  868. // tick 一归零,此刻所有挂起的延时都要等 tick 重新涨回旧值才到期,
  869. // syswatch 的 mdelay(10) 正是其中之一,喂狗会被硬冻几百毫秒。
  870. tick_start = rt_tick_get();
  871. while (1)
  872. {
  873. if (rt_device_read(shell_dev, -1, &ch, 1) == 1)
  874. {
  875. if (ch == RT_FOTA_ENTER_SHELL_KEY)
  876. {
  877. goto __exit_get_shell_key;
  878. }
  879. }
  880. else
  881. {
  882. // 分片等,不再一次睡满 5 秒
  883. rt_sem_take(shell_sem, RT_FOTA_SHELL_WAIT_SLICE);
  884. }
  885. // 每片都喂一次,不管是等到的还是读到的:
  886. // 5 秒的喂狗责任不能只押在 syswatch 一个线程上
  887. wdg_feed_once();
  888. if ((rt_tick_get() - tick_start) >= RT_FOTA_GET_CHAR_WAITTIGN)
  889. {
  890. res = RT_ERROR;
  891. goto __exit_get_shell_key;
  892. }
  893. }
  894. __exit_get_shell_key:
  895. return res;
  896. }
  897. static rt_err_t rt_fota_rx_ind(rt_device_t dev, rt_size_t size)
  898. {
  899. RT_ASSERT(shell_sem != RT_NULL);
  900. /* release semaphore to let fota thread rx data */
  901. rt_sem_release(shell_sem);
  902. return RT_EOK;
  903. }
  904. static rt_err_t rt_fota_set_device(const char *device_name)
  905. {
  906. rt_device_t dev;
  907. RT_ASSERT(device_name != RT_NULL);
  908. dev = rt_device_find(device_name);
  909. if (dev == RT_NULL)
  910. {
  911. LOG_D("Can not find device: %s.", device_name);
  912. return RT_ERROR;
  913. }
  914. if (shell_sem)
  915. rt_sem_delete(shell_sem);
  916. shell_sem = rt_sem_create("shell_sem", 0, RT_IPC_FLAG_FIFO);
  917. if (shell_sem == RT_NULL)
  918. return RT_ERROR;
  919. if (dev == shell_dev)
  920. return RT_EOK;
  921. if (rt_device_open(dev, RT_DEVICE_OFLAG_RDWR | RT_DEVICE_FLAG_INT_RX | RT_DEVICE_FLAG_STREAM) == RT_EOK)
  922. {
  923. if (shell_dev != RT_NULL)
  924. {
  925. /* close old finsh device */
  926. rt_device_close(shell_dev);
  927. rt_device_set_rx_indicate(shell_dev, RT_NULL);
  928. }
  929. shell_dev = dev;
  930. rt_device_set_rx_indicate(dev, rt_fota_rx_ind);
  931. LOG_D("Shell device %s open success.", device_name);
  932. return RT_EOK;
  933. }
  934. LOG_D("Shell device %s open failed.", device_name);
  935. return RT_ERROR;
  936. }
  937. #define RT_FOTA_DEFAULT_KEY_PIN GET_PIN(E, 15)
  938. #define RT_FOTA_DEFAULT_KEY_CHK_TIME 5
  939. #if defined(RT_FOTA_DEFAULT_KEY_PIN) && defined(RT_FOTA_DEFAULT_KEY_CHK_TIME)
  940. static rt_err_t rt_fota_check_defalut_key(void)
  941. {
  942. int chk_idx;
  943. /* GPIO initialized */
  944. rt_pin_mode(RT_FOTA_DEFAULT_KEY_PIN, PIN_MODE_INPUT_PULLUP);
  945. /* Delay for power up */
  946. bl_delay_fed(500);
  947. if (rt_pin_read(RT_FOTA_DEFAULT_KEY_PIN) == PIN_LOW)
  948. rt_kprintf("Default firmware key pressed:\n");
  949. /* Check GPIO status */
  950. for (chk_idx = 0; (rt_pin_read(RT_FOTA_DEFAULT_KEY_PIN) == PIN_LOW) && (chk_idx < RT_FOTA_DEFAULT_KEY_CHK_TIME); chk_idx++)
  951. {
  952. bl_delay_fed(RT_TICK_PER_SECOND);
  953. rt_kprintf(">");
  954. }
  955. if (chk_idx < RT_FOTA_DEFAULT_KEY_CHK_TIME)
  956. return RT_ERROR;
  957. else
  958. return RT_EOK;
  959. }
  960. #endif
  961. // 进了 shell 就是放弃启动,到点必须离场:能跳就跳,跳不了复位重来
  962. static void bl_stay_timeout_thread(void *arg)
  963. {
  964. rt_uint32_t wait_ms = (rt_uint32_t)(rt_ubase_t)arg;
  965. // 120 秒的等待同样自己切片喂:shell 模式下不能只靠 syswatch 一个喂狗源
  966. bl_delay_fed((rt_int32_t)wait_ms);
  967. LOG_I("BL stay over %d s, force leave.", BL_STAY_TIMEOUT_S);
  968. Recode_e_code(e_boot_timeout, BL_STAY_TIMEOUT_S);
  969. rt_fota_start_application();
  970. // APP 区没有可启动镜像时跳不过去,复位重来一轮(含出厂恢复)
  971. rt_hw_cpu_reset();
  972. }
  973. static void bl_stay_timeout_start(rt_uint32_t elapsed_ms)
  974. {
  975. rt_thread_t tid;
  976. rt_uint32_t wait_ms = (rt_uint32_t)BL_STAY_TIMEOUT_S * 1000u;
  977. wait_ms = (elapsed_ms >= wait_ms) ? 0u : (wait_ms - elapsed_ms);
  978. tid = rt_thread_create("bl-timeout", bl_stay_timeout_thread, (void *)(rt_ubase_t)wait_ms,
  979. 2048, RT_FOTA_THREAD_PRIORITY + 1, 10);
  980. if (tid != RT_NULL)
  981. {
  982. rt_thread_startup(tid);
  983. }
  984. else
  985. {
  986. LOG_I("bl-timeout thread create failed.");
  987. }
  988. }
  989. void rt_fota_thread_entry(void *arg)
  990. {
  991. int fota_err = RT_FOTA_NO_ERR;
  992. rt_tick_t bl_entry_tick = rt_tick_get();
  993. extern int finsh_system_init(void);
  994. /* Signal led initialized */
  995. rt_fota_signal_led_init();
  996. /* Partition initialized */
  997. fota_err = rt_fota_boot_verify();
  998. if (fota_err != RT_FOTA_NO_ERR)
  999. {
  1000. LOG_I("Partition initialized failed.");
  1001. }
  1002. #if defined(RT_FOTA_DEFAULT_KEY_PIN) && defined(RT_FOTA_DEFAULT_KEY_CHK_TIME)
  1003. /* Default key check */
  1004. if (rt_fota_check_defalut_key() == RT_EOK)
  1005. {
  1006. /* enter to defalut key mode */
  1007. rt_fota_signal_led_mode(led_upgrade_mode);
  1008. // goto __exit_default_entry;
  1009. goto __exit_shell_entry;
  1010. }
  1011. #endif
  1012. /* Shell initialized */
  1013. if (rt_fota_set_device(RT_CONSOLE_DEVICE_NAME) == RT_EOK)
  1014. {
  1015. rt_kprintf("Please press [Enter] key into shell mode in %d secs:\r\n", RT_FOTA_GET_CHAR_WAITTIGN / RT_TICK_PER_SECOND);
  1016. if (rt_fota_get_shell_key() == RT_EOK)
  1017. {
  1018. goto __exit_shell_entry;
  1019. }
  1020. }
  1021. else
  1022. {
  1023. LOG_I("Shell device config failed.");
  1024. }
  1025. // 记录区先就位,失败也不阻塞启动(分区坏了不能挡开机)
  1026. ecode_init();
  1027. // 复位来源已在 INIT_BOARD 级抓过(bl_capture_reset_cause),这里只落盘;
  1028. // 擦 RCC_CSR 交给 fal 的 print_reset_cause,别在这里抢
  1029. Recode_e_code(e_boot, bl_reset_bits);
  1030. // 出厂备份区必须有一份能通过校验的固件,没有就趁这次开机补一份
  1031. boot_auto_clone_df();
  1032. /* Firmware partition verify */
  1033. fota_err = rt_fota_part_fw_verify(RT_FOTA_FM_PART_NAME);
  1034. if (fota_err != RT_FOTA_NO_ERR)
  1035. {
  1036. // 坏包必须作废,否则每次开机都为它重算 384KB CRC
  1037. if (fota_err == RT_FOTA_FW_VERIFY_FAILED)
  1038. {
  1039. rt_fota_drop_pkg(RT_FOTA_FM_PART_NAME);
  1040. Recode_e_code(e_update_verify_fail, 1);
  1041. }
  1042. goto __exit_boot_entry;
  1043. }
  1044. Recode_e_code(e_update_verify_ok, 0);
  1045. /* Check upgrade status */
  1046. if (rt_fota_check_upgrade() <= 0)
  1047. goto __exit_boot_entry;
  1048. /* enter to upgrade mode */
  1049. rt_fota_signal_led_mode(led_upgrade_mode);
  1050. /* Implement upgrade, copy firmware partition to app partition */
  1051. Recode_e_code(e_update_start, 2);
  1052. fota_err = rt_fota_upgrade(RT_FOTA_FM_PART_NAME);
  1053. if (fota_err != RT_FOTA_NO_ERR)
  1054. {
  1055. Recode_e_code(e_update_fail, (uint16_t)(-fota_err));
  1056. goto __exit_boot_entry;
  1057. }
  1058. Recode_e_code(e_update_ok, 0);
  1059. /* Update new application verison in RBL file of firmware partition */
  1060. fota_err = rt_fota_copy_version(RT_FOTA_FM_PART_NAME);
  1061. if (fota_err != RT_FOTA_NO_ERR)
  1062. goto __exit_boot_entry;
  1063. __exit_boot_entry:
  1064. /* Implement application */
  1065. rt_fota_start_application();
  1066. __exit_shell_entry:
  1067. bl_stay_timeout_start((rt_uint32_t)(rt_tick_get() - bl_entry_tick));
  1068. /* enter to shell mode */
  1069. rt_fota_signal_led_mode(led_shell_mode);
  1070. /* Implement shell */
  1071. finsh_system_init();
  1072. extern struct rt_event hmi_event;
  1073. rt_event_send(&hmi_event, SWITCH_HMI);//切换到BootLoader显示页面
  1074. rt_thread_mdelay(100);
  1075. void display_firmware_info(void);
  1076. display_firmware_info();
  1077. Fw_mg_Ready //固件管理模式就绪
  1078. }
  1079. void rt_fota_init(void)
  1080. {
  1081. rt_thread_t tid;
  1082. tid = rt_thread_create("rt-boot", rt_fota_thread_entry, RT_NULL, RT_FOTA_THREAD_STACK_SIZE, RT_FOTA_THREAD_PRIORITY, 10);
  1083. if (tid != RT_NULL)
  1084. {
  1085. rt_thread_startup(tid);
  1086. }
  1087. else
  1088. {
  1089. LOG_I("rt-fota thread create failed.");
  1090. }
  1091. }
  1092. void rt_fota_info(rt_uint8_t argc, char **argv)
  1093. {
  1094. char put_buf[24];
  1095. char part_name[2][FAL_DEV_NAME_MAX] =
  1096. {
  1097. {RT_FOTA_FM_PART_NAME},
  1098. {RT_FOTA_DF_PART_NAME}
  1099. };
  1100. const char* help_info[] =
  1101. {
  1102. [0] = "fota probe - probe RBL file of partiton",
  1103. [1] = "fota show partition addr size - show 'size' bytes starting at 'addr'",
  1104. [2] = "fota clone des_part src_part - clone src partition to des partiton",
  1105. [3] = "fota exec - execute application program",
  1106. [4] = "fota upgrade - execute upgrade program from fm_area",
  1107. [5] = "fota upgrade_df - execute upgrade program from df_area",
  1108. };
  1109. if (argc < 2)
  1110. {
  1111. rt_kprintf("Usage:\n");
  1112. for (int i = 0; i < sizeof(help_info) / sizeof(char*); i++)
  1113. {
  1114. rt_kprintf("%s\n", help_info[i]);
  1115. }
  1116. rt_kprintf("\n");
  1117. }
  1118. else
  1119. {
  1120. const char *operator = argv[1];
  1121. if (!rt_strcmp(operator, "probe"))
  1122. {
  1123. for (int i = 0; i < 2; i++)
  1124. {
  1125. if (rt_fota_part_fw_verify(&part_name[i][0]) == RT_FOTA_NO_ERR)
  1126. {
  1127. LOG_I("===== RBL of %s partition =====", &part_name[i][0]);
  1128. LOG_I("| App partition name | %*.s |", 11, fota_part_head.app_part_name);
  1129. rt_memset(put_buf, 0x0, sizeof(put_buf));
  1130. // if ((fota_part_head.fota_algo & RT_FOTA_CRYPT_STAT_MASK) == RT_FOTA_CRYPT_ALGO_AES256)
  1131. // {
  1132. // rt_strncpy(put_buf, " AES", 4);
  1133. // }else
  1134. if ((fota_part_head.fota_algo & RT_FOTA_CRYPT_STAT_MASK) == RT_FOTA_CRYPT_ALGO_XOR)
  1135. {
  1136. rt_strncpy(put_buf, " XOR", 4);
  1137. }
  1138. else
  1139. {
  1140. rt_strncpy(put_buf, "NONE", 4);
  1141. }
  1142. if ((fota_part_head.fota_algo & RT_FOTA_CMPRS_STAT_MASK) == RT_FOTA_CMPRS_ALGO_GZIP)
  1143. {
  1144. rt_strncpy(&put_buf[rt_strlen(put_buf)], " && GLZ", 7);
  1145. }
  1146. // else if ((fota_part_head.fota_algo & RT_FOTA_CMPRS_STAT_MASK) == RT_FOTA_CMPRS_ALGO_QUICKLZ)
  1147. // {
  1148. // rt_strncpy(&put_buf[rt_strlen(put_buf)], " && QLZ", 7);
  1149. // }
  1150. else if ((fota_part_head.fota_algo & RT_FOTA_CMPRS_STAT_MASK) == RT_FOTA_CMPRS_ALGO_FASTLZ)
  1151. {
  1152. rt_strncpy(&put_buf[rt_strlen(put_buf)], " && FLZ", 7);
  1153. }
  1154. if (rt_strlen(put_buf) <= 0)
  1155. {
  1156. rt_strncpy(put_buf, "None", 4);
  1157. }
  1158. LOG_I("| Algorithm mode | %*.s |", 11, put_buf);
  1159. LOG_I("| Firmware version | %*.s |", 11, fota_part_head.download_version);
  1160. LOG_I("| Code raw size | %11d |", fota_part_head.raw_size);
  1161. LOG_I("| Code package size | %11d |", fota_part_head.com_size);
  1162. LOG_I("| Build Timestamp | %11d |", *((rt_uint32_t *)(&fota_part_head.fm_time[2])));
  1163. }
  1164. }
  1165. }
  1166. else if (!rt_strcmp(operator, "show"))
  1167. {
  1168. const struct fal_partition *part;
  1169. const char *part_name = argv[2];
  1170. rt_uint32_t addr = strtol(argv[3], NULL, 0);
  1171. rt_uint32_t size = strtol(argv[4], NULL, 0);
  1172. rt_uint8_t buf[16];
  1173. part = fal_partition_find(part_name);
  1174. if (part != RT_NULL)
  1175. {
  1176. while (size > 16)
  1177. {
  1178. fal_partition_read(part, addr, buf, 16);
  1179. rt_kprintf("%08X: ", addr);
  1180. for (int i = 0; i < 16; i++)
  1181. {
  1182. rt_kprintf("%02X ", buf[i]);
  1183. }
  1184. rt_kprintf("\n");
  1185. size -= 16;
  1186. addr += 16;
  1187. }
  1188. fal_partition_read(part, addr, buf, size);
  1189. rt_kprintf("%08X: ", addr);
  1190. for (int i = 0; i < size; i++)
  1191. {
  1192. rt_kprintf("%02X ", buf[i]);
  1193. }
  1194. rt_kprintf("\n");
  1195. }
  1196. else
  1197. {
  1198. rt_kprintf("%s partition is not exist!\n", part_name);
  1199. }
  1200. }
  1201. else if (!rt_strcmp(operator, "clone"))
  1202. {
  1203. const char *dst_part_name = argv[2];
  1204. const char *src_part_name = argv[3];
  1205. const struct fal_partition *dst_part;
  1206. const struct fal_partition *src_part;
  1207. dst_part = fal_partition_find(dst_part_name);
  1208. src_part = fal_partition_find(src_part_name);
  1209. if (dst_part == RT_NULL || src_part == RT_NULL)
  1210. {
  1211. if (dst_part == RT_NULL)
  1212. rt_kprintf("%s partition is not exist!\n", dst_part_name);
  1213. if (src_part == RT_NULL)
  1214. rt_kprintf("%s partition is not exist!\n", src_part_name);
  1215. }
  1216. else
  1217. {
  1218. // 源首字全 1 = 空分区。拿空做源去擦 dst,等于把 dst 也清空,
  1219. // 手工敲错参数就能把出厂备份毁掉,必须先挡
  1220. rt_uint32_t src_head = 0xFFFFFFFFu;
  1221. fal_partition_read(src_part, 0, (rt_uint8_t *)&src_head, sizeof(src_head));
  1222. if (src_head == 0xFFFFFFFFu)
  1223. {
  1224. rt_kprintf("src %s is blank, refuse to erase %s\n",
  1225. src_part_name, dst_part_name);
  1226. return; // 参数无效,直接退出,后面没有需要释放的资源
  1227. }
  1228. rt_kprintf("Clone %s partition to %s partition:\n", src_part_name, dst_part_name);
  1229. if (nor_erase_feeded(dst_part, 0, dst_part->len) >= 0)
  1230. {
  1231. int clone_pos = 0;
  1232. int clone_len = 0, clone_tol_len;
  1233. rt_uint8_t *buf = rt_malloc(4096);
  1234. if (dst_part->len < src_part->len)
  1235. clone_tol_len = dst_part->len;
  1236. else
  1237. clone_tol_len = src_part->len;
  1238. while ((clone_pos < clone_tol_len) && (buf != RT_NULL))
  1239. {
  1240. clone_len = fal_partition_read(src_part, clone_pos, buf, 4096);
  1241. if (clone_len < 0)
  1242. {
  1243. rt_kprintf("\nread %s partition failed, clone stop!\n", src_part_name);
  1244. break;
  1245. }
  1246. if (fal_partition_write(dst_part, clone_pos, buf, clone_len) < 0)
  1247. {
  1248. rt_kprintf("\nwrite %s partition failed, clone stop!\n", dst_part_name);
  1249. break;
  1250. }
  1251. rt_kprintf("#");
  1252. clone_pos += clone_len;
  1253. wdg_feed_once(); // 每克隆完一块立即喂一次
  1254. }
  1255. if (clone_pos >= clone_tol_len)
  1256. rt_kprintf("\nClone partition success, total %d bytes!\n", clone_tol_len);
  1257. else
  1258. rt_kprintf("\nClone partition failed!\n");
  1259. if (buf)
  1260. rt_free(buf);
  1261. }
  1262. }
  1263. }
  1264. else if (!rt_strcmp(operator, "exec"))
  1265. {
  1266. rt_fota_start_application();
  1267. }
  1268. else if (!rt_strcmp(operator, "upgrade"))
  1269. {
  1270. if (rt_fota_part_fw_verify(RT_FOTA_FM_PART_NAME) == RT_FOTA_NO_ERR)
  1271. {
  1272. if (rt_fota_upgrade(RT_FOTA_FM_PART_NAME) == RT_FOTA_NO_ERR)
  1273. {
  1274. rt_fota_start_application();
  1275. }
  1276. }
  1277. LOG_I("Boot application failed, entry shell mode.");
  1278. }
  1279. else if (!rt_strcmp(operator, "upgrade_df"))
  1280. {
  1281. if (rt_fota_part_fw_verify(RT_FOTA_DF_PART_NAME) == RT_FOTA_NO_ERR)
  1282. {
  1283. if (rt_fota_upgrade(RT_FOTA_DF_PART_NAME) == RT_FOTA_NO_ERR)
  1284. {
  1285. rt_fota_start_application();
  1286. }
  1287. }
  1288. LOG_I("Boot application failed, entry shell mode.");
  1289. }
  1290. else
  1291. {
  1292. rt_kprintf("Usage:\n");
  1293. for (int i = 0; i < sizeof(help_info) / sizeof(char*); i++)
  1294. {
  1295. rt_kprintf("%s\n", help_info[i]);
  1296. }
  1297. rt_kprintf("\n");
  1298. }
  1299. }
  1300. }
  1301. /**
  1302. * rt-fota />ymodem_ota
  1303. */
  1304. MSH_CMD_EXPORT_ALIAS(rt_fota_info, fota, Check RBL file of partition);
  1305. /******************自行增加子函数********************/
  1306. int upgrade_df(void)//恢复出厂固件
  1307. {
  1308. int fv = rt_fota_part_fw_verify(RT_FOTA_DF_PART_NAME);
  1309. if (fv != RT_FOTA_NO_ERR)
  1310. {
  1311. UpgradeFail
  1312. LOG_I("%s has no valid package (err %d).", RT_FOTA_DF_PART_NAME, fv);
  1313. Recode_e_code(e_boot_recover, 2);
  1314. return -1;
  1315. }
  1316. if (rt_fota_upgrade(RT_FOTA_DF_PART_NAME) != RT_FOTA_NO_ERR)
  1317. {
  1318. UpgradeFail
  1319. LOG_I("Factory package write failed.");
  1320. Recode_e_code(e_boot_recover, 3);
  1321. return -2;
  1322. }
  1323. UpgradeSuccess
  1324. return 0;
  1325. }
  1326. void upgrade(void)//从fm区烧写固件
  1327. {
  1328. if (rt_fota_part_fw_verify(RT_FOTA_FM_PART_NAME) == RT_FOTA_NO_ERR)
  1329. {
  1330. if (rt_fota_upgrade(RT_FOTA_FM_PART_NAME) == RT_FOTA_NO_ERR)
  1331. {
  1332. /* 更新fw分区当前的应用程序版本号*/
  1333. if(rt_fota_copy_version(RT_FOTA_FM_PART_NAME) == RT_FOTA_NO_ERR)
  1334. {
  1335. UpgradeFail//显示升级失败
  1336. }
  1337. UpgradeSuccess//升级成功
  1338. goto __exit_boot_entry;
  1339. }
  1340. }
  1341. UpgradeFail//显示升级失败
  1342. LOG_I("upgrade_fw failed, entry shell mode.");
  1343. goto __exit_boot_entry;
  1344. __exit_boot_entry:
  1345. /* Implement application */
  1346. rt_thread_mdelay(1000); //延时一段时间保证状态显示效果
  1347. rt_fota_start_application();
  1348. }
  1349. #include "bsp_date.h" // bl_time.c 提供的当前 RTC 值;合成出厂备份时要给包头填时间戳 extern uint32_t year, month, day, hour, min, sec; extern void Reflash_RTC(void);
  1350. rtc_time fm_compiletime;
  1351. rtc_time df_compiletime;
  1352. rtc_time time_convert(time_t timestamp)
  1353. {
  1354. rtc_time compiletime;
  1355. to_tm((timestamp + 8*60*60), &compiletime);/*把定时器的值转换为北京时间*/
  1356. /* 输出时间戳,公历时间 */
  1357. log_i("UNIX tamp = %d : %d-%d-%d-%0.2d:%0.2d:%0.2d\n",timestamp,
  1358. compiletime.tm_year, compiletime.tm_mon, compiletime.tm_mday,
  1359. compiletime.tm_hour, compiletime.tm_min, compiletime.tm_sec);
  1360. return compiletime;
  1361. }
  1362. extern void Display_fun_str(const char *position,char *str);
  1363. //显示版本号
  1364. void display_firmware_info(void)
  1365. {
  1366. char buf[100]= "\0";
  1367. char part_name[2][FAL_DEV_NAME_MAX] =
  1368. {
  1369. {RT_FOTA_FM_PART_NAME},
  1370. {RT_FOTA_DF_PART_NAME}
  1371. };
  1372. char intobl[] = "page bootloader";
  1373. Display_fun_str(intobl , NULL);
  1374. for (int i = 0; i < 2; i++)
  1375. {
  1376. if (rt_fota_part_fw_verify(&part_name[i][0]) == RT_FOTA_NO_ERR)
  1377. {
  1378. if(i == 0)
  1379. {
  1380. bl_delay_fed(200);
  1381. Display_fun_str("bootloader.t5.txt=\"当前固件版本:%-11s\"",fota_part_head.download_version);
  1382. fm_compiletime = time_convert(*((rt_uint32_t *)(&fota_part_head.fm_time[2])));
  1383. rt_memset(buf, '\0', 100);
  1384. rt_sprintf(buf,"%.2d/%.2d/%.2d %0.2d:%0.2d:%0.2d",
  1385. fm_compiletime.tm_year, fm_compiletime.tm_mon, fm_compiletime.tm_mday,
  1386. fm_compiletime.tm_hour, fm_compiletime.tm_min, fm_compiletime.tm_sec);
  1387. bl_delay_fed(500);
  1388. Display_fun_str("bootloader.t6.txt=\"编译日期:%s\"", buf);
  1389. }
  1390. else if(i == 1)
  1391. {
  1392. Display_fun_str("bootloader.t7.txt=\"出厂固件版本:%-11s\"",fota_part_head.download_version);
  1393. df_compiletime = time_convert(*((rt_uint32_t *)(&fota_part_head.fm_time[2])));
  1394. rt_memset(buf, '\0', 100);
  1395. rt_sprintf(buf,"%.2d/%.2d/%.2d %0.2d:%0.2d:%0.2d",
  1396. df_compiletime.tm_year, df_compiletime.tm_mon, df_compiletime.tm_mday,
  1397. df_compiletime.tm_hour, df_compiletime.tm_min, df_compiletime.tm_sec);
  1398. bl_delay_fed(500);
  1399. Display_fun_str("bootloader.t8.txt=\"编译日期:%s\"", buf);
  1400. }
  1401. bl_delay_fed(1000);
  1402. }
  1403. else
  1404. {
  1405. // 分区里没有有效包时必须清空这两行:否则屏上留着上一次的值,
  1406. // 现场会把旧备份当成当前固件看。
  1407. if (i == 0)
  1408. {
  1409. Display_fun_str("bootloader.t5.txt=\"当前固件版本:--\"", NULL);
  1410. Display_fun_str("bootloader.t6.txt=\"编译日期:--\"", NULL);
  1411. }
  1412. else
  1413. {
  1414. Display_fun_str("bootloader.t7.txt=\"出厂固件版本:--\"", NULL);
  1415. Display_fun_str("bootloader.t8.txt=\"编译日期:--\"", NULL);
  1416. }
  1417. }
  1418. }
  1419. }
  1420. uint8_t firstime_flag = 0;//第一次启动标志位
  1421. // BL 自己的上电次数,只用来给出厂备份当延时门槛
  1422. // 绝不能借用 APP 的 boot_t:那个键被 APP 当成"要不要重建默认参数"的信号,
  1423. // 参数复位就是把 0 写进去再重启。BL 一 ++ 就把这个信号抹掉,复位变假成功
  1424. uint32_t bl_boot_n = 0;
  1425. static void test_env(void)
  1426. {
  1427. size_t len;
  1428. len = ef_get_env_blob("bl_boot_n", &bl_boot_n, sizeof(bl_boot_n), NULL);
  1429. if (len != sizeof(bl_boot_n))
  1430. {
  1431. // 读不到(新板子或 ENV 被格式化)就从 0 重新计
  1432. bl_boot_n = 0;
  1433. }
  1434. if (bl_boot_n < 0xFFFFFFFFu)
  1435. {
  1436. bl_boot_n++;
  1437. }
  1438. // 只有写成功才算数:失败就把本地值退回去,别让下一次从假值往上加
  1439. if (bl_env_set("bl_boot_n", &bl_boot_n, sizeof(bl_boot_n)) == EF_NO_ERR)
  1440. {
  1441. LOG_I("BL boot %lu times", bl_boot_n);
  1442. }
  1443. else
  1444. {
  1445. LOG_E("BL boot counter not saved, still %lu.", bl_boot_n - 1u);
  1446. }
  1447. }
  1448. void easyflash_initialize(void)
  1449. {
  1450. EfErrCode err = easyflash_init();
  1451. // 初始化失败必须报出来:否则 firstime 永远是 0、开机次数永远从 1 算,全静默
  1452. if (err != EF_NO_ERR)
  1453. {
  1454. LOG_E("easyflash init failed: %d.", err);
  1455. return;
  1456. }
  1457. ef_get_env_blob("firstime", &firstime_flag, sizeof(firstime_flag), NULL);
  1458. LOG_I("firstime=%d", firstime_flag);
  1459. test_env();
  1460. sync_bl_ver_env(); // 把本 BL 版本告诉 APP,status 包要用
  1461. }
  1462. // 读一字节 ENV,键不存在或长度不符都算没读到
  1463. static int env_get_byte(const char *key, uint8_t *out)
  1464. {
  1465. uint8_t v = 0;
  1466. if (ef_get_env_blob(key, &v, sizeof(v), NULL) != sizeof(v))
  1467. {
  1468. return 0;
  1469. }
  1470. *out = v;
  1471. return 1;
  1472. }
  1473. // 写 ENV 必须看返回值:写不进去时日志还报"成功"就是撒谎,
  1474. // 现场表现就是 boot_t 卡在一个数不动、firstime 永远是 0
  1475. static EfErrCode bl_env_set(const char *key, const void *val, size_t len)
  1476. {
  1477. EfErrCode r = ef_set_env_blob(key, val, len);
  1478. if (r != EF_NO_ERR)
  1479. {
  1480. LOG_E("env \"%s\" write failed: %d", key, r);
  1481. Recode_e_code(e_env_fail, (uint16_t)(((uint16_t)(r & 0xFFu) << 8) | 1u));
  1482. }
  1483. return r;
  1484. }
  1485. static void env_set_byte(const char *key, uint8_t v)
  1486. {
  1487. bl_env_set(key, &v, sizeof(v));
  1488. }
  1489. // "V1.31" -> 131。非数字前缀跳过,主版本 0..2、次版本 0..99,超出返回 0 表示不支持
  1490. // 编码规则与 protocol.c 里 bak_parameters 回包的 bl_ver 一致:主*100 + 次
  1491. static uint8_t bl_version_code(const char *ver)
  1492. {
  1493. int major = 0;
  1494. int minor = 0;
  1495. const char *p = ver;
  1496. while ((*p != '\0') && ((*p < '0') || (*p > '9')))
  1497. {
  1498. p++;
  1499. }
  1500. while ((*p >= '0') && (*p <= '9'))
  1501. {
  1502. major = major * 10 + (*p - '0');
  1503. p++;
  1504. }
  1505. if (*p == '.')
  1506. {
  1507. p++;
  1508. while ((*p >= '0') && (*p <= '9'))
  1509. {
  1510. minor = minor * 10 + (*p - '0');
  1511. p++;
  1512. }
  1513. }
  1514. // uint8 只能放 0..255,主版本 >2 或次版本 >99 就是版本号超出本编码能力
  1515. if ((major > 2) || (minor > 99))
  1516. {
  1517. return 0;
  1518. }
  1519. return (uint8_t)(major * 100 + minor);
  1520. }
  1521. // 每次上电把 BL 版本同步进 ENV。值没变就不写,省 ENV 擦写寿命
  1522. static void sync_bl_ver_env(void)
  1523. {
  1524. uint8_t want = bl_version_code(Version);
  1525. uint8_t have = 0;
  1526. if (want == 0)
  1527. {
  1528. LOG_E("BL version \"%s\" unparsable, bl_ver not saved.", Version);
  1529. return;
  1530. }
  1531. if (env_get_byte("bl_ver", &have) && (have == want))
  1532. {
  1533. return;
  1534. }
  1535. env_set_byte("bl_ver", want);
  1536. LOG_I("bl_ver %u -> %u saved.", have, want);
  1537. }
  1538. // RTC 备份寄存器 DR3 的格式:高字节 magic + 低 24 位版本码
  1539. // magic 用来区分"BL 写过"和"备份域掉电后的随机值",否则 APP 会把野值当版本号
  1540. #define BL_VER_MAGIC 0xB1u
  1541. // 每次开机无条件写 RTC 备份寄存器,App 从那里读版本。
  1542. // 选 RTC 而不是 ENV 的原因:APP 的 ef_env_set_default() 会格式化整个 ENV 区,
  1543. // 参数复位后 bl_ver 必被抹掉;备份域不受影响。
  1544. // 没装 RTC 电池时备份域上电是野值,但 BL 是每次开机必走的路径,写一次就覆盖掉了
  1545. void bl_publish_version(void)
  1546. {
  1547. uint8_t code = bl_version_code(Version);
  1548. uint32_t val;
  1549. if (code == 0)
  1550. {
  1551. // 版本号超出编码能力:不写,让 APP 报 old,绝不塞一个假版本进去
  1552. rt_kprintf("BL version \"%s\" unparsable, RTC version not written\n", Version);
  1553. return;
  1554. }
  1555. val = ((uint32_t)BL_VER_MAGIC << 24) | (uint32_t)code;
  1556. // 成功不打:紧跟的版本横幅已说明 BL 是哪个版本;失败必须报,否则 APP 只能报 old
  1557. if (BSP_Write_RTC_Reg(App_Ver_Sync, Reg_All, val) == 0u)
  1558. {
  1559. rt_kprintf("BL ver RTC write FAILED\n");
  1560. }
  1561. }
  1562. // 把固件区整包克隆到出厂备份区。返回 0 成功,负数失败
  1563. // refresh_display:开机阶段屏还没就绪,不能刷屏;人工操作时才刷
  1564. static int df_clone_once(int refresh_display)
  1565. {
  1566. const struct fal_partition *dst_part;
  1567. const struct fal_partition *src_part;
  1568. rt_uint8_t *buf;
  1569. int clone_pos = 0;
  1570. int clone_len = 0;
  1571. int clone_tol_len;
  1572. dst_part = fal_partition_find(RT_FOTA_DF_PART_NAME);
  1573. src_part = fal_partition_find(RT_FOTA_FM_PART_NAME);
  1574. if (dst_part == RT_NULL || src_part == RT_NULL)
  1575. {
  1576. LOG_I("Backup partition missing (dst %d src %d).", dst_part != RT_NULL, src_part != RT_NULL);
  1577. return -1;
  1578. }
  1579. clone_tol_len = (dst_part->len < src_part->len) ? dst_part->len : src_part->len;
  1580. // 擦 dst 之前必须先确认 src 里真有货。源空着就擦,等于把备份清成 0xFF,
  1581. // 一旦 app 也空了就再也起不来(HMI 0x04 强制覆盖时可复现)。
  1582. // 用包头轻校验判断,不额外算 384KB body CRC
  1583. if (!rt_fota_part_head_ok(RT_FOTA_FM_PART_NAME))
  1584. {
  1585. LOG_I("No valid package in %s, refuse to erase %s.",
  1586. src_part->name, dst_part->name);
  1587. return -6;
  1588. }
  1589. buf = rt_malloc(4096);
  1590. if (buf == RT_NULL)
  1591. {
  1592. LOG_I("No memory for clone buffer.");
  1593. return -1;
  1594. }
  1595. LOG_I("Clone %s to %s, %d bytes.", src_part->name, dst_part->name, clone_tol_len);
  1596. if (nor_erase_feeded(dst_part, 0, dst_part->len) < 0)
  1597. {
  1598. LOG_I("Erase %s failed.", dst_part->name);
  1599. rt_free(buf);
  1600. return -2;
  1601. }
  1602. while (clone_pos < clone_tol_len)
  1603. {
  1604. clone_len = fal_partition_read(src_part, clone_pos, buf, 4096);
  1605. if (clone_len <= 0)
  1606. {
  1607. LOG_I("Read %s failed at %d.", src_part->name, clone_pos);
  1608. break;
  1609. }
  1610. if (fal_partition_write(dst_part, clone_pos, buf, clone_len) < 0)
  1611. {
  1612. LOG_I("Write %s failed at %d.", dst_part->name, clone_pos);
  1613. break;
  1614. }
  1615. clone_pos += clone_len;
  1616. wdg_feed_once();
  1617. }
  1618. rt_free(buf);
  1619. if (clone_pos < clone_tol_len)
  1620. {
  1621. LOG_I("Clone aborted at %d/%d.", clone_pos, clone_tol_len);
  1622. return -3;
  1623. }
  1624. // 回读校验:写完不算数,能按原样考出来才算备份成功
  1625. if (rt_fota_part_fw_verify(RT_FOTA_DF_PART_NAME) != RT_FOTA_NO_ERR)
  1626. {
  1627. LOG_I("Backup verify failed after clone.");
  1628. return -4;
  1629. }
  1630. // 只有真备成功才置位落盘,失败一定要留下重试机会
  1631. firstime_flag = 1;
  1632. env_set_byte("df_v", (uint8_t)BL_DF_BAK_VER);
  1633. bl_env_set("firstime", &firstime_flag, sizeof(firstime_flag));
  1634. LOG_I("Backup ok, firstime=%d.", firstime_flag);
  1635. if (refresh_display)
  1636. {
  1637. display_firmware_info();
  1638. }
  1639. return 0;
  1640. }
  1641. // 产线是直接烧 app 分区的,从没下发过 fm 包,此时 df 备份无从克隆。
  1642. // 这一条把正在跑的 app 反抄一份,按 RBL 格式补上头(fota_algo=0,不加密不压缩),
  1643. // 恢复时就是原样拷回去,跟正式包走同一条 rt_fota_upgrade 路径。
  1644. // 代价:df 无效时才做一次,约 7 秒(擦了 512KB + 写 384KB),做过就记 df_v 不再来。
  1645. // 只校验包头(64 字节),不算 384KB 的 body CRC。
  1646. // 用途:df_v 命中时确认"备份现在还在",避免 ENV 说有效、flash 其实已被擦。
  1647. // 每上电一次的开销是一次 64 字节读 + 一次短 CRC,可以忽略。
  1648. static int rt_fota_part_head_ok(const char *part_name)
  1649. {
  1650. const struct fal_partition *part;
  1651. rt_fota_part_head head;
  1652. part = fal_partition_find(part_name);
  1653. if (part == RT_NULL)
  1654. {
  1655. return 0;
  1656. }
  1657. if (fal_partition_read(part, 0, (rt_uint8_t *)&head, sizeof(head)) != sizeof(head))
  1658. {
  1659. return 0;
  1660. }
  1661. if (rt_fota_crc((rt_uint8_t *)&head, sizeof(head) - 4) != head.head_crc)
  1662. {
  1663. return 0;
  1664. }
  1665. if (rt_strcmp(head.type, "RBL") != 0)
  1666. {
  1667. return 0;
  1668. }
  1669. if (!rbl_pname_is(head.app_part_name, sizeof(head.app_part_name), QXZ_APP_PKG_NAME))
  1670. {
  1671. return 0;
  1672. }
  1673. return 1;
  1674. }
  1675. static int df_clone_from_app(void)
  1676. {
  1677. const struct fal_partition *app_part;
  1678. const struct fal_partition *df_part;
  1679. rt_fota_part_head head;
  1680. rt_uint8_t *buf;
  1681. rt_uint32_t addr;
  1682. rt_uint32_t len;
  1683. rt_uint32_t crc = 0xFFFFFFFFu;
  1684. rt_uint32_t pos = 0;
  1685. int n;
  1686. app_part = fal_partition_find(RT_FOTA_APP_PART_NAME);
  1687. df_part = fal_partition_find(RT_FOTA_DF_PART_NAME);
  1688. if ((app_part == RT_NULL) || (df_part == RT_NULL))
  1689. {
  1690. LOG_E("Partition missing for app backup.");
  1691. return -1;
  1692. }
  1693. len = app_part->len;
  1694. if (df_part->len < (len + sizeof(rt_fota_part_head)))
  1695. {
  1696. LOG_E("df_area too small: %d < %d.", df_part->len, len + sizeof(rt_fota_part_head));
  1697. return -1;
  1698. }
  1699. // 正在跑的这份自身必须自洽,否则抄下来也是个坏的
  1700. addr = ONCHIP_FLASH_BASE + app_part->offset;
  1701. if (!rt_fota_app_image_ok(addr))
  1702. {
  1703. LOG_E("APP image invalid, nothing to back up.");
  1704. return -2;
  1705. }
  1706. buf = rt_malloc(4096);
  1707. if (buf == RT_NULL)
  1708. {
  1709. LOG_E("No memory for app backup.");
  1710. return -1;
  1711. }
  1712. // 整分区当固件体:长度就取 app 分区长度,0xFF 尾巴也算内容,自洽且不越界
  1713. while (pos < len)
  1714. {
  1715. n = (int)((len - pos) > 4096u ? 4096u : (len - pos));
  1716. rt_memcpy(buf, (const void *)(addr + pos), (size_t)n);
  1717. crc = rt_fota_step_crc(crc, buf, (rt_uint32_t)n);
  1718. pos += (rt_uint32_t)n;
  1719. wdg_feed_once();
  1720. }
  1721. rt_memset(&head, 0, sizeof(head));
  1722. rt_memcpy(head.type, "RBL", 3);
  1723. head.fota_algo = 0; // 不加密不压缩,升级时原样拷回 app
  1724. rt_memcpy(head.app_part_name, QXZ_APP_PKG_NAME, rt_strlen(QXZ_APP_PKG_NAME));
  1725. // 版本号标 SYNTH:屏上一眼能看出这是本机自动合成的备份,不是平台下发的正式包
  1726. rt_snprintf(head.download_version, sizeof(head.download_version), "%s", "SYNTH");
  1727. rt_snprintf(head.current_version, sizeof(head.current_version), "%s", Version);
  1728. // 合成包必须自己填时间戳:正式包由打包脚本写,这里不填就是 0,
  1729. // 屏上"编译日期"会显示 1970/01/01(现场看到的就是这个)。
  1730. // 取当前 RTC 作为备份生成时间,配合 download_version=SYNTH 一起读。
  1731. {
  1732. rtc_time now_tm;
  1733. uint32_t now_stamp;
  1734. rt_memset(&now_tm, 0, sizeof(now_tm));
  1735. Reflash_RTC();
  1736. now_tm.tm_year = (int)year;
  1737. now_tm.tm_mon = (int)month;
  1738. now_tm.tm_mday = (int)day;
  1739. now_tm.tm_hour = (int)hour;
  1740. now_tm.tm_min = (int)min;
  1741. now_tm.tm_sec = (int)sec;
  1742. now_stamp = mktimev(&now_tm); // 会就地改 now_tm,之后不再用
  1743. if (now_stamp != 0)
  1744. rt_memcpy(&head.fm_time[2], &now_stamp, 4);
  1745. }
  1746. head.raw_size = len;
  1747. head.com_size = len;
  1748. head.code_crc = crc ^ 0xFFFFFFFFu;
  1749. head.head_crc = rt_fota_crc((rt_uint8_t *)&head, sizeof(rt_fota_part_head) - 4);
  1750. LOG_I("Synthesize factory pkg from %s, %d bytes.", app_part->name, len);
  1751. if (nor_erase_feeded(df_part, 0, df_part->len) < 0)
  1752. {
  1753. LOG_E("Erase %s failed.", df_part->name);
  1754. rt_free(buf);
  1755. return -3;
  1756. }
  1757. if (fal_partition_write(df_part, 0, (const rt_uint8_t *)&head, sizeof(head)) < 0)
  1758. {
  1759. LOG_E("Write pkg head to %s failed.", df_part->name);
  1760. rt_free(buf);
  1761. return -4;
  1762. }
  1763. pos = 0;
  1764. while (pos < len)
  1765. {
  1766. n = (int)((len - pos) > 4096u ? 4096u : (len - pos));
  1767. rt_memcpy(buf, (const void *)(addr + pos), (size_t)n);
  1768. if (fal_partition_write(df_part, sizeof(rt_fota_part_head) + pos, buf, (size_t)n) < 0)
  1769. {
  1770. LOG_E("Write body to %s failed at %u.", df_part->name, pos);
  1771. rt_free(buf);
  1772. return -4;
  1773. }
  1774. pos += (rt_uint32_t)n;
  1775. wdg_feed_once();
  1776. }
  1777. rt_free(buf);
  1778. // 写完必须走一遍正式校验,过不了就当没做,别留下半个包
  1779. if (rt_fota_part_fw_verify(RT_FOTA_DF_PART_NAME) != RT_FOTA_NO_ERR)
  1780. {
  1781. LOG_E("Synthesized pkg verify failed.");
  1782. return -5;
  1783. }
  1784. // 必须落盘 df_v,否则下次上电又白做一遍 7 秒合成
  1785. firstime_flag = 1;
  1786. bl_env_set("firstime", &firstime_flag, sizeof(firstime_flag));
  1787. env_set_byte("df_v", (uint8_t)BL_DF_BAK_VER);
  1788. LOG_I("Factory backup from APP ok.");
  1789. return 0;
  1790. }
  1791. // 首次烧写程序,出厂备份区保存固件(人工触发:HMI 指令 / U盘烧写后)
  1792. void firstime_clone_df(void)
  1793. {
  1794. if (firstime_flag != 0)
  1795. {
  1796. return;
  1797. }
  1798. // 源没包就别先报"正在写入备份",否则屏上刚亮写入就立刻跳失败
  1799. if (!rt_fota_part_head_ok(RT_FOTA_FM_PART_NAME))
  1800. {
  1801. LOG_I("No valid package in %s, backup skipped.", RT_FOTA_FM_PART_NAME);
  1802. UpgradeFail
  1803. return;
  1804. }
  1805. WritetoRecove
  1806. if (df_clone_once(1) == 0)
  1807. {
  1808. UpgradeSuccess
  1809. fota_status_send("固件存入备份分区成功", sizeof("固件存入备份分区成功"));
  1810. }
  1811. else
  1812. {
  1813. UpgradeFail
  1814. fota_status_send("固件存入备份分区失败", sizeof("固件存入备份分区失败"));
  1815. }
  1816. }
  1817. // 开机自检:出厂备份区必须有一份能过校验的固件,没有就自己补一份。
  1818. // 只看两个事实——df_v 记过没有、df_area 里有没有合法包,不依赖开机次数:
  1819. // 次数存在 ENV 里,会被 APP 的参数复位格式化抹掉,拿它当门槛等于永不触发
  1820. void boot_auto_clone_df(void)
  1821. {
  1822. uint8_t df_ver = 0;
  1823. const struct fal_partition *app_part;
  1824. rt_uint32_t app_addr;
  1825. int app_ok;
  1826. int err;
  1827. app_part = fal_partition_find(RT_FOTA_APP_PART_NAME);
  1828. app_addr = (app_part != RT_NULL) ? (app_part->offset + 0x08000000) : 0;
  1829. app_ok = (app_part != RT_NULL) && rt_fota_app_image_ok(app_addr);
  1830. // df_v 只说明"上次确认过",不说明"现在还在"。两种情况它都会说谎:
  1831. // app 被全片擦除(重烧 BL)后 df_v 仍是 1;df 包头被毁后 df_v 也仍是 1。
  1832. // 所以命中还要两道实证:app 能起来,且 df 包头完好。
  1833. // 正常设备这两道都是纯读操作(64 字节包头 + 8 字节镜像头),几乎零开销。
  1834. if (env_get_byte("df_v", &df_ver) && (df_ver == (uint8_t)BL_DF_BAK_VER)
  1835. && app_ok && rt_fota_part_head_ok(RT_FOTA_DF_PART_NAME))
  1836. {
  1837. return;
  1838. }
  1839. // app 已经不在了:这时候什么都别写,先让 rt_fota_start_application 去 df 恢复。
  1840. // 在这里重建备份毫无意义(没有源可抄),而且会白擦一遍 df。
  1841. if (!app_ok)
  1842. {
  1843. LOG_I("APP not bootable, skip backup rebuild.");
  1844. return;
  1845. }
  1846. // 备份区就有合法包:以前备过,只是 df_v 标记没落住,认下它别再擦一遍
  1847. // 只打日志不记 ecode:备份存在是稳态不是事件,记了就是刷记录;
  1848. // 真正该追的是"df_v 为什么会丢",那由 e_env_fail 报
  1849. if (rt_fota_part_fw_verify(RT_FOTA_DF_PART_NAME) == RT_FOTA_NO_ERR)
  1850. {
  1851. firstime_flag = 1;
  1852. bl_env_set("firstime", &firstime_flag, sizeof(firstime_flag));
  1853. env_set_byte("df_v", (uint8_t)BL_DF_BAK_VER);
  1854. LOG_I("Backup already valid, mark it.");
  1855. return;
  1856. }
  1857. // 固件区有包就照原样克隆;没包说明产线是直接烧 app 的,
  1858. // 那就把正在跑的这份 app 反抄成出厂包,否则永远建不起备份
  1859. if (rt_fota_part_fw_verify(RT_FOTA_FM_PART_NAME) == RT_FOTA_NO_ERR)
  1860. {
  1861. LOG_I("Clone backup from %s.", RT_FOTA_FM_PART_NAME);
  1862. err = df_clone_once(0);
  1863. if (err == 0)
  1864. {
  1865. Recode_e_code(e_df_backup, 0);
  1866. }
  1867. else if (err == -2)
  1868. {
  1869. Recode_e_code(e_df_backup, 3); // 备份区擦除失败
  1870. }
  1871. else if (err == -6)
  1872. {
  1873. Recode_e_code(e_df_backup, 2); // 源无有效包,拒绝擦备份
  1874. }
  1875. else
  1876. {
  1877. Recode_e_code(e_df_backup, 4); // 读/写/校验失败
  1878. }
  1879. }
  1880. else
  1881. {
  1882. LOG_I("%s empty, synthesize from running APP.", RT_FOTA_FM_PART_NAME);
  1883. err = df_clone_from_app();
  1884. if (err == 0)
  1885. {
  1886. Recode_e_code(e_df_backup, 0);
  1887. }
  1888. else if (err == -2)
  1889. {
  1890. Recode_e_code(e_df_backup, 2); // app 区没有可抄的镜像
  1891. }
  1892. else if (err == -3)
  1893. {
  1894. Recode_e_code(e_df_backup, 3); // 备份区擦除失败
  1895. }
  1896. else
  1897. {
  1898. Recode_e_code(e_df_backup, 4); // 写入/校验失败
  1899. }
  1900. }
  1901. LOG_I("Auto backup end, err %d.", err);
  1902. }