| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227 |
- /*
- * Copyright (c) 2006-2018, RT-Thread Development Team
- *
- * SPDX-License-Identifier: Apache-2.0
- *
- * Change Logs:
- * Date Author Notes
- * 2019-09-22 Warfalcon first version
- */
- #include <stdint.h>
- #include <stdio.h>
- #include <string.h>
- #include <rtthread.h>
- #include <rtdevice.h>
- #include <board.h>
- #include <fal.h>
- //#include <tinycrypt.h>
- //#include <fastlz.h>
- //#include <quicklz.h>
- #include <rt_fota.h>
- #include <signal_led.h>
- #include "sys_config.h"
- #include "ecode.h"
- #include "flash_ops.h"
- #include "main.h" // BSP_Write_RTC_Reg / App_Ver_Sync
- #include <easyflash.h>
- // 升级包目标分区名,打包时写入,APP 与 BL 强校验同一份白名单
- #define QXZ_APP_PKG_NAME "QXZAPP"
- #define QXZ_BL_PKG_NAME "QXZBL"
- void firstime_clone_df(void);
- // 定义在本文件后半段,drop_pkg 的退路判断要用
- static int rt_fota_app_image_ok(rt_uint32_t app_addr);
- static int rt_fota_part_head_ok(const char *part_name);
- void boot_auto_clone_df(void);
- static EfErrCode bl_env_set(const char *key, const void *val, size_t len);
- static void sync_bl_ver_env(void);
- void bl_publish_version(void);
- extern rt_uint32_t rt_fota_crc(rt_uint8_t *buf, rt_uint32_t len);
- extern rt_uint32_t rt_fota_step_crc(rt_uint32_t crc, rt_uint8_t *buf, rt_uint32_t len);
- // 定长字段整段比较,避免未终止字符串越界读
- static int rbl_pname_is(const char *field, rt_uint32_t size, const char *name)
- {
- rt_uint32_t n = rt_strlen(name);
- if (n >= size)
- {
- return 0;
- }
- if (rt_memcmp(field, name, n) != 0)
- {
- return 0;
- }
- return (field[n] == 0) ? 1 : 0;
- }
- // 擦掉 fm_area 包头让包彻底失效:只擦 4KB 头扇区,nor flash 擦除不会 stall CPU
- // 只对 fm_area 生效:df_area 是出厂备份,包头坏了只是"这个备份无效",
- // 主动擦掉等于自毁,一旦 app 也空了就彻底起不来
- // 而且擦之前必须有退路:系统里还得有一份能起来的固件,否则宁可不擦
- static void rt_fota_drop_pkg(const char *part_name)
- {
- const struct fal_partition *part;
- const struct fal_partition *app_part;
- int has_fallback;
- if (rt_strcmp(part_name, RT_FOTA_FM_PART_NAME) != 0)
- {
- return;
- }
- // 退路 = app 分区能启动,或 df 里有有效包头。
- // 两者都没有时,fm 里的坏包就是唯一"可能救回来"的东西,绝不擦。
- // 代价只是每次开机多算一次 64 字节包头 CRC —— 三个调用点都在 body CRC 之前
- app_part = fal_partition_find(RT_FOTA_APP_PART_NAME);
- has_fallback = ((app_part != RT_NULL)
- && rt_fota_app_image_ok(app_part->offset + 0x08000000))
- || rt_fota_part_head_ok(RT_FOTA_DF_PART_NAME);
- if (!has_fallback)
- {
- // 此处 rtdbg.h 还没 include,LOG_I 不可用,只能走 rt_kprintf
- rt_kprintf("no fallback firmware, keep broken %s pkg\n", part_name);
- return;
- }
- part = fal_partition_find(part_name);
- if (part != RT_NULL)
- {
- if (fal_partition_erase(part, 0, 4096) < 0)
- {
- rt_kprintf("drop pkg header failed\n");
- }
- wdg_feed_once();
- }
- }
- // 复位来源必须在这里抓:ports/fal/fal_flash_sfud_port.c 的 print_reset_cause()
- // 是 INIT_COMPONENT 级,它读完就把 RCC_CSR 清掉,等 rt_fota 跑到全是 0。
- // 这里只读不清,把清除留给它,否则它自己的日志会变成 Unknown。
- static uint16_t bl_reset_bits = 0;
- static int bl_capture_reset_cause(void)
- {
- uint32_t csr = RCC->CSR;
- if ((csr & RCC_CSR_PORRSTF) != 0u) bl_reset_bits |= 0x01;
- if ((csr & RCC_CSR_PINRSTF) != 0u) bl_reset_bits |= 0x02;
- if ((csr & RCC_CSR_SFTRSTF) != 0u) bl_reset_bits |= 0x04;
- if ((csr & RCC_CSR_IWDGRSTF) != 0u) bl_reset_bits |= 0x08;
- if ((csr & RCC_CSR_WWDGRSTF) != 0u) bl_reset_bits |= 0x10;
- if ((csr & RCC_CSR_LPWRRSTF) != 0u) bl_reset_bits |= 0x20;
- if ((csr & RCC_CSR_BORRSTF) != 0u) bl_reset_bits |= 0x40;
- // 主因文案由 ecode_detail 表按位的优先级决定(boot_desc),这里只采集位标志
- return 0;
- }
- INIT_BOARD_EXPORT(bl_capture_reset_cause);
- #define EXWATCHDOG_PIN GET_PIN(E, 11)
- void feed_watch(void)
- {
- if(rt_pin_read(EXWATCHDOG_PIN) == 0)rt_pin_write(EXWATCHDOG_PIN, PIN_HIGH);
- else if(rt_pin_read(EXWATCHDOG_PIN) == 1)rt_pin_write(EXWATCHDOG_PIN, PIN_LOW);
- }
- #if defined(RT_USING_FINSH) && defined(FINSH_USING_MSH)
- #include <finsh.h>
- #include <shell.h>
- #endif
- #define DBG_ENABLE
- #define DBG_SECTION_NAME "fota"
- #ifdef RT_FOTA_DEBUG
- #define DBG_LEVEL DBG_INFO
- #else
- #define DBG_LEVEL DBG_INFO
- #endif
- #define DBG_COLOR
- #include <rtdbg.h>
- // BL 停留上限:超过就强制离场,不允许无限停在 shell
- #define BL_STAY_TIMEOUT_S 120
- // 备份确认版本:老固件用 firstime 标记但写失败也置 1,升级后靠这个键自愈
- #define BL_DF_BAK_VER 1
- #ifndef RT_FOTA_THREAD_STACK_SIZE
- #define RT_FOTA_THREAD_STACK_SIZE 4096
- #endif
- #ifndef RT_FOTA_THREAD_PRIORITY
- #define RT_FOTA_THREAD_PRIORITY (RT_THREAD_PRIORITY_MAX - 3)
- #endif
- #ifndef RT_FOTA_ALGO_BUFF_SIZE
- #define RT_FOTA_ALGO_BUFF_SIZE 4096
- #endif
- /**
- * AES256 encryption algorithm option
- */
- #ifndef RT_FOTA_ALGO_AES_IV
- #define RT_FOTA_ALGO_AES_IV "0123456789ABCDEF"
- #endif
- #ifndef RT_FOTA_ALGO_AES_KEY
- #define RT_FOTA_ALGO_AES_KEY "0123456789ABCDEF0123456789ABCDEF"
- #endif
- #ifndef RT_FOTA_BLOCK_HEADER_SIZE
- #define RT_FOTA_BLOCK_HEADER_SIZE 4
- #endif
- #ifndef RT_FOTA_CMPRS_BUFFER_SIZE
- #define RT_FOTA_CMPRS_BUFFER_SIZE 4096
- #endif
- #ifndef RT_FOTA_FASTLZ_BUFFER_PADDING
- #define RT_FOTA_FASTLZ_BUFFER_PADDING FASTLZ_BUFFER_PADDING(RT_FOTA_CMPRS_BUFFER_SIZE)
- #endif
- //#ifndef RT_FOTA_QUICKLZ_BUFFER_PADDING
- //#define RT_FOTA_QUICKLZ_BUFFER_PADDING QLZ_BUFFER_PADDING
- //#endif
- #ifndef RT_FOTA_ENTER_SHELL_KEY
- #define RT_FOTA_ENTER_SHELL_KEY 0x0d
- #endif
- #ifndef RT_FOTA_GET_CHAR_WAITTIGN
- #define RT_FOTA_GET_CHAR_WAITTIGN (RT_TICK_PER_SECOND * 5)
- #endif
- // shell 等待分片:每片醒来喂一次外狗。
- // 这 5 秒 rt-boot 全程阻塞,原来一次 rt_sem_take 就睡满 5 秒,喂狗只靠 syswatch 单点。
- #ifndef RT_FOTA_SHELL_WAIT_SLICE
- #define RT_FOTA_SHELL_WAIT_SLICE (RT_TICK_PER_SECOND / 10)
- #endif
- #ifndef RT_FOTA_SIGNAL_LED_PIN
- #define RT_FOTA_SIGNAL_LED_PIN 76
- #endif
- #ifndef RT_FOTA_SIGNAL_LED_THREAD_STACK_SIZE
- #define RT_FOTA_SIGNAL_LED_THREAD_STACK_SIZE 1024
- #endif
- #ifndef RT_FOTA_SIGNAL_LED_THREAD_PRIORITY
- #define RT_FOTA_SIGNAL_LED_THREAD_PRIORITY (RT_THREAD_PRIORITY_MAX - 4)
- #endif
- /* For signal led */
- static led_t *signal_led = NULL;
- static led_mem_opreation_t signal_led_mem_op;
- const char *led_shell_mode = "500,500,"; /* 1Hz 闪烁 */
- const char *led_upgrade_mode = "50,50,"; /* 10Hz 闪烁 */
- const char *led_off_mode = "0,100,"; /* 常灭 */
- const char *led_on_mode = "100,0,"; /* 常亮 */
- /* For shell */
- static rt_sem_t shell_sem = RT_NULL;
- static rt_device_t shell_dev = RT_NULL;
- typedef struct {
- char type[4];
- rt_uint16_t fota_algo;
- rt_uint8_t fm_time[6];
- char app_part_name[16];
- char download_version[24];
- char current_version[24];
- rt_uint32_t code_crc;
- rt_uint32_t hash_val;
- rt_uint32_t raw_size;
- rt_uint32_t com_size;
- rt_uint32_t head_crc;
- } rt_fota_part_head, *rt_fota_part_head_t;
- typedef void (*rt_fota_app_func)(void);
- static rt_fota_app_func app_func = RT_NULL;
- static rt_fota_part_head fota_part_head;
- static void rt_fota_signal_led_on(void)
- {
- rt_pin_write(RT_FOTA_SIGNAL_LED_PIN, PIN_LOW);
- }
- static void rt_fota_signal_led_off(void)
- {
- rt_pin_write(RT_FOTA_SIGNAL_LED_PIN, PIN_HIGH);
- }
- static void rt_fota_signal_led_entry(void *arg)
- {
- while(1)
- {
- led_ticks();
- rt_thread_mdelay(LED_TICK_TIME);
- }
- }
- static void rt_fota_signal_led_init(void)
- {
- rt_pin_mode(RT_FOTA_SIGNAL_LED_PIN, PIN_MODE_OUTPUT);
- signal_led_mem_op.malloc_fn = (void* (*)(size_t))rt_malloc;
- signal_led_mem_op.free_fn = rt_free;
- led_set_mem_operation(&signal_led_mem_op);
- signal_led = led_create(rt_fota_signal_led_on, rt_fota_signal_led_off);
- /* Config signal led mode */
- led_set_mode(signal_led, LOOP_PERMANENT, (char *)led_on_mode);
- led_set_blink_over_callback(signal_led, RT_NULL);
- led_start(signal_led);
- rt_thread_t tid;
- 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);
- if (tid)
- rt_thread_startup(tid);
- }
- static void rt_fota_signal_led_mode(const char *led_cfg)
- {
- RT_ASSERT(led_cfg != RT_NULL);
- led_set_mode(signal_led, LOOP_PERMANENT, (char *)led_cfg);
- }
- static int rt_fota_boot_verify(void)
- {
- int fota_res = RT_FOTA_NO_ERR;
- rt_memset(&fota_part_head, 0x0, sizeof(rt_fota_part_head));
- /* partition initial */
- fal_init();
- extern int fal_init_check(void);
- /* verify partition */
- if (fal_init_check() != 1)
- {
- PartitionInitFail
- LOG_D("Partition initialized failed!");
- fota_res = RT_FOTA_GENERAL_ERR;
- goto __exit_boot_verify;
- }
- __exit_boot_verify:
- return fota_res;
- }
- int rt_fota_part_fw_verify(const char *part_name)
- {
- #define RT_FOTA_CRC_BUFF_SIZE 4096
- #define RT_FOTA_CRC_INIT_VAL 0xffffffff
- int fota_res = RT_FOTA_NO_ERR;
- const struct fal_partition *part;
- rt_fota_part_head part_head;
- rt_uint8_t *body_buf = RT_NULL;
- rt_uint32_t body_crc = RT_FOTA_CRC_INIT_VAL;
- rt_uint32_t hdr_crc;
- if (part_name == RT_NULL)
- {
- LOG_D("Invaild paramenter input!");
- fota_res = RT_FOTA_GENERAL_ERR;
- goto __exit_partition_verify;
- }
- part = fal_partition_find(part_name);
- if (part == RT_NULL)
- {
- PartitionNotFound
- LOG_D("Partition[%s] not found.", part_name);
- fota_res = RT_FOTA_GENERAL_ERR;
- goto __exit_partition_verify;
- }
- /* read the head of RBL files */
- if (fal_partition_read(part, 0, (rt_uint8_t *)&part_head, sizeof(rt_fota_part_head)) < 0)
- {
- PartitionReadError //分区读取错误
- // 读失败必须报:DBG_LEVEL=DBG_INFO 会把 LOG_D 整条编译掉,等于"读不到"和"读到了 FF"无法区分
- LOG_E("Partition[%s] head read failed!", part->name);
- fota_res = RT_FOTA_PART_READ_ERR;
- goto __exit_partition_verify;
- }
- // 空分区(全 0xFF)= 从没下过包。这是开机常态,静默返回,不打日志也不记事件
- {
- const rt_uint32_t *w = (const rt_uint32_t *)&part_head;
- rt_uint32_t n;
- int blank = 1;
- for (n = 0; n < (sizeof(rt_fota_part_head) / 4u); n++)
- {
- if (w[n] != 0xFFFFFFFFu)
- {
- blank = 0;
- break;
- }
- }
- if (blank)
- {
- fota_res = RT_FOTA_CHECK_FAILED;
- goto __exit_partition_verify;
- }
- }
- extern rt_uint32_t rt_fota_crc(rt_uint8_t *buf, rt_uint32_t len);
- hdr_crc = rt_fota_crc((rt_uint8_t *)&part_head, sizeof(rt_fota_part_head) - 4);
- if (hdr_crc != part_head.head_crc)
- {
- // 包头对不上就擦掉让它失效。但擦之前必须把实测值留下:
- // 这是唯一能看出"包到底写成什么样"的时刻,擦完就成了全 0xFF 的黑盒
- LOG_W("fm head crc: got %08X want %08X type=%02X%02X%02X%02X",
- (unsigned)part_head.head_crc, (unsigned)hdr_crc,
- (unsigned)(rt_uint8_t)part_head.type[0], (unsigned)(rt_uint8_t)part_head.type[1],
- (unsigned)(rt_uint8_t)part_head.type[2], (unsigned)(rt_uint8_t)part_head.type[3]);
- rt_fota_drop_pkg(part_name);
- fota_res = RT_FOTA_CHECK_FAILED;
- goto __exit_partition_verify;
- }
- if (rt_strcmp(part_head.type, "RBL") != 0)
- {
- // 不是 RBL 包,等同没有包。打出来是哪种类型,才看得出包是怎么来的
- LOG_W("fm type not RBL: %02X %02X %02X %02X",
- (unsigned)(rt_uint8_t)part_head.type[0], (unsigned)(rt_uint8_t)part_head.type[1],
- (unsigned)(rt_uint8_t)part_head.type[2], (unsigned)(rt_uint8_t)part_head.type[3]);
- rt_fota_drop_pkg(part_name);
- fota_res = RT_FOTA_CHECK_FAILED;
- goto __exit_partition_verify;
- }
- // 包只用一次:升级成功会把 partname 擦成 0xFF,这里第一道门就返回,
- // 384KB 整包 CRC 不再做(这是开机时外狗超时的主因之一)
- if (!rbl_pname_is(part_head.app_part_name, sizeof(part_head.app_part_name), QXZ_APP_PKG_NAME))
- {
- // 只有既不是"已用掉"(0xFF)、也不是旧格式("app")时才说明头在传输/落盘时被改了;
- // 前两种是开机常态,静默处理,否则每次开机都刷一条
- if ((!rbl_pname_is(part_head.app_part_name, sizeof(part_head.app_part_name), "app"))
- && ((rt_uint8_t)part_head.app_part_name[0] != 0xFFu))
- {
- LOG_W("fm part_name unexpected: %.16s", part_head.app_part_name);
- }
- if (rbl_pname_is(part_head.app_part_name, sizeof(part_head.app_part_name), "app"))
- {
- rt_fota_drop_pkg(part_name);
- }
- fota_res = RT_FOTA_CHECK_FAILED;
- goto __exit_partition_verify;
- }
- // 体积上限必须在擦除之前卡死:包头被篡改时 raw_size 会直接传给擦除,
- // 越界就会把 bl 分区抹掉(BL 自己就没代码可跑了)
- {
- const struct fal_partition *app_part = fal_partition_find(RT_FOTA_APP_PART_NAME);
- if ((app_part == RT_NULL) || (part_head.raw_size == 0) || (part_head.com_size == 0)
- || (part_head.raw_size > app_part->len) || (part_head.com_size > app_part->len))
- {
- LOG_W("pkg size out of range: raw=%u com=%u part=%u",
- part_head.raw_size, part_head.com_size,
- (app_part != RT_NULL) ? app_part->len : 0);
- PartitionIntegrityVerifyError
- fota_res = RT_FOTA_FW_VERIFY_FAILED;
- goto __exit_partition_verify;
- }
- }
- body_buf = rt_malloc(RT_FOTA_CRC_BUFF_SIZE);
- if (body_buf == RT_NULL)
- {
- LOG_W("Not enough memory for body CRC32 verify.");
- fota_res = RT_FOTA_NO_MEM_ERR;
- goto __exit_partition_verify;
- }
- // 分包递进:每读完一包(4KB)立刻校验并喂一次狗,包与包之间串行
- for (int body_pos = 0; body_pos < part_head.com_size;)
- {
- int body_read_len;
- body_read_len = fal_partition_read(part, sizeof(rt_fota_part_head) + body_pos, body_buf, RT_FOTA_CRC_BUFF_SIZE);
- if (body_read_len > 0)
- {
- if ((body_pos + body_read_len) > part_head.com_size)
- {
- body_read_len = part_head.com_size - body_pos;
- }
- extern rt_uint32_t rt_fota_step_crc(rt_uint32_t crc, rt_uint8_t *buf, rt_uint32_t len);
- body_crc = rt_fota_step_crc(body_crc, body_buf, body_read_len);
- body_pos = body_pos + body_read_len;
- wdg_feed_once(); // 每校验完一包立即喂一次,串行递进
- }
- else
- {
- LOG_W("Partition[%s] read error!", part->name);
- fota_res = RT_FOTA_PART_READ_ERR;
- goto __exit_partition_verify;
- }
- }
- body_crc = body_crc ^ RT_FOTA_CRC_INIT_VAL;
- if (body_crc != part_head.code_crc)
- {
- PartitionIntegrityVerifyError //固件完整性校验失败
- LOG_W("Partition[%s] firmware integrity verify failed.", part->name);
- fota_res = RT_FOTA_FW_VERIFY_FAILED;
- goto __exit_partition_verify;
- }
- char cache[32] = {0};
- __exit_partition_verify:
- if (fota_res == RT_FOTA_NO_ERR)
- {
- rt_enter_critical();
- rt_memcpy(&fota_part_head, &part_head, sizeof(rt_fota_part_head));
- rt_exit_critical();
- //PartitionVerifySuccess //固件校验成功
- sprintf(cache , "固件校验成功:%s" , part_name);
- fota_status_send( cache, strlen(cache));
- LOG_I("partition[%s] verify success!", part->name);
- }
- else
- {
- rt_enter_critical();
- rt_memset(&fota_part_head, 0x0, sizeof(rt_fota_part_head));
- rt_exit_critical();
- // RT_FOTA_CHECK_FAILED 表示"没有待升级包",是开机常态,不打印也不上屏;
- // 只有真有 QXZAPP 包头但体积/内容校验不过时才报,避免现场被无意义的失败刷屏
- if (fota_res != RT_FOTA_CHECK_FAILED)
- {
- LOG_W("fota_res:%d partition[%s] verify failed", fota_res, part_name);
- sprintf(cache , "固件校验失败:%s" , part_name);
- fota_status_send( cache, strlen(cache));
- }
- }
- if (body_buf)
- rt_free(body_buf);
- return fota_res;
- }
- int rt_fota_check_upgrade(void)
- {
- int is_upgrade = 0;
- rt_kprintf("download_version %s >> current_version %s \n" , fota_part_head.download_version, fota_part_head.current_version);
- // 一次性包:partname 合法就要装,不再比版本号(否则同版本重刷会被跳过)
- if (rbl_pname_is(fota_part_head.app_part_name, sizeof(fota_part_head.app_part_name), QXZ_APP_PKG_NAME))
- {
- is_upgrade = 1;
- LOG_D("Application need upgrade.");
- goto __exit_check_upgrade;
- }
- __exit_check_upgrade:
- return is_upgrade;
- }
- int rt_fota_copy_version(const char *part_name)
- {
- #define THE_NOR_FLASH_GRANULARITY 4096
- int fota_res = RT_FOTA_NO_ERR;
- const struct fal_partition *part;
-
- rt_fota_part_head_t part_head = RT_NULL;
- rt_uint8_t *cache_buf = RT_NULL;
- part = fal_partition_find(part_name);
- if (part == RT_NULL)
- {
- LOG_D("Find partition[%s] not found.", part_name);
- fota_res = RT_FOTA_FW_VERIFY_FAILED;
- goto __exit_copy_version;
- }
- cache_buf = rt_malloc(THE_NOR_FLASH_GRANULARITY);
- if (cache_buf == RT_NULL)
- {
- LOG_I("Not enough memory for head erase.");
- fota_res = RT_FOTA_NO_MEM_ERR;
- goto __exit_copy_version;
- }
- part_head = (rt_fota_part_head_t)cache_buf;
- if (fal_partition_read(part, 0, cache_buf, THE_NOR_FLASH_GRANULARITY) < 0)
- {
- LOG_I("Read partition[%s] failed.", part_name);
- fota_res = RT_FOTA_PART_READ_ERR;
- goto __exit_copy_version;
- }
- rt_memcpy(part_head->current_version, part_head->download_version, sizeof(part_head->current_version));
- // 一次性消耗:把目标分区名整段填 0xFF,下次开机 verify 第一道门就过不了
- rt_memset(part_head->app_part_name, 0xFF, sizeof(part_head->app_part_name));
- extern rt_uint32_t rt_fota_crc(rt_uint8_t *buf, rt_uint32_t len);
- part_head->head_crc = rt_fota_crc((rt_uint8_t *)part_head, sizeof(rt_fota_part_head) - 4);
- if (fal_partition_erase(part, 0, THE_NOR_FLASH_GRANULARITY) < 0)
- {
- LOG_I("Erase partition[%s] failed.", part_name);
- fota_res = RT_FOTA_PART_ERASE_ERR;
- goto __exit_copy_version;
- }
- if (fal_partition_write(part, 0, (const rt_uint8_t *)cache_buf, THE_NOR_FLASH_GRANULARITY) < 0)
- {
- LOG_I("Write partition[%s] failed.", part_name);
- fota_res = RT_FOTA_PART_WRITE_ERR;
- goto __exit_copy_version;
- }
- wdg_feed_once();
- __exit_copy_version:
- if (cache_buf)
- rt_free(cache_buf);
- if (fota_res != RT_FOTA_NO_ERR)
- LOG_I("Copy firmware version failed!");
- else
- LOG_I("Copy firmware version Success!");
- return fota_res;
- }
- int rt_fota_erase_app_part(void)
- {
- int fota_res = RT_FOTA_NO_ERR;
- const struct fal_partition *part;
- // 包头里的 QXZAPP 是产品级名字,fal 分区名仍是 app,不能用包里的名字去 find
- part = fal_partition_find(RT_FOTA_APP_PART_NAME);
- if (part == RT_NULL)
- {
- PartitionNotFound //分区未找到
- LOG_D("Erase partition[%s] not found.", fota_part_head.app_part_name);
- fota_res = RT_FOTA_FW_VERIFY_FAILED;
- goto __exit_partition_erase;
- }
- EraseStart //开始擦除分区
- // 128KB 扇区擦除是慢操作,最坏十几秒且全程无输出,先说明一句免得现场以为死机
- LOG_I("Erase %s %u bytes, may take 10s+...", part->name, fota_part_head.raw_size);
- // 128KB 扇区擦除期间 CPU 取指被 stall,必须走 SRAM 里的擦除循环持续喂狗
- if (flash_erase_range_hw(ONCHIP_FLASH_BASE + part->offset, fota_part_head.raw_size) != 0)
- {
- EraseFailed //擦除失败
- LOG_I("Partition[%s] erase failed!", part->name);
- fota_res = RT_FOTA_PART_ERASE_ERR;
- goto __exit_partition_erase;
- }
- __exit_partition_erase:
- if (fota_res == RT_FOTA_NO_ERR)
- {
- EraseSuccess //擦除成功
- LOG_D("Partition[%s] erase %d bytes success!", part->name, fota_part_head.raw_size);
- }
- return fota_res;
- }
- int rt_fota_write_app_part(int fw_pos, rt_uint8_t *fw_buf, int fw_len)
- {
- int rt_fota_res = RT_FOTA_NO_ERR;
- const struct fal_partition *part;
- // 包头里的 QXZAPP 是产品级名字,fal 分区名仍是 app,不能用包里的名字去 find
- part = fal_partition_find(RT_FOTA_APP_PART_NAME);
- if (part == RT_NULL)
- {
- PartitionNotFound
- LOG_D("Erase partition[%s] not found.", fota_part_head.app_part_name);
- rt_fota_res = RT_FOTA_FW_VERIFY_FAILED;
- goto __partition_write_exit;
- }
- if (fal_partition_write(part, fw_pos, fw_buf, fw_len) < 0)
- {
- WriteFailed //写入失败
- LOG_I("Partition[%s] write failed!", part->name);
- rt_fota_res = RT_FOTA_PART_WRITE_ERR;
- goto __partition_write_exit;
- }
- __partition_write_exit:
- if (rt_fota_res == RT_FOTA_NO_ERR)
- {
- LOG_D("Partition[%s] write %d bytes success!", part->name, fw_len);
- }
- return rt_fota_res;
- }
- 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)
- {
- int fota_err = RT_FOTA_NO_ERR;
- rt_uint8_t *encrypt_buf = RT_NULL;
- if ((part == RT_NULL) || (decrypt_buf == RT_NULL)
- || (decrypt_len % 16 != 0) || (decrypt_len > RT_FOTA_ALGO_BUFF_SIZE))
- {
- fota_err = RT_FOTA_GENERAL_ERR;
- goto __exit_read_decrypt;
- }
- rt_memset(decrypt_buf, 0x0, decrypt_len);
- /* Not use AES256 algorithm */
- if (aes_ctx == RT_NULL || aes_iv == RT_NULL)
- {
- fota_err = fal_partition_read(part, sizeof(rt_fota_part_head) + read_pos, decrypt_buf, decrypt_len);
- if (fota_err <= 0)
- {
- fota_err = RT_FOTA_PART_READ_ERR;
- }
- goto __exit_read_decrypt;
- }
- encrypt_buf = rt_malloc(decrypt_len);
- if (encrypt_buf == RT_NULL)
- {
- fota_err = RT_FOTA_GENERAL_ERR;
- goto __exit_read_decrypt;
- }
- rt_memset(encrypt_buf, 0x0, decrypt_len);
- fota_err = fal_partition_read(part, sizeof(rt_fota_part_head) + read_pos, encrypt_buf, decrypt_len);
- if (fota_err <= 0 || fota_err % 16 != 0)
- {
- fota_err = RT_FOTA_PART_READ_ERR;
- goto __exit_read_decrypt;
- }
- // tiny_aes_crypt_cbc(aes_ctx, AES_DECRYPT, fota_err, aes_iv, encrypt_buf, decrypt_buf);
- __exit_read_decrypt:
- if (encrypt_buf)
- rt_free(encrypt_buf);
- return fota_err;
- }
- int rt_fota_upgrade(const char *part_name)
- {
- int fota_err = RT_FOTA_NO_ERR;
- const struct fal_partition *part;
- rt_fota_part_head_t part_head = RT_NULL;
- tiny_aes_context *aes_ctx = RT_NULL;
- rt_uint8_t *aes_iv = RT_NULL;
- rt_uint8_t *crypt_buf = RT_NULL;
- int fw_raw_pos = 0;
- int fw_raw_len = 0;
- rt_uint32_t total_copy_size = 0;
- rt_uint8_t block_hdr_buf[RT_FOTA_BLOCK_HEADER_SIZE];
- rt_uint32_t block_hdr_pos = RT_FOTA_ALGO_BUFF_SIZE;
- rt_uint32_t block_size = 0;
- rt_uint32_t dcprs_size = 0;
- // qlz_state_decompress *dcprs_state = RT_NULL;
- rt_uint8_t *cmprs_buff = RT_NULL;
- rt_uint8_t *dcprs_buff = RT_NULL;
- rt_uint32_t padding_size = 0;
- if (part_name == RT_NULL)
- {
- LOG_D("Invaild paramenter input!");
- fota_err = RT_FOTA_GENERAL_ERR;
- goto __exit_upgrade;
- }
- part = fal_partition_find(part_name);
- if (part == RT_NULL)
- {PartitionNotFound
- LOG_I("Upgrade partition[%s] not found.", part_name);
- fota_err = RT_FOTA_GENERAL_ERR;
- goto __exit_upgrade;
- }
- /* Application partition erase */
- fota_err = rt_fota_erase_app_part();
- if (fota_err != RT_FOTA_NO_ERR)
- {
- goto __exit_upgrade;
- }
- /* rt_fota_erase_app_part() has check fota_part_head vaild already */
- part_head = &fota_part_head;
- crypt_buf = rt_malloc(RT_FOTA_ALGO_BUFF_SIZE);
- if (crypt_buf == RT_NULL)
- {
- LOG_I("Not enough memory for firmware buffer.");
- fota_err = RT_FOTA_NO_MEM_ERR;
- goto __exit_upgrade;
- }
- if ((part_head->fota_algo & RT_FOTA_CRYPT_STAT_MASK) == RT_FOTA_CRYPT_ALGO_XOR)
- {
- LOG_I("Not surpport XOR.");
- fota_err = RT_FOTA_GENERAL_ERR;
- goto __exit_upgrade;
- }
- else if ((part_head->fota_algo & RT_FOTA_CMPRS_STAT_MASK) == RT_FOTA_CMPRS_ALGO_GZIP)
- {
- LOG_I("Not surpport GZIP.");
- fota_err = RT_FOTA_GENERAL_ERR;
- goto __exit_upgrade;
- }
- //按照输入分区名称判断显示
- if(rt_strcmp(part_name,"fm_area") == 0)Flash_Fw //正在刷写固件
- else if(rt_strcmp(part_name,"df_area") == 0)Recove_Fw //正在恢复出厂固件
- LOG_I("Start to copy firmware from %s to %s partition:", part->name, part_head->app_part_name);
- while (fw_raw_pos < part_head->com_size)
- {
- fw_raw_len = rt_fota_read_part(part, fw_raw_pos, aes_ctx, aes_iv, crypt_buf, RT_FOTA_ALGO_BUFF_SIZE);
- if (fw_raw_len < 0)
- {
- LOG_I("AES256 algorithm failed.");
- fota_err = RT_FOTA_PART_READ_ERR;
- goto __exit_upgrade;
- }
- fw_raw_pos += fw_raw_len;
- if (rt_fota_write_app_part(total_copy_size, crypt_buf, fw_raw_len) < 0)
- {
- fota_err = RT_FOTA_COPY_FAILED;
- goto __exit_upgrade;
- }
- total_copy_size += fw_raw_len;
- wdg_feed_once();
- rt_kprintf("#");
- }
- /* it has compress option */
- if ((part_head->fota_algo & RT_FOTA_CMPRS_STAT_MASK) != RT_FOTA_CRYPT_ALGO_NONE)
- {
- while (total_copy_size < part_head->raw_size)
- {
- if ((block_hdr_pos < fw_raw_len) && ((fw_raw_len - block_hdr_pos) > RT_FOTA_BLOCK_HEADER_SIZE))
- {
- rt_memcpy(block_hdr_buf, &crypt_buf[block_hdr_pos], RT_FOTA_BLOCK_HEADER_SIZE);
- block_size = block_hdr_buf[0] * (1 << 24) + block_hdr_buf[1] * (1 << 16) + block_hdr_buf[2] * (1 << 8) + block_hdr_buf[3];
- if ((fw_raw_len - block_hdr_pos - RT_FOTA_BLOCK_HEADER_SIZE) >= block_size)
- {
- rt_memset(cmprs_buff, 0x0, RT_FOTA_CMPRS_BUFFER_SIZE + padding_size);
- rt_memcpy(cmprs_buff, &crypt_buf[block_hdr_pos + RT_FOTA_BLOCK_HEADER_SIZE], block_size);
- rt_memset(dcprs_buff, 0x0, RT_FOTA_CMPRS_BUFFER_SIZE);
-
- block_hdr_pos += (block_size + RT_FOTA_BLOCK_HEADER_SIZE);
-
- if (dcprs_size <= 0)
- {
- LOG_I("Decompress failed: %d.", dcprs_size);
- fota_err = RT_FOTA_GENERAL_ERR;
- goto __exit_upgrade;
- }
- if (rt_fota_write_app_part(total_copy_size, dcprs_buff, dcprs_size) < 0)
- {
- fota_err = RT_FOTA_COPY_FAILED;
- goto __exit_upgrade;
- }
- total_copy_size += dcprs_size;
- wdg_feed_once(); // 每写入一块立即喂一次
- rt_kprintf("#");
- }
- else
- {
- break;
- }
- }
- else
- {
- break;
- }
- }
- }
- rt_kprintf("\r\n");
- /* 有可能两个值不相等,因为AES需要填充16字节整数,但最后的解密解压值的代码数量必须是大于等于raw_size */
- /* 比较好的方法是做一个校验,目前打包软件的HASH_CODE算法不知道 */
- if (total_copy_size < part_head->raw_size)
- {
- LOG_I("Decompress check failed.");
- fota_err = RT_FOTA_GENERAL_ERR;
- }
- __exit_upgrade:
- if (aes_ctx)
- rt_free(aes_ctx);
- if (aes_iv)
- rt_free(aes_iv);
- if (crypt_buf)
- rt_free(crypt_buf);
- if (cmprs_buff)
- rt_free(cmprs_buff);
- if (dcprs_buff)
- rt_free(dcprs_buff);
- // if (dcprs_state)
- // rt_free(dcprs_state);
- if (fota_err == RT_FOTA_NO_ERR)
- { UpgradeSuccess //固件升级成功
- LOG_I("Upgrade success, total %d bytes.", total_copy_size);
- }
- else UpgradeFail //固件升级失败
- return fota_err;
- }
- // APP 区镜像自检:首字是 SRAM 栈顶,次字是 0x08XXXXXX 复位入口,缺一个都不能跳
- static int rt_fota_app_image_ok(rt_uint32_t app_addr)
- {
- //判断是否为0x08XXXXXX.
- if (((*(__IO uint32_t *)(app_addr + 4)) & 0xff000000) != 0x08000000)
- {
- return 0;
- }
- // 检查栈顶地址是否合法.
- if (((*(__IO uint32_t *)app_addr) & 0x2ffe0000) != 0x20000000)
- {
- return 0;
- }
- return 1;
- }
- int rt_fota_start_application(void)
- {
- int fota_res = RT_FOTA_NO_ERR;
- const struct fal_partition *part;
- rt_uint32_t app_addr;
- part = fal_partition_find(RT_FOTA_APP_PART_NAME);
- if (part == RT_NULL)
- {
- LOG_I("Partition[%s] not found.", RT_FOTA_APP_PART_NAME);
- fota_res = RT_FOTA_GENERAL_ERR;
- goto __exit_start_application;
- }
- app_addr = part->offset + 0x08000000;
- // APP 区没有可启动镜像时硬跳会跑飞,必须先拿出厂固件补一次,补不上就停在这里
- if (!rt_fota_app_image_ok(app_addr))
- {
- LOG_I("APP image invalid, boot refused.");
- Recode_e_code(e_boot_recover, 1);
- LOG_I("Recover APP from %s.", RT_FOTA_DF_PART_NAME);
- if (upgrade_df() != 0)
- {
- fota_res = RT_FOTA_GENERAL_ERR;
- goto __exit_start_application;
- }
- if (!rt_fota_app_image_ok(app_addr))
- {
- // 恢复后仍不可启动说明出厂包本身有问题,再补也是空转
- LOG_I("APP image still invalid after recover.");
- Recode_e_code(e_boot_recover, 4);
- fota_res = RT_FOTA_GENERAL_ERR;
- goto __exit_start_application;
- }
- LOG_I("Factory image restored, boot again.");
- }
- StartApp //正在启动应用……
- for (int i = 0; i < 10; i++)
- {
- wdg_feed_once();
- rt_thread_mdelay(100);
- }
- rt_pin_mode(GET_PIN(E, 0), PIN_MODE_OUTPUT);
- rt_pin_write(GET_PIN(E, 0), PIN_LOW);
- for (int i = 0; i < 10; i++)
- {
- wdg_feed_once();
- rt_thread_mdelay(100);
- }
- rt_pin_write(GET_PIN(E, 0), PIN_HIGH);
- LOG_I("Implement application now.");
-
- __disable_irq();
- // for (IRQn_Type irq = WWDG_IRQn; irq <= FPU_IRQn; irq++)
- // {
- // HAL_NVIC_DisableIRQ(irq);
- // HAL_NVIC_ClearPendingIRQ(irq);
- // }
- //Resets the RCC clock configuration to the default reset state.
- HAL_RCC_DeInit();
-
- SysTick->CTRL = 0;
- SysTick->LOAD = 0;
- SysTick->VAL = 0;
- HAL_DeInit();
- //用户代码区第二个字为程序开始地址(复位地址)
- app_func = (rt_fota_app_func)*(__IO uint32_t *)(app_addr + 4);
- /* Configure main stack */
- __set_MSP(*(__IO uint32_t *)app_addr);
-
- /* jump to application */
- app_func();
- __exit_start_application:
- LOG_I("Implement application failed.");
- return fota_res;
- }
- // 外狗约 2 秒没被翻转就拉 NRST。BL 里任何上千毫秒的等待都不能只靠
- // syswatch 一个线程喂狗,自己切片喂:每片醒来翻一次 WDI。
- #ifndef RT_FOTA_FEED_SLICE_MS
- #define RT_FOTA_FEED_SLICE_MS 200
- #endif
- static void bl_delay_fed(rt_int32_t ms)
- {
- while (ms > 0)
- {
- rt_int32_t step = (ms > RT_FOTA_FEED_SLICE_MS) ? RT_FOTA_FEED_SLICE_MS : ms;
- rt_thread_mdelay(step);
- wdg_feed_once();
- ms -= step;
- }
- }
- static rt_err_t rt_fota_get_shell_key(void)
- {
- char ch = 0;
- rt_err_t res = RT_EOK;
- rt_tick_t tick_start;
- RT_ASSERT(shell_dev != RT_NULL);
- RT_ASSERT(shell_sem != RT_NULL);
- // 计时一律用 tick 差值,绝不把全局 tick 归零:
- // 线程延时的 timeout_tick 是绝对值(timer.c: rt_tick_get() + init_tick),
- // tick 一归零,此刻所有挂起的延时都要等 tick 重新涨回旧值才到期,
- // syswatch 的 mdelay(10) 正是其中之一,喂狗会被硬冻几百毫秒。
- tick_start = rt_tick_get();
- while (1)
- {
- if (rt_device_read(shell_dev, -1, &ch, 1) == 1)
- {
- if (ch == RT_FOTA_ENTER_SHELL_KEY)
- {
- goto __exit_get_shell_key;
- }
- }
- else
- {
- // 分片等,不再一次睡满 5 秒
- rt_sem_take(shell_sem, RT_FOTA_SHELL_WAIT_SLICE);
- }
- // 每片都喂一次,不管是等到的还是读到的:
- // 5 秒的喂狗责任不能只押在 syswatch 一个线程上
- wdg_feed_once();
- if ((rt_tick_get() - tick_start) >= RT_FOTA_GET_CHAR_WAITTIGN)
- {
- res = RT_ERROR;
- goto __exit_get_shell_key;
- }
- }
- __exit_get_shell_key:
- return res;
- }
- static rt_err_t rt_fota_rx_ind(rt_device_t dev, rt_size_t size)
- {
- RT_ASSERT(shell_sem != RT_NULL);
- /* release semaphore to let fota thread rx data */
- rt_sem_release(shell_sem);
- return RT_EOK;
- }
- static rt_err_t rt_fota_set_device(const char *device_name)
- {
- rt_device_t dev;
- RT_ASSERT(device_name != RT_NULL);
- dev = rt_device_find(device_name);
- if (dev == RT_NULL)
- {
- LOG_D("Can not find device: %s.", device_name);
- return RT_ERROR;
- }
- if (shell_sem)
- rt_sem_delete(shell_sem);
-
- shell_sem = rt_sem_create("shell_sem", 0, RT_IPC_FLAG_FIFO);
- if (shell_sem == RT_NULL)
- return RT_ERROR;
- if (dev == shell_dev)
- return RT_EOK;
- if (rt_device_open(dev, RT_DEVICE_OFLAG_RDWR | RT_DEVICE_FLAG_INT_RX | RT_DEVICE_FLAG_STREAM) == RT_EOK)
- {
- if (shell_dev != RT_NULL)
- {
- /* close old finsh device */
- rt_device_close(shell_dev);
- rt_device_set_rx_indicate(shell_dev, RT_NULL);
- }
- shell_dev = dev;
- rt_device_set_rx_indicate(dev, rt_fota_rx_ind);
-
- LOG_D("Shell device %s open success.", device_name);
- return RT_EOK;
- }
- LOG_D("Shell device %s open failed.", device_name);
- return RT_ERROR;
- }
- #define RT_FOTA_DEFAULT_KEY_PIN GET_PIN(E, 15)
- #define RT_FOTA_DEFAULT_KEY_CHK_TIME 5
- #if defined(RT_FOTA_DEFAULT_KEY_PIN) && defined(RT_FOTA_DEFAULT_KEY_CHK_TIME)
- static rt_err_t rt_fota_check_defalut_key(void)
- {
- int chk_idx;
-
- /* GPIO initialized */
- rt_pin_mode(RT_FOTA_DEFAULT_KEY_PIN, PIN_MODE_INPUT_PULLUP);
- /* Delay for power up */
- bl_delay_fed(500);
- if (rt_pin_read(RT_FOTA_DEFAULT_KEY_PIN) == PIN_LOW)
- rt_kprintf("Default firmware key pressed:\n");
- /* Check GPIO status */
- for (chk_idx = 0; (rt_pin_read(RT_FOTA_DEFAULT_KEY_PIN) == PIN_LOW) && (chk_idx < RT_FOTA_DEFAULT_KEY_CHK_TIME); chk_idx++)
- {
- bl_delay_fed(RT_TICK_PER_SECOND);
- rt_kprintf(">");
- }
- if (chk_idx < RT_FOTA_DEFAULT_KEY_CHK_TIME)
- return RT_ERROR;
- else
- return RT_EOK;
- }
- #endif
- // 进了 shell 就是放弃启动,到点必须离场:能跳就跳,跳不了复位重来
- static void bl_stay_timeout_thread(void *arg)
- {
- rt_uint32_t wait_ms = (rt_uint32_t)(rt_ubase_t)arg;
- // 120 秒的等待同样自己切片喂:shell 模式下不能只靠 syswatch 一个喂狗源
- bl_delay_fed((rt_int32_t)wait_ms);
- LOG_I("BL stay over %d s, force leave.", BL_STAY_TIMEOUT_S);
- Recode_e_code(e_boot_timeout, BL_STAY_TIMEOUT_S);
- rt_fota_start_application();
- // APP 区没有可启动镜像时跳不过去,复位重来一轮(含出厂恢复)
- rt_hw_cpu_reset();
- }
- static void bl_stay_timeout_start(rt_uint32_t elapsed_ms)
- {
- rt_thread_t tid;
- rt_uint32_t wait_ms = (rt_uint32_t)BL_STAY_TIMEOUT_S * 1000u;
- wait_ms = (elapsed_ms >= wait_ms) ? 0u : (wait_ms - elapsed_ms);
- tid = rt_thread_create("bl-timeout", bl_stay_timeout_thread, (void *)(rt_ubase_t)wait_ms,
- 2048, RT_FOTA_THREAD_PRIORITY + 1, 10);
- if (tid != RT_NULL)
- {
- rt_thread_startup(tid);
- }
- else
- {
- LOG_I("bl-timeout thread create failed.");
- }
- }
- void rt_fota_thread_entry(void *arg)
- {
- int fota_err = RT_FOTA_NO_ERR;
- rt_tick_t bl_entry_tick = rt_tick_get();
- extern int finsh_system_init(void);
- /* Signal led initialized */
- rt_fota_signal_led_init();
- /* Partition initialized */
- fota_err = rt_fota_boot_verify();
- if (fota_err != RT_FOTA_NO_ERR)
- {
- LOG_I("Partition initialized failed.");
- }
- #if defined(RT_FOTA_DEFAULT_KEY_PIN) && defined(RT_FOTA_DEFAULT_KEY_CHK_TIME)
- /* Default key check */
- if (rt_fota_check_defalut_key() == RT_EOK)
- {
- /* enter to defalut key mode */
- rt_fota_signal_led_mode(led_upgrade_mode);
- // goto __exit_default_entry;
- goto __exit_shell_entry;
- }
- #endif
- /* Shell initialized */
- if (rt_fota_set_device(RT_CONSOLE_DEVICE_NAME) == RT_EOK)
- {
- rt_kprintf("Please press [Enter] key into shell mode in %d secs:\r\n", RT_FOTA_GET_CHAR_WAITTIGN / RT_TICK_PER_SECOND);
- if (rt_fota_get_shell_key() == RT_EOK)
- {
- goto __exit_shell_entry;
- }
- }
- else
- {
- LOG_I("Shell device config failed.");
- }
- // 记录区先就位,失败也不阻塞启动(分区坏了不能挡开机)
- ecode_init();
- // 复位来源已在 INIT_BOARD 级抓过(bl_capture_reset_cause),这里只落盘;
- // 擦 RCC_CSR 交给 fal 的 print_reset_cause,别在这里抢
- Recode_e_code(e_boot, bl_reset_bits);
- // 出厂备份区必须有一份能通过校验的固件,没有就趁这次开机补一份
- boot_auto_clone_df();
- /* Firmware partition verify */
- fota_err = rt_fota_part_fw_verify(RT_FOTA_FM_PART_NAME);
- if (fota_err != RT_FOTA_NO_ERR)
- {
- // 坏包必须作废,否则每次开机都为它重算 384KB CRC
- if (fota_err == RT_FOTA_FW_VERIFY_FAILED)
- {
- rt_fota_drop_pkg(RT_FOTA_FM_PART_NAME);
- Recode_e_code(e_update_verify_fail, 1);
- }
- goto __exit_boot_entry;
- }
- Recode_e_code(e_update_verify_ok, 0);
- /* Check upgrade status */
- if (rt_fota_check_upgrade() <= 0)
- goto __exit_boot_entry;
- /* enter to upgrade mode */
- rt_fota_signal_led_mode(led_upgrade_mode);
- /* Implement upgrade, copy firmware partition to app partition */
- Recode_e_code(e_update_start, 2);
- fota_err = rt_fota_upgrade(RT_FOTA_FM_PART_NAME);
- if (fota_err != RT_FOTA_NO_ERR)
- {
- Recode_e_code(e_update_fail, (uint16_t)(-fota_err));
- goto __exit_boot_entry;
- }
- Recode_e_code(e_update_ok, 0);
- /* Update new application verison in RBL file of firmware partition */
- fota_err = rt_fota_copy_version(RT_FOTA_FM_PART_NAME);
- if (fota_err != RT_FOTA_NO_ERR)
- goto __exit_boot_entry;
- __exit_boot_entry:
- /* Implement application */
- rt_fota_start_application();
- __exit_shell_entry:
- bl_stay_timeout_start((rt_uint32_t)(rt_tick_get() - bl_entry_tick));
- /* enter to shell mode */
- rt_fota_signal_led_mode(led_shell_mode);
- /* Implement shell */
- finsh_system_init();
- extern struct rt_event hmi_event;
- rt_event_send(&hmi_event, SWITCH_HMI);//切换到BootLoader显示页面
- rt_thread_mdelay(100);
- void display_firmware_info(void);
- display_firmware_info();
- Fw_mg_Ready //固件管理模式就绪
- }
- void rt_fota_init(void)
- {
- rt_thread_t tid;
- tid = rt_thread_create("rt-boot", rt_fota_thread_entry, RT_NULL, RT_FOTA_THREAD_STACK_SIZE, RT_FOTA_THREAD_PRIORITY, 10);
- if (tid != RT_NULL)
- {
- rt_thread_startup(tid);
- }
- else
- {
- LOG_I("rt-fota thread create failed.");
- }
- }
- void rt_fota_info(rt_uint8_t argc, char **argv)
- {
- char put_buf[24];
- char part_name[2][FAL_DEV_NAME_MAX] =
- {
- {RT_FOTA_FM_PART_NAME},
- {RT_FOTA_DF_PART_NAME}
- };
- const char* help_info[] =
- {
- [0] = "fota probe - probe RBL file of partiton",
- [1] = "fota show partition addr size - show 'size' bytes starting at 'addr'",
- [2] = "fota clone des_part src_part - clone src partition to des partiton",
- [3] = "fota exec - execute application program",
- [4] = "fota upgrade - execute upgrade program from fm_area",
- [5] = "fota upgrade_df - execute upgrade program from df_area",
- };
- if (argc < 2)
- {
- rt_kprintf("Usage:\n");
- for (int i = 0; i < sizeof(help_info) / sizeof(char*); i++)
- {
- rt_kprintf("%s\n", help_info[i]);
- }
- rt_kprintf("\n");
- }
- else
- {
- const char *operator = argv[1];
- if (!rt_strcmp(operator, "probe"))
- {
- for (int i = 0; i < 2; i++)
- {
- if (rt_fota_part_fw_verify(&part_name[i][0]) == RT_FOTA_NO_ERR)
- {
- LOG_I("===== RBL of %s partition =====", &part_name[i][0]);
- LOG_I("| App partition name | %*.s |", 11, fota_part_head.app_part_name);
- rt_memset(put_buf, 0x0, sizeof(put_buf));
- // if ((fota_part_head.fota_algo & RT_FOTA_CRYPT_STAT_MASK) == RT_FOTA_CRYPT_ALGO_AES256)
- // {
- // rt_strncpy(put_buf, " AES", 4);
- // }else
- if ((fota_part_head.fota_algo & RT_FOTA_CRYPT_STAT_MASK) == RT_FOTA_CRYPT_ALGO_XOR)
- {
- rt_strncpy(put_buf, " XOR", 4);
- }
- else
- {
- rt_strncpy(put_buf, "NONE", 4);
- }
- if ((fota_part_head.fota_algo & RT_FOTA_CMPRS_STAT_MASK) == RT_FOTA_CMPRS_ALGO_GZIP)
- {
- rt_strncpy(&put_buf[rt_strlen(put_buf)], " && GLZ", 7);
- }
- // else if ((fota_part_head.fota_algo & RT_FOTA_CMPRS_STAT_MASK) == RT_FOTA_CMPRS_ALGO_QUICKLZ)
- // {
- // rt_strncpy(&put_buf[rt_strlen(put_buf)], " && QLZ", 7);
- // }
- else if ((fota_part_head.fota_algo & RT_FOTA_CMPRS_STAT_MASK) == RT_FOTA_CMPRS_ALGO_FASTLZ)
- {
- rt_strncpy(&put_buf[rt_strlen(put_buf)], " && FLZ", 7);
- }
- if (rt_strlen(put_buf) <= 0)
- {
- rt_strncpy(put_buf, "None", 4);
- }
- LOG_I("| Algorithm mode | %*.s |", 11, put_buf);
- LOG_I("| Firmware version | %*.s |", 11, fota_part_head.download_version);
- LOG_I("| Code raw size | %11d |", fota_part_head.raw_size);
- LOG_I("| Code package size | %11d |", fota_part_head.com_size);
- LOG_I("| Build Timestamp | %11d |", *((rt_uint32_t *)(&fota_part_head.fm_time[2])));
- }
- }
- }
- else if (!rt_strcmp(operator, "show"))
- {
- const struct fal_partition *part;
- const char *part_name = argv[2];
- rt_uint32_t addr = strtol(argv[3], NULL, 0);
- rt_uint32_t size = strtol(argv[4], NULL, 0);
- rt_uint8_t buf[16];
- part = fal_partition_find(part_name);
- if (part != RT_NULL)
- {
- while (size > 16)
- {
- fal_partition_read(part, addr, buf, 16);
- rt_kprintf("%08X: ", addr);
- for (int i = 0; i < 16; i++)
- {
- rt_kprintf("%02X ", buf[i]);
- }
- rt_kprintf("\n");
- size -= 16;
- addr += 16;
- }
- fal_partition_read(part, addr, buf, size);
- rt_kprintf("%08X: ", addr);
- for (int i = 0; i < size; i++)
- {
- rt_kprintf("%02X ", buf[i]);
- }
- rt_kprintf("\n");
- }
- else
- {
- rt_kprintf("%s partition is not exist!\n", part_name);
- }
- }
- else if (!rt_strcmp(operator, "clone"))
- {
- const char *dst_part_name = argv[2];
- const char *src_part_name = argv[3];
- const struct fal_partition *dst_part;
- const struct fal_partition *src_part;
- dst_part = fal_partition_find(dst_part_name);
- src_part = fal_partition_find(src_part_name);
- if (dst_part == RT_NULL || src_part == RT_NULL)
- {
- if (dst_part == RT_NULL)
- rt_kprintf("%s partition is not exist!\n", dst_part_name);
- if (src_part == RT_NULL)
- rt_kprintf("%s partition is not exist!\n", src_part_name);
- }
- else
- {
- // 源首字全 1 = 空分区。拿空做源去擦 dst,等于把 dst 也清空,
- // 手工敲错参数就能把出厂备份毁掉,必须先挡
- rt_uint32_t src_head = 0xFFFFFFFFu;
- fal_partition_read(src_part, 0, (rt_uint8_t *)&src_head, sizeof(src_head));
- if (src_head == 0xFFFFFFFFu)
- {
- rt_kprintf("src %s is blank, refuse to erase %s\n",
- src_part_name, dst_part_name);
- return; // 参数无效,直接退出,后面没有需要释放的资源
- }
- rt_kprintf("Clone %s partition to %s partition:\n", src_part_name, dst_part_name);
- if (nor_erase_feeded(dst_part, 0, dst_part->len) >= 0)
- {
- int clone_pos = 0;
- int clone_len = 0, clone_tol_len;
- rt_uint8_t *buf = rt_malloc(4096);
- if (dst_part->len < src_part->len)
- clone_tol_len = dst_part->len;
- else
- clone_tol_len = src_part->len;
- while ((clone_pos < clone_tol_len) && (buf != RT_NULL))
- {
- clone_len = fal_partition_read(src_part, clone_pos, buf, 4096);
- if (clone_len < 0)
- {
- rt_kprintf("\nread %s partition failed, clone stop!\n", src_part_name);
- break;
- }
- if (fal_partition_write(dst_part, clone_pos, buf, clone_len) < 0)
- {
- rt_kprintf("\nwrite %s partition failed, clone stop!\n", dst_part_name);
- break;
- }
- rt_kprintf("#");
- clone_pos += clone_len;
- wdg_feed_once(); // 每克隆完一块立即喂一次
- }
- if (clone_pos >= clone_tol_len)
- rt_kprintf("\nClone partition success, total %d bytes!\n", clone_tol_len);
- else
- rt_kprintf("\nClone partition failed!\n");
- if (buf)
- rt_free(buf);
- }
- }
- }
- else if (!rt_strcmp(operator, "exec"))
- {
- rt_fota_start_application();
- }
- else if (!rt_strcmp(operator, "upgrade"))
- {
- if (rt_fota_part_fw_verify(RT_FOTA_FM_PART_NAME) == RT_FOTA_NO_ERR)
- {
- if (rt_fota_upgrade(RT_FOTA_FM_PART_NAME) == RT_FOTA_NO_ERR)
- {
- rt_fota_start_application();
- }
- }
- LOG_I("Boot application failed, entry shell mode.");
- }
- else if (!rt_strcmp(operator, "upgrade_df"))
- {
- if (rt_fota_part_fw_verify(RT_FOTA_DF_PART_NAME) == RT_FOTA_NO_ERR)
- {
- if (rt_fota_upgrade(RT_FOTA_DF_PART_NAME) == RT_FOTA_NO_ERR)
- {
- rt_fota_start_application();
- }
- }
- LOG_I("Boot application failed, entry shell mode.");
- }
- else
- {
- rt_kprintf("Usage:\n");
- for (int i = 0; i < sizeof(help_info) / sizeof(char*); i++)
- {
- rt_kprintf("%s\n", help_info[i]);
- }
- rt_kprintf("\n");
- }
- }
- }
- /**
- * rt-fota />ymodem_ota
- */
- MSH_CMD_EXPORT_ALIAS(rt_fota_info, fota, Check RBL file of partition);
- /******************自行增加子函数********************/
- int upgrade_df(void)//恢复出厂固件
- {
- int fv = rt_fota_part_fw_verify(RT_FOTA_DF_PART_NAME);
- if (fv != RT_FOTA_NO_ERR)
- {
- UpgradeFail
- LOG_I("%s has no valid package (err %d).", RT_FOTA_DF_PART_NAME, fv);
- Recode_e_code(e_boot_recover, 2);
- return -1;
- }
- if (rt_fota_upgrade(RT_FOTA_DF_PART_NAME) != RT_FOTA_NO_ERR)
- {
- UpgradeFail
- LOG_I("Factory package write failed.");
- Recode_e_code(e_boot_recover, 3);
- return -2;
- }
- UpgradeSuccess
- return 0;
- }
- void upgrade(void)//从fm区烧写固件
- {
- if (rt_fota_part_fw_verify(RT_FOTA_FM_PART_NAME) == RT_FOTA_NO_ERR)
- {
- if (rt_fota_upgrade(RT_FOTA_FM_PART_NAME) == RT_FOTA_NO_ERR)
- {
- /* 更新fw分区当前的应用程序版本号*/
- if(rt_fota_copy_version(RT_FOTA_FM_PART_NAME) == RT_FOTA_NO_ERR)
- {
- UpgradeFail//显示升级失败
- }
- UpgradeSuccess//升级成功
- goto __exit_boot_entry;
- }
- }
- UpgradeFail//显示升级失败
- LOG_I("upgrade_fw failed, entry shell mode.");
- goto __exit_boot_entry;
- __exit_boot_entry:
- /* Implement application */
- rt_thread_mdelay(1000); //延时一段时间保证状态显示效果
- rt_fota_start_application();
- }
- #include "bsp_date.h"
// bl_time.c 提供的当前 RTC 值;合成出厂备份时要给包头填时间戳
extern uint32_t year, month, day, hour, min, sec;
extern void Reflash_RTC(void);
- rtc_time fm_compiletime;
- rtc_time df_compiletime;
- rtc_time time_convert(time_t timestamp)
- {
- rtc_time compiletime;
- to_tm((timestamp + 8*60*60), &compiletime);/*把定时器的值转换为北京时间*/
- /* 输出时间戳,公历时间 */
- log_i("UNIX tamp = %d : %d-%d-%d-%0.2d:%0.2d:%0.2d\n",timestamp,
- compiletime.tm_year, compiletime.tm_mon, compiletime.tm_mday,
- compiletime.tm_hour, compiletime.tm_min, compiletime.tm_sec);
- return compiletime;
- }
- extern void Display_fun_str(const char *position,char *str);
- //显示版本号
- void display_firmware_info(void)
- {
- char buf[100]= "\0";
- char part_name[2][FAL_DEV_NAME_MAX] =
- {
- {RT_FOTA_FM_PART_NAME},
- {RT_FOTA_DF_PART_NAME}
- };
- char intobl[] = "page bootloader";
- Display_fun_str(intobl , NULL);
- for (int i = 0; i < 2; i++)
- {
- if (rt_fota_part_fw_verify(&part_name[i][0]) == RT_FOTA_NO_ERR)
- {
- if(i == 0)
- {
- bl_delay_fed(200);
- Display_fun_str("bootloader.t5.txt=\"当前固件版本:%-11s\"",fota_part_head.download_version);
- fm_compiletime = time_convert(*((rt_uint32_t *)(&fota_part_head.fm_time[2])));
- rt_memset(buf, '\0', 100);
- rt_sprintf(buf,"%.2d/%.2d/%.2d %0.2d:%0.2d:%0.2d",
- fm_compiletime.tm_year, fm_compiletime.tm_mon, fm_compiletime.tm_mday,
- fm_compiletime.tm_hour, fm_compiletime.tm_min, fm_compiletime.tm_sec);
- bl_delay_fed(500);
- Display_fun_str("bootloader.t6.txt=\"编译日期:%s\"", buf);
- }
- else if(i == 1)
- {
- Display_fun_str("bootloader.t7.txt=\"出厂固件版本:%-11s\"",fota_part_head.download_version);
- df_compiletime = time_convert(*((rt_uint32_t *)(&fota_part_head.fm_time[2])));
- rt_memset(buf, '\0', 100);
- rt_sprintf(buf,"%.2d/%.2d/%.2d %0.2d:%0.2d:%0.2d",
- df_compiletime.tm_year, df_compiletime.tm_mon, df_compiletime.tm_mday,
- df_compiletime.tm_hour, df_compiletime.tm_min, df_compiletime.tm_sec);
- bl_delay_fed(500);
- Display_fun_str("bootloader.t8.txt=\"编译日期:%s\"", buf);
- }
- bl_delay_fed(1000);
- }
- else
- {
- // 分区里没有有效包时必须清空这两行:否则屏上留着上一次的值,
- // 现场会把旧备份当成当前固件看。
- if (i == 0)
- {
- Display_fun_str("bootloader.t5.txt=\"当前固件版本:--\"", NULL);
- Display_fun_str("bootloader.t6.txt=\"编译日期:--\"", NULL);
- }
- else
- {
- Display_fun_str("bootloader.t7.txt=\"出厂固件版本:--\"", NULL);
- Display_fun_str("bootloader.t8.txt=\"编译日期:--\"", NULL);
- }
- }
- }
- }
- uint8_t firstime_flag = 0;//第一次启动标志位
- // BL 自己的上电次数,只用来给出厂备份当延时门槛
- // 绝不能借用 APP 的 boot_t:那个键被 APP 当成"要不要重建默认参数"的信号,
- // 参数复位就是把 0 写进去再重启。BL 一 ++ 就把这个信号抹掉,复位变假成功
- uint32_t bl_boot_n = 0;
- static void test_env(void)
- {
- size_t len;
- len = ef_get_env_blob("bl_boot_n", &bl_boot_n, sizeof(bl_boot_n), NULL);
- if (len != sizeof(bl_boot_n))
- {
- // 读不到(新板子或 ENV 被格式化)就从 0 重新计
- bl_boot_n = 0;
- }
- if (bl_boot_n < 0xFFFFFFFFu)
- {
- bl_boot_n++;
- }
- // 只有写成功才算数:失败就把本地值退回去,别让下一次从假值往上加
- if (bl_env_set("bl_boot_n", &bl_boot_n, sizeof(bl_boot_n)) == EF_NO_ERR)
- {
- LOG_I("BL boot %lu times", bl_boot_n);
- }
- else
- {
- LOG_E("BL boot counter not saved, still %lu.", bl_boot_n - 1u);
- }
- }
- void easyflash_initialize(void)
- {
- EfErrCode err = easyflash_init();
- // 初始化失败必须报出来:否则 firstime 永远是 0、开机次数永远从 1 算,全静默
- if (err != EF_NO_ERR)
- {
- LOG_E("easyflash init failed: %d.", err);
- return;
- }
- ef_get_env_blob("firstime", &firstime_flag, sizeof(firstime_flag), NULL);
- LOG_I("firstime=%d", firstime_flag);
- test_env();
- sync_bl_ver_env(); // 把本 BL 版本告诉 APP,status 包要用
- }
- // 读一字节 ENV,键不存在或长度不符都算没读到
- static int env_get_byte(const char *key, uint8_t *out)
- {
- uint8_t v = 0;
- if (ef_get_env_blob(key, &v, sizeof(v), NULL) != sizeof(v))
- {
- return 0;
- }
- *out = v;
- return 1;
- }
- // 写 ENV 必须看返回值:写不进去时日志还报"成功"就是撒谎,
- // 现场表现就是 boot_t 卡在一个数不动、firstime 永远是 0
- static EfErrCode bl_env_set(const char *key, const void *val, size_t len)
- {
- EfErrCode r = ef_set_env_blob(key, val, len);
- if (r != EF_NO_ERR)
- {
- LOG_E("env \"%s\" write failed: %d", key, r);
- Recode_e_code(e_env_fail, (uint16_t)(((uint16_t)(r & 0xFFu) << 8) | 1u));
- }
- return r;
- }
- static void env_set_byte(const char *key, uint8_t v)
- {
- bl_env_set(key, &v, sizeof(v));
- }
- // "V1.31" -> 131。非数字前缀跳过,主版本 0..2、次版本 0..99,超出返回 0 表示不支持
- // 编码规则与 protocol.c 里 bak_parameters 回包的 bl_ver 一致:主*100 + 次
- static uint8_t bl_version_code(const char *ver)
- {
- int major = 0;
- int minor = 0;
- const char *p = ver;
- while ((*p != '\0') && ((*p < '0') || (*p > '9')))
- {
- p++;
- }
- while ((*p >= '0') && (*p <= '9'))
- {
- major = major * 10 + (*p - '0');
- p++;
- }
- if (*p == '.')
- {
- p++;
- while ((*p >= '0') && (*p <= '9'))
- {
- minor = minor * 10 + (*p - '0');
- p++;
- }
- }
- // uint8 只能放 0..255,主版本 >2 或次版本 >99 就是版本号超出本编码能力
- if ((major > 2) || (minor > 99))
- {
- return 0;
- }
- return (uint8_t)(major * 100 + minor);
- }
- // 每次上电把 BL 版本同步进 ENV。值没变就不写,省 ENV 擦写寿命
- static void sync_bl_ver_env(void)
- {
- uint8_t want = bl_version_code(Version);
- uint8_t have = 0;
- if (want == 0)
- {
- LOG_E("BL version \"%s\" unparsable, bl_ver not saved.", Version);
- return;
- }
- if (env_get_byte("bl_ver", &have) && (have == want))
- {
- return;
- }
- env_set_byte("bl_ver", want);
- LOG_I("bl_ver %u -> %u saved.", have, want);
- }
- // RTC 备份寄存器 DR3 的格式:高字节 magic + 低 24 位版本码
- // magic 用来区分"BL 写过"和"备份域掉电后的随机值",否则 APP 会把野值当版本号
- #define BL_VER_MAGIC 0xB1u
- // 每次开机无条件写 RTC 备份寄存器,App 从那里读版本。
- // 选 RTC 而不是 ENV 的原因:APP 的 ef_env_set_default() 会格式化整个 ENV 区,
- // 参数复位后 bl_ver 必被抹掉;备份域不受影响。
- // 没装 RTC 电池时备份域上电是野值,但 BL 是每次开机必走的路径,写一次就覆盖掉了
- void bl_publish_version(void)
- {
- uint8_t code = bl_version_code(Version);
- uint32_t val;
- if (code == 0)
- {
- // 版本号超出编码能力:不写,让 APP 报 old,绝不塞一个假版本进去
- rt_kprintf("BL version \"%s\" unparsable, RTC version not written\n", Version);
- return;
- }
- val = ((uint32_t)BL_VER_MAGIC << 24) | (uint32_t)code;
- // 成功不打:紧跟的版本横幅已说明 BL 是哪个版本;失败必须报,否则 APP 只能报 old
- if (BSP_Write_RTC_Reg(App_Ver_Sync, Reg_All, val) == 0u)
- {
- rt_kprintf("BL ver RTC write FAILED\n");
- }
- }
- // 把固件区整包克隆到出厂备份区。返回 0 成功,负数失败
- // refresh_display:开机阶段屏还没就绪,不能刷屏;人工操作时才刷
- static int df_clone_once(int refresh_display)
- {
- const struct fal_partition *dst_part;
- const struct fal_partition *src_part;
- rt_uint8_t *buf;
- int clone_pos = 0;
- int clone_len = 0;
- int clone_tol_len;
- dst_part = fal_partition_find(RT_FOTA_DF_PART_NAME);
- src_part = fal_partition_find(RT_FOTA_FM_PART_NAME);
- if (dst_part == RT_NULL || src_part == RT_NULL)
- {
- LOG_I("Backup partition missing (dst %d src %d).", dst_part != RT_NULL, src_part != RT_NULL);
- return -1;
- }
- clone_tol_len = (dst_part->len < src_part->len) ? dst_part->len : src_part->len;
- // 擦 dst 之前必须先确认 src 里真有货。源空着就擦,等于把备份清成 0xFF,
- // 一旦 app 也空了就再也起不来(HMI 0x04 强制覆盖时可复现)。
- // 用包头轻校验判断,不额外算 384KB body CRC
- if (!rt_fota_part_head_ok(RT_FOTA_FM_PART_NAME))
- {
- LOG_I("No valid package in %s, refuse to erase %s.",
- src_part->name, dst_part->name);
- return -6;
- }
- buf = rt_malloc(4096);
- if (buf == RT_NULL)
- {
- LOG_I("No memory for clone buffer.");
- return -1;
- }
- LOG_I("Clone %s to %s, %d bytes.", src_part->name, dst_part->name, clone_tol_len);
- if (nor_erase_feeded(dst_part, 0, dst_part->len) < 0)
- {
- LOG_I("Erase %s failed.", dst_part->name);
- rt_free(buf);
- return -2;
- }
- while (clone_pos < clone_tol_len)
- {
- clone_len = fal_partition_read(src_part, clone_pos, buf, 4096);
- if (clone_len <= 0)
- {
- LOG_I("Read %s failed at %d.", src_part->name, clone_pos);
- break;
- }
- if (fal_partition_write(dst_part, clone_pos, buf, clone_len) < 0)
- {
- LOG_I("Write %s failed at %d.", dst_part->name, clone_pos);
- break;
- }
- clone_pos += clone_len;
- wdg_feed_once();
- }
- rt_free(buf);
- if (clone_pos < clone_tol_len)
- {
- LOG_I("Clone aborted at %d/%d.", clone_pos, clone_tol_len);
- return -3;
- }
- // 回读校验:写完不算数,能按原样考出来才算备份成功
- if (rt_fota_part_fw_verify(RT_FOTA_DF_PART_NAME) != RT_FOTA_NO_ERR)
- {
- LOG_I("Backup verify failed after clone.");
- return -4;
- }
- // 只有真备成功才置位落盘,失败一定要留下重试机会
- firstime_flag = 1;
- env_set_byte("df_v", (uint8_t)BL_DF_BAK_VER);
- bl_env_set("firstime", &firstime_flag, sizeof(firstime_flag));
- LOG_I("Backup ok, firstime=%d.", firstime_flag);
- if (refresh_display)
- {
- display_firmware_info();
- }
- return 0;
- }
- // 产线是直接烧 app 分区的,从没下发过 fm 包,此时 df 备份无从克隆。
- // 这一条把正在跑的 app 反抄一份,按 RBL 格式补上头(fota_algo=0,不加密不压缩),
- // 恢复时就是原样拷回去,跟正式包走同一条 rt_fota_upgrade 路径。
- // 代价:df 无效时才做一次,约 7 秒(擦了 512KB + 写 384KB),做过就记 df_v 不再来。
- // 只校验包头(64 字节),不算 384KB 的 body CRC。
- // 用途:df_v 命中时确认"备份现在还在",避免 ENV 说有效、flash 其实已被擦。
- // 每上电一次的开销是一次 64 字节读 + 一次短 CRC,可以忽略。
- static int rt_fota_part_head_ok(const char *part_name)
- {
- const struct fal_partition *part;
- rt_fota_part_head head;
- part = fal_partition_find(part_name);
- if (part == RT_NULL)
- {
- return 0;
- }
- if (fal_partition_read(part, 0, (rt_uint8_t *)&head, sizeof(head)) != sizeof(head))
- {
- return 0;
- }
- if (rt_fota_crc((rt_uint8_t *)&head, sizeof(head) - 4) != head.head_crc)
- {
- return 0;
- }
- if (rt_strcmp(head.type, "RBL") != 0)
- {
- return 0;
- }
- if (!rbl_pname_is(head.app_part_name, sizeof(head.app_part_name), QXZ_APP_PKG_NAME))
- {
- return 0;
- }
- return 1;
- }
- static int df_clone_from_app(void)
- {
- const struct fal_partition *app_part;
- const struct fal_partition *df_part;
- rt_fota_part_head head;
- rt_uint8_t *buf;
- rt_uint32_t addr;
- rt_uint32_t len;
- rt_uint32_t crc = 0xFFFFFFFFu;
- rt_uint32_t pos = 0;
- int n;
- app_part = fal_partition_find(RT_FOTA_APP_PART_NAME);
- df_part = fal_partition_find(RT_FOTA_DF_PART_NAME);
- if ((app_part == RT_NULL) || (df_part == RT_NULL))
- {
- LOG_E("Partition missing for app backup.");
- return -1;
- }
- len = app_part->len;
- if (df_part->len < (len + sizeof(rt_fota_part_head)))
- {
- LOG_E("df_area too small: %d < %d.", df_part->len, len + sizeof(rt_fota_part_head));
- return -1;
- }
- // 正在跑的这份自身必须自洽,否则抄下来也是个坏的
- addr = ONCHIP_FLASH_BASE + app_part->offset;
- if (!rt_fota_app_image_ok(addr))
- {
- LOG_E("APP image invalid, nothing to back up.");
- return -2;
- }
- buf = rt_malloc(4096);
- if (buf == RT_NULL)
- {
- LOG_E("No memory for app backup.");
- return -1;
- }
- // 整分区当固件体:长度就取 app 分区长度,0xFF 尾巴也算内容,自洽且不越界
- while (pos < len)
- {
- n = (int)((len - pos) > 4096u ? 4096u : (len - pos));
- rt_memcpy(buf, (const void *)(addr + pos), (size_t)n);
- crc = rt_fota_step_crc(crc, buf, (rt_uint32_t)n);
- pos += (rt_uint32_t)n;
- wdg_feed_once();
- }
- rt_memset(&head, 0, sizeof(head));
- rt_memcpy(head.type, "RBL", 3);
- head.fota_algo = 0; // 不加密不压缩,升级时原样拷回 app
- rt_memcpy(head.app_part_name, QXZ_APP_PKG_NAME, rt_strlen(QXZ_APP_PKG_NAME));
- // 版本号标 SYNTH:屏上一眼能看出这是本机自动合成的备份,不是平台下发的正式包
- rt_snprintf(head.download_version, sizeof(head.download_version), "%s", "SYNTH");
- rt_snprintf(head.current_version, sizeof(head.current_version), "%s", Version);
- // 合成包必须自己填时间戳:正式包由打包脚本写,这里不填就是 0,
- // 屏上"编译日期"会显示 1970/01/01(现场看到的就是这个)。
- // 取当前 RTC 作为备份生成时间,配合 download_version=SYNTH 一起读。
- {
- rtc_time now_tm;
- uint32_t now_stamp;
- rt_memset(&now_tm, 0, sizeof(now_tm));
- Reflash_RTC();
- now_tm.tm_year = (int)year;
- now_tm.tm_mon = (int)month;
- now_tm.tm_mday = (int)day;
- now_tm.tm_hour = (int)hour;
- now_tm.tm_min = (int)min;
- now_tm.tm_sec = (int)sec;
- now_stamp = mktimev(&now_tm); // 会就地改 now_tm,之后不再用
- if (now_stamp != 0)
- rt_memcpy(&head.fm_time[2], &now_stamp, 4);
- }
- head.raw_size = len;
- head.com_size = len;
- head.code_crc = crc ^ 0xFFFFFFFFu;
- head.head_crc = rt_fota_crc((rt_uint8_t *)&head, sizeof(rt_fota_part_head) - 4);
- LOG_I("Synthesize factory pkg from %s, %d bytes.", app_part->name, len);
- if (nor_erase_feeded(df_part, 0, df_part->len) < 0)
- {
- LOG_E("Erase %s failed.", df_part->name);
- rt_free(buf);
- return -3;
- }
- if (fal_partition_write(df_part, 0, (const rt_uint8_t *)&head, sizeof(head)) < 0)
- {
- LOG_E("Write pkg head to %s failed.", df_part->name);
- rt_free(buf);
- return -4;
- }
- pos = 0;
- while (pos < len)
- {
- n = (int)((len - pos) > 4096u ? 4096u : (len - pos));
- rt_memcpy(buf, (const void *)(addr + pos), (size_t)n);
- if (fal_partition_write(df_part, sizeof(rt_fota_part_head) + pos, buf, (size_t)n) < 0)
- {
- LOG_E("Write body to %s failed at %u.", df_part->name, pos);
- rt_free(buf);
- return -4;
- }
- pos += (rt_uint32_t)n;
- wdg_feed_once();
- }
- rt_free(buf);
- // 写完必须走一遍正式校验,过不了就当没做,别留下半个包
- if (rt_fota_part_fw_verify(RT_FOTA_DF_PART_NAME) != RT_FOTA_NO_ERR)
- {
- LOG_E("Synthesized pkg verify failed.");
- return -5;
- }
- // 必须落盘 df_v,否则下次上电又白做一遍 7 秒合成
- firstime_flag = 1;
- bl_env_set("firstime", &firstime_flag, sizeof(firstime_flag));
- env_set_byte("df_v", (uint8_t)BL_DF_BAK_VER);
- LOG_I("Factory backup from APP ok.");
- return 0;
- }
- // 首次烧写程序,出厂备份区保存固件(人工触发:HMI 指令 / U盘烧写后)
- void firstime_clone_df(void)
- {
- if (firstime_flag != 0)
- {
- return;
- }
- // 源没包就别先报"正在写入备份",否则屏上刚亮写入就立刻跳失败
- if (!rt_fota_part_head_ok(RT_FOTA_FM_PART_NAME))
- {
- LOG_I("No valid package in %s, backup skipped.", RT_FOTA_FM_PART_NAME);
- UpgradeFail
- return;
- }
- WritetoRecove
- if (df_clone_once(1) == 0)
- {
- UpgradeSuccess
- fota_status_send("固件存入备份分区成功", sizeof("固件存入备份分区成功"));
- }
- else
- {
- UpgradeFail
- fota_status_send("固件存入备份分区失败", sizeof("固件存入备份分区失败"));
- }
- }
- // 开机自检:出厂备份区必须有一份能过校验的固件,没有就自己补一份。
- // 只看两个事实——df_v 记过没有、df_area 里有没有合法包,不依赖开机次数:
- // 次数存在 ENV 里,会被 APP 的参数复位格式化抹掉,拿它当门槛等于永不触发
- void boot_auto_clone_df(void)
- {
- uint8_t df_ver = 0;
- const struct fal_partition *app_part;
- rt_uint32_t app_addr;
- int app_ok;
- int err;
- app_part = fal_partition_find(RT_FOTA_APP_PART_NAME);
- app_addr = (app_part != RT_NULL) ? (app_part->offset + 0x08000000) : 0;
- app_ok = (app_part != RT_NULL) && rt_fota_app_image_ok(app_addr);
- // df_v 只说明"上次确认过",不说明"现在还在"。两种情况它都会说谎:
- // app 被全片擦除(重烧 BL)后 df_v 仍是 1;df 包头被毁后 df_v 也仍是 1。
- // 所以命中还要两道实证:app 能起来,且 df 包头完好。
- // 正常设备这两道都是纯读操作(64 字节包头 + 8 字节镜像头),几乎零开销。
- if (env_get_byte("df_v", &df_ver) && (df_ver == (uint8_t)BL_DF_BAK_VER)
- && app_ok && rt_fota_part_head_ok(RT_FOTA_DF_PART_NAME))
- {
- return;
- }
- // app 已经不在了:这时候什么都别写,先让 rt_fota_start_application 去 df 恢复。
- // 在这里重建备份毫无意义(没有源可抄),而且会白擦一遍 df。
- if (!app_ok)
- {
- LOG_I("APP not bootable, skip backup rebuild.");
- return;
- }
- // 备份区就有合法包:以前备过,只是 df_v 标记没落住,认下它别再擦一遍
- // 只打日志不记 ecode:备份存在是稳态不是事件,记了就是刷记录;
- // 真正该追的是"df_v 为什么会丢",那由 e_env_fail 报
- if (rt_fota_part_fw_verify(RT_FOTA_DF_PART_NAME) == RT_FOTA_NO_ERR)
- {
- firstime_flag = 1;
- bl_env_set("firstime", &firstime_flag, sizeof(firstime_flag));
- env_set_byte("df_v", (uint8_t)BL_DF_BAK_VER);
- LOG_I("Backup already valid, mark it.");
- return;
- }
- // 固件区有包就照原样克隆;没包说明产线是直接烧 app 的,
- // 那就把正在跑的这份 app 反抄成出厂包,否则永远建不起备份
- if (rt_fota_part_fw_verify(RT_FOTA_FM_PART_NAME) == RT_FOTA_NO_ERR)
- {
- LOG_I("Clone backup from %s.", RT_FOTA_FM_PART_NAME);
- err = df_clone_once(0);
- if (err == 0)
- {
- Recode_e_code(e_df_backup, 0);
- }
- else if (err == -2)
- {
- Recode_e_code(e_df_backup, 3); // 备份区擦除失败
- }
- else if (err == -6)
- {
- Recode_e_code(e_df_backup, 2); // 源无有效包,拒绝擦备份
- }
- else
- {
- Recode_e_code(e_df_backup, 4); // 读/写/校验失败
- }
- }
- else
- {
- LOG_I("%s empty, synthesize from running APP.", RT_FOTA_FM_PART_NAME);
- err = df_clone_from_app();
- if (err == 0)
- {
- Recode_e_code(e_df_backup, 0);
- }
- else if (err == -2)
- {
- Recode_e_code(e_df_backup, 2); // app 区没有可抄的镜像
- }
- else if (err == -3)
- {
- Recode_e_code(e_df_backup, 3); // 备份区擦除失败
- }
- else
- {
- Recode_e_code(e_df_backup, 4); // 写入/校验失败
- }
- }
- LOG_I("Auto backup end, err %d.", err);
- }
|